aboutsummaryrefslogtreecommitdiffstats
path: root/src/config.cpp
blob: cb6168f848f0dde1a87cc81659bf85a09a8102ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
/*
 * qtmaildir - a Qt6 mail client for notmuch-indexed Maildirs
 * Copyright (C) 2026 Danilo M. <danix@danix.xyz>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "config.h"

#include "mailsync.h"
// For kMinZoom/kMaxZoom. The bounds live with the widget that enforces them,
// so this reports the same numbers rather than keeping a second copy.
#include "messageview.h"

#include <algorithm>

#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QLocale>
#include <QSaveFile>
#include <QSettings>
#include <QStandardPaths>

namespace {

/// Bounds for [general] toolbar_icon_size. 16 is the smallest size the icon
/// themes actually ship art for, and is what this desktop's style reports;
/// above 64 the toolbar is taller than the thread rows it sits over.
constexpr int kMinToolbarIconSize = 16;
constexpr int kMaxToolbarIconSize = 64;

/// queries.json format version. Bump only for a BREAKING change: an optional
/// field needs no bump, because an older build preserves what it does not
/// understand rather than dropping it.
///
/// Unlike rules.json this file has ONE implementation, so a bump here is not a
/// two-repo change and no hook stops tagging if it is half-deployed.
constexpr int kQueriesFormatVersion = 1;

/// Generators a saved query may name in its `generated` field.
///
/// A closed set, checked on load so a typo is reported rather than producing a
/// button that silently finds nothing. Adding one here needs no format bump:
/// an older build keeps the row and reports it, which is why an unknown
/// generator is a problem rather than a reason to drop the entry.
const QStringList kQueryGenerators = { QStringLiteral("unread"),
                                       QStringLiteral("inbox"),
                                       QStringLiteral("flagged"),
                                       QStringLiteral("sent"),
                                       QStringLiteral("drafts"),
                                       QStringLiteral("trash") };

/// The tag a generator matches, for the three filters that are a plain tag
/// query. Empty for "sent", "drafts" and "trash", which compose from each
/// account's folder instead and are handled separately.
QString generatorTag(const QString &generator)
{
    if (generator == QStringLiteral("unread"))
        return QStringLiteral("unread");
    if (generator == QStringLiteral("inbox"))
        return QStringLiteral("inbox");
    if (generator == QStringLiteral("flagged"))
        return QStringLiteral("flagged");
    return QString();
}

} // namespace

QString Account::scopedQuery(const QString &query) const
{
    const QString prefix = QStringLiteral("path:\"%1/**\"").arg(maildir);
    if (query.trimmed().isEmpty())
        return prefix;
    return QStringLiteral("%1 and (%2)").arg(prefix, query);
}

namespace {

/// Composes `path:"<maildir>/<folder>/**"`, or empty when the folder is unset.
///
/// The QUOTES are load-bearing, not decoration. A real provider nests both its
/// sent and its drafts folder under a bracketed parent with a localised name,
/// "[Provider]/Posta inviata" and "[Provider]/Bozze", and "[" and "]" are
/// Xapian syntax: unquoted, the term is parsed rather than matched and the
/// query silently returns nothing while looking correct.
///
/// The path is user config and is interpolated into a query, so this is the
/// only place that composition happens; a caller building it by hand would be
/// a second chance to forget the quotes.
QString folderQuery(const QString &maildir, const QString &folder)
{
    if (folder.isEmpty())
        return QString();
    return QStringLiteral("path:\"%1/%2/**\"").arg(maildir, folder);
}

/// Joins the non-empty results of `extract` across `accounts` with " or ".
///
/// Collect first, join after. Appending "or" per account and trimming the
/// result is the version that produced the defect this guards: an account with
/// no key contributes an empty term, notmuch accepts the bare "or" without
/// complaint, and the query quietly means something else. Measured against a
/// real database, `A or  or B` returns 190 where the correct pair returns 211.
QString joinAccountQueries(const QList<Account> &accounts,
                           QString (Account::*extract)() const)
{
    QStringList parts;
    for (const Account &account : accounts) {
        const QString query = (account.*extract)();
        if (!query.isEmpty())
            parts.append(query);
    }
    return parts.join(QStringLiteral(" or "));
}

} // namespace

QString Account::sentQuery() const
{
    return folderQuery(maildir, sent);
}

QString Account::draftsQuery() const
{
    return folderQuery(maildir, drafts);
}

QString Account::trashQuery() const
{
    return folderQuery(maildir, trash);
}

QString Account::inboxFolder() const
{
    // Never empty: Restore needs a folder to name, and "Inbox" is both the
    // Maildir convention and what mbsync's own Inbox directive defaults to.
    return inbox.isEmpty() ? QStringLiteral("Inbox") : inbox;
}

QString Account::inboxQuery() const
{
    return folderQuery(maildir, inboxFolder());
}

QString Config::allSentQuery() const
{
    return joinAccountQueries(m_accounts, &Account::sentQuery);
}

QString Config::allDraftsQuery() const
{
    return joinAccountQueries(m_accounts, &Account::draftsQuery);
}

QString Config::allTrashQuery() const
{
    return joinAccountQueries(m_accounts, &Account::trashQuery);
}

QString Config::defaultPath()
{
    const QString base =
        QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);
    return base + QStringLiteral("/qtmaildir/qtmaildir.conf");
}

void Config::addProblem(const QString &message)
{
    m_warnings.append(message);
    m_problems.append(message);
}

void Config::addNotice(const QString &message)
{
    m_warnings.append(message);
}

void Config::load(const QString &path)
{
    QSettings settings(path, QSettings::IniFormat);

    // Keys of [general] are read WITHOUT the "general/" prefix. QSettings'
    // INI backend treats a section literally named [general] as its own
    // fallback section and strips the prefix, so "general/notmuch_config"
    // never matches anything, in any section arrangement (verified on
    // Qt 6.11). The file still reads as [general] to the user; only the
    // lookup differs. Same family of trap as the [account.work] dot and the
    // childKeys() ordering already documented in CLAUDE.md.
    m_notmuchConfig =
        settings.value(QStringLiteral("notmuch_config")).toString();

    // Absent is fine and silent: the default is 1.0. Present but unparseable
    // is a problem, since the user asked for something and is not getting it.
    // The range is enforced by MessageView::clampZoom(), the one place that
    // knows what the web view can render; out of range is reported below.
    // Empty is treated as unset rather than as "a query named nothing".
    const QString startup =
        settings.value(QStringLiteral("startup_query")).toString().trimmed();
    if (!startup.isEmpty()) {
        m_startupQuery = startup;
        m_startupQueryWasSet = true;
    }

    // Stored raw here and validated once the accounts are parsed, below: the
    // account sections have not been read yet at this point.
    m_startupAccount =
        settings.value(QStringLiteral("startup_account")).toString().trimmed();

    // Interface language. "system" is spelled out so the default can be written
    // down rather than only expressed by deleting the key.
    //
    // Validated here rather than left to whether a translation loads, because
    // those are different questions and only one of them is an error. QLocale
    // accepts anything and degrades an unrecognised name to C, so `language =
    // itallian` would load no translation and look exactly like asking for
    // English. Meanwhile `language = en_US` legitimately loads nothing, since
    // English is the source language and ships no .qm. Checking the NAME
    // separates the typo from the deliberate choice.
    const QString language =
        settings.value(QStringLiteral("language")).toString().trimmed();
    if (!language.isEmpty()
        && language.compare(QStringLiteral("system"), Qt::CaseInsensitive) != 0) {
        if (QLocale(language).language() == QLocale::C) {
            addProblem(tr("Language '%1' is not a locale name; using the "
                          "system language. Expected something like 'it' or "
                          "'it_IT'.")
                           .arg(language));
        } else {
            m_language = language;
        }
    }

    const QVariant zoom = settings.value(QStringLiteral("message_zoom"));
    if (zoom.isValid()) {
        bool ok = false;
        const double value = zoom.toString().toDouble(&ok);
        if (ok) {
            m_messageZoom = value;
            // Reported, not clamped: MessageView::clampZoom() owns the bounds
            // and already stops this reaching the web view, so clamping here
            // too would be a second copy of the range, free to drift from the
            // first. What was missing is the report. The value parses, so
            // nothing ever said the 500 in the file is not what is on screen.
            if (value < MessageView::kMinZoom || value > MessageView::kMaxZoom) {
                addProblem(tr("Message zoom %1 is outside %2 to %3; "
                                          "using the nearest allowed value.")
                               .arg(value)
                               .arg(MessageView::kMinZoom)
                               .arg(MessageView::kMaxZoom));
            }
        } else {
            addProblem(tr("Message zoom '%1' is not a number; "
                                      "using the default.")
                           .arg(zoom.toString()));
        }
    }

    // A [general] key, so no prefix, per the note at the top of load().
    m_completionOnFocus =
        settings.value(QStringLiteral("completion_on_focus"), false).toBool();

    // Clamped, unlike message_zoom above, which documents a 0.5 to 3.0 range in
    // the README and enforces none of it. Both ends here are unrecoverable from
    // the UI they break: too small is an invisible icon, too large is a toolbar
    // taller than the window, and in either case the control the user would
    // reach for to fix it is the one that just broke.
    const QVariant iconSize = settings.value(QStringLiteral("toolbar_icon_size"));
    if (iconSize.isValid()) {
        bool ok = false;
        const int value = iconSize.toString().trimmed().toInt(&ok);
        if (!ok) {
            addProblem(tr("Toolbar icon size '%1' is not a number; "
                                      "using %2.")
                           .arg(iconSize.toString())
                           .arg(m_toolbarIconSize));
        } else if (value < kMinToolbarIconSize || value > kMaxToolbarIconSize) {
            m_toolbarIconSize =
                qBound(kMinToolbarIconSize, value, kMaxToolbarIconSize);
            addProblem(tr("Toolbar icon size %1 is outside %2 to "
                                      "%3; using %4.")
                           .arg(value)
                           .arg(kMinToolbarIconSize)
                           .arg(kMaxToolbarIconSize)
                           .arg(m_toolbarIconSize));
        } else {
            m_toolbarIconSize = value;
        }
    }

    // Absent or empty means the system locale's short format, which is what
    // every other application on the desktop shows. Only a non-empty pattern is
    // validated, and a rejected one falls back to that same default.
    const QString dateFormat =
        settings.value(QStringLiteral("date_format")).toString().trimmed();
    if (!dateFormat.isEmpty()) {
        // QDateTime::toString() with a pattern carrying no date or time field
        // returns the pattern verbatim rather than failing, so "banana" would
        // print "banana" on every card. Formatting two DIFFERENT instants and
        // comparing is what catches that: a pattern with any real field gives
        // two different strings, one with none gives the same string twice.
        const QDateTime a(QDate(2028, 12, 28), QTime(22, 58));
        const QDateTime b(QDate(2019, 1, 3), QTime(4, 5));
        const QLocale locale = QLocale::system();
        if (locale.toString(a, dateFormat) == locale.toString(b, dateFormat)) {
            addProblem(tr("Date format '%1' contains no date or "
                                      "time field; using the system format.")
                           .arg(dateFormat));
        } else {
            m_dateFormat = dateFormat;
        }
    }

    // Absent is silent, the default being 2000. Present but unparseable warns,
    // for the same reason message_zoom does: the user asked for something and
    // is not getting it.
    //
    // Zero and negative are NOT errors and must not be clamped. Zero means mark
    // read at once, and any negative value means never, which is how the
    // behaviour is turned off.
    // Three values, not a bool: "prompt me", "just do it" and "do nothing" are
    // three distinct behaviours and true/false can only express two of them.
    const QString syncExit =
        settings.value(QStringLiteral("sync_on_exit"),
                       QStringLiteral("ask")).toString().trimmed().toLower();
    if (syncExit == QStringLiteral("ask")) {
        m_syncOnExit = SyncOnExit::Ask;
    } else if (syncExit == QStringLiteral("always")) {
        m_syncOnExit = SyncOnExit::Always;
    } else if (syncExit == QStringLiteral("never")) {
        m_syncOnExit = SyncOnExit::Never;
    } else {
        // Naming the accepted values, since a typo here silently changes what
        // happens to unsynced work at exit.
        addProblem(tr("Unknown sync_on_exit '%1'; expected ask, "
                                  "always or never. Using ask.")
                       .arg(syncExit));
    }

    const QVariant markRead = settings.value(QStringLiteral("mark_read_delay_ms"));
    if (markRead.isValid()) {
        bool ok = false;
        const int value = markRead.toString().toInt(&ok);
        if (ok) {
            m_markReadDelayMs = value;
        } else {
            addProblem(tr("Mark-read delay '%1' is not a number; "
                                      "using the default.")
                           .arg(markRead.toString()));
        }
    }

    // Item 71. Same shape as mark_read_delay_ms above, including that zero and
    // negative are not errors: 0 syncs on the next trip through the event loop
    // and negative disables the automatic sync entirely, which is how a user who
    // wants only their cron job turns this off.
    const QVariant autoSync = settings.value(QStringLiteral("auto_sync_delay_ms"));
    if (autoSync.isValid()) {
        bool ok = false;
        const int value = autoSync.toString().toInt(&ok);
        if (ok) {
            m_autoSyncDelayMs = value;
        } else {
            addProblem(tr("Auto-sync delay '%1' is not a number; "
                                      "using the default.")
                           .arg(autoSync.toString()));
        }
    }

    // [completion] is an ordinary section, so this one DOES take its prefix.
    // ',' separates entries and '|' separates a value from its description:
    // two different characters because QSettings splits comma lists itself,
    // so a description holding a comma would otherwise become two entries.
    // Neither character is legal in a mimetype.
    const QStringList rawMimetypes =
        settings.value(QStringLiteral("completion/extra_mimetypes")).toStringList();
    for (const QString &raw : rawMimetypes) {
        const QString entry = raw.trimmed();
        if (entry.isEmpty())
            continue;

        const int bar = entry.indexOf(QLatin1Char('|'));
        const QString value = (bar < 0 ? entry : entry.left(bar)).trimmed();
        const QString description =
            (bar < 0 ? QString() : entry.mid(bar + 1)).trimmed();

        // Skip only the bad entry: one typo must not cost the user the rest
        // of the list, and the built-ins are appended to regardless.
        if (value.isEmpty()) {
            addProblem(tr("[completion] extra_mimetypes: entry '%1' "
                                      "has no mimetype; ignoring it.")
                           .arg(entry));
            continue;
        }
        m_extraMimetypes.append({ value, description });
    }

    m_syncCommand = settings.value(QStringLiteral("sync/command")).toString();
    if (m_syncCommand.isEmpty()) {
        // Not a problem: sync is optional, and nothing the user asked for is
        // being ignored. A modal here would fire on every launch.
        addNotice(QStringLiteral(
            "No sync command configured ([sync] command); syncing is disabled."));
    } else if (!QFileInfo::exists(m_syncCommand.split(QLatin1Char(' ')).first())) {
        addProblem(
            QStringLiteral("Sync command '%1' does not exist; syncing is disabled.")
                .arg(m_syncCommand));
        m_syncCommand.clear();
    }

    // Not validated for existence, unlike the command above. The log is written
    // by the script when it runs, so a fresh install has no file yet, and a
    // startup problem reported for that would be noise. A missing file simply
    // reads as SyncOutcome::Unknown when the time comes.
    m_syncLog = settings.value(QStringLiteral("sync/log")).toString().trimmed();
    if (m_syncLog.isEmpty())
        m_syncLog = MailSync::defaultLogPath();

    // Account groups are written as [account.work], [account.personal], etc.
    // A dot, not a slash, separates the "account" namespace from the key:
    // QSettings' INI backend treats "/" as its own hierarchical group
    // separator, so a literal "[account/work]" section header would be
    // parsed as a *nested* group "work" inside a group "account" (and trips
    // a QSettings::FormatError besides), not as a single flat group named
    // "account/work". "." carries no such meaning to QSettings, so
    // childGroups() here returns "account.work" and "account.personal" as
    // plain top-level entries and status() stays NoError.
    for (const QString &group : settings.childGroups()) {
        if (!group.startsWith(QStringLiteral("account.")))
            continue;

        Account account;
        account.key = group.mid(QStringLiteral("account.").size());

        settings.beginGroup(group);
        account.name = settings.value(QStringLiteral("name")).toString();
        account.address = settings.value(QStringLiteral("address")).toString();
        account.maildir = settings.value(QStringLiteral("maildir")).toString();
        account.drafts = settings.value(QStringLiteral("drafts")).toString();

        // Optional, and absent for an account that keeps no sent mail locally.
        // Trimmed because a trailing space would land inside the quoted path
        // and match nothing, which is invisible in a config file.
        account.sent =
            settings.value(QStringLiteral("sent")).toString().trimmed();

        // Mandatory, unlike sent: Delete moves a file into this folder, so an
        // account without one cannot delete at all. Trimmed for the same
        // reason as sent, above.
        account.trash =
            settings.value(QStringLiteral("trash")).toString().trimmed();

        // Optional, unlike trash: inboxFolder() defaults it to "Inbox", which
        // is right for any ordinary Maildir. Read so an account whose inbox is
        // named otherwise can say so, rather than having Restore create a
        // second folder under a name this program assumed.
        account.inbox =
            settings.value(QStringLiteral("inbox")).toString().trimmed();

        // Optional, and its absence IS the receive-only state: see the field
        // comment in config.h. Run without a shell, so trimming here is only
        // whitespace hygiene, never a quoting concern.
        account.sendCommand =
            settings.value(QStringLiteral("send_command")).toString().trimmed();

        // Both optional, and both describe this account's chip in the thread
        // list. An account tag is a different taxonomy from a functional one,
        // saying which mailbox a thread arrived in rather than what state it
        // is in, so these live here rather than in [tagcolors].
        account.label = settings.value(QStringLiteral("label")).toString();

        // Optional, and absent for most accounts: syncChannel() falls back to
        // the key. Needed only where the section key and the mbsync channel
        // name diverge.
        account.channel = settings.value(QStringLiteral("channel")).toString();

        const QString colour = settings.value(QStringLiteral("color")).toString();
        if (!colour.isEmpty()) {
            account.color = QColor(colour);
            if (!account.color.isValid()) {
                addProblem(
                    QStringLiteral("Account '%1' has an unparseable color '%2'; "
                                   "using a generated one.")
                        .arg(account.key, colour));
            }
        }
        settings.endGroup();

        if (!account.isValid()) {
            addProblem(
                QStringLiteral("Account '%1' has no maildir; ignoring it.")
                    .arg(account.key));
            continue;
        }

        // Mandatory, unlike sent: Delete moves a file into this folder, so an
        // account without one cannot delete at all. Reported rather than
        // silently disabled, so the user finds out from a warning rather than
        // from a Delete that quietly does nothing. The account still loads;
        // only Delete is unusable, which does not warrant losing the rest of
        // the account's mail.
        if (account.trash.isEmpty()) {
            addProblem(
                tr("Account '%1' has no trash folder configured; add a "
                   "'trash' key to its section. Delete will not work for "
                   "this account until it does.")
                    .arg(account.key));
        }

        m_accounts.append(account);
    }

    settings.beginGroup(QStringLiteral("compose"));
    // Absent keys stay silent (the struct's own default holds), but a
    // PRESENT and malformed value is reported: value(key, default) alone
    // would happily accept "quote_position = abov" as Above, matching every
    // other enum-ish key in this file (sync_on_exit, language, date_format)
    // rather than being the one silent exception.
    const QString quotePosition =
        settings.value(QStringLiteral("quote_position"), QStringLiteral("below"))
            .toString().trimmed();
    if (quotePosition.compare(QStringLiteral("above"), Qt::CaseInsensitive) == 0) {
        m_compose.quotePosition = ComposeSettings::QuotePosition::Above;
    } else if (quotePosition.compare(QStringLiteral("below"), Qt::CaseInsensitive) == 0) {
        m_compose.quotePosition = ComposeSettings::QuotePosition::Below;
    } else {
        addProblem(tr("[compose] quote_position '%1' is not recognised; "
                      "expected above or below. Using below.")
                       .arg(quotePosition));
    }

    m_compose.sendHtml =
        settings.value(QStringLiteral("send_html"), true).toBool();

    // Three numerics, all following the shape already established at
    // message_zoom, toolbar_icon_size, mark_read_delay_ms and
    // auto_sync_delay_ms elsewhere in this function: a QVariant, a checked
    // toInt()/toLongLong(), and a reported fallback to the struct's own
    // default on failure. The bare toInt()/toLongLong() this replaced return
    // 0 on a PARSE FAILURE, not the default, which is silently indistinguishable
    // from the user writing 0 on purpose. For autosave_interval_ms that 0
    // reaches a QTimer restarted on every keystroke, so it would fire on the
    // very next event-loop pass and turn the debounce into a write per
    // keystroke, each one uploaded by mbsync.
    const QVariant autosave = settings.value(QStringLiteral("autosave_interval_ms"));
    if (autosave.isValid()) {
        bool ok = false;
        const int value = autosave.toString().trimmed().toInt(&ok);
        if (ok) {
            // Clamped, not merely parsed: nothing in the spec assigns a
            // meaning to a zero or negative autosave interval, unlike
            // mark_read_delay_ms where negative-means-off is documented
            // behaviour. A zero interval here is the same runaway-write
            // hazard as the parse failure above, just spelled correctly.
            m_compose.autosaveIntervalMs = qMax(1000, value);
        } else {
            addProblem(tr("[compose] autosave_interval_ms '%1' is not a "
                          "number; using %2.")
                           .arg(autosave.toString())
                           .arg(m_compose.autosaveIntervalMs));
        }
    }

    // Zero is a REAL setting here, meaning "send at once", and must be
    // honoured rather than mistaken for unset: that is exactly why this is
    // isValid()-then-checked-parse rather than a zero-test.
    const QVariant sendDelay = settings.value(QStringLiteral("send_delay_ms"));
    if (sendDelay.isValid()) {
        bool ok = false;
        const int value = sendDelay.toString().trimmed().toInt(&ok);
        if (ok) {
            m_compose.sendDelayMs = value;
        } else {
            addProblem(tr("[compose] send_delay_ms '%1' is not a number; "
                          "using %2.")
                           .arg(sendDelay.toString())
                           .arg(m_compose.sendDelayMs));
        }
    }

    m_compose.defaultAccount =
        settings.value(QStringLiteral("default_account")).toString().trimmed();

    const QVariant attachmentWarn =
        settings.value(QStringLiteral("attachment_warn_bytes"));
    if (attachmentWarn.isValid()) {
        bool ok = false;
        const qint64 value = attachmentWarn.toString().trimmed().toLongLong(&ok);
        if (ok) {
            m_compose.attachmentWarnBytes = value;
        } else {
            addProblem(tr("[compose] attachment_warn_bytes '%1' is not a "
                          "number; using %2.")
                           .arg(attachmentWarn.toString())
                           .arg(m_compose.attachmentWarnBytes));
        }
    }
    settings.endGroup();

    loadSavedQueries(path, settings);

    // Checked here rather than where startup_query is read: the saved queries
    // are not parsed until now. Only a name the user actually wrote is worth a
    // problem; the built-in default naming a query they never created is not
    // something they got wrong.
    // Same shape as the startup_query check below: a name the user wrote that
    // matches nothing is a problem, because they asked for something and are
    // not getting it. Cleared rather than passed on, since the dropdown has no
    // entry for an account that does not exist and would sit on "All accounts"
    // without saying why.
    if (!m_startupAccount.isEmpty() && !account(m_startupAccount).isValid()) {
        addProblem(tr("Startup account '%1' is not a configured "
                                  "account; starting on all accounts.")
                       .arg(m_startupAccount));
        m_startupAccount.clear();
    }

    // default_account is validated here, once the accounts are parsed. A
    // named account that cannot send is reported: the user named an account
    // and expects mail to come from it, unlike an installation where no
    // account can send at all, which is a valid read-only setup and not
    // warned about below.
    //
    // Unlike startup_account just above, the bad value is NOT cleared after
    // the warning: the composer resolves this through canSend() at the point
    // of use, so a value naming an unusable account is simply skipped there
    // rather than needing to be blanked here.
    if (!m_compose.defaultAccount.isEmpty()) {
        const auto named = std::find_if(
            m_accounts.cbegin(), m_accounts.cend(),
            [this](const Account &a) { return a.key == m_compose.defaultAccount; });

        if (named == m_accounts.cend()) {
            addProblem(
                tr("[compose] default_account names '%1', which is not a "
                   "configured account. A new message will pick a sending "
                   "account by the usual rules.")
                    .arg(m_compose.defaultAccount));
        } else if (!named->canSend()) {
            addProblem(
                tr("[compose] default_account names '%1', which has no "
                   "send_command and cannot send. A new message will pick a "
                   "sending account by the usual rules.")
                    .arg(m_compose.defaultAccount));
        }
    }

    for (const Account &account : m_accounts) {
        if (!account.canSend())
            continue;
        // A notice, not a problem: a provider whose SMTP server files sent
        // mail on its own is a legitimate, permanently correct configuration.
        // addProblem() here would raise a startup modal on every launch for a
        // setup that will never change, which is exactly how a user learns to
        // dismiss dialogs unread.
        if (account.sent.isEmpty()) {
            addNotice(
                tr("Account '%1' can send but configures no `sent` folder, so "
                   "no local copy of sent mail is filed.")
                    .arg(account.key));
        }
        // Still a problem: unlike a missing sent folder, this is a real loss
        // of protection (no draft is saved while composing) rather than a
        // deliberate provider-side choice.
        if (account.drafts.isEmpty()) {
            addProblem(
                tr("Account '%1' can send but configures no `drafts` folder, "
                   "so the composer runs without draft protection.")
                    .arg(account.key));
        }
    }

    // Asks whether the resolved query matched on EITHER a name or a generator,
    // rather than comparing the name alone. Comparing names warned about a
    // config that was working: `startup_query = Inbox` resolves through the
    // generator under a translated UI, where the filter's name is "In arrivo",
    // so the app opened the right view and reported it as wrong.
    if (m_startupQueryWasSet && !m_savedQueries.isEmpty()) {
        const SavedQuery resolved = startupSavedQuery();
        const bool matched =
            resolved.name.compare(m_startupQuery, Qt::CaseInsensitive) == 0
            || (!resolved.generated.isEmpty()
                && resolved.generated.compare(m_startupQuery,
                                              Qt::CaseInsensitive) == 0);
        if (!matched) {
            addProblem(tr("Startup query '%1' is not a saved query; "
                                      "opening '%2' instead.")
                           .arg(m_startupQuery, resolved.name));
        }
    }
}

QString Config::queriesPath(const QString &configPath)
{
    return QFileInfo(configPath).absolutePath()
           + QStringLiteral("/queries.json");
}

void Config::loadSavedQueries(const QString &configPath, QSettings &settings)
{
    m_queriesPath = queriesPath(configPath);

    QFile file(m_queriesPath);
    if (!file.exists()) {
        // Migration. Read [queries] once, write the JSON, and leave the INI
        // section alone: stripping it would mean rewriting a hand-edited file
        // with QSettings, which drops comments and key order across the WHOLE
        // file. A few stale lines the user can delete by hand is the cheaper
        // loss, and it keeps a downgrade working.
        settings.beginGroup(QStringLiteral("queries"));
        const QStringList names = settings.childKeys();
        for (const QString &name : names) {
            SavedQuery query;
            query.name = name;
            query.query = settings.value(name).toString();
            // Pinned, because these are buttons today. A migration that left
            // them unpinned would empty the query row on the first launch
            // after an upgrade, which reads as data loss.
            query.pinned = true;
            m_savedQueries.append(query);
        }
        settings.endGroup();

        // Sent is NOT migrated into queries.json any more. It used to become an
        // ordinary saved query here, so the hardcoded button could be
        // reordered, renamed or removed; item 93 makes it one of four built-in
        // filters instead, which are shipped rather than stored. Migrating it
        // as well would put two Sent buttons on the row, one of them the user's
        // to edit and one not.
        //
        // Nothing is lost: the built-in Sent resolves through the same
        // generator, so it still follows the accounts, and it now composes with
        // the account dropdown rather than resetting it.

        // Order is alphabetical here because childKeys() is genuinely all the
        // INI knows. The user reorders once and it sticks from then on.
        if (!m_savedQueries.isEmpty() && !saveSavedQueries()) {
            addProblem(tr("Could not write saved queries to %1.")
                           .arg(m_queriesPath));
        }
        return;
    }

    if (!file.open(QIODevice::ReadOnly)) {
        addProblem(tr("Could not read %1: %2.")
                       .arg(m_queriesPath, file.errorString()));
        m_queriesRefused = true;
        return;
    }

    QJsonParseError error;
    const QJsonDocument document =
        QJsonDocument::fromJson(file.readAll(), &error);
    file.close();

    if (error.error != QJsonParseError::NoError || !document.isObject()) {
        addProblem(tr("%1 is not valid JSON: %2.")
                       .arg(m_queriesPath, error.errorString()));
        m_queriesRefused = true;
        return;
    }

    const QJsonObject root = document.object();
    const int version =
        root.value(QStringLiteral("version")).toInt(kQueriesFormatVersion);
    if (version != kQueriesFormatVersion) {
        // Refused rather than guessed at, and the refusal blocks the save:
        // rewriting a newer document with this build's reading of it would
        // destroy whatever the newer build stored.
        addProblem(tr("%1 has format version %2; this build "
                                  "understands %3. Saved queries were not "
                                  "loaded.")
                       .arg(m_queriesPath)
                       .arg(version)
                       .arg(kQueriesFormatVersion));
        m_queriesRefused = true;
        return;
    }

    for (auto it = root.begin(); it != root.end(); ++it) {
        if (it.key() != QStringLiteral("version")
            && it.key() != QStringLiteral("queries"))
            m_queriesUnknown.insert(it.key(), it.value());
    }

    const QJsonArray array = root.value(QStringLiteral("queries")).toArray();
    for (const QJsonValue &value : array) {
        const QJsonObject object = value.toObject();
        SavedQuery query;
        query.name = object.value(QStringLiteral("name")).toString();
        query.query = object.value(QStringLiteral("query")).toString();
        query.pinned = object.value(QStringLiteral("pinned")).toBool(false);
        query.account = object.value(QStringLiteral("account")).toString();
        query.generated = object.value(QStringLiteral("generated")).toString();
        // A generator carries its own view mode, so "sent" is flat whether or
        // not the file says so. Storing it as a plain field would let a
        // hand-edited or migrated-from-elsewhere row produce a THREADED sent
        // view, which folds every reply back into the conversation the user
        // sent one message into. The file may still set it for an ordinary
        // query.
        query.flat = object.value(QStringLiteral("flat")).toBool(false)
                     || query.generated == QStringLiteral("sent");

        if (query.isGenerated()
            && !kQueryGenerators.contains(query.generated)) {
            // Reported but KEPT. A later build may know this generator, and
            // dropping the row here would delete it from the file on the next
            // save, which is the same data loss the unknown-field handling
            // exists to prevent.
            addProblem(tr("Saved query '%1' uses an unknown "
                                      "generator '%2' and will find nothing.")
                           .arg(query.name, query.generated));
        }

        if (query.name.isEmpty()) {
            addProblem(tr("A saved query in %1 has no name and was "
                                      "skipped.").arg(m_queriesPath));
            continue;
        }

        // A stored entry naming a generator now duplicates a BUILT-IN filter of
        // the same name, since item 93 ships all four rather than storing them.
        // 0.19.0 migrated the hardcoded Sent button into exactly such an entry,
        // so every existing install has one.
        //
        // Unpinned, never dropped: the row would otherwise carry two Sent
        // buttons, one the user's to edit and one not. Deleting it would be
        // data loss on a file whose readers are supposed to preserve what they
        // do not own, and an unpin is reversible from the UI.
        if (query.isGenerated() && isKnownGenerator(query.generated))
            query.pinned = false;

        for (auto it = object.begin(); it != object.end(); ++it) {
            static const QStringList known = {
                QStringLiteral("name"), QStringLiteral("query"),
                QStringLiteral("pinned"), QStringLiteral("account"),
                QStringLiteral("generated"), QStringLiteral("flat")
            };
            if (!known.contains(it.key()))
                query.unknown.insert(it.key(), it.value());
        }

        m_savedQueries.append(query);
    }
}

bool Config::saveSavedQueries() const
{
    if (m_queriesPath.isEmpty() || m_queriesRefused)
        return false;

    QJsonArray array;
    for (const SavedQuery &query : m_savedQueries) {
        // Only what carries information. The file is hand-editable, so a key
        // that always holds the same value, or one the generator already
        // implies, is just something the reader has to skip past. Same reason
        // `pinned` and `account` are written only when set.
        QJsonObject object;
        object.insert(QStringLiteral("name"), query.name);
        if (query.isGenerated()) {
            object.insert(QStringLiteral("generated"), query.generated);
        } else {
            object.insert(QStringLiteral("query"), query.query);
        }
        if (query.pinned)
            object.insert(QStringLiteral("pinned"), true);
        if (!query.account.isEmpty())
            object.insert(QStringLiteral("account"), query.account);
        // Skipped when the generator already implies it, which loadSavedQueries
        // reapplies on the way back in.
        if (query.flat && query.generated != QStringLiteral("sent"))
            object.insert(QStringLiteral("flat"), true);
        for (auto it = query.unknown.begin(); it != query.unknown.end(); ++it)
            object.insert(it.key(), it.value());
        array.append(object);
    }

    QJsonObject root = m_queriesUnknown;
    root.insert(QStringLiteral("version"), kQueriesFormatVersion);
    root.insert(QStringLiteral("queries"), array);

    QDir().mkpath(QFileInfo(m_queriesPath).absolutePath());

    // QSaveFile writes a temporary and renames on commit, so an interrupted
    // write cannot leave a half-written file where the queries used to be.
    QSaveFile file(m_queriesPath);
    if (!file.open(QIODevice::WriteOnly))
        return false;
    file.write(QJsonDocument(root).toJson(QJsonDocument::Indented));
    return file.commit();
}

QString Config::resolvedQuery(const SavedQuery &query) const
{
    // Composed from the accounts every time it is asked for, which is the
    // point: the answer follows the config rather than a copy of it taken when
    // the entry was written.
    if (query.isGenerated()) {
        if (query.generated == QStringLiteral("sent"))
            return allSentQuery();
        if (query.generated == QStringLiteral("trash"))
            return allTrashQuery();
        // An unknown generator was reported on load. Empty rather than the
        // bare stored query, which for a generated entry is empty anyway and
        // would otherwise run as "match everything".
        return QString();
    }

    if (query.account.isEmpty())
        return query.query;

    const Account scope = account(query.account);
    if (!scope.isValid())
        return query.query;

    return scope.scopedQuery(query.query);
}

bool Config::isKnownGenerator(const QString &generator)
{
    return kQueryGenerators.contains(generator);
}

QString Config::matchNothingQuery()
{
    // notmuch reads an EMPTY query as "match everything", so a generator with
    // nothing to match must say so explicitly. `tag:` and its negation cannot
    // both hold, and the tag name is irrelevant: what matters is that this
    // parses and matches nothing. A malformed string would not do, since
    // notmuch accepts almost anything and matches nothing quietly, which is the
    // same result reached by luck rather than by contract.
    return QStringLiteral("tag:unread and not tag:unread");
}

QList<SavedQuery> Config::builtinFilters()
{
    // Left to right on the query row. Fixed rather than configurable: item 94
    // removes the mixed row entirely once these are confirmed, so a settings
    // surface for the order would be built and deleted inside two items.
    QList<SavedQuery> filters;
    for (const QString &generator : kQueryGenerators)
        filters.append(builtinFilter(generator));
    return filters;
}

SavedQuery Config::builtinFilter(const QString &generator)
{
    if (!isKnownGenerator(generator))
        return {};

    SavedQuery filter;
    filter.generated = generator;

    // Translated, because these are the labels on the buttons. The GENERATOR
    // name is not: it is stored in queries.json and matched against a closed
    // set, so translating it would make a file written in one locale unreadable
    // in another.
    if (generator == QStringLiteral("unread")) {
        filter.name = tr("Unread");
    } else if (generator == QStringLiteral("inbox")) {
        filter.name = tr("Inbox");
    } else if (generator == QStringLiteral("flagged")) {
        // "Important", matching the `flag` action, which item 57 renamed from
        // "Flag" for exactly this reason. Shipping the filter as "Flagged"
        // beside it put the same tag under two names in one window. The
        // GENERATOR stays `flagged`: that string is stored in queries.json and
        // matched against a closed set, so it is wire format, not a label.
        filter.name = tr("Important");
    } else if (generator == QStringLiteral("sent")) {
        filter.name = tr("Sent");
        // Messages rather than threads, and the only filter that sets this. A
        // thread would fold the user's sent message back into the conversation
        // it belongs to, which is item 63's finding.
        filter.flat = true;
    } else if (generator == QStringLiteral("drafts")) {
        // The LABEL is translated; the generator stays `drafts`, which is what
        // queries.json stores and what a closed set is matched against.
        filter.name = tr("Drafts");
        // NOT flat, like Trash and unlike Sent: a draft reply belongs with the
        // conversation it answers.
    } else if (generator == QStringLiteral("trash")) {
        filter.name = tr("Trash");
        // NOT flat, unlike Sent. A deleted message still belongs to its
        // conversation, and folding it back is what Sent had to avoid rather
        // than something every folder filter wants.
    }

    return filter;
}

QString Config::resolvedQuery(const SavedQuery &query,
                              const QString &accountKey) const
{
    // An ordinary saved query is a DESTINATION: it states its own scope and
    // ignores the dropdown, which is the behaviour item 90 leaves alone. Only a
    // generated filter composes.
    if (!query.isGenerated())
        return resolvedQuery(query);

    if (!isKnownGenerator(query.generated))
        return QString();

    if (accountKey.isEmpty()) {
        // Across every account, which for the tag filters is the bare query and
        // for Sent is the union of the accounts' folders.
        if (query.generated == QStringLiteral("sent")) {
            const QString all = allSentQuery();
            return all.isEmpty() ? matchNothingQuery() : all;
        }
        if (query.generated == QStringLiteral("drafts")) {
            const QString all = allDraftsQuery();
            return all.isEmpty() ? matchNothingQuery() : all;
        }
        if (query.generated == QStringLiteral("trash")) {
            const QString all = allTrashQuery();
            return all.isEmpty() ? matchNothingQuery() : all;
        }
        return QStringLiteral("tag:%1").arg(generatorTag(query.generated));
    }

    const Account scope = account(accountKey);
    if (!scope.isValid())
        return resolvedQuery(query, QString());

    if (query.generated == QStringLiteral("sent")) {
        // The account's OWN sent query, never the all-accounts one wrapped in
        // this account's path. Wrapping gives
        //     path:"a/**" and (path:"a/Sent/**" or path:"b/Sent/**")
        // which returns the right rows because path: is hierarchical, and is
        // still wrong: it double-scopes and works by accident of the syntax.
        const QString sent = scope.sentQuery();
        // Empty when the account configures no sent folder, which is a real
        // case and not a misconfiguration. Returned as-is it would mean "match
        // everything", so a button labelled Sent would show the whole Maildir.
        return sent.isEmpty() ? matchNothingQuery() : sent;
    }

    if (query.generated == QStringLiteral("drafts")) {
        // The account's OWN drafts query, for the reason spelled out above the
        // sent case.
        const QString drafts = scope.draftsQuery();
        return drafts.isEmpty() ? matchNothingQuery() : drafts;
    }

    if (query.generated == QStringLiteral("trash")) {
        // The account's OWN trash query, for the reason spelled out above the
        // sent case: wrapping the all-accounts query in this account's path
        // works by accident of path: being hierarchical.
        const QString trash = scope.trashQuery();
        return trash.isEmpty() ? matchNothingQuery() : trash;
    }

    // A tag filter carries no path of its own, so scoping is exactly what
    // scopedQuery() does. Its parentheses are load-bearing: `path:... and a or
    // b` binds as `(path:... and a) or b`.
    return scope.scopedQuery(
        QStringLiteral("tag:%1").arg(generatorTag(query.generated)));
}

SavedQuery Config::startupSavedQuery() const
{
    // The user's own queries first, so a saved query wins a name collision with
    // a built-in filter: they named theirs deliberately, where the filter's
    // name is one this application chose for them.
    for (const SavedQuery &query : m_savedQueries) {
        if (query.name.compare(m_startupQuery, Qt::CaseInsensitive) == 0)
            return query;
    }

    // Then the built-in filters. Without this, a startup_query of "Inbox"
    // matched nothing once item 93 shipped Inbox as a filter and the duplicated
    // saved query was removed, and the app started on whatever query happened
    // to be first in the file.
    //
    // Matched on the GENERATOR as well as the name, and the generator is what
    // makes this survive translation. A filter's name is a translated label, so
    // under LANG=it_IT the Inbox filter is called "In arrivo" and a config
    // reading `startup_query = Inbox` matched nothing, warned, and fell back to
    // another filter: the user's startup view changed because the UI language
    // did. The generator is stored in queries.json and matched against a closed
    // set, so it is wire format and identical in every locale. Names are still
    // tried first, so a translated name a user copied out of their own UI keeps
    // working.
    const QList<SavedQuery> filters = builtinFilters();
    for (const SavedQuery &filter : filters) {
        if (filter.name.compare(m_startupQuery, Qt::CaseInsensitive) == 0)
            return filter;
    }
    for (const SavedQuery &filter : filters) {
        if (filter.generated.compare(m_startupQuery, Qt::CaseInsensitive) == 0)
            return filter;
    }

    // Named nothing that exists. Falling back to m_savedQueries.first() is what
    // this used to do and it is worse than it looks: after the duplicated
    // entries were removed it could be any leftover query, so a startup view
    // became a search for one sender, and an empty queries.json started nothing
    // at all. A filter is always present, so the fallback can be one.
    //
    // Still not worth a warning: the default is a name the user never wrote.
    return builtinFilter(QStringLiteral("unread"));
}

QList<Account> Config::sendingAccounts() const
{
    QList<Account> sending;
    for (const Account &account : m_accounts) {
        if (account.canSend())
            sending.append(account);
    }
    return sending;
}

Account Config::account(const QString &key) const
{
    for (const Account &a : m_accounts) {
        if (a.key == key)
            return a;
    }
    return {};
}