aboutsummaryrefslogtreecommitdiffstats
path: root/mail/message-list.c
blob: 8bd77907d9b7e78817614600f35d5757efb0c088 (plain) (blame)
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
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
/*
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) version 3.
 *
 * 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with the program; if not, see <http://www.gnu.org/licenses/>
 *
 *
 * Authors:
 *      Miguel de Icaza (miguel@ximian.com)
 *      Bertrand Guiheneuf (bg@aful.org)
 *      And just about everyone else in evolution ...
 *
 * Copyright (C) 1999-2008 Novell, Inc. (www.novell.com)
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "message-list.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <string.h>
#include <ctype.h>

#include <glib/gi18n.h>
#include <glib/gstdio.h>

#include "libemail-engine/e-mail-utils.h"
#include "libemail-engine/mail-config.h"
#include "libemail-engine/mail-mt.h"
#include "libemail-engine/mail-ops.h"
#include "libemail-engine/mail-tools.h"

#include "e-mail-label-list-store.h"
#include "e-mail-ui-session.h"
#include "em-utils.h"

/*#define TIMEIT */

#ifdef TIMEIT
#include <sys/time.h>
#include <unistd.h>
#endif

#ifdef G_OS_WIN32
#ifdef gmtime_r
#undef gmtime_r
#endif
#ifdef localtime_r
#undef localtime_r
#endif

/* The gmtime() and localtime() in Microsoft's C library are MT-safe */
#define gmtime_r(tp,tmp) (gmtime(tp)?(*(tmp)=*gmtime(tp),(tmp)):0)
#define localtime_r(tp,tmp) (localtime(tp)?(*(tmp)=*localtime(tp),(tmp)):0)
#endif

#define d(x)
#define t(x)

#define MESSAGE_LIST_GET_PRIVATE(obj) \
    (G_TYPE_INSTANCE_GET_PRIVATE \
    ((obj), MESSAGE_LIST_TYPE, MessageListPrivate))

/* Common search expression segments. */
#define EXCLUDE_DELETED_MESSAGES_EXPR   "(not (system-flag \"deleted\"))"
#define EXCLUDE_JUNK_MESSAGES_EXPR  "(not (system-flag \"junk\"))"

typedef struct _RegenData RegenData;

struct _MLSelection {
    GPtrArray *uids;
    CamelFolder *folder;
};

struct _MessageListPrivate {
    GtkWidget *invisible;   /* 4 selection */

    EMailSession *session;

    CamelFolder *folder;
    gulong folder_changed_handler_id;

    /* For message list regeneration. */
    GMutex regen_lock;
    RegenData *regen_data;
    guint regen_timeout_id;

    struct _MLSelection clipboard;
    gboolean destroyed;

    gboolean show_deleted;
    gboolean thread_latest;
    gboolean thread_subject;
    gboolean any_row_changed; /* save state before regen list when this is set to true */

    GtkTargetList *copy_target_list;
    GtkTargetList *paste_target_list;

    /* This aids in automatic message selection. */
    time_t newest_read_date;
    const gchar *newest_read_uid;
    time_t oldest_unread_date;
    const gchar *oldest_unread_uid;
};

struct _RegenData {
    volatile gint ref_count;

    EActivity *activity;
    MessageList *message_list;

    gchar *search;

    gboolean threaded;
    gboolean thread_subject;
    CamelFolderThread *tree;

    /* This indicates we're regenerating the message list because
     * we received a "folder-changed" signal from our CamelFolder. */
    gboolean folder_changed;

    CamelFolder *folder;
    GPtrArray *summary;

    gint last_row; /* last selected (cursor) row */

    xmlDoc *expand_state; /* expanded state to be restored */

    /* These may be set during a regen operation.  Use the
     * select_lock to ensure consistency and thread-safety.
     * These are applied after the operation is finished. */
    GMutex select_lock;
    gchar *select_uid;
    gboolean select_all;
    gboolean select_use_fallback;
};

enum {
    PROP_0,
    PROP_COPY_TARGET_LIST,
    PROP_FOLDER,
    PROP_PASTE_TARGET_LIST,
    PROP_SESSION,
    PROP_SHOW_DELETED,
    PROP_THREAD_LATEST,
    PROP_THREAD_SUBJECT
};

/* Forward Declarations */
static void message_list_selectable_init
                    (ESelectableInterface *interface);

G_DEFINE_TYPE_WITH_CODE (
    MessageList,
    message_list,
    E_TYPE_TREE,
    G_IMPLEMENT_INTERFACE (
        E_TYPE_EXTENSIBLE, NULL)
    G_IMPLEMENT_INTERFACE (
        E_TYPE_SELECTABLE,
        message_list_selectable_init))

static struct {
    const gchar *target;
    GdkAtom atom;
    guint32 actions;
} ml_drag_info[] = {
    { "x-uid-list", NULL, GDK_ACTION_MOVE | GDK_ACTION_COPY },
    { "message/rfc822", NULL, GDK_ACTION_COPY },
    { "text/uri-list", NULL, GDK_ACTION_COPY },
};

enum {
    DND_X_UID_LIST,     /* x-uid-list */
    DND_MESSAGE_RFC822, /* message/rfc822 */
    DND_TEXT_URI_LIST   /* text/uri-list */
};

/* What we send */
static GtkTargetEntry ml_drag_types[] = {
    { (gchar *) "x-uid-list", 0, DND_X_UID_LIST },
    { (gchar *) "text/uri-list", 0, DND_TEXT_URI_LIST },
};

/* What we accept */
static GtkTargetEntry ml_drop_types[] = {
    { (gchar *) "x-uid-list", 0, DND_X_UID_LIST },
    { (gchar *) "message/rfc822", 0, DND_MESSAGE_RFC822 },
    { (gchar *) "text/uri-list", 0, DND_TEXT_URI_LIST },
};

/*
 * Default sizes for the ETable display
 *
 */
#define N_CHARS(x) (CHAR_WIDTH * (x))

#define COL_ICON_WIDTH         (16)
#define COL_ATTACH_WIDTH       (16)
#define COL_CHECK_BOX_WIDTH    (16)
#define COL_FROM_EXPANSION     (24.0)
#define COL_FROM_WIDTH_MIN     (32)
#define COL_SUBJECT_EXPANSION  (30.0)
#define COL_SUBJECT_WIDTH_MIN  (32)
#define COL_SENT_EXPANSION     (24.0)
#define COL_SENT_WIDTH_MIN     (32)
#define COL_RECEIVED_EXPANSION (20.0)
#define COL_RECEIVED_WIDTH_MIN (32)
#define COL_TO_EXPANSION       (24.0)
#define COL_TO_WIDTH_MIN       (32)
#define COL_SIZE_EXPANSION     (6.0)
#define COL_SIZE_WIDTH_MIN     (32)
#define COL_SENDER_EXPANSION     (24.0)
#define COL_SENDER_WIDTH_MIN     (32)

enum {
    NORMALISED_SUBJECT,
    NORMALISED_FROM,
    NORMALISED_TO,
    NORMALISED_LAST
};

static void on_cursor_activated_cmd (ETree *tree, gint row, ETreePath path, gpointer user_data);
static void on_selection_changed_cmd (ETree *tree, MessageList *ml);
static gint on_click (ETree *tree, gint row, ETreePath path, gint col, GdkEvent *event, MessageList *list);
static gchar *filter_date (time_t date);
static gchar *filter_size (gint size);

static void mail_regen_list (MessageList *ml, const gchar *search, gboolean folder_changed);
static void mail_regen_cancel (MessageList *ml);

static void clear_info (gchar *key, ETreePath *node, MessageList *ml);

enum {
    MESSAGE_SELECTED,
    MESSAGE_LIST_BUILT,
    LAST_SIGNAL
};

static guint message_list_signals[LAST_SIGNAL] = {0, };

static const gchar *status_icons[] = {
    "mail-unread",
    "mail-read",
    "mail-replied",
    "mail-forward",
    "stock_mail-unread-multiple",
    "stock_mail-open-multiple"
};

static const gchar *score_icons[] = {
    "stock_score-lowest",
    "stock_score-lower",
    "stock_score-low",
    "stock_score-normal",
    "stock_score-high",
    "stock_score-higher",
    "stock_score-highest"
};

static const gchar *attachment_icons[] = {
    NULL,  /* empty icon */
    "mail-attachment",
    "stock_new-meeting"
};

static const gchar *flagged_icons[] = {
    NULL,  /* empty icon */
    "emblem-important"
};

static const gchar *followup_icons[] = {
    NULL,  /* empty icon */
    "stock_mail-flag-for-followup",
    "stock_mail-flag-for-followup-done"
};

static RegenData *
regen_data_new (MessageList *message_list,
                GCancellable *cancellable)
{
    RegenData *regen_data;
    EActivity *activity;
    EMailSession *session;

    activity = e_activity_new ();
    e_activity_set_cancellable (activity, cancellable);
    e_activity_set_text (activity, _("Generating message list"));

    regen_data = g_slice_new0 (RegenData);
    regen_data->ref_count = 1;
    regen_data->activity = g_object_ref (activity);
    regen_data->message_list = g_object_ref (message_list);
    regen_data->last_row = -1;

    /* Capture MessageList state to use for this regen. */
    regen_data->folder = message_list_ref_folder (message_list);
    regen_data->threaded = message_list->threaded;
    regen_data->thread_subject =
        message_list_get_thread_subject (message_list);

    g_mutex_init (&regen_data->select_lock);

    session = message_list_get_session (message_list);
    e_mail_ui_session_add_activity (E_MAIL_UI_SESSION (session), activity);

    g_object_unref (activity);

    return regen_data;
}

static RegenData *
regen_data_ref (RegenData *regen_data)
{
    g_return_val_if_fail (regen_data != NULL, NULL);
    g_return_val_if_fail (regen_data->ref_count > 0, NULL);

    g_atomic_int_inc (&regen_data->ref_count);

    return regen_data;
}

static void
regen_data_unref (RegenData *regen_data)
{
    g_return_if_fail (regen_data != NULL);
    g_return_if_fail (regen_data->ref_count > 0);

    if (g_atomic_int_dec_and_test (&regen_data->ref_count)) {

        g_clear_object (&regen_data->activity);
        g_clear_object (&regen_data->message_list);

        g_free (regen_data->search);

        if (regen_data->tree != NULL)
            camel_folder_thread_messages_unref (regen_data->tree);

        if (regen_data->summary != NULL) {
            guint ii, length;

            length = regen_data->summary->len;

            for (ii = 0; ii < length; ii++)
                camel_folder_free_message_info (
                    regen_data->folder,
                    regen_data->summary->pdata[ii]);

            g_ptr_array_free (regen_data->summary, TRUE);
        }

        g_clear_object (&regen_data->folder);

        if (regen_data->expand_state != NULL)
            xmlFreeDoc (regen_data->expand_state);

        g_mutex_clear (&regen_data->select_lock);
        g_free (regen_data->select_uid);

        g_slice_free (RegenData, regen_data);
    }
}

static RegenData *
message_list_ref_regen_data (MessageList *message_list)
{
    RegenData *regen_data = NULL;

    g_mutex_lock (&message_list->priv->regen_lock);

    if (message_list->priv->regen_data != NULL)
        regen_data = regen_data_ref (message_list->priv->regen_data);

    g_mutex_unlock (&message_list->priv->regen_lock);

    return regen_data;
}

static gint
address_compare (gconstpointer address1,
                 gconstpointer address2,
                 gpointer cmp_cache)
{
    gint retval;

    g_return_val_if_fail (address1 != NULL, 1);
    g_return_val_if_fail (address2 != NULL, -1);

    retval = g_ascii_strcasecmp ((gchar *) address1, (gchar *) address2);

    return retval;
}

static gchar *
filter_size (gint size)
{
    gfloat fsize;

    if (size < 1024) {
        return g_strdup_printf ("%d", size);
    } else {
        fsize = ((gfloat) size) / 1024.0;
        if (fsize < 1024.0) {
            return g_strdup_printf ("%.2f K", fsize);
        } else {
            fsize /= 1024.0;
            return g_strdup_printf ("%.2f M", fsize);
        }
    }
}

/* Gets the uid of the message displayed at a given view row */
static const gchar *
get_message_uid (MessageList *message_list,
                 ETreePath node)
{
    CamelMessageInfo *info;

    g_return_val_if_fail (node != NULL, NULL);
    info = e_tree_memory_node_get_data (E_TREE_MEMORY (message_list->model), node);
    /* correct me if I'm wrong, but this should never be NULL, should it? */
    g_return_val_if_fail (info != NULL, NULL);

    return camel_message_info_uid (info);
}

/* Gets the CamelMessageInfo for the message displayed at the given
 * view row.
 */
static CamelMessageInfo *
get_message_info (MessageList *message_list,
                  ETreePath node)
{
    CamelMessageInfo *info;

    g_return_val_if_fail (node != NULL, NULL);
    info = e_tree_memory_node_get_data (E_TREE_MEMORY (message_list->model), node);
    g_return_val_if_fail (info != NULL, NULL);

    return info;
}

static const gchar *
get_normalised_string (MessageList *message_list,
                       CamelMessageInfo *info,
                       gint col)
{
    const gchar *string, *str;
    gchar *normalised;
    EPoolv *poolv;
    gint index;

    switch (col) {
    case COL_SUBJECT_NORM:
        string = camel_message_info_subject (info);
        index = NORMALISED_SUBJECT;
        break;
    case COL_FROM_NORM:
        string = camel_message_info_from (info);
        index = NORMALISED_FROM;
        break;
    case COL_TO_NORM:
        string = camel_message_info_to (info);
        index = NORMALISED_TO;
        break;
    default:
        string = NULL;
        index = NORMALISED_LAST;
        g_warning ("Should not be reached\n");
    }

    /* slight optimisation */
    if (string == NULL || string[0] == '\0')
        return "";

    poolv = g_hash_table_lookup (message_list->normalised_hash, camel_message_info_uid (info));
    if (poolv == NULL) {
        poolv = e_poolv_new (NORMALISED_LAST);
        g_hash_table_insert (message_list->normalised_hash, (gchar *) camel_message_info_uid (info), poolv);
    } else {
        str = e_poolv_get (poolv, index);
        if (*str)
            return str;
    }

    if (col == COL_SUBJECT_NORM) {
        gint skip_len;
        const gchar *subject;
        gboolean found_re = TRUE;

        subject = string;
        while (found_re) {
            found_re = em_utils_is_re_in_subject (
                subject, &skip_len) && skip_len > 0;
            if (found_re)
                subject += skip_len;

            /* jump over any spaces */
            while (*subject && isspace ((gint) *subject))
                subject++;
        }

        /* jump over any spaces */
        while (*subject && isspace ((gint) *subject))
            subject++;

        string = subject;
        normalised = g_utf8_collate_key (string, -1);
    } else {
        /* because addresses require strings, not collate keys */
        normalised = g_strdup (string);
    }

    e_poolv_set (poolv, index, normalised, TRUE);

    return e_poolv_get (poolv, index);
}

static void
clear_selection (MessageList *ml,
                 struct _MLSelection *selection)
{
    if (selection->uids) {
        em_utils_uids_free (selection->uids);
        selection->uids = NULL;
    }
    if (selection->folder) {
        g_object_unref (selection->folder);
        selection->folder = NULL;
    }
}

static ETreePath
ml_search_forward (MessageList *ml,
                   gint start,
                   gint end,
                   guint32 flags,
                   guint32 mask)
{
    ETreePath path;
    gint row;
    CamelMessageInfo *info;
    ETreeTableAdapter *etta;

    etta = e_tree_get_table_adapter (E_TREE (ml));

    for (row = start; row <= end; row++) {
        path = e_tree_table_adapter_node_at_row (etta, row);
        if (path
            && (info = get_message_info (ml, path))
            && (camel_message_info_flags (info) & mask) == flags)
            return path;
    }

    return NULL;
}

static ETreePath
ml_search_backward (MessageList *ml,
                    gint start,
                    gint end,
                    guint32 flags,
                    guint32 mask)
{
    ETreePath path;
    gint row;
    CamelMessageInfo *info;
    ETreeTableAdapter *etta;

    etta = e_tree_get_table_adapter (E_TREE (ml));

    for (row = start; row >= end; row--) {
        path = e_tree_table_adapter_node_at_row (etta, row);
        if (path
            && (info = get_message_info (ml, path))
            && (camel_message_info_flags (info) & mask) == flags)
            return path;
    }

    return NULL;
}

static ETreePath
ml_search_path (MessageList *ml,
                MessageListSelectDirection direction,
                guint32 flags,
                guint32 mask)
{
    ETreePath node;
    gint row, count;
    ETreeTableAdapter *etta;

    etta = e_tree_get_table_adapter (E_TREE (ml));

    if (ml->cursor_uid == NULL
        || (node = g_hash_table_lookup (ml->uid_nodemap, ml->cursor_uid)) == NULL)
        return NULL;

    row = e_tree_table_adapter_row_of_node (etta, node);
    if (row == -1)
        return NULL;
    count = e_table_model_row_count ((ETableModel *) etta);

    if ((direction & MESSAGE_LIST_SELECT_DIRECTION) == MESSAGE_LIST_SELECT_NEXT)
        node = ml_search_forward (ml, row + 1, count - 1, flags, mask);
    else
        node = ml_search_backward (ml, row - 1, 0, flags, mask);

    if (node == NULL && (direction & MESSAGE_LIST_SELECT_WRAP)) {
        if ((direction & MESSAGE_LIST_SELECT_DIRECTION) == MESSAGE_LIST_SELECT_NEXT)
            node = ml_search_forward (ml, 0, row, flags, mask);
        else
            node = ml_search_backward (ml, count - 1, row, flags, mask);
    }

    return node;
}

static void
select_path (MessageList *ml,
             ETreePath path)
{
    ETree *tree;
    ETreeTableAdapter *etta;
    ETreeSelectionModel *etsm;

    tree = E_TREE (ml);
    etta = e_tree_get_table_adapter (tree);
    etsm = (ETreeSelectionModel *) e_tree_get_selection_model (tree);

    g_free (ml->cursor_uid);
    ml->cursor_uid = NULL;

    e_tree_table_adapter_show_node (etta, path);
    e_tree_set_cursor (tree, path);
    e_tree_selection_model_select_single_path (etsm, path);
}

/**
 * message_list_select:
 * @message_list: a MessageList
 * @direction: the direction to search in
 * @flags: a set of flag values
 * @mask: a mask for comparing against @flags
 *
 * This moves the message list selection to a suitable row. @flags and
 * @mask combine to specify what constitutes a suitable row. @direction is
 * %MESSAGE_LIST_SELECT_NEXT if it should find the next matching
 * message, or %MESSAGE_LIST_SELECT_PREVIOUS if it should find the
 * previous. %MESSAGE_LIST_SELECT_WRAP is an option bit which specifies the
 * search should wrap.
 *
 * If no suitable row is found, the selection will be
 * unchanged.
 *
 * Returns %TRUE if a new message has been selected or %FALSE otherwise.
 **/
gboolean
message_list_select (MessageList *ml,
                     MessageListSelectDirection direction,
                     guint32 flags,
                     guint32 mask)
{
    ETreePath path;

    path = ml_search_path (ml, direction, flags, mask);
    if (path) {
        select_path (ml, path);

        /* This function is usually called in response to a key
         * press, so grab focus if the message list is visible. */
        if (gtk_widget_get_visible (GTK_WIDGET (ml)))
            gtk_widget_grab_focus (GTK_WIDGET (ml));

        return TRUE;
    } else
        return FALSE;
}

/**
 * message_list_can_select:
 * @ml:
 * @direction:
 * @flags:
 * @mask:
 *
 * Returns true if the selection specified is possible with the current view.
 *
 * Return value:
 **/
gboolean
message_list_can_select (MessageList *ml,
                         MessageListSelectDirection direction,
                         guint32 flags,
                         guint32 mask)
{
    return ml_search_path (ml, direction, flags, mask) != NULL;
}

/**
 * message_list_select_uid:
 * @message_list:
 * @uid:
 *
 * Selects the message with the given UID.
 **/
void
message_list_select_uid (MessageList *message_list,
                         const gchar *uid,
                         gboolean with_fallback)
{
    MessageListPrivate *priv;
    GHashTable *uid_nodemap;
    ETreePath node = NULL;
    RegenData *regen_data = NULL;

    g_return_if_fail (IS_MESSAGE_LIST (message_list));

    priv = message_list->priv;
    uid_nodemap = message_list->uid_nodemap;

    if (message_list->priv->folder == NULL)
        return;

    /* Try to find the requested message UID. */
    if (uid != NULL)
        node = g_hash_table_lookup (uid_nodemap, uid);

    regen_data = message_list_ref_regen_data (message_list);

    /* If we're busy or waiting to regenerate the message list, cache
     * the UID so we can try again when we're done.  Otherwise if the
     * requested message UID was not found and 'with_fallback' is set,
     * try a couple fallbacks:
     *
     * 1) Oldest unread message in the list, by date received.
     * 2) Newest read message in the list, by date received.
     */
    if (regen_data != NULL) {
        g_mutex_lock (&regen_data->select_lock);
        g_free (regen_data->select_uid);
        regen_data->select_uid = g_strdup (uid);
        regen_data->select_use_fallback = with_fallback;
        g_mutex_unlock (&regen_data->select_lock);

        regen_data_unref (regen_data);

    } else if (with_fallback) {
        if (node == NULL && priv->oldest_unread_uid != NULL)
            node = g_hash_table_lookup (
                uid_nodemap, priv->oldest_unread_uid);
        if (node == NULL && priv->newest_read_uid != NULL)
            node = g_hash_table_lookup (
                uid_nodemap, priv->newest_read_uid);
    }

    if (node) {
        ETree *tree;
        ETreePath old_cur;

        tree = E_TREE (message_list);
        old_cur = e_tree_get_cursor (tree);

        /* This will emit a changed signal that we'll pick up */
        e_tree_set_cursor (tree, node);

        if (old_cur == node)
            g_signal_emit (
                message_list,
                message_list_signals[MESSAGE_SELECTED],
                0, message_list->cursor_uid);
    } else {
        g_free (message_list->cursor_uid);
        message_list->cursor_uid = NULL;
        g_signal_emit (
            message_list,
            message_list_signals[MESSAGE_SELECTED],
            0, NULL);
    }
}

void
message_list_select_next_thread (MessageList *ml)
{
    ETreePath node;
    ETreeTableAdapter *etta;
    gint i, count, row;

    etta = e_tree_get_table_adapter (E_TREE (ml));

    if (!ml->cursor_uid
        || (node = g_hash_table_lookup (ml->uid_nodemap, ml->cursor_uid)) == NULL)
        return;

    row = e_tree_table_adapter_row_of_node (etta, node);
    if (row == -1)
        return;
    count = e_table_model_row_count ((ETableModel *) etta);

    /* find the next node which has a root parent (i.e. toplevel node) */
    for (i = row + 1; i < count - 1; i++) {
        node = e_tree_table_adapter_node_at_row (etta, i);
        if (node
            && e_tree_model_node_is_root (ml->model, e_tree_model_node_get_parent (ml->model, node))) {
            select_path (ml, node);
            return;
        }
    }
}

void
message_list_select_prev_thread (MessageList *ml)
{
    ETreePath node;
    ETreeTableAdapter *etta;
    gint i, row;
    gboolean skip_first;

    etta = e_tree_get_table_adapter (E_TREE (ml));

    if (!ml->cursor_uid
        || (node = g_hash_table_lookup (ml->uid_nodemap, ml->cursor_uid)) == NULL)
        return;

    row = e_tree_table_adapter_row_of_node (etta, node);
    if (row == -1)
        return;

    /* skip first found if in the middle of the thread */
    skip_first = !e_tree_model_node_is_root (ml->model, e_tree_model_node_get_parent (ml->model, node));

    /* find the previous node which has a root parent (i.e. toplevel node) */
    for (i = row - 1; i >= 0; i--) {
        node = e_tree_table_adapter_node_at_row (etta, i);
        if (node
            && e_tree_model_node_is_root (ml->model, e_tree_model_node_get_parent (ml->model, node))) {
            if (skip_first) {
                skip_first = FALSE;
                continue;
            }

            select_path (ml, node);
            return;
        }
    }
}

/**
 * message_list_select_all:
 * @message_list: Message List widget
 *
 * Selects all messages in the message list.
 **/
void
message_list_select_all (MessageList *message_list)
{
    RegenData *regen_data = NULL;

    g_return_if_fail (IS_MESSAGE_LIST (message_list));

    regen_data = message_list_ref_regen_data (message_list);

    if (message_list->threaded && regen_data != NULL) {
        regen_data->select_all = TRUE;
    } else {
        ETree *tree;
        ESelectionModel *selection_model;

        tree = E_TREE (message_list);
        selection_model = e_tree_get_selection_model (tree);
        e_selection_model_select_all (selection_model);
    }

    if (regen_data != NULL)
        regen_data_unref (regen_data);
}

typedef struct thread_select_info {
    MessageList *ml;
    GPtrArray *paths;
} thread_select_info_t;

static gboolean
select_node (ETreeModel *model,
             ETreePath path,
             gpointer user_data)
{
    thread_select_info_t *tsi = (thread_select_info_t *) user_data;

    g_ptr_array_add (tsi->paths, path);
    return FALSE; /*not done yet */
}

static void
select_thread (MessageList *message_list,
               void (*selector) (ETreePath,
                                 gpointer))
{
    ETree *tree;
    ETreeSelectionModel *etsm;
    thread_select_info_t tsi;

    tsi.ml = message_list;
    tsi.paths = g_ptr_array_new ();

    tree = E_TREE (message_list);
    etsm = (ETreeSelectionModel *) e_tree_get_selection_model (tree);

    e_tree_selected_path_foreach (tree, selector, &tsi);

    e_tree_selection_model_select_paths (etsm, tsi.paths);

    g_ptr_array_free (tsi.paths, TRUE);
}

static void
thread_select_foreach (ETreePath path,
                       gpointer user_data)
{
    thread_select_info_t *tsi = (thread_select_info_t *) user_data;
    ETreeModel *model = tsi->ml->model;
    ETreePath node, last;

    node = path;

    do {
        last = node;
        node = e_tree_model_node_get_parent (model, node);
    } while (!e_tree_model_node_is_root (model, node));

    g_ptr_array_add (tsi->paths, last);

    e_tree_model_node_traverse (model, last, select_node, tsi);
}

/**
 * message_list_select_thread:
 * @message_list: Message List widget
 *
 * Selects all messages in the current thread (based on cursor).
 **/
void
message_list_select_thread (MessageList *message_list)
{
    select_thread (message_list, thread_select_foreach);
}

static void
subthread_select_foreach (ETreePath path,
                          gpointer user_data)
{
    thread_select_info_t *tsi = (thread_select_info_t *) user_data;
    ETreeModel *model = tsi->ml->model;

    e_tree_model_node_traverse (model, path, select_node, tsi);
}

/**
 * message_list_select_subthread:
 * @message_list: Message List widget
 *
 * Selects all messages in the current subthread (based on cursor).
 **/
void
message_list_select_subthread (MessageList *message_list)
{
    select_thread (message_list, subthread_select_foreach);
}

/**
 * message_list_invert_selection:
 * @message_list: Message List widget
 *
 * Invert the current selection in the message-list.
 **/
void
message_list_invert_selection (MessageList *message_list)
{
    ESelectionModel *etsm;

    etsm = e_tree_get_selection_model (E_TREE (message_list));

    e_selection_model_invert_selection (etsm);
}

void
message_list_copy (MessageList *ml,
                   gboolean cut)
{
    MessageListPrivate *p = ml->priv;
    GPtrArray *uids;

    clear_selection (ml, &p->clipboard);

    uids = message_list_get_selected (ml);

    if (uids->len > 0) {
        if (cut) {
            CamelFolder *folder;
            gint i;

            folder = message_list_ref_folder (ml);

            camel_folder_freeze (folder);

            for (i = 0; i < uids->len; i++)
                camel_folder_set_message_flags (
                    folder, uids->pdata[i],
                    CAMEL_MESSAGE_SEEN |
                    CAMEL_MESSAGE_DELETED,
                    CAMEL_MESSAGE_SEEN |
                    CAMEL_MESSAGE_DELETED);

            camel_folder_thaw (folder);

            g_object_unref (folder);
        }

        p->clipboard.uids = uids;
        p->clipboard.folder = message_list_ref_folder (ml);
        gtk_selection_owner_set (p->invisible, GDK_SELECTION_CLIPBOARD, gtk_get_current_event_time ());
    } else {
        em_utils_uids_free (uids);
        gtk_selection_owner_set (NULL, GDK_SELECTION_CLIPBOARD, gtk_get_current_event_time ());
    }
}

void
message_list_paste (MessageList *ml)
{
    gtk_selection_convert (
        ml->priv->invisible, GDK_SELECTION_CLIPBOARD,
        gdk_atom_intern ("x-uid-list", FALSE),
        GDK_CURRENT_TIME);
}

/*
 * SimpleTableModel::col_count
 */
static gint
ml_column_count (ETreeModel *etm,
                 gpointer data)
{
    return COL_LAST;
}

/*
 * SimpleTableModel::has_save_id
 */
static gboolean
ml_has_save_id (ETreeModel *etm,
                gpointer data)
{
    return TRUE;
}

/*
 * SimpleTableModel::get_save_id
 */
static gchar *
ml_get_save_id (ETreeModel *etm,
                ETreePath path,
                gpointer data)
{
    CamelMessageInfo *info;

    if (e_tree_model_node_is_root (etm, path))
        return g_strdup ("root");

    /* Note: etable can ask for the save_id while we're clearing it,
     * which is the only time data should be null */
    info = e_tree_memory_node_get_data (E_TREE_MEMORY (etm), path);
    if (info == NULL)
        return NULL;

    return g_strdup (camel_message_info_uid (info));
}

/*
 * SimpleTableModel::has_save_id
 */
static gboolean
ml_has_get_node_by_id (ETreeModel *etm,
                       gpointer data)
{
    return TRUE;
}

/*
 * SimpleTableModel::get_save_id
 */
static ETreePath
ml_get_node_by_id (ETreeModel *etm,
                   const gchar *save_id,
                   gpointer data)
{
    MessageList *ml;

    ml = data;

    if (!strcmp (save_id, "root"))
        return e_tree_model_get_root (etm);

    return g_hash_table_lookup (ml->uid_nodemap, save_id);
}

static gpointer
ml_duplicate_value (ETreeModel *etm,
                    gint col,
                    gconstpointer value,
                    gpointer data)
{
    switch (col) {
    case COL_MESSAGE_STATUS:
    case COL_FLAGGED:
    case COL_SCORE:
    case COL_ATTACHMENT:
    case COL_DELETED:
    case COL_UNREAD:
    case COL_SENT:
    case COL_RECEIVED:
    case COL_SIZE:
    case COL_FOLLOWUP_FLAG_STATUS:
    case COL_FOLLOWUP_DUE_BY:
        return (gpointer) value;

    case COL_FROM:
    case COL_SUBJECT:
    case COL_TO:
    case COL_SENDER:
    case COL_RECIPIENTS:
    case COL_MIXED_SENDER:
    case COL_MIXED_RECIPIENTS:
    case COL_FOLLOWUP_FLAG:
    case COL_LOCATION:
    case COL_LABELS:
        return g_strdup (value);
    default:
        g_warning ("This shouldn't be reached\n");
    }
    return NULL;
}

static void
ml_free_value (ETreeModel *etm,
               gint col,
               gpointer value,
               gpointer data)
{
    switch (col) {
    case COL_MESSAGE_STATUS:
    case COL_FLAGGED:
    case COL_SCORE:
    case COL_ATTACHMENT:
    case COL_DELETED:
    case COL_UNREAD:
    case COL_SENT:
    case COL_RECEIVED:
    case COL_SIZE:
    case COL_FOLLOWUP_FLAG_STATUS:
    case COL_FOLLOWUP_DUE_BY:
    case COL_FROM_NORM:
    case COL_SUBJECT_NORM:
    case COL_TO_NORM:
    case COL_SUBJECT_TRIMMED:
    case COL_COLOUR:
        break;

    case COL_FROM:
    case COL_SUBJECT:
    case COL_TO:
    case COL_FOLLOWUP_FLAG:
    case COL_LOCATION:
    case COL_SENDER:
    case COL_RECIPIENTS:
    case COL_MIXED_SENDER:
    case COL_MIXED_RECIPIENTS:
    case COL_LABELS:
        g_free (value);
        break;
    default:
        g_warning ("%s: This shouldn't be reached (col:%d)", G_STRFUNC, col);
    }
}

static gpointer
ml_initialize_value (ETreeModel *etm,
                     gint col,
                     gpointer data)
{
    switch (col) {
    case COL_MESSAGE_STATUS:
    case COL_FLAGGED:
    case COL_SCORE:
    case COL_ATTACHMENT:
    case COL_DELETED:
    case COL_UNREAD:
    case COL_SENT:
    case COL_RECEIVED:
    case COL_SIZE:
    case COL_FOLLOWUP_FLAG_STATUS:
    case COL_FOLLOWUP_DUE_BY:
        return NULL;

    case COL_FROM:
    case COL_SUBJECT:
    case COL_TO:
    case COL_FOLLOWUP_FLAG:
    case COL_LOCATION:
    case COL_SENDER:
    case COL_RECIPIENTS:
    case COL_MIXED_SENDER:
    case COL_MIXED_RECIPIENTS:
    case COL_LABELS:
        return g_strdup ("");
    default:
        g_warning ("This shouldn't be reached\n");
    }

    return NULL;
}

static gboolean
ml_value_is_empty (ETreeModel *etm,
                   gint col,
                   gconstpointer value,
                   gpointer data)
{
    switch (col) {
    case COL_MESSAGE_STATUS:
    case COL_FLAGGED:
    case COL_SCORE:
    case COL_ATTACHMENT:
    case COL_DELETED:
    case COL_UNREAD:
    case COL_SENT:
    case COL_RECEIVED:
    case COL_SIZE:
    case COL_FOLLOWUP_FLAG_STATUS:
    case COL_FOLLOWUP_DUE_BY:
        return value == NULL;

    case COL_FROM:
    case COL_SUBJECT:
    case COL_TO:
    case COL_FOLLOWUP_FLAG:
    case COL_LOCATION:
    case COL_SENDER:
    case COL_RECIPIENTS:
    case COL_MIXED_SENDER:
    case COL_MIXED_RECIPIENTS:
    case COL_LABELS:
        return !(value && *(gchar *) value);
    default:
        g_warning ("This shouldn't be reached\n");
        return FALSE;
    }
}

static const gchar *status_map[] = {
    N_("Unseen"),
    N_("Seen"),
    N_("Answered"),
    N_("Forwarded"),
    N_("Multiple Unseen Messages"),
    N_("Multiple Messages"),
};

static const gchar *score_map[] = {
    N_("Lowest"),
    N_("Lower"),
    N_("Low"),
    N_("Normal"),
    N_("High"),
    N_("Higher"),
    N_("Highest"),
};

static gchar *
ml_value_to_string (ETreeModel *etm,
                    gint col,
                    gconstpointer value,
                    gpointer data)
{
    guint i;

    switch (col) {
    case COL_MESSAGE_STATUS:
        i = GPOINTER_TO_UINT (value);
        if (i > 5)
            return g_strdup ("");
        return g_strdup (_(status_map[i]));

    case COL_SCORE:
        i = GPOINTER_TO_UINT (value) + 3;
        if (i > 6)
            i = 3;
        return g_strdup (_(score_map[i]));

    case COL_ATTACHMENT:
    case COL_FLAGGED:
    case COL_DELETED:
    case COL_UNREAD:
    case COL_FOLLOWUP_FLAG_STATUS:
        return g_strdup_printf ("%u", GPOINTER_TO_UINT (value));

    case COL_SENT:
    case COL_RECEIVED:
    case COL_FOLLOWUP_DUE_BY:
        return filter_date (GPOINTER_TO_INT (value));

    case COL_SIZE:
        return filter_size (GPOINTER_TO_INT (value));

    case COL_FROM:
    case COL_SUBJECT:
    case COL_TO:
    case COL_FOLLOWUP_FLAG:
    case COL_LOCATION:
    case COL_SENDER:
    case COL_RECIPIENTS:
    case COL_MIXED_SENDER:
    case COL_MIXED_RECIPIENTS:
    case COL_LABELS:
        return g_strdup (value);
    default:
        g_warning ("This shouldn't be reached\n");
        return NULL;
    }
}

static GdkPixbuf *
ml_tree_icon_at (ETreeModel *etm,
                 ETreePath path,
                 gpointer model_data)
{
    /* we dont really need an icon ... */
    return NULL;
}

static void
for_node_and_subtree_if_collapsed (MessageList *ml,
                                   ETreePath node,
                                   CamelMessageInfo *mi,
                                   ETreePathFunc func,
                                   gpointer data)
{
    ETreeModel *etm = ml->model;
    ETreePath child;

    func (NULL, (ETreePath) mi, data);

    if (!node)
        return;

    child = e_tree_model_node_get_first_child (etm, node);
    if (child && !e_tree_node_is_expanded (E_TREE (ml), node))
        e_tree_model_node_traverse (etm, node, func, data);
}

static gboolean
unread_foreach (ETreeModel *etm,
                ETreePath node,
                gpointer data)
{
    gboolean *saw_unread = data;
    CamelMessageInfo *info;

    if (!etm)
        info = (CamelMessageInfo *) node;
    else
        info = e_tree_memory_node_get_data ((ETreeMemory *) etm, node);
    g_return_val_if_fail (info != NULL, FALSE);

    if (!(camel_message_info_flags (info) & CAMEL_MESSAGE_SEEN))
        *saw_unread = TRUE;

    return FALSE;
}

struct LatestData {
    gboolean sent;
    time_t latest;
};

static gboolean
latest_foreach (ETreeModel *etm,
                ETreePath node,
                gpointer data)
{
    struct LatestData *ld = data;
    CamelMessageInfo *info;
    time_t date;

    if (!etm)
        info = (CamelMessageInfo *) node;
    else
        info = e_tree_memory_node_get_data ((ETreeMemory *) etm, node);
    g_return_val_if_fail (info != NULL, FALSE);

    date = ld->sent ? camel_message_info_date_sent (info)
            : camel_message_info_date_received (info);

    if (ld->latest == 0 || date > ld->latest)
        ld->latest = date;

    return FALSE;
}

static gchar *
sanitize_recipients (const gchar *string)
{
    GString     *gstring;
    gboolean     quoted = FALSE;
    const gchar *p;
    GString *recipients = g_string_new ("");
    gchar *single_add;
    gchar **name;

    if (!string || !*string)
        return (gchar *) "";

    gstring = g_string_new ("");

    for (p = string; *p; p = g_utf8_next_char (p)) {
        gunichar c = g_utf8_get_char (p);

        if (c == '"')
            quoted = ~quoted;
        else if (c == ',' && !quoted) {
            single_add = g_string_free (gstring, FALSE);
            name = g_strsplit (single_add,"<",2);
            g_string_append (recipients, *name);
            g_string_append (recipients, ",");
            g_free (single_add);
            g_strfreev (name);
            gstring = g_string_new ("");
            continue;
        }

        g_string_append_unichar (gstring, c);
    }

    single_add = g_string_free (gstring, FALSE);
    name = g_strsplit (single_add,"<",2);
    g_string_append (recipients, *name);
    g_free (single_add);
    g_strfreev (name);

    return g_string_free (recipients, FALSE);
}

struct LabelsData {
    EMailLabelListStore *store;
    GHashTable *labels_tag2iter;
};

static void
add_label_if_known (struct LabelsData *ld,
                    const gchar *tag)
{
    GtkTreeIter label_defn;

    if (e_mail_label_list_store_lookup (ld->store, tag, &label_defn)) {
        g_hash_table_insert (
            ld->labels_tag2iter,
            /* Should be the same as the "tag" arg */
            e_mail_label_list_store_get_tag (ld->store, &label_defn),
            gtk_tree_iter_copy (&label_defn));
    }
}

static gboolean
add_all_labels_foreach (ETreeModel *etm,
                        ETreePath node,
                        gpointer data)
{
    struct LabelsData *ld = data;
    CamelMessageInfo *msg_info;
    const gchar *old_label;
    gchar *new_label;
    const CamelFlag *flag;

    if (!etm)
        msg_info = (CamelMessageInfo *) node;
    else
        msg_info = e_tree_memory_node_get_data ((ETreeMemory *) etm, node);
    g_return_val_if_fail (msg_info != NULL, FALSE);

    for (flag = camel_message_info_user_flags (msg_info); flag; flag = flag->next)
        add_label_if_known (ld, flag->name);

    old_label = camel_message_info_user_tag (msg_info, "label");
    if (old_label != NULL) {
        /* Convert old-style labels ("<name>") to "$Label<name>". */
        new_label = g_alloca (strlen (old_label) + 10);
        g_stpcpy (g_stpcpy (new_label, "$Label"), old_label);

        add_label_if_known (ld, new_label);
    }

    return FALSE;
}

static const gchar *
get_trimmed_subject (CamelMessageInfo *info)
{
    const gchar *subject;
    const gchar *mlist;
    gint mlist_len = 0;
    gboolean found_mlist;

    subject = camel_message_info_subject (info);
    if (!subject || !*subject)
        return subject;

    mlist = camel_message_info_mlist (info);

    if (mlist && *mlist) {
        const gchar *mlist_end;

        mlist_end = strchr (mlist, '@');
        if (mlist_end)
            mlist_len = mlist_end - mlist;
        else
            mlist_len = strlen (mlist);
    }

    do {
        gint skip_len;
        gboolean found_re = TRUE;

        found_mlist = FALSE;

        while (found_re) {
            found_re = FALSE;

            found_re = em_utils_is_re_in_subject (
                subject, &skip_len) && skip_len > 0;
            if (found_re)
                subject += skip_len;

            /* jump over any spaces */
            while (*subject && isspace ((gint) *subject))
                subject++;
        }

        if (mlist_len &&
            *subject == '[' &&
            !g_ascii_strncasecmp ((gchar *) subject + 1, mlist, mlist_len) &&
            subject[1 + mlist_len] == ']') {
            subject += 1 + mlist_len + 1;  /* jump over "[mailing-list]" */
            found_mlist = TRUE;

            /* jump over any spaces */
            while (*subject && isspace ((gint) *subject))
                subject++;
        }
    } while (found_mlist);

    /* jump over any spaces */
    while (*subject && isspace ((gint) *subject))
        subject++;

    return subject;
}

static gpointer
ml_tree_value_at_ex (ETreeModel *etm,
                     ETreePath path,
                     gint col,
                     CamelMessageInfo *msg_info,
                     MessageList *message_list)
{
    EMailSession *session;
    const gchar *str;
    guint32 flags;

    session = message_list_get_session (message_list);

    g_return_val_if_fail (msg_info != NULL, NULL);

    switch (col) {
    case COL_MESSAGE_STATUS:
        flags = camel_message_info_flags (msg_info);
        if (flags & CAMEL_MESSAGE_ANSWERED)
            return GINT_TO_POINTER (2);
        else if (flags & CAMEL_MESSAGE_FORWARDED)
            return GINT_TO_POINTER (3);
        else if (flags & CAMEL_MESSAGE_SEEN)
            return GINT_TO_POINTER (1);
        else
            return GINT_TO_POINTER (0);
    case COL_FLAGGED:
        return GINT_TO_POINTER ((camel_message_info_flags (msg_info) & CAMEL_MESSAGE_FLAGGED) != 0);
    case COL_SCORE: {
        const gchar *tag;
        gint score = 0;

        tag = camel_message_info_user_tag (msg_info, "score");
        if (tag)
            score = atoi (tag);

        return GINT_TO_POINTER (score);
    }
    case COL_FOLLOWUP_FLAG_STATUS: {
        const gchar *tag, *cmp;

        /* FIXME: this all should be methods off of message-tag-followup class,
         * FIXME: the tag names should be namespaced :( */
        tag = camel_message_info_user_tag (msg_info, "follow-up");
        cmp = camel_message_info_user_tag (msg_info, "completed-on");
        if (tag && tag[0]) {
            if (cmp && cmp[0])
                return GINT_TO_POINTER (2);
            else
                return GINT_TO_POINTER (1);
        } else
            return GINT_TO_POINTER (0);
    }
    case COL_FOLLOWUP_DUE_BY: {
        const gchar *tag;
        time_t due_by;

        tag = camel_message_info_user_tag (msg_info, "due-by");
        if (tag && *tag) {
            due_by = camel_header_decode_date (tag, NULL);
            return GINT_TO_POINTER (due_by);
        } else {
            return GINT_TO_POINTER (0);
        }
    }
    case COL_FOLLOWUP_FLAG:
        str = camel_message_info_user_tag (msg_info, "follow-up");
        return (gpointer)(str ? str : "");
    case COL_ATTACHMENT:
        if (camel_message_info_user_flag (msg_info, "$has_cal"))
            return GINT_TO_POINTER (2);
        return GINT_TO_POINTER ((camel_message_info_flags (msg_info) & CAMEL_MESSAGE_ATTACHMENTS) != 0);
    case COL_FROM:
        str = camel_message_info_from (msg_info);
        return (gpointer)(str ? str : "");
    case COL_FROM_NORM:
        return (gpointer) get_normalised_string (message_list, msg_info, col);
    case COL_SUBJECT:
        str = camel_message_info_subject (msg_info);
        return (gpointer)(str ? str : "");
    case COL_SUBJECT_TRIMMED:
        str = get_trimmed_subject (msg_info);
        return (gpointer)(str ? str : "");
    case COL_SUBJECT_NORM:
        return (gpointer) get_normalised_string (message_list, msg_info, col);
    case COL_SENT: {
        struct LatestData ld;
        ld.sent = TRUE;
        ld.latest = 0;

        for_node_and_subtree_if_collapsed (message_list, path, msg_info, latest_foreach, &ld);

        return GINT_TO_POINTER (ld.latest);
    }
    case COL_RECEIVED: {
        struct LatestData ld;
        ld.sent = FALSE;
        ld.latest = 0;

        for_node_and_subtree_if_collapsed (message_list, path, msg_info, latest_foreach, &ld);

        return GINT_TO_POINTER (ld.latest);
    }
    case COL_TO:
        str = camel_message_info_to (msg_info);
        return (gpointer)(str ? str : "");
    case COL_TO_NORM:
        return (gpointer) get_normalised_string (message_list, msg_info, col);
    case COL_SIZE:
        return GINT_TO_POINTER (camel_message_info_size (msg_info));
    case COL_DELETED:
        return GINT_TO_POINTER ((camel_message_info_flags (msg_info) & CAMEL_MESSAGE_DELETED) != 0);
    case COL_UNREAD: {
        gboolean saw_unread = FALSE;

        for_node_and_subtree_if_collapsed (message_list, path, msg_info, unread_foreach, &saw_unread);

        return GINT_TO_POINTER (saw_unread);
    }
    case COL_COLOUR: {
        const gchar *colour, *due_by, *completed, *followup;

        /* Priority: colour tag; label tag; important flag; due-by tag */

        /* This is astonisngly poorly written code */

        /* To add to the woes, what color to show when the user choose multiple labels ?
        Don't say that I need to have the new labels[with subject] column visible always */

        colour = NULL;
        due_by = camel_message_info_user_tag (msg_info, "due-by");
        completed = camel_message_info_user_tag (msg_info, "completed-on");
        followup = camel_message_info_user_tag (msg_info, "follow-up");
        if (colour == NULL) {
            /* Get all applicable labels. */
            struct LabelsData ld;

            ld.store = e_mail_ui_session_get_label_store (
                E_MAIL_UI_SESSION (session));
            ld.labels_tag2iter = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) gtk_tree_iter_free);
            for_node_and_subtree_if_collapsed (message_list, path, msg_info, add_all_labels_foreach, &ld);

            if (g_hash_table_size (ld.labels_tag2iter) == 1) {
                GHashTableIter iter;
                GtkTreeIter *label_defn;
                GdkColor colour_val;
                gchar *colour_alloced;

                /* Extract the single label from the hashtable. */
                g_hash_table_iter_init (&iter, ld.labels_tag2iter);
                g_hash_table_iter_next (&iter, NULL, (gpointer *) &label_defn);

                e_mail_label_list_store_get_color (ld.store, label_defn, &colour_val);

                /* XXX Hack to avoid returning an allocated string. */
                colour_alloced = gdk_color_to_string (&colour_val);
                colour = g_intern_string (colour_alloced);
                g_free (colour_alloced);
            } else if (camel_message_info_flags (msg_info) & CAMEL_MESSAGE_FLAGGED) {
                /* FIXME: extract from the important.xpm somehow. */
                colour = "#A7453E";
            } else if (((followup && *followup) || (due_by && *due_by)) && !(completed && *completed)) {
                time_t now = time (NULL);

                if ((followup && *followup) || now >= camel_header_decode_date (due_by, NULL))
                    colour = "#A7453E";
            }

            g_hash_table_destroy (ld.labels_tag2iter);
        }

        if (!colour)
            colour = camel_message_info_user_tag (msg_info, "color");

        return (gpointer) colour;
    }
    case COL_LOCATION: {
        /* Fixme : freeing memory stuff (mem leaks) */
        CamelStore *store;
        CamelFolder *folder;
        CamelService *service;
        const gchar *store_name;
        const gchar *folder_name;

        folder = message_list->priv->folder;

        if (CAMEL_IS_VEE_FOLDER (folder))
            folder = camel_vee_folder_get_location (
                CAMEL_VEE_FOLDER (folder),
                (CamelVeeMessageInfo *) msg_info, NULL);

        store = camel_folder_get_parent_store (folder);
        folder_name = camel_folder_get_full_name (folder);

        service = CAMEL_SERVICE (store);
        store_name = camel_service_get_display_name (service);

        return g_strdup_printf ("%s : %s", store_name, folder_name);
    }
    case COL_MIXED_RECIPIENTS:
    case COL_RECIPIENTS:{
        str = camel_message_info_to (msg_info);

        return sanitize_recipients (str);
    }
    case COL_MIXED_SENDER:
    case COL_SENDER:{
        gchar **sender_name = NULL;
        str = camel_message_info_from (msg_info);
        if (str && str[0] != '\0') {
            gchar *res;
            sender_name = g_strsplit (str,"<",2);
            res = g_strdup (*sender_name);
            g_strfreev (sender_name);
            return (gpointer)(res);
        }
        else
            return (gpointer)("");
    }
    case COL_LABELS:{
        struct LabelsData ld;
        GString *result = g_string_new ("");

        ld.store = e_mail_ui_session_get_label_store (
            E_MAIL_UI_SESSION (session));
        ld.labels_tag2iter = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) gtk_tree_iter_free);
        for_node_and_subtree_if_collapsed (message_list, path, msg_info, add_all_labels_foreach, &ld);

        if (g_hash_table_size (ld.labels_tag2iter) > 0) {
            GHashTableIter iter;
            GtkTreeIter *label_defn;

            g_hash_table_iter_init (&iter, ld.labels_tag2iter);
            while (g_hash_table_iter_next (&iter, NULL, (gpointer *) &label_defn)) {
                gchar *label_name, *label_name_clean;

                if (result->len > 0)
                    g_string_append (result, ", ");

                label_name = e_mail_label_list_store_get_name (ld.store, label_defn);
                label_name_clean = e_str_without_underscores (label_name);

                g_string_append (result, label_name_clean);

                g_free (label_name_clean);
                g_free (label_name);
            }
        }

        g_hash_table_destroy (ld.labels_tag2iter);
        return (gpointer) g_string_free (result, FALSE);
    }
    default:
        g_warning ("%s: This shouldn't be reached (col:%d)", G_STRFUNC, col);
        return NULL;
    }
}

static gpointer
ml_tree_value_at (ETreeModel *etm,
                  ETreePath path,
                  gint col,
                  gpointer model_data)
{
    MessageList *message_list = model_data;
    CamelMessageInfo *msg_info;

    if (e_tree_model_node_is_root (etm, path))
        return NULL;

    /* retrieve the message information array */
    msg_info = e_tree_memory_node_get_data (E_TREE_MEMORY (etm), path);
    g_return_val_if_fail (msg_info != NULL, NULL);

    return ml_tree_value_at_ex (etm, path, col, msg_info, message_list);
}

static gpointer
ml_tree_sort_value_at (ETreeModel *etm,
                       ETreePath path,
                       gint col,
                       gpointer model_data)
{
    MessageList *message_list = model_data;
    struct LatestData ld;

    if (!(col == COL_SENT || col == COL_RECEIVED))
        return ml_tree_value_at (etm, path, col, model_data);

    if (e_tree_model_node_is_root (etm, path))
        return NULL;

    ld.sent = (col == COL_SENT);
    ld.latest = 0;

    latest_foreach (etm, path, &ld);
    if (message_list->priv->thread_latest)
        e_tree_model_node_traverse (etm, path, latest_foreach, &ld);

    return GINT_TO_POINTER (ld.latest);
}

static void
ml_tree_set_value_at (ETreeModel *etm,
                      ETreePath path,
                      gint col,
                      gconstpointer val,
                      gpointer model_data)
{
    g_warning ("This shouldn't be reached\n");
}

static gboolean
ml_tree_is_cell_editable (ETreeModel *etm,
                          ETreePath path,
                          gint col,
                          gpointer model_data)
{
    return FALSE;
}

static gchar *
filter_date (time_t date)
{
    time_t nowdate = time (NULL);
    time_t yesdate;
    struct tm then, now, yesterday;
    gchar buf[26];
    gboolean done = FALSE;

    if (date == 0)
        return g_strdup (_("?"));

    localtime_r (&date, &then);
    localtime_r (&nowdate, &now);
    if (then.tm_mday == now.tm_mday &&
        then.tm_mon == now.tm_mon &&
        then.tm_year == now.tm_year) {
        e_utf8_strftime_fix_am_pm (buf, 26, _("Today %l:%M %p"), &then);
        done = TRUE;
    }
    if (!done) {
        yesdate = nowdate - 60 * 60 * 24;
        localtime_r (&yesdate, &yesterday);
        if (then.tm_mday == yesterday.tm_mday &&
            then.tm_mon == yesterday.tm_mon &&
            then.tm_year == yesterday.tm_year) {
            e_utf8_strftime_fix_am_pm (buf, 26, _("Yesterday %l:%M %p"), &then);
            done = TRUE;
        }
    }
    if (!done) {
        gint i;
        for (i = 2; i < 7; i++) {
            yesdate = nowdate - 60 * 60 * 24 * i;
            localtime_r (&yesdate, &yesterday);
            if (then.tm_mday == yesterday.tm_mday &&
                then.tm_mon == yesterday.tm_mon &&
                then.tm_year == yesterday.tm_year) {
                e_utf8_strftime_fix_am_pm (buf, 26, _("%a %l:%M %p"), &then);
                done = TRUE;
                break;
            }
        }
    }
    if (!done) {
        if (then.tm_year == now.tm_year) {
            e_utf8_strftime_fix_am_pm (buf, 26, _("%b %d %l:%M %p"), &then);
        } else {
            e_utf8_strftime_fix_am_pm (buf, 26, _("%b %d %Y"), &then);
        }
    }

    return g_strdup (buf);
}

static ECell * create_composite_cell (gint col)
{
    ECell *cell_vbox, *cell_hbox, *cell_sub, *cell_date, *cell_from, *cell_tree, *cell_attach;
    GSettings *settings;
    gchar *fixed_name = NULL;
    gboolean show_email;
    gint alt_col = (col == COL_FROM) ? COL_SENDER : COL_RECIPIENTS;
    gboolean same_font = FALSE;

    settings = g_settings_new ("org.gnome.evolution.mail");
    show_email = g_settings_get_boolean (settings, "show-email");
    same_font = g_settings_get_boolean (settings, "vertical-view-fonts");
    g_object_unref (settings);
    if (!same_font) {
        settings = g_settings_new ("org.gnome.desktop.interface");
        fixed_name = g_settings_get_string (settings, "monospace-font-name");
        g_object_unref (settings);
    }

    cell_vbox = e_cell_vbox_new ();

    cell_hbox = e_cell_hbox_new ();

    /* Exclude the meeting icon. */
    cell_attach = e_cell_toggle_new (attachment_icons, G_N_ELEMENTS (attachment_icons));

    cell_date = e_cell_date_new (NULL, GTK_JUSTIFY_RIGHT);
    e_cell_date_set_format_component (E_CELL_DATE (cell_date), "mail");
    g_object_set (
        cell_date,
        "bold_column", COL_UNREAD,
        "color_column", COL_COLOUR,
        NULL);

    cell_from = e_cell_text_new (NULL, GTK_JUSTIFY_LEFT);
    g_object_set (
        cell_from,
        "bold_column", COL_UNREAD,
        "color_column", COL_COLOUR,
        NULL);

    e_cell_hbox_append (E_CELL_HBOX (cell_hbox), cell_from, show_email ? col : alt_col, 68);
    e_cell_hbox_append (E_CELL_HBOX (cell_hbox), cell_attach, COL_ATTACHMENT, 5);
    e_cell_hbox_append (E_CELL_HBOX (cell_hbox), cell_date, COL_SENT, 27);
    g_object_unref (cell_from);
    g_object_unref (cell_attach);
    g_object_unref (cell_date);

    cell_sub = e_cell_text_new (fixed_name? fixed_name : NULL, GTK_JUSTIFY_LEFT);
    g_object_set (
        cell_sub,
        "color_column", COL_COLOUR,
        NULL);
    cell_tree = e_cell_tree_new (TRUE, cell_sub);
    e_cell_vbox_append (E_CELL_VBOX (cell_vbox), cell_hbox, COL_FROM);
    e_cell_vbox_append (E_CELL_VBOX (cell_vbox), cell_tree, COL_SUBJECT);
    g_object_unref (cell_sub);
    g_object_unref (cell_hbox);
    g_object_unref (cell_tree);

    g_object_set_data (G_OBJECT (cell_vbox), "cell_date", cell_date);
    g_object_set_data (G_OBJECT (cell_vbox), "cell_sub", cell_sub);
    g_object_set_data (G_OBJECT (cell_vbox), "cell_from", cell_from);

    g_free (fixed_name);

    return cell_vbox;
}

static void
composite_cell_set_strike_col (ECell *cell,
                               gint col)
{
    g_object_set (g_object_get_data (G_OBJECT (cell), "cell_date"),  "strikeout_column", col, NULL);
    g_object_set (g_object_get_data (G_OBJECT (cell), "cell_from"),  "strikeout_column", col, NULL);
}

static ETableExtras *
message_list_create_extras (void)
{
    ETableExtras *extras;
    ECell *cell;

    extras = e_table_extras_new ();
    e_table_extras_add_icon_name (extras, "status", "mail-unread");
    e_table_extras_add_icon_name (extras, "score", "stock_score-higher");
    e_table_extras_add_icon_name (extras, "attachment", "mail-attachment");
    e_table_extras_add_icon_name (extras, "flagged", "emblem-important");
    e_table_extras_add_icon_name (extras, "followup", "stock_mail-flag-for-followup");

    e_table_extras_add_compare (extras, "address_compare", address_compare);

    cell = e_cell_toggle_new (
        status_icons, G_N_ELEMENTS (status_icons));
    e_table_extras_add_cell (extras, "render_message_status", cell);
    g_object_unref (cell);

    cell = e_cell_toggle_new (
        attachment_icons, G_N_ELEMENTS (attachment_icons));
    e_table_extras_add_cell (extras, "render_attachment", cell);
    g_object_unref (cell);

    cell = e_cell_toggle_new (
        flagged_icons, G_N_ELEMENTS (flagged_icons));
    e_table_extras_add_cell (extras, "render_flagged", cell);
    g_object_unref (cell);

    cell = e_cell_toggle_new (
        followup_icons, G_N_ELEMENTS (followup_icons));
    e_table_extras_add_cell (extras, "render_flag_status", cell);
    g_object_unref (cell);

    cell = e_cell_toggle_new (
        score_icons, G_N_ELEMENTS (score_icons));
    e_table_extras_add_cell (extras, "render_score", cell);
    g_object_unref (cell);

    /* date cell */
    cell = e_cell_date_new (NULL, GTK_JUSTIFY_LEFT);
    e_cell_date_set_format_component (E_CELL_DATE (cell), "mail");
    g_object_set (
        cell,
        "bold_column", COL_UNREAD,
        "color_column", COL_COLOUR,
        NULL);
    e_table_extras_add_cell (extras, "render_date", cell);
    g_object_unref (cell);

    /* text cell */
    cell = e_cell_text_new (NULL, GTK_JUSTIFY_LEFT);
    g_object_set (
        cell,
        "bold_column", COL_UNREAD,
        "color_column", COL_COLOUR,
        NULL);
    e_table_extras_add_cell (extras, "render_text", cell);
    g_object_unref (cell);

    cell = e_cell_tree_new (TRUE, cell);
    e_table_extras_add_cell (extras, "render_tree", cell);
    g_object_unref (cell);

    /* size cell */
    cell = e_cell_size_new (NULL, GTK_JUSTIFY_RIGHT);
    g_object_set (
        cell,
        "bold_column", COL_UNREAD,
        "color_column", COL_COLOUR,
        NULL);
    e_table_extras_add_cell (extras, "render_size", cell);
    g_object_unref (cell);

    /* Composite cell for wide view */
    cell = create_composite_cell (COL_FROM);
    e_table_extras_add_cell (extras, "render_composite_from", cell);
    g_object_unref (cell);

    cell = create_composite_cell (COL_TO);
    e_table_extras_add_cell (extras, "render_composite_to", cell);
    g_object_unref (cell);

    /* set proper format component for a default 'date' cell renderer */
    cell = e_table_extras_get_cell (extras, "date");
    e_cell_date_set_format_component (E_CELL_DATE (cell), "mail");

    return extras;
}

static void
save_tree_state (MessageList *ml,
                 CamelFolder *folder)
{
    gchar *filename;

    if (folder == NULL)
        return;

    if (ml->search != NULL && *ml->search != '\0')
        return;

    filename = mail_config_folder_to_cachename (folder, "et-expanded-");
    e_tree_save_expanded_state (E_TREE (ml), filename);
    g_free (filename);

    ml->priv->any_row_changed = FALSE;
}

static void
load_tree_state (MessageList *ml,
                 CamelFolder *folder,
                 xmlDoc *expand_state)
{
    if (folder == NULL)
        return;

    if (expand_state) {
        e_tree_load_expanded_state_xml (E_TREE (ml), expand_state);
    } else if (!ml->search || !*ml->search) {
        /* only when not searching */
        gchar *filename;

        filename = mail_config_folder_to_cachename (
            folder, "et-expanded-");
        e_tree_load_expanded_state (E_TREE (ml), filename);
        g_free (filename);
    }

    ml->priv->any_row_changed = FALSE;
}

void
message_list_save_state (MessageList *ml)
{
    CamelFolder *folder;

    folder = message_list_ref_folder (ml);

    if (folder != NULL) {
        save_tree_state (ml, folder);
        g_object_unref (folder);
    }
}

static void
message_list_setup_etree (MessageList *message_list)
{
    CamelFolder *folder;

    /* Build the spec based on the folder, and possibly
     * from a saved file.   Otherwise, leave default. */

    folder = message_list_ref_folder (message_list);

    if (folder != NULL) {
        gint data = 1;
        ETableItem *item;

        item = e_tree_get_item (E_TREE (message_list));

        g_object_set (message_list, "uniform_row_height", TRUE, NULL);
        g_object_set_data (
            G_OBJECT (((GnomeCanvasItem *) item)->canvas),
            "freeze-cursor", &data);

        /* build based on saved file */
        load_tree_state (message_list, folder, NULL);

        g_object_unref (folder);
    }
}

static void
ml_selection_get (GtkWidget *widget,
                  GtkSelectionData *data,
                  guint info,
                  guint time_stamp,
                  MessageList *ml)
{
    struct _MLSelection *selection;

    selection = &ml->priv->clipboard;

    if (selection->uids == NULL)
        return;

    if (info & 2) {
        /* text/plain */
        d (printf ("setting text/plain selection for uids\n"));
        em_utils_selection_set_mailbox (data, selection->folder, selection->uids);
    } else {
        /* x-uid-list */
        d (printf ("setting x-uid-list selection for uids\n"));
        em_utils_selection_set_uidlist (data, selection->folder, selection->uids);
    }
}

static gboolean
ml_selection_clear_event (GtkWidget *widget,
                          GdkEventSelection *event,
                          MessageList *ml)
{
    MessageListPrivate *p = ml->priv;

    clear_selection (ml, &p->clipboard);

    return TRUE;
}

static void
ml_selection_received (GtkWidget *widget,
                       GtkSelectionData *selection_data,
                       guint time,
                       MessageList *message_list)
{
    EMailSession *session;
    CamelFolder *folder;
    GdkAtom target;

    target = gtk_selection_data_get_target (selection_data);

    if (target != gdk_atom_intern ("x-uid-list", FALSE)) {
        d (printf ("Unknown selection received by message-list\n"));
        return;
    }

    folder = message_list_ref_folder (message_list);
    session = message_list_get_session (message_list);

    /* FIXME Not passing a GCancellable or GError here. */
    em_utils_selection_get_uidlist (
        selection_data, session, folder, FALSE, NULL, NULL);

    g_clear_object (&folder);
}

static void
ml_tree_drag_data_get (ETree *tree,
                       gint row,
                       ETreePath path,
                       gint col,
                       GdkDragContext *context,
                       GtkSelectionData *data,
                       guint info,
                       guint time,
                       MessageList *ml)
{
    CamelFolder *folder;
    GPtrArray *uids;

    folder = message_list_ref_folder (ml);
    uids = message_list_get_selected (ml);

    if (uids->len > 0) {
        switch (info) {
        case DND_X_UID_LIST:
            em_utils_selection_set_uidlist (data, folder, uids);
            break;
        case DND_TEXT_URI_LIST:
            em_utils_selection_set_urilist (data, folder, uids);
            break;
        }
    }

    g_clear_object (&folder);
    em_utils_uids_free (uids);
}

/* TODO: merge this with the folder tree stuff via empopup targets */
/* Drop handling */
struct _drop_msg {
    MailMsg base;

    GdkDragContext *context;

    /* Only selection->data and selection->length are valid */
    GtkSelectionData *selection;

    CamelFolder *folder;
    MessageList *message_list;

    guint32 action;
    guint info;

    guint move : 1;
    guint moved : 1;
    guint aborted : 1;
};

static gchar *
ml_drop_async_desc (struct _drop_msg *m)
{
    const gchar *full_name;

    full_name = camel_folder_get_full_name (m->folder);

    if (m->move)
        return g_strdup_printf (_("Moving messages into folder %s"), full_name);
    else
        return g_strdup_printf (_("Copying messages into folder %s"), full_name);
}

static void
ml_drop_async_exec (struct _drop_msg *m,
                    GCancellable *cancellable,
                    GError **error)
{
    EMailSession *session;

    session = message_list_get_session (m->message_list);

    switch (m->info) {
    case DND_X_UID_LIST:
        em_utils_selection_get_uidlist (
            m->selection, session, m->folder,
            m->action == GDK_ACTION_MOVE,
            cancellable, error);
        break;
    case DND_MESSAGE_RFC822:
        em_utils_selection_get_message (m->selection, m->folder);
        break;
    case DND_TEXT_URI_LIST:
        em_utils_selection_get_urilist (m->selection, m->folder);
        break;
    }
}

static void
ml_drop_async_done (struct _drop_msg *m)
{
    gboolean success, delete;

    /* ?? */
    if (m->aborted) {
        success = FALSE;
        delete = FALSE;
    } else {
        success = (m->base.error == NULL);
        delete = success && m->move && !m->moved;
    }

    gtk_drag_finish (m->context, success, delete, GDK_CURRENT_TIME);
}

static void
ml_drop_async_free (struct _drop_msg *m)
{
    g_object_unref (m->context);
    g_object_unref (m->folder);
    g_object_unref (m->message_list);
    gtk_selection_data_free (m->selection);
}

static MailMsgInfo ml_drop_async_info = {
    sizeof (struct _drop_msg),
    (MailMsgDescFunc) ml_drop_async_desc,
    (MailMsgExecFunc) ml_drop_async_exec,
    (MailMsgDoneFunc) ml_drop_async_done,
    (MailMsgFreeFunc) ml_drop_async_free
};

static void
ml_drop_action (struct _drop_msg *m)
{
    m->move = m->action == GDK_ACTION_MOVE;
    mail_msg_unordered_push (m);
}

static void
ml_tree_drag_data_received (ETree *tree,
                            gint row,
                            ETreePath path,
                            gint col,
                            GdkDragContext *context,
                            gint x,
                            gint y,
                            GtkSelectionData *selection_data,
                            guint info,
                            guint time,
                            MessageList *ml)
{
    CamelFolder *folder;
    struct _drop_msg *m;

    if (gtk_selection_data_get_data (selection_data) == NULL)
        return;

    if (gtk_selection_data_get_length (selection_data) == -1)
        return;

    folder = message_list_ref_folder (ml);
    if (folder == NULL)
        return;

    m = mail_msg_new (&ml_drop_async_info);
    m->context = g_object_ref (context);
    m->folder = g_object_ref (folder);
    m->message_list = g_object_ref (ml);
    m->action = gdk_drag_context_get_selected_action (context);
    m->info = info;

    /* need to copy, goes away once we exit */
    m->selection = gtk_selection_data_copy (selection_data);

    ml_drop_action (m);

    g_object_unref (folder);
}

struct search_child_struct {
    gboolean found;
    gconstpointer looking_for;
};

static void
search_child_cb (GtkWidget *widget,
                 gpointer data)
{
    struct search_child_struct *search = (struct search_child_struct *) data;

    search->found = search->found || g_direct_equal (widget, search->looking_for);
}

static gboolean
is_tree_widget_children (ETree *tree,
                         gconstpointer widget)
{
    struct search_child_struct search;

    search.found = FALSE;
    search.looking_for = widget;

    gtk_container_foreach (GTK_CONTAINER (tree), search_child_cb, &search);

    return search.found;
}

static gboolean
ml_tree_drag_motion (ETree *tree,
                     GdkDragContext *context,
                     gint x,
                     gint y,
                     guint time,
                     MessageList *ml)
{
    GList *targets;
    GdkDragAction action, actions = 0;
    GtkWidget *source_widget;

    /* If drop target is name of the account/store
     * and not actual folder, don't allow any action. */
    if (ml->priv->folder == NULL) {
        gdk_drag_status (context, 0, time);
        return TRUE;
    }

    source_widget = gtk_drag_get_source_widget (context);

    /* If source widget is packed under 'tree', don't allow any action */
    if (is_tree_widget_children (tree, source_widget)) {
        gdk_drag_status (context, 0, time);
        return TRUE;
    }

    if (EM_IS_FOLDER_TREE (source_widget)) {
        EMFolderTree *folder_tree;
        CamelFolder *selected_folder = NULL;
        CamelStore *selected_store;
        gchar *selected_folder_name;
        gboolean has_selection;

        folder_tree = EM_FOLDER_TREE (source_widget);

        has_selection = em_folder_tree_get_selected (
            folder_tree, &selected_store, &selected_folder_name);

        /* Sanity checks */
        g_warn_if_fail (
            (has_selection && selected_store != NULL) ||
            (!has_selection && selected_store == NULL));
        g_warn_if_fail (
            (has_selection && selected_folder_name != NULL) ||
            (!has_selection && selected_folder_name == NULL));

        if (has_selection) {
            selected_folder = camel_store_get_folder_sync (
                selected_store, selected_folder_name,
                CAMEL_STORE_FOLDER_INFO_FAST, NULL, NULL);
            g_object_unref (selected_store);
            g_free (selected_folder_name);
        }

        if (selected_folder == ml->priv->folder) {
            gdk_drag_status (context, 0, time);
            return TRUE;
        }
    }

    targets = gdk_drag_context_list_targets (context);
    while (targets != NULL) {
        gint i;

        d (printf ("atom drop '%s'\n", gdk_atom_name (targets->data)));
        for (i = 0; i < G_N_ELEMENTS (ml_drag_info); i++)
            if (targets->data == (gpointer) ml_drag_info[i].atom)
                actions |= ml_drag_info[i].actions;

        targets = g_list_next (targets);
    }
    d (printf ("\n"));

    actions &= gdk_drag_context_get_actions (context);
    action = gdk_drag_context_get_suggested_action (context);
    if (action == GDK_ACTION_COPY && (actions & GDK_ACTION_MOVE))
        action = GDK_ACTION_MOVE;

    gdk_drag_status (context, action, time);

    return action != 0;
}

static void
on_model_row_changed (ETableModel *model,
                      gint row,
                      MessageList *ml)
{
    ml->priv->any_row_changed = TRUE;
}

static gboolean
ml_tree_sorting_changed (ETreeTableAdapter *adapter,
                         MessageList *ml)
{
    g_return_val_if_fail (ml != NULL, FALSE);

    if (ml->threaded && ml->frozen == 0) {
        if (ml->thread_tree) {
            /* free the previous thread_tree to recreate it fully */
            camel_folder_thread_messages_unref (ml->thread_tree);
            ml->thread_tree = NULL;
        }

        mail_regen_list (ml, ml->search, FALSE);

        return TRUE;
    }

    return FALSE;
}

static void
message_list_set_session (MessageList *message_list,
                          EMailSession *session)
{
    g_return_if_fail (E_IS_MAIL_SESSION (session));
    g_return_if_fail (message_list->priv->session == NULL);

    message_list->priv->session = g_object_ref (session);
}

static void
message_list_init (MessageList *message_list)
{
    MessageListPrivate *p;
    GtkTargetList *target_list;
    GdkAtom matom;

    message_list->priv = MESSAGE_LIST_GET_PRIVATE (message_list);

    /* FIXME This should be a GTypeInterface. */
    message_list->model = e_tree_memory_callbacks_new (
        ml_tree_icon_at,

        ml_column_count,

        ml_has_save_id,
        ml_get_save_id,

        ml_has_get_node_by_id,
        ml_get_node_by_id,

        ml_tree_sort_value_at,
        ml_tree_value_at,
        ml_tree_set_value_at,
        ml_tree_is_cell_editable,

        ml_duplicate_value,
        ml_free_value,
        ml_initialize_value,
        ml_value_is_empty,
        ml_value_to_string,

        message_list);

    message_list->normalised_hash = g_hash_table_new_full (
        g_str_hash, g_str_equal,
        (GDestroyNotify) NULL,
        (GDestroyNotify) e_poolv_destroy);

    message_list->uid_nodemap = g_hash_table_new (g_str_hash, g_str_equal);

    message_list->cursor_uid = NULL;
    message_list->last_sel_single = FALSE;

    g_mutex_init (&message_list->priv->regen_lock);

    /* TODO: Should this only get the selection if we're realised? */
    p = message_list->priv;
    p->invisible = gtk_invisible_new ();
    p->destroyed = FALSE;
    g_object_ref_sink (p->invisible);
    p->any_row_changed = FALSE;

    matom = gdk_atom_intern ("x-uid-list", FALSE);
    gtk_selection_add_target (p->invisible, GDK_SELECTION_CLIPBOARD, matom, 0);
    gtk_selection_add_target (p->invisible, GDK_SELECTION_CLIPBOARD, GDK_SELECTION_TYPE_STRING, 2);

    g_signal_connect (
        p->invisible, "selection_get",
        G_CALLBACK (ml_selection_get), message_list);
    g_signal_connect (
        p->invisible, "selection_clear_event",
        G_CALLBACK (ml_selection_clear_event), message_list);
    g_signal_connect (
        p->invisible, "selection_received",
        G_CALLBACK (ml_selection_received), message_list);

    /* FIXME This is currently unused. */
    target_list = gtk_target_list_new (NULL, 0);
    message_list->priv->copy_target_list = target_list;

    /* FIXME This is currently unused. */
    target_list = gtk_target_list_new (NULL, 0);
    message_list->priv->paste_target_list = target_list;
}

static void
message_list_set_property (GObject *object,
                           guint property_id,
                           const GValue *value,
                           GParamSpec *pspec)
{
    switch (property_id) {
        case PROP_FOLDER:
            message_list_set_folder (
                MESSAGE_LIST (object),
                g_value_get_object (value));
            return;

        case PROP_SESSION:
            message_list_set_session (
                MESSAGE_LIST (object),
                g_value_get_object (value));
            return;

        case PROP_SHOW_DELETED:
            message_list_set_show_deleted (
                MESSAGE_LIST (object),
                g_value_get_boolean (value));
            return;

        case PROP_THREAD_LATEST:
            message_list_set_thread_latest (
                MESSAGE_LIST (object),
                g_value_get_boolean (value));
            return;

        case PROP_THREAD_SUBJECT:
            message_list_set_thread_subject (
                MESSAGE_LIST (object),
                g_value_get_boolean (value));
            return;
    }

    G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}

static void
message_list_get_property (GObject *object,
                           guint property_id,
                           GValue *value,
                           GParamSpec *pspec)
{
    switch (property_id) {
        case PROP_COPY_TARGET_LIST:
            g_value_set_boxed (
                value,
                message_list_get_copy_target_list (
                MESSAGE_LIST (object)));
            return;

        case PROP_FOLDER:
            g_value_take_object (
                value,
                message_list_ref_folder (
                MESSAGE_LIST (object)));
            return;

        case PROP_PASTE_TARGET_LIST:
            g_value_set_boxed (
                value,
                message_list_get_paste_target_list (
                MESSAGE_LIST (object)));
            return;

        case PROP_SESSION:
            g_value_set_object (
                value,
                message_list_get_session (
                MESSAGE_LIST (object)));
            return;

        case PROP_SHOW_DELETED:
            g_value_set_boolean (
                value,
                message_list_get_show_deleted (
                MESSAGE_LIST (object)));
            return;

        case PROP_THREAD_LATEST:
            g_value_set_boolean (
                value,
                message_list_get_thread_latest (
                MESSAGE_LIST (object)));
            return;

        case PROP_THREAD_SUBJECT:
            g_value_set_boolean (
                value,
                message_list_get_thread_subject (
                MESSAGE_LIST (object)));
            return;
    }

    G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}

static void
message_list_dispose (GObject *object)
{
    MessageList *message_list = MESSAGE_LIST (object);
    MessageListPrivate *priv;

    priv = message_list->priv;

    if (priv->folder_changed_handler_id > 0) {
        g_signal_handler_disconnect (
            priv->folder,
            priv->folder_changed_handler_id);
        priv->folder_changed_handler_id = 0;
    }

    if (priv->session != NULL) {
        g_object_unref (priv->session);
        priv->session = NULL;
    }

    if (priv->copy_target_list != NULL) {
        gtk_target_list_unref (priv->copy_target_list);
        priv->copy_target_list = NULL;
    }

    if (priv->paste_target_list != NULL) {
        gtk_target_list_unref (priv->paste_target_list);
        priv->paste_target_list = NULL;
    }

    priv->destroyed = TRUE;

    if (message_list->priv->folder != NULL)
        mail_regen_cancel (message_list);

    if (message_list->uid_nodemap) {
        g_hash_table_foreach (message_list->uid_nodemap, (GHFunc) clear_info, message_list);
        g_hash_table_destroy (message_list->uid_nodemap);
        message_list->uid_nodemap = NULL;
    }

    if (message_list->priv->folder) {
        g_object_unref (message_list->priv->folder);
        message_list->priv->folder = NULL;
    }

    if (priv->invisible) {
        g_object_unref (priv->invisible);
        priv->invisible = NULL;
    }

    if (message_list->extras) {
        g_object_unref (message_list->extras);
        message_list->extras = NULL;
    }

    if (message_list->model) {
        g_object_unref (message_list->model);
        message_list->model = NULL;
    }

    if (message_list->idle_id != 0) {
        g_source_remove (message_list->idle_id);
        message_list->idle_id = 0;
    }

    if (message_list->seen_id) {
        g_source_remove (message_list->seen_id);
        message_list->seen_id = 0;
    }

    /* Chain up to parent's dispose() method. */
    G_OBJECT_CLASS (message_list_parent_class)->dispose (object);
}

static void
message_list_finalize (GObject *object)
{
    MessageList *message_list = MESSAGE_LIST (object);

    g_hash_table_destroy (message_list->normalised_hash);

    if (message_list->thread_tree)
        camel_folder_thread_messages_unref (message_list->thread_tree);

    g_free (message_list->search);
    g_free (message_list->frozen_search);
    g_free (message_list->cursor_uid);

    g_mutex_clear (&message_list->priv->regen_lock);

    clear_selection (message_list, &message_list->priv->clipboard);

    /* Chain up to parent's finalize() method. */
    G_OBJECT_CLASS (message_list_parent_class)->finalize (object);
}

static void
message_list_constructed (GObject *object)
{
    /* Chain up to parent's constructed() method. */
    G_OBJECT_CLASS (message_list_parent_class)->constructed (object);

    e_extensible_load_extensions (E_EXTENSIBLE (object));
}

static void
message_list_selectable_update_actions (ESelectable *selectable,
                                        EFocusTracker *focus_tracker,
                                        GdkAtom *clipboard_targets,
                                        gint n_clipboard_targets)
{
    GtkAction *action;
    gboolean sensitive;

    action = e_focus_tracker_get_select_all_action (focus_tracker);
    sensitive = (e_tree_row_count (E_TREE (selectable)) > 0);
    gtk_action_set_tooltip (action, _("Select all visible messages"));
    gtk_action_set_sensitive (action, sensitive);
}

static void
message_list_selectable_select_all (ESelectable *selectable)
{
    message_list_select_all (MESSAGE_LIST (selectable));
}

static void
message_list_class_init (MessageListClass *class)
{
    GObjectClass *object_class;
    gint i;

    for (i = 0; i < G_N_ELEMENTS (ml_drag_info); i++)
        ml_drag_info[i].atom = gdk_atom_intern (ml_drag_info[i].target, FALSE);

    g_type_class_add_private (class, sizeof (MessageListPrivate));

    object_class = G_OBJECT_CLASS (class);
    object_class->set_property = message_list_set_property;
    object_class->get_property = message_list_get_property;
    object_class->dispose = message_list_dispose;
    object_class->finalize = message_list_finalize;
    object_class->constructed = message_list_constructed;

    class->message_list_built = NULL;

    /* Inherited from ESelectableInterface */
    g_object_class_override_property (
        object_class,
        PROP_COPY_TARGET_LIST,
        "copy-target-list");

    g_object_class_install_property (
        object_class,
        PROP_FOLDER,
        g_param_spec_object (
            "folder",
            "Folder",
            "The source folder",
            CAMEL_TYPE_FOLDER,
            G_PARAM_READWRITE |
            G_PARAM_STATIC_STRINGS));

    /* Inherited from ESelectableInterface */
    g_object_class_override_property (
        object_class,
        PROP_PASTE_TARGET_LIST,
        "paste-target-list");

    g_object_class_install_property (
        object_class,
        PROP_SESSION,
        g_param_spec_object (
            "session",
            "Mail Session",
            "The mail session",
            E_TYPE_MAIL_SESSION,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT_ONLY |
            G_PARAM_STATIC_STRINGS));

    g_object_class_install_property (
        object_class,
        PROP_SHOW_DELETED,
        g_param_spec_boolean (
            "show-deleted",
            "Show Deleted",
            "Show messages marked for deletion",
            FALSE,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT |
            G_PARAM_STATIC_STRINGS));

    g_object_class_install_property (
        object_class,
        PROP_THREAD_LATEST,
        g_param_spec_boolean (
            "thread-latest",
            "Thread Latest",
            "Sort threads by latest message",
            TRUE,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT |
            G_PARAM_STATIC_STRINGS));

    g_object_class_install_property (
        object_class,
        PROP_THREAD_SUBJECT,
        g_param_spec_boolean (
            "thread-subject",
            "Thread Subject",
            "Thread messages by Subject headers",
            FALSE,
            G_PARAM_READWRITE |
            G_PARAM_CONSTRUCT |
            G_PARAM_STATIC_STRINGS));

    message_list_signals[MESSAGE_SELECTED] = g_signal_new (
        "message_selected",
        MESSAGE_LIST_TYPE,
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET (MessageListClass, message_selected),
        NULL,
        NULL,
        g_cclosure_marshal_VOID__STRING,
        G_TYPE_NONE, 1,
        G_TYPE_STRING);

    message_list_signals[MESSAGE_LIST_BUILT] = g_signal_new (
        "message_list_built",
        MESSAGE_LIST_TYPE,
        G_SIGNAL_RUN_LAST,
        G_STRUCT_OFFSET (MessageListClass, message_list_built),
        NULL,
        NULL,
        g_cclosure_marshal_VOID__VOID,
        G_TYPE_NONE, 0);
}

static void
message_list_selectable_init (ESelectableInterface *interface)
{
    interface->update_actions = message_list_selectable_update_actions;
    interface->select_all = message_list_selectable_select_all;
}

static void
message_list_construct (MessageList *message_list)
{
    AtkObject *a11y;
    gboolean constructed;
    gchar *etspecfile;

    /*
     * The etree
     */
    message_list->extras = message_list_create_extras ();

    etspecfile = g_build_filename (EVOLUTION_ETSPECDIR, "message-list.etspec", NULL);
    constructed = e_tree_construct_from_spec_file (
        E_TREE (message_list), message_list->model,
        message_list->extras, etspecfile, NULL);
    g_free (etspecfile);

    if (constructed)
        e_tree_root_node_set_visible (E_TREE (message_list), FALSE);

    if (atk_get_root () != NULL) {
        a11y = gtk_widget_get_accessible (GTK_WIDGET (message_list));
        atk_object_set_name (a11y, _("Messages"));
    }

    g_signal_connect (
        e_tree_get_table_adapter (E_TREE (message_list)),
        "model_row_changed",
        G_CALLBACK (on_model_row_changed), message_list);

    g_signal_connect (
        message_list, "cursor_activated",
        G_CALLBACK (on_cursor_activated_cmd), message_list);

    g_signal_connect (
        message_list, "click",
        G_CALLBACK (on_click), message_list);

    g_signal_connect (
        message_list, "selection_change",
        G_CALLBACK (on_selection_changed_cmd), message_list);

    e_tree_drag_source_set (
        E_TREE (message_list), GDK_BUTTON1_MASK,
        ml_drag_types, G_N_ELEMENTS (ml_drag_types),
        GDK_ACTION_MOVE | GDK_ACTION_COPY);

    g_signal_connect (
        message_list, "tree_drag_data_get",
        G_CALLBACK (ml_tree_drag_data_get), message_list);

    e_tree_drag_dest_set (
        E_TREE (message_list), GTK_DEST_DEFAULT_ALL,
        ml_drop_types, G_N_ELEMENTS (ml_drop_types),
        GDK_ACTION_MOVE | GDK_ACTION_COPY);

    g_signal_connect (
        message_list, "tree_drag_data_received",
        G_CALLBACK (ml_tree_drag_data_received), message_list);

    g_signal_connect (
        message_list, "drag-motion",
        G_CALLBACK (ml_tree_drag_motion), message_list);

    g_signal_connect (
        e_tree_get_table_adapter (E_TREE (message_list)),
        "sorting_changed",
        G_CALLBACK (ml_tree_sorting_changed), message_list);
}

/**
 * message_list_new:
 *
 * Creates a new message-list widget.
 *
 * Returns a new message-list widget.
 **/
GtkWidget *
message_list_new (EMailSession *session)
{
    GtkWidget *message_list;

    g_return_val_if_fail (E_IS_MAIL_SESSION (session), NULL);

    message_list = g_object_new (
        message_list_get_type (),
        "session", session, NULL);

    message_list_construct (MESSAGE_LIST (message_list));

    return message_list;
}

EMailSession *
message_list_get_session (MessageList *message_list)
{
    g_return_val_if_fail (IS_MESSAGE_LIST (message_list), NULL);

    return message_list->priv->session;
}

static void
clear_info (gchar *key,
            ETreePath *node,
            MessageList *ml)
{
    CamelMessageInfo *info;

    info = e_tree_memory_node_get_data ((ETreeMemory *) ml->model, node);
    camel_folder_free_message_info (ml->priv->folder, info);
    e_tree_memory_node_set_data ((ETreeMemory *) ml->model, node, NULL);
}

static void
clear_tree (MessageList *ml,
            gboolean tfree)
{
    ETreeModel *etm = ml->model;
    CamelFolder *folder;

#ifdef TIMEIT
    struct timeval start, end;
    gulong diff;

    printf ("Clearing tree\n");
    gettimeofday (&start, NULL);
#endif

    /* we also reset the uid_rowmap since it is no longer useful/valid anyway */
    folder = message_list_ref_folder (ml);
    if (folder != NULL)
        g_hash_table_foreach (ml->uid_nodemap, (GHFunc) clear_info, ml);
    g_hash_table_destroy (ml->uid_nodemap);
    ml->uid_nodemap = g_hash_table_new (g_str_hash, g_str_equal);
    g_clear_object (&folder);

    ml->priv->newest_read_date = 0;
    ml->priv->newest_read_uid = NULL;
    ml->priv->oldest_unread_date = 0;
    ml->priv->oldest_unread_uid = NULL;

    if (ml->tree_root) {
        /* we should be frozen already */
        e_tree_memory_node_remove (E_TREE_MEMORY (etm), ml->tree_root);
    }

    ml->tree_root = e_tree_memory_node_insert (E_TREE_MEMORY (etm), NULL, 0, NULL);
    if (tfree)
        e_tree_model_rebuilt (E_TREE_MODEL (etm));
#ifdef TIMEIT
    gettimeofday (&end, NULL);
    diff = end.tv_sec * 1000 + end.tv_usec / 1000;
    diff -= start.tv_sec * 1000 + start.tv_usec / 1000;
    printf ("Clearing tree took %ld.%03ld seconds\n", diff / 1000, diff % 1000);
#endif

}

static gboolean
folder_store_supports_vjunk_folder (CamelFolder *folder)
{
    CamelStore *store;

    g_return_val_if_fail (folder != NULL, FALSE);

    store = camel_folder_get_parent_store (folder);
    if (store == NULL)
        return FALSE;

    if (CAMEL_IS_VEE_FOLDER (folder))
        return TRUE;

    if (store->flags & CAMEL_STORE_VJUNK)
        return TRUE;

    if (store->flags & CAMEL_STORE_REAL_JUNK_FOLDER)
        return TRUE;

    return FALSE;
}

static gboolean
message_list_get_hide_junk (MessageList *message_list,
                            CamelFolder *folder)
{
    if (folder == NULL)
        return FALSE;

    if (!folder_store_supports_vjunk_folder (folder))
        return FALSE;

    if (folder->folder_flags & CAMEL_FOLDER_IS_JUNK)
        return FALSE;

    if (folder->folder_flags & CAMEL_FOLDER_IS_TRASH)
        return FALSE;

    return TRUE;
}

static gboolean
message_list_get_hide_deleted (MessageList *message_list,
                               CamelFolder *folder)
{
    CamelStore *store;
    gboolean non_trash_folder;

    if (folder == NULL)
        return FALSE;

    if (message_list_get_show_deleted (message_list))
        return FALSE;

    store = camel_folder_get_parent_store (folder);
    g_return_val_if_fail (store != NULL, FALSE);

    non_trash_folder =
        ((store->flags & CAMEL_STORE_VTRASH) == 0) ||
        ((folder->folder_flags & CAMEL_FOLDER_IS_TRASH) == 0);

    return non_trash_folder;
}

/* Check if the given node is selectable in the current message list,
 * which depends on the type of the folder (normal, junk, trash). */
static gboolean
is_node_selectable (MessageList *ml,
                    CamelMessageInfo *info)
{
    CamelFolder *folder;
    gboolean is_junk_folder;
    gboolean is_trash_folder;
    guint32 flags;
    gboolean flag_junk;
    gboolean flag_deleted;
    gboolean hide_junk;
    gboolean hide_deleted;
    gboolean store_has_vjunk;

    g_return_val_if_fail (info != NULL, FALSE);

    folder = message_list_ref_folder (ml);
    g_return_val_if_fail (folder != NULL, FALSE);

    store_has_vjunk = folder_store_supports_vjunk_folder (folder);

    /* check folder type */
    is_junk_folder =
        store_has_vjunk &&
        (folder->folder_flags & CAMEL_FOLDER_IS_JUNK) != 0;
    is_trash_folder = folder->folder_flags & CAMEL_FOLDER_IS_TRASH;

    hide_junk = message_list_get_hide_junk (ml, folder);
    hide_deleted = message_list_get_hide_deleted (ml, folder);

    g_object_unref (folder);

    /* check flags set on current message */
    flags = camel_message_info_flags (info);
    flag_junk = store_has_vjunk && (flags & CAMEL_MESSAGE_JUNK) != 0;
    flag_deleted = flags & CAMEL_MESSAGE_DELETED;

    /* perform actions depending on folder type */
    if (is_junk_folder) {
        /* messages in a junk folder are selectable only if
         * the message is marked as junk and if not deleted
         * when hide_deleted is set */
        if (flag_junk && !(flag_deleted && hide_deleted))
            return TRUE;

    } else if (is_trash_folder) {
        /* messages in a trash folder are selectable unless
         * not deleted any more */
        if (flag_deleted)
            return TRUE;
    } else {
        /* in normal folders it depends on hide_deleted,
         * hide_junk and the message flags */
        if (!(flag_junk && hide_junk)
            && !(flag_deleted && hide_deleted))
            return TRUE;
    }

    return FALSE;
}

/* We try and find something that is selectable in our tree.  There is
 * actually no assurance that we'll find something that will still be
 * there next time, but its probably going to work most of the time. */
static gchar *
find_next_selectable (MessageList *ml)
{
    ETreePath node;
    gint last;
    gint vrow_orig;
    gint vrow;
    ETree *et = E_TREE (ml);
    CamelMessageInfo *info;

    node = g_hash_table_lookup (ml->uid_nodemap, ml->cursor_uid);
    if (node == NULL)
        return NULL;

    info = get_message_info (ml, node);
    if (info && is_node_selectable (ml, info))
        return NULL;

    last = e_tree_row_count (et);

    /* model_to_view_row etc simply dont work for sorted views.  Sigh. */
    vrow_orig = e_tree_row_of_node (et, node);

    /* We already checked this node. */
    vrow = vrow_orig + 1;

    while (vrow < last) {
        node = e_tree_node_at_row (et, vrow);
        info = get_message_info (ml, node);
        if (info && is_node_selectable (ml, info))
            return g_strdup (camel_message_info_uid (info));
        vrow++;
    }

    /* We didn't find any undeleted entries _below_ the currently selected one
 *       * so let's try to find one _above_ */
    vrow = vrow_orig - 1;

    while (vrow >= 0) {
        node = e_tree_node_at_row (et, vrow);
        info = get_message_info (ml, node);
        if (info && is_node_selectable (ml, info))
            return g_strdup (camel_message_info_uid (info));
        vrow--;
    }

    return NULL;
}

static ETreePath *
ml_uid_nodemap_insert (MessageList *message_list,
                       CamelMessageInfo *info,
                       ETreePath *parent_node,
                       gint row)
{
    CamelFolder *folder;
    ETreeMemory *tree;
    ETreePath *node;
    const gchar *uid;
    time_t date;
    guint flags;

    folder = message_list_ref_folder (message_list);
    g_return_val_if_fail (folder != NULL, NULL);

    if (parent_node == NULL)
        parent_node = message_list->tree_root;

    tree = E_TREE_MEMORY (message_list->model);
    node = e_tree_memory_node_insert (tree, parent_node, row, info);

    uid = camel_message_info_uid (info);
    flags = camel_message_info_flags (info);
    date = camel_message_info_date_received (info);

    camel_folder_ref_message_info (folder, info);
    g_hash_table_insert (message_list->uid_nodemap, (gpointer) uid, node);

    /* Track the latest seen and unseen messages shown, used in
     * fallback heuristics for automatic message selection. */
    if (flags & CAMEL_MESSAGE_SEEN) {
        if (date > message_list->priv->newest_read_date) {
            message_list->priv->newest_read_date = date;
            message_list->priv->newest_read_uid = uid;
        }
    } else {
        if (message_list->priv->oldest_unread_date == 0) {
            message_list->priv->oldest_unread_date = date;
            message_list->priv->oldest_unread_uid = uid;
        } else if (date < message_list->priv->oldest_unread_date) {
            message_list->priv->oldest_unread_date = date;
            message_list->priv->oldest_unread_uid = uid;
        }
    }

    g_object_unref (folder);

    return node;
}

static void
ml_uid_nodemap_remove (MessageList *message_list,
                       CamelMessageInfo *info)
{
    CamelFolder *folder;
    const gchar *uid;

    folder = message_list_ref_folder (message_list);
    g_return_if_fail (folder != NULL);

    uid = camel_message_info_uid (info);

    if (uid == message_list->priv->newest_read_uid) {
        message_list->priv->newest_read_date = 0;
        message_list->priv->newest_read_uid = NULL;
    }

    if (uid == message_list->priv->oldest_unread_uid) {
        message_list->priv->oldest_unread_date = 0;
        message_list->priv->oldest_unread_uid = NULL;
    }

    g_hash_table_remove (message_list->uid_nodemap, uid);
    camel_folder_free_message_info (folder, info);

    g_object_unref (folder);
}

/* only call if we have a tree model */
/* builds the tree structure */

static void build_subtree (MessageList *ml, ETreePath parent, CamelFolderThreadNode *c, gint *row);

static void build_subtree_diff (MessageList *ml, ETreePath parent, ETreePath path, CamelFolderThreadNode *c, gint *row);

static void
build_tree (MessageList *ml,
            CamelFolderThread *thread,
            gboolean folder_changed)
{
    gint row = 0;
    ETreeModel *etm = ml->model;
    ETableItem *table_item = e_tree_get_item (E_TREE (ml));
    gchar *saveuid = NULL;
    GPtrArray *selected;
#ifdef TIMEIT
    struct timeval start, end;
    gulong diff;

    printf ("Building tree\n");
    gettimeofday (&start, NULL);
#endif

#ifdef TIMEIT
    gettimeofday (&end, NULL);
    diff = end.tv_sec * 1000 + end.tv_usec / 1000;
    diff -= start.tv_sec * 1000 + start.tv_usec / 1000;
    printf ("Loading tree state took %ld.%03ld seconds\n", diff / 1000, diff % 1000);
#endif

    if (ml->tree_root == NULL) {
        ml->tree_root = e_tree_memory_node_insert (E_TREE_MEMORY (etm), NULL, 0, NULL);
    }

    if (ml->cursor_uid)
        saveuid = find_next_selectable (ml);

        selected = message_list_get_selected (ml);
        e_tree_memory_freeze (E_TREE_MEMORY (etm));
        clear_tree (ml, FALSE);

        build_subtree (ml, ml->tree_root, thread->tree, &row);

        /* Show the cursor unless we're responding to a
         * "folder-changed" signal from our CamelFolder. */
        if (folder_changed && table_item != NULL)
            table_item->queue_show_cursor = FALSE;

        e_tree_memory_thaw (E_TREE_MEMORY (etm));

        /* it's required to thaw & freeze, to propagate changes */
        e_tree_memory_freeze (E_TREE_MEMORY (etm));

        message_list_set_selected (ml, selected);
        em_utils_uids_free (selected);

        /* Show the cursor unless we're responding to a
         * "folder-changed" signal from our CamelFolder. */
        if (folder_changed && table_item != NULL)
            table_item->queue_show_cursor = FALSE;

        e_tree_memory_thaw (E_TREE_MEMORY (etm));
    if (!saveuid && ml->cursor_uid && g_hash_table_lookup (ml->uid_nodemap, ml->cursor_uid)) {
        /* this makes sure a visible node is selected, like when
         * collapsing all nodes and a children had been selected
        */
        saveuid = g_strdup (ml->cursor_uid);
    }

    if (saveuid) {
        ETreePath node = g_hash_table_lookup (ml->uid_nodemap, saveuid);
        if (node == NULL) {
            g_free (ml->cursor_uid);
            ml->cursor_uid = NULL;
            g_signal_emit (ml, message_list_signals[MESSAGE_SELECTED], 0, NULL);
        } else {
            ETree *tree = E_TREE (ml);
            ETreePath parent = node;

            while (parent = e_tree_model_node_get_parent (etm, parent), parent) {
                if (!e_tree_node_is_expanded (tree, parent))
                    node = parent;
            }

            e_tree_memory_freeze (E_TREE_MEMORY (etm));

            e_tree_set_cursor (E_TREE (ml), node);

            /* Show the cursor unless we're responding to a
             * "folder-changed" signal from our CamelFolder. */
            if (folder_changed && table_item != NULL)
                table_item->queue_show_cursor = FALSE;

            e_tree_memory_thaw (E_TREE_MEMORY (etm));
        }
        g_free (saveuid);
    } else if (ml->cursor_uid && !g_hash_table_lookup (ml->uid_nodemap, ml->cursor_uid)) {
        g_free (ml->cursor_uid);
        ml->cursor_uid = NULL;
        g_signal_emit (ml, message_list_signals[MESSAGE_SELECTED], 0, NULL);
    }

#ifdef TIMEIT
    gettimeofday (&end, NULL);
    diff = end.tv_sec * 1000 + end.tv_usec / 1000;
    diff -= start.tv_sec * 1000 + start.tv_usec / 1000;
    printf ("Building tree took %ld.%03ld seconds\n", diff / 1000, diff % 1000);
#endif
}

/* this is about 20% faster than build_subtree_diff,
 * entirely because e_tree_model_node_insert (xx, -1 xx)
 * is faster than inserting to the right row :( */
/* Otherwise, this code would probably go as it does the same thing essentially */
static void
build_subtree (MessageList *ml,
               ETreePath parent,
               CamelFolderThreadNode *c,
               gint *row)
{
    ETreePath node;

    while (c) {
        /* phantom nodes no longer allowed */
        if (!c->message) {
            g_warning ("c->message shouldn't be NULL\n");
            c = c->next;
            continue;
        }

        node = ml_uid_nodemap_insert (
            ml, (CamelMessageInfo *) c->message, parent, -1);

        if (c->child) {
            build_subtree (ml, node, c->child, row);
        }
        c = c->next;
    }
}

/* compares a thread tree node with the etable tree node to see if they point to
 * the same object */
static gint
node_equal (ETreeModel *etm,
            ETreePath ap,
            CamelFolderThreadNode *bp)
{
    CamelMessageInfo *info;

    info = e_tree_memory_node_get_data (E_TREE_MEMORY (etm), ap);

    if (bp->message && strcmp (camel_message_info_uid (info), camel_message_info_uid (bp->message)) == 0)
        return 1;

    return 0;
}

/* adds a single node, retains save state, and handles adding children if required */
static void
add_node_diff (MessageList *ml,
               ETreePath parent,
               ETreePath path,
               CamelFolderThreadNode *c,
               gint *row,
               gint myrow)
{
    CamelMessageInfo *info;
    ETreePath node;

    g_return_if_fail (c->message != NULL);

    /* XXX Casting away constness. */
    info = (CamelMessageInfo *) c->message;

    /* we just update the hashtable key */
    ml_uid_nodemap_remove (ml, info);
    node = ml_uid_nodemap_insert (ml, info, parent, myrow);
    (*row)++;

    if (c->child) {
        build_subtree_diff (ml, node, NULL, c->child, row);
    }
}

/* removes node, children recursively and all associated data */
static void
remove_node_diff (MessageList *ml,
                  ETreePath node,
                  gint depth)
{
    ETreeModel *etm = ml->model;
    ETreePath cp, cn;
    CamelMessageInfo *info;

    t (printf ("Removing node: %s\n", (gchar *) e_tree_memory_node_get_data (etm, node)));

    /* we depth-first remove all node data's ... */
    cp = e_tree_model_node_get_first_child (etm, node);
    while (cp) {
        cn = e_tree_model_node_get_next (etm, cp);
        remove_node_diff (ml, cp, depth + 1);
        cp = cn;
    }

    /* and the rowid entry - if and only if it is referencing this node */
    info = e_tree_memory_node_get_data (E_TREE_MEMORY (etm), node);

    /* and only at the toplevel, remove the node (etree should optimise this remove somewhat) */
    if (depth == 0)
        e_tree_memory_node_remove (E_TREE_MEMORY (etm), node);

    g_return_if_fail (info);
    ml_uid_nodemap_remove (ml, info);
}

/* applies a new tree structure to an existing tree, but only by changing things
 * that have changed */
static void
build_subtree_diff (MessageList *ml,
                    ETreePath parent,
                    ETreePath path,
                    CamelFolderThreadNode *c,
                    gint *row)
{
    ETreeModel *etm = ml->model;
    ETreePath ap, *ai, *at, *tmp;
    CamelFolderThreadNode *bp, *bi, *bt;
    gint i, j, myrow = 0;

    ap = path;
    bp = c;

    while (ap || bp) {
        t (printf ("Processing row: %d (subtree row %d)\n", *row, myrow));
        if (ap == NULL) {
            t (printf ("out of old nodes\n"));
            /* ran out of old nodes - remaining nodes are added */
            add_node_diff (ml, parent, ap, bp, row, myrow);
            myrow++;
            bp = bp->next;
        } else if (bp == NULL) {
            t (printf ("out of new nodes\n"));
            /* ran out of new nodes - remaining nodes are removed */
            tmp = e_tree_model_node_get_next (etm, ap);
            remove_node_diff (ml, ap, 0);
            ap = tmp;
        } else if (node_equal (etm, ap, bp)) {
            *row = (*row)+1;
            myrow++;
            tmp = e_tree_model_node_get_first_child (etm, ap);
            /* make child lists match (if either has one) */
            if (bp->child || tmp) {
                build_subtree_diff (ml, ap, tmp, bp->child, row);
            }
            ap = e_tree_model_node_get_next (etm, ap);
            bp = bp->next;
        } else {
            t (printf ("searching for matches\n"));
            /* we have to scan each side for a match */
            bi = bp->next;
            ai = e_tree_model_node_get_next (etm, ap);
            for (i = 1; bi != NULL; i++,bi = bi->next) {
                if (node_equal (etm, ap, bi))
                    break;
            }
            for (j = 1; ai != NULL; j++,ai = e_tree_model_node_get_next (etm, ai)) {
                if (node_equal (etm, ai, bp))
                    break;
            }
            if (i < j) {
                /* smaller run of new nodes - must be nodes to add */
                if (bi) {
                    bt = bp;
                    while (bt != bi) {
                        t (printf ("adding new node 0\n"));
                        add_node_diff (ml, parent, NULL, bt, row, myrow);
                        myrow++;
                        bt = bt->next;
                    }
                    bp = bi;
                } else {
                    t (printf ("adding new node 1\n"));
                    /* no match in new nodes, add one, try next */
                    add_node_diff (ml, parent, NULL, bp, row, myrow);
                    myrow++;
                    bp = bp->next;
                }
            } else {
                /* bigger run of old nodes - must be nodes to remove */
                if (ai) {
                    at = ap;
                    while (at != NULL && at != ai) {
                        t (printf ("removing old node 0\n"));
                        tmp = e_tree_model_node_get_next (etm, at);
                        remove_node_diff (ml, at, 0);
                        at = tmp;
                    }
                    ap = ai;
                } else {
                    t (printf ("adding new node 2\n"));
                    /* didn't find match in old nodes, must be new node? */
                    add_node_diff (ml, parent, NULL, bp, row, myrow);
                    myrow++;
                    bp = bp->next;
                }
            }
        }
    }
}

static void
build_flat (MessageList *ml,
            GPtrArray *summary)
{
    ETreeModel *etm = ml->model;
    gchar *saveuid = NULL;
    gint i;
    GPtrArray *selected;
#ifdef TIMEIT
    struct timeval start, end;
    gulong diff;

    printf ("Building flat\n");
    gettimeofday (&start, NULL);
#endif

    if (ml->cursor_uid)
        saveuid = find_next_selectable (ml);

    selected = message_list_get_selected (ml);
    e_tree_memory_freeze (E_TREE_MEMORY (etm));
    clear_tree (ml, FALSE);
    for (i = 0; i < summary->len; i++) {
        CamelMessageInfo *info = summary->pdata[i];

        ml_uid_nodemap_insert (ml, info, NULL, -1);
    }
    e_tree_memory_thaw (E_TREE_MEMORY (etm));
    message_list_set_selected (ml, selected);
    em_utils_uids_free (selected);

    if (saveuid) {
        ETreePath node = g_hash_table_lookup (ml->uid_nodemap, saveuid);
        if (node == NULL) {
            g_free (ml->cursor_uid);
            ml->cursor_uid = NULL;
            g_signal_emit (ml, message_list_signals[MESSAGE_SELECTED], 0, NULL);
        } else {
            e_tree_set_cursor (E_TREE (ml), node);
        }
        g_free (saveuid);
    }

#ifdef TIMEIT
    gettimeofday (&end, NULL);
    diff = end.tv_sec * 1000 + end.tv_usec / 1000;
    diff -= start.tv_sec * 1000 + start.tv_usec / 1000;
    printf ("Building flat took %ld.%03ld seconds\n", diff / 1000, diff % 1000);
#endif

}

static void
message_list_change_first_visible_parent (MessageList *ml,
                                          ETreePath node)
{
    ETreePath first_visible = NULL;

    while (node && (node = e_tree_model_node_get_parent (ml->model, node))) {
        if (!e_tree_node_is_expanded (E_TREE (ml), node))
            first_visible = node;
    }

    if (first_visible != NULL) {
        e_tree_model_pre_change (ml->model);
        e_tree_model_node_data_changed (ml->model, first_visible);
    }
}

static CamelFolderChangeInfo *
mail_folder_hide_by_flag (CamelFolder *folder,
                          MessageList *ml,
                          CamelFolderChangeInfo *changes,
                          gint flag)
{
    CamelFolderChangeInfo *newchanges;
    CamelMessageInfo *info;
    gint i;

    newchanges = camel_folder_change_info_new ();

    for (i = 0; i < changes->uid_changed->len; i++) {
        ETreePath node;
        guint32 flags;

        node = g_hash_table_lookup (
            ml->uid_nodemap, changes->uid_changed->pdata[i]);
        info = camel_folder_get_message_info (
            folder, changes->uid_changed->pdata[i]);
        if (info)
            flags = camel_message_info_flags (info);

        if (node != NULL && info != NULL && (flags & flag) != 0)
            camel_folder_change_info_remove_uid (
                newchanges, changes->uid_changed->pdata[i]);
        else if (node == NULL && info != NULL && (flags & flag) == 0)
            camel_folder_change_info_add_uid (
                newchanges, changes->uid_changed->pdata[i]);
        else
            camel_folder_change_info_change_uid (
                newchanges, changes->uid_changed->pdata[i]);
        if (info)
            camel_folder_free_message_info (folder, info);
    }

    if (newchanges->uid_added->len > 0 || newchanges->uid_removed->len > 0) {
        for (i = 0; i < changes->uid_added->len; i++)
            camel_folder_change_info_add_uid (
                newchanges, changes->uid_added->pdata[i]);
        for (i = 0; i < changes->uid_removed->len; i++)
            camel_folder_change_info_remove_uid (
                newchanges, changes->uid_removed->pdata[i]);
    } else {
        camel_folder_change_info_clear (newchanges);
        camel_folder_change_info_cat (newchanges, changes);
    }

    return newchanges;
}

static void
message_list_folder_changed (CamelFolder *folder,
                             CamelFolderChangeInfo *changes,
                             MessageList *ml)
{
    CamelFolderChangeInfo *altered_changes = NULL;
    gboolean need_list_regen = TRUE;
    gboolean hide_junk;
    gboolean hide_deleted;
    gint i;

    if (ml->priv->destroyed)
        return;

    hide_junk = message_list_get_hide_junk (ml, folder);
    hide_deleted = message_list_get_hide_deleted (ml, folder);

    d (printf ("folder changed event, changes = %p\n", changes));
    if (changes != NULL) {
        for (i = 0; i < changes->uid_removed->len; i++)
            g_hash_table_remove (
                ml->normalised_hash,
                changes->uid_removed->pdata[i]);

        /* Check if the hidden state has changed.
         * If so, modify accordingly and regenerate. */
        if (hide_junk || hide_deleted)
            altered_changes = mail_folder_hide_by_flag (
                folder, ml, changes,
                (hide_junk ? CAMEL_MESSAGE_JUNK : 0) |
                (hide_deleted ? CAMEL_MESSAGE_DELETED : 0));
        else {
            altered_changes = camel_folder_change_info_new ();
            camel_folder_change_info_cat (altered_changes, changes);
        }

        if (altered_changes->uid_added->len == 0 && altered_changes->uid_removed->len == 0 && altered_changes->uid_changed->len < 100) {
            for (i = 0; i < altered_changes->uid_changed->len; i++) {
                ETreePath node = g_hash_table_lookup (ml->uid_nodemap, altered_changes->uid_changed->pdata[i]);
                if (node) {
                    e_tree_model_pre_change (ml->model);
                    e_tree_model_node_data_changed (ml->model, node);

                    message_list_change_first_visible_parent (ml, node);
                }
            }

            g_signal_emit (ml, message_list_signals[MESSAGE_LIST_BUILT], 0);

            need_list_regen = FALSE;
        }
    }

    if (need_list_regen)
        mail_regen_list (ml, ml->search, TRUE);

    if (altered_changes != NULL)
        camel_folder_change_info_free (altered_changes);
}

CamelFolder *
message_list_ref_folder (MessageList *message_list)
{
    CamelFolder *folder = NULL;

    /* XXX Do we need a property lock to guard this? */

    g_return_val_if_fail (IS_MESSAGE_LIST (message_list), NULL);

    if (message_list->priv->folder != NULL)
        folder = g_object_ref (message_list->priv->folder);

    return folder;
}

/**
 * message_list_set_folder:
 * @message_list: Message List widget
 * @folder: folder backend to be set
 *
 * Sets @folder to be the backend folder for @message_list.
 **/
void
message_list_set_folder (MessageList *message_list,
                         CamelFolder *folder)
{
    ETreeModel *etm = message_list->model;

    /* XXX Do we need a property lock to guard this? */

    g_return_if_fail (IS_MESSAGE_LIST (message_list));

    if (folder == message_list->priv->folder)
        return;

    if (folder != NULL) {
        g_return_if_fail (CAMEL_IS_FOLDER (folder));
        g_object_ref (folder);
    }

    g_free (message_list->search);
    message_list->search = NULL;

    g_free (message_list->frozen_search);
    message_list->frozen_search = NULL;

    if (message_list->seen_id) {
        g_source_remove (message_list->seen_id);
        message_list->seen_id = 0;
    }

    /* reset the normalised sort performance hack */
    g_hash_table_remove_all (message_list->normalised_hash);

    mail_regen_cancel (message_list);

    if (message_list->priv->folder != NULL)
        save_tree_state (message_list, message_list->priv->folder);

    e_tree_memory_freeze (E_TREE_MEMORY (etm));
    clear_tree (message_list, TRUE);
    e_tree_memory_thaw (E_TREE_MEMORY (etm));

    /* remove the cursor activate idle handler */
    if (message_list->idle_id != 0) {
        g_source_remove (message_list->idle_id);
        message_list->idle_id = 0;
    }

    if (message_list->priv->folder != NULL) {
        g_signal_handler_disconnect (
            message_list->priv->folder,
            message_list->priv->folder_changed_handler_id);
        message_list->priv->folder_changed_handler_id = 0;

        if (message_list->uid_nodemap != NULL)
            g_hash_table_foreach (
                message_list->uid_nodemap,
                (GHFunc) clear_info, message_list);

        g_clear_object (&message_list->priv->folder);
    }

    if (message_list->thread_tree != NULL) {
        camel_folder_thread_messages_unref (message_list->thread_tree);
        message_list->thread_tree = NULL;
    }

    g_free (message_list->cursor_uid);
    message_list->cursor_uid = NULL;

    /* Always emit message-selected, event when an account node
     * (folder == NULL) is selected, so that views know what happened and
     * can stop all running operations etc. */
    g_signal_emit (
        message_list, message_list_signals[MESSAGE_SELECTED], 0, NULL);

    if (folder != NULL) {
        CamelStore *store;
        gboolean non_trash_folder;
        gint strikeout_col;
        ECell *cell;
        gulong handler_id;

        message_list->priv->folder = folder;
        message_list->just_set_folder = TRUE;

        store = camel_folder_get_parent_store (folder);

        non_trash_folder =
            ((store->flags & CAMEL_STORE_VTRASH) == 0) ||
            ((folder->folder_flags & CAMEL_FOLDER_IS_TRASH) == 0);

        /* Setup the strikeout effect for non-trash folders */
        strikeout_col = non_trash_folder ? COL_DELETED : -1;

        cell = e_table_extras_get_cell (message_list->extras, "render_date");
        g_object_set (cell, "strikeout_column", strikeout_col, NULL);

        cell = e_table_extras_get_cell (message_list->extras, "render_text");
        g_object_set (cell, "strikeout_column", strikeout_col, NULL);

        cell = e_table_extras_get_cell (message_list->extras, "render_size");
        g_object_set (cell, "strikeout_column", strikeout_col, NULL);

        cell = e_table_extras_get_cell (message_list->extras, "render_composite_from");
        composite_cell_set_strike_col (cell, strikeout_col);

        cell = e_table_extras_get_cell (message_list->extras, "render_composite_to");
        composite_cell_set_strike_col (cell, strikeout_col);

        /* Build the etree suitable for this folder */
        message_list_setup_etree (message_list);

        handler_id = g_signal_connect (
            folder, "changed",
            G_CALLBACK (message_list_folder_changed),
            message_list);
        message_list->priv->folder_changed_handler_id = handler_id;

        if (message_list->frozen == 0)
            mail_regen_list (message_list, message_list->search, FALSE);
    }
}

GtkTargetList *
message_list_get_copy_target_list (MessageList *message_list)
{
    g_return_val_if_fail (IS_MESSAGE_LIST (message_list), NULL);

    return message_list->priv->copy_target_list;
}

GtkTargetList *
message_list_get_paste_target_list (MessageList *message_list)
{
    g_return_val_if_fail (IS_MESSAGE_LIST (message_list), NULL);

    return message_list->priv->paste_target_list;
}

gboolean
message_list_get_show_deleted (MessageList *message_list)
{
    g_return_val_if_fail (IS_MESSAGE_LIST (message_list), FALSE);

    return message_list->priv->show_deleted;
}

void
message_list_set_show_deleted (MessageList *message_list,
                               gboolean show_deleted)
{
    g_return_if_fail (IS_MESSAGE_LIST (message_list));

    if (show_deleted == message_list->priv->show_deleted)
        return;

    message_list->priv->show_deleted = show_deleted;

    g_object_notify (G_OBJECT (message_list), "show-deleted");

    /* Changing this property triggers a message list regen. */
    if (message_list->frozen == 0)
        mail_regen_list (message_list, message_list->search, FALSE);
}

gboolean
message_list_get_thread_latest (MessageList *message_list)
{
    g_return_val_if_fail (IS_MESSAGE_LIST (message_list), FALSE);

    return message_list->priv->thread_latest;
}

void
message_list_set_thread_latest (MessageList *message_list,
                                gboolean thread_latest)
{
    g_return_if_fail (IS_MESSAGE_LIST (message_list));

    if (thread_latest == message_list->priv->thread_latest)
        return;

    message_list->priv->thread_latest = thread_latest;

    g_object_notify (G_OBJECT (message_list), "thread-latest");
}

gboolean
message_list_get_thread_subject (MessageList *message_list)
{
    g_return_val_if_fail (IS_MESSAGE_LIST (message_list), FALSE);

    return message_list->priv->thread_subject;
}

void
message_list_set_thread_subject (MessageList *message_list,
                                 gboolean thread_subject)
{
    g_return_if_fail (IS_MESSAGE_LIST (message_list));

    if (thread_subject == message_list->priv->thread_subject)
        return;

    message_list->priv->thread_subject = thread_subject;

    g_object_notify (G_OBJECT (message_list), "thread-subject");
}

static gboolean
on_cursor_activated_idle (gpointer data)
{
    MessageList *message_list = data;
    ESelectionModel *esm;
    gint selected;

    esm = e_tree_get_selection_model (E_TREE (message_list));
    selected = e_selection_model_selected_count (esm);

    if (selected == 1 && message_list->cursor_uid) {
        d (printf ("emitting cursor changed signal, for uid %s\n", message_list->cursor_uid));
        g_signal_emit (message_list, message_list_signals[MESSAGE_SELECTED], 0, message_list->cursor_uid);
    } else {
        g_signal_emit (message_list, message_list_signals[MESSAGE_SELECTED], 0, NULL);
    }

    message_list->idle_id = 0;
    return FALSE;
}

static void
on_cursor_activated_cmd (ETree *tree,
                         gint row,
                         ETreePath path,
                         gpointer user_data)
{
    MessageList *message_list = MESSAGE_LIST (user_data);
    const gchar *new_uid;

    if (path == NULL)
        new_uid = NULL;
    else
        new_uid = get_message_uid (message_list, path);

    /* Do not check the cursor_uid and the new_uid values, because the
    * selected item (set in on_selection_changed_cmd) can be different
    * from the one with a cursor (when selecting with Ctrl, for example).
    * This has a little side-effect, when keeping list it that state,
    * then changing folders forth and back will select and move cursor
    * to that selected item. Does anybody consider it as a bug? */
    if ((message_list->cursor_uid == NULL && new_uid == NULL)
        || (message_list->last_sel_single && message_list->cursor_uid != NULL && new_uid != NULL))
        return;

    g_free (message_list->cursor_uid);
    message_list->cursor_uid = g_strdup (new_uid);

    if (!message_list->idle_id) {
        message_list->idle_id =
            g_idle_add_full (
                G_PRIORITY_LOW, on_cursor_activated_idle,
                message_list, NULL);
    }
}

static void
on_selection_changed_cmd (ETree *tree,
                          MessageList *ml)
{
    GPtrArray *uids;
    const gchar *newuid;
    ETreePath cursor;

    /* not sure if we could just ignore this for the cursor, i think sometimes you
     * only get a selection changed when you should also get a cursor activated? */
    uids = message_list_get_selected (ml);
    if (uids->len == 1)
        newuid = g_ptr_array_index (uids, 0);
    else if ((cursor = e_tree_get_cursor (tree)))
        newuid = (gchar *) camel_message_info_uid (e_tree_memory_node_get_data ((ETreeMemory *) tree, cursor));
    else
        newuid = NULL;

    /* If the selection isn't empty, then we ignore the no-uid check, since this event
     * is also used for other updating.  If it is empty, it might just be a setup event
     * from etree which we do need to ignore */
    if ((newuid == NULL && ml->cursor_uid == NULL && uids->len == 0) ||
        (ml->last_sel_single && uids->len == 1 && newuid != NULL && ml->cursor_uid != NULL && !strcmp (ml->cursor_uid, newuid))) {
        /* noop */
    } else {
        g_free (ml->cursor_uid);
        ml->cursor_uid = g_strdup (newuid);
        if (!ml->idle_id)
            ml->idle_id = g_idle_add_full (G_PRIORITY_LOW, on_cursor_activated_idle, ml, NULL);
    }

    ml->last_sel_single = uids->len == 1;

    em_utils_uids_free (uids);
}

static gint
on_click (ETree *tree,
          gint row,
          ETreePath path,
          gint col,
          GdkEvent *event,
          MessageList *list)
{
    CamelFolder *folder;
    CamelMessageInfo *info;
    gboolean folder_is_trash;
    const gchar *uid;
    gint flag = 0;
    guint32 flags;

    if (col == COL_MESSAGE_STATUS)
        flag = CAMEL_MESSAGE_SEEN;
    else if (col == COL_FLAGGED)
        flag = CAMEL_MESSAGE_FLAGGED;
    else if (col != COL_FOLLOWUP_FLAG_STATUS)
        return FALSE;

    if (!(info = get_message_info (list, path)))
        return FALSE;

    folder = message_list_ref_folder (list);
    g_return_val_if_fail (folder != NULL, FALSE);

    if (col == COL_FOLLOWUP_FLAG_STATUS) {
        const gchar *tag, *cmp;

        tag = camel_message_info_user_tag (info, "follow-up");
        cmp = camel_message_info_user_tag (info, "completed-on");
        if (tag && tag[0]) {
            if (cmp && cmp[0]) {
                camel_message_info_set_user_tag (info, "follow-up", NULL);
                camel_message_info_set_user_tag (info, "due-by", NULL);
                camel_message_info_set_user_tag (info, "completed-on", NULL);
            } else {
                gchar *text;

                text = camel_header_format_date (time (NULL), 0);
                camel_message_info_set_user_tag (info, "completed-on", text);
                g_free (text);
            }
        } else {
            /* default follow-up flag name to use when clicked in the message list column */
            camel_message_info_set_user_tag (info, "follow-up", _("Follow-up"));
            camel_message_info_set_user_tag (info, "completed-on", NULL);
        }

        return TRUE;
    }

    flags = camel_message_info_flags (info);

    folder_is_trash =
        ((folder->folder_flags & CAMEL_FOLDER_IS_TRASH) != 0);

    /* If a message was marked as deleted and the user flags it as
     * important or unread in a non-Trash folder, then undelete the
     * message.  We avoid automatically undeleting messages while
     * viewing a Trash folder because it would cause the message to
     * suddenly disappear from the message list, which is confusing
     * and alarming to the user. */
    if (!folder_is_trash && flags & CAMEL_MESSAGE_DELETED) {
        if (col == COL_FLAGGED && !(flags & CAMEL_MESSAGE_FLAGGED))
            flag |= CAMEL_MESSAGE_DELETED;

        if (col == COL_MESSAGE_STATUS && (flags & CAMEL_MESSAGE_SEEN))
            flag |= CAMEL_MESSAGE_DELETED;
    }

    uid = camel_message_info_uid (info);
    camel_folder_set_message_flags (folder, uid, flag, ~flags);

    /* Notify the folder tree model that the user has marked a message
     * as unread so it doesn't mistake the event as new mail arriving. */
    if (col == COL_MESSAGE_STATUS && (flags & CAMEL_MESSAGE_SEEN)) {
        EMFolderTreeModel *model;

        model = em_folder_tree_model_get_default ();
        em_folder_tree_model_user_marked_unread (model, folder, 1);
    }

    if (flag == CAMEL_MESSAGE_SEEN && list->seen_id) {
        g_source_remove (list->seen_id);
        list->seen_id = 0;
    }

    g_object_unref (folder);

    return TRUE;
}

struct _ml_selected_data {
    MessageList *ml;
    GPtrArray *uids;
};

static void
ml_getselected_cb (ETreePath path,
                   gpointer user_data)
{
    struct _ml_selected_data *data = user_data;
    const gchar *uid;

    if (e_tree_model_node_is_root (data->ml->model, path))
        return;

    uid = get_message_uid (data->ml, path);
    g_return_if_fail (uid != NULL);
    g_ptr_array_add (data->uids, g_strdup (uid));
}

GPtrArray *
message_list_get_uids (MessageList *ml)
{
    CamelFolder *folder;

    struct _ml_selected_data data = {
        ml,
        g_ptr_array_new ()
    };

    e_tree_path_foreach (E_TREE (ml), ml_getselected_cb, &data);

    folder = message_list_ref_folder (ml);

    if (folder != NULL && data.uids->len > 0)
        camel_folder_sort_uids (folder, data.uids);

    g_clear_object (&folder);

    return data.uids;
}

GPtrArray *
message_list_get_selected (MessageList *ml)
{
    CamelFolder *folder;

    struct _ml_selected_data data = {
        ml,
        g_ptr_array_new ()
    };

    e_tree_selected_path_foreach (E_TREE (ml), ml_getselected_cb, &data);

    folder = message_list_ref_folder (ml);

    if (folder != NULL && data.uids->len > 0)
        camel_folder_sort_uids (folder, data.uids);

    g_clear_object (&folder);

    return data.uids;
}

void
message_list_set_selected (MessageList *ml,
                           GPtrArray *uids)
{
    gint i;
    ETreeSelectionModel *etsm;
    ETreePath node;
    GPtrArray *paths = g_ptr_array_new ();

    etsm = (ETreeSelectionModel *) e_tree_get_selection_model (E_TREE (ml));
    for (i = 0; i < uids->len; i++) {
        node = g_hash_table_lookup (ml->uid_nodemap, uids->pdata[i]);
        if (node)
            g_ptr_array_add (paths, node);
    }

    e_tree_selection_model_select_paths (etsm, paths);
    g_ptr_array_free (paths, TRUE);
}

struct ml_sort_uids_data {
    gchar *uid;
    gint row;
};

static gint
ml_sort_uids_cb (gconstpointer a,
                 gconstpointer b)
{
    struct ml_sort_uids_data * const *pdataA = a;
    struct ml_sort_uids_data * const *pdataB = b;

    return (* pdataA)->row - (* pdataB)->row;
}

void
message_list_sort_uids (MessageList *message_list,
                        GPtrArray *uids)
{
    struct ml_sort_uids_data *data;
    GPtrArray *array;
    ETreePath path;
    ETreeTableAdapter *adapter;
    gint ii;

    g_return_if_fail (message_list != NULL);
    g_return_if_fail (IS_MESSAGE_LIST (message_list));
    g_return_if_fail (uids != NULL);

    if (uids->len <= 1)
        return;

    adapter = e_tree_get_table_adapter (E_TREE (message_list));

    array = g_ptr_array_new_full (uids->len, g_free);

    for (ii = 0; ii < uids->len; ii++) {
        data = g_new0 (struct ml_sort_uids_data, 1);
        data->uid = g_ptr_array_index (uids, ii);

        path = g_hash_table_lookup (message_list->uid_nodemap, data->uid);
        if (path)
            data->row = e_tree_table_adapter_row_of_node (adapter, path);
        else
            data->row = ii;

        g_ptr_array_add (array, data);
    }

    g_ptr_array_sort (array, ml_sort_uids_cb);

    for (ii = 0; ii < uids->len; ii++) {
        data = g_ptr_array_index (array, ii);

        uids->pdata[ii] = data->uid;
    }

    g_ptr_array_free (array, TRUE);
}

struct ml_count_data {
    MessageList *ml;
    guint count;
};

static void
ml_getcount_cb (ETreePath path,
                gpointer user_data)
{
    struct ml_count_data *data = user_data;

    if (!e_tree_model_node_is_root (data->ml->model, path))
        data->count++;
}

guint
message_list_count (MessageList *message_list)
{
    struct ml_count_data data = { message_list, 0 };

    g_return_val_if_fail (message_list != NULL, 0);
    g_return_val_if_fail (IS_MESSAGE_LIST (message_list), 0);

    e_tree_path_foreach (E_TREE (message_list), ml_getcount_cb, &data);

    return data.count;
}

static void
ml_getselcount_cb (gint model_row,
                   gpointer user_data)
{
    struct ml_count_data *data = user_data;

    data->count++;
}

guint
message_list_selected_count (MessageList *message_list)
{
    struct ml_count_data data = { message_list, 0 };

    g_return_val_if_fail (message_list != NULL, 0);
    g_return_val_if_fail (IS_MESSAGE_LIST (message_list), 0);

    e_tree_selected_row_foreach (E_TREE (message_list), ml_getselcount_cb, &data);

    return data.count;
}

void
message_list_freeze (MessageList *ml)
{
    ml->frozen++;
}

void
message_list_thaw (MessageList *ml)
{
    g_return_if_fail (ml->frozen != 0);

    ml->frozen--;
    if (ml->frozen == 0) {
        const gchar *search;

        if (ml->frozen_search != NULL)
            search = ml->frozen_search;
        else
            search = ml->search;

        mail_regen_list (ml, search, FALSE);

        g_free (ml->frozen_search);
        ml->frozen_search = NULL;
    }
}

/* set whether we are in threaded view or flat view */
void
message_list_set_threaded_expand_all (MessageList *ml)
{
    if (ml->threaded) {
        ml->expand_all = 1;

        if (ml->frozen == 0)
            mail_regen_list (ml, ml->search, FALSE);
    }
}

void
message_list_set_threaded_collapse_all (MessageList *ml)
{
    if (ml->threaded) {
        ml->collapse_all = 1;

        if (ml->frozen == 0)
            mail_regen_list (ml, ml->search, FALSE);
    }
}

void
message_list_set_threaded (MessageList *ml,
                           gboolean threaded)
{
    if (ml->threaded != threaded) {
        ml->threaded = threaded;

        if (ml->frozen == 0)
            mail_regen_list (ml, ml->search, FALSE);
    }
}

void
message_list_set_search (MessageList *ml,
                         const gchar *search)
{
    if (search == NULL || search[0] == '\0')
        if (ml->search == NULL || ml->search[0] == '\0')
            return;

    if (search != NULL && ml->search != NULL && strcmp (search, ml->search) == 0)
        return;

    if (ml->thread_tree) {
        camel_folder_thread_messages_unref (ml->thread_tree);
        ml->thread_tree = NULL;
    }

    if (ml->frozen == 0)
        mail_regen_list (ml, search, FALSE);
    else {
        g_free (ml->frozen_search);
        ml->frozen_search = g_strdup (search);
    }
}

struct sort_column_data {
    ETableCol *col;
    gboolean ascending;
};

struct sort_message_info_data {
    CamelMessageInfo *mi;
    GPtrArray *values; /* read values so far, in order of sort_array_data::sort_columns */
};

struct sort_array_data {
    MessageList *ml;
    CamelFolder *folder;
    GPtrArray *sort_columns; /* struct sort_column_data in order of sorting */
    GHashTable *message_infos; /* uid -> struct sort_message_info_data */
    gpointer cmp_cache;
    GCancellable *cancellable;
};

static gint
cmp_array_uids (gconstpointer a,
                gconstpointer b,
                gpointer user_data)
{
    const gchar *uid1 = *(const gchar **) a;
    const gchar *uid2 = *(const gchar **) b;
    struct sort_array_data *sort_data = user_data;
    gint i, res = 0;
    struct sort_message_info_data *md1, *md2;

    g_return_val_if_fail (sort_data != NULL, 0);

    md1 = g_hash_table_lookup (sort_data->message_infos, uid1);
    md2 = g_hash_table_lookup (sort_data->message_infos, uid2);

    g_return_val_if_fail (md1 != NULL, 0);
    g_return_val_if_fail (md1->mi != NULL, 0);
    g_return_val_if_fail (md2 != NULL, 0);
    g_return_val_if_fail (md2->mi != NULL, 0);

    if (g_cancellable_is_cancelled (sort_data->cancellable))
        return 0;

    for (i = 0;
         res == 0
         && i < sort_data->sort_columns->len
         && !g_cancellable_is_cancelled (sort_data->cancellable);
         i++) {
        gpointer v1, v2;
        struct sort_column_data *scol = g_ptr_array_index (sort_data->sort_columns, i);

        if (md1->values->len <= i) {
            v1 = ml_tree_value_at_ex (NULL, NULL, scol->col->compare_col, md1->mi, sort_data->ml);
            g_ptr_array_add (md1->values, v1);
        } else {
            v1 = g_ptr_array_index (md1->values, i);
        }

        if (md2->values->len <= i) {
            v2 = ml_tree_value_at_ex (NULL, NULL, scol->col->compare_col, md2->mi, sort_data->ml);
            g_ptr_array_add (md2->values, v2);
        } else {
            v2 = g_ptr_array_index (md2->values, i);
        }

        if (v1 != NULL && v2 != NULL) {
            res = (*scol->col->compare) (v1, v2, sort_data->cmp_cache);
        } else if (v1 != NULL || v2 != NULL) {
            res = v1 == NULL ? -1 : 1;
        }

        if (!scol->ascending)
            res = res * (-1);
    }

    if (res == 0)
        res = camel_folder_cmp_uids (sort_data->folder, uid1, uid2);

    return res;
}

static void
free_message_info_data (gpointer uid,
                        struct sort_message_info_data *data,
                        struct sort_array_data *sort_data)
{
    if (data->values) {
        /* values in this array are not newly allocated, even ml_tree_value_at_ex
         * returns gpointer, not a gconstpointer */
        g_ptr_array_free (data->values, TRUE);
    }

    camel_folder_free_message_info (sort_data->folder, data->mi);
    g_free (data);
}

static void
ml_sort_uids_by_tree (MessageList *ml,
                      GPtrArray *uids,
                      GCancellable *cancellable)
{
    ETreeTableAdapter *adapter;
    ETableSortInfo *sort_info;
    ETableHeader *full_header;
    CamelFolder *folder;
    struct sort_array_data sort_data;
    guint i, len;

    if (g_cancellable_is_cancelled (cancellable))
        return;

    g_return_if_fail (uids != NULL);

    folder = message_list_ref_folder (ml);
    g_return_if_fail (folder != NULL);

    adapter = e_tree_get_table_adapter (E_TREE (ml));
    g_return_if_fail (adapter != NULL);

    sort_info = e_tree_table_adapter_get_sort_info (adapter);
    full_header = e_tree_table_adapter_get_header (adapter);

    if (!sort_info || uids->len == 0 || !full_header || e_table_sort_info_sorting_get_count (sort_info) == 0) {
        camel_folder_sort_uids (folder, uids);
        g_object_unref (folder);
        return;
    }

    len = e_table_sort_info_sorting_get_count (sort_info);

    sort_data.ml = ml;
    sort_data.folder = folder;
    sort_data.sort_columns = g_ptr_array_sized_new (len);
    sort_data.message_infos = g_hash_table_new (g_str_hash, g_str_equal);
    sort_data.cmp_cache = e_table_sorting_utils_create_cmp_cache ();
    sort_data.cancellable = cancellable;

    for (i = 0;
         i < len
         && !g_cancellable_is_cancelled (cancellable);
         i++) {
        ETableSortColumn scol;
        struct sort_column_data *data = g_new0 (struct sort_column_data, 1);

        scol = e_table_sort_info_sorting_get_nth (sort_info, i);

        data->ascending = scol.ascending;
        data->col = e_table_header_get_column_by_col_idx (full_header, scol.column);
        if (data->col == NULL)
            data->col = e_table_header_get_column (full_header, e_table_header_count (full_header) - 1);

        g_ptr_array_add (sort_data.sort_columns, data);
    }

    camel_folder_summary_prepare_fetch_all (folder->summary, NULL);

    for (i = 0;
         i < uids->len
         && !g_cancellable_is_cancelled (cancellable);
         i++) {
        gchar *uid;
        CamelMessageInfo *mi;
        struct sort_message_info_data *md;

        uid = g_ptr_array_index (uids, i);
        mi = camel_folder_get_message_info (folder, uid);
        if (mi == NULL) {
            g_warning (
                "%s: Cannot find uid '%s' in folder '%s'",
                G_STRFUNC, uid,
                camel_folder_get_full_name (folder));
            continue;
        }

        md = g_new0 (struct sort_message_info_data, 1);
        md->mi = mi;
        md->values = g_ptr_array_sized_new (len);

        g_hash_table_insert (sort_data.message_infos, uid, md);
    }

    if (!g_cancellable_is_cancelled (cancellable))
        g_qsort_with_data (
            uids->pdata,
            uids->len,
            sizeof (gpointer),
            cmp_array_uids,
            &sort_data);

    camel_folder_summary_unlock (folder->summary, CAMEL_FOLDER_SUMMARY_SUMMARY_LOCK);

    /* FIXME Teach the hash table to destroy its own data. */
    g_hash_table_foreach (
        sort_data.message_infos,
        (GHFunc) free_message_info_data,
        &sort_data);
    g_hash_table_destroy (sort_data.message_infos);

    g_ptr_array_foreach (sort_data.sort_columns, (GFunc) g_free, NULL);
    g_ptr_array_free (sort_data.sort_columns, TRUE);

    e_table_sorting_utils_free_cmp_cache (sort_data.cmp_cache);

    g_object_unref (folder);
}

static void
message_list_regen_tweak_search_results (MessageList *message_list,
                                         GPtrArray *search_results,
                                         CamelFolder *folder,
                                         gboolean folder_changed,
                                         gboolean show_deleted,
                                         gboolean show_junk)
{
    CamelMessageInfo *info;
    CamelMessageFlags flags;
    const gchar *uid;
    gboolean needs_tweaking;
    gboolean uid_is_deleted;
    gboolean uid_is_junk;
    gboolean add_uid;
    guint ii;

    /* If we're responding to a "folder-changed" signal, then the
     * displayed message may not be included in the search results.
     * Include the displayed message anyway so it doesn't suddenly
     * disappear while the user is reading it. */
    needs_tweaking =
        (folder_changed && message_list->cursor_uid != NULL);

    if (!needs_tweaking)
        return;

    uid = message_list->cursor_uid;

    /* Scan the search results for a particular UID.
     * If found then the results don't need tweaked. */
    for (ii = 0; ii < search_results->len; ii++) {
        if (g_str_equal (uid, search_results->pdata[ii]))
            return;
    }

    info = camel_folder_get_message_info (folder, uid);

    /* XXX Should we emit a runtime warning here? */
    if (info == NULL)
        return;

    flags = camel_message_info_flags (info);
    uid_is_deleted = ((flags & CAMEL_MESSAGE_DELETED) != 0);
    uid_is_junk = ((flags & CAMEL_MESSAGE_JUNK) != 0);

    if (!folder_store_supports_vjunk_folder (folder))
        uid_is_junk = FALSE;

    add_uid =
        (!uid_is_junk || show_junk) &&
        (!uid_is_deleted || show_deleted);

    if (add_uid)
        g_ptr_array_add (
            search_results,
            (gpointer) camel_pstring_strdup (uid));

    camel_folder_free_message_info (folder, info);
}

static void
message_list_regen_thread (GSimpleAsyncResult *simple,
                           GObject *source_object,
                           GCancellable *cancellable)
{
    MessageList *message_list;
    RegenData *regen_data;
    GPtrArray *uids, *searchuids = NULL;
    CamelMessageInfo *info;
    ETreePath cursor;
    ETree *tree;
    GString *expr;
    gboolean hide_deleted;
    gboolean hide_junk;
    GError *local_error = NULL;

    message_list = MESSAGE_LIST (source_object);
    regen_data = g_simple_async_result_get_op_res_gpointer (simple);

    if (g_cancellable_is_cancelled (cancellable))
        return;

    hide_junk = message_list_get_hide_junk (
        message_list, regen_data->folder);
    hide_deleted = message_list_get_hide_deleted (
        message_list, regen_data->folder);

    tree = E_TREE (message_list);
    cursor = e_tree_get_cursor (tree);
    if (cursor != NULL)
        regen_data->last_row =
            e_tree_table_adapter_row_of_node (
            e_tree_get_table_adapter (tree), cursor);

    /* Construct the search expression. */

    expr = g_string_new ("");

    if (hide_deleted && hide_junk) {
        g_string_append_printf (
            expr, "(match-all (and %s %s))",
            EXCLUDE_DELETED_MESSAGES_EXPR,
            EXCLUDE_JUNK_MESSAGES_EXPR);
    } else if (hide_deleted) {
        g_string_append_printf (
            expr, "(match-all %s)",
            EXCLUDE_DELETED_MESSAGES_EXPR);
    } else if (hide_junk) {
        g_string_append_printf (
            expr, "(match-all %s)",
            EXCLUDE_JUNK_MESSAGES_EXPR);
    }

    if (regen_data->search != NULL) {
        if (expr->len == 0) {
            g_string_assign (expr, regen_data->search);
        } else {
            g_string_prepend (expr, "(and ");
            g_string_append_c (expr, ' ');
            g_string_append (expr, regen_data->search);
            g_string_append_c (expr, ')');
        }
    }

    /* Execute the search. */

    if (expr->len == 0) {
        uids = camel_folder_get_uids (regen_data->folder);
    } else {
        uids = camel_folder_search_by_expression (
            regen_data->folder, expr->str,
            cancellable, &local_error);

        /* XXX This indicates we need to use a different
         *     "free UID" function for some dumb reason. */
        searchuids = uids;

        if (uids != NULL)
            message_list_regen_tweak_search_results (
                message_list, uids,
                regen_data->folder,
                regen_data->folder_changed,
                !hide_deleted,
                !hide_junk);
    }

    g_string_free (expr, TRUE);

    /* Handle search error or cancellation. */

    if (local_error == NULL)
        g_cancellable_set_error_if_cancelled (
            cancellable, &local_error);

    if (local_error != NULL) {
        g_simple_async_result_take_error (simple, local_error);
        goto exit;
    }

    /* XXX This check might not be necessary.  A successfully completed
     *     search with no results should return an empty UID array, but
     *     still need to verify that. */
    if (uids == NULL)
        goto exit;

    /* update/build a new tree */
    if (regen_data->threaded) {
        ml_sort_uids_by_tree (message_list, uids, cancellable);

        if (regen_data->tree != NULL)
            camel_folder_thread_messages_apply (
                regen_data->tree, uids);
        else
            regen_data->tree = camel_folder_thread_messages_new (
                regen_data->folder, uids,
                regen_data->thread_subject);
    } else {
        guint ii;

        camel_folder_sort_uids (regen_data->folder, uids);
        regen_data->summary = g_ptr_array_new ();

        camel_folder_summary_prepare_fetch_all (
            regen_data->folder->summary, NULL);

        for (ii = 0; ii < uids->len; ii++) {
            info = camel_folder_get_message_info (
                regen_data->folder, uids->pdata[ii]);
            if (info != NULL)
                g_ptr_array_add (regen_data->summary, info);
        }
    }

exit:
    if (searchuids != NULL)
        camel_folder_search_free (regen_data->folder, searchuids);
    else if (uids != NULL)
        camel_folder_free_uids (regen_data->folder, uids);
}

static void
message_list_regen_done_cb (GObject *source_object,
                            GAsyncResult *result,
                            gpointer user_data)
{
    MessageList *message_list;
    GSimpleAsyncResult *simple;
    RegenData *regen_data;
    EActivity *activity;
    ETree *tree;
    ETreeTableAdapter *adapter;
    gboolean searching;
    GError *local_error = NULL;

    message_list = MESSAGE_LIST (source_object);
    simple = G_SIMPLE_ASYNC_RESULT (result);
    regen_data = g_simple_async_result_get_op_res_gpointer (simple);

    /* Withdraw our RegenData from the private struct, if it hasn't
     * already been replaced.  We have exclusive access to it now. */
    g_mutex_lock (&message_list->priv->regen_lock);
    if (message_list->priv->regen_data == regen_data) {
        regen_data_unref (message_list->priv->regen_data);
        message_list->priv->regen_data = NULL;
    }
    g_mutex_unlock (&message_list->priv->regen_lock);

    activity = regen_data->activity;

    g_simple_async_result_propagate_error (simple, &local_error);

    if (e_activity_handle_cancellation (activity, local_error)) {
        g_error_free (local_error);
        return;

    /* FIXME This should be handed off to an EAlertSink. */
    } else if (local_error != NULL) {
        g_warning ("%s: %s", G_STRFUNC, local_error->message);
        g_error_free (local_error);
        return;
    }

    e_activity_set_state (activity, E_ACTIVITY_COMPLETED);

    tree = E_TREE (message_list);
    adapter = e_tree_get_table_adapter (tree);

    /* Show the cursor unless we're responding to a
     * "folder-changed" signal from our CamelFolder. */
    if (!regen_data->folder_changed)
        e_tree_show_cursor_after_reflow (tree);

    g_signal_handlers_block_by_func (
        adapter, ml_tree_sorting_changed, message_list);

    g_free (message_list->search);
    message_list->search = g_strdup (regen_data->search);

    searching =
        (message_list->search != NULL) &&
        (*message_list->search != '\0');

    if (regen_data->threaded) {
        gboolean forcing_expand_state;

        forcing_expand_state =
            message_list->expand_all ||
            message_list->collapse_all;

        if (message_list->just_set_folder) {
            message_list->just_set_folder = FALSE;
            if (regen_data->expand_state != NULL) {
                /* Load state from disk rather than use
                 * the memory data when changing folders. */
                xmlFreeDoc (regen_data->expand_state);
                regen_data->expand_state = NULL;
            }
        }

        if (forcing_expand_state || searching) {
            if (message_list->expand_all || searching)
                e_tree_force_expanded_state (tree, 1);
            else
                e_tree_force_expanded_state (tree, -1);
        }

        /* Show the cursor unless we're responding to a
         * "folder-changed" signal from our CamelFolder. */
        build_tree (
            message_list,
            regen_data->tree,
            regen_data->folder_changed);

        if (message_list->thread_tree != NULL)
            camel_folder_thread_messages_unref (
                message_list->thread_tree);
        message_list->thread_tree = regen_data->tree;
        regen_data->tree = NULL;

        if (forcing_expand_state || searching) {
            if (message_list->priv->folder != NULL &&
                tree != NULL && !searching)
                save_tree_state (
                    message_list,
                    regen_data->folder);
            /* do not forget to set this back to use the default value... */
            e_tree_force_expanded_state (tree, 0);
        } else {
            load_tree_state (
                message_list,
                regen_data->folder,
                regen_data->expand_state);
        }

        message_list->expand_all = 0;
        message_list->collapse_all = 0;
    } else {
        build_flat (
            message_list,
            regen_data->summary);
    }

    if (regen_data->select_all) {
        message_list_select_all (message_list);

    } else if (regen_data->select_uid != NULL) {
        message_list_select_uid (
            message_list,
            regen_data->select_uid,
            regen_data->select_use_fallback);

    } else if (message_list->cursor_uid == NULL && regen_data->last_row != -1) {
        gint row_count;

        row_count = e_table_model_row_count (E_TABLE_MODEL (adapter));

        if (regen_data->last_row >= row_count)
            regen_data->last_row = row_count;

        if (regen_data->last_row >= 0) {
            ETreePath path;

            path = e_tree_table_adapter_node_at_row (
                adapter, regen_data->last_row);
            if (path != NULL)
                select_path (message_list, path);
        }
    }

    if (gtk_widget_get_visible (GTK_WIDGET (message_list))) {
        const gchar *info_message;
        gboolean have_search_expr;

        /* space is used to indicate no search too */
        have_search_expr =
            (message_list->search != NULL) &&
            (*message_list->search != '\0') &&
            (strcmp (message_list->search, " ") != 0);

        if (e_tree_row_count (E_TREE (tree)) > 0) {
            info_message = NULL;
        } else if (have_search_expr) {
            info_message =
                _("No message satisfies your search criteria. "
                "Change search criteria by selecting a new "
                "Show message filter from the drop down list "
                "above or by running a new search either by "
                "clearing it with Search->Clear menu item or "
                "by changing the query above.");
        } else {
            info_message =
                _("There are no messages in this folder.");
        }

        e_tree_set_info_message (tree, info_message);
    }

    g_signal_handlers_unblock_by_func (
        adapter, ml_tree_sorting_changed, message_list);

    g_signal_emit (
        message_list,
        message_list_signals[MESSAGE_LIST_BUILT], 0);

    message_list->priv->any_row_changed = FALSE;
}

static gboolean
message_list_regen_timeout_cb (gpointer user_data)
{
    GSimpleAsyncResult *simple;
    RegenData *regen_data;
    GCancellable *cancellable;

    simple = G_SIMPLE_ASYNC_RESULT (user_data);
    regen_data = g_simple_async_result_get_op_res_gpointer (simple);
    cancellable = e_activity_get_cancellable (regen_data->activity);

    g_mutex_lock (&regen_data->message_list->priv->regen_lock);
    regen_data->message_list->priv->regen_timeout_id = 0;
    g_mutex_unlock (&regen_data->message_list->priv->regen_lock);

    if (g_cancellable_is_cancelled (cancellable)) {
        g_simple_async_result_complete (simple);
    } else {
        g_simple_async_result_run_in_thread (
            simple,
            message_list_regen_thread,
            G_PRIORITY_DEFAULT,
            cancellable);
    }

    return FALSE;
}

static void
mail_regen_cancel (MessageList *message_list)
{
    RegenData *regen_data = NULL;

    g_mutex_lock (&message_list->priv->regen_lock);

    if (message_list->priv->regen_data != NULL)
        regen_data = regen_data_ref (message_list->priv->regen_data);

    if (message_list->priv->regen_timeout_id > 0) {
        g_source_remove (message_list->priv->regen_timeout_id);
        message_list->priv->regen_timeout_id = 0;
    }

    g_mutex_unlock (&message_list->priv->regen_lock);

    /* Cancel outside the lock, since this will emit a signal. */
    if (regen_data != NULL) {
        e_activity_cancel (regen_data->activity);
        regen_data_unref (regen_data);
    }
}

static void
mail_regen_list (MessageList *message_list,
                 const gchar *search,
                 gboolean folder_changed)
{
    GSimpleAsyncResult *simple;
    GCancellable *cancellable;
    RegenData *new_regen_data;
    RegenData *old_regen_data;
    gboolean searching;

    /* Report empty search as NULL, not as one/two-space string. */
    if (search && (strcmp (search, " ") == 0 || strcmp (search, "  ") == 0))
        search = NULL;

    /* Can't list messages in a folder until we have a folder. */
    if (message_list->priv->folder == NULL) {
        g_free (message_list->search);
        message_list->search = g_strdup (search);
        return;
    }

    cancellable = g_cancellable_new ();

    new_regen_data = regen_data_new (message_list, cancellable);
    new_regen_data->search = g_strdup (search);
    new_regen_data->folder_changed = folder_changed;

    if (message_list->thread_tree != NULL) {
        CamelFolderThread *thread_tree;
        gboolean hide_deleted;

        thread_tree = message_list->thread_tree;
        hide_deleted = message_list_get_hide_deleted (
            message_list, new_regen_data->folder);

        if (message_list->threaded && hide_deleted) {
            new_regen_data->tree = thread_tree;
            camel_folder_thread_messages_ref (thread_tree);
        } else {
            camel_folder_thread_messages_unref (thread_tree);
            message_list->thread_tree = NULL;
        }
    }

    searching = (g_strcmp0 (message_list->search, " ") != 0);

    if (e_tree_row_count (E_TREE (message_list)) <= 0) {
        if (gtk_widget_get_visible (GTK_WIDGET (message_list))) {
            gchar *txt;

            txt = g_strdup_printf (
                "%s...", _("Generating message list"));
            e_tree_set_info_message (E_TREE (message_list), txt);
            g_free (txt);
        }
    } else if (message_list->priv->any_row_changed &&
           message_list->threaded &&
           !message_list->just_set_folder &&
           !searching) {
        /* Something changed.  If it was an expand
         * state change, then save the expand state. */
        message_list_save_state (message_list);
    } else if (message_list->threaded &&
           !message_list->just_set_folder &&
           !searching) {
        /* Remember the expand state and restore it after regen. */
        new_regen_data->expand_state =
            e_tree_save_expanded_state_xml (E_TREE (message_list));
    }

    /* We generate the message list content in a worker thread, and
     * then supply our own GAsyncReadyCallback to redraw the widget. */

    simple = g_simple_async_result_new (
        G_OBJECT (message_list),
        message_list_regen_done_cb,
        NULL, mail_regen_list);

    g_simple_async_result_set_check_cancellable (simple, cancellable);

    g_simple_async_result_set_op_res_gpointer (
        simple,
        regen_data_ref (new_regen_data),
        (GDestroyNotify) regen_data_unref);

    /* Swap the old regen data (if present) for the new regen data. */

    g_mutex_lock (&message_list->priv->regen_lock);

    old_regen_data = message_list->priv->regen_data;
    message_list->priv->regen_data = regen_data_ref (new_regen_data);

    if (message_list->priv->regen_timeout_id > 0) {
        g_source_remove (message_list->priv->regen_timeout_id);
        message_list->priv->regen_timeout_id = 0;
    }

    /* Start the regen after a short timeout, so normal updates
     * are immediate.  XXX Do we still need to do this timeout?
     * What are "normal" updates? */
    if (old_regen_data != NULL) {
        message_list->priv->regen_timeout_id =
            g_timeout_add_full (
                G_PRIORITY_DEFAULT, 50,
                message_list_regen_timeout_cb,
                g_object_ref (simple),
                (GDestroyNotify) g_object_unref);
    } else {
        g_simple_async_result_run_in_thread (
            simple,
            message_list_regen_thread,
            G_PRIORITY_DEFAULT,
            cancellable);
    }

    g_mutex_unlock (&message_list->priv->regen_lock);

    /* Cancel outside the lock, since this will emit a signal. */
    if (old_regen_data != NULL) {
        e_activity_cancel (old_regen_data->activity);
        regen_data_unref (old_regen_data);
    }

    g_object_unref (simple);

    regen_data_unref (new_regen_data);

    g_object_unref (cancellable);
}