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

#include "prsystem.h"

#include "nsMessenger.h"

// xpcom
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsIStringStream.h"
#include "nsIFile.h"
#include "nsDirectoryServiceDefs.h"
#include "nsQuickSort.h"
#include "nsNativeCharsetUtils.h"
#include "nsIMutableArray.h"
#include "mozilla/Services.h"

// necko
#include "nsMimeTypes.h"
#include "nsIURL.h"
#include "nsIPrompt.h"
#include "nsIStreamListener.h"
#include "nsIStreamConverterService.h"
#include "nsNetUtil.h"
#include "nsIFileURL.h"
#include "nsIMIMEInfo.h"

// rdf
#include "nsIRDFResource.h"
#include "nsIRDFService.h"
#include "nsRDFCID.h"

// gecko
#include "nsLayoutCID.h"
#include "nsIContentViewer.h"

// embedding
#ifdef NS_PRINTING
#include "nsIWebBrowserPrint.h"
#include "nsMsgPrintEngine.h"
#endif

/* for access to docshell */
#include "nsPIDOMWindow.h"
#include "nsIDocShell.h"
#include "nsIDocShellLoadInfo.h"
#include "nsIDocShellTreeItem.h"
#include "nsIWebNavigation.h"

// mail
#include "nsIMsgMailNewsUrl.h"
#include "nsMsgBaseCID.h"
#include "nsIMsgAccountManager.h"
#include "nsIMsgMailSession.h"
#include "nsIMailboxUrl.h"
#include "nsIMsgFolder.h"
#include "nsMsgFolderFlags.h"
#include "nsMsgMessageFlags.h"
#include "nsIMsgIncomingServer.h"

#include "nsIMsgMessageService.h"
#include "nsMsgRDFUtils.h"

#include "nsIMsgHdr.h"
#include "nsIMimeMiscStatus.h"
// compose
#include "nsMsgCompCID.h"
#include "nsMsgI18N.h"
#include "nsNativeCharsetUtils.h"

// draft/folders/sendlater/etc
#include "nsIMsgCopyService.h"
#include "nsIMsgCopyServiceListener.h"
#include "nsIUrlListener.h"

// undo
#include "nsITransaction.h"
#include "nsMsgTxn.h"

// charset conversions
#include "nsMsgMimeCID.h"
#include "nsIMimeConverter.h"

// Save As
#include "nsIFilePicker.h"
#include "nsIStringBundle.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsCExternalHandlerService.h"
#include "nsIExternalProtocolService.h"
#include "nsIMIMEService.h"
#include "nsITransfer.h"

#include "nsILinkHandler.h"

static NS_DEFINE_CID(kRDFServiceCID,  NS_RDFSERVICE_CID);

#define MESSENGER_SAVE_DIR_PREF_NAME "messenger.save.dir"
#define MIMETYPE_DELETED    "text/x-moz-deleted"
#define ATTACHMENT_PERMISSION 00664

//
// Convert an nsString buffer to plain text...
//
#include "nsMsgUtils.h"
#include "nsCharsetSource.h"
#include "nsIChannel.h"
#include "nsIOutputStream.h"
#include "nsIPrincipal.h"

static void ConvertAndSanitizeFileName(const char * displayName, nsString& aResult)
{
  nsCString unescapedName;

  /* we need to convert the UTF-8 fileName to platform specific character set.
     The display name is in UTF-8 because it has been escaped from JS
  */
  MsgUnescapeString(nsDependentCString(displayName), 0, unescapedName);
  CopyUTF8toUTF16(unescapedName, aResult);

  // replace platform specific path separator and illegale characters to avoid any confusion
  MsgReplaceChar(aResult, FILE_PATH_SEPARATOR FILE_ILLEGAL_CHARACTERS, '-');
}

// ***************************************************
// jefft - this is a rather obscured class serves for Save Message As File,
// Save Message As Template, and Save Attachment to a file
//
class nsSaveAllAttachmentsState;

class nsSaveMsgListener : public nsIUrlListener,
                          public nsIMsgCopyServiceListener,
                          public nsIStreamListener,
                          public nsICancelable
{
public:
  nsSaveMsgListener(nsIFile *file, nsMessenger *aMessenger, nsIUrlListener *aListener);

  NS_DECL_ISUPPORTS

  NS_DECL_NSIURLLISTENER
  NS_DECL_NSIMSGCOPYSERVICELISTENER
  NS_DECL_NSISTREAMLISTENER
  NS_DECL_NSIREQUESTOBSERVER
  NS_DECL_NSICANCELABLE

  nsCOMPtr<nsIFile> m_file;
  nsCOMPtr<nsIOutputStream> m_outputStream;
  char m_dataBuffer[FILE_IO_BUFFER_SIZE];
  nsCOMPtr<nsIChannel> m_channel;
  nsCString m_templateUri;
  nsMessenger *m_messenger; // not ref counted
  nsSaveAllAttachmentsState *m_saveAllAttachmentsState;

  // rhp: For character set handling
  bool          m_doCharsetConversion;
  nsString      m_charset;
  enum {
    eUnknown,
    ePlainText,
    eHTML
  }             m_outputFormat;
  nsCString     m_msgBuffer;

  nsCString     m_contentType;    // used only when saving attachment

  nsCOMPtr<nsITransfer> mTransfer;
  nsCOMPtr<nsIUrlListener> mListener;
  nsCOMPtr<nsIURI> mListenerUri;
  int64_t mProgress;
  int64_t mMaxProgress;
  bool    mCanceled;
  bool    mInitialized;
  bool    mUrlHasStopped;
  bool    mRequestHasStopped;
  nsresult InitializeDownload(nsIRequest * aRequest);

private:
  virtual ~nsSaveMsgListener();
};

class nsSaveAllAttachmentsState
{
public:
  nsSaveAllAttachmentsState(uint32_t count,
                            const char **contentTypeArray,
                            const char **urlArray,
                            const char **displayNameArray,
                            const char **messageUriArray,
                            const char *directoryName,
                            bool detachingAttachments);
  virtual ~nsSaveAllAttachmentsState();

  uint32_t m_count;
  uint32_t m_curIndex;
  char* m_directoryName;
  char** m_contentTypeArray;
  char** m_urlArray;
  char** m_displayNameArray;
  char** m_messageUriArray;
  bool m_detachingAttachments;

  // if detaching, do without warning? Will create unique files instead of
  //  prompting if duplicate files exist.
  bool m_withoutWarning;
  nsTArray<nsCString> m_savedFiles; // if detaching first, remember where we saved to.
};

//
// nsMessenger
//
nsMessenger::nsMessenger()
{
  mCurHistoryPos = -2; // first message selected goes at position 0.
  //  InitializeFolderRoot();
}

nsMessenger::~nsMessenger()
{
}


NS_IMPL_ISUPPORTS(nsMessenger, nsIMessenger, nsISupportsWeakReference, nsIFolderListener)

NS_IMETHODIMP nsMessenger::SetWindow(mozIDOMWindowProxy *aWin, nsIMsgWindow *aMsgWindow)
{
  nsresult rv;

  nsCOMPtr<nsIMsgMailSession> mailSession =
    do_GetService(NS_MSGMAILSESSION_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  if (aWin)
  {
    mMsgWindow = aMsgWindow;
    mWindow = aWin;

    rv = mailSession->AddFolderListener(this, nsIFolderListener::removed);
    NS_ENSURE_SUCCESS(rv, rv);

    NS_ENSURE_TRUE(aWin, NS_ERROR_FAILURE);
    nsCOMPtr<nsPIDOMWindowOuter> win = nsPIDOMWindowOuter::From(aWin);

    nsIDocShell *docShell = win->GetDocShell();
    nsCOMPtr<nsIDocShellTreeItem> docShellAsItem(do_QueryInterface(docShell));
    NS_ENSURE_TRUE(docShellAsItem, NS_ERROR_FAILURE);

    nsCOMPtr<nsIDocShellTreeItem> rootDocShellAsItem;
    docShellAsItem->GetSameTypeRootTreeItem(getter_AddRefs(rootDocShellAsItem));

    nsCOMPtr<nsIDocShellTreeItem> childAsItem;
    rv = rootDocShellAsItem->FindChildWithName(NS_LITERAL_STRING("messagepane"), true, false,
                                               nullptr, nullptr, getter_AddRefs(childAsItem));

    mDocShell = do_QueryInterface(childAsItem);
    if (NS_SUCCEEDED(rv) && mDocShell) {
      mCurrentDisplayCharset = ""; // Important! Clear out mCurrentDisplayCharset so we reset a default charset on mDocshell the next time we try to load something into it.

      if (aMsgWindow)
        aMsgWindow->GetTransactionManager(getter_AddRefs(mTxnMgr));
    }

    // we don't always have a message pane, like in the addressbook
    // so if we don't have a docshell, use the one for the xul window.
    // we do this so OpenURL() will work.
    if (!mDocShell)
      mDocShell = docShell;
  } // if aWin
  else
  {
    // Remove the folder listener if we added it, i.e. if mWindow is non-null
    if (mWindow)
    {
      rv = mailSession->RemoveFolderListener(this);
      NS_ENSURE_SUCCESS(rv, rv);
    }

    mWindow = nullptr;
  }

  return NS_OK;
}

NS_IMETHODIMP nsMessenger::SetDisplayCharset(const nsACString& aCharset)
{
  // libmime always converts to UTF-8 (both HTML and XML)
  if (mDocShell)
  {
    nsCOMPtr<nsIContentViewer> cv;
    mDocShell->GetContentViewer(getter_AddRefs(cv));
    if (cv)
    {
      cv->SetHintCharacterSet(aCharset);
      cv->SetHintCharacterSetSource(kCharsetFromChannel);

      mCurrentDisplayCharset = aCharset;
    }
  }

  return NS_OK;
}

nsresult
nsMessenger::PromptIfFileExists(nsIFile *file)
{
  nsresult rv = NS_ERROR_FAILURE;
  bool exists;
  file->Exists(&exists);
  if (exists)
  {
    nsCOMPtr<nsIPrompt> dialog(do_GetInterface(mDocShell));
    if (!dialog) return rv;
    nsAutoString path;
    bool dialogResult = false;
    nsString errorMessage;

    file->GetPath(path);
    const char16_t *pathFormatStrings[] = { path.get() };

    if (!mStringBundle)
    {
      rv = InitStringBundle();
      NS_ENSURE_SUCCESS(rv, rv);
    }
    rv = mStringBundle->FormatStringFromName(u"fileExists",
                                             pathFormatStrings, 1,
                                             getter_Copies(errorMessage));
    NS_ENSURE_SUCCESS(rv, rv);
    rv = dialog->Confirm(nullptr, errorMessage.get(), &dialogResult);
    NS_ENSURE_SUCCESS(rv, rv);

    if (dialogResult)
    {
      return NS_OK; // user says okay to replace
    }
    else
    {
      // if we don't re-init the path for redisplay the picker will
      // show the full path, not just the file name
      nsCOMPtr<nsIFile> currentFile = do_CreateInstance("@mozilla.org/file/local;1");
      if (!currentFile) return NS_ERROR_FAILURE;

      rv = currentFile->InitWithPath(path);
      NS_ENSURE_SUCCESS(rv, rv);

      nsAutoString leafName;
      currentFile->GetLeafName(leafName);
      if (!leafName.IsEmpty())
        path.Assign(leafName); // path should be a copy of leafName

      nsCOMPtr<nsIFilePicker> filePicker =
        do_CreateInstance("@mozilla.org/filepicker;1", &rv);
      NS_ENSURE_SUCCESS(rv, rv);
      nsString saveAttachmentStr;
      GetString(NS_LITERAL_STRING("SaveAttachment"), saveAttachmentStr);
      filePicker->Init(mWindow,
                       saveAttachmentStr,
                       nsIFilePicker::modeSave);
      filePicker->SetDefaultString(path);
      filePicker->AppendFilters(nsIFilePicker::filterAll);

      nsCOMPtr <nsIFile> lastSaveDir;
      rv = GetLastSaveDirectory(getter_AddRefs(lastSaveDir));
      if (NS_SUCCEEDED(rv) && lastSaveDir) {
        filePicker->SetDisplayDirectory(lastSaveDir);
      }

      int16_t dialogReturn;
      rv = filePicker->Show(&dialogReturn);
      if (NS_FAILED(rv) || dialogReturn == nsIFilePicker::returnCancel) {
        // XXX todo
        // don't overload the return value like this
        // change this function to have an out boolean
        // that we check to see if the user cancelled
        return NS_ERROR_FAILURE;
      }

      nsCOMPtr<nsIFile> localFile;

      rv = filePicker->GetFile(getter_AddRefs(localFile));
      NS_ENSURE_SUCCESS(rv, rv);

      rv = SetLastSaveDirectory(localFile);
      NS_ENSURE_SUCCESS(rv,rv);

      // reset the file to point to the new path
      return file->InitWithFile(localFile);
    }
  }
  else
  {
    return NS_OK;
  }
  return rv;
}

NS_IMETHODIMP
nsMessenger::AddMsgUrlToNavigateHistory(const nsACString& aURL)
{
  // mNavigatingToUri is set to a url if we're already doing a back/forward,
  // in which case we don't want to add the url to the history list.
  // Or if the entry at the cur history pos is the same as what we're loading, don't
  // add it to the list.
  if (!mNavigatingToUri.Equals(aURL) && (mCurHistoryPos < 0 || !mLoadedMsgHistory[mCurHistoryPos].Equals(aURL)))
  {
    mNavigatingToUri = aURL;
    nsCString curLoadedFolderUri;
    nsCOMPtr <nsIMsgFolder> curLoadedFolder;

    mMsgWindow->GetOpenFolder(getter_AddRefs(curLoadedFolder));
    // for virtual folders, we want to select the right folder,
    // which isn't the same as the folder specified in the msg uri.
    // So add the uri for the currently loaded folder to the history list.
    if (curLoadedFolder)
      curLoadedFolder->GetURI(curLoadedFolderUri);

    mLoadedMsgHistory.InsertElementAt(mCurHistoryPos++ + 2, mNavigatingToUri);
    mLoadedMsgHistory.InsertElementAt(mCurHistoryPos++ + 2, curLoadedFolderUri);
    // we may want to prune this history if it gets large, but I think it's
    // more interesting to prune the back and forward menu.
  }
  return NS_OK;
}

NS_IMETHODIMP
nsMessenger::OpenURL(const nsACString& aURL)
{
  // This is to setup the display DocShell as UTF-8 capable...
  SetDisplayCharset(NS_LITERAL_CSTRING("UTF-8"));

  nsCOMPtr <nsIMsgMessageService> messageService;
  nsresult rv = GetMessageServiceFromURI(aURL, getter_AddRefs(messageService));

  if (NS_SUCCEEDED(rv) && messageService)
  {
    nsCOMPtr<nsIURI> dummyNull;
    messageService->DisplayMessage(PromiseFlatCString(aURL).get(), mDocShell,
        mMsgWindow, nullptr, nullptr, getter_AddRefs(dummyNull));
    AddMsgUrlToNavigateHistory(aURL);
    mLastDisplayURI = aURL; // remember the last uri we displayed....
    return NS_OK;
  }

  nsCOMPtr<nsIWebNavigation> webNav(do_QueryInterface(mDocShell));
  if(!webNav)
    return NS_ERROR_FAILURE;
  rv = webNav->LoadURI(NS_ConvertASCIItoUTF16(aURL).get(),   // URI string
                       nsIWebNavigation::LOAD_FLAGS_IS_LINK, // Load flags
                       nullptr,                               // Referring URI
                       nullptr,                               // Post stream
                       nullptr);                              // Extra headers
  return rv;
}

NS_IMETHODIMP nsMessenger::LaunchExternalURL(const nsACString& aURL)
{
  nsresult rv;

  nsCOMPtr<nsIURI> uri;
  rv = NS_NewURI(getter_AddRefs(uri), PromiseFlatCString(aURL).get());
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIExternalProtocolService> extProtService = do_GetService(NS_EXTERNALPROTOCOLSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv,rv);
  return extProtService->LoadUrl(uri);
}

NS_IMETHODIMP
nsMessenger::LoadURL(mozIDOMWindowProxy *aWin, const nsACString& aURL)
{
  nsresult rv;

  SetDisplayCharset(NS_LITERAL_CSTRING("UTF-8"));

  NS_ConvertASCIItoUTF16 uriString(aURL);
  // Cleanup the empty spaces that might be on each end.
  uriString.Trim(" ");
  // Eliminate embedded newlines, which single-line text fields now allow:
  uriString.StripChars("\r\n");
  NS_ENSURE_TRUE(!uriString.IsEmpty(), NS_ERROR_FAILURE);

  bool loadingFromFile = false;
  bool getDummyMsgHdr = false;
  int64_t fileSize;

  if (StringBeginsWith(uriString, NS_LITERAL_STRING("file:")))
  {
    nsCOMPtr<nsIURI> fileUri;
    rv = NS_NewURI(getter_AddRefs(fileUri), uriString);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr <nsIFileURL> fileUrl = do_QueryInterface(fileUri, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr <nsIFile> file;
    rv = fileUrl->GetFile(getter_AddRefs(file));
    NS_ENSURE_SUCCESS(rv, rv);
    file->GetFileSize(&fileSize);
    uriString.Replace(0, 5, NS_LITERAL_STRING("mailbox:"));
    uriString.Append(NS_LITERAL_STRING("&number=0"));
    loadingFromFile = true;
    getDummyMsgHdr = true;
  }
  else if (StringBeginsWith(uriString, NS_LITERAL_STRING("mailbox:")) &&
           (CaseInsensitiveFindInReadable(NS_LITERAL_STRING(".eml?"), uriString)))
  {
    // if we have a mailbox:// url that points to an .eml file, we have to read
    // the file size as well
    uriString.Replace(0, 8, NS_LITERAL_STRING("file:"));
    nsCOMPtr<nsIURI> fileUri;
    rv = NS_NewURI(getter_AddRefs(fileUri), uriString);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr <nsIFileURL> fileUrl = do_QueryInterface(fileUri, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    nsCOMPtr <nsIFile> file;
    rv = fileUrl->GetFile(getter_AddRefs(file));
    NS_ENSURE_SUCCESS(rv, rv);
    file->GetFileSize(&fileSize);
    uriString.Replace(0, 5, NS_LITERAL_STRING("mailbox:"));
    loadingFromFile = true;
    getDummyMsgHdr = true;
  }
  else if (uriString.Find("type=application/x-message-display") >= 0)
    getDummyMsgHdr = true;

  nsCOMPtr<nsIURI> uri;
  rv = NS_NewURI(getter_AddRefs(uri), uriString);
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ENSURE_TRUE(mDocShell, NS_ERROR_FAILURE);
  nsCOMPtr<nsIMsgMailNewsUrl> msgurl = do_QueryInterface(uri);
  if (msgurl)
  {
    msgurl->SetMsgWindow(mMsgWindow);
    if (loadingFromFile || getDummyMsgHdr)
    {
      if (loadingFromFile)
      {
        nsCOMPtr <nsIMailboxUrl> mailboxUrl = do_QueryInterface(msgurl, &rv);
        mailboxUrl->SetMessageSize((uint32_t) fileSize);
      }
      if (getDummyMsgHdr)
      {
        nsCOMPtr <nsIMsgHeaderSink> headerSink;
         // need to tell the header sink to capture some headers to create a fake db header
         // so we can do reply to a .eml file or a rfc822 msg attachment.
        mMsgWindow->GetMsgHeaderSink(getter_AddRefs(headerSink));
        if (headerSink)
        {
          nsCOMPtr <nsIMsgDBHdr> dummyHeader;
          headerSink->GetDummyMsgHeader(getter_AddRefs(dummyHeader));
          if (dummyHeader && loadingFromFile)
            dummyHeader->SetMessageSize((uint32_t) fileSize);
        }
      }
    }
  }

  nsCOMPtr<nsIDocShellLoadInfo> loadInfo;
  rv = mDocShell->CreateLoadInfo(getter_AddRefs(loadInfo));
  NS_ENSURE_SUCCESS(rv, rv);
  loadInfo->SetLoadType(nsIDocShellLoadInfo::loadNormal);
  AddMsgUrlToNavigateHistory(aURL);
  mNavigatingToUri.Truncate();
  mLastDisplayURI = aURL; // Remember the last uri we displayed.
  return mDocShell->LoadURI(uri, loadInfo, 0, true);
}

NS_IMETHODIMP nsMessenger::SaveAttachmentToFile(nsIFile *aFile,
                                                const nsACString &aURL,
                                                const nsACString &aMessageUri,
                                                const nsACString &aContentType,
                                                nsIUrlListener *aListener)
{
  return SaveAttachment(aFile, aURL, aMessageUri, aContentType, nullptr, aListener);
}

NS_IMETHODIMP
nsMessenger::DetachAttachmentsWOPrompts(nsIFile* aDestFolder,
                                        uint32_t aCount,
                                        const char **aContentTypeArray,
                                        const char **aUrlArray,
                                        const char **aDisplayNameArray,
                                        const char **aMessageUriArray,
                                        nsIUrlListener *aListener)
{
  NS_ENSURE_ARG_POINTER(aDestFolder);
  NS_ENSURE_ARG_POINTER(aContentTypeArray);
  NS_ENSURE_ARG_POINTER(aUrlArray);
  NS_ENSURE_ARG_POINTER(aMessageUriArray);
  NS_ENSURE_ARG_POINTER(aDisplayNameArray);
  if (!aCount)
    return NS_OK;
  nsSaveAllAttachmentsState *saveState;
  nsCOMPtr<nsIFile> attachmentDestination;
  nsresult rv = aDestFolder->Clone(getter_AddRefs(attachmentDestination));
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoCString path;
  rv = attachmentDestination->GetNativePath(path);
  NS_ENSURE_SUCCESS(rv, rv);

  nsAutoString unescapedFileName;
  ConvertAndSanitizeFileName(aDisplayNameArray[0], unescapedFileName);
  rv = attachmentDestination->Append(unescapedFileName);
  NS_ENSURE_SUCCESS(rv, rv);
  rv = attachmentDestination->CreateUnique(nsIFile::NORMAL_FILE_TYPE, ATTACHMENT_PERMISSION);
  NS_ENSURE_SUCCESS(rv, rv);

  saveState = new nsSaveAllAttachmentsState(aCount,
                                            aContentTypeArray,
                                            aUrlArray,
                                            aDisplayNameArray,
                                            aMessageUriArray,
                                            path.get(),
                                            true);

  // This method is used in filters, where we don't want to warn
  saveState->m_withoutWarning = true;
  rv = SaveAttachment(attachmentDestination,
                      nsDependentCString(aUrlArray[0]),
                      nsDependentCString(aMessageUriArray[0]),
                      nsDependentCString(aContentTypeArray[0]),
                      (void *)saveState,
                      aListener);
  return rv;
}

nsresult nsMessenger::SaveAttachment(nsIFile *aFile,
                                     const nsACString &aURL,
                                     const nsACString &aMessageUri,
                                     const nsACString &aContentType,
                                     void *closure,
                                     nsIUrlListener *aListener)
{
  nsCOMPtr<nsIMsgMessageService> messageService;
  nsSaveAllAttachmentsState *saveState= (nsSaveAllAttachmentsState*) closure;
  nsCOMPtr<nsIMsgMessageFetchPartService> fetchService;
  nsAutoCString urlString;
  nsCOMPtr<nsIURI> URL;
  nsAutoCString fullMessageUri(aMessageUri);

  // This instance will be held onto by the listeners, and will be released once 
  // the transfer has been completed.
  RefPtr<nsSaveMsgListener> saveListener(new nsSaveMsgListener(aFile, this, aListener));
  if (!saveListener)
    return NS_ERROR_OUT_OF_MEMORY;

  saveListener->m_contentType = aContentType;
  if (saveState)
  {
    saveListener->m_saveAllAttachmentsState = saveState;
    if (saveState->m_detachingAttachments)
    {
      nsCOMPtr<nsIURI> outputURI;
      nsresult rv = NS_NewFileURI(getter_AddRefs(outputURI), aFile);
      NS_ENSURE_SUCCESS(rv, rv);
      nsAutoCString fileUriSpec;
      rv = outputURI->GetSpec(fileUriSpec);
      NS_ENSURE_SUCCESS(rv, rv);
      saveState->m_savedFiles.AppendElement(fileUriSpec);
    }
  }

  urlString = aURL;
  // strip out ?type=application/x-message-display because it confuses libmime

  int32_t typeIndex = urlString.Find("?type=application/x-message-display");
  if (typeIndex != kNotFound)
  {
    urlString.Cut(typeIndex, sizeof("?type=application/x-message-display") - 1);
    // we also need to replace the next '&' with '?'
    int32_t firstPartIndex = urlString.FindChar('&');
    if (firstPartIndex != kNotFound)
      urlString.SetCharAt('?', firstPartIndex);
  }

  MsgReplaceSubstring(urlString, "/;section", "?section");
  nsresult rv = CreateStartupUrl(urlString.get(), getter_AddRefs(URL));

  if (NS_SUCCEEDED(rv))
  {
    rv = GetMessageServiceFromURI(aMessageUri, getter_AddRefs(messageService));
    if (NS_SUCCEEDED(rv))
    {
      fetchService = do_QueryInterface(messageService);
      // if the message service has a fetch part service then we know we can fetch mime parts...
      if (fetchService)
      {
        int32_t partPos = urlString.FindChar('?');
        if (partPos == kNotFound)
          return NS_ERROR_FAILURE;
        fullMessageUri.Append(Substring(urlString, partPos));
      }

      nsCOMPtr<nsIStreamListener> convertedListener;
      saveListener->QueryInterface(NS_GET_IID(nsIStreamListener),
                                 getter_AddRefs(convertedListener));

#ifndef XP_MACOSX
      // if the content type is bin hex we are going to do a hokey hack and make sure we decode the bin hex
      // when saving an attachment to disk..
      if (MsgLowerCaseEqualsLiteral(aContentType, APPLICATION_BINHEX))
      {
        nsCOMPtr<nsIStreamListener> listener (do_QueryInterface(convertedListener));
        nsCOMPtr<nsIStreamConverterService> streamConverterService = do_GetService("@mozilla.org/streamConverters;1", &rv);
        nsCOMPtr<nsISupports> channelSupport = do_QueryInterface(saveListener->m_channel);

        rv = streamConverterService->AsyncConvertData(APPLICATION_BINHEX,
                                                      "*/*",
                                                      listener,
                                                      channelSupport,
                                                      getter_AddRefs(convertedListener));
      }
#endif
      nsCOMPtr<nsIURI> dummyNull;
      if (fetchService)
        rv = fetchService->FetchMimePart(URL, fullMessageUri.get(),
                                         convertedListener, mMsgWindow,
                                         saveListener, getter_AddRefs(dummyNull));
      else
        rv = messageService->DisplayMessage(fullMessageUri.get(),
                                            convertedListener, mMsgWindow,
                                            nullptr, nullptr,
                                            getter_AddRefs(dummyNull));
    } // if we got a message service
  } // if we created a url

  if (NS_FAILED(rv))
    Alert("saveAttachmentFailed");

  return rv;
}

NS_IMETHODIMP
nsMessenger::OpenAttachment(const nsACString& aContentType, const nsACString& aURL,
                            const nsACString& aDisplayName, const nsACString& aMessageUri, bool aIsExternalAttachment)
{
  nsresult rv = NS_OK;

  // open external attachments inside our message pane which in turn should trigger the
  // helper app dialog...
  if (aIsExternalAttachment)
    rv = OpenURL(aURL);
  else
  {
    nsCOMPtr <nsIMsgMessageService> messageService;
    rv = GetMessageServiceFromURI(aMessageUri, getter_AddRefs(messageService));
    if (messageService)
      rv = messageService->OpenAttachment(PromiseFlatCString(aContentType).get(), PromiseFlatCString(aDisplayName).get(),
                                          PromiseFlatCString(aURL).get(), PromiseFlatCString(aMessageUri).get(),
                                          mDocShell, mMsgWindow, nullptr);
  }

  return rv;
}

NS_IMETHODIMP
nsMessenger::SaveAttachmentToFolder(const nsACString& contentType, const nsACString& url, const nsACString& displayName,
                                    const nsACString& messageUri, nsIFile * aDestFolder, nsIFile ** aOutFile)
{
  NS_ENSURE_ARG_POINTER(aDestFolder);
  nsresult rv;

  nsCOMPtr<nsIFile> attachmentDestination;
  rv = aDestFolder->Clone(getter_AddRefs(attachmentDestination));
  NS_ENSURE_SUCCESS(rv, rv);

  nsString unescapedFileName;
  ConvertAndSanitizeFileName(PromiseFlatCString(displayName).get(), unescapedFileName);
  rv = attachmentDestination->Append(unescapedFileName);
  NS_ENSURE_SUCCESS(rv, rv);
#ifdef XP_MACOSX
  rv = attachmentDestination->CreateUnique(nsIFile::NORMAL_FILE_TYPE, ATTACHMENT_PERMISSION);
  NS_ENSURE_SUCCESS(rv, rv);
#endif

  rv = SaveAttachment(attachmentDestination, url, messageUri, contentType, nullptr, nullptr);
  attachmentDestination.swap(*aOutFile);
  return rv;
}

NS_IMETHODIMP
nsMessenger::SaveAttachment(const nsACString& aContentType, const nsACString& aURL,
                            const nsACString& aDisplayName, const nsACString& aMessageUri, bool aIsExternalAttachment)
{
  // open external attachments inside our message pane which in turn should trigger the
  // helper app dialog...
  if (aIsExternalAttachment)
    return OpenURL(aURL);
  return SaveOneAttachment(PromiseFlatCString(aContentType).get(),
                           PromiseFlatCString(aURL).get(),
                           PromiseFlatCString(aDisplayName).get(),
                           PromiseFlatCString(aMessageUri).get(),
                           false);
}

nsresult
nsMessenger::SaveOneAttachment(const char * aContentType, const char * aURL,
                               const char * aDisplayName, const char * aMessageUri,
                               bool detaching)
{
  nsresult rv = NS_ERROR_OUT_OF_MEMORY;
  nsCOMPtr<nsIFilePicker> filePicker =
      do_CreateInstance("@mozilla.org/filepicker;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  int16_t dialogResult;
  nsCOMPtr<nsIFile> localFile;
  nsCOMPtr<nsIFile> lastSaveDir;
  nsCString filePath;
  nsString saveAttachmentStr;
  nsString defaultDisplayString;
  ConvertAndSanitizeFileName(aDisplayName, defaultDisplayString);

  GetString(NS_LITERAL_STRING("SaveAttachment"), saveAttachmentStr);
  filePicker->Init(mWindow, saveAttachmentStr,
                   nsIFilePicker::modeSave);
  filePicker->SetDefaultString(defaultDisplayString);

  // Check if the attachment file name has an extension (which must not
  // contain spaces) and set it as the default extension for the attachment.
  int32_t extensionIndex = defaultDisplayString.RFindChar('.');
  if (extensionIndex > 0 &&
      defaultDisplayString.FindChar(' ', extensionIndex) == kNotFound)
  {
    nsString extension;
    extension = Substring(defaultDisplayString, extensionIndex + 1);
    filePicker->SetDefaultExtension(extension);
    if (!mStringBundle)
    {
      rv = InitStringBundle();
      NS_ENSURE_SUCCESS(rv, rv);
    }

    nsString filterName;
    const char16_t *extensionParam[] = { extension.get() };
    rv = mStringBundle->FormatStringFromName(
      u"saveAsType", extensionParam, 1, getter_Copies(filterName));
    NS_ENSURE_SUCCESS(rv, rv);

    extension.Insert(NS_LITERAL_STRING("*."), 0);
    filePicker->AppendFilter(filterName, extension);
  }

  filePicker->AppendFilters(nsIFilePicker::filterAll);

  rv = GetLastSaveDirectory(getter_AddRefs(lastSaveDir));
  if (NS_SUCCEEDED(rv) && lastSaveDir)
    filePicker->SetDisplayDirectory(lastSaveDir);

  rv = filePicker->Show(&dialogResult);
  if (NS_FAILED(rv) || dialogResult == nsIFilePicker::returnCancel)
    return rv;

  rv = filePicker->GetFile(getter_AddRefs(localFile));
  NS_ENSURE_SUCCESS(rv, rv);

  SetLastSaveDirectory(localFile);

  nsCString dirName;
  rv = localFile->GetNativePath(dirName);
  NS_ENSURE_SUCCESS(rv, rv);

  nsSaveAllAttachmentsState *saveState = 
    new nsSaveAllAttachmentsState(1,
                                  &aContentType,
                                  &aURL,
                                  &aDisplayName,
                                  &aMessageUri,
                                  dirName.get(),
                                  detaching);

  return SaveAttachment(localFile, nsDependentCString(aURL), nsDependentCString(aMessageUri),
                        nsDependentCString(aContentType), (void *)saveState, nullptr);
}


NS_IMETHODIMP
nsMessenger::SaveAllAttachments(uint32_t count,
                                const char **contentTypeArray,
                                const char **urlArray,
                                const char **displayNameArray,
                                const char **messageUriArray)
{
  if (!count)
    return NS_ERROR_INVALID_ARG;
  return SaveAllAttachments(count, contentTypeArray, urlArray, displayNameArray, messageUriArray, false);
}

nsresult
nsMessenger::SaveAllAttachments(uint32_t count,
                                const char **contentTypeArray,
                                const char **urlArray,
                                const char **displayNameArray,
                                const char **messageUriArray,
                                bool detaching)
{
  nsresult rv = NS_ERROR_OUT_OF_MEMORY;
  nsCOMPtr<nsIFilePicker> filePicker =
    do_CreateInstance("@mozilla.org/filepicker;1", &rv);
  nsCOMPtr<nsIFile> localFile;
  nsCOMPtr<nsIFile> lastSaveDir;
  int16_t dialogResult;
  nsString saveAttachmentStr;

  NS_ENSURE_SUCCESS(rv, rv);
  GetString(NS_LITERAL_STRING("SaveAllAttachments"), saveAttachmentStr);
  filePicker->Init(mWindow,
                   saveAttachmentStr,
                   nsIFilePicker::modeGetFolder);

  rv = GetLastSaveDirectory(getter_AddRefs(lastSaveDir));
  if (NS_SUCCEEDED(rv) && lastSaveDir)
    filePicker->SetDisplayDirectory(lastSaveDir);

  rv = filePicker->Show(&dialogResult);
  if (NS_FAILED(rv) || dialogResult == nsIFilePicker::returnCancel)
    return rv;

  rv = filePicker->GetFile(getter_AddRefs(localFile));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = SetLastSaveDirectory(localFile);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCString dirName;
  nsSaveAllAttachmentsState *saveState = nullptr;
  rv = localFile->GetNativePath(dirName);
  NS_ENSURE_SUCCESS(rv, rv);

  saveState = new nsSaveAllAttachmentsState(count,
                                            contentTypeArray,
                                            urlArray,
                                            displayNameArray,
                                            messageUriArray,
                                            dirName.get(),
                                            detaching);
  nsString unescapedName;
  ConvertAndSanitizeFileName(displayNameArray[0], unescapedName);
  rv = localFile->Append(unescapedName);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = PromptIfFileExists(localFile);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = SaveAttachment(localFile, nsDependentCString(urlArray[0]), nsDependentCString(messageUriArray[0]),
                      nsDependentCString(contentTypeArray[0]), (void *)saveState, nullptr);
  return rv;
}

enum MESSENGER_SAVEAS_FILE_TYPE
{
 EML_FILE_TYPE =  0,
 HTML_FILE_TYPE = 1,
 TEXT_FILE_TYPE = 2,
 ANY_FILE_TYPE = 3
};
#define HTML_FILE_EXTENSION ".htm"
#define HTML_FILE_EXTENSION2 ".html"
#define TEXT_FILE_EXTENSION ".txt"

/**
 * Adjust the file name, removing characters from the middle of the name if
 * the name would otherwise be too long - too long for what file systems
 * usually support.
 */
nsresult nsMessenger::AdjustFileIfNameTooLong(nsIFile* aFile)
{
  NS_ENSURE_ARG_POINTER(aFile);
  nsAutoString path;
  nsresult rv = aFile->GetPath(path);
  NS_ENSURE_SUCCESS(rv, rv);
  // Most common file systems have a max filename length of 255. On windows, the
  // total path length is (at least for all practical purposees) limited to 255.
  // Let's just don't allow paths longer than that elsewhere either for
  // simplicity.
  uint32_t MAX = 255;
  if (path.Length() > MAX) {
    nsAutoString leafName;
    rv = aFile->GetLeafName(leafName);
    NS_ENSURE_SUCCESS(rv, rv);

    uint32_t pathLengthUpToLeaf = path.Length() - leafName.Length();
    if (pathLengthUpToLeaf >= MAX - 8) { // want at least 8 chars for name
      return NS_ERROR_FILE_NAME_TOO_LONG;
    }
    uint32_t x = MAX - pathLengthUpToLeaf; // x = max leaf size
    nsAutoString truncatedLeaf;
    truncatedLeaf.Append(Substring(leafName, 0, x/2));
    truncatedLeaf.AppendLiteral("...");
    truncatedLeaf.Append(Substring(leafName, leafName.Length() - x/2 + 3,
                                   leafName.Length()));
    rv = aFile->SetLeafName(truncatedLeaf);
  }
  return rv;
}

NS_IMETHODIMP
nsMessenger::SaveAs(const nsACString& aURI, bool aAsFile,
                    nsIMsgIdentity *aIdentity, const nsAString& aMsgFilename,
                    bool aBypassFilePicker)
{
  nsCOMPtr<nsIMsgMessageService> messageService;
  nsCOMPtr<nsIUrlListener> urlListener;
  nsSaveMsgListener *saveListener = nullptr;
  nsCOMPtr<nsIURI> url;
  nsCOMPtr<nsIStreamListener> convertedListener;
  int32_t saveAsFileType = EML_FILE_TYPE;

  nsresult rv = GetMessageServiceFromURI(aURI, getter_AddRefs(messageService));
  if (NS_FAILED(rv))
    goto done;

  if (aAsFile)
  {
    nsCOMPtr<nsIFile> saveAsFile;
    // show the file picker if BypassFilePicker is not specified (null) or false
    if (!aBypassFilePicker) {
      rv = GetSaveAsFile(aMsgFilename, &saveAsFileType, getter_AddRefs(saveAsFile));
      // A null saveAsFile means that the user canceled the save as
      if (NS_FAILED(rv) || !saveAsFile)
        goto done;
    }
    else {
      saveAsFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
      rv = saveAsFile->InitWithPath(aMsgFilename);
      if (NS_FAILED(rv))
        goto done;      
      if (StringEndsWith(aMsgFilename, NS_LITERAL_STRING(TEXT_FILE_EXTENSION),
                         nsCaseInsensitiveStringComparator()))
        saveAsFileType = TEXT_FILE_TYPE;
      else if ((StringEndsWith(aMsgFilename,
                               NS_LITERAL_STRING(HTML_FILE_EXTENSION),
                               nsCaseInsensitiveStringComparator())) ||
               (StringEndsWith(aMsgFilename,
                               NS_LITERAL_STRING(HTML_FILE_EXTENSION2),
                               nsCaseInsensitiveStringComparator())))
        saveAsFileType = HTML_FILE_TYPE;
      else
        saveAsFileType = EML_FILE_TYPE;
    }

    rv = AdjustFileIfNameTooLong(saveAsFile);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = PromptIfFileExists(saveAsFile);
    if (NS_FAILED(rv)) {
      goto done;
    }

    // After saveListener goes out of scope, the listener will be owned by
    // whoever the listener is registered with, usually a URL.
    RefPtr<nsSaveMsgListener> saveListener = new nsSaveMsgListener(saveAsFile, this, nullptr);
    if (!saveListener) {
      rv = NS_ERROR_OUT_OF_MEMORY;
      goto done;
    }
    rv = saveListener->QueryInterface(NS_GET_IID(nsIUrlListener), getter_AddRefs(urlListener));
    if (NS_FAILED(rv))
      goto done;

    if (saveAsFileType == EML_FILE_TYPE)
    {
      nsCOMPtr<nsIURI> dummyNull;
      rv = messageService->SaveMessageToDisk(PromiseFlatCString(aURI).get(), saveAsFile, false,
        urlListener, getter_AddRefs(dummyNull),
        true, mMsgWindow);
    }
    else
    {
      nsAutoCString urlString(aURI);

      // we can't go RFC822 to TXT until bug #1775 is fixed
      // so until then, do the HTML to TXT conversion in
      // nsSaveMsgListener::OnStopRequest(), see ConvertBufToPlainText()
      //
      // Setup the URL for a "Save As..." Operation...
      // For now, if this is a save as TEXT operation, then do
      // a "printing" operation
      if (saveAsFileType == TEXT_FILE_TYPE)
      {
        saveListener->m_outputFormat = nsSaveMsgListener::ePlainText;
        saveListener->m_doCharsetConversion = true;
        urlString.AppendLiteral("?header=print");
      }
      else
      {
        saveListener->m_outputFormat = nsSaveMsgListener::eHTML;
        saveListener->m_doCharsetConversion = false;
        urlString.AppendLiteral("?header=saveas");
      }

      rv = CreateStartupUrl(urlString.get(), getter_AddRefs(url));
      NS_ASSERTION(NS_SUCCEEDED(rv), "CreateStartupUrl failed");
      if (NS_FAILED(rv))
        goto done;

      nsCOMPtr<nsIPrincipal> nullPrincipal =
        do_CreateInstance("@mozilla.org/nullprincipal;1", &rv);
      NS_ASSERTION(NS_SUCCEEDED(rv), "CreateInstance of nullprincipal failed");
      if (NS_FAILED(rv))
        goto done;

      saveListener->m_channel = nullptr;
      rv = NS_NewInputStreamChannel(getter_AddRefs(saveListener->m_channel),
                                    url,
                                    nullptr,
                                    nullPrincipal,
                                    nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
                                    nsIContentPolicy::TYPE_OTHER);
      NS_ASSERTION(NS_SUCCEEDED(rv), "NS_NewChannel failed");
      if (NS_FAILED(rv))
        goto done;

      nsCOMPtr<nsIStreamConverterService> streamConverterService = do_GetService("@mozilla.org/streamConverters;1");
      nsCOMPtr<nsISupports> channelSupport = do_QueryInterface(saveListener->m_channel);

      // we can't go RFC822 to TXT until bug #1775 is fixed
      // so until then, do the HTML to TXT conversion in
      // nsSaveMsgListener::OnStopRequest(), see ConvertBufToPlainText()
      rv = streamConverterService->AsyncConvertData(MESSAGE_RFC822,
        TEXT_HTML,
        saveListener,
        channelSupport,
        getter_AddRefs(convertedListener));
      NS_ASSERTION(NS_SUCCEEDED(rv), "AsyncConvertData failed");
      if (NS_FAILED(rv))
        goto done;

      nsCOMPtr<nsIURI> dummyNull;
      rv = messageService->DisplayMessage(urlString.get(), convertedListener, mMsgWindow,
        nullptr, nullptr, getter_AddRefs(dummyNull));
    }
  }
  else
  {
    // ** save as Template
    nsCOMPtr <nsIFile> tmpFile;
    nsresult rv = GetSpecialDirectoryWithFileName(NS_OS_TEMP_DIR,
                                                  "nsmail.tmp",
                                                  getter_AddRefs(tmpFile));

    NS_ENSURE_SUCCESS(rv, rv);

    // For temp file, we should use restrictive 00600 instead of ATTACHMENT_PERMISSION 
    rv = tmpFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 00600);
    if (NS_FAILED(rv)) goto done;

    // The saveListener is owned by whoever we ultimately register the
    // listener with, generally a URL.
    saveListener = new nsSaveMsgListener(tmpFile, this, nullptr);
    if (!saveListener) {
      rv = NS_ERROR_OUT_OF_MEMORY;
      goto done;
    }

    if (aIdentity)
      rv = aIdentity->GetStationeryFolder(saveListener->m_templateUri);
    if (NS_FAILED(rv))
      goto done;

    bool needDummyHeader = StringBeginsWith(saveListener->m_templateUri, NS_LITERAL_CSTRING("mailbox://"));
    bool canonicalLineEnding = StringBeginsWith(saveListener->m_templateUri, NS_LITERAL_CSTRING("imap://"));

    rv = saveListener->QueryInterface(
      NS_GET_IID(nsIUrlListener),
      getter_AddRefs(urlListener));
    if (NS_FAILED(rv))
      goto done;

    nsCOMPtr<nsIURI> dummyNull;
    rv = messageService->SaveMessageToDisk(PromiseFlatCString(aURI).get(), tmpFile,
      needDummyHeader,
      urlListener, getter_AddRefs(dummyNull),
      canonicalLineEnding, mMsgWindow);
  }

done:
  if (NS_FAILED(rv))
  {
    NS_IF_RELEASE(saveListener);
    Alert("saveMessageFailed");
  }
  return rv;
}

nsresult
nsMessenger::GetSaveAsFile(const nsAString& aMsgFilename, int32_t *aSaveAsFileType,
                           nsIFile **aSaveAsFile)
{
  nsresult rv;
  nsCOMPtr<nsIFilePicker> filePicker = do_CreateInstance("@mozilla.org/filepicker;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);
  nsString saveMailAsStr;
  GetString(NS_LITERAL_STRING("SaveMailAs"), saveMailAsStr);
  filePicker->Init(mWindow, saveMailAsStr, nsIFilePicker::modeSave);

  // if we have a non-null filename use it, otherwise use default save message one
  if (aMsgFilename.IsEmpty())
  {
    nsString saveMsgStr;
    GetString(NS_LITERAL_STRING("defaultSaveMessageAsFileName"), saveMsgStr);
    filePicker->SetDefaultString(saveMsgStr);
  }
  else
  {
    filePicker->SetDefaultString(aMsgFilename);
  }

  // because we will be using GetFilterIndex()
  // we must call AppendFilters() one at a time,
  // in MESSENGER_SAVEAS_FILE_TYPE order
  nsString emlFilesStr;
  GetString(NS_LITERAL_STRING("EMLFiles"), emlFilesStr);
  filePicker->AppendFilter(emlFilesStr,
                           NS_LITERAL_STRING("*.eml"));
  filePicker->AppendFilters(nsIFilePicker::filterHTML);
  filePicker->AppendFilters(nsIFilePicker::filterText);
  filePicker->AppendFilters(nsIFilePicker::filterAll);

  // Save as the "All Files" file type by default. We want to save as .eml by
  // default, but the filepickers on some platforms don't switch extensions
  // based on the file type selected (bug 508597).
  filePicker->SetFilterIndex(ANY_FILE_TYPE);
  // Yes, this is fine even if we ultimately save as HTML or text. On Windows,
  // this actually is a boolean telling the file picker to automatically add
  // the correct extension depending on the filter. On Mac or Linux this is a
  // no-op.
  filePicker->SetDefaultExtension(NS_LITERAL_STRING("eml"));

  int16_t dialogResult;

  nsCOMPtr <nsIFile> lastSaveDir;
  rv = GetLastSaveDirectory(getter_AddRefs(lastSaveDir));
  if (NS_SUCCEEDED(rv) && lastSaveDir)
    filePicker->SetDisplayDirectory(lastSaveDir);

  nsCOMPtr<nsIFile> localFile;
  rv = filePicker->Show(&dialogResult);
  NS_ENSURE_SUCCESS(rv, rv);
  if (dialogResult == nsIFilePicker::returnCancel)
  {
    // We'll indicate this by setting the outparam to null.
    *aSaveAsFile = nullptr;
    return NS_OK;
  }

  rv = filePicker->GetFile(getter_AddRefs(localFile));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = SetLastSaveDirectory(localFile);
  NS_ENSURE_SUCCESS(rv, rv);

  int32_t selectedSaveAsFileType;
  rv = filePicker->GetFilterIndex(&selectedSaveAsFileType);
  NS_ENSURE_SUCCESS(rv, rv);

  // If All Files was selected, look at the extension
  if (selectedSaveAsFileType == ANY_FILE_TYPE)
  {
    nsAutoString fileName;
    rv = localFile->GetLeafName(fileName);
    NS_ENSURE_SUCCESS(rv, rv);

    if (StringEndsWith(fileName, NS_LITERAL_STRING(HTML_FILE_EXTENSION),
                       nsCaseInsensitiveStringComparator()) ||
        StringEndsWith(fileName, NS_LITERAL_STRING(HTML_FILE_EXTENSION2),
                       nsCaseInsensitiveStringComparator()))
      *aSaveAsFileType = HTML_FILE_TYPE;
    else if (StringEndsWith(fileName, NS_LITERAL_STRING(TEXT_FILE_EXTENSION),
                            nsCaseInsensitiveStringComparator()))
      *aSaveAsFileType = TEXT_FILE_TYPE;
    else
      // The default is .eml
      *aSaveAsFileType = EML_FILE_TYPE;
  }
  else
  {
    *aSaveAsFileType = selectedSaveAsFileType;
  }

  if (dialogResult == nsIFilePicker::returnReplace)
  {
    // be extra safe and only delete when the file is really a file
    bool isFile;
    rv = localFile->IsFile(&isFile);
    if (NS_SUCCEEDED(rv) && isFile)
    {
      rv = localFile->Remove(false /* recursive delete */);
      NS_ENSURE_SUCCESS(rv, rv);
    }
    else
    {
      // We failed, or this isn't a file. We can't do anything about it.
      return NS_ERROR_FAILURE;
    }
  }

  *aSaveAsFile = nullptr;
  localFile.swap(*aSaveAsFile);
  return NS_OK;
}

/**
 * Show a Save All dialog allowing the user to pick which folder to save
 * messages to.
 * @param [out] aSaveDir directory to save to. Will be null on cancel.
 */
nsresult
nsMessenger::GetSaveToDir(nsIFile **aSaveDir)
{
  nsresult rv;
  nsCOMPtr<nsIFilePicker> filePicker =
    do_CreateInstance("@mozilla.org/filepicker;1", &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  nsString chooseFolderStr;
  GetString(NS_LITERAL_STRING("ChooseFolder"), chooseFolderStr);
  filePicker->Init(mWindow, chooseFolderStr, nsIFilePicker::modeGetFolder);

  nsCOMPtr<nsIFile> lastSaveDir;
  rv = GetLastSaveDirectory(getter_AddRefs(lastSaveDir));
  if (NS_SUCCEEDED(rv) && lastSaveDir)
    filePicker->SetDisplayDirectory(lastSaveDir);

  int16_t dialogResult;
  rv = filePicker->Show(&dialogResult);
  if (NS_FAILED(rv) || dialogResult == nsIFilePicker::returnCancel)
  {
    // We'll indicate this by setting the outparam to null.
    *aSaveDir = nullptr;
    return NS_OK;
  }

  nsCOMPtr<nsIFile> dir;
  rv = filePicker->GetFile(getter_AddRefs(dir));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = SetLastSaveDirectory(dir);
  NS_ENSURE_SUCCESS(rv, rv);

  *aSaveDir = nullptr;
  dir.swap(*aSaveDir);
  return NS_OK;
}

NS_IMETHODIMP
nsMessenger::SaveMessages(uint32_t aCount,
                          const char16_t **aFilenameArray,
                          const char **aMessageUriArray)
{
  NS_ENSURE_ARG_MIN(aCount, 1);
  NS_ENSURE_ARG_POINTER(aFilenameArray);
  NS_ENSURE_ARG_POINTER(aMessageUriArray);

  nsresult rv;

  nsCOMPtr<nsIFile> saveDir;
  rv = GetSaveToDir(getter_AddRefs(saveDir));
  NS_ENSURE_SUCCESS(rv, rv);
  if (!saveDir) // A null saveDir means that the user canceled the save.
    return NS_OK;

  for (uint32_t i = 0; i < aCount; i++) {
    if (!aFilenameArray[i]) // just to be sure
      return NS_ERROR_FAILURE;

    nsCOMPtr<nsIFile> saveToFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    rv = saveToFile->InitWithFile(saveDir);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = saveToFile->Append(nsDependentString(aFilenameArray[i]));
    NS_ENSURE_SUCCESS(rv, rv);

    rv = AdjustFileIfNameTooLong(saveToFile);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = PromptIfFileExists(saveToFile);
    if (NS_FAILED(rv))
      continue;

    nsCOMPtr<nsIMsgMessageService> messageService;
    nsCOMPtr<nsIUrlListener> urlListener;

    rv = GetMessageServiceFromURI(nsDependentCString(aMessageUriArray[i]),
                                  getter_AddRefs(messageService));
    if (NS_FAILED(rv)) {
      Alert("saveMessageFailed");
      return rv;
    }

    nsSaveMsgListener *saveListener = new nsSaveMsgListener(saveToFile, this, nullptr);
    if (!saveListener) {
      NS_IF_RELEASE(saveListener);
      Alert("saveMessageFailed");
      return NS_ERROR_OUT_OF_MEMORY;
    }
    NS_ADDREF(saveListener);

    rv = saveListener->QueryInterface(NS_GET_IID(nsIUrlListener),
                                      getter_AddRefs(urlListener));
    if (NS_FAILED(rv)) {
      NS_IF_RELEASE(saveListener);
      Alert("saveMessageFailed");
      return rv;
    }

    // Ok, now save the message.
    nsCOMPtr<nsIURI> dummyNull;
    rv = messageService->SaveMessageToDisk(aMessageUriArray[i],
                                           saveToFile, false,
                                           urlListener, getter_AddRefs(dummyNull),
                                           true, mMsgWindow);
    if (NS_FAILED(rv)) {
      NS_IF_RELEASE(saveListener);
      Alert("saveMessageFailed");
      return rv;
    }
  }
  return rv;
}

nsresult
nsMessenger::Alert(const char *stringName)
{
  nsresult rv = NS_OK;

  if (mDocShell)
  {
    nsCOMPtr<nsIPrompt> dialog(do_GetInterface(mDocShell));

    if (dialog)
    {
      nsString alertStr;
      GetString(NS_ConvertASCIItoUTF16(stringName), alertStr);
      rv = dialog->Alert(nullptr, alertStr.get());
    }
  }
  return rv;
}

NS_IMETHODIMP
nsMessenger::MessageServiceFromURI(const nsACString& aUri, nsIMsgMessageService **aMsgService)
{
  NS_ENSURE_ARG_POINTER(aMsgService);
  return GetMessageServiceFromURI(aUri, aMsgService);
}

NS_IMETHODIMP
nsMessenger::MsgHdrFromURI(const nsACString& aUri, nsIMsgDBHdr **aMsgHdr)
{
  NS_ENSURE_ARG_POINTER(aMsgHdr);
  nsCOMPtr <nsIMsgMessageService> msgService;
  nsresult rv;


  if (mMsgWindow &&
      (StringBeginsWith(aUri, NS_LITERAL_CSTRING("file:")) ||
       PromiseFlatCString(aUri).Find("type=application/x-message-display") >= 0))
  {
    nsCOMPtr <nsIMsgHeaderSink> headerSink;
    mMsgWindow->GetMsgHeaderSink(getter_AddRefs(headerSink));
    if (headerSink)
    {
      rv = headerSink->GetDummyMsgHeader(aMsgHdr);
      // Is there a way to check if they're asking for the hdr currently
      // displayed in a stand-alone msg window from a .eml file?
      // (pretty likely if this is a file: uri)
      return rv;
    }
  }

  rv = GetMessageServiceFromURI(aUri, getter_AddRefs(msgService));
  NS_ENSURE_SUCCESS(rv, rv);
  return msgService->MessageURIToMsgHdr(PromiseFlatCString(aUri).get(), aMsgHdr);
}

NS_IMETHODIMP nsMessenger::GetUndoTransactionType(uint32_t *txnType)
{
  NS_ENSURE_TRUE(txnType && mTxnMgr, NS_ERROR_NULL_POINTER);

  nsresult rv;
  *txnType = nsMessenger::eUnknown;
  nsCOMPtr<nsITransaction> txn;
  rv = mTxnMgr->PeekUndoStack(getter_AddRefs(txn));
  if (NS_SUCCEEDED(rv) && txn)
  {
    nsCOMPtr <nsIPropertyBag2> propertyBag = do_QueryInterface(txn, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    return propertyBag->GetPropertyAsUint32(NS_LITERAL_STRING("type"), txnType);
  }
  return rv;
}

NS_IMETHODIMP nsMessenger::CanUndo(bool *bValue)
{
  NS_ENSURE_TRUE(bValue && mTxnMgr, NS_ERROR_NULL_POINTER);

  nsresult rv;
  *bValue = false;
  int32_t count = 0;
  rv = mTxnMgr->GetNumberOfUndoItems(&count);
  if (NS_SUCCEEDED(rv) && count > 0)
    *bValue = true;
  return rv;
}

NS_IMETHODIMP nsMessenger::GetRedoTransactionType(uint32_t *txnType)
{
  NS_ENSURE_TRUE(txnType && mTxnMgr, NS_ERROR_NULL_POINTER);

  nsresult rv;
  *txnType = nsMessenger::eUnknown;
  nsCOMPtr<nsITransaction> txn;
  rv = mTxnMgr->PeekRedoStack(getter_AddRefs(txn));
  if (NS_SUCCEEDED(rv) && txn)
  {
    nsCOMPtr <nsIPropertyBag2> propertyBag = do_QueryInterface(txn, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    return propertyBag->GetPropertyAsUint32(NS_LITERAL_STRING("type"), txnType);
  }
  return rv;
}

NS_IMETHODIMP nsMessenger::CanRedo(bool *bValue)
{
  NS_ENSURE_TRUE(bValue && mTxnMgr, NS_ERROR_NULL_POINTER);

  nsresult rv;
  *bValue = false;
  int32_t count = 0;
  rv = mTxnMgr->GetNumberOfRedoItems(&count);
  if (NS_SUCCEEDED(rv) && count > 0)
    *bValue = true;
  return rv;
}

NS_IMETHODIMP
nsMessenger::Undo(nsIMsgWindow *msgWindow)
{
  nsresult rv = NS_OK;
  if (mTxnMgr)
  {
    int32_t numTxn = 0;
    rv = mTxnMgr->GetNumberOfUndoItems(&numTxn);
    if (NS_SUCCEEDED(rv) && numTxn > 0)
    {
        nsCOMPtr<nsITransaction> txn;
        rv = mTxnMgr->PeekUndoStack(getter_AddRefs(txn));
        if (NS_SUCCEEDED(rv) && txn)
        {
            static_cast<nsMsgTxn*>(static_cast<nsITransaction*>(txn.get()))->SetMsgWindow(msgWindow);
        }
        mTxnMgr->UndoTransaction();
    }
  }
  return rv;
}

NS_IMETHODIMP
nsMessenger::Redo(nsIMsgWindow *msgWindow)
{
  nsresult rv = NS_OK;
  if (mTxnMgr)
  {
    int32_t numTxn = 0;
    rv = mTxnMgr->GetNumberOfRedoItems(&numTxn);
    if (NS_SUCCEEDED(rv) && numTxn > 0)
    {
        nsCOMPtr<nsITransaction> txn;
        rv = mTxnMgr->PeekRedoStack(getter_AddRefs(txn));
        if (NS_SUCCEEDED(rv) && txn)
        {
            static_cast<nsMsgTxn*>(static_cast<nsITransaction*>(txn.get()))->SetMsgWindow(msgWindow);
        }
        mTxnMgr->RedoTransaction();
    }
  }
  return rv;
}

NS_IMETHODIMP
nsMessenger::GetTransactionManager(nsITransactionManager* *aTxnMgr)
{
  NS_ENSURE_TRUE(mTxnMgr && aTxnMgr, NS_ERROR_NULL_POINTER);

  *aTxnMgr = mTxnMgr;
  NS_ADDREF(*aTxnMgr);

  return NS_OK;
}

NS_IMETHODIMP nsMessenger::SetDocumentCharset(const nsACString& aCharacterSet)
{
  // We want to redisplay the currently selected message (if any) but forcing the
  // redisplay to use characterSet
  if (!mLastDisplayURI.IsEmpty())
  {
    SetDisplayCharset(NS_LITERAL_CSTRING("UTF-8"));

    nsCOMPtr <nsIMsgMessageService> messageService;
    nsresult rv = GetMessageServiceFromURI(mLastDisplayURI, getter_AddRefs(messageService));

    if (NS_SUCCEEDED(rv) && messageService)
    {
      nsCOMPtr<nsIURI> dummyNull;
      messageService->DisplayMessage(mLastDisplayURI.get(), mDocShell, mMsgWindow, nullptr,
                                     PromiseFlatCString(aCharacterSet).get(), getter_AddRefs(dummyNull));
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
nsMessenger::GetLastDisplayedMessageUri(nsACString& aLastDisplayedMessageUri)
{
  aLastDisplayedMessageUri = mLastDisplayURI;
  return NS_OK;
}

nsSaveMsgListener::nsSaveMsgListener(nsIFile* aFile, nsMessenger *aMessenger, nsIUrlListener *aListener)
{
  m_file = do_QueryInterface(aFile);
  m_messenger = aMessenger;
  mListener = aListener;
  mUrlHasStopped = false;
  mRequestHasStopped = false;
  
    // rhp: for charset handling
  m_doCharsetConversion = false;
  m_saveAllAttachmentsState = nullptr;
  mProgress = 0;
  mMaxProgress = -1;
  mCanceled = false;
  m_outputFormat = eUnknown;
  mInitialized = false;
}

nsSaveMsgListener::~nsSaveMsgListener()
{
}

//
// nsISupports
//
NS_IMPL_ISUPPORTS(nsSaveMsgListener,
                   nsIUrlListener,
                   nsIMsgCopyServiceListener,
                   nsIStreamListener,
                   nsIRequestObserver,
                   nsICancelable)

NS_IMETHODIMP
nsSaveMsgListener::Cancel(nsresult status)
{
  mCanceled = true;
  return NS_OK;
}

//
// nsIUrlListener
//
NS_IMETHODIMP
nsSaveMsgListener::OnStartRunningUrl(nsIURI* url)
{
  if (mListener)
    mListener->OnStartRunningUrl(url);
  return NS_OK;
}

NS_IMETHODIMP
nsSaveMsgListener::OnStopRunningUrl(nsIURI *url, nsresult exitCode)
{
  nsresult rv = exitCode;
  mUrlHasStopped = true;

  // ** save as template goes here
  if (!m_templateUri.IsEmpty()) 
  {
    nsCOMPtr<nsIRDFService> rdf(do_GetService(kRDFServiceCID, &rv));
    if (NS_FAILED(rv)) goto done;
    nsCOMPtr<nsIRDFResource> res;
    rv = rdf->GetResource(m_templateUri, getter_AddRefs(res));
    if (NS_FAILED(rv)) goto done;
    nsCOMPtr<nsIMsgFolder> templateFolder;
    templateFolder = do_QueryInterface(res, &rv);
    if (NS_FAILED(rv)) goto done;
    nsCOMPtr<nsIMsgCopyService> copyService = do_GetService(NS_MSGCOPYSERVICE_CONTRACTID);
    if (copyService)
    {
      nsCOMPtr<nsIFile> clone;
      m_file->Clone(getter_AddRefs(clone));
      rv = copyService->CopyFileMessage(clone, templateFolder, nullptr,
                                        true, nsMsgMessageFlags::Read,
                                        EmptyCString(), this, nullptr);
      // Clear this so we don't end up in a loop if OnStopRunningUrl gets
      // called again.
      m_templateUri.Truncate();
    }
  }
  else if (m_outputStream && mRequestHasStopped)
  {
    m_outputStream->Close();
    m_outputStream = nullptr;
  }

done:
  if (NS_FAILED(rv))
  {
    if (m_file)
      m_file->Remove(false);
    if (m_messenger)
        m_messenger->Alert("saveMessageFailed");
  }
  
  if (mRequestHasStopped && mListener)
    mListener->OnStopRunningUrl(url, exitCode);
  else
    mListenerUri = url;
  
  return rv;
}

NS_IMETHODIMP
nsSaveMsgListener::OnStartCopy(void)
{
  return NS_OK;
}

NS_IMETHODIMP
nsSaveMsgListener::OnProgress(uint32_t aProgress, uint32_t aProgressMax)
{
  return NS_OK;
}

NS_IMETHODIMP
nsSaveMsgListener::SetMessageKey(nsMsgKey aKey)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP
nsSaveMsgListener::GetMessageId(nsACString& aMessageId)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP
nsSaveMsgListener::OnStopCopy(nsresult aStatus)
{
  if (m_file)
    m_file->Remove(false);
  return aStatus;
}

// initializes the progress window if we are going to show one
// and for OSX, sets creator flags on the output file
nsresult nsSaveMsgListener::InitializeDownload(nsIRequest * aRequest)
{
  nsresult rv = NS_OK;
  
  mInitialized = true;
  nsCOMPtr<nsIChannel> channel (do_QueryInterface(aRequest));
  
  if (!channel)
    return rv;
  
  // Get the max progress from the URL if we haven't already got it.
  if (mMaxProgress == -1)
  {
    nsCOMPtr<nsIURI> uri;
    channel->GetURI(getter_AddRefs(uri));
    nsCOMPtr<nsIMsgMailNewsUrl> mailnewsUrl(do_QueryInterface(uri));
    if (mailnewsUrl)
      mailnewsUrl->GetMaxProgress(&mMaxProgress);
  }
  
  if (!m_contentType.IsEmpty())
  {
    nsCOMPtr<nsIMIMEService> mimeService (do_GetService(NS_MIMESERVICE_CONTRACTID));
    nsCOMPtr<nsIMIMEInfo> mimeinfo;
    
    mimeService->GetFromTypeAndExtension(m_contentType, EmptyCString(), getter_AddRefs(mimeinfo));
    
    // create a download progress window

    // Set saveToDisk explicitly to avoid launching the saved file.
    // See http://hg.mozilla.org/mozilla-central/file/814a6f071472/toolkit/components/jsdownloads/src/DownloadLegacy.js#l164
    mimeinfo->SetPreferredAction(nsIHandlerInfo::saveToDisk);

    // When we don't allow warnings, also don't show progress, as this
    //  is an environment (typically filters) where we don't want
    //  interruption.
    bool allowProgress = true;
    if (m_saveAllAttachmentsState)
      allowProgress = !m_saveAllAttachmentsState->m_withoutWarning;
    if (allowProgress)
    {
      nsCOMPtr<nsITransfer> tr = do_CreateInstance(NS_TRANSFER_CONTRACTID, &rv);
      if (tr && m_file)
      {
        PRTime timeDownloadStarted = PR_Now();
        
        nsCOMPtr<nsIURI> outputURI;
        NS_NewFileURI(getter_AddRefs(outputURI), m_file);
        
        nsCOMPtr<nsIURI> url;
        channel->GetURI(getter_AddRefs(url));
        rv = tr->Init(url, outputURI, EmptyString(), mimeinfo,
                      timeDownloadStarted, nullptr, this, false);
        
          // now store the web progresslistener
        mTransfer = tr;
      }
    }
  }
  return rv;
}

NS_IMETHODIMP
nsSaveMsgListener::OnStartRequest(nsIRequest* request, nsISupports* aSupport)
{
  if (m_file)
    MsgNewBufferedFileOutputStream(getter_AddRefs(m_outputStream), m_file, -1, ATTACHMENT_PERMISSION);
  if (!m_outputStream)
  {
    mCanceled = true;
    if (m_messenger)
      m_messenger->Alert("saveAttachmentFailed");
  }
  return NS_OK;
}

NS_IMETHODIMP
nsSaveMsgListener::OnStopRequest(nsIRequest* request, nsISupports* aSupport,
                                 nsresult status)
{
  nsresult rv = NS_OK;
  mRequestHasStopped = true;
  
  // rhp: If we are doing the charset conversion magic, this is different
  // processing, otherwise, its just business as usual.
  // If we need text/plain, then we need to convert the HTML and then convert
  // to the systems charset.
  if (m_doCharsetConversion && m_outputStream)
  {
    // For HTML, code is emitted immediately in OnDataAvailable.
    MOZ_ASSERT(m_outputFormat == ePlainText,
      "For HTML, m_doCharsetConversion shouldn't be set");
    NS_ConvertUTF8toUTF16 utf16Buffer(m_msgBuffer);
    ConvertBufToPlainText(utf16Buffer, false, false, false, false);

    nsCString outCString;
    rv = nsMsgI18NConvertFromUnicode(nsMsgI18NFileSystemCharset(),
      utf16Buffer, outCString, false, true);
    if (rv == NS_ERROR_UENC_NOMAPPING) {
      // If we can't encode with the preferred charset, use UTF-8.
      CopyUTF16toUTF8(utf16Buffer, outCString);
      rv = NS_OK;
    }
    if (NS_SUCCEEDED(rv))
    {
      uint32_t writeCount;
      rv = m_outputStream->Write(outCString.get(), outCString.Length(), &writeCount);
      if (outCString.Length() != writeCount)
        rv = NS_ERROR_FAILURE;
    }
  }
 
  if (m_outputStream)
  {
    m_outputStream->Close();
    m_outputStream = nullptr;
  }
  
  if (m_saveAllAttachmentsState)
  {
    m_saveAllAttachmentsState->m_curIndex++;
    if (!mCanceled && m_saveAllAttachmentsState->m_curIndex < m_saveAllAttachmentsState->m_count)
    {
      nsSaveAllAttachmentsState *state = m_saveAllAttachmentsState;
      uint32_t i = state->m_curIndex;
      nsString unescapedName;
      nsCOMPtr<nsIFile> localFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv);
      if (NS_FAILED(rv)) goto done;
      rv = localFile->InitWithNativePath(nsDependentCString(state->m_directoryName));
      
      if (NS_FAILED(rv)) goto done;
      
      ConvertAndSanitizeFileName(state->m_displayNameArray[i], unescapedName);
      rv = localFile->Append(unescapedName);
      if (NS_FAILED(rv))
        goto done;

      // When we are running with no warnings (typically filters and other automatic
      //  uses), then don't prompt for duplicates, but create a unique file
      //  instead.
      if (!m_saveAllAttachmentsState->m_withoutWarning)
      {
        rv = m_messenger->PromptIfFileExists(localFile);
        if (NS_FAILED(rv)) goto done;
      }
      else
      {
        rv = localFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, ATTACHMENT_PERMISSION);
        if (NS_FAILED(rv)) goto done;
      }
      rv = m_messenger->SaveAttachment(localFile,
                                       nsDependentCString(state->m_urlArray[i]),
                                       nsDependentCString(state->m_messageUriArray[i]),
                                       nsDependentCString(state->m_contentTypeArray[i]),
                                       (void *)state, nullptr);
      done:
        if (NS_FAILED(rv))
        {
          delete state;
          m_saveAllAttachmentsState = nullptr;
        }
    }
    else
    {
          // check if we're saving attachments prior to detaching them.
      if (m_saveAllAttachmentsState->m_detachingAttachments && !mCanceled)
      {
        nsSaveAllAttachmentsState *state = m_saveAllAttachmentsState;
        m_messenger->DetachAttachments(state->m_count,
                                       (const char **) state->m_contentTypeArray,
                                       (const char **) state->m_urlArray,
                                       (const char **) state->m_displayNameArray,
                                       (const char **) state->m_messageUriArray,
                                       &state->m_savedFiles,
                                       state->m_withoutWarning);
      }

      delete m_saveAllAttachmentsState;
      m_saveAllAttachmentsState = nullptr;
    }
  }

  if(mTransfer)
  {
    mTransfer->OnProgressChange64(nullptr, nullptr, mMaxProgress, mMaxProgress, mMaxProgress, mMaxProgress);
    mTransfer->OnStateChange(nullptr, nullptr, nsIWebProgressListener::STATE_STOP |
      nsIWebProgressListener::STATE_IS_NETWORK, NS_OK);
    mTransfer = nullptr; // break any circular dependencies between the progress dialog and use
  }

  if (mUrlHasStopped && mListener)
    mListener->OnStopRunningUrl(mListenerUri, rv);

  return NS_OK;
}

NS_IMETHODIMP
nsSaveMsgListener::OnDataAvailable(nsIRequest* request,
                                  nsISupports* aSupport,
                                  nsIInputStream* inStream,
                                  uint64_t srcOffset,
                                  uint32_t count)
{
  nsresult rv = NS_ERROR_FAILURE;
  // first, check to see if we've been canceled....
  if (mCanceled) // then go cancel our underlying channel too
    return request->Cancel(NS_BINDING_ABORTED);
  
  if (!mInitialized)
    InitializeDownload(request);

  if (m_outputStream)
  {
    mProgress += count;
    uint64_t available;
    uint32_t readCount, maxReadCount = sizeof(m_dataBuffer);
    uint32_t writeCount;
    rv = inStream->Available(&available);
    while (NS_SUCCEEDED(rv) && available)
    {
      if (maxReadCount > available)
        maxReadCount = (uint32_t)available;
      rv = inStream->Read(m_dataBuffer, maxReadCount, &readCount);

      // rhp:
      // Ok, now we do one of two things. If we are sending out HTML, then
      // just write it to the HTML stream as it comes along...but if this is
      // a save as TEXT operation, we need to buffer this up for conversion
      // when we are done. When the stream converter for HTML-TEXT gets in place,
      // this magic can go away.
      //
      if (NS_SUCCEEDED(rv))
      {
        if ( (m_doCharsetConversion) && (m_outputFormat == ePlainText) )
          m_msgBuffer.Append(Substring(m_dataBuffer, m_dataBuffer + readCount));
        else
          rv = m_outputStream->Write(m_dataBuffer, readCount, &writeCount);

        available -= readCount;
      }
    }

    if (NS_SUCCEEDED(rv) && mTransfer) // Send progress notification.
      mTransfer->OnProgressChange64(nullptr, request, mProgress, mMaxProgress, mProgress, mMaxProgress);
  }
  return rv;
}

#define MESSENGER_STRING_URL       "chrome://messenger/locale/messenger.properties"

nsresult
nsMessenger::InitStringBundle()
{
  if (mStringBundle)
    return NS_OK;

  const char propertyURL[] = MESSENGER_STRING_URL;
  nsCOMPtr<nsIStringBundleService> sBundleService =
    mozilla::services::GetStringBundleService();
  NS_ENSURE_TRUE(sBundleService, NS_ERROR_UNEXPECTED);
  return sBundleService->CreateBundle(propertyURL,
                                      getter_AddRefs(mStringBundle));
}

void
nsMessenger::GetString(const nsString& aStringName, nsString& aValue)
{
  nsresult rv;
  aValue.Truncate();

  if (!mStringBundle)
    rv = InitStringBundle();

  if (mStringBundle)
    rv = mStringBundle->GetStringFromName(aStringName.get(), getter_Copies(aValue));
  else
    rv = NS_ERROR_FAILURE;

  if (NS_FAILED(rv) || aValue.IsEmpty())
    aValue = aStringName;
  return;
}

nsSaveAllAttachmentsState::nsSaveAllAttachmentsState(uint32_t count,
                                                     const char **contentTypeArray,
                                                     const char **urlArray,
                                                     const char **nameArray,
                                                     const char **uriArray,
                                                     const char *dirName,
                                                     bool detachingAttachments)
    : m_withoutWarning(false)
{
    uint32_t i;
    NS_ASSERTION(count && urlArray && nameArray && uriArray && dirName,
                 "fatal - invalid parameters\n");

    m_count = count;
    m_curIndex = 0;
    m_contentTypeArray = new char*[count];
    m_urlArray = new char*[count];
    m_displayNameArray = new char*[count];
    m_messageUriArray = new char*[count];
    for (i = 0; i < count; i++)
    {
        m_contentTypeArray[i] = strdup(contentTypeArray[i]);
        m_urlArray[i] = strdup(urlArray[i]);
        m_displayNameArray[i] = strdup(nameArray[i]);
        m_messageUriArray[i] = strdup(uriArray[i]);
    }
    m_directoryName = strdup(dirName);
    m_detachingAttachments = detachingAttachments;
}

nsSaveAllAttachmentsState::~nsSaveAllAttachmentsState()
{
    uint32_t i;
    for (i = 0; i < m_count; i++)
    {
      NS_Free(m_contentTypeArray[i]);
      NS_Free(m_urlArray[i]);
      NS_Free(m_displayNameArray[i]);
      NS_Free(m_messageUriArray[i]);
    }
    delete[] m_contentTypeArray;
    delete[] m_urlArray;
    delete[] m_displayNameArray;
    delete[] m_messageUriArray;
    NS_Free(m_directoryName);
}

nsresult
nsMessenger::GetLastSaveDirectory(nsIFile **aLastSaveDir)
{
  nsresult rv;
  nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  // this can fail, and it will, on the first time we call it, as there is no default for this pref.
  nsCOMPtr <nsIFile> localFile;
  rv = prefBranch->GetComplexValue(MESSENGER_SAVE_DIR_PREF_NAME, NS_GET_IID(nsIFile), getter_AddRefs(localFile));
  if (NS_SUCCEEDED(rv)) {
    NS_IF_ADDREF(*aLastSaveDir = localFile);
  }
  return rv;
}

nsresult
nsMessenger::SetLastSaveDirectory(nsIFile *aLocalFile)
{
  nsresult rv;
  nsCOMPtr<nsIPrefBranch> prefBranch = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  nsCOMPtr <nsIFile> file = do_QueryInterface(aLocalFile, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  // if the file is a directory, just use it for the last dir chosen
  // otherwise, use the parent of the file as the last dir chosen.
  // IsDirectory() will return error on saving a file, as the
  // file doesn't exist yet.
  bool isDirectory;
  rv = file->IsDirectory(&isDirectory);
  if (NS_SUCCEEDED(rv) && isDirectory) {
    rv = prefBranch->SetComplexValue(MESSENGER_SAVE_DIR_PREF_NAME, NS_GET_IID(nsIFile), aLocalFile);
    NS_ENSURE_SUCCESS(rv,rv);
  }
  else {
    nsCOMPtr <nsIFile> parent;
    rv = file->GetParent(getter_AddRefs(parent));
    NS_ENSURE_SUCCESS(rv,rv);

    rv = prefBranch->SetComplexValue(MESSENGER_SAVE_DIR_PREF_NAME, NS_GET_IID(nsIFile), parent);
    NS_ENSURE_SUCCESS(rv,rv);
  }
  return NS_OK;
}

/* void getUrisAtNavigatePos (in long aPos, out ACString aFolderUri, out ACString aMsgUri); */
// aPos is relative to the current history cursor - 1 is forward, -1 is back.
NS_IMETHODIMP nsMessenger::GetMsgUriAtNavigatePos(int32_t aPos, nsACString& aMsgUri)
{
  int32_t desiredArrayIndex = (mCurHistoryPos + (aPos << 1));
  if (desiredArrayIndex >= 0 && desiredArrayIndex < (int32_t)mLoadedMsgHistory.Length())
  {
    mNavigatingToUri = mLoadedMsgHistory[desiredArrayIndex];
    aMsgUri = mNavigatingToUri;
    return NS_OK;
  }
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP nsMessenger::SetNavigatePos(int32_t aPos)
{
  if ((aPos << 1) < (int32_t)mLoadedMsgHistory.Length())
  {
    mCurHistoryPos = aPos << 1;
    return NS_OK;
  }
  else
    return NS_ERROR_INVALID_ARG;
}

NS_IMETHODIMP nsMessenger::GetNavigatePos(int32_t *aPos)
{
  NS_ENSURE_ARG_POINTER(aPos);
  *aPos = mCurHistoryPos >> 1;
  return NS_OK;
}

// aPos is relative to the current history cursor - 1 is forward, -1 is back.
NS_IMETHODIMP nsMessenger::GetFolderUriAtNavigatePos(int32_t aPos, nsACString& aFolderUri)
{
  int32_t desiredArrayIndex = (mCurHistoryPos + (aPos << 1));
  if (desiredArrayIndex >= 0 && desiredArrayIndex < (int32_t)mLoadedMsgHistory.Length())
  {
    mNavigatingToUri = mLoadedMsgHistory[desiredArrayIndex + 1];
    aFolderUri = mNavigatingToUri;
    return NS_OK;
  }
  return NS_ERROR_FAILURE;
}

NS_IMETHODIMP nsMessenger::GetNavigateHistory(uint32_t *aCurPos, uint32_t *aCount, char *** aHistoryUris)
{
  NS_ENSURE_ARG_POINTER(aCount);
  NS_ENSURE_ARG_POINTER(aCurPos);

  *aCurPos = mCurHistoryPos >> 1;
  *aCount = mLoadedMsgHistory.Length();
  // for just enabling commands, we don't need the history uris.
  if (!aHistoryUris)
    return NS_OK;

  char **outArray, **next;
  next = outArray = (char **)moz_xmalloc(*aCount * sizeof(char *));
  if (!outArray) return NS_ERROR_OUT_OF_MEMORY;
  for (uint32_t i = 0; i < *aCount; i++)
  {
    *next = ToNewCString(mLoadedMsgHistory[i]);
    if (!*next)
      return NS_ERROR_OUT_OF_MEMORY;
    next++;
  }
  *aHistoryUris = outArray;
  return NS_OK;
}

NS_IMETHODIMP
nsMessenger::FormatFileSize(uint64_t aSize, bool aUseKB, nsAString& aFormattedSize)
{
  return ::FormatFileSize(aSize, aUseKB, aFormattedSize);
}


/* void OnItemAdded (in nsIMsgFolder parentItem, in nsISupports item); */
NS_IMETHODIMP nsMessenger::OnItemAdded(nsIMsgFolder *parentItem, nsISupports *item)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}

/* void OnItemRemoved (in nsIMsgFolder parentItem, in nsISupports item); */
NS_IMETHODIMP nsMessenger::OnItemRemoved(nsIMsgFolder *parentItem, nsISupports *item)
{
  // check if this item is a message header that's in our history list. If so,
  // remove it from the history list.
  nsCOMPtr <nsIMsgDBHdr> msgHdr = do_QueryInterface(item);
  if (msgHdr)
  {
    nsCOMPtr <nsIMsgFolder> folder;
    msgHdr->GetFolder(getter_AddRefs(folder));
    if (folder)
    {
      nsCString msgUri;
      nsMsgKey msgKey;
      msgHdr->GetMessageKey(&msgKey);
      folder->GenerateMessageURI(msgKey, msgUri);
      // need to remove the correspnding folder entry, and
      // adjust the current history pos.
      size_t uriPos = mLoadedMsgHistory.IndexOf(msgUri);
      if (uriPos != mLoadedMsgHistory.NoIndex)
      {
        mLoadedMsgHistory.RemoveElementAt(uriPos);
        mLoadedMsgHistory.RemoveElementAt(uriPos); // and the folder uri entry
        if (mCurHistoryPos >= (int32_t)uriPos)
          mCurHistoryPos -= 2;
      }
    }
  }
  return NS_OK;
}

/* void OnItemPropertyChanged (in nsIMsgFolder item, in nsIAtom property, in string oldValue, in string newValue); */
NS_IMETHODIMP nsMessenger::OnItemPropertyChanged(nsIMsgFolder *item, nsIAtom *property, const char *oldValue, const char *newValue)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}

/* void OnItemIntPropertyChanged (in nsIMsgFolder item, in nsIAtom property, in long long oldValue, in long long newValue); */
NS_IMETHODIMP nsMessenger::OnItemIntPropertyChanged(nsIMsgFolder *item, nsIAtom *property, int64_t oldValue, int64_t newValue)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}

/* void OnItemBoolPropertyChanged (in nsIMsgFolder item, in nsIAtom property, in boolean oldValue, in boolean newValue); */
NS_IMETHODIMP nsMessenger::OnItemBoolPropertyChanged(nsIMsgFolder *item, nsIAtom *property, bool oldValue, bool newValue)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}

/* void OnItemUnicharPropertyChanged (in nsIMsgFolder item, in nsIAtom property, in wstring oldValue, in wstring newValue); */
NS_IMETHODIMP nsMessenger::OnItemUnicharPropertyChanged(nsIMsgFolder *item, nsIAtom *property, const char16_t *oldValue, const char16_t *newValue)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}

/* void OnItemPropertyFlagChanged (in nsIMsgDBHdr item, in nsIAtom property, in unsigned long oldFlag, in unsigned long newFlag); */
NS_IMETHODIMP nsMessenger::OnItemPropertyFlagChanged(nsIMsgDBHdr *item, nsIAtom *property, uint32_t oldFlag, uint32_t newFlag)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}

/* void OnItemEvent (in nsIMsgFolder item, in nsIAtom event); */
NS_IMETHODIMP nsMessenger::OnItemEvent(nsIMsgFolder *item, nsIAtom *event)
{
  return NS_ERROR_NOT_IMPLEMENTED;
}

///////////////////////////////////////////////////////////////////////////////
// Detach/Delete Attachments
///////////////////////////////////////////////////////////////////////////////

static const char * GetAttachmentPartId(const char * aAttachmentUrl)
{
  static const char partIdPrefix[] = "part=";
  const char * partId = PL_strstr(aAttachmentUrl, partIdPrefix);
  return partId ? (partId + sizeof(partIdPrefix) - 1) : nullptr;
}

static int CompareAttachmentPartId(const char * aAttachUrlLeft, const char * aAttachUrlRight)
{
  // part ids are numbers separated by periods, like "1.2.3.4".
  // we sort by doing a numerical comparison on each item in turn. e.g. "1.4" < "1.25"
  // shorter entries come before longer entries. e.g. "1.4" < "1.4.1.2"
  // return values:
  //  -2  left is a parent of right
  //  -1  left is less than right
  //   0  left == right
  //   1  right is greater than left
  //   2  right is a parent of left

  const char * partIdLeft  = GetAttachmentPartId(aAttachUrlLeft);
  const char * partIdRight = GetAttachmentPartId(aAttachUrlRight);

  // for detached attachments the URL does not contain any "part=xx"
  if(!partIdLeft)
    partIdLeft = "0";

  if(!partIdRight)
    partIdRight = "0";

  long idLeft, idRight;
  do
  {
    MOZ_ASSERT(partIdLeft && IS_DIGIT(*partIdLeft), "Invalid character in part id string");
    MOZ_ASSERT(partIdRight && IS_DIGIT(*partIdRight), "Invalid character in part id string");

    // if the part numbers are different then the numerically smaller one is first
    char *fixConstLoss;
    idLeft  = strtol(partIdLeft, &fixConstLoss, 10);
    partIdLeft = fixConstLoss;
    idRight = strtol(partIdRight, &fixConstLoss, 10);
    partIdRight = fixConstLoss;
    if (idLeft != idRight)
      return idLeft < idRight ? -1 : 1;

    // if one part id is complete but the other isn't, then the shortest one
    // is first (parents before children)
    if (*partIdLeft != *partIdRight)
      return *partIdRight ? -2 : 2;

    // if both part ids are complete (*partIdLeft == *partIdRight now) then
    // they are equal
    if (!*partIdLeft)
      return 0;

    MOZ_ASSERT(*partIdLeft == '.', "Invalid character in part id string");
    MOZ_ASSERT(*partIdRight == '.', "Invalid character in part id string");

    ++partIdLeft;
    ++partIdRight;
  }
  while (true);
  return 0;
}

// ------------------------------------

// struct on purpose -> show that we don't ever want a vtable
struct msgAttachment
{
  msgAttachment()
    : mContentType(nullptr),
      mUrl(nullptr),
      mDisplayName(nullptr),
      mMessageUri(nullptr)
  {
  }

  ~msgAttachment()
  {
    Clear();
  }

  void Clear()
  {
    NS_Free(mContentType);
    NS_Free(mUrl);
    NS_Free(mDisplayName);
    NS_Free(mMessageUri);
  }

  bool Init(const char * aContentType, const char * aUrl,
              const char * aDisplayName, const char * aMessageUri)
  {
    Clear();
    mContentType = strdup(aContentType);
    mUrl = strdup(aUrl);
    mDisplayName = strdup(aDisplayName);
    mMessageUri = strdup(aMessageUri);
    return (mContentType && mUrl && mDisplayName && mMessageUri);
  }

  // take the pointers from aSource
  void Adopt(msgAttachment & aSource)
  {
    Clear();

    mContentType = aSource.mContentType;
    mUrl = aSource.mUrl;
    mDisplayName = aSource.mDisplayName;
    mMessageUri = aSource.mMessageUri;

    aSource.mContentType = nullptr;
    aSource.mUrl = nullptr;
    aSource.mDisplayName = nullptr;
    aSource.mMessageUri = nullptr;
  }

  char* mContentType;
  char* mUrl;
  char* mDisplayName;
  char* mMessageUri;

private:
  // disable by not implementing
  msgAttachment(const msgAttachment & rhs);
  msgAttachment & operator=(const msgAttachment & rhs);
};

// ------------------------------------

class nsAttachmentState
{
public:
  nsAttachmentState();
  ~nsAttachmentState();
  nsresult Init(uint32_t aCount,
                const char **aContentTypeArray,
                const char **aUrlArray,
                const char **aDisplayNameArray,
                const char **aMessageUriArray);
  nsresult PrepareForAttachmentDelete();

private:
  static int SortAttachmentsByPartId(const void * aLeft, const void * aRight, void *);

public:
  uint32_t        mCount;
  uint32_t        mCurIndex;
  msgAttachment*  mAttachmentArray;
};

nsAttachmentState::nsAttachmentState()
  : mCount(0),
    mCurIndex(0),
    mAttachmentArray(nullptr)
{
}

nsAttachmentState::~nsAttachmentState()
{
  delete[] mAttachmentArray;
}

nsresult
nsAttachmentState::Init(uint32_t aCount, const char ** aContentTypeArray,
                        const char ** aUrlArray, const char ** aDisplayNameArray,
                        const char ** aMessageUriArray)
{
  MOZ_ASSERT(aCount > 0, "count is invalid");

  mCount = aCount;
  mCurIndex = 0;
  delete[] mAttachmentArray;

  mAttachmentArray = new msgAttachment[aCount];
  if (!mAttachmentArray)
    return NS_ERROR_OUT_OF_MEMORY;

  for(uint32_t u = 0; u < aCount; ++u)
  {
    if (!mAttachmentArray[u].Init(aContentTypeArray[u], aUrlArray[u],
      aDisplayNameArray[u], aMessageUriArray[u]))
      return NS_ERROR_OUT_OF_MEMORY;
  }

  return NS_OK;
}

nsresult
nsAttachmentState::PrepareForAttachmentDelete()
{
  // this must be called before any processing
  if (mCurIndex != 0)
    return NS_ERROR_FAILURE;

  // this prepares the attachment list for use in deletion. In order to prepare, we
  // sort the attachments in numerical ascending order on their part id, remove all
  // duplicates and remove any subparts which will be removed automatically by the
  // removal of the parent.
  //
  // e.g. the attachment list processing (showing only part ids)
  // before: 1.11, 1.3, 1.2, 1.2.1.3, 1.4.1.2
  // sorted: 1.2, 1.2.1.3, 1.3, 1.4.1.2, 1.11
  // after:  1.2, 1.3, 1.4.1.2, 1.11

  // sort
  NS_QuickSort(mAttachmentArray, mCount, sizeof(msgAttachment), SortAttachmentsByPartId, nullptr);

  // remove duplicates and sub-items
  int nCompare;
  for(uint32_t u = 1; u < mCount;)
  {
    nCompare = ::CompareAttachmentPartId(mAttachmentArray[u-1].mUrl, mAttachmentArray[u].mUrl);
    if (nCompare == 0 || nCompare == -2) // [u-1] is the same as or a parent of [u]
    {
      // shuffle the array down (and thus keeping the sorted order)
      // this will get rid of the current unnecessary element
      for (uint32_t i = u + 1; i < mCount; ++i)
      {
        mAttachmentArray[i-1].Adopt(mAttachmentArray[i]);
      }
      --mCount;
    }
    else
    {
      ++u;
    }
  }

  return NS_OK;
}

int
nsAttachmentState::SortAttachmentsByPartId(const void * aLeft, const void * aRight, void *)
{
  msgAttachment & attachLeft  = *((msgAttachment*) aLeft);
  msgAttachment & attachRight = *((msgAttachment*) aRight);
  return ::CompareAttachmentPartId(attachLeft.mUrl, attachRight.mUrl);
}

// ------------------------------------

class nsDelAttachListener : public nsIStreamListener,
                            public nsIUrlListener,
                            public nsIMsgCopyServiceListener
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSISTREAMLISTENER
  NS_DECL_NSIREQUESTOBSERVER
  NS_DECL_NSIURLLISTENER
  NS_DECL_NSIMSGCOPYSERVICELISTENER

public:
  nsDelAttachListener();
  nsresult StartProcessing(nsMessenger * aMessenger, nsIMsgWindow * aMsgWindow,
    nsAttachmentState * aAttach, bool aSaveFirst);
  nsresult DeleteOriginalMessage();
  void SelectNewMessage();

public:
  nsAttachmentState * mAttach;                      // list of attachments to process
  bool mSaveFirst;                                // detach (true) or delete (false)
  nsCOMPtr<nsIFile> mMsgFile;                       // temporary file (processed mail)
  nsCOMPtr<nsIOutputStream> mMsgFileStream;         // temporary file (processed mail)
  nsCOMPtr<nsIMsgMessageService> mMessageService;   // original message service
  nsCOMPtr<nsIMsgDBHdr> mOriginalMessage;           // original message header
  nsCOMPtr<nsIMsgFolder> mMessageFolder;            // original message folder
  nsCOMPtr<nsIMessenger> mMessenger;                // our messenger instance
  nsCOMPtr<nsIMsgWindow> mMsgWindow;                // our UI window
  nsMsgKey mNewMessageKey;                          // new message key
  uint32_t mOrigMsgFlags;


   enum {
      eStarting,
      eCopyingNewMsg,
      eUpdatingFolder, // for IMAP
      eDeletingOldMessage,
      eSelectingNewMessage
    } m_state;
   // temp
  bool mWrittenExtra;
  bool mDetaching;
  nsTArray<nsCString> mDetachedFileUris;

private:
  virtual ~nsDelAttachListener();
};

//
// nsISupports
//
NS_IMPL_ISUPPORTS(nsDelAttachListener,
                   nsIStreamListener,
                   nsIRequestObserver,
                   nsIUrlListener,
                   nsIMsgCopyServiceListener)

//
// nsIRequestObserver
//
NS_IMETHODIMP
nsDelAttachListener::OnStartRequest(nsIRequest * aRequest, nsISupports * aContext)
{
  // called when we start processing the StreamMessage request.
  // This is called after OnStartRunningUrl().
  return NS_OK;
}

NS_IMETHODIMP
nsDelAttachListener::OnStopRequest(nsIRequest * aRequest, nsISupports * aContext, nsresult aStatusCode)
{
  // called when we have completed processing the StreamMessage request.
  // This is called after OnStopRequest(). This means that we have now
  // received all data of the message and we have completed processing.
  // We now start to copy the processed message from the temporary file
  // back into the message store, replacing the original message.

  mMessageFolder->CopyDataDone();
  if (NS_FAILED(aStatusCode))
    return aStatusCode;

  // called when we complete processing of the StreamMessage request.
  // This is called before OnStopRunningUrl().
  nsresult rv;

  // copy the file back into the folder. Note: setting msgToReplace only copies
  // metadata, so we do the delete ourselves
  nsCOMPtr<nsIMsgCopyServiceListener> listenerCopyService;
  rv = this->QueryInterface( NS_GET_IID(nsIMsgCopyServiceListener), getter_AddRefs(listenerCopyService) );
  NS_ENSURE_SUCCESS(rv,rv);

  mMsgFileStream->Close();
  mMsgFileStream = nullptr;
  mNewMessageKey = nsMsgKey_None;
  nsCOMPtr<nsIMsgCopyService> copyService = do_GetService(NS_MSGCOPYSERVICE_CONTRACTID);
  m_state = eCopyingNewMsg;
  // clone file because nsIFile on Windows caches the wrong file size.
  nsCOMPtr <nsIFile> clone;
  mMsgFile->Clone(getter_AddRefs(clone));
  if (copyService)
  {
    nsCString originalKeys;
    mOriginalMessage->GetStringProperty("keywords", getter_Copies(originalKeys));
    rv = copyService->CopyFileMessage(clone, mMessageFolder, mOriginalMessage, false,
                                      mOrigMsgFlags, originalKeys, listenerCopyService, mMsgWindow);
  }
  return rv;
}

//
// nsIStreamListener
//

NS_IMETHODIMP
nsDelAttachListener::OnDataAvailable(nsIRequest * aRequest, nsISupports * aSupport,
                                     nsIInputStream * aInStream, uint64_t aSrcOffset,
                                     uint32_t aCount)
{
  if (!mMsgFileStream)
    return NS_ERROR_NULL_POINTER;
  return mMessageFolder->CopyDataToOutputStreamForAppend(aInStream, aCount, mMsgFileStream);
}

//
// nsIUrlListener
//

NS_IMETHODIMP
nsDelAttachListener::OnStartRunningUrl(nsIURI * aUrl)
{
  // called when we start processing the StreamMessage request. This is
  // called before OnStartRequest().
  return NS_OK;
}

nsresult nsDelAttachListener::DeleteOriginalMessage()
{
  nsresult rv;
  nsCOMPtr<nsIMutableArray> messageArray(do_CreateInstance(NS_ARRAY_CONTRACTID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = messageArray->AppendElement(mOriginalMessage, false);
  NS_ENSURE_SUCCESS(rv,rv);
  nsCOMPtr<nsIMsgCopyServiceListener> listenerCopyService;

  QueryInterface( NS_GET_IID(nsIMsgCopyServiceListener), getter_AddRefs(listenerCopyService) );

  mOriginalMessage = nullptr;
  m_state = eDeletingOldMessage;
  return mMessageFolder->DeleteMessages(
    messageArray,         // messages
    mMsgWindow,           // msgWindow
    true,              // deleteStorage
    false,              // isMove
    listenerCopyService,  // listener
    false);            // allowUndo
}

void nsDelAttachListener::SelectNewMessage()
{
  nsCString displayUri;
  // all attachments refer to the same message
  const char * messageUri = mAttach->mAttachmentArray[0].mMessageUri;
  mMessenger->GetLastDisplayedMessageUri(displayUri);
  if (displayUri.Equals(messageUri))
  {
    mMessageFolder->GenerateMessageURI(mNewMessageKey, displayUri);
    if (!displayUri.IsEmpty() && mMsgWindow)
    {
      nsCOMPtr<nsIMsgWindowCommands> windowCommands;
      mMsgWindow->GetWindowCommands(getter_AddRefs(windowCommands));
      if (windowCommands)
        windowCommands->SelectMessage(displayUri);
    }
  }
  mNewMessageKey = nsMsgKey_None;
}

NS_IMETHODIMP
nsDelAttachListener::OnStopRunningUrl(nsIURI * aUrl, nsresult aExitCode)
{
  nsresult rv = NS_OK;
  const char * messageUri = mAttach->mAttachmentArray[0].mMessageUri;
  if (mOriginalMessage && !strncmp(messageUri, "imap-message:", 13))
  {
    if (m_state == eUpdatingFolder)
      rv = DeleteOriginalMessage();
  }
  // check if we've deleted the original message, and we know the new msg id.
  else if (m_state == eDeletingOldMessage && mMsgWindow)
    SelectNewMessage();

  return rv;
}

//
// nsIMsgCopyServiceListener
//

NS_IMETHODIMP
nsDelAttachListener::OnStartCopy(void)
{
  // never called?
  return NS_OK;
}

NS_IMETHODIMP
nsDelAttachListener::OnProgress(uint32_t aProgress, uint32_t aProgressMax)
{
  // never called?
  return NS_OK;
}

NS_IMETHODIMP
nsDelAttachListener::SetMessageKey(nsMsgKey aKey)
{
  // called during the copy of the modified message back into the message
  // store to notify us of the message key of the newly created message.
  mNewMessageKey = aKey;
  return NS_OK;
}

NS_IMETHODIMP
nsDelAttachListener::GetMessageId(nsACString& aMessageId)
{
  // never called?
  return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP
nsDelAttachListener::OnStopCopy(nsresult aStatus)
{
  // only if the currently selected message is the one that we are about to delete then we
  // change the selection to the new message that we just added. Failures in this code are not fatal.
  // Note that can only do this if we have the new message key, which we don't always get from IMAP.
  // delete the original message
  if (NS_FAILED(aStatus))
    return aStatus;

  // check if we've deleted the original message, and we know the new msg id.
  if (m_state == eDeletingOldMessage && mMsgWindow)
    SelectNewMessage();
  // do this for non-imap messages - for imap, we'll do the delete in
  // OnStopRunningUrl. For local messages, we won't get an OnStopRunningUrl
  // notification. And for imap, it's too late to delete the message here,
  // because we'll be updating the folder naturally as a result of
  // running an append url. If we delete the header here, that folder
  // update will think we need to download the header...If we do it
  // in OnStopRunningUrl, we'll issue the delete before we do the
  // update....all nasty stuff.
  const char * messageUri = mAttach->mAttachmentArray[0].mMessageUri;
  if (mOriginalMessage && strncmp(messageUri, "imap-message:", 13))
    return DeleteOriginalMessage();
  else
    m_state = eUpdatingFolder;
  return NS_OK;
}

//
// local methods
//

nsDelAttachListener::nsDelAttachListener()
{
  mAttach = nullptr;
  mSaveFirst = false;
  mWrittenExtra = false;
  mNewMessageKey = nsMsgKey_None;
  m_state = eStarting;
}

nsDelAttachListener::~nsDelAttachListener()
{
  if (mAttach)
  {
    delete mAttach;
  }
  if (mMsgFileStream)
  {
    mMsgFileStream->Close();
    mMsgFileStream = nullptr;
  }
  if (mMsgFile)
  {
    mMsgFile->Remove(false);
  }
}

nsresult
nsDelAttachListener::StartProcessing(nsMessenger * aMessenger, nsIMsgWindow * aMsgWindow,
                                     nsAttachmentState * aAttach, bool detaching)
{
  aMessenger->QueryInterface(NS_GET_IID(nsIMessenger), getter_AddRefs(mMessenger));
  mMsgWindow = aMsgWindow;
  mAttach    = aAttach;
  mDetaching = detaching;

  nsresult rv;

  // all attachments refer to the same message
  const char * messageUri = mAttach->mAttachmentArray[0].mMessageUri;

  // get the message service, original message and folder for this message
  rv = GetMessageServiceFromURI(nsDependentCString(messageUri), getter_AddRefs(mMessageService));
  NS_ENSURE_SUCCESS(rv,rv);
  rv = mMessageService->MessageURIToMsgHdr(messageUri, getter_AddRefs(mOriginalMessage));
  NS_ENSURE_SUCCESS(rv,rv);
  rv = mOriginalMessage->GetFolder(getter_AddRefs(mMessageFolder));
  NS_ENSURE_SUCCESS(rv,rv);
  mOriginalMessage->GetFlags(&mOrigMsgFlags);

  // ensure that we can store and delete messages in this folder, if we
  // can't then we can't do attachment deleting
  bool canDelete = false;
  mMessageFolder->GetCanDeleteMessages(&canDelete);
  bool canFile = false;
  mMessageFolder->GetCanFileMessages(&canFile);
  if (!canDelete || !canFile)
    return NS_ERROR_FAILURE;

  // create an output stream on a temporary file. This stream will save the modified
  // message data to a file which we will later use to replace the existing message.
  // The file is removed in the destructor.
  rv = GetSpecialDirectoryWithFileName(NS_OS_TEMP_DIR, "nsmail.tmp",
                                       getter_AddRefs(mMsgFile));
  NS_ENSURE_SUCCESS(rv,rv);

  // For temp file, we should use restrictive 00600 instead of ATTACHMENT_PERMISSION 
  rv = mMsgFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 00600);
  NS_ENSURE_SUCCESS(rv,rv);

  rv = MsgNewBufferedFileOutputStream(getter_AddRefs(mMsgFileStream), mMsgFile, -1, ATTACHMENT_PERMISSION);

  // create the additional header for data conversion. This will tell the stream converter
  // which MIME emitter we want to use, and it will tell the MIME emitter which attachments
  // should be deleted.
  const char * partId;
  const char * nextField;
  nsAutoCString sHeader("attach&del=");
  nsAutoCString detachToHeader("&detachTo=");
  for (uint32_t u = 0; u < mAttach->mCount; ++u)
  {
    if (u > 0)
    {
      sHeader.Append(",");
      if (detaching)
        detachToHeader.Append(",");
    }
    partId = GetAttachmentPartId(mAttach->mAttachmentArray[u].mUrl);
    nextField = PL_strchr(partId, '&');
    sHeader.Append(partId, nextField ? nextField - partId : -1);
    if (detaching)
      detachToHeader.Append(mDetachedFileUris[u]);
  }

  if (detaching)
    sHeader.Append(detachToHeader);
  // stream this message to our listener converting it via the attachment mime
  // converter. The listener will just write the converted message straight to disk.
  nsCOMPtr<nsISupports> listenerSupports;
  rv = this->QueryInterface(NS_GET_IID(nsISupports), getter_AddRefs(listenerSupports));
  NS_ENSURE_SUCCESS(rv,rv);
  nsCOMPtr<nsIUrlListener> listenerUrlListener = do_QueryInterface(listenerSupports, &rv);
  NS_ENSURE_SUCCESS(rv,rv);

  nsCOMPtr<nsIURI> dummyNull;
  rv = mMessageService->StreamMessage(messageUri, listenerSupports, mMsgWindow,
                                      listenerUrlListener, true, sHeader,
                                      false, getter_AddRefs(dummyNull));
  NS_ENSURE_SUCCESS(rv,rv);

  return NS_OK;
}

// ------------------------------------

NS_IMETHODIMP
nsMessenger::DetachAttachment(const char * aContentType, const char * aUrl,
                              const char * aDisplayName, const char * aMessageUri,
                              bool aSaveFirst, bool withoutWarning = false)
{
  NS_ENSURE_ARG_POINTER(aContentType);
  NS_ENSURE_ARG_POINTER(aUrl);
  NS_ENSURE_ARG_POINTER(aDisplayName);
  NS_ENSURE_ARG_POINTER(aMessageUri);

  if (aSaveFirst)
    return SaveOneAttachment(aContentType, aUrl, aDisplayName, aMessageUri, true);
  return DetachAttachments(1, &aContentType, &aUrl, &aDisplayName, &aMessageUri, nullptr, withoutWarning);
}

NS_IMETHODIMP
nsMessenger::DetachAllAttachments(uint32_t aCount,
                                  const char ** aContentTypeArray,
                                  const char ** aUrlArray,
                                  const char ** aDisplayNameArray,
                                  const char ** aMessageUriArray,
                                  bool aSaveFirst,
                                  bool withoutWarning = false)
{
  NS_ENSURE_ARG_MIN(aCount, 1);
  NS_ENSURE_ARG_POINTER(aContentTypeArray);
  NS_ENSURE_ARG_POINTER(aUrlArray);
  NS_ENSURE_ARG_POINTER(aDisplayNameArray);
  NS_ENSURE_ARG_POINTER(aMessageUriArray);

  if (aSaveFirst)
    return SaveAllAttachments(aCount, aContentTypeArray, aUrlArray, aDisplayNameArray, aMessageUriArray, true);
  else
    return DetachAttachments(aCount, aContentTypeArray, aUrlArray, aDisplayNameArray, aMessageUriArray, nullptr, withoutWarning);
}

nsresult
nsMessenger::DetachAttachments(uint32_t aCount,
                               const char ** aContentTypeArray,
                               const char ** aUrlArray,
                               const char ** aDisplayNameArray,
                               const char ** aMessageUriArray,
                               nsTArray<nsCString> *saveFileUris,
                               bool withoutWarning)
{
  // if withoutWarning no dialog for user
  if (!withoutWarning && NS_FAILED(PromptIfDeleteAttachments(saveFileUris != nullptr, aCount, aDisplayNameArray)))
      return NS_OK;
  
  nsresult rv = NS_OK;

  // ensure that our arguments are valid
//  char * partId;
  for (uint32_t u = 0; u < aCount; ++u)
  {
    // ensure all of the message URI are the same, we cannot process
    // attachments from different messages
    if (u > 0 && 0 != strcmp(aMessageUriArray[0], aMessageUriArray[u]))
    {
      rv = NS_ERROR_INVALID_ARG;
      break;
    }

    // ensure that we don't have deleted messages in this list
    if (0 == strcmp(aContentTypeArray[u], MIMETYPE_DELETED))
    {
      rv = NS_ERROR_INVALID_ARG;
      break;
    }

    // for the moment we prevent any attachments other than root level
    // attachments being deleted (i.e. you can't delete attachments from a
    // email forwarded as an attachment). We do this by ensuring that the
    // part id only has a single period in it (e.g. "1.2").
    //TODO: support non-root level attachment delete
//    partId = ::GetAttachmentPartId(aUrlArray[u]);
//    if (!partId || PL_strchr(partId, '.') != PL_strrchr(partId, '.'))
//    {
//      rv = NS_ERROR_INVALID_ARG;
//      break;
//    }
  }
  if (NS_FAILED(rv))
  {
    Alert("deleteAttachmentFailure");
    return rv;
  }

  //TODO: ensure that nothing else is processing this message uri at the same time

  //TODO: if any of the selected attachments are messages that contain other
  // attachments we need to warn the user that all sub-attachments of those
  // messages will also be deleted. Best to display a list of them.

  // get the listener for running the url
  nsDelAttachListener * listener = new nsDelAttachListener;
  if (!listener)
    return NS_ERROR_OUT_OF_MEMORY;
  nsCOMPtr<nsISupports> listenerSupports; // auto-delete of the listener with error
  listener->QueryInterface(NS_GET_IID(nsISupports), getter_AddRefs(listenerSupports));

  if (saveFileUris)
    listener->mDetachedFileUris = *saveFileUris;
  // create the attachments for use by the listener
  nsAttachmentState * attach = new nsAttachmentState;
  if (!attach)
    return NS_ERROR_OUT_OF_MEMORY;
  rv = attach->Init(aCount, aContentTypeArray, aUrlArray, aDisplayNameArray, aMessageUriArray);
  if (NS_SUCCEEDED(rv))
    rv = attach->PrepareForAttachmentDelete();
  if (NS_FAILED(rv))
  {
    delete attach;
    return rv;
  }

  // initialize our listener with the attachments and details. The listener takes ownership
  // of 'attach' immediately irrespective of the return value (error or not).
  return listener->StartProcessing(this, mMsgWindow, attach, saveFileUris != nullptr);
}

nsresult
nsMessenger::PromptIfDeleteAttachments(bool aSaveFirst,
                                       uint32_t aCount,
                                       const char ** aDisplayNameArray)
{
  nsresult rv = NS_ERROR_FAILURE;

  nsCOMPtr<nsIPrompt> dialog(do_GetInterface(mDocShell));
  if (!dialog) return rv;

  if (!mStringBundle)
  {
    rv = InitStringBundle();
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // create the list of attachments we are removing
  nsString displayString;
  nsString attachmentList;
  for (uint32_t u = 0; u < aCount; ++u)
  {
    ConvertAndSanitizeFileName(aDisplayNameArray[u], displayString);
    attachmentList.Append(displayString);
    attachmentList.Append(char16_t('\n'));
  }
  const char16_t *formatStrings[] = { attachmentList.get() };

  // format the message and display
  nsString promptMessage;
  const char16_t * propertyName = aSaveFirst ?
    u"detachAttachments" : u"deleteAttachments";
  rv = mStringBundle->FormatStringFromName(propertyName, formatStrings, 1,getter_Copies(promptMessage));
  NS_ENSURE_SUCCESS(rv, rv);

  bool dialogResult = false;
  rv = dialog->Confirm(nullptr, promptMessage.get(), &dialogResult);
  NS_ENSURE_SUCCESS(rv, rv);

  return dialogResult ? NS_OK : NS_ERROR_FAILURE;
}