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
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
|
/*
* 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 <QtTest>
#include <QAction>
#include <QApplication>
#include <QFocusEvent>
#include <QCloseEvent>
#include <QDir>
#include <QKeyEvent>
#include <QLabel>
#include <QLineEdit>
#include <QMenu>
#include <QPushButton>
#include <QProgressBar>
#include <QFile>
#include <QSet>
#include <QSettings>
#include <QStandardPaths>
#include <QTemporaryDir>
#include <QStyle>
#include <QSplitter>
#include <QTableView>
#include <QToolBar>
#include <QTreeView>
#include <QTimer>
#include "config.h"
#include "keymap.h"
#include "mainwindow.h"
#include "messageview.h"
#include "notmuchworker.h"
#include "carddelegate.h"
#include "cardlayout.h"
#include <QImage>
#include <QPainter>
#include <QComboBox>
#include <QScrollBar>
#include "tagchip.h"
#include "threadlistmodel.h"
#include "threadlistview.h"
/// MainWindow is mostly wiring, and the parts that need a real database are
/// still verified manually. What is checked here is the action registry: the
/// bindings a user configures reach the QActions the menus and the keyboard
/// both read from, and no action is left unreachable.
class TestMainWindow : public QObject
{
Q_OBJECT
private slots:
void everyKnownActionIsRegistered();
void everyRegisteredActionIsKnown();
void everyActionHasAShortcut();
void configuredBindingReachesTheAction();
void cidPrefixesAreBangFree();
void cidPrefixesAreDistinctPerMessage();
void uiStateIsNotWrittenIntoTheUserConfig();
void uiStateSurvivesARestart();
void missingUiStateLeavesTheDefaults();
void splitterStateFromAWiderWindowKeepsTheMessagePane();
void usableSplitterStateIsRestoredUntouched();
void headerStateFromADifferentColumnLayoutIsDiscarded();
void returnInTheQueryBarRunsTheQueryNotOpenThread();
void markReadTimerRestartsRatherThanStacking();
void markReadTimerIsNotArmedForAReadThread();
void markReadCanBeDisabled();
void pendingEditCountSurvivesAQuery();
void aFailedSyncDoesNotClearThePendingCount();
void closingWithNoPendingEditsDoesNotPrompt();
void syncOnExitNeverClosesSilently();
void selectAllIsBoundAndSelectsEveryRow();
void aMultiRowSelectionDoesNotArmTheMarkReadTimer();
void growingASelectionCancelsAnAlreadyArmedTimer();
void collapsingBackToOneRowLoadsThatThreadAgain();
void theStatusBarReportsAMultiRowSelection();
void clearSelectionBlanksThePaneAndDeselects();
void clearPaneLeavesTheSelectionAlone();
void maildirOverviewShowsUnknownRatherThanZero();
void maildirOverviewIgnoresAStaleReply();
void theThreadListOffersAContextMenu();
void aSecondRowBlanksThePaneNotOnlyAThird();
void aLocalSyncIsNotReportedAsABackgroundOne();
void aLocalSyncsOwnLockIsNeverReportedAsBackground();
void aSkippedLocalSyncStillReportsTheOtherRunFinishing();
void aCronSyncRefreshesTheListWithoutAQuery();
void aCronSyncRefreshesOverASelectionWithoutClearingIt();
void aCronSyncDoesNotRefreshBeforeAnyQueryHasRun();
void aRefreshAddsNewMailAndDropsWhatStoppedMatching();
void theOpenThreadLeavingTheListRaisesTheStaleNotice();
void aThreadStillMatchingRaisesNoStaleNotice();
void theStaleNoticeCarriesTheMessageBeingRead();
void recoveringAStaleThreadQueriesTheWholeThread();
void recoveryReselectsTheMessageThatWasBeingRead();
void recoveryOnTheFirstMessageSelectsTheThreadRow();
void aUserQueryAbandonsAPendingRecovery();
void blankingThePaneAlsoDropsTheStaleNotice();
void aNewQueryDropsTheStaleNotice();
void aFinishedBackgroundSyncStopsSayingItIsRunning();
void aRefreshDoesNotStampOverASelectionMessage();
void aRefreshDoesNotOpenNewMailByItself();
void openingAnotherMessageDropsTheStaleNoticeOfThePreviousOne();
void theStaleNoticeKeepsTheMessageOfAThreadRootToo();
void recoveryExpandsTheThreadAndSelectsRatherThanOnlyPointing();
void recoveryFromAnExpandedThreadRestoresTheReply();
void theRecoveryButtonSurvivesThePaneBeingBlanked();
void anUnobservableLockTableLeavesTheSyncButtonUsable();
void theStatusBarFollowsTheSyncPhase();
void aSelectedReadThreadIsNotDimmedIntoTheHighlight();
void childRowsAreIndentedUnderTheirThread();
void aThreadWithRepliesDrawsAVisibleExpander();
void cardsNeverScrollSideways();
void selectingARootCardKeepsItsThreadForMarkRead();
void nextThreadLeavesTheLastReply();
void altDownSkipsReplies();
void bothThreadStepBindingsReachTheAction();
void sortChoiceSurvivesRestart();
void accountEntriesCarryTheirColour();
void replyRowsKeepTheirTextUnderTheThreadLine();
void clickingTheExpanderTogglesTheThread();
void selectingAMessageRowTargetsThatMessageNotItsThread();
void selectingAThreadRowNamesHowManyMessagesItStandsFor();
void selectingAMessageRowReportsNoBulkCount();
void anActionOnAThreadRowSaysItHitTheWholeThread();
void anActionOnAMessageRowTagsThatMessageNotTheThread();
void markAllReadIsDisabledUntilTheQueryFinishes();
void markAllReadActsOnEveryRowAndUndoesInOneStep();
void markAllReadDoesNothingWhenNothingIsUnread();
void theSyncActionIsDisabledWhileABackgroundSyncHoldsTheLock();
void escapeBlanksTheMessagePane();
void deleteTogglesOnAnAlreadyDeletedThread();
void deleteOnAMixedSelectionDeletesRatherThanSplittingIt();
void aTransientStatusMessageExpires();
void theSelectionCountIsStateAndDoesNotExpire();
void anEditUndoneNettsBackToZero();
void aDifferentTagOnTheSameMessageStillCounts();
void anEditWithNoMessageIdsStillCounts();
void anEditDuringABackgroundSyncIsNotSentYet();
void aHeldEditIsSentWhenTheBackgroundSyncEnds();
void aHeldEditCountsAsUnsynced();
void anUnreadableLockTableStillSendsTheEdit();
void aRejectedWriteKeepsEarlierUndoHistory();
void aSuccessfulCronSyncClearsThePendingCount();
void aFailedCronSyncLeavesThePendingCount();
void anUnreadableSyncLogLeavesThePendingCount();
void anUnknownExternalStateClearsNothing();
void aSuccessfulCronSyncDrainsTheEditedAccounts();
void aCronSyncDoesNotClearAnEditMadeWhileItRan();
void everyActionCarriesAnIcon();
void theToolbarDoesNotOverrideTheDesktopButtonStyle();
void theImportantActionIsLabelledImportant();
void theImportantActionStillWritesTheFlaggedTag();
void theToolbarUsesTheConfiguredIconSize();
void thereIsNoSentButtonWithoutASentKey();
void theSentButtonRunsEveryConfiguredAccount();
void theSentButtonSurvivesABracketedPath();
void placeholderCountsSkipSentAndDraftsWithoutTheKeys();
void placeholderCountsCarrySentAndDrafts();
void placeholderLabelsStayPairedWithTheirQueries();
void placeholderCountsDropAnUncountableQuery();
void flatModeDoesNotSurviveTheNextQuery();
void noTwoActionsShareAnIcon();
};
void TestMainWindow::everyKnownActionIsRegistered()
{
// KeyMap::knownActions() is what loadOverrides() validates config bindings
// against. An action listed there but never registered means a user can
// bind a key in qtmaildir.conf, get no warning, and have it do nothing.
//
// registeredActionNames() is now derived from the QActions themselves, so
// this compares against what the window really installed.
const Config config;
MainWindow window(config);
const QStringList known = KeyMap::knownActions();
const QStringList registered = window.registeredActionNames();
for (const QString &action : known) {
QVERIFY2(registered.contains(action),
qPrintable(QStringLiteral("known action '%1' is never registered "
"by MainWindow").arg(action)));
}
}
void TestMainWindow::everyRegisteredActionIsKnown()
{
// The reverse drift: an action MainWindow implements but KeyMap rejects.
// The user would get "unknown action" for a binding that is really there.
const Config config;
MainWindow window(config);
const QStringList known = KeyMap::knownActions();
const QStringList registered = window.registeredActionNames();
for (const QString &action : registered) {
QVERIFY2(known.contains(action),
qPrintable(QStringLiteral("registered action '%1' is not in "
"KeyMap::knownActions()").arg(action)));
}
}
void TestMainWindow::everyActionHasAShortcut()
{
// An action with no binding is unreachable from the keyboard. Every one
// of them carries a default, so an empty shortcut means the default table
// and the action list have drifted apart.
const Config config;
MainWindow window(config);
for (const QString &name : window.registeredActionNames()) {
const QAction *action = window.findChild<QAction *>(name);
QVERIFY2(action, qPrintable(QStringLiteral("no QAction named '%1'").arg(name)));
QVERIFY2(!action->shortcut().isEmpty(),
qPrintable(QStringLiteral("action '%1' has no shortcut").arg(name)));
}
}
void TestMainWindow::configuredBindingReachesTheAction()
{
// The whole point of [keys]: a user's override must end up on the QAction,
// which is what both the keyboard and the menus read.
QTemporaryDir dir;
const QString path = dir.filePath(QStringLiteral("qtmaildir.conf"));
{
QSettings s(path, QSettings::IniFormat);
s.beginGroup(QStringLiteral("keys"));
s.setValue(QStringLiteral("Ctrl+Alt+A"), QStringLiteral("archive"));
s.endGroup();
}
// MainWindow reads its keymap from Config::defaultPath(), so point that
// at the temporary file for this test.
const QString previous = qEnvironmentVariable("XDG_CONFIG_HOME");
QVERIFY(QDir().mkpath(dir.filePath(QStringLiteral("qtmaildir"))));
QVERIFY(QFile::copy(path, dir.filePath(QStringLiteral("qtmaildir/qtmaildir.conf"))));
qputenv("XDG_CONFIG_HOME", dir.path().toUtf8());
{
const Config config;
MainWindow window(config);
const QAction *archive =
window.findChild<QAction *>(QStringLiteral("archive"));
QVERIFY(archive);
QCOMPARE(archive->shortcut(), QKeySequence(QStringLiteral("Ctrl+Alt+A")));
}
if (previous.isEmpty())
qunsetenv("XDG_CONFIG_HOME");
else
qputenv("XDG_CONFIG_HOME", previous.toUtf8());
}
void TestMainWindow::cidPrefixesAreBangFree()
{
// MainWindow is the only producer of cidPrefix in the application. The
// '!' separator that keeps two messages' cid: references apart is only
// unambiguous while the prefix half contains none.
for (int i : { 0, 1, 9, 10, 99, 1000 }) {
const QString prefix = MainWindow::cidPrefixForIndex(i);
QVERIFY(!prefix.isEmpty());
QVERIFY2(!prefix.contains(QLatin1Char('!')),
qPrintable(QStringLiteral("prefix '%1' contains '!'").arg(prefix)));
}
}
void TestMainWindow::cidPrefixesAreDistinctPerMessage()
{
// Two messages sharing a prefix would share a cid: namespace, which is the
// collision the namespacing exists to prevent.
QSet<QString> seen;
for (int i = 0; i < 200; ++i) {
const QString prefix = MainWindow::cidPrefixForIndex(i);
QVERIFY2(!seen.contains(prefix),
qPrintable(QStringLiteral("prefix '%1' repeats").arg(prefix)));
seen.insert(prefix);
}
}
void TestMainWindow::uiStateIsNotWrittenIntoTheUserConfig()
{
// The config file is hand-edited and must never gain a base64 geometry
// blob, nor be rewritten on exit: QSettings preserves neither comments nor
// key order, so writing it would quietly destroy the user's formatting.
QVERIFY(MainWindow::uiStatePath() != Config::defaultPath());
// One qtmaildir component, not two. QStandardPaths::StateLocation appends
// both the organization and the application name, and here both are
// "qtmaildir", so using it nests the directory inside itself.
QCOMPARE(MainWindow::uiStatePath().count(QStringLiteral("/qtmaildir/")), 1);
QVERIFY(MainWindow::uiStatePath().endsWith(
QStringLiteral("/qtmaildir/uistate.conf")));
}
void TestMainWindow::uiStateSurvivesARestart()
{
// Test mode redirects QStandardPaths at the process level, so the state
// file lands in a scratch directory rather than the real ~/.local/state.
QStandardPaths::setTestModeEnabled(true);
QFile::remove(MainWindow::uiStatePath());
// Must fit the smallest screen this ever runs against: the offscreen
// platform reports 800x800, and restoreGeometry() clamps to the available
// area, so a 940px width came back as 798 and failed only under offscreen.
// The number carries no meaning beyond differing from the default size.
const QSize resized(640, 560);
{
const Config config;
MainWindow window(config);
window.resize(resized);
window.findChild<MessageView *>()->setZoomFactor(1.4);
window.close(); // closeEvent() is what persists the state
}
QVERIFY2(QFile::exists(MainWindow::uiStatePath()),
qPrintable(QStringLiteral("no state file at %1")
.arg(MainWindow::uiStatePath())));
const Config config;
MainWindow reopened(config);
QCOMPARE(reopened.size(), resized);
QCOMPARE(reopened.findChild<MessageView *>()->zoomFactor(), 1.4);
QFile::remove(MainWindow::uiStatePath());
QStandardPaths::setTestModeEnabled(false);
}
void TestMainWindow::missingUiStateLeavesTheDefaults()
{
// A restore that silently succeeded on an empty blob would give a
// zero-size window on first launch. Absent state must be a no-op.
QStandardPaths::setTestModeEnabled(true);
QFile::remove(MainWindow::uiStatePath());
const Config config;
MainWindow window(config);
QCOMPARE(window.size(), QSize(1200, 800));
QStandardPaths::setTestModeEnabled(false);
}
void TestMainWindow::splitterStateFromAWiderWindowKeepsTheMessagePane()
{
// The reported symptom, from a real state file: a splitter position saved
// at 1285/1252 and restored into a 1136px window. QSplitter honours the
// first size and gives the second what is left, so the message pane came
// back roughly 30px wide, a sliver of rendered mail against a full-width
// thread list. It is not a first-run problem, which is why widening the
// default window would not have helped: the wider the window ever was, the
// worse the next narrower session is.
QStandardPaths::setTestModeEnabled(true);
QFile::remove(MainWindow::uiStatePath());
{
const Config config;
MainWindow window(config);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
auto *splitter = window.findChild<QSplitter *>();
QVERIFY(splitter);
// Guard: the forged sizes have to be genuinely wider than the window
// this reopens into, or the test proves nothing.
QVERIFY(splitter->width() > 0);
// Times four, not times two: the offscreen platform chooses the window
// width itself and has been seen to choose differently between runs of
// this binary, so a margin that only just exceeds THIS window's width
// can fail to exceed the reopened one's and quietly stop reproducing
// the bug.
const int overwide = splitter->width() * 4;
splitter->setSizes({ overwide, overwide });
window.close();
}
const Config config;
MainWindow reopened(config);
reopened.show();
QVERIFY(QTest::qWaitForWindowExposed(&reopened));
auto *splitter = reopened.findChild<QSplitter *>();
QVERIFY(splitter);
const QList<int> sizes = splitter->sizes();
QCOMPARE(sizes.size(), 2);
// Asserted against the pane's OWN minimum rather than a number repeated
// here: the floor is private to MainWindow, and a literal copy would keep
// passing if the shipped one were lowered back to a width mail cannot be
// read at. The guard below is what stops that from being vacuous.
auto *pane = reopened.findChild<MessageView *>();
QVERIFY(pane);
QVERIFY2(pane->minimumWidth() >= 300,
qPrintable(QStringLiteral("message pane floor is %1px")
.arg(pane->minimumWidth())));
QVERIFY2(sizes.at(1) >= pane->minimumWidth(),
qPrintable(QStringLiteral("message pane restored %1px wide in a "
"%2px splitter")
.arg(sizes.at(1))
.arg(splitter->width())));
reopened.close();
QFile::remove(MainWindow::uiStatePath());
QStandardPaths::setTestModeEnabled(false);
}
void TestMainWindow::usableSplitterStateIsRestoredUntouched()
{
// The rescue must not fire on a position that fits. This is item 1's whole
// point: a splitter the user dragged comes back where they left it.
QStandardPaths::setTestModeEnabled(true);
QFile::remove(MainWindow::uiStatePath());
QList<int> saved;
{
const Config config;
MainWindow window(config);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
auto *splitter = window.findChild<QSplitter *>();
QVERIFY(splitter);
// Lopsided but both panes usable, so nothing should touch it. Sized as
// a fraction rather than "width minus 250": this window's width is the
// platform's to choose and has been seen to differ between two runs of
// the same binary, so an absolute split saved here can arrive too wide
// for the reopened window and trip the rescue the test is asserting
// does NOT fire.
const int total = splitter->width();
QVERIFY(total > 500);
splitter->setSizes({ total / 4, total - total / 4 });
saved = splitter->sizes();
QVERIFY(saved.at(0) < saved.at(1));
window.close();
}
const Config config;
MainWindow reopened(config);
reopened.show();
QVERIFY(QTest::qWaitForWindowExposed(&reopened));
auto *splitter = reopened.findChild<QSplitter *>();
QVERIFY(splitter);
// The saved ratio, not the saved pixels: QSplitter redistributes to the
// current width, and only a rescue would flip which pane is the larger.
// The FIRST pane's saved pixel width is what must survive: QSplitter
// restores it verbatim and gives the second whatever the current window
// leaves, so this is the value a rescue would overwrite and the only one
// that does not move with the window width. Which matters here, because
// the offscreen platform picks that width itself and has been seen to
// pick differently between two runs of this same binary (1181 and 779),
// so any assertion on a ratio or on pane 1 is checking the platform's
// mood rather than this code.
const QList<int> sizes = splitter->sizes();
QCOMPARE(sizes.at(0), saved.at(0));
reopened.close();
QFile::remove(MainWindow::uiStatePath());
QStandardPaths::setTestModeEnabled(false);
}
void TestMainWindow::headerStateFromADifferentColumnLayoutIsDiscarded()
{
// The upgrade hazard: a 0.3.0 state file holds a three-column header blob,
// and 0.4.0 added the attachment column in front. QHeaderView::
// restoreState() returns TRUE for a blob with fewer sections than the
// model and applies the old widths shifted one column right, mangling the
// layout with no error to detect it by (verified on Qt 6.11). The stored
// column count is what makes that detectable.
QStandardPaths::setTestModeEnabled(true);
QFile::remove(MainWindow::uiStatePath());
{
const Config config;
MainWindow window(config);
window.close();
}
// Forge a state file from the five-column layout. Nothing reads these keys
// any more, and that is exactly what must be verified: a blob saved by an
// older version has to be ignored rather than applied to a one-column view.
{
QSettings state(MainWindow::uiStatePath(), QSettings::IniFormat);
state.setValue(QStringLiteral("threadlist/columns"), 5);
state.setValue(QStringLiteral("threadlist/header"),
QByteArray("not a header this model could have saved"));
}
// Constructing must not apply it, and must not crash on the garbage blob.
const Config config;
MainWindow reopened(config);
auto *view = reopened.findChild<QTreeView *>();
QVERIFY(view);
QCOMPARE(view->model()->columnCount(), 1);
QFile::remove(MainWindow::uiStatePath());
QStandardPaths::setTestModeEnabled(false);
}
void TestMainWindow::returnInTheQueryBarRunsTheQueryNotOpenThread()
{
// Return is bound to open_thread as a WindowShortcut, and the query bar has
// to win it back while it has focus. Qt withholds a plain-LETTER shortcut
// from an editable widget, but Return is not a letter and gets no such
// protection, so without an explicit override the action fires, the query
// never runs, and focus jumps to the thread list.
//
// The delivery order matters and is the reason this bug survived earlier
// tests: real input sends ShortcutOverride first and only dispatches the
// shortcut if nothing accepts it. QTest::keyClick() skips that round trip,
// so a test written with it passes against the broken code.
const Config config;
MainWindow window(config);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
auto *edit = window.findChild<QLineEdit *>();
QVERIFY(edit);
edit->setFocus();
QTRY_COMPARE(QApplication::focusWidget(), edit);
edit->setText(QStringLiteral("tag:unread"));
QAction *openThread = window.findChild<QAction *>(QStringLiteral("open_thread"));
QVERIFY(openThread);
bool actionFired = false;
connect(openThread, &QAction::triggered, &window, [&actionFired]() {
actionFired = true;
});
// The query bar must claim the override, which is what stops the shortcut
// from ever being dispatched.
QKeyEvent override(QEvent::ShortcutOverride, Qt::Key_Return, Qt::NoModifier);
override.ignore();
QApplication::sendEvent(edit, &override);
QVERIFY2(override.isAccepted(),
"the query bar let Return through to the open_thread shortcut");
QVERIFY(!actionFired);
}
/// Selects a top-level THREAD row, replacing QTableView::selectRow which a
/// QTreeView does not have.
///
/// Not merely a rename: setCurrentIndex alone leaves the selection model empty,
/// and select() alone leaves current invalid, so every test asserting on either
/// would break in a different way. Both are set here, exactly as
/// QTableView::selectRow did.
static void selectThreadRow(QTreeView *view, int row)
{
const QModelIndex index = view->model()->index(row, 0, QModelIndex());
view->selectionModel()->select(
index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
view->setCurrentIndex(index);
}
/// The height of a top-level row, replacing QTableView::rowHeight(int).
static int threadRowHeight(QTreeView *view, int row)
{
return view->visualRect(view->model()->index(row, 0, QModelIndex())).height();
}
/// A thread summary carrying the tags a test needs. Enough to drive selection;
/// nothing here touches a database.
static ThreadSummary makeThread(const QString &id, const QStringList &tags)
{
ThreadSummary thread;
thread.threadId = id;
thread.subject = QStringLiteral("Subject ") + id;
thread.authors = QStringLiteral("Someone <someone@example.org>");
thread.tags = tags;
return thread;
}
void TestMainWindow::childRowsAreIndentedUnderTheirThread()
{
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY2(view, "the thread list is not a QTreeView, so it cannot indent");
// With an account tag, so the thread row draws the chip that a reply row
// does not. That asymmetry is the whole reason the indent has to be wide,
// and a test against an untagged thread never sees it.
model->appendBatch({ makeThread(
QStringLiteral("t1"),
QStringList{ TagColors::tagForAccountKey(QStringLiteral("work")) }) });
MessageNode first;
first.messageId = QStringLiteral("m0@example.org");
first.threadId = QStringLiteral("t1");
first.depth = 0;
MessageNode reply;
reply.messageId = QStringLiteral("m1@example.org");
reply.threadId = QStringLiteral("t1");
reply.from = QStringLiteral("A Replier <replier@example.org>");
reply.depth = 1;
model->setThreadMessages(QStringLiteral("t1"), { first, reply });
window.resize(1400, 300);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
const QModelIndex root = model->index(0, 0, QModelIndex());
view->expand(root);
QApplication::processEvents();
// One column, and setIndentation(0): Qt indents nothing, CardLayout draws
// the indent itself. So visualRect reports the SAME rect for a thread and
// its reply, and the indent has to be read off the layout rather than off
// the geometry. That is the trap CLAUDE.md records in reverse: there,
// visualRect reported an indent the text did not have; here it reports
// none while the text is indented.
const QModelIndex rootCell = model->index(0, 0, QModelIndex());
const QModelIndex child = model->index(0, 0, root);
QVERIFY(child.isValid());
// Guards before the claim: a probe that cannot see both rows can report
// anything it likes about their relative position.
QVERIFY2(view->visualRect(rootCell).height() > 0,
"the thread row has no height, so nothing about it is measurable");
QVERIFY2(view->visualRect(child).height() > 0,
"the reply row has no height: it is collapsed or off-screen, and "
"an indent test against it would pass without drawing anything");
// The indent is NOT in the geometry. setIndentation(0) means visualRect
// reports the same left edge for both rows, deliberately: CardLayout draws
// the indent inside the card's own rect. Asserting on visualRect here
// would fail against a perfectly indented list, which is the mirror of the
// trap CLAUDE.md records for item 20, where visualRect reported an indent
// the text did not have.
//
// So the real property, as before: where the TEXT lands. It is read off
// the layout, which is what the delegate paints from.
CardLayout::Input threadIn;
threadIn.isMessage = false;
threadIn.depth = 0;
CardLayout::Input replyIn;
replyIn.isMessage = true;
replyIn.depth =
model->data(child, ThreadListModel::MessageDepthRole).toInt();
QVERIFY2(replyIn.depth > 0,
"the reply reports depth 0, so there is no nesting to measure");
const QRect rect = view->visualRect(rootCell);
const CardLayout threadCard =
CardLayout::compute(threadIn, rect, view->font());
const CardLayout replyCard =
CardLayout::compute(replyIn, rect, view->font());
QVERIFY2(replyCard.contentLeft > threadCard.contentLeft,
qPrintable(QStringLiteral("the reply's text starts at x=%1, not "
"right of the thread's at x=%2: the "
"nesting is invisible")
.arg(replyCard.contentLeft)
.arg(threadCard.contentLeft)));
// And the spine that makes the nesting read as one block rather than as an
// arbitrary offset.
QCOMPARE(replyCard.spines.size(), replyIn.depth);
}
namespace {
/// Two threads, the first with one reply, expanded. The shared fixture for the
/// two navigation tests below.
struct NavFixture
{
QTreeView *view = nullptr;
ThreadListModel *model = nullptr;
QModelIndex root;
QModelIndex reply;
};
NavFixture buildNavFixture(MainWindow &window)
{
NavFixture f;
f.view = window.findChild<QTreeView *>();
f.model = window.findChild<ThreadListModel *>();
// unread, so a selection arms the mark-read timer: scheduleMarkRead()
// returns early for a thread that is already read, and a fixture without
// it would make a mark-read assertion pass for the wrong reason.
ThreadSummary first = makeThread(QStringLiteral("T1"),
QStringList{ QStringLiteral("inbox"),
QStringLiteral("unread") });
first.totalCount = 2;
ThreadSummary second = makeThread(QStringLiteral("T2"),
QStringList{ QStringLiteral("inbox") });
second.totalCount = 1;
f.model->appendBatch({ first, second });
MessageNode rootNode;
rootNode.messageId = QStringLiteral("M1");
rootNode.threadId = QStringLiteral("T1");
rootNode.depth = 0;
MessageNode replyNode;
replyNode.messageId = QStringLiteral("M2");
replyNode.threadId = QStringLiteral("T1");
replyNode.depth = 1;
f.model->setThreadMessages(QStringLiteral("T1"), { rootNode, replyNode });
f.root = f.model->index(0, 0);
f.view->expand(f.root);
f.reply = f.model->index(0, 0, f.root);
return f;
}
} // namespace
void TestMainWindow::selectingARootCardKeepsItsThreadForMarkRead()
{
// A root card is BOTH a message and a thread: it renders the thread's
// first message, and it is still the thread that gets marked read and
// repainted on a tag change. The message-row path deliberately clears the
// current thread id; doing that here too would silently disable mark-read
// and the tag-change repaint for every thread root in the list.
const Config config;
MainWindow window(config);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
const NavFixture f = buildNavFixture(window);
f.view->setCurrentIndex(f.root);
QApplication::processEvents();
// Guard: the fixture loads replies, so the root knows its own message and
// the branch under test is the one that runs.
QVERIFY2(!f.model->data(f.root, ThreadListModel::MessageIdRole)
.toString().isEmpty(),
"the root card does not know its first message, so this exercises "
"the fallback rather than the path it is written for");
// A mark-read timer armed for the thread is what proves the thread id
// survived: scheduleMarkRead() is only reached on the thread-row path.
auto *timer = window.findChild<QTimer *>(QStringLiteral("markReadTimer"));
QVERIFY(timer);
QVERIFY2(timer->isActive(),
"no mark-read timer for a selected root card: its thread id was "
"cleared along with the switch to rendering one message");
}
void TestMainWindow::nextThreadLeavesTheLastReply()
{
const Config config;
MainWindow window(config);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
const NavFixture f = buildNavFixture(window);
QVERIFY(f.reply.isValid());
QVERIFY2(f.view->isExpanded(f.root),
"the thread is collapsed, so this test would arrow down a flat "
"list and pass against the bug it exists to catch");
f.view->setCurrentIndex(f.reply);
// The defect (item 60): selectRow(current.row() + 1) asked for row 1 UNDER
// T1, which does not exist, so the action did nothing at all.
window.findChild<QAction *>(QStringLiteral("next_thread"))->trigger();
QCOMPARE(f.view->currentIndex().data(ThreadListModel::ThreadIdRole)
.toString(),
QStringLiteral("T2"));
}
void TestMainWindow::altDownSkipsReplies()
{
const Config config;
MainWindow window(config);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
const NavFixture f = buildNavFixture(window);
QVERIFY(f.view->isExpanded(f.root));
// From the thread ROOT with its replies showing: one step must land on the
// next THREAD, not on the first reply. That is what makes the action mean
// thread-to-thread while plain Up/Down still steps message-to-message.
f.view->setCurrentIndex(f.root);
window.findChild<QAction *>(QStringLiteral("next_thread"))->trigger();
QCOMPARE(f.view->currentIndex().data(ThreadListModel::ThreadIdRole)
.toString(),
QStringLiteral("T2"));
QVERIFY(!f.view->currentIndex().data(ThreadListModel::IsMessageRole)
.toBool());
// And back, which is the mirror case the old arithmetic also failed.
window.findChild<QAction *>(QStringLiteral("prev_thread"))->trigger();
QCOMPARE(f.view->currentIndex().data(ThreadListModel::ThreadIdRole)
.toString(),
QStringLiteral("T1"));
QVERIFY(!f.view->currentIndex().data(ThreadListModel::IsMessageRole)
.toBool());
}
void TestMainWindow::bothThreadStepBindingsReachTheAction()
{
const Config config;
MainWindow window(config);
// Two bindings per action, which needs setShortcuts rather than
// setShortcut: Ctrl+J/K for a neomutt hand, Alt+Up/Down for a mouse one.
// Alt because Shift+arrows is QTreeView's built-in extend-selection that
// multi-row tagging depends on, and a bare arrow cannot be a window
// shortcut without breaking every text field in the window.
for (const auto &pair : { std::pair<const char *, const char *>{
"next_thread", "Alt+Down" },
{ "prev_thread", "Alt+Up" } }) {
auto *action =
window.findChild<QAction *>(QString::fromLatin1(pair.first));
QVERIFY2(action, pair.first);
const QList<QKeySequence> shortcuts = action->shortcuts();
QVERIFY2(shortcuts.size() >= 2,
qPrintable(QStringLiteral("%1 carries %2 shortcut(s), so the "
"second binding is unreachable")
.arg(QString::fromLatin1(pair.first))
.arg(shortcuts.size())));
QVERIFY2(shortcuts.contains(
QKeySequence(QString::fromLatin1(pair.second))),
pair.second);
}
}
void TestMainWindow::sortChoiceSurvivesRestart()
{
QStandardPaths::setTestModeEnabled(true);
QFile::remove(MainWindow::uiStatePath());
{
const Config config;
MainWindow window(config);
auto *sort = window.findChild<QComboBox *>(QStringLiteral("sortOrder"));
QVERIFY(sort);
QCOMPARE(sort->count(), 2);
QCOMPARE(sort->currentIndex(), 0); // Newest first by default.
sort->setCurrentIndex(1);
window.close();
}
const Config config;
MainWindow second(config);
auto *sort = second.findChild<QComboBox *>(QStringLiteral("sortOrder"));
QVERIFY(sort);
QCOMPARE(sort->currentIndex(), 1);
// A stale or hand-edited file can hold anything, which is the lesson item
// 58 recorded: an out-of-range value must fall back rather than select a
// row that does not exist.
{
QSettings state(MainWindow::uiStatePath(), QSettings::IniFormat);
state.setValue(QStringLiteral("threadlist/sortOrder"), 47);
}
MainWindow third(config);
auto *thirdSort = third.findChild<QComboBox *>(QStringLiteral("sortOrder"));
QCOMPARE(thirdSort->currentIndex(), 0);
QFile::remove(MainWindow::uiStatePath());
QStandardPaths::setTestModeEnabled(false);
}
void TestMainWindow::accountEntriesCarryTheirColour()
{
// Its own config, not the environment's. Reading the real one made this
// SKIP wherever no accounts are configured, which is a test that asserts
// nothing while reporting success.
QTemporaryDir dir;
const QString path = dir.filePath(QStringLiteral("qtmaildir.conf"));
{
QSettings s(path, QSettings::IniFormat);
s.beginGroup(QStringLiteral("account.work"));
s.setValue(QStringLiteral("maildir"), QStringLiteral("work"));
s.setValue(QStringLiteral("color"), QStringLiteral("#3d7fd1"));
s.endGroup();
s.beginGroup(QStringLiteral("account.personal"));
s.setValue(QStringLiteral("maildir"), QStringLiteral("personal"));
s.endGroup();
}
Config config;
config.load(path);
QCOMPARE(config.accounts().size(), 2);
MainWindow window(config);
auto *box = window.findChild<QComboBox *>(QStringLiteral("accountBox"));
QVERIFY(box);
QCOMPARE(box->count(), 3);
// "All accounts" is not an account and carries no swatch.
QVERIFY(!box->itemData(0, Qt::DecorationRole).isValid());
// Every real account does, including the one with no color= key:
// colourFor() never fails, deriving a stable colour from the tag name, so
// adding an account and forgetting to colour it degrades to something
// usable rather than to nothing.
QSet<QRgb> seen;
for (int i = 1; i < box->count(); ++i) {
const QVariant swatch = box->itemData(i, Qt::DecorationRole);
QVERIFY2(swatch.isValid(),
qPrintable(QStringLiteral("account %1 carries no swatch")
.arg(box->itemText(i))));
const QColor colour = swatch.value<QColor>();
QVERIFY(colour.isValid());
seen.insert(colour.rgb());
}
// Guard: two accounts sharing one colour would make the swatches useless
// as a key to the accent bars, and would let a broken lookup pass.
QCOMPARE(seen.size(), 2);
}
void TestMainWindow::cardsNeverScrollSideways()
{
const Config config;
MainWindow window(config);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
// A long subject, so the guard below is not vacuous: this is exactly the
// content that used to make the subject column wider than the viewport.
model->appendBatch({ makeThread(
QStringLiteral("t1"),
QStringList{ QStringLiteral("inbox") }) });
QApplication::processEvents();
// Item 51: clicking a row used to scroll the list sideways, because the
// subject column was wider than the viewport and auto-scroll brought the
// clicked index fully into view. A card is exactly viewport width, so
// there is nowhere to scroll to.
QVERIFY2(view->visualRect(model->index(0, 0)).height() > 0,
"no card is drawn, so there is no layout to assert about");
QCOMPARE(view->horizontalScrollBar()->minimum(),
view->horizontalScrollBar()->maximum());
}
void TestMainWindow::aThreadWithRepliesDrawsAVisibleExpander()
{
// The expander is the ONLY thing saying a thread can be opened, and it took
// four wrong attempts to get on screen before item 53, each of which looked
// correct in code and none of which a geometry or role assertion could see.
// So this counts painted pixels.
//
// Painted through the DELEGATE rather than through viewport()->render().
// The viewport render returns a blank image here: CLAUDE.md records that it
// does so in several ordinary situations, and this test proved it again,
// reporting zero ink over a card the delegate demonstrably paints 2183
// pixels into. A probe that sees nothing cannot report on anything.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
// Two threads: one with replies, one without. The second is the control,
// and without it a test that counts ink would pass on any card.
ThreadSummary withReplies = makeThread(
QStringLiteral("t1"),
QStringList{ TagColors::tagForAccountKey(QStringLiteral("work")) });
withReplies.totalCount = 3;
ThreadSummary lone = makeThread(
QStringLiteral("t2"),
QStringList{ TagColors::tagForAccountKey(QStringLiteral("work")) });
lone.totalCount = 1;
model->appendBatch({ withReplies, lone });
const QModelIndex first = model->index(0, 0, QModelIndex());
const QModelIndex second = model->index(1, 0, QModelIndex());
// Guards: the model agrees about which thread has replies, and only that
// one is offered an expander at all.
QCOMPARE(model->data(first, ThreadListModel::ReplyCountRole).toInt(), 2);
QCOMPARE(model->data(second, ThreadListModel::ReplyCountRole).toInt(), 0);
const QFont font = view->font();
const int height = CardLayout::heightFor(font);
const auto inkInExpander = [&](const QModelIndex &index) {
QImage shot(400, height, QImage::Format_ARGB32);
shot.fill(Qt::white);
QPainter painter(&shot);
QStyleOptionViewItem option;
option.rect = QRect(0, 0, 400, height);
option.font = font;
option.palette = QApplication::palette();
option.state = QStyle::State_Enabled;
CardDelegate delegate;
delegate.paint(&painter, option, index);
painter.end();
const QRect rect = CardDelegate::expanderRectFor(option, index);
int found = 0;
for (int y = rect.top(); y <= rect.bottom() && y < shot.height(); ++y) {
for (int x = rect.left(); x <= rect.right() && x < shot.width();
++x) {
if ((shot.pixel(x, y) | 0xff000000) != 0xffffffffu)
++found;
}
}
// Guard on the probe itself: prove it can see the card's own text
// before trusting it about the expander. A probe that finds no ink
// anywhere reports "nothing was drawn" whatever the delegate did.
int anyInk = 0;
for (int y = 0; y < shot.height(); ++y)
for (int x = 0; x < shot.width(); ++x)
if ((shot.pixel(x, y) | 0xff000000) != 0xffffffffu)
++anyInk;
return std::pair<int, int>(found, anyInk);
};
const auto [drawn, drawnAnywhere] = inkInExpander(first);
const auto [control, controlAnywhere] = inkInExpander(second);
QVERIFY2(drawnAnywhere > 0 && controlAnywhere > 0,
"the probe finds no ink on either card, so it cannot report on "
"the expander either");
QVERIFY2(drawn > 12,
qPrintable(QStringLiteral("only %1 pixels in the expander's rect: "
"the reply count is clipped or painted "
"over").arg(drawn)));
QVERIFY2(control == 0,
qPrintable(QStringLiteral("a thread with no replies drew %1 "
"pixels where an expander would go")
.arg(control)));
}
void TestMainWindow::selectingAThreadRowNamesHowManyMessagesItStandsFor()
{
// With two kinds of row selectable, one selected row no longer says how
// much an action will touch. CLAUDE.md forbids a confirmation dialog for
// tag mutations, so the scope is made visible instead: this is the "before"
// half of that, and the count has to come from the thread's own total, not
// from whatever happens to be expanded.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
ThreadSummary t = makeThread(QStringLiteral("t1"), {});
t.totalCount = 7;
model->appendBatch({ t });
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
// Guard: nothing is expanded, so a count taken from the loaded children
// would read 0 and this test would be measuring the wrong source.
QCOMPARE(model->rowCount(model->index(0, 0, QModelIndex())), 0);
selectThreadRow(view, 0);
QApplication::processEvents();
QVERIFY2(status->text().contains(QStringLiteral("7")),
qPrintable(QStringLiteral("the status bar says '%1', which does "
"not name the 7 messages the thread "
"stands for")
.arg(status->text())));
}
void TestMainWindow::selectingAMessageRowReportsNoBulkCount()
{
// Reading one message is not a bulk action, so it gets no count. A message
// row reporting "1 thread selected" would be actively wrong about what an
// action would touch.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
ThreadSummary t = makeThread(QStringLiteral("t1"), {});
t.totalCount = 3;
model->appendBatch({ t });
MessageNode root;
root.messageId = QStringLiteral("m0@example.org");
root.threadId = QStringLiteral("t1");
root.depth = 0;
MessageNode reply;
reply.messageId = QStringLiteral("m1@example.org");
reply.threadId = QStringLiteral("t1");
reply.depth = 1;
model->setThreadMessages(QStringLiteral("t1"), { root, reply });
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
const QModelIndex threadRow = model->index(0, 0, QModelIndex());
view->expand(threadRow);
QApplication::processEvents();
const QModelIndex messageRow = model->index(0, 0, threadRow);
QVERIFY(model->isMessageRow(messageRow));
view->selectionModel()->select(
messageRow,
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
view->setCurrentIndex(messageRow);
QApplication::processEvents();
QVERIFY2(!status->text().contains(QStringLiteral("thread")),
qPrintable(QStringLiteral("a single message row reports '%1', "
"which claims a thread-wide scope it "
"does not have")
.arg(status->text())));
}
void TestMainWindow::anActionOnAThreadRowSaysItHitTheWholeThread()
{
// The "after" half. Undo is the safety net this project chose over a
// confirmation dialog, and undo is only usable if the user can tell that
// something bigger than they intended just happened.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
ThreadSummary t = makeThread(QStringLiteral("t1"), {});
t.totalCount = 7;
model->appendBatch({ t });
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
selectThreadRow(view, 0);
QApplication::processEvents();
auto *archive = window.findChild<QAction *>(QStringLiteral("archive"));
QVERIFY2(archive, "no archive action to trigger");
archive->trigger();
// Read BEFORE processEvents, deliberately. This binary has no worker
// (backlog item 36), so the queued applyTagsToThreads reaches a throwaway
// database that has never heard of thread t1 and answers with
// errorOccurred, which overwrites the status bar. Draining the event loop
// here would assert on that error rather than on the scope message, and
// the test would fail against correct code.
const QString message = status->text();
QVERIFY2(message.contains(QStringLiteral("7")),
qPrintable(QStringLiteral("after archiving a 7-message thread the "
"status bar says '%1', which does not "
"say how much was touched")
.arg(message)));
// And it must say the whole thread went, not merely how many messages: the
// count alone does not distinguish "7 messages you picked" from "7 messages
// because you picked their thread".
QVERIFY2(message.contains(QStringLiteral("whole thread")),
qPrintable(QStringLiteral("the status bar says '%1', which does "
"not say the action took the whole "
"thread")
.arg(message)));
}
void TestMainWindow::anActionOnAMessageRowTagsThatMessageNotTheThread()
{
// The routing itself, which nothing else here can see. A message row sent
// down the THREAD path produces the same undo depth and the same status
// text while tagging every sibling in the conversation: a mutation that did
// exactly that passed the entire suite, so this test exists because that
// gap was found rather than because the path looked risky.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
ThreadSummary t = makeThread(QStringLiteral("t1"), {});
t.totalCount = 3;
model->appendBatch({ t });
MessageNode root;
root.messageId = QStringLiteral("m0@example.org");
root.threadId = QStringLiteral("t1");
root.depth = 0;
MessageNode reply;
reply.messageId = QStringLiteral("m1@example.org");
reply.threadId = QStringLiteral("t1");
reply.depth = 1;
model->setThreadMessages(QStringLiteral("t1"), { root, reply });
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
const QModelIndex threadRow = model->index(0, 0, QModelIndex());
view->expand(threadRow);
QApplication::processEvents();
const QModelIndex messageRow = model->index(0, 0, threadRow);
QVERIFY(model->isMessageRow(messageRow));
view->selectionModel()->select(
messageRow,
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
view->setCurrentIndex(messageRow);
QApplication::processEvents();
auto *archive = window.findChild<QAction *>(QStringLiteral("archive"));
QVERIFY(archive);
archive->trigger();
// The change must carry the MESSAGE id and no thread id. Sent as a thread
// id it would archive the root and every other reply along with it.
QCOMPARE(window.pendingMessageIdsForTesting(),
QStringList{ QStringLiteral("m1@example.org") });
QVERIFY2(window.pendingThreadIdsForTesting().isEmpty(),
qPrintable(QStringLiteral("the action was sent for thread(s) %1: a "
"message row must not tag its siblings")
.arg(window.pendingThreadIdsForTesting()
.join(QStringLiteral(", ")))));
// And it is undoable, on its own terms rather than the thread's.
QCOMPARE(window.undoDepthForTesting(), 1);
}
void TestMainWindow::selectingAMessageRowTargetsThatMessageNotItsThread()
{
// test_mainwindow has no worker (backlog item 36), so this cannot assert on
// what the pane renders. What it CAN assert is the decision the UI makes:
// a message row must stop tracking a current thread, or a reply arriving
// for either kind of selection cannot tell which one it belongs to.
//
// The trap this covers is specific. threadAt() takes a TOP-LEVEL row
// number, and a child's row number indexes its siblings, so handing a
// message row's number to it loads whichever thread happens to sit at that
// position in the list. Row 0 under a thread is a plausible-looking wrong
// answer, which is why the fixture puts the reply under the SECOND thread.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
ThreadSummary first = makeThread(QStringLiteral("t1"), {});
ThreadSummary second = makeThread(QStringLiteral("t2"), {});
second.totalCount = 2;
model->appendBatch({ first, second });
MessageNode root;
root.messageId = QStringLiteral("m0@example.org");
root.threadId = QStringLiteral("t2");
root.depth = 0;
MessageNode reply;
reply.messageId = QStringLiteral("m1@example.org");
reply.threadId = QStringLiteral("t2");
reply.depth = 1;
model->setThreadMessages(QStringLiteral("t2"), { root, reply });
window.resize(1400, 300);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
// Start on a thread row, so the transition to a message row is what is
// being observed rather than the initial state.
const QModelIndex threadRow = model->index(1, 0, QModelIndex());
selectThreadRow(view, 1);
QApplication::processEvents();
QCOMPARE(window.currentThreadId(), QStringLiteral("t2"));
view->expand(threadRow);
QApplication::processEvents();
const QModelIndex messageRow = model->index(0, 0, threadRow);
QVERIFY(messageRow.isValid());
QVERIFY2(model->isMessageRow(messageRow),
"the fixture did not produce a message row, so this test would "
"assert nothing about one");
view->selectionModel()->select(
messageRow,
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
view->setCurrentIndex(messageRow);
QApplication::processEvents();
// The thread is no longer what the pane is about. Left set, a late
// loadThread reply would repaint the whole conversation over the single
// message the user asked for.
QVERIFY2(window.currentThreadId().isEmpty(),
qPrintable(QStringLiteral("selecting a reply left the current "
"thread set to '%1': the pane is still "
"tracking the conversation")
.arg(window.currentThreadId())));
}
void TestMainWindow::clickingTheExpanderTogglesTheThread()
{
// The glyph being VISIBLE and the glyph being CLICKABLE are separate
// properties, and the pixel test for the first passes happily against a
// triangle nothing can hit. Turning off rootIsDecorated to stop the style
// drawing its own dot under ours also removed the style's hit area, so the
// expander rendered perfectly and did nothing.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
ThreadSummary t = makeThread(
QStringLiteral("t1"),
QStringList{ TagColors::tagForAccountKey(QStringLiteral("work")) });
t.totalCount = 3;
model->appendBatch({ t });
window.resize(1400, 300);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
QApplication::processEvents();
const QModelIndex root = model->index(0, 0, QModelIndex());
const QModelIndex subject =
model->index(0, 0, QModelIndex());
const QRect rect = view->visualRect(subject);
// Guards: the row is drawn, it claims to have replies, and it starts
// collapsed. Without the last one a toggle test can pass by doing nothing.
QVERIFY2(rect.height() > 0, "the thread row is not on screen");
QVERIFY(model->data(subject, ThreadListModel::HasRepliesRole).toBool());
QVERIFY(!view->isExpanded(root));
// Aimed at the rect the delegate reports, not at one reconstructed here:
// the drawn target and the clickable one cannot drift if both come from
// the same call.
QStyleOptionViewItem option;
option.rect = rect;
option.font = view->font();
const QRect expander = CardDelegate::expanderRectFor(option, subject);
QVERIFY2(!expander.isEmpty(), "the card offers no expander to click");
const QPoint hit = expander.center();
QTest::mouseClick(view->viewport(), Qt::LeftButton, Qt::NoModifier, hit);
QApplication::processEvents();
QVERIFY2(view->isExpanded(root),
"clicking the expander did not open the thread");
QTest::mouseClick(view->viewport(), Qt::LeftButton, Qt::NoModifier, hit);
QApplication::processEvents();
QVERIFY2(!view->isExpanded(root),
"clicking the expander again did not close the thread");
}
void TestMainWindow::replyRowsKeepTheirTextUnderTheThreadLine()
{
// paintEvent runs AFTER the cells, so anything it fills across a reply row
// covers the text the delegate just drew. The tint and the thread line are
// both painted there, which makes this the obvious way to ship a block of
// blank rows.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
ThreadSummary t = makeThread(
QStringLiteral("t1"),
QStringList{ TagColors::tagForAccountKey(QStringLiteral("work")) });
t.totalCount = 2;
model->appendBatch({ t });
MessageNode first;
first.messageId = QStringLiteral("m0@example.org");
first.threadId = QStringLiteral("t1");
first.depth = 0;
MessageNode reply;
reply.messageId = QStringLiteral("m1@example.org");
reply.threadId = QStringLiteral("t1");
reply.from = QStringLiteral("A Replier <replier@example.org>");
reply.subject = QStringLiteral("Re: a subject");
reply.depth = 1;
model->setThreadMessages(QStringLiteral("t1"), { first, reply });
window.resize(1400, 300);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
const QModelIndex root = model->index(0, 0, QModelIndex());
view->expand(root);
QApplication::processEvents();
const QModelIndex child =
model->index(0, 0, root);
const QRect rect = view->visualRect(child);
QVERIFY2(rect.height() > 0, "the reply row is not on screen");
QImage shot(view->viewport()->size(), QImage::Format_ARGB32);
shot.fill(Qt::transparent);
view->viewport()->render(&shot);
// Count pixels in the sender cell that differ from the row's own tint.
// Text is the only thing that can produce them.
const QRgb tint = ThreadListModel::replyBackground().rgb() | 0xff000000;
int textPixels = 0;
for (int y = rect.top(); y < qMin(rect.bottom(), shot.height()); ++y) {
for (int x = rect.left(); x < qMin(rect.right(), shot.width()); ++x) {
if ((shot.pixel(x, y) | 0xff000000) != tint)
++textPixels;
}
}
QVERIFY2(textPixels > 20,
qPrintable(QStringLiteral("only %1 non-background pixels in the "
"reply's sender cell: the row was "
"painted over after its text was drawn")
.arg(textPixels)));
}
void TestMainWindow::aSelectedReadThreadIsNotDimmedIntoTheHighlight()
{
// Read threads carry a dimmed Qt::ForegroundRole, blended against the
// UNSELECTED background. Qt's own painting prefers a model foreground over
// HighlightedText, so without SubjectDelegate::initStyleOption reversing
// that, selecting a read row paints it grey on the selection colour, which
// is close to unreadable. Seen in a screenshot before it was caught here.
//
// Rendered rather than asserted on roles: the model is right either way,
// and the defect lives entirely in how the delegate resolves them.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
// Both rows READ, so both are dimmed and neither is bold: the only thing
// that could differ is how the dimming composites against the selection.
//
// Comparing a read row against an unread one would not work, and an
// earlier version of this test did exactly that. Unread also paints bold,
// so the rows differ legitimately and the comparison says nothing about
// the selection. That version passed only because the machine it was
// written on had its Qt font configured Bold, which made every row bold
// and hid the difference.
ThreadSummary first = makeThread(QStringLiteral("t1"), {});
ThreadSummary second = makeThread(QStringLiteral("t2"), {});
first.subject = second.subject = QStringLiteral("Same subject both rows");
first.authors = second.authors = QStringLiteral("Someone <s@example.org>");
model->appendBatch({ first, second });
window.resize(900, 300);
window.show();
QVERIFY(QTest::qWaitForWindowExposed(&window));
// Row 0 selected, row 1 not. The property under test is that selecting a
// dimmed row switches it to the highlight's own text colour, so the two
// rows MUST differ; comparing two identically-styled rows would pass
// against a delegate that did nothing at all.
selectThreadRow(view, 0);
QApplication::processEvents();
const int rowHeight = threadRowHeight(view, 0);
QVERIFY(rowHeight > 0);
QImage shot(view->viewport()->size(), QImage::Format_ARGB32);
shot.fill(Qt::transparent);
view->viewport()->render(&shot);
// What the delegate resolves for each row, which is the thing the fix
// changes. Rendering alone cannot separate "used the highlight colour"
// from "used the dim over a highlighted background".
QStyleOptionViewItem selected;
selected.initFrom(view);
selected.state |= QStyle::State_Selected;
QStyleOptionViewItem unselected;
unselected.initFrom(view);
unselected.state &= ~QStyle::State_Selected;
auto *delegate = qobject_cast<QStyledItemDelegate *>(view->itemDelegate());
QVERIFY2(delegate, "the thread view has no styled delegate");
const QModelIndex index =
model->index(0, 0);
// initStyleOption is protected, so the resolved palette is reached the way
// the painter does: through a subclass that exposes it.
struct Probe : CardDelegate {
using CardDelegate::initStyleOption;
};
const auto *probe = static_cast<const Probe *>(
static_cast<const CardDelegate *>(delegate));
probe->initStyleOption(&selected, index);
probe->initStyleOption(&unselected, index);
QVERIFY2(selected.palette.color(QPalette::Text)
== selected.palette.color(QPalette::HighlightedText),
"a selected row still resolves to the dimmed text colour, so the "
"dimming will paint over the selection highlight");
QVERIFY2(unselected.palette.color(QPalette::Text)
!= selected.palette.color(QPalette::Text),
"an unselected read row lost its dimming");
}
void TestMainWindow::markAllReadIsDisabledUntilTheQueryFinishes()
{
// Threads arrive in batches, so acting mid-load would silently skip
// whatever had not arrived. Rather than acting on part of the view and
// calling it "all", or stalling on a wait the user cannot see, the action
// is simply unavailable until the result set is complete.
const Config config;
MainWindow window(config);
auto *action = window.findChild<QAction *>(QStringLiteral("mark_all_read"));
QVERIFY2(action, "no mark_all_read action registered");
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
// A query in flight: rows are arriving but the worker has not said it is
// done, so the action must stay out of reach.
// A query is needed for runCurrentQuery to do anything: it returns early
// on an empty one, which would leave the flag untouched.
window.findChild<QLineEdit *>()->setText(QStringLiteral("tag:inbox"));
QMetaObject::invokeMethod(&window, "runCurrentQuery");
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("unread") }) });
QVERIFY2(!action->isEnabled(),
"the action was live while the query was still loading");
// The generation must match or the reply is discarded as stale, which is
// how a superseded query is ignored everywhere else in this window.
const quint64 generation = window.currentGenerationForTesting();
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 1), Q_ARG(quint64, generation));
QVERIFY2(action->isEnabled(),
"the action stayed disabled after the query finished");
}
void TestMainWindow::markAllReadActsOnEveryRowAndUndoesInOneStep()
{
// Every row in the view, not just the selected ones, and one undo entry for
// the batch: a user who marks 400 threads read expects one Ctrl+Z to be
// enough.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *action = window.findChild<QAction *>(QStringLiteral("mark_all_read"));
QVERIFY(action);
// A query is needed for runCurrentQuery to do anything: it returns early
// on an empty one, which would leave the flag untouched.
window.findChild<QLineEdit *>()->setText(QStringLiteral("tag:inbox"));
QMetaObject::invokeMethod(&window, "runCurrentQuery");
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("unread") }),
makeThread(QStringLiteral("t2"),
{ QStringLiteral("unread") }),
makeThread(QStringLiteral("t3"),
{ QStringLiteral("unread"),
QStringLiteral("flagged") }) });
QMetaObject::invokeMethod(&window, "onQueryFinished", Q_ARG(int, 3),
Q_ARG(quint64,
window.currentGenerationForTesting()));
// One row selected, to prove the action ignores the selection rather than
// acting on it.
selectThreadRow(view, 0);
action->trigger();
for (int row = 0; row < 3; ++row) {
QVERIFY2(!model->threadAt(row).tags.contains(QStringLiteral("unread")),
qPrintable(QStringLiteral("row %1 kept its unread tag")
.arg(row)));
}
// An unrelated tag on a row is untouched: only unread is removed.
QVERIFY(model->threadAt(2).tags.contains(QStringLiteral("flagged")));
// ONE undo entry for the whole batch, not one per thread. Asserted as a
// depth, since triggering undo once and finding everything restored would
// also pass if three commands had been pushed and the model happened to
// recover on the first.
QCOMPARE(window.undoDepthForTesting(), 1);
auto *undo = window.findChild<QAction *>(QStringLiteral("undo"));
QVERIFY(undo);
undo->trigger();
for (int row = 0; row < 3; ++row) {
QVERIFY2(model->threadAt(row).tags.contains(QStringLiteral("unread")),
qPrintable(QStringLiteral("row %1 was not restored by one undo")
.arg(row)));
}
}
void TestMainWindow::markAllReadDoesNothingWhenNothingIsUnread()
{
// No write, no undo entry, and no pending edit for a view that is already
// read: an undo entry that restores nothing is worse than none, since it
// absorbs a Ctrl+Z the user meant for their previous action.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *action = window.findChild<QAction *>(QStringLiteral("mark_all_read"));
QVERIFY(action);
// A query is needed for runCurrentQuery to do anything: it returns early
// on an empty one, which would leave the flag untouched.
window.findChild<QLineEdit *>()->setText(QStringLiteral("tag:inbox"));
QMetaObject::invokeMethod(&window, "runCurrentQuery");
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("flagged") }),
makeThread(QStringLiteral("t2"), {}) });
QMetaObject::invokeMethod(&window, "onQueryFinished", Q_ARG(int, 2),
Q_ARG(quint64,
window.currentGenerationForTesting()));
QCOMPARE(window.undoDepthForTesting(), 0);
action->trigger();
// The real assertion: no command was pushed. Checking only that the tags
// did not change would pass against a version that sent a no-op write for
// every row, which still costs an undo entry and a pending edit each. The
// undo QAction cannot answer this: it is always enabled and tests canUndo()
// when triggered.
QVERIFY2(window.undoDepthForTesting() == 0,
"an undo entry was pushed for a view with nothing unread");
QVERIFY(model->threadAt(0).tags.contains(QStringLiteral("flagged")));
// And it says so rather than appearing to have done something.
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
QVERIFY2(status->text().contains(QStringLiteral("Nothing unread")),
qPrintable(status->text()));
}
void TestMainWindow::markReadTimerRestartsRatherThanStacking()
{
// The plan's hard requirement: arrowing quickly down a list must not mark
// every thread passed through as read, only the one still selected when the
// timer fires. A stacked timer per selection would mark all of them.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *timer = window.findChild<QTimer *>(QStringLiteral("markReadTimer"));
QVERIFY(timer);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("unread") }),
makeThread(QStringLiteral("t2"),
{ QStringLiteral("unread") }),
makeThread(QStringLiteral("t3"),
{ QStringLiteral("unread") }) });
selectThreadRow(view, 0);
QVERIFY2(timer->isActive(), "no timer armed for an unread thread");
// Move on before it can fire. One timer stays armed, not three.
selectThreadRow(view, 1);
QVERIFY(timer->isActive());
selectThreadRow(view, 2);
QVERIFY(timer->isActive());
// Exactly one timer exists at all, which is what "restarted, not stacked"
// means concretely.
QCOMPARE(window.findChildren<QTimer *>(QStringLiteral("markReadTimer")).size(),
1);
}
void TestMainWindow::markReadTimerIsNotArmedForAReadThread()
{
// Opening a thread that is already read must not schedule a write that
// would change nothing.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *timer = window.findChild<QTimer *>(QStringLiteral("markReadTimer"));
QVERIFY(timer);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
model->appendBatch({ makeThread(QStringLiteral("read"),
{ QStringLiteral("inbox") }),
makeThread(QStringLiteral("unread"),
{ QStringLiteral("unread") }) });
selectThreadRow(view, 0);
QVERIFY2(!timer->isActive(), "armed a timer for an already-read thread");
// And the unread one still arms, so this is not "never arms".
selectThreadRow(view, 1);
QVERIFY(timer->isActive());
// Moving back to a read thread disarms it again, rather than leaving the
// previous thread's timer running to fire against the wrong row.
selectThreadRow(view, 0);
QVERIFY(!timer->isActive());
}
void TestMainWindow::markReadCanBeDisabled()
{
// A negative delay turns the behaviour off entirely. Documented, so it must
// work rather than being clamped to "immediately".
QTemporaryDir dir;
const QString path = dir.filePath(QStringLiteral("qtmaildir.conf"));
{
QFile file(path);
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
file.write("[general]\nmark_read_delay_ms=-1\n");
}
Config config;
config.load(path);
QCOMPARE(config.markReadDelayMs(), -1);
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *timer = window.findChild<QTimer *>(QStringLiteral("markReadTimer"));
QVERIFY(timer);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("unread") }) });
selectThreadRow(view, 0);
QVERIFY2(!timer->isActive(),
"a negative mark_read_delay_ms must disable the timer");
}
void TestMainWindow::pendingEditCountSurvivesAQuery()
{
// The defining property, and the reason this is a counter of its own rather
// than QUndoStack::isClean(): the undo stack is cleared on every query,
// because its entries refer to rows the new result set discards. Tag a
// thread, run any query, and the stack is empty while the change is still
// sitting unsynced in the database.
const Config config;
MainWindow window(config);
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
QVERIFY2(label->isHidden(), "the indicator must start hidden at zero");
// Confirm a write the way the worker really does, by emitting the signal
// the window listens to. No test-only entry point on MainWindow.
TagChange change;
change.added = { QStringLiteral("deleted") };
change.description = QStringLiteral("Delete");
QVERIFY(QMetaObject::invokeMethod(&window, "onTagsApplied",
Q_ARG(TagChange, change)));
QVERIFY2(!label->isHidden(), "a confirmed edit must show the indicator");
const QString afterEdit = label->text();
QVERIFY(!afterEdit.isEmpty());
// Now run a query, which clears the undo stack. The indicator must not
// follow it down.
window.findChild<QLineEdit *>()->setText(QStringLiteral("tag:inbox"));
QMetaObject::invokeMethod(&window, "runCurrentQuery");
QVERIFY2(!label->isHidden(),
"the indicator was cleared by a query, so it is tracking the undo "
"stack rather than unsynced state");
QCOMPARE(label->text(), afterEdit);
}
void TestMainWindow::aFailedSyncDoesNotClearThePendingCount()
{
// A failed sync means the edits are still unsynced. Clearing here would
// assert the opposite, and the user would quit believing their tagging had
// been carried over.
const Config config;
MainWindow window(config);
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
TagChange change;
change.added = { QStringLiteral("flagged") };
QVERIFY(QMetaObject::invokeMethod(&window, "onTagsApplied",
Q_ARG(TagChange, change)));
QVERIFY(!label->isHidden());
const QString afterEdit = label->text();
QMetaObject::invokeMethod(&window, "onSyncFinished",
Q_ARG(bool, false), Q_ARG(int, 1));
QVERIFY2(!label->isHidden(), "a FAILED sync cleared the pending count");
QCOMPARE(label->text(), afterEdit);
// A successful one does clear it, so this is not "never clears".
QMetaObject::invokeMethod(&window, "onSyncFinished",
Q_ARG(bool, true), Q_ARG(int, 0));
QVERIFY2(label->isHidden(), "a successful sync must clear the indicator");
}
/// Closes a window and reports whether it accepted, failing rather than hanging
/// if a modal appears.
///
/// A modal spins its own event loop, so a test that simply sends a close event
/// blocks forever when a dialog it did not expect opens. This arms a timer that
/// closes any active modal and records that one was there, which turns "a
/// dialog appeared" into an assertion instead of a hung run.
struct CloseProbe
{
bool accepted = false;
bool sawModal = false;
void run(MainWindow *window)
{
QTimer poll;
poll.setInterval(50);
int ticks = 0;
QObject::connect(&poll, &QTimer::timeout, [this, &poll, &ticks]() {
if (QWidget *modal = QApplication::activeModalWidget()) {
sawModal = true;
modal->close();
poll.stop();
return;
}
if (++ticks > 20) // one second is ample for a synchronous close
poll.stop();
});
poll.start();
QCloseEvent event;
QApplication::sendEvent(window, &event);
accepted = event.isAccepted();
poll.stop();
}
};
void TestMainWindow::closingWithNoPendingEditsDoesNotPrompt()
{
// Nothing outstanding means nothing to ask about. If a prompt fires here it
// is keying off something other than there being work to lose, and every
// quit would carry a dialog.
const Config config;
MainWindow window(config);
CloseProbe probe;
probe.run(&window);
QVERIFY2(!probe.sawModal, "a clean window prompted on close");
QVERIFY2(probe.accepted, "a clean window refused to close");
}
void TestMainWindow::syncOnExitNeverClosesSilently()
{
// "never" is the behaviour that existed before the prompt did, and it has
// to stay reachable for anyone who does not want to be asked. It must hold
// whether or not a sync command is configured, so this covers both: the
// no-command path has its own dialog, and "never" must skip that one too.
QTemporaryDir dir;
const QString path = dir.filePath(QStringLiteral("qtmaildir.conf"));
{
QFile file(path);
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
file.write("[general]\nsync_on_exit=never\n\n[sync]\ncommand=/bin/true\n");
}
Config config;
config.load(path);
QCOMPARE(config.syncOnExit(), Config::SyncOnExit::Never);
MainWindow window(config);
// Give it something to lose, so this is not passing for the same reason
// the previous test does.
TagChange change;
change.added = { QStringLiteral("deleted") };
QVERIFY(QMetaObject::invokeMethod(&window, "onTagsApplied",
Q_ARG(TagChange, change)));
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
QVERIFY(!label->isHidden());
CloseProbe probe;
probe.run(&window);
QVERIFY2(!probe.sawModal,
"sync_on_exit=never prompted anyway");
QVERIFY2(probe.accepted,
"sync_on_exit=never must close without prompting");
}
void TestMainWindow::selectAllIsBoundAndSelectsEveryRow()
{
// Multi-select already worked by Ctrl+click and Shift+click; what was
// missing was a keyboard and menu route to it. The action has to exist as a
// registered action, not as a raw view shortcut, so it reaches the menu,
// the shortcut reference and [keys] like every other binding.
const Config config;
MainWindow window(config);
auto *action = window.findChild<QAction *>(QStringLiteral("select_all"));
QVERIFY2(action, "no select_all action registered");
QCOMPARE(action->shortcut(), QKeySequence(QStringLiteral("Ctrl+A")));
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
model->appendBatch({ makeThread(QStringLiteral("t1"), {}),
makeThread(QStringLiteral("t2"), {}),
makeThread(QStringLiteral("t3"), {}) });
action->trigger();
QCOMPARE(view->selectionModel()->selectedRows().size(), 3);
}
void TestMainWindow::aMultiRowSelectionDoesNotArmTheMarkReadTimer()
{
// A selection gesture must never mutate mail. current follows the keyboard
// cursor as a selection extends, so without a guard every row swept through
// by Shift+arrow would be queued to be marked read: threads the user only
// ever selected, never opened.
//
// Note selectAll() on a fresh view is NOT the case to test here: it leaves
// current invalid and emits no currentRowChanged at all (verified against
// Qt 6.11), so it would pass without any guard in place. The real path is a
// row already current, which is how a user reaches select-all: click a
// thread, then Ctrl+A.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *timer = window.findChild<QTimer *>(QStringLiteral("markReadTimer"));
QVERIFY(timer);
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("unread") }),
makeThread(QStringLiteral("t2"),
{ QStringLiteral("unread") }),
makeThread(QStringLiteral("t3"),
{ QStringLiteral("unread") }) });
// Sweep down as Shift+arrow does: current moves onto a row while the
// selection already spans more than one.
selectThreadRow(view, 0);
view->selectionModel()->select(
model->index(1, 0),
QItemSelectionModel::Select | QItemSelectionModel::Rows);
view->selectionModel()->setCurrentIndex(
model->index(1, 0),
QItemSelectionModel::Select | QItemSelectionModel::Rows);
QVERIFY2(view->selectionModel()->selectedRows().size() > 1,
"test setup failed to build a multi-row selection");
QVERIFY2(!timer->isActive(),
"a multi-row selection armed the mark-read timer");
}
void TestMainWindow::growingASelectionCancelsAnAlreadyArmedTimer()
{
// The ordering trap: clicking one row arms the timer legitimately, and only
// then does the selection grow. Guarding the new selection alone is not
// enough, the timer already running for the first row has to be cancelled
// or that thread goes read behind a pane that no longer shows it.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *timer = window.findChild<QTimer *>(QStringLiteral("markReadTimer"));
QVERIFY(timer);
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("unread") }),
makeThread(QStringLiteral("t2"),
{ QStringLiteral("unread") }) });
selectThreadRow(view, 0);
QVERIFY2(timer->isActive(), "no timer armed for a single unread thread");
// Extend to a second row, as Shift+click would.
view->selectionModel()->select(
model->index(1, 0),
QItemSelectionModel::Select | QItemSelectionModel::Rows);
QVERIFY2(!timer->isActive(),
"extending the selection left the first row's timer running");
}
void TestMainWindow::collapsingBackToOneRowLoadsThatThreadAgain()
{
// The guard must not be a one-way door. Narrowing a multi-row selection
// back to a single row is ordinary reading again, so the timer arms as it
// always did.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *timer = window.findChild<QTimer *>(QStringLiteral("markReadTimer"));
QVERIFY(timer);
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("unread") }),
makeThread(QStringLiteral("t2"),
{ QStringLiteral("unread") }) });
view->selectAll();
QVERIFY(!timer->isActive());
// Back to one row, as a plain click would leave it.
selectThreadRow(view, 1);
QVERIFY2(timer->isActive(),
"collapsing back to one row did not resume mark-read");
}
void TestMainWindow::theStatusBarReportsAMultiRowSelection()
{
// The actual discoverability gap: the UI never acknowledged a selection, so
// nothing taught the user that selecting more than one row was possible.
// A count that appears while the selection is being built does.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY2(status, "no status label to report into");
model->appendBatch({ makeThread(QStringLiteral("t1"), {}),
makeThread(QStringLiteral("t2"), {}),
makeThread(QStringLiteral("t3"), {}) });
view->selectAll();
QVERIFY2(status->text().contains(QStringLiteral("3")),
qPrintable(QStringLiteral("status bar does not report the selection "
"size, it says '%1'").arg(status->text())));
}
void TestMainWindow::clearSelectionBlanksThePaneAndDeselects()
{
// Item 50: the user asked for "two actions instead of one", so this is the
// new action and clearPaneLeavesTheSelectionAlone() below pins the old one.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
model->appendBatch({ makeThread(QStringLiteral("t1"), {}),
makeThread(QStringLiteral("t2"), {}) });
// From a row that is already current, which is both how a user reaches this
// and what CLAUDE.md requires: selectAll() on a fresh view emits no
// currentRowChanged at all, so a test starting there passes against a
// missing guard.
selectThreadRow(view, 0);
QCOMPARE(view->selectionModel()->selectedRows().size(), 1);
auto *action = window.findChild<QAction *>(QStringLiteral("clear_selection"));
QVERIFY2(action, "no clear_selection action");
action->trigger();
QVERIFY2(view->selectionModel()->selectedRows().isEmpty(),
"the row is still selected: this action's whole point is that it "
"deselects as well as blanking");
// The hazard: clearSelection() leaves currentIndex() VALID, so
// onSelectionChanged() takes its "one or fewer rows" branch, sees a current
// row whose id differs from the just-cleared m_currentThreadId, and calls
// onThreadSelected for it, which sets m_currentThreadId again and sends a
// loadThread. The pane would then repaint itself a moment later.
//
// **currentThreadId() is what detects that, not the pane.** This fixture
// has no worker, so loadThread never replies and nothing ever repaints;
// asserting showingPlaceholder() here passes whatever the code does, which
// CLAUDE.md records as the standing limit of test_mainwindow. What IS
// observable is the id the window set on its way to that request.
QVERIFY2(window.currentThreadId().isEmpty(),
qPrintable(QStringLiteral("a thread was re-adopted after the "
"selection was cleared: currentThreadId "
"is '%1', and a loadThread for it is "
"already in flight")
.arg(window.currentThreadId())));
// And current itself is gone, so no later collapse-to-one-row can reload
// it either.
QVERIFY2(!view->currentIndex().isValid(),
"currentIndex is still valid, so onSelectionChanged can reload "
"that row on the next selection change");
}
void TestMainWindow::clearPaneLeavesTheSelectionAlone()
{
// The pre-existing action keeps its behaviour. Item 32 built it to blank
// WITHOUT touching the selection, and a user who binds it is entitled to
// that; item 50 adds a second action rather than changing this one.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
model->appendBatch({ makeThread(QStringLiteral("t1"), {}),
makeThread(QStringLiteral("t2"), {}) });
selectThreadRow(view, 0);
QCOMPARE(view->selectionModel()->selectedRows().size(), 1);
auto *action = window.findChild<QAction *>(QStringLiteral("clear_pane"));
QVERIFY2(action, "no clear_pane action");
action->trigger();
QCOMPARE(view->selectionModel()->selectedRows().size(), 1);
}
void TestMainWindow::maildirOverviewShowsUnknownRatherThanZero()
{
// A field notmuch could not answer must not render as 0. "0 messages" says
// the Maildir is empty, which is a claim; the truth is that the count
// failed, and telling someone their mail is gone is the worst available
// way to report an unreadable index.
const Config config;
MainWindow window(config);
auto *action = window.findChild<QAction *>(QStringLiteral("maildirOverview"));
QVERIFY2(action, "no maildirOverview action");
action->trigger();
auto *counts = window.findChild<QLabel *>(QStringLiteral("maildirCounts"));
QVERIFY2(counts, "the overview dialog has no counts label");
// The worker never answers in this fixture, so drive the slot directly
// with the all-unknown stats a failed open produces.
QMetaObject::invokeMethod(
&window, "onDatabaseStatsReady", Qt::DirectConnection,
Q_ARG(DatabaseStats, DatabaseStats{}),
Q_ARG(quint64, window.statsGenerationForTesting()));
QVERIFY2(counts->text().contains(QStringLiteral("unknown")),
qPrintable(QStringLiteral("counts label says '%1'")
.arg(counts->text())));
QVERIFY2(!counts->text().contains(QStringLiteral(">0<")),
qPrintable(QStringLiteral("an unanswered count rendered as zero: "
"'%1'").arg(counts->text())));
// WA_DeleteOnClose, so closing is what frees it. Left open, each test
// leaks a window for the rest of the run.
counts->window()->close();
}
void TestMainWindow::maildirOverviewIgnoresAStaleReply()
{
// Counting every message is slow enough that closing and reopening the
// dialog while one runs is realistic. The older answer must not fill in the
// newer dialog, or the numbers silently predate whatever prompted the
// reopen.
const Config config;
MainWindow window(config);
auto *action = window.findChild<QAction *>(QStringLiteral("maildirOverview"));
QVERIFY(action);
action->trigger();
const quint64 stale = window.statsGenerationForTesting();
// Reopening bumps the generation, which is what makes the first reply old.
action->trigger();
QVERIFY2(window.statsGenerationForTesting() != stale,
"reopening the dialog did not bump the generation, so a reply for "
"the previous one cannot be told apart");
auto *counts = window.findChild<QLabel *>(QStringLiteral("maildirCounts"));
QVERIFY(counts);
const QString before = counts->text();
DatabaseStats old;
old.messages = 4321;
old.threads = 999;
old.tags = 42;
QMetaObject::invokeMethod(&window, "onDatabaseStatsReady",
Qt::DirectConnection,
Q_ARG(DatabaseStats, old),
Q_ARG(quint64, stale));
QCOMPARE(counts->text(), before);
QVERIFY2(!counts->text().contains(QStringLiteral("4321")),
"a reply for the previous dialog filled in the current one");
QPointer<QLabel> watch(counts);
counts->window()->close();
// WA_DeleteOnClose deletes through deleteLater, so the label outlives
// close() until the event loop runs. Drain it, or the "reply after the
// dialog is gone" case below is not actually being tested.
QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
QVERIFY2(watch.isNull(),
"the dialog was not destroyed, so the case below is not the one "
"this test means to exercise");
// The QPointer's reason for being: counting a large database takes long
// enough that closing the dialog first is ordinary, and the reply then
// arrives for a label that has been deleted. A raw pointer would dangle
// here, so this must not crash.
QMetaObject::invokeMethod(&window, "onDatabaseStatsReady",
Qt::DirectConnection,
Q_ARG(DatabaseStats, old),
Q_ARG(quint64,
window.statsGenerationForTesting()));
}
void TestMainWindow::theThreadListOffersAContextMenu()
{
// Right-click is the other half of discoverability: until now every tag
// action was keyboard-only, so the Ctrl+T dialog in particular could not be
// reached with the mouse at all.
const Config config;
MainWindow window(config);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
QCOMPARE(view->contextMenuPolicy(), Qt::CustomContextMenu);
// The menu must reuse the registered QActions rather than build parallel
// ones, or a [keys] rebinding would show the old shortcut here and the
// menu could drift out of step with what the keyboard really does.
auto *menu = window.findChild<QMenu *>(QStringLiteral("threadContextMenu"));
QVERIFY2(menu, "no thread-list context menu");
const QStringList expected = { QStringLiteral("archive"),
QStringLiteral("delete"),
QStringLiteral("spam"),
QStringLiteral("toggle_unread"),
QStringLiteral("edit_tags"),
QStringLiteral("flag") };
for (const QString &name : expected) {
QAction *action = window.findChild<QAction *>(name);
QVERIFY2(action, qPrintable(QStringLiteral("no action '%1'").arg(name)));
QVERIFY2(menu->actions().contains(action),
qPrintable(QStringLiteral("context menu is missing the "
"registered '%1' action").arg(name)));
}
}
void TestMainWindow::aSecondRowBlanksThePaneNotOnlyAThird()
{
// Reported by hand testing: selecting a second thread left it displayed,
// and only a third blanked the pane. The cause is that currentRowChanged is
// emitted before the selection model updates, so the Ctrl+click that makes
// the count two arrives at onThreadSelected still reporting one, which
// loads the thread; onSelectionChanged then blanks the pane, and the load,
// being queued to the worker, paints over the blank when it returns. By the
// third row m_currentThreadId is already cleared, so the late result is
// discarded and the blank survives, which is why the fault looked like an
// off-by-one in the threshold rather than a race.
//
// Two rows must behave exactly as three do.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *timer = window.findChild<QTimer *>(QStringLiteral("markReadTimer"));
QVERIFY(timer);
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("unread") }),
makeThread(QStringLiteral("t2"),
{ QStringLiteral("unread") }),
makeThread(QStringLiteral("t3"),
{ QStringLiteral("unread") }) });
// One row: ordinary reading, so a timer is armed and a thread is current.
selectThreadRow(view, 0);
QCOMPARE(view->selectionModel()->selectedRows().size(), 1);
QVERIFY(timer->isActive());
// Ctrl+click a second row. This is the exact gesture that failed: the
// selection becomes two while currentRowChanged still reports one.
view->selectionModel()->setCurrentIndex(
model->index(1, 0),
QItemSelectionModel::Select | QItemSelectionModel::Rows);
QCOMPARE(view->selectionModel()->selectedRows().size(), 2);
QVERIFY2(!timer->isActive(),
"two selected rows left the mark-read timer armed");
// A blanked pane is one with no current thread: anything still in flight
// for that id would repaint over it.
QVERIFY2(window.currentThreadId().isEmpty(),
qPrintable(QStringLiteral("two selected rows left thread '%1' "
"loaded in the pane")
.arg(window.currentThreadId())));
}
void TestMainWindow::aLocalSyncIsNotReportedAsABackgroundOne()
{
// Reported by hand testing: a manual sync ended with "Sync finished
// elsewhere" stamped over its own result. The monitor sees the lock the
// local run takes, and while the process lives isRunning() suppresses the
// message; but the process exits, and therefore isRunning() goes false,
// BEFORE the next poll notices the lock was released. That poll then
// reported a local sync as a background one.
//
// Ownership is latched when the lock appears, so the release can still be
// attributed after the process is gone.
const Config config;
MainWindow window(config);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
// The lock appears while no local sync is running: a background one.
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Running));
QVERIFY2(status->text().contains(QStringLiteral("Background")),
qPrintable(QStringLiteral("a background sync was not announced, "
"status says '%1'").arg(status->text())));
// The finish is no longer ANNOUNCED, since item 35b made the refresh
// silent, but it must still be acted on: the running message it wrote is
// retired. Asserting the absence of "running" rather than the presence of
// "completed" keeps the test on this window's subject, which is that the
// lock period was attributed to a background sync rather than to a local
// one, without pinning wording that has already changed once.
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
QVERIFY2(!status->text().contains(QStringLiteral("running")),
qPrintable(QStringLiteral("a finished background sync left the bar "
"claiming it was still running: '%1'")
.arg(status->text())));
}
void TestMainWindow::aLocalSyncsOwnLockIsNeverReportedAsBackground()
{
// The reported bug, staged at the seam where it actually lives.
//
// A real child process was tried first and abandoned: it needs a sync
// command in the config, it leaves a live process behind for the length of
// the test, and it made the suite pop a dialog. None of that is needed,
// because the defect is not in MailSync. It is that ownership of a lock
// period was decided at RELEASE time, when MailSync::isRunning() has
// already gone false, instead of being latched when the lock appeared.
//
// With no sync command configured isRunning() is false throughout, which is
// exactly the state the buggy code misread. So: announce a Running that the
// window believes is external, then a matching Idle. Both must be reported.
// The local case is covered by the latch being set only inside the Running
// branch, and by aSkippedLocalSyncStillReportsTheOtherRunFinishing()
// proving the latch is handed back when the lock was never ours.
const Config config;
MainWindow window(config);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
auto *progress =
window.findChild<QProgressBar *>(QStringLiteral("syncProgress"));
QVERIFY(progress);
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Running));
QVERIFY2(progress->isVisibleTo(&window),
"a background sync did not show the progress bar");
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
QVERIFY2(!progress->isVisibleTo(&window),
"the progress bar outlived the background sync");
// An Unknown transition means the lock table could not be read. Nothing was
// observed, so nothing may be claimed: the previous message must stand.
status->setText(QStringLiteral("untouched"));
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Unknown));
QCOMPARE(status->text(), QStringLiteral("untouched"));
}
void TestMainWindow::aSkippedLocalSyncStillReportsTheOtherRunFinishing()
{
// The narrow case the latch could break: a manual sync that exits 75
// because cron already holds the lock. If both started inside one poll
// interval the monitor sees the lock appear while isRunning() is true and
// latches it local, even though the lock belongs to the cron run. The
// completion of that run would then be swallowed. onSyncFinished() hands
// ownership back when it sees the skip code.
const Config config;
MainWindow window(config);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
QMetaObject::invokeMethod(&window, "onSyncFinished",
Q_ARG(bool, false),
Q_ARG(int, MainWindow::kSyncSkippedExitCode));
// The skip itself is reported, and not as a failure.
QVERIFY2(!status->text().contains(QStringLiteral("failed")),
qPrintable(QStringLiteral("a skip was reported as a failure: '%1'")
.arg(status->text())));
// The other run finishing must still be ACTED ON. What that means depends
// on the state of the list, and this fixture has an empty one with nothing
// selected, so item 35a's free-refresh branch is what a handed-back lock
// reaches: the window re-runs the query rather than printing "press Enter".
//
// Asserting the generation rather than the status text is deliberate. The
// property under test is that the Idle was attributed to the OTHER run
// instead of being swallowed as this window's own; which of the two
// responses it then produces is item 35a's business, and pinning the
// wording here would fail every time that decision is revisited.
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
queryEdit->setText(QStringLiteral("tag:inbox"));
queryEdit->returnPressed();
const quint64 before = window.currentGenerationForTesting();
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
QVERIFY2(window.currentGenerationForTesting() > before,
"after a skipped local sync, the other run finishing was "
"swallowed rather than attributed to the background sync");
}
void TestMainWindow::aCronSyncRefreshesTheListWithoutAQuery()
{
// Item 35b. A background sync brings the list up to date on its own, with
// no keystroke: this is the whole point of the item, and it holds whether
// the list is empty or full.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
// The refresh is observed as a NEW query being issued. There is no worker
// in this fixture, so no result ever arrives; what is asserted is that the
// query went out at all, which is what used to be missing.
const quint64 before = window.currentGenerationForTesting();
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
QVERIFY2(window.currentGenerationForTesting() > before,
"a finished cron sync did not refresh the list");
}
void TestMainWindow::aCronSyncRefreshesOverASelectionWithoutClearingIt()
{
// The behaviour 0.8.0 refused to build and the reason it refused: a refresh
// used to mean runCurrentQuery(), which clears the model, the selection and
// the message pane, so firing it on a cron timer would close the thread
// being read six times an hour.
//
// refreshCurrentQuery() reconciles instead, so the refresh runs AND the
// selection survives. A test that only checked the query was issued would
// pass against the destructive version, which is the version this item
// exists to avoid.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
model->appendBatch({ makeThread(QStringLiteral("T1"),
{ QStringLiteral("unread") }) });
const QModelIndex first = model->index(0, 0, QModelIndex());
QVERIFY(first.isValid());
view->setCurrentIndex(first);
QVERIFY2(view->selectionModel()->hasSelection(),
"the fixture failed to select a row, so this proves nothing");
const quint64 before = window.currentGenerationForTesting();
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
QVERIFY2(window.currentGenerationForTesting() > before,
"a cron sync did not refresh a populated list");
// The rows are untouched until the result comes back, and the selection is
// still there. A clear() would have emptied both.
QCOMPARE(model->rowCount(QModelIndex()), 1);
QVERIFY2(view->selectionModel()->hasSelection(),
"the refresh cleared the selection, which is what made the old "
"one unusable on a cron timer");
}
void TestMainWindow::aCronSyncDoesNotRefreshBeforeAnyQueryHasRun()
{
// The query bar holds text the user has typed but not run, and a refresh
// must not execute it: that is a search they never asked for. The refresh
// re-runs the LAST RUN query, so with none there is nothing to do.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
queryEdit->setText(QStringLiteral("tag:draft-i-was-typing"));
const quint64 before = window.currentGenerationForTesting();
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
QCOMPARE(window.currentGenerationForTesting(), before);
}
void TestMainWindow::aRefreshAddsNewMailAndDropsWhatStoppedMatching()
{
// The round trip end to end, driven through the real handlers: the refresh
// query goes out, its batches accumulate, and the result reconciles into
// the model in one go.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
model->appendBatch({ makeThread(QStringLiteral("T1"),
{ QStringLiteral("unread") }),
makeThread(QStringLiteral("T2"),
{ QStringLiteral("unread") }) });
QCOMPARE(model->rowCount(QModelIndex()), 2);
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
const quint64 refresh = window.currentGenerationForTesting();
// T2 was read elsewhere and no longer matches; T3 is new mail.
const QVector<ThreadSummary> result{
makeThread(QStringLiteral("T3"), { QStringLiteral("unread") }),
makeThread(QStringLiteral("T1"), { QStringLiteral("unread") })
};
QMetaObject::invokeMethod(&window, "onThreadsReady",
Q_ARG(QVector<ThreadSummary>, result),
Q_ARG(quint64, refresh));
// Nothing has changed yet: a refresh applies its result whole, never batch
// by batch, or the first batch would delete every row after it.
QCOMPARE(model->rowCount(QModelIndex()), 2);
QCOMPARE(model->threadAt(0).threadId, QStringLiteral("T1"));
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 2), Q_ARG(quint64, refresh));
QCOMPARE(model->rowCount(QModelIndex()), 2);
QCOMPARE(model->threadAt(0).threadId, QStringLiteral("T3"));
QCOMPARE(model->threadAt(1).threadId, QStringLiteral("T1"));
}
void TestMainWindow::theOpenThreadLeavingTheListRaisesTheStaleNotice()
{
// The user is reading a thread when a refresh drops it: read the last
// unread message and the thread stops matching tag:unread. The pane keeps
// rendering it, correctly, so without a notice the message becomes an
// orphan with no route back to its thread.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
auto *pane = window.findChild<MessageView *>();
QVERIFY(pane);
model->appendBatch({ makeThread(QStringLiteral("T1"),
{ QStringLiteral("unread") }) });
view->setCurrentIndex(model->index(0, 0, QModelIndex()));
QCOMPARE(window.currentThreadId(), QStringLiteral("T1"));
QVERIFY(pane->staleThreadId().isEmpty());
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
const quint64 refresh = window.currentGenerationForTesting();
// The refresh comes back empty: the thread was read and is gone.
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 0), Q_ARG(quint64, refresh));
QCOMPARE(model->rowCount(QModelIndex()), 0);
QCOMPARE(pane->staleThreadId(), QStringLiteral("T1"));
}
void TestMainWindow::aThreadStillMatchingRaisesNoStaleNotice()
{
// The common case, and the guard on the test above: a refresh that changes
// nothing must be invisible. A notice on every sync would be noise, and it
// would be a lie.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
auto *pane = window.findChild<MessageView *>();
QVERIFY(pane);
model->appendBatch({ makeThread(QStringLiteral("T1"),
{ QStringLiteral("unread") }) });
view->setCurrentIndex(model->index(0, 0, QModelIndex()));
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
const quint64 refresh = window.currentGenerationForTesting();
const QVector<ThreadSummary> result{
makeThread(QStringLiteral("T1"), { QStringLiteral("unread") })
};
QMetaObject::invokeMethod(&window, "onThreadsReady",
Q_ARG(QVector<ThreadSummary>, result),
Q_ARG(quint64, refresh));
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 1), Q_ARG(quint64, refresh));
QCOMPARE(model->rowCount(QModelIndex()), 1);
QVERIFY2(pane->staleThreadId().isEmpty(),
"a thread that still matches was reported as stale");
}
void TestMainWindow::theStaleNoticeCarriesTheMessageBeingRead()
{
// Reading reply four of eight when the thread drops out. Recovery has to
// restore the READER'S place, so the notice carries the message id as well
// as the thread; without it the thread reopens at its first message.
//
// Selecting a message row clears m_currentThreadId, so a notice keyed on
// that alone never fires for exactly the reader who is deepest into a
// thread. That is the case this pins.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
auto *pane = window.findChild<MessageView *>();
QVERIFY(pane);
ThreadSummary thread = makeThread(QStringLiteral("T1"),
{ QStringLiteral("unread") });
thread.totalCount = 3;
model->appendBatch({ thread });
MessageNode root;
root.messageId = QStringLiteral("m0@example.org");
root.threadId = QStringLiteral("T1");
root.depth = 0;
MessageNode reply;
reply.messageId = QStringLiteral("m1@example.org");
reply.threadId = QStringLiteral("T1");
reply.depth = 1;
model->setThreadMessages(QStringLiteral("T1"), { root, reply });
const QModelIndex threadIndex = model->index(0, 0, QModelIndex());
const QModelIndex replyIndex = model->index(0, 0, threadIndex);
QVERIFY(replyIndex.isValid());
view->setCurrentIndex(replyIndex);
// A message row, so the window is tracking a message rather than a thread.
QVERIFY2(window.currentThreadId().isEmpty(),
"the fixture selected a thread row, so this proves nothing");
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
const quint64 refresh = window.currentGenerationForTesting();
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 0), Q_ARG(quint64, refresh));
QCOMPARE(pane->staleThreadId(), QStringLiteral("T1"));
QCOMPARE(pane->staleMessageId(), QStringLiteral("m1@example.org"));
}
void TestMainWindow::recoveringAStaleThreadQueriesTheWholeThread()
{
// Clicking "Show it anyway" runs thread:<id>, not a query for the single
// message: the user asked to get the whole conversation back, with their
// place in it, so the list has to offer every message of it.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
QMetaObject::invokeMethod(&window, "recoverStaleThread",
Q_ARG(QString, QStringLiteral("T1")),
Q_ARG(QString, QStringLiteral("m1@example.org")));
QCOMPARE(queryEdit->text(), QStringLiteral("thread:T1"));
}
void TestMainWindow::recoveryReselectsTheMessageThatWasBeingRead()
{
// The whole point of carrying the message id: reading reply four of eight,
// the thread comes back, and the selection lands on reply four rather than
// at the top of the thread.
//
// Driven through the real handlers because that is the only way the
// sequencing is exercised: the query has to come back before the thread
// can be expanded, and the expansion before the reply row exists at all.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
QMetaObject::invokeMethod(&window, "recoverStaleThread",
Q_ARG(QString, QStringLiteral("T1")),
Q_ARG(QString, QStringLiteral("m2@example.org")));
const quint64 generation = window.currentGenerationForTesting();
ThreadSummary thread = makeThread(QStringLiteral("T1"), {});
thread.totalCount = 3;
const QVector<ThreadSummary> result{ thread };
QMetaObject::invokeMethod(&window, "onThreadsReady",
Q_ARG(QVector<ThreadSummary>, result),
Q_ARG(quint64, generation));
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 1), Q_ARG(quint64, generation));
// The thread is listed, and nothing can be selected inside it yet: its
// replies are not loaded, so the recovery is still pending.
QCOMPARE(model->rowCount(QModelIndex()), 1);
MessageNode root;
root.messageId = QStringLiteral("m0@example.org");
root.threadId = QStringLiteral("T1");
root.depth = 0;
MessageNode first;
first.messageId = QStringLiteral("m1@example.org");
first.threadId = QStringLiteral("T1");
first.depth = 1;
MessageNode target;
target.messageId = QStringLiteral("m2@example.org");
target.threadId = QStringLiteral("T1");
target.depth = 1;
const QVector<MessageNode> nodes{ root, first, target };
QMetaObject::invokeMethod(&window, "onThreadTreeLoaded",
Q_ARG(QVector<MessageNode>, nodes),
Q_ARG(quint64, generation));
const QModelIndex current = view->currentIndex();
QVERIFY2(current.isValid(), "recovery selected nothing");
QVERIFY2(model->isMessageRow(current),
"recovery landed on the thread rather than on the message");
QCOMPARE(model->messageAt(current).messageId,
QStringLiteral("m2@example.org"));
}
void TestMainWindow::recoveryOnTheFirstMessageSelectsTheThreadRow()
{
// The trap in the model: setThreadMessages DROPS the depth-0 message,
// because the root card is that message. So a reader recovering from the
// thread's first message must land on the ROOT row; looking for it among
// the children finds nothing and would leave the selection nowhere.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
QMetaObject::invokeMethod(&window, "recoverStaleThread",
Q_ARG(QString, QStringLiteral("T1")),
Q_ARG(QString, QStringLiteral("m0@example.org")));
const quint64 generation = window.currentGenerationForTesting();
ThreadSummary thread = makeThread(QStringLiteral("T1"), {});
thread.totalCount = 2;
const QVector<ThreadSummary> result{ thread };
QMetaObject::invokeMethod(&window, "onThreadsReady",
Q_ARG(QVector<ThreadSummary>, result),
Q_ARG(quint64, generation));
MessageNode root;
root.messageId = QStringLiteral("m0@example.org");
root.threadId = QStringLiteral("T1");
root.depth = 0;
MessageNode reply;
reply.messageId = QStringLiteral("m1@example.org");
reply.threadId = QStringLiteral("T1");
reply.depth = 1;
const QVector<MessageNode> nodes{ root, reply };
QMetaObject::invokeMethod(&window, "onThreadTreeLoaded",
Q_ARG(QVector<MessageNode>, nodes),
Q_ARG(quint64, generation));
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 1), Q_ARG(quint64, generation));
const QModelIndex current = view->currentIndex();
QVERIFY2(current.isValid(), "recovery selected nothing");
QVERIFY2(!model->isMessageRow(current),
"the thread's first message is the ROOT row, not a child");
QCOMPARE(model->threadAt(current.row()).threadId, QStringLiteral("T1"));
}
void TestMainWindow::aUserQueryAbandonsAPendingRecovery()
{
// A recovery spans two round-trips, so the user can type a query in the
// middle of one. That is them choosing to go somewhere else, and the
// pending selection must not follow them there: restoring a thread's
// message into a result the user asked for something else from would yank
// the view out from under them.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
// Recovering the thread with NO message pinned, so the pending recovery
// selects its thread row the moment that thread appears. A recovery
// waiting on a specific reply would pass this test without the guard,
// simply by never reaching its target: it would sit expanding a thread
// whose replies this fixture never delivers.
QMetaObject::invokeMethod(&window, "recoverStaleThread",
Q_ARG(QString, QStringLiteral("T1")),
Q_ARG(QString, QString()));
// The user changes their mind before the recovery's query comes back.
queryEdit->setText(QStringLiteral("tag:flagged"));
queryEdit->returnPressed();
const quint64 generation = window.currentGenerationForTesting();
// That query happens to contain the same thread, which is what makes this
// a trap rather than a theoretical case: the recovery would find its
// target and select it.
ThreadSummary thread = makeThread(QStringLiteral("T1"), {});
thread.totalCount = 2;
const QVector<ThreadSummary> result{
makeThread(QStringLiteral("T9"), {}), thread
};
QMetaObject::invokeMethod(&window, "onThreadsReady",
Q_ARG(QVector<ThreadSummary>, result),
Q_ARG(quint64, generation));
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 2), Q_ARG(quint64, generation));
QVERIFY2(!view->currentIndex().isValid(),
"an abandoned recovery selected a row in the query the user ran "
"instead");
}
void TestMainWindow::blankingThePaneAlsoDropsTheStaleNotice()
{
// Reported by the user against the first build of item 35b. The notice
// outlived the message it describes: blanking the pane left the bar sitting
// above an empty pane, still naming a thread that was no longer shown, with
// a button offering to recover it.
//
// The bar belongs to the rendered message, exactly as the remote-content
// bar does, and MessageView::clear() already hides that one. This is the
// same rule applied to the same place.
const Config config;
MainWindow window(config);
auto *pane = window.findChild<MessageView *>();
QVERIFY(pane);
pane->setStaleThread(QStringLiteral("T1"),
QStringLiteral("m1@example.org"));
QCOMPARE(pane->staleThreadId(), QStringLiteral("T1"));
pane->clear();
QVERIFY2(pane->staleThreadId().isEmpty(),
"the stale notice survived the pane being blanked, so it names a "
"message that is no longer displayed");
QVERIFY2(pane->staleMessageId().isEmpty(),
"the stale notice kept the message id of a cleared pane");
}
void TestMainWindow::aNewQueryDropsTheStaleNotice()
{
// The user's actual route to the bug: read a thread out of a view, get the
// notice, then type a new query. The pane blanks and the bar must go with
// it. Driven through the window rather than through MessageView::clear()
// directly, because the defect was that nothing on this path called it.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
auto *pane = window.findChild<MessageView *>();
QVERIFY(pane);
queryEdit->setText(QStringLiteral("tag:inbox"));
queryEdit->returnPressed();
model->appendBatch({ makeThread(QStringLiteral("T1"),
{ QStringLiteral("unread") }) });
view->setCurrentIndex(model->index(0, 0, QModelIndex()));
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
const quint64 refresh = window.currentGenerationForTesting();
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 0), Q_ARG(quint64, refresh));
QCOMPARE(pane->staleThreadId(), QStringLiteral("T1"));
// The user runs a different query.
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
QVERIFY2(pane->staleThreadId().isEmpty(),
"after a new query the notice still offered to recover the thread "
"from the previous view");
}
void TestMainWindow::aFinishedBackgroundSyncStopsSayingItIsRunning()
{
// Reported by the user against item 35b. "Background sync running..." is
// written straight to the status label when the lock appears, and the
// "Background sync completed" message on the way out was the only thing
// that ever replaced it. Removing that message, so a refresh could be
// silent, left the bar claiming a sync was running long after it finished.
//
// Silent means "says nothing NEW", not "leaves a stale claim standing".
const Config config;
MainWindow window(config);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Running));
QVERIFY2(status->text().contains(QStringLiteral("running")),
qPrintable(QStringLiteral("the fixture never announced a running "
"sync, status says '%1'")
.arg(status->text())));
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
QVERIFY2(!status->text().contains(QStringLiteral("running")),
qPrintable(QStringLiteral("the status bar still claims a sync is "
"running after it finished: '%1'")
.arg(status->text())));
}
void TestMainWindow::aRefreshDoesNotStampOverASelectionMessage()
{
// The other half, and the reason this is not simply "always write the
// thread count". A refresh runs on a cron timer under a user who may be
// doing something, and the bar carries their selection count while they
// are. Overwriting that every ten minutes is the noise the silence rule
// exists to prevent.
const Config config;
MainWindow window(config);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
queryEdit->setText(QStringLiteral("tag:inbox"));
queryEdit->returnPressed();
model->appendBatch({ makeThread(QStringLiteral("T1"), {}),
makeThread(QStringLiteral("T2"), {}) });
view->setCurrentIndex(model->index(0, 0, QModelIndex()));
view->selectionModel()->select(model->index(1, 0, QModelIndex()),
QItemSelectionModel::Select);
const QString before = status->text();
QVERIFY2(!before.isEmpty(),
"the fixture left the status bar empty, so this proves nothing");
// A refresh completes with no sync ever having been announced.
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
const quint64 refresh = window.currentGenerationForTesting();
const QVector<ThreadSummary> result{
makeThread(QStringLiteral("T1"), {}), makeThread(QStringLiteral("T2"), {})
};
QMetaObject::invokeMethod(&window, "onThreadsReady",
Q_ARG(QVector<ThreadSummary>, result),
Q_ARG(quint64, refresh));
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 2), Q_ARG(quint64, refresh));
QCOMPARE(status->text(), before);
}
void TestMainWindow::aRefreshDoesNotOpenNewMailByItself()
{
// Reported by the user against item 35b. A thread read to the end empties
// an Unread view; the refresh then brings in one new message, and it opens
// ITSELF in the message pane, marking it read two seconds later without
// the user ever having looked at it.
//
// Nothing in MainWindow selects it: QTreeView sets a current index of its
// own when rows are inserted into a model that had none, and selecting a
// row is what loads it. An automatic refresh must not do that, or a cron
// timer decides what the user is reading.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
// The view has been read empty: no rows, nothing current.
QCOMPARE(model->rowCount(QModelIndex()), 0);
QVERIFY(!view->currentIndex().isValid());
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
const quint64 refresh = window.currentGenerationForTesting();
const QVector<ThreadSummary> result{
makeThread(QStringLiteral("NEW"), { QStringLiteral("unread") })
};
QMetaObject::invokeMethod(&window, "onThreadsReady",
Q_ARG(QVector<ThreadSummary>, result),
Q_ARG(quint64, refresh));
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 1), Q_ARG(quint64, refresh));
QCOMPARE(model->rowCount(QModelIndex()), 1);
// Insertion alone does not do it, which is why the bug only showed up when
// the user came back from another desktop: QTreeView gives itself a current
// index when it takes FOCUS with none set. Reproduced here rather than
// asserted from the report, since a test that only inserts rows passes
// against the defect.
view->setFocus();
QApplication::sendEvent(view, new QFocusEvent(QEvent::FocusIn));
QVERIFY2(window.currentThreadId().isEmpty(),
"the refresh opened the new mail in the message pane, which marks "
"it read without the user having looked at it");
}
void TestMainWindow::openingAnotherMessageDropsTheStaleNoticeOfThePreviousOne()
{
// The other half of the user's report: the pane showed the new message
// while the notice above it still named the thread they had been reading.
//
// The notice itself was right at the moment it was raised. What made it a
// lie was the pane being replaced underneath it, so this pins the rule that
// the notice belongs to whatever is currently rendered: selecting anything
// else retires it, exactly as blanking the pane does.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
auto *pane = window.findChild<MessageView *>();
QVERIFY(pane);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
model->appendBatch({ makeThread(QStringLiteral("OLD"),
{ QStringLiteral("unread") }) });
view->setCurrentIndex(model->index(0, 0, QModelIndex()));
// The refresh drops the thread being read and brings in new mail.
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
const quint64 refresh = window.currentGenerationForTesting();
const QVector<ThreadSummary> result{
makeThread(QStringLiteral("NEW"), { QStringLiteral("unread") })
};
QMetaObject::invokeMethod(&window, "onThreadsReady",
Q_ARG(QVector<ThreadSummary>, result),
Q_ARG(quint64, refresh));
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 1), Q_ARG(quint64, refresh));
QCOMPARE(pane->staleThreadId(), QStringLiteral("OLD"));
// The user chooses to open the new mail themselves.
const QModelIndex fresh = model->index(0, 0, QModelIndex());
QVERIFY(fresh.isValid());
QCOMPARE(model->threadAt(0).threadId, QStringLiteral("NEW"));
view->setCurrentIndex(fresh);
view->selectionModel()->select(fresh, QItemSelectionModel::Select);
QVERIFY2(pane->staleThreadId().isEmpty(),
"the notice still named the previous thread while the pane showed "
"a different message");
}
void TestMainWindow::theStaleNoticeKeepsTheMessageOfAThreadRootToo()
{
// Reported by the user: recovering a thread they were reading brought the
// thread back collapsed, with the pane blank, instead of reopening the
// message they had been on.
//
// The cause is that a thread ROOT sets both ids. The root card IS the
// thread's first message and the pane renders exactly that message, so
// m_currentThreadId and m_currentMessageId are both filled; the notice read
// the message id only when the thread id was EMPTY, so the root case threw
// away a message id it had. Recovery then had nothing to restore, landed on
// the thread row and never expanded it.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
auto *pane = window.findChild<MessageView *>();
QVERIFY(pane);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
ThreadSummary thread = makeThread(QStringLiteral("T1"),
{ QStringLiteral("unread") });
thread.totalCount = 4;
model->appendBatch({ thread });
// The root knows its own message once the tree is loaded, which is what
// makes the pane show one message rather than the conversation.
MessageNode root;
root.messageId = QStringLiteral("m0@example.org");
root.threadId = QStringLiteral("T1");
root.depth = 0;
MessageNode reply;
reply.messageId = QStringLiteral("m1@example.org");
reply.threadId = QStringLiteral("T1");
reply.depth = 1;
model->setThreadMessages(QStringLiteral("T1"), { root, reply });
const QModelIndex threadIndex = model->index(0, 0, QModelIndex());
view->setCurrentIndex(threadIndex);
view->selectionModel()->select(threadIndex, QItemSelectionModel::Select);
QCOMPARE(window.currentThreadId(), QStringLiteral("T1"));
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
const quint64 refresh = window.currentGenerationForTesting();
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 0), Q_ARG(quint64, refresh));
QCOMPARE(pane->staleThreadId(), QStringLiteral("T1"));
QVERIFY2(!pane->staleMessageId().isEmpty(),
"the notice dropped the message of a thread root, so recovery has "
"nothing to reopen and lands on a collapsed thread");
QCOMPARE(pane->staleMessageId(), QStringLiteral("m0@example.org"));
}
void TestMainWindow::recoveryExpandsTheThreadAndSelectsRatherThanOnlyPointing()
{
// The rest of the same report: recovery brought the thread back COLLAPSED
// with the pane BLANK. Two separate faults behind one symptom.
//
// setCurrentIndex() alone sets a current row without selecting it, and
// since the fix for the auto-open defect onThreadSelected() ignores exactly
// that: an unselected current index is Qt's housekeeping, not the user. So
// recovery pointed at the row and nothing rendered.
//
// And nothing expanded the thread, so the reply the user had been reading
// was not on screen even when it was the target.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
// Recovering onto the thread's FIRST message, which is the root card: the
// case the user hit by opening a thread rather than a reply.
QMetaObject::invokeMethod(&window, "recoverStaleThread",
Q_ARG(QString, QStringLiteral("T1")),
Q_ARG(QString, QStringLiteral("m0@example.org")));
const quint64 generation = window.currentGenerationForTesting();
ThreadSummary thread = makeThread(QStringLiteral("T1"), {});
thread.totalCount = 4;
const QVector<ThreadSummary> result{ thread };
QMetaObject::invokeMethod(&window, "onThreadsReady",
Q_ARG(QVector<ThreadSummary>, result),
Q_ARG(quint64, generation));
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 1), Q_ARG(quint64, generation));
// No tree reply. This is the user's actual case and the one the earlier
// test missed: the thread comes back from the query with its replies NOT
// yet loaded, which is the normal state of a freshly queried row. Recovery
// has to ask for them rather than assuming they are already there.
const QModelIndex threadIndex = model->index(0, 0, QModelIndex());
QVERIFY(threadIndex.isValid());
QCOMPARE(model->rowCount(threadIndex), 0);
QVERIFY2(view->selectionModel()->hasSelection(),
"recovery pointed at the row without selecting it, so nothing "
"renders and the pane stays blank");
QCOMPARE(window.currentThreadId(), QStringLiteral("T1"));
QVERIFY2(view->isExpanded(threadIndex),
"recovery brought the thread back collapsed, so the conversation "
"the user was reading is not on screen");
}
void TestMainWindow::recoveryFromAnExpandedThreadRestoresTheReply()
{
// The user's case, staged exactly: a thread ALREADY EXPANDED with the
// fourth reply selected and rendered, dropped by a refresh, then recovered.
// Reported twice as still broken while the earlier recovery tests passed,
// which means those tests were not reproducing it.
//
// What they missed is the whole round trip. Recovery re-runs thread:<id>,
// and that query REPLACES the model contents, so the recovered thread
// arrives collapsed with no replies loaded whatever state the old row was
// in. The reply the user wants therefore does not exist as a row at the
// moment recovery first runs, and the only thing that can create it is the
// tree reply arriving after an expand.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<ThreadListView *>();
QVERIFY(view);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
// Reading reply 4 of a 4-message thread, expanded.
ThreadSummary thread = makeThread(QStringLiteral("T1"),
{ QStringLiteral("unread") });
thread.totalCount = 4;
model->appendBatch({ thread });
QVector<MessageNode> nodes;
for (int i = 0; i < 4; ++i) {
MessageNode n;
n.messageId = QStringLiteral("m%1@example.org").arg(i);
n.threadId = QStringLiteral("T1");
n.depth = i == 0 ? 0 : 1;
nodes.append(n);
}
model->setThreadMessages(QStringLiteral("T1"), nodes);
const QModelIndex threadIndex = model->index(0, 0, QModelIndex());
view->expand(threadIndex);
QCOMPARE(model->rowCount(threadIndex), 3);
const QModelIndex fourth = model->index(2, 0, threadIndex);
QVERIFY(fourth.isValid());
QCOMPARE(model->messageAt(fourth).messageId,
QStringLiteral("m3@example.org"));
view->setCurrentIndex(fourth);
view->selectionModel()->select(fourth, QItemSelectionModel::Select);
// The refresh drops it, and the user follows the notice.
QMetaObject::invokeMethod(&window, "recoverStaleThread",
Q_ARG(QString, QStringLiteral("T1")),
Q_ARG(QString, QStringLiteral("m3@example.org")));
const quint64 generation = window.currentGenerationForTesting();
// The recovery query comes back: ONE collapsed thread, no replies. This is
// what the query really returns, and the state the earlier tests skipped.
const QVector<ThreadSummary> recovered{ thread };
QMetaObject::invokeMethod(&window, "onThreadsReady",
Q_ARG(QVector<ThreadSummary>, recovered),
Q_ARG(quint64, generation));
QMetaObject::invokeMethod(&window, "onQueryFinished",
Q_ARG(int, 1), Q_ARG(quint64, generation));
const QModelIndex back = model->index(0, 0, QModelIndex());
QVERIFY(back.isValid());
QVERIFY2(view->isExpanded(back),
"the recovered thread came back collapsed");
// Expanding asks the worker for the tree; that reply is what creates the
// reply rows. Without it the conversation is not on screen at all.
QMetaObject::invokeMethod(&window, "onThreadTreeLoaded",
Q_ARG(QVector<MessageNode>, nodes),
Q_ARG(quint64, generation));
QVERIFY2(view->isExpanded(back),
"the thread collapsed again once its replies arrived");
QCOMPARE(model->rowCount(back), 3);
const QModelIndex current = view->currentIndex();
QVERIFY2(current.isValid(), "recovery left nothing selected");
QVERIFY2(model->isMessageRow(current),
"recovery landed on the thread rather than on the reply the user "
"was reading");
QCOMPARE(model->messageAt(current).messageId,
QStringLiteral("m3@example.org"));
}
void TestMainWindow::theRecoveryButtonSurvivesThePaneBeingBlanked()
{
// The defect that survived six wrong diagnoses and every other recovery
// test in this file, because all of them reach the slot through
// invokeMethod, which COPIES its arguments.
//
// MessageView emitted the signal with its own members, so a direct
// connection handed MainWindow::recoverStaleThread() references to them.
// That slot calls runCurrentQuery(), which blanks the pane, which calls
// setStaleThread() and assigns to those very members. The ids the slot was
// still holding went empty mid-call, the recovery target was stored as an
// empty string, and nothing was ever recovered: the thread came back
// collapsed with the pane blank.
//
// Driven through the real button so the real signal runs. A test that
// calls the slot directly cannot see this and will pass against it.
const Config config;
MainWindow window(config);
auto *queryEdit = window.findChild<QLineEdit *>();
QVERIFY(queryEdit);
auto *pane = window.findChild<MessageView *>();
QVERIFY(pane);
auto *button =
pane->findChild<QPushButton *>(QStringLiteral("staleThreadButton"));
QVERIFY(button);
queryEdit->setText(QStringLiteral("tag:unread"));
queryEdit->returnPressed();
pane->setStaleThread(QStringLiteral("T1"),
QStringLiteral("m3@example.org"));
QCOMPARE(pane->staleThreadId(), QStringLiteral("T1"));
button->click();
// The query the button ran is the thread's own, which is only true if the
// id survived the round trip.
QCOMPARE(queryEdit->text(), QStringLiteral("thread:T1"));
// And the target is still pending, waiting for the result. Empty here means
// the reference was clobbered and the recovery is already dead.
QVERIFY2(window.hasPendingRecoveryForTesting(),
"the recovery target was lost during the slot, so the thread will "
"come back collapsed with a blank pane");
}
void TestMainWindow::theSyncActionIsDisabledWhileABackgroundSyncHoldsTheLock()
{
// Item 29 shipped for the QPushButton only: onExternalSyncStateChanged
// disabled m_syncButton and never touched the QAction, so the toolbar and
// menu Sync stayed clickable during a cron sync and could only produce the
// EX_TEMPFAIL skip. The button-based test passed throughout, because it
// drove the half that worked.
QTemporaryDir dir;
QVERIFY(dir.isValid());
QVERIFY(QDir().mkpath(dir.filePath(QStringLiteral("qtmaildir"))));
const QString conf = dir.filePath(QStringLiteral("qtmaildir/qtmaildir.conf"));
{
QSettings s(conf, QSettings::IniFormat);
s.setValue(QStringLiteral("sync/command"), QStringLiteral("/bin/true"));
}
const QString locks = dir.filePath(QStringLiteral("locks"));
{
QFile f(locks);
QVERIFY(f.open(QIODevice::WriteOnly));
}
MainWindow::setLocksPathForTesting(locks);
Config config;
config.load(conf);
MainWindow window(config);
auto *action = window.findChild<QAction *>(QStringLiteral("sync"));
QVERIFY2(action, "no sync action to check");
QVERIFY2(action->isEnabled(), "the action starts disabled with a command set");
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Running));
QVERIFY2(!action->isEnabled(),
"the sync action stayed enabled during a background sync");
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
QVERIFY2(action->isEnabled(),
"the sync action was not re-enabled after the background sync");
MainWindow::setLocksPathForTesting(QStringLiteral("/proc/locks"));
}
void TestMainWindow::theStatusBarFollowsTheSyncPhase()
{
// Item 42: "Syncing..." said nothing about what was happening, while the
// script was already streaming its phase into the log pane and the app was
// throwing it away.
//
// Driven through a real script rather than by calling the tracker directly,
// because the defect this guards is in the wiring: the chunks QProcess
// hands over split mid-line, so a handler that fed them straight to the
// tracker would stall on the first partial line.
QTemporaryDir dir;
QVERIFY(dir.isValid());
QVERIFY(QDir().mkpath(dir.filePath(QStringLiteral("qtmaildir"))));
const QString script = dir.filePath(QStringLiteral("fakesync.sh"));
{
QFile f(script);
QVERIFY(f.open(QIODevice::WriteOnly));
// Shaped like the real thing: timestamped lines, the noise that makes
// up the bulk of a run, mbsync's one summary, then notmuch's output.
// Paced, not dumped. A script that prints everything at once is
// delivered in a single readyRead, so the tracker sees the whole run in
// one call and only its final phase is ever painted: the intermediate
// ones would be unobservable and the test would assert nothing. A real
// sync takes tens of seconds and arrives in separate chunks, which the
// sleeps stand in for.
f.write("#!/bin/sh\n"
"echo '===== RUN START: 2026-08-07T11:00:00+02:00 ====='\n"
"echo '11:00:01 Note: Ignoring non-mail file: /home/you/Mail/x/.uidvalidity'\n"
"sleep 0.2\n"
"echo '11:00:02 Channels: 5 Boxes: 39 Far: +0 *1 #0 -0 Near: +1 *0 #0 -0'\n"
"sleep 0.2\n"
"echo '11:00:03 Processed 79 total files in almost no time.'\n"
"echo '11:00:03 Added 1 new message to the database.'\n"
"sleep 0.2\n"
"echo '===== RUN END: 2026-08-07T11:00:03+02:00 status=OK ====='\n");
f.close();
QVERIFY(QFile::setPermissions(script,
QFile::ReadOwner | QFile::WriteOwner
| QFile::ExeOwner));
}
const QString conf = dir.filePath(QStringLiteral("qtmaildir/qtmaildir.conf"));
{
QSettings s(conf, QSettings::IniFormat);
s.setValue(QStringLiteral("sync/command"), script);
}
const QString locks = dir.filePath(QStringLiteral("locks"));
{
QFile f(locks);
QVERIFY(f.open(QIODevice::WriteOnly));
}
MainWindow::setLocksPathForTesting(locks);
Config config;
config.load(conf);
QCOMPARE(config.syncCommand(), script);
MainWindow window(config);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
// Every value the label takes, recorded as it changes. A run this small
// finishes in well under a second, so polling for an intermediate phase
// races the process and usually sees only "Sync complete": the sequence has
// to be captured, not sampled.
// QLabel has no textChanged signal, so the label is sampled on a fast timer
// rather than watched. Each distinct value is recorded once.
QStringList seen;
QTimer sampler;
sampler.setInterval(1);
connect(&sampler, &QTimer::timeout, &sampler, [&seen, status]() {
const QString text = status->text();
if (seen.isEmpty() || seen.constLast() != text)
seen.append(text);
});
sampler.start();
QVERIFY(QMetaObject::invokeMethod(&window, "startSync"));
QTRY_VERIFY_WITH_TIMEOUT(
std::any_of(seen.cbegin(), seen.cend(), [](const QString &s) {
return s.contains(QStringLiteral("Sync complete"));
}),
10000);
const QString trace = seen.join(QStringLiteral(" | "));
// mbsync's summary is the only concrete thing the stream carries, since it
// names no channel unless run verbose. The counts must reach the label.
QVERIFY2(std::any_of(seen.cbegin(), seen.cend(), [](const QString &s) {
return s.contains(QStringLiteral("39"))
&& s.contains(QStringLiteral("5"));
}),
qPrintable(QStringLiteral("the mbsync summary never reached the "
"status bar. Saw: ") + trace));
// Then the reindex phase, which is a different message entirely. Without
// the wiring the label went from "Syncing..." straight to "Sync complete",
// which is exactly what the defect looked like.
QVERIFY2(std::any_of(seen.cbegin(), seen.cend(), [](const QString &s) {
return s.contains(QStringLiteral("notmuch"));
}),
qPrintable(QStringLiteral("the notmuch phase never reached the "
"status bar. Saw: ") + trace));
// The banners are not a phase and must never appear in the status bar.
for (const QString &s : seen) {
QVERIFY2(!s.contains(QStringLiteral("RUN ")), qPrintable(s));
QVERIFY2(!s.contains(QStringLiteral("status=")), qPrintable(s));
}
MainWindow::setLocksPathForTesting(QStringLiteral("/proc/locks"));
}
void TestMainWindow::anUnobservableLockTableLeavesTheSyncButtonUsable()
{
// Unknown means /proc/locks could not be read, so nothing was observed. A
// button left permanently disabled on a platform that cannot see the lock
// is worse than one that occasionally offers a run that gets skipped.
QTemporaryDir dir;
QVERIFY(dir.isValid());
QVERIFY(QDir().mkpath(dir.filePath(QStringLiteral("qtmaildir"))));
const QString conf = dir.filePath(QStringLiteral("qtmaildir/qtmaildir.conf"));
{
QSettings s(conf, QSettings::IniFormat);
s.setValue(QStringLiteral("sync/command"), QStringLiteral("/bin/true"));
}
Config config;
config.load(conf);
MainWindow window(config);
auto *action = window.findChild<QAction *>(QStringLiteral("sync"));
QVERIFY(action);
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Running));
QVERIFY(!action->isEnabled());
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Unknown));
QVERIFY2(action->isEnabled(),
"an unobservable lock table left the sync action disabled");
}
void TestMainWindow::escapeBlanksTheMessagePane()
{
// A registered action like any other, so it reaches the menus, the shortcut
// reference and [keys]. Clearing m_currentThreadId with the pane is the
// part that matters: a late threadLoaded would otherwise paint the thread
// straight back, which is the race fixed in 0.8.0.
const Config config;
MainWindow window(config);
auto *action = window.findChild<QAction *>(QStringLiteral("clear_pane"));
QVERIFY2(action, "no clear_pane action registered");
// Shift+Esc since item 50: plain Escape now clears the selection too, and
// this narrower action kept the same key with a modifier. The behaviour
// asserted below is unchanged, which is the point of keeping both.
QCOMPARE(action->shortcut(),
QKeySequence(Qt::ShiftModifier | Qt::Key_Escape));
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
model->appendBatch({ makeThread(QStringLiteral("t1"), {}),
makeThread(QStringLiteral("t2"), {}) });
selectThreadRow(view, 0);
QVERIFY2(!window.currentThreadId().isEmpty(),
"no thread was opened to blank");
action->trigger();
QVERIFY2(window.currentThreadId().isEmpty(),
"Escape left the thread loaded in the pane");
// Blanking is a view change, not a mail change: the selection stays.
QCOMPARE(view->selectionModel()->selectedRows().size(), 1);
}
void TestMainWindow::deleteTogglesOnAnAlreadyDeletedThread()
{
// Hitting Delete twice is the natural way to say "no, put it back", and
// adding a tag that is already present is a no-op the user cannot see.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *action = window.findChild<QAction *>(QStringLiteral("delete"));
QVERIFY(action);
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("deleted") }) });
selectThreadRow(view, 0);
action->trigger();
// The optimistic model update is synchronous, so the row reflects the
// change without a worker.
QVERIFY2(!model->threadAt(0).isDeleted(),
"delete on an already-deleted thread did not undelete it");
}
void TestMainWindow::deleteOnAMixedSelectionDeletesRatherThanSplittingIt()
{
// The constraint that makes this more than a one-liner: toggling each
// thread independently would leave one keystroke with the selection in two
// states, which is worse than either outcome. Undelete only when every
// selected thread is already deleted.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *action = window.findChild<QAction *>(QStringLiteral("delete"));
QVERIFY(action);
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("deleted") }),
makeThread(QStringLiteral("t2"), {}) });
view->selectAll();
QCOMPARE(view->selectionModel()->selectedRows().size(), 2);
action->trigger();
QVERIFY2(model->threadAt(0).isDeleted() && model->threadAt(1).isDeleted(),
"a mixed selection split instead of deleting the whole selection");
}
void TestMainWindow::aTransientStatusMessageExpires()
{
// "Sync complete" describes an event, not a state, and reads as though it
// describes the present until something else overwrites it.
const Config config;
MainWindow window(config);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
auto *timer = window.findChild<QTimer *>(QStringLiteral("statusTimer"));
QVERIFY2(timer, "no status expiry timer");
QMetaObject::invokeMethod(&window, "showTransientStatus",
Q_ARG(QString, QStringLiteral("Sync complete")));
QCOMPARE(status->text(), QStringLiteral("Sync complete"));
QVERIFY(timer->isActive());
// Fire it rather than waiting out the real interval.
timer->setInterval(0);
QTRY_VERIFY_WITH_TIMEOUT(status->text() != QStringLiteral("Sync complete"),
2000);
}
void TestMainWindow::theSelectionCountIsStateAndDoesNotExpire()
{
// Not everything in the status bar is an event. The selection count
// describes what is true right now and must persist while it stays true;
// expiring it would undo the 0.8.0 discoverability work.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *status = window.findChild<QLabel *>(QStringLiteral("statusMessage"));
QVERIFY(status);
auto *timer = window.findChild<QTimer *>(QStringLiteral("statusTimer"));
QVERIFY(timer);
model->appendBatch({ makeThread(QStringLiteral("t1"), {}),
makeThread(QStringLiteral("t2"), {}) });
view->selectAll();
QVERIFY2(status->text().contains(QStringLiteral("2")),
"the selection count was not reported");
QVERIFY2(!timer->isActive(),
"the selection count armed the expiry timer; it is state, "
"not an event");
}
void TestMainWindow::anEditUndoneNettsBackToZero()
{
// Reported by the user: open a thread, let the 2 s auto-mark-read remove
// `unread`, then press Ctrl+U to put it back. The indicator read 2 unsynced
// changes when the mail store was exactly where it started.
//
// The count tracks NET state, not writes. Two writes did happen, but their
// effect cancels, and what the user needs to know is whether quitting now
// would strand work.
const Config config;
MainWindow window(config);
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
QVERIFY(label->isHidden());
// The automatic mark-read: remove `unread` from one message.
TagChange off;
off.messageIds = { QStringLiteral("m1") };
off.removed = { QStringLiteral("unread") };
off.description = QStringLiteral("Mark read");
QVERIFY(QMetaObject::invokeMethod(&window, "onTagsApplied",
Q_ARG(TagChange, off)));
QVERIFY2(!label->isHidden(), "one edit must show the indicator");
// Ctrl+U puts it back on the same message.
TagChange on;
on.messageIds = { QStringLiteral("m1") };
on.added = { QStringLiteral("unread") };
on.description = QStringLiteral("Mark unread");
QVERIFY(QMetaObject::invokeMethod(&window, "onTagsApplied",
Q_ARG(TagChange, on)));
QVERIFY2(label->isHidden(),
qPrintable(QStringLiteral("an edit and its inverse left the "
"indicator showing '%1'")
.arg(label->text())));
}
void TestMainWindow::aDifferentTagOnTheSameMessageStillCounts()
{
// Netting must be per (message, tag), not per message. Removing `unread`
// and adding `flagged` on one message are two independent changes, and
// neither cancels the other.
const Config config;
MainWindow window(config);
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
TagChange a;
a.messageIds = { QStringLiteral("m1") };
a.removed = { QStringLiteral("unread") };
a.description = QStringLiteral("Mark read");
QVERIFY(QMetaObject::invokeMethod(&window, "onTagsApplied",
Q_ARG(TagChange, a)));
TagChange b;
b.messageIds = { QStringLiteral("m1") };
b.added = { QStringLiteral("flagged") };
b.description = QStringLiteral("Flag");
QVERIFY(QMetaObject::invokeMethod(&window, "onTagsApplied",
Q_ARG(TagChange, b)));
QVERIFY2(!label->isHidden(),
"two different tags on one message cancelled each other");
}
void TestMainWindow::anEditWithNoMessageIdsStillCounts()
{
// A TagChange carrying no message ids cannot be netted against anything,
// and must still register rather than silently counting as zero. Losing an
// edit understates the indicator, which is the direction that costs the
// user work.
const Config config;
MainWindow window(config);
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
TagChange change;
change.added = { QStringLiteral("deleted") };
change.description = QStringLiteral("Delete");
QVERIFY(QMetaObject::invokeMethod(&window, "onTagsApplied",
Q_ARG(TagChange, change)));
QVERIFY2(!label->isHidden(),
"an edit with no message ids was not counted at all");
}
// Item 37. A tag edit made while a background sync holds notmuch's write lock
// used to stall the worker: the read-write open BLOCKS until the lock frees
// (measured 9.158s against a 12s hold, returning NOTMUCH_STATUS_SUCCESS), so
// every later query and thread load queued behind it. These cases pin the fix:
// do not send the write while a sync is running, send it when the sync ends.
void TestMainWindow::anEditDuringABackgroundSyncIsNotSentYet()
{
// The defect. Sending during the sync is what stalls the worker, so the
// edit is held instead. The rows still show it: it is what the user asked
// for and it is going to be applied.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *action = window.findChild<QAction *>(QStringLiteral("flag"));
QVERIFY2(action, "no flag action registered");
model->appendBatch({ makeThread(QStringLiteral("t1"), {}) });
selectThreadRow(view, 0);
// A cron sync takes the lock.
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Running));
action->trigger();
QVERIFY2(window.hasEditAwaitingSend(),
"the edit was sent straight into a running sync, which is the "
"blocking open that stalls the worker");
QVERIFY2(model->threadAt(0).tags.contains(QStringLiteral("flagged")),
"holding the edit also dropped it from the rows");
}
void TestMainWindow::aHeldEditIsSentWhenTheBackgroundSyncEnds()
{
// The release. SyncMonitor already reports this transition for item 27, so
// the held edit rides a signal that exists rather than a timer.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *action = window.findChild<QAction *>(QStringLiteral("flag"));
QVERIFY(action);
model->appendBatch({ makeThread(QStringLiteral("t1"), {}) });
selectThreadRow(view, 0);
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Running));
action->trigger();
QVERIFY(window.hasEditAwaitingSend());
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle));
QVERIFY2(!window.hasEditAwaitingSend(),
"the sync ending did not send the held edit");
QVERIFY2(model->threadAt(0).tags.contains(QStringLiteral("flagged")),
"sending the held edit lost the tag from the rows");
}
void TestMainWindow::aHeldEditCountsAsUnsynced()
{
// A held edit has not reached the index, so onTagsApplied() never counted
// it. It must still count here, because this is what the exit prompt reads:
// quitting on a held edit loses it outright, which is the whole failure the
// prompt exists to prevent.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *action = window.findChild<QAction *>(QStringLiteral("flag"));
QVERIFY(action);
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
QVERIFY2(label->isHidden(), "the indicator starts hidden at zero");
model->appendBatch({ makeThread(QStringLiteral("t1"), {}) });
selectThreadRow(view, 0);
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Running));
action->trigger();
QVERIFY2(!label->isHidden(),
"an edit held for a running sync was not counted as unsynced, so "
"the exit prompt would let the user quit on it");
}
void TestMainWindow::anUnreadableLockTableStillSendsTheEdit()
{
// State::Unknown means /proc/locks could not be read, so nothing is
// observed. Holding writes there would strand every edit forever on a
// platform that cannot see the lock at all. Unknown is not "running".
//
// Driven from Running, not from a fresh window: the guard is that Unknown
// CLEARS the busy flag, and a window that was never busy would pass this
// whatever Unknown did. Reaching Unknown by way of Running is also the only
// way a real monitor gets there, when /proc/locks becomes unreadable
// mid-session.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *action = window.findChild<QAction *>(QStringLiteral("flag"));
QVERIFY(action);
model->appendBatch({ makeThread(QStringLiteral("t1"), {}),
makeThread(QStringLiteral("t2"), {}) });
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Running));
selectThreadRow(view, 0);
action->trigger();
QVERIFY2(window.hasEditAwaitingSend(),
"the edit was not held during a running sync, so this test is not "
"exercising the Unknown transition it claims to");
// The lock table becomes unreadable. That is not evidence of a sync, so
// writing must resume and the held edit must go out.
QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Unknown));
QVERIFY2(!window.hasEditAwaitingSend(),
"an unreadable lock table kept the edit held, stranding it on any "
"platform without /proc/locks");
// And a NEW edit is sent rather than held.
selectThreadRow(view, 1);
action->trigger();
QVERIFY2(!window.hasEditAwaitingSend(),
"an unreadable lock table held a new edit, so writes never resume");
}
void TestMainWindow::aRejectedWriteKeepsEarlierUndoHistory()
{
// revertPendingTagChange() used to undo the failed command and then CLEAR
// the whole stack, so one rejected write threw away every undo step the
// user had built up. Undoing the failed command is enough: it is already
// off the stack afterwards.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
auto *flag = window.findChild<QAction *>(QStringLiteral("flag"));
QVERIFY(flag);
auto *archive = window.findChild<QAction *>(QStringLiteral("archive"));
QVERIFY2(archive, "no archive action registered");
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("inbox") }) });
selectThreadRow(view, 0);
// One edit that succeeds, so there is history worth keeping.
archive->trigger();
TagChange applied;
applied.messageIds = { QStringLiteral("m1") };
applied.removed = { QStringLiteral("inbox") };
applied.description = QStringLiteral("Archive");
QVERIFY(QMetaObject::invokeMethod(&window, "onTagsApplied",
Q_ARG(TagChange, applied)));
// A second edit that the worker rejects outright.
flag->trigger();
QVERIFY(QMetaObject::invokeMethod(
&window, "onWorkerError",
Q_ARG(QString, QStringLiteral("Cannot resolve threads"))));
QVERIFY2(window.canUndo(),
"a rejected write cleared the undo history of edits that had "
"already succeeded");
}
// Item 54. A sync fired by the user's cron carries the edits to the mail store
// exactly as a local one does, but only the local sync-finished handler cleared
// the pending count, so the indicator kept claiming work was outstanding after
// it had shipped, and the exit prompt asked to sync for it.
//
// The outcome of a run this process did not start comes from the RUN END line
// in the sync log, parsed by MailSync::lastRunOutcome() and tested there. These
// tests are about what MainWindow does with each answer.
namespace {
/// Writes a config naming \p logPath as the sync log, and loads it.
///
/// The log path has to come from config rather than the real
/// ~/.local/state/mailsync.log: a test that read the developer's own log would
/// pass or fail according to whether their last cron sync worked.
void loadConfigWithSyncLog(Config &config, const QTemporaryDir &dir,
const QString &logPath)
{
const QString path = dir.filePath(QStringLiteral("qtmaildir.conf"));
QFile file(path);
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
file.write(QStringLiteral("[sync]\nlog=%1\n").arg(logPath).toUtf8());
file.close();
config.load(path);
QCOMPARE(config.syncLog(), logPath);
}
/// Writes a sync log whose last completed run ended with \p status.
void writeSyncLog(const QString &path, const QString &status)
{
QFile file(path);
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
file.write(QStringLiteral("===== RUN END: 2026-08-09T10:20:03+02:00 status=%1 "
"=====\n").arg(status).toUtf8());
file.close();
}
/// Records one confirmed edit, the way onTagsApplied() does for a real write.
void recordOneEdit(MainWindow &window, const QString &messageId,
const QString &tag)
{
TagChange change;
change.messageIds = { messageId };
change.added = { tag };
change.description = QStringLiteral("Flag");
QVERIFY(QMetaObject::invokeMethod(&window, "onTagsApplied",
Q_ARG(TagChange, change)));
}
/// Drives a complete external sync: the lock appears, then it is released.
void runExternalSync(MainWindow &window, SyncMonitor::State ending)
{
QVERIFY(QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Running)));
QVERIFY(QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State, ending)));
}
} // namespace
void TestMainWindow::aSuccessfulCronSyncClearsThePendingCount()
{
// The reported defect: edits applied, cron syncs, indicator still says N.
QTemporaryDir dir;
QVERIFY(dir.isValid());
const QString logPath = dir.filePath(QStringLiteral("mailsync.log"));
writeSyncLog(logPath, QStringLiteral("OK"));
Config config;
loadConfigWithSyncLog(config, dir, logPath);
MainWindow window(config);
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
recordOneEdit(window, QStringLiteral("m1"), QStringLiteral("flagged"));
QVERIFY2(!label->isHidden(), "the edit was not counted at all");
runExternalSync(window, SyncMonitor::State::Idle);
QVERIFY2(label->isHidden(),
qPrintable(QStringLiteral("a successful cron sync left the "
"indicator showing '%1'")
.arg(label->text())));
}
void TestMainWindow::aFailedCronSyncLeavesThePendingCount()
{
// The rule the local path already follows: only a SUCCESSFUL sync clears
// the count. Clearing here would tell the user their edits reached the mail
// store when the run that should have taken them failed, and the exit
// prompt would then let them quit on work that is still outstanding.
QTemporaryDir dir;
QVERIFY(dir.isValid());
const QString logPath = dir.filePath(QStringLiteral("mailsync.log"));
writeSyncLog(logPath, QStringLiteral("FAILED mbsync=1 notmuch=0"));
Config config;
loadConfigWithSyncLog(config, dir, logPath);
MainWindow window(config);
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
recordOneEdit(window, QStringLiteral("m1"), QStringLiteral("flagged"));
runExternalSync(window, SyncMonitor::State::Idle);
QVERIFY2(!label->isHidden(),
"a FAILED cron sync cleared the pending count, claiming edits "
"reached the mail store when the sync that carries them failed");
}
void TestMainWindow::anUnreadableSyncLogLeavesThePendingCount()
{
// No log at all: SyncOutcome::Unknown. Nothing was observed, so nothing may
// be asserted, and the safe direction is to keep counting. Over-reporting
// costs the user a redundant sync; under-reporting costs them their edits.
QTemporaryDir dir;
QVERIFY(dir.isValid());
const QString logPath = dir.filePath(QStringLiteral("absent.log"));
QVERIFY(!QFileInfo::exists(logPath));
Config config;
loadConfigWithSyncLog(config, dir, logPath);
MainWindow window(config);
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
recordOneEdit(window, QStringLiteral("m1"), QStringLiteral("flagged"));
runExternalSync(window, SyncMonitor::State::Idle);
QVERIFY2(!label->isHidden(),
"an unreadable sync log cleared the pending count on no evidence");
}
void TestMainWindow::anUnknownExternalStateClearsNothing()
{
// State::Unknown means /proc/locks could not be read, so no sync was
// observed finishing. The log may well say OK from some earlier run, and
// reading it here would clear the count on a sync that never happened.
QTemporaryDir dir;
QVERIFY(dir.isValid());
const QString logPath = dir.filePath(QStringLiteral("mailsync.log"));
writeSyncLog(logPath, QStringLiteral("OK"));
Config config;
loadConfigWithSyncLog(config, dir, logPath);
MainWindow window(config);
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
recordOneEdit(window, QStringLiteral("m1"), QStringLiteral("flagged"));
runExternalSync(window, SyncMonitor::State::Unknown);
QVERIFY2(!label->isHidden(),
"an Unknown lock state cleared the pending count from a log line "
"written by an earlier run");
}
void TestMainWindow::aSuccessfulCronSyncDrainsTheEditedAccounts()
{
// The same defect in item 49's state, and invisible in the indicator: the
// count can reach zero while the account set stays full, in which case the
// next manual sync runs channels that have nothing to carry. Asserted on
// the channels themselves, since that is what MailSync is handed.
QTemporaryDir dir;
QVERIFY(dir.isValid());
const QString logPath = dir.filePath(QStringLiteral("mailsync.log"));
writeSyncLog(logPath, QStringLiteral("OK"));
const QString confPath = dir.filePath(QStringLiteral("qtmaildir.conf"));
QFile conf(confPath);
QVERIFY(conf.open(QIODevice::WriteOnly | QIODevice::Text));
conf.write(QStringLiteral("[sync]\nlog=%1\n\n"
"[account.work]\n"
"maildir=work-mail\n"
"channel=work-channel\n")
.arg(logPath).toUtf8());
conf.close();
Config config;
config.load(confPath);
QCOMPARE(config.accounts().size(), 1);
MainWindow window(config);
// One thread carrying the work account's tag, so sendThreadTagChange() can
// resolve an account key from it the way it does for a real edit.
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
ThreadSummary thread;
thread.threadId = QStringLiteral("t1");
thread.subject = QStringLiteral("Subject");
thread.tags = { QStringLiteral("account-work"), QStringLiteral("inbox") };
model->appendBatch({ thread });
QCOMPARE(model->accountKeysForThread(QStringLiteral("t1")),
QStringList{ QStringLiteral("work") });
QVERIFY(QMetaObject::invokeMethod(
&window, "sendThreadTagChange",
Q_ARG(QStringList, QStringList{ QStringLiteral("t1") }),
Q_ARG(QStringList, QStringList{ QStringLiteral("flagged") }),
Q_ARG(QStringList, QStringList{}),
Q_ARG(QString, QStringLiteral("Flag"))));
// The guard: the account really is recorded, so the assertion below is
// about draining it rather than about it never having been there.
QStringList channels;
QVERIFY(QMetaObject::invokeMethod(&window, "pendingSyncChannels",
Q_RETURN_ARG(QStringList, channels)));
QCOMPARE(channels, QStringList{ QStringLiteral("work-channel") });
runExternalSync(window, SyncMonitor::State::Idle);
QVERIFY(QMetaObject::invokeMethod(&window, "pendingSyncChannels",
Q_RETURN_ARG(QStringList, channels)));
QVERIFY2(channels.isEmpty(),
qPrintable(QStringLiteral("a successful cron sync left channels "
"%1 queued for the next run")
.arg(channels.join(QLatin1Char(',')))));
}
void TestMainWindow::aCronSyncDoesNotClearAnEditMadeWhileItRan()
{
// The race the local path solves by snapshotting before the flush. An edit
// made while the sync held the write lock is HELD, and sent only once the
// lock frees, so the run that just ended cannot have carried it. Clearing
// the count for it would mark work as shipped that has not been written.
QTemporaryDir dir;
QVERIFY(dir.isValid());
const QString logPath = dir.filePath(QStringLiteral("mailsync.log"));
writeSyncLog(logPath, QStringLiteral("OK"));
Config config;
loadConfigWithSyncLog(config, dir, logPath);
MainWindow window(config);
auto *label = window.findChild<QLabel *>(QStringLiteral("pendingEdits"));
QVERIFY(label);
// The sync starts, then the user edits while it is running.
QVERIFY(QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Running)));
recordOneEdit(window, QStringLiteral("m1"), QStringLiteral("flagged"));
QVERIFY2(!label->isHidden(), "the edit was not counted at all");
QVERIFY(QMetaObject::invokeMethod(&window, "onExternalSyncStateChanged",
Q_ARG(SyncMonitor::State,
SyncMonitor::State::Idle)));
// onTagsApplied() ran while the lock was held, so this edit reached the
// INDEX during the sync. Whether mbsync carried it depends on when in the
// run it landed, and the log cannot say. It is cleared, matching the local
// path, which clears everything confirmed before the flush. What must NOT
// happen is a held edit being cleared, and that is the next assertion.
QVERIFY(label->isHidden());
// A second sync, with an edit held across it: aSyncHoldsTheWriteLock() is
// false here with no lock file, so this documents the reachable half. The
// held-edit path has its own coverage in aHeldEditCountsAsUnsynced().
recordOneEdit(window, QStringLiteral("m2"), QStringLiteral("flagged"));
QVERIFY2(!label->isHidden(),
"an edit made after the sync ended was swallowed by it");
}
// Items 56 and 57.
void TestMainWindow::everyActionCarriesAnIcon()
{
// Item 56. The complaint was inconsistency, not absence: eight actions had
// themed icons and the other sixteen had none, so adjacent entries in one
// menu disagreed, and the toolbar's TextBesideIcon style laid out an empty
// slot for each of the sixteen.
//
// What this test can and cannot prove is worth stating, because it is
// weaker than it looks. QIcon::fromTheme() resolves against the icon theme
// of the machine running the test, so a PASS says "this desktop has art for
// every name assigned", not "every name is correct" and not "the icon suits
// the action". A machine with a sparse theme fails this through no fault of
// the code. It is still worth having: it catches the actual regression,
// which is an action registered with no name assigned at all.
const Config config;
MainWindow window(config);
// The guard. Without it a MainWindow that registered nothing would pass an
// empty loop, which is the classic way a "for each" assertion goes vacuous.
const QList<QAction *> actions =
window.findChildren<QAction *>(QString(), Qt::FindDirectChildrenOnly);
QVERIFY2(actions.size() >= KeyMap::knownActions().size(),
qPrintable(QStringLiteral("expected at least %1 actions, found %2")
.arg(KeyMap::knownActions().size())
.arg(actions.size())));
QStringList missing;
for (const QString &name : KeyMap::knownActions()) {
auto *action = window.findChild<QAction *>(name);
QVERIFY2(action, qPrintable(QStringLiteral("no action named %1").arg(name)));
if (action->icon().isNull())
missing.append(name);
}
QVERIFY2(missing.isEmpty(),
qPrintable(QStringLiteral("%1 action(s) have no icon: %2")
.arg(missing.size())
.arg(missing.join(QStringLiteral(", ")))));
}
void TestMainWindow::theToolbarDoesNotOverrideTheDesktopButtonStyle()
{
// The second half of the user's note: "Buttons should honor the 'Icon only'
// option". They cannot while the toolbar asserts its own style. Qt takes
// the desktop's preference from the platform theme and exposes it as
// SH_ToolButtonStyle; a hardcoded setToolButtonStyle() overrides it, so the
// user's setting has no effect whatever it is set to.
const Config config;
MainWindow window(config);
auto *toolBar = window.findChild<QToolBar *>(QStringLiteral("main_toolbar"));
QVERIFY(toolBar);
const auto expected = static_cast<Qt::ToolButtonStyle>(
window.style()->styleHint(QStyle::SH_ToolButtonStyle, nullptr, toolBar));
QCOMPARE(toolBar->toolButtonStyle(), expected);
}
void TestMainWindow::theImportantActionIsLabelledImportant()
{
// Item 57. The user picked "Important" over "Starred": the Message menu
// already has `Mark &spam`, so "Starred" would have had to take an
// accelerator from inside the word, while "Important" takes a free &I.
const Config config;
MainWindow window(config);
// The action NAME is unchanged on purpose. It is the key a user writes in
// the config's [keys] section, so renaming it would silently break every
// existing binding for a change that is only about wording.
auto *action = window.findChild<QAction *>(QStringLiteral("flag"));
QVERIFY(action);
QVERIFY2(action->text().contains(QStringLiteral("Important")),
qPrintable(QStringLiteral("the action still reads '%1'")
.arg(action->text())));
QVERIFY2(!action->text().contains(QStringLiteral("Flag")),
qPrintable(QStringLiteral("the action still reads '%1'")
.arg(action->text())));
// The accelerator the item chose, and the reason "Starred" was rejected.
QCOMPARE(action->text(), QStringLiteral("&Important"));
}
void TestMainWindow::theImportantActionStillWritesTheFlaggedTag()
{
// The rename is a LABEL change and must not reach the mail store. `flagged`
// is a notmuch tag: neomutt reads it, the user's saved queries match on it,
// ThreadSummary::isFlagged() tests for it and TagColors colours it. A
// rename that followed the label through to the tag would rewrite the store
// and desynchronise every other tool that reads the same Maildir.
//
// Asserted on the ids and tags actually sent to the worker, which is the
// only place the distinction is observable.
const Config config;
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *view = window.findChild<QTreeView *>();
QVERIFY(view);
model->appendBatch({ makeThread(QStringLiteral("t1"),
{ QStringLiteral("inbox") }) });
// The guard: the thread must NOT already carry the tag, or the assertion
// below would pass against an action that did nothing at all.
QVERIFY(!model->threadAt(0).isFlagged());
selectThreadRow(view, 0);
auto *action = window.findChild<QAction *>(QStringLiteral("flag"));
QVERIFY(action);
action->trigger();
// sendThreadTagChange() applies the change to the model optimistically, so
// the tag the action really wrote is observable here without a worker.
QVERIFY2(model->threadAt(0).isFlagged(),
"the renamed action no longer writes the `flagged` tag");
QVERIFY2(model->threadAt(0).tags.contains(QStringLiteral("flagged")),
"the tag written was not `flagged`");
QVERIFY2(!model->threadAt(0).tags.contains(QStringLiteral("important")),
"the rename reached the mail store: an `important` tag was "
"written, which no other tool reading this Maildir knows");
}
void TestMainWindow::theToolbarUsesTheConfiguredIconSize()
{
// With the toolbar following the desktop's "Icon only" style, the icons are
// the whole control, and this style reports 16px, which is a small target.
// The size is configurable with a 24px default; this proves the config
// value actually reaches the widget rather than sitting in Config unread.
QTemporaryDir dir;
QVERIFY(dir.isValid());
const QString path = dir.filePath(QStringLiteral("qtmaildir.conf"));
QFile file(path);
QVERIFY(file.open(QIODevice::WriteOnly | QIODevice::Text));
file.write("[general]\ntoolbar_icon_size = 40\n");
file.close();
Config config;
config.load(path);
QCOMPARE(config.toolbarIconSize(), 40);
MainWindow window(config);
auto *toolBar = window.findChild<QToolBar *>(QStringLiteral("main_toolbar"));
QVERIFY(toolBar);
// 40 is deliberately not any of this style's own metrics (16 small, 32
// large), so the assertion cannot pass by the widget happening to agree
// with the theme.
QCOMPARE(toolBar->iconSize(), QSize(40, 40));
}
namespace {
/// A config whose accounts carry the given maildir/sent pairs. An empty `sent`
/// writes no key at all, which is the account-without-a-sent-folder case.
QString writeSentConfig(const QTemporaryDir &dir,
const QList<QPair<QString, QString>> &accounts)
{
const QString path = dir.filePath(QStringLiteral("qtmaildir.conf"));
QSettings s(path, QSettings::IniFormat);
for (const auto &account : accounts) {
s.beginGroup(QStringLiteral("account.") + account.first);
s.setValue(QStringLiteral("maildir"), account.first);
if (!account.second.isEmpty())
s.setValue(QStringLiteral("sent"), account.second);
s.endGroup();
}
s.sync();
return path;
}
} // namespace
void TestMainWindow::thereIsNoSentButtonWithoutASentKey()
{
// Hidden entirely rather than present and finding nothing. An account may
// legitimately keep no sent mail locally, and a button that always returns
// an empty list reads as a broken feature rather than an absent one.
QTemporaryDir dir;
QVERIFY(dir.isValid());
Config config;
config.load(writeSentConfig(dir, {{QStringLiteral("provider-c"), {}}}));
QVERIFY(config.allSentQuery().isEmpty());
MainWindow window(config);
QVERIFY(!window.findChild<QPushButton *>(QStringLiteral("sentButton")));
}
void TestMainWindow::theSentButtonRunsEveryConfiguredAccount()
{
// The button composes its query rather than storing one, which is the whole
// reason it is not a [queries] entry: a saved query is a fixed string and
// would not gain the third account here without the user editing it.
QTemporaryDir dir;
QVERIFY(dir.isValid());
Config config;
config.load(writeSentConfig(dir, {
{QStringLiteral("webmail-primary"), QStringLiteral("Sent")},
{QStringLiteral("provider-c"), {}},
{QStringLiteral("webmail-secondary"), QStringLiteral("Sent")},
}));
MainWindow window(config);
auto *button = window.findChild<QPushButton *>(QStringLiteral("sentButton"));
QVERIFY(button);
auto *queryEdit = window.findChild<QLineEdit *>(QStringLiteral("queryEdit"));
QVERIFY(queryEdit);
button->click();
const QString query = queryEdit->text();
QVERIFY(query.contains(QStringLiteral("webmail-primary/Sent")));
QVERIFY(query.contains(QStringLiteral("webmail-secondary/Sent")));
// The account with no key contributes nothing, and leaves no bare "or"
// behind: notmuch accepts that and silently returns a different result.
QVERIFY(!query.contains(QStringLiteral("provider-c")));
QVERIFY(!query.contains(QStringLiteral("or or")));
QCOMPARE(query.count(QStringLiteral(" or ")), 1);
}
void TestMainWindow::theSentButtonSurvivesABracketedPath()
{
// A real provider nests its sent folder under a bracketed parent, and "["
// and "]" are Xapian syntax. The quoting has to survive the trip from the
// config through Account::sentQuery() into the query bar; unquoted, the
// query looks plausible and matches nothing.
QTemporaryDir dir;
QVERIFY(dir.isValid());
Config config;
config.load(writeSentConfig(dir, {
{QStringLiteral("provider-a"), QStringLiteral("[Provider]/Posta inviata")},
}));
MainWindow window(config);
auto *button = window.findChild<QPushButton *>(QStringLiteral("sentButton"));
QVERIFY(button);
auto *queryEdit = window.findChild<QLineEdit *>(QStringLiteral("queryEdit"));
QVERIFY(queryEdit);
button->click();
QCOMPARE(queryEdit->text(),
QStringLiteral("path:\"provider-a/[Provider]/Posta inviata/**\""));
}
namespace {
/// Writes a config whose accounts carry a sent folder, a drafts folder, or
/// neither. Separate from writeSentConfig() because the two keys are
/// independent: the interesting cases here are exactly the ones where an
/// account has one and not the other.
struct FolderAccount {
QString maildir;
QString sent;
QString drafts;
};
QString writeFolderConfig(const QTemporaryDir &dir,
const QList<FolderAccount> &accounts)
{
const QString path = dir.filePath(QStringLiteral("qtmaildir.conf"));
QSettings s(path, QSettings::IniFormat);
for (const FolderAccount &account : accounts) {
s.beginGroup(QStringLiteral("account.") + account.maildir);
s.setValue(QStringLiteral("maildir"), account.maildir);
if (!account.sent.isEmpty())
s.setValue(QStringLiteral("sent"), account.sent);
if (!account.drafts.isEmpty())
s.setValue(QStringLiteral("drafts"), account.drafts);
s.endGroup();
}
s.sync();
return path;
}
/// The label of the helper whose query is `query`, or a null string.
QString labelForQuery(const QList<HtmlBuilder::PlaceholderHelper> &helpers,
const QString &query)
{
for (const HtmlBuilder::PlaceholderHelper &helper : helpers) {
if (helper.query == query)
return helper.label;
}
return QString();
}
} // namespace
void TestMainWindow::placeholderCountsSkipSentAndDraftsWithoutTheKeys()
{
// The tag: lines are unconditional, the folder lines are not. An account
// with no sent or drafts folder must contribute no line at all rather than
// a line reading 0: item 63 established that a missing folder is a real
// configuration, and "0 sent" claims the user has sent nothing.
QTemporaryDir dir;
QVERIFY(dir.isValid());
Config config;
config.load(writeFolderConfig(dir, {{QStringLiteral("provider-c"), {}, {}}}));
MainWindow window(config);
const QStringList queries = window.placeholderQueriesForTesting();
QCOMPARE(queries.size(), 3);
QVERIFY(queries.contains(QStringLiteral("tag:unread")));
QVERIFY(queries.contains(QStringLiteral("tag:flagged")));
QVERIFY(queries.contains(QStringLiteral("tag:inbox")));
}
void TestMainWindow::placeholderCountsCarrySentAndDrafts()
{
// Both composed from the folder keys rather than from a tag. `tag:draft`
// counts 0 against the user's real database (measured 2026-08-11) and no
// draft-ish tag exists in it at all, so a tag-based drafts line would be a
// permanent zero that looks like working code.
//
// The account layout is the real one's shape: one account with both keys,
// one with drafts and NO sent, which is what proves the two are collected
// independently rather than per-account in one pass.
QTemporaryDir dir;
QVERIFY(dir.isValid());
Config config;
config.load(writeFolderConfig(dir, {
{QStringLiteral("webmail-primary"), QStringLiteral("Sent"),
QStringLiteral("Drafts")},
{QStringLiteral("provider-a"), {}, QStringLiteral("[Provider]/Bozze")},
}));
MainWindow window(config);
const QStringList queries = window.placeholderQueriesForTesting();
QCOMPARE(queries.size(), 5);
// The quoting survives the trip, which is the trap this whole composition
// exists for: unquoted, "[" and "]" are Xapian syntax and the count reads
// 0 while looking like an empty folder.
QVERIFY2(queries.contains(config.allDraftsQuery()),
qPrintable(QStringLiteral("drafts query missing, got: %1")
.arg(queries.join(QStringLiteral(" | ")))));
QVERIFY(queries.contains(config.allSentQuery()));
QVERIFY(config.allDraftsQuery().contains(
QStringLiteral("path:\"provider-a/[Provider]/Bozze/**\"")));
// The sent term comes from the account that has one, and the drafts terms
// from both. An implementation that emitted a folder line per account
// would produce four folder queries instead of two.
QCOMPARE(config.allSentQuery().count(QStringLiteral("path:")), 1);
QCOMPARE(config.allDraftsQuery().count(QStringLiteral("path:")), 2);
}
void TestMainWindow::placeholderLabelsStayPairedWithTheirQueries()
{
// The defect this guards is the one the old fixed array invited: the
// labels were written positionally against a separate query array, so
// inserting an entry in one and not the other put a real number against
// the wrong name. Asserting the PAIRING rather than the order is what
// survives a later reshuffle.
QTemporaryDir dir;
QVERIFY(dir.isValid());
Config config;
config.load(writeFolderConfig(dir, {
{QStringLiteral("webmail-primary"), QStringLiteral("Sent"),
QStringLiteral("Drafts")},
}));
MainWindow window(config);
const QStringList queries = window.placeholderQueriesForTesting();
QCOMPARE(queries.size(), 5);
// Distinct counts, so a label reading the wrong index cannot coincide with
// the right answer. Positional against the queries the window just asked
// for, which is exactly the contract requestCounts() replies under.
QVector<int> counts;
for (int i = 0; i < queries.size(); ++i)
counts.append((i + 1) * 10);
QMetaObject::invokeMethod(&window, "onCountsReady",
Q_ARG(QVector<int>, counts),
Q_ARG(quint64, window.countsGenerationForTesting()));
const QList<HtmlBuilder::PlaceholderHelper> helpers =
window.placeholderHelpersForTesting();
for (int i = 0; i < queries.size(); ++i) {
const QString label = labelForQuery(helpers, queries.at(i));
QVERIFY2(!label.isNull(),
qPrintable(QStringLiteral("no helper for query '%1'")
.arg(queries.at(i))));
QVERIFY2(label.contains(QString::number(counts.at(i))),
qPrintable(QStringLiteral("query '%1' was labelled '%2', which "
"does not carry its own count %3")
.arg(queries.at(i), label)
.arg(counts.at(i))));
}
// And the folder lines say what they are, not "in inbox".
QVERIFY(labelForQuery(helpers, config.allSentQuery())
.contains(QStringLiteral("sent")));
QVERIFY(labelForQuery(helpers, config.allDraftsQuery())
.contains(QStringLiteral("draft")));
}
void TestMainWindow::placeholderCountsDropAnUncountableQuery()
{
// The worker answers -1 for a query it could not count, rather than
// skipping the entry, precisely so the positional pairing holds. The pane
// must then drop that LINE rather than print a negative number, and drop
// only that one.
QTemporaryDir dir;
QVERIFY(dir.isValid());
Config config;
config.load(writeFolderConfig(dir, {
{QStringLiteral("webmail-primary"), QStringLiteral("Sent"),
QStringLiteral("Drafts")},
}));
MainWindow window(config);
const QStringList queries = window.placeholderQueriesForTesting();
QVector<int> counts;
for (int i = 0; i < queries.size(); ++i)
counts.append(i == 0 ? -1 : (i + 1) * 10);
QMetaObject::invokeMethod(&window, "onCountsReady",
Q_ARG(QVector<int>, counts),
Q_ARG(quint64, window.countsGenerationForTesting()));
const QList<HtmlBuilder::PlaceholderHelper> helpers =
window.placeholderHelpersForTesting();
QVERIFY(labelForQuery(helpers, queries.at(0)).isNull());
for (int i = 1; i < queries.size(); ++i) {
QVERIFY2(!labelForQuery(helpers, queries.at(i)).isNull(),
qPrintable(QStringLiteral("an uncountable query took '%1' "
"down with it").arg(queries.at(i))));
}
}
void TestMainWindow::flatModeDoesNotSurviveTheNextQuery()
{
// The condition the user set for this feature: a flat Sent list is fine, a
// flat anything-else is not. Asserted at the window rather than the model,
// because the leak this guards against is in the WIRING, not in the model:
// setFlatMode(true) from the button with no matching false anywhere else
// passes every model test and flattens the app from the first Sent click
// until it restarts.
QTemporaryDir dir;
QVERIFY(dir.isValid());
Config config;
config.load(writeSentConfig(dir, {
{QStringLiteral("webmail-primary"), QStringLiteral("Sent")},
}));
MainWindow window(config);
auto *model = window.findChild<ThreadListModel *>();
QVERIFY(model);
auto *button = window.findChild<QPushButton *>(QStringLiteral("sentButton"));
QVERIFY(button);
auto *queryEdit = window.findChild<QLineEdit *>(QStringLiteral("queryEdit"));
QVERIFY(queryEdit);
QVERIFY2(!model->flatMode(), "the model starts flat");
button->click();
QVERIFY2(model->flatMode(), "the Sent button did not flatten the list");
// Any other query restores the tree. Typed by hand rather than through a
// saved-query button, since that is the route with no flag of its own and
// therefore the one most likely to be forgotten.
queryEdit->setText(QStringLiteral("tag:inbox"));
QMetaObject::invokeMethod(&window, "runCurrentQuery");
QVERIFY2(!model->flatMode(),
"flat mode survived into an ordinary query, so every view after "
"one Sent click lost its replies");
// And back, so the button still works after the round trip.
button->click();
QVERIFY(model->flatMode());
// Even the SAME query typed by hand comes back as a tree: the flag follows
// the button, not the text, which is the rule the user chose.
queryEdit->setText(config.allSentQuery());
QMetaObject::invokeMethod(&window, "runCurrentQuery");
QVERIFY(!model->flatMode());
}
void TestMainWindow::noTwoActionsShareAnIcon()
{
// Reported by the user against the icons shipped in 0.12.0: Archive and
// Mark all read both used `mail-mark-read`. With the toolbar following a
// desktop set to icon-only, the icon is the entire control, so two buttons
// with different consequences were indistinguishable.
//
// Asserted over every action rather than that one pair, because the defect
// is the class and not the instance: the icon table is hand-written and
// twenty-four entries long, so the next duplicate is a plausible typo.
//
// Compared by cacheKey() rather than by the theme NAME, which this window
// does not keep. Two distinct names that resolve to the same art on a given
// theme are just as ambiguous on screen, and that is what the user sees.
const Config config;
MainWindow window(config);
QHash<qint64, QString> owners;
QStringList collisions;
int withIcons = 0;
for (const QString &name : KeyMap::knownActions()) {
auto *action = window.findChild<QAction *>(name);
QVERIFY2(action, qPrintable(QStringLiteral("no action named %1").arg(name)));
if (action->icon().isNull())
continue;
++withIcons;
const qint64 key = action->icon().cacheKey();
const auto existing = owners.constFind(key);
if (existing != owners.constEnd()) {
collisions.append(QStringLiteral("%1 and %2")
.arg(existing.value(), name));
} else {
owners.insert(key, name);
}
}
// The guard. On a theme that resolves nothing every icon is null, the loop
// body never runs, and the assertion below would pass having compared
// nothing at all.
QVERIFY2(withIcons >= KeyMap::knownActions().size(),
qPrintable(QStringLiteral("only %1 of %2 actions had an icon to "
"compare")
.arg(withIcons)
.arg(KeyMap::knownActions().size())));
QVERIFY2(collisions.isEmpty(),
qPrintable(QStringLiteral("actions sharing one icon: %1")
.arg(collisions.join(QStringLiteral("; ")))));
}
// Constructing a MainWindow needs a QApplication and a platform plugin. The
// test has no display under ctest, so it runs offscreen unless the caller
// asked for something else.
int main(int argc, char *argv[])
{
qputenv("QT_QPA_PLATFORM", qgetenv("QT_QPA_PLATFORM").isEmpty()
? QByteArray("offscreen")
: qgetenv("QT_QPA_PLATFORM"));
QApplication app(argc, argv);
TestMainWindow test;
return QTest::qExec(&test, argc, argv);
}
#include "test_mainwindow.moc"
|