Source

qtm-1.2 / EditingWindow.cc

Full commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
/*******************************************************************************

  QTM - Qt-based blog manager
  Copyright (C) 2006-2010 Matthew J Smith

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License (version 2), as
  published by the Free Software Foundation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

 *******************************************************************************/

// EditingWindow.cc - Main window class for QTM applicaiton

// #define QTM_DEBUG

//#include <QApplication>
//#include <QCoreApplication>
#include <QDesktopWidget>
#include <QRect>
#include <QCursor>
#include <QSettings>
#include <QList>
#include <QMainWindow>
#include <QComboBox>
#include <QResizeEvent>
#include <QCloseEvent>
#include <QSize>
#include <QPoint>
#include <QColor>
#include <QPalette>
#include <QLabel>
#include <QStackedWidget>
#include <QTextBrowser>
#include <QPushButton>
#include <QToolButton>
#include <QVBoxLayout>
#include <QAction>
#include <QIcon>
#include <QPixmap>
#include <QWidget>
#include <QCheckBox>
#include <QLineEdit>
#include <QMessageBox>
#include <QTextCursor>
#include <QTextDocument>
#include <QTextDocumentFragment>
#include <QClipboard>
#include <QDir>
#include <QTemporaryFile>
#include <QTextStream>
#include <QDataStream>
#include <QChar>
#include <QRegExp>
#include <QRegExpValidator>
#include <QDateTime>
#include <QKeySequence>
#include <QFileDialog>
#include <QIODevice>
#include <QMap>
#include <QHash>
#include <QHashIterator>
#include <QWhatsThis>
#include <QHBoxLayout>
#include <QListWidget>
#include <QListWidgetItem>
#include <QFont>
#include <QFontDialog>
#include <QHostInfo>
#include <QProgressDialog>
#include <QTextEdit>
#include <QProcess>
#include <QProgressBar>
#include <QTimer>
#if QT_VERSION >= 0x040400 && !defined DONT_USE_PTE
#include <QPlainTextEdit>
#endif

#include "XmlRpcHandler.h"
#include "Application.h"
#include "EditingWindow.h"
#ifdef USE_SYSTRAYICON
#include "SysTrayIcon.h"
#endif
#ifdef USE_SAFEHTTP
#include "SafeHttp.h"
#else
#include <QHttp>
#endif

#ifdef Q_WS_MAC
#include <Carbon/Carbon.h>
#endif

#include "qtm_version.h"
#if defined Q_WS_X11 || defined Q_WS_WIN
#include "markdown_header.h"
#endif

#include <QtAlgorithms>
#include <QtNetwork>
#include <QtXml>
#include <cmath>

#include "addimg.xpm"
#include "addlink.xpm"
#include "blog-this.xpm"
#include "fileopen.xpm"
#include "filesave.xpm"
#include "more.xpm"
#include "paragraph.xpm"
#include "preview.xpm"
#include "textbold.xpm"
#include "textital.xpm"
#include "textul.xpm"
#include "bquote.xpm"
#include "addtag.xpm"
#include "addctag.xpm"
#include "remtag.xpm"

#define EDITOR ed

EditingWindow::EditingWindow( QString newPost, QWidget *parent )
: QMainWindow( parent )
{
  QDomElement detailElem, attribElem, nameElem, serverElem, locElem, loginElem, pwdElem;
  QSettings settings;

  setAttribute( Qt::WA_DeleteOnClose );
  doUiSetup();

  xmlEntities["quot"] = '"';
  xmlEntities["amp"]  = '&';
  xmlEntities["gt"]   = '>';
  xmlEntities["lt"]   = '<';
  xmlEntities["apos"] = '\'';

  readSettings();
  setEditorColors();
  setTextFonts();

  cw.chAllowComments->setEnabled( true );
  cw.chAllowComments->setCheckState( allowComments ? Qt::Checked :
                                Qt::Unchecked );
  cw.chAllowTB->setCheckState( allowTB ? Qt::Checked : Qt::Unchecked );

  handleEnableCategories();

  QFile accountsXmlFile( PROPERSEPS( QString( "%1/qtmaccounts2.xml" ).arg( localStorageDirectory ) ) );
  if( accountsDom.setContent( &accountsXmlFile ) ) {
    accountsXmlFile.close();
    setInitialAccount();
  }
  else {
    accountsXmlFile.close();
    accountsXmlFile.setFileName( PROPERSEPS( QString( "%1/qtmaccounts.xml" ).arg( localStorageDirectory ) ) );
    accountsXmlFile.open( QIODevice::ReadOnly | QIODevice::Text );
     if( accountsDom.setContent( &accountsXmlFile ) ) {
      accountsXmlFile.close();
      setInitialAccount();
    }
    else {
#ifndef NO_DEBUG_OUTPUT
      // qDebug() << "Can't read the XML";
#endif
      accountsXmlFile.close();
      accountsElement = accountsDom.createElement( "QTMAccounts" );

      readServerSettings();
      if( !server.isEmpty() ) {
        // qDebug() << "copying details to new default element";
        currentAccountElement = accountsDom.createElement( "account" );
        currentAccountElement.setAttribute( "id", "default" );
        detailElem = accountsDom.createElement( "details" );
        nameElem = accountsDom.createElement( "title" );
        nameElem.appendChild( accountsDom.createTextNode( tr( "Default account" ) ) );
        serverElem = accountsDom.createElement( "server" );
        serverElem.appendChild( accountsDom.createTextNode( server ) );
        locElem = accountsDom.createElement( "location" );
        locElem.appendChild( accountsDom.createTextNode( location ) );
        loginElem = accountsDom.createElement( "login" );
        loginElem.appendChild( accountsDom.createTextNode( login ) );
        pwdElem = accountsDom.createElement( "password" );
        pwdElem.appendChild( accountsDom.createTextNode( password ) );
        detailElem.appendChild( nameElem );
        detailElem.appendChild( serverElem );
        detailElem.appendChild( locElem );
        detailElem.appendChild( loginElem );
        detailElem.appendChild( pwdElem );
        currentAccountElement.appendChild( detailElem );

        // Delete the old account from the settings
        settings.beginGroup( "account" );
        settings.remove( "server" );
        settings.remove( "location" );
        settings.remove( "login" );
        settings.remove( "password" );
        settings.endGroup();

        // Now transfer the attributes to the default accounts
        QStringList attribs( accountAttributes.keys() );
        Q_FOREACH( QString s, attribs ) {
          if( *(accountAttributes[s]) ) {
            attribElem = accountsDom.createElement( "attribute" );
            attribElem.setAttribute( "name", s );
            detailElem.appendChild( attribElem );
          }
        }
      }
      extractAccountDetails();

      accountsElement.appendChild( currentAccountElement );
      accountsDom.appendChild( accountsElement );
      accountsDom.insertBefore( accountsDom.createProcessingInstruction( "xml", "version=\"1.0\"" ),
                                accountsDom.firstChild() );
      QHostInfo::lookupHost( server, this, SLOT( handleInitialLookup( QHostInfo ) ) );
    }
  }

  checkForEmptySettings();
  if( !newPost.isEmpty() )
    EDITOR->setPlainText( newPost );
  mainStack->setCurrentIndex( edID );

}

EditingWindow::~EditingWindow()
{
  deleteLater();
}

#ifdef USE_SYSTRAYICON
void EditingWindow::setSTI( SysTrayIcon *_sti )
{
  sti = _sti;
}
#endif

void EditingWindow::doUiSetup()
{
  qApp->setWindowIcon( QIcon( QPixmap( ":/images/qtm-logo1.png" ) ) );

#ifdef USE_SYSTRAYICON
  sti = 0;
#endif

#if QT_VERSION >= 0x040300
  setUnifiedTitleAndToolBarOnMac( true );
#endif

  qtm = qobject_cast<Application *>( qApp );

  loadedEntryBlog = 999;
  noAutoSave = false;
  noAlphaCats = false;
  networkActionsEnabled = false;
  setAttribute( Qt::WA_QuitOnClose );

  userAgentString = QString( "QTM/%1" ).arg( QTM_VERSION );

  QCoreApplication::setOrganizationName( "Catkin Project" );
  QCoreApplication::setOrganizationDomain( "catkin.blogistan.co.uk" );
  QCoreApplication::setApplicationName( "QTM" );
#if QT_VERSION >= 0x040400
  QCoreApplication::setApplicationVersion ( QTM_VERSION );
#endif

  qtmaccounts_xml << "qtmaccounts2.xml" << "qtmaccounts.xml";

  ui.setupUi( this );
  currentHttpBusiness = None;
  entryBlogged = false;
  http = new _HTTP;

  // Setup main signals and slots

  ui.actionPrint->setEnabled( false );    // implemented
  ui.actionClose_and_Delete->setEnabled( false );

  connect( ui.action_About, SIGNAL( triggered( bool ) ),
           this, SLOT( about() ) );
  connect( ui.actionE_xit, SIGNAL( triggered( bool ) ),
           this, SLOT( doQuit() ) );
  connect( ui.action_Close, SIGNAL( triggered( bool ) ),
           this, SLOT( close() ) );
  connect( ui.actionAccounts, SIGNAL( triggered( bool ) ),
           this, SLOT( getAccounts() ) );
  connect( ui.actionPr_eferences, SIGNAL( triggered( bool ) ),
           this, SLOT( getPreferences() ) );
  connect( ui.actionRefresh_blog_list, SIGNAL( triggered( bool ) ),
           this, SLOT( refreshBlogList() ) );
  connect( ui.actionRefresh_categories, SIGNAL( triggered( bool ) ),
           this, SLOT( refreshCategories() ) );
#if QT_VERSION >= 0x040200
#if defined USE_SYSTRAYICON
  connect( ui.actionQuickpost_Templates, SIGNAL( triggered( bool ) ),
           this, SLOT( configureQuickpostTemplates() ) );
#else
  ui.actionQuickpost_Templates->setVisible( false );
#endif
#else
  ui.actionQuickpost_Templates->setVisible( false );
#endif

  // Set up icons

  ui.action_Blog_this->setIcon( QIcon( QPixmap( blogThisIcon_xpm ) ) );
  ui.actionP_review->setIcon( QIcon( QPixmap( previewIcon_xpm ) ) );
  ui.action_Open->setIcon( QIcon( QPixmap( fileopen ) ) );
  ui.action_Save->setIcon( QIcon( QPixmap( filesave ) ) );
  ui.action_Bold->setIcon( QIcon( QPixmap( mini_bold_xpm ) ) );
  ui.action_Italic->setIcon( QIcon( QPixmap( mini_ital_xpm ) ) );
  ui.actionU_nderline->setIcon( QIcon( QPixmap( underline_xpm ) ) );
  ui.actionBlockquote->setIcon( QIcon( QPixmap( bquote_xpm ) ) );
  ui.actionP_aragraph->setIcon( QIcon( QPixmap( paraIcon_xpm ) ) );
  ui.action_Link->setIcon( QIcon( QPixmap( linkIcon_xpm ) ) );
  ui.actionI_mage->setIcon( QIcon( QPixmap( imgIcon_xpm ) ) );
  ui.action_More->setIcon( QIcon( QPixmap( more_xpm ) ) );
  ui.actionAdd_tag->setIcon( QIcon( QPixmap( addtag_xpm ) ) );
  ui.actionAdd_tag_from_clipboard->setIcon( QIcon( QPixmap( addctag_xpm ) ) );
  ui.action_Remove_tag->setIcon( QIcon( QPixmap( remtag_xpm ) ) );

  // Action key sequences

  ui.actionStop_this_job->setShortcut( QKeySequence::fromString( "Ctrl+A" ) );
  ui.action_Bold->setShortcut( QKeySequence::fromString( "Ctrl+B" ) );
  ui.action_Italic->setShortcut( QKeySequence::fromString( "Ctrl+I" ) );
  ui.actionI_mage->setShortcut( QKeySequence::fromString( "Ctrl+J" ) );
  ui.action_Link->setShortcut( QKeySequence::fromString( "Ctrl+L" ) );
  ui.action_Auto_link->setShortcut( QKeySequence::fromString( "Shift+Ctrl+L" ) );
  ui.actionLink_from_C_lipboard->setShortcut( QKeySequence::fromString( "Ctrl+U" ) );
  ui.action_View_Console->setShortcut( QKeySequence::fromString( "Shift+Ctrl+V" ) );
  ui.action_BES->setShortcut( QKeySequence( "Ctrl+1" ) );
  ui.actionC_ategories->setShortcut( QKeySequence( "Ctrl+2" ) );
  ui.action_Show_Excerpt_window->setShortcut( QKeySequence( "Ctrl+3" ) );
  ui.actionKeyword_tags->setShortcut( QKeySequence( "Ctrl+4" ) );
  ui.actionTechnorati_tags->setShortcut( QKeySequence( "Ctrl+5" ) );
  ui.actionTrackback_pings->setShortcut( QKeySequence( "Ctrl+6" ) );
  ui.actionAdd_tag->setShortcut( QKeySequence( "Ctrl++" ) );
  ui.actionAdd_tag_from_clipboard->setShortcut( QKeySequence( "Shift+Ctrl++" ) );
  ui.action_Remove_tag->setShortcut( QKeySequence( "Ctrl+-" ) );

  // Add actions to toolbar

  ui.toolBar->addAction( ui.action_Open );
  ui.toolBar->addAction( ui.action_Save );
  ui.toolBar->addSeparator();
  ui.toolBar->addAction( ui.action_Bold );
  ui.toolBar->addAction( ui.action_Italic );
  ui.toolBar->addAction( ui.actionU_nderline );
  ui.toolBar->addAction( ui.actionBlockquote );
  ui.toolBar->addAction( ui.action_Link );
  ui.toolBar->addAction( ui.actionI_mage );
  ui.toolBar->addAction( ui.action_More );
  ui.toolBar->addSeparator();
  ui.toolBar->addAction( ui.actionP_review );
  ui.toolBar->addAction( ui.action_Blog_this );
  ui.toolBar->addSeparator();
  ui.toolBar->setAllowedAreas( Qt::TopToolBarArea | Qt::BottomToolBarArea );

  // Connect actions to slots

  connect( ui.action_New, SIGNAL( triggered( bool ) ),
           this, SLOT( newDoc() ) );
  connect( ui.action_Open, SIGNAL( triggered( bool ) ),
           this, SLOT( choose() ) );
  connect( ui.action_Save, SIGNAL( triggered( bool ) ),
           this, SLOT( save() ) );
  connect( ui.action_Export, SIGNAL( triggered( bool ) ),
           this, SLOT( exportEntry() ) );
  connect( ui.actionSave_As, SIGNAL( triggered( bool ) ),
           this, SLOT( saveAs() ) );
  connect( ui.actionSave_all, SIGNAL( triggered( bool ) ),
           qtm, SLOT( saveAll() ) );
  connect( ui.action_Upload, SIGNAL( triggered( bool ) ),
           this, SLOT( uploadFile() ) );
  connect( ui.actionStop_this_job, SIGNAL( triggered( bool ) ),
           this, SLOT( stopThisJob() ) );
  connect( ui.actionSend_categories, SIGNAL( triggered( bool ) ),
           this, SLOT( updatePostCategories() ) );
  connect( ui.actionSave_blogs, SIGNAL( triggered( bool ) ),
           this, SLOT( saveBlogs() ) );

#ifdef Q_WS_MAC
  // The action to view the toolbar is not required on the Mac, because the grey
  // lozenge at top right shows and hides the toolbar.
  ui.actionView_Toolbar->setVisible( false );
  ui.toolBar->setVisible( true );
#else
  connect( ui.actionView_Toolbar, SIGNAL( toggled( bool ) ),
           ui.toolBar, SLOT( setVisible( bool ) ) );
#endif

  connect( ui.action_Bold, SIGNAL( triggered( bool ) ),
           this, SLOT( makeBold() ) );
  connect( ui.action_Italic, SIGNAL( triggered( bool ) ),
           this, SLOT( makeItalic() ) );
  connect( ui.actionU_nderline, SIGNAL( triggered( bool ) ),
           this, SLOT( makeUnderline() ) );
  connect( ui.actionBlockquote, SIGNAL( triggered( bool ) ),
           this, SLOT( makeBlockquote() ) );
  connect( ui.action_More, SIGNAL( triggered( bool ) ),
           this, SLOT( insertMore() ) );
  connect( ui.action_Link, SIGNAL( triggered( bool ) ),
           this, SLOT( insertLink() ) );
  connect( ui.actionLink_from_C_lipboard, SIGNAL( triggered( bool ) ),
           this, SLOT( insertLinkFromClipboard() ) );
  connect( ui.action_Self_link, SIGNAL( triggered( bool ) ),
           this, SLOT( insertSelfLink() ) );
  connect( ui.action_Auto_link, SIGNAL( triggered( bool ) ),
           this, SLOT( insertAutoLink() ) );
  connect( ui.actionI_mage, SIGNAL( triggered( bool ) ),
           this, SLOT( insertImage() ) );
  connect( ui.actionIma_ge_from_Clipboard, SIGNAL( triggered( bool ) ),
           this, SLOT( insertImageFromClipboard() ) );
  connect( ui.action_Cut,  SIGNAL( triggered( bool ) ),   this, SLOT( cut() ) );
  connect( ui.actionC_opy, SIGNAL( triggered( bool ) ),   this, SLOT( copy() ) );
  connect( ui.actionCopy_upload_location, SIGNAL( triggered( bool ) ),
           this, SLOT( copyURL() ) );
  connect( ui.actionPaste, SIGNAL( triggered( bool ) ),   this, SLOT( paste() ) );
  connect( ui.actionTidy_paste, SIGNAL( triggered( bool ) ),
           this, SLOT( tidyPaste() ) );
  connect( ui.actionMarked_paragraphs, SIGNAL( triggered( bool ) ),
           this, SLOT( pasteAsMarkedParagraphs() ) );
  connect( ui.actionBlockquote_2, SIGNAL( triggered( bool ) ),
           this, SLOT( pasteAsBlockquote() ) );
  connect( ui.actionMarkdown_blockquote, SIGNAL( triggered( bool ) ),
           this, SLOT( pasteAsMarkdownBlockquote() ) );
  connect( ui.actionUnordered_list_2, SIGNAL( triggered( bool ) ),
           this, SLOT( pasteAsUnorderedList() ) );
  connect( ui.actionOrdered_list, SIGNAL( triggered( bool ) ),
           this, SLOT( pasteAsOrderedList() ) );
  connect( ui.action_Undo, SIGNAL( triggered( bool ) ),   this, SLOT( undo() ) );
  connect( ui.action_Redo, SIGNAL( triggered( bool ) ),   this, SLOT( redo() ) );
  connect( ui.actionUnordered_list, SIGNAL( triggered( bool ) ),
           this, SLOT( makeUnorderedList() ) );
  connect( ui.action_Ordered_list, SIGNAL( triggered( bool ) ),
           this, SLOT( makeOrderedList() ) );
#if QT_VERSION >= 0x040200
  ui.action_Font->setVisible( false );
  ui.actionPreview_font->setVisible( false );
  ui.actionConsole_font->setVisible( false );
#else
  connect( ui.action_Font, SIGNAL( triggered( bool ) ),   this, SLOT( doFont() ) );
  connect( ui.actionPreview_font, SIGNAL( triggered( bool ) ),
           this, SLOT( doPreviewFont() ) );
  connect( ui.actionConsole_font, SIGNAL( triggered( bool ) ),
           this, SLOT( doConsoleFont() ) );
#endif
  connect( ui.action_Add_category, SIGNAL( triggered( bool ) ),
           this, SLOT( newCategory() ) );
  connect( ui.actionP_review, SIGNAL( toggled( bool ) ),
           this, SLOT( doPreview( bool ) ) );
  connect( ui.action_BES, SIGNAL( triggered( bool ) ),
           this, SLOT( doViewBasicSettings() ) );
  connect( ui.actionC_ategories, SIGNAL( triggered( bool ) ),
           this, SLOT( doViewCategories() ) );
  connect( ui.action_Show_Excerpt_window, SIGNAL( triggered( bool ) ),
           this, SLOT( doViewExcerpt() ) );

  // Connect signals related to Wordpress-style (keyword) tags
  connect( ui.actionKeyword_tags, SIGNAL( triggered( bool ) ),
           this, SLOT( doViewKeywordTags() ) );
  connect( ui.actionAdd_Keyword_tag, SIGNAL( triggered( bool ) ),
           this, SLOT( addKeywordTag() ) );
  connect( ui.actionRemove_Keyword_tag, SIGNAL( triggered( bool ) ),
           this, SLOT( removeKeywordTag() ) );
  connect( ui.actionRefresh_Keyword_tags, SIGNAL( triggered( bool ) ),
           this, SLOT( refreshKeywordTags() ) );

  // Connect signals related to Technorati tags
  connect( ui.actionTechnorati_tags, SIGNAL( triggered( bool ) ),
           this, SLOT( doViewTechTags() ) );
  connect( ui.actionAdd_tag, SIGNAL( triggered( bool ) ),
           this, SLOT( addTechTag() ) );
  connect( ui.actionAdd_tag_from_clipboard, SIGNAL( triggered( bool ) ),
           this, SLOT( addClipTag() ) );
  connect( ui.action_Remove_tag, SIGNAL( triggered( bool ) ),
           this, SLOT( removeTechTag() ) );
  // Connect signals related to Trackback pings
  connect( ui.actionTrackback_pings, SIGNAL( triggered( bool ) ),
           this, SLOT( doViewTBPings() ) );
  connect( ui.actionAdd_trackback_ping, SIGNAL( triggered( bool ) ),
           this, SLOT( addTBPing() ) );
  connect( ui.actionAdd_ping_from_clip_board, SIGNAL( triggered( bool ) ),
           this, SLOT( addClipTBPing() ) );
  connect( ui.actionRe_move_ping, SIGNAL( triggered( bool ) ),
           this, SLOT( removeTBPing() ) );
  connect( ui.action_Blog_this, SIGNAL( triggered( bool ) ),
           this, SLOT( newMTPost() ) );
  connect( ui.action_What_s_this, SIGNAL( triggered( bool ) ),
           this, SLOT( doWhatsThis() ) );

  // Set up the main layout

  cWidget = new QWidget( this );

  leftWidget = new QWidget( cWidget );
  mainWindowLayout = new QHBoxLayout;
  mainWindowLayout->setMargin( 0 );
  mainWindowLayout->setMargin( 5 );
  cw.setupUi( leftWidget );

  connect( cw.lwOtherCats, SIGNAL( itemSelectionChanged() ),
           this, SLOT( changeOtherCatsHeading() ) );
  cw.cbBlogSelector->setMaxVisibleItems( 10 );
  cw.cbMainCat->setMaxVisibleItems( 10 );
  cw.lwTags->addAction( ui.actionAdd_tag );
  cw.lwTags->addAction( ui.actionAdd_tag_from_clipboard );
  cw.lwTags->addAction( ui.action_Remove_tag );
  cw.lwTBPings->addAction( ui.actionAdd_trackback_ping );
  cw.lwTBPings->addAction( ui.actionAdd_ping_from_clip_board );
  cw.lwTBPings->addAction( ui.actionRe_move_ping );

  addKeywordTag_forList = new QAction( tr( "Add this tag" ), 0 );
  removeKeywordTag_forList = new QAction( tr( "Remove this tag" ), 0 );
  _refreshKeywordTags = new QAction( tr( "Refresh" ), 0 );
  connect( addKeywordTag_forList, SIGNAL( triggered( bool ) ),
           this, SLOT( addKeywordTagFromAvailTags() ) );
  connect( removeKeywordTag_forList, SIGNAL( triggered( bool ) ),
           this, SLOT( removeKeywordTag() ) );
  connect( _refreshKeywordTags, SIGNAL( triggered( bool ) ),
           this, SLOT( refreshKeywordTags() ) );
  cw.lwKeywordTags->addAction( removeKeywordTag_forList );
  cw.lwAvailKeywordTags->addAction( addKeywordTag_forList );
  cw.lwAvailKeywordTags->addAction( _refreshKeywordTags );

  connect( cw.lwAvailKeywordTags, SIGNAL( itemDoubleClicked( QListWidgetItem * ) ),
           this, SLOT( addKeywordTagFromAvailTags() ) );
  connect( cw.leAddKeywordTag, SIGNAL( returnPressed() ),
           this, SLOT( addKeywordTagFromLineEdit() ) );
  connect( cw.tbAddKeywordTag, SIGNAL( clicked( bool ) ),
           this, SLOT( addKeywordTagFromLineEdit() ) );
  cw.tbSelectKeywordTag->setIcon( QIcon( ":/images/next.png" ) );
  cw.tbRemoveKeywordTag->setIcon( QIcon( ":/images/previous.png" ) );

  childCategoryHereAction = new QAction( tr( "Add child category" ), cw.lwOtherCats );
  connect( childCategoryHereAction, SIGNAL( triggered( bool ) ),
           this, SLOT( newChildCategory() ) );
  cw.lwOtherCats->addAction( childCategoryHereAction );

#ifdef Q_WS_MAC
  cw.lwOtherCats->setWhatsThis( tr( "Secondary categories, if your blog system supports "
                                    "them.  To highlight more than one category, press "
                                    "Command and click the mouse, or the left mouse button." ) );
#endif

  tagValidator = new QRegExpValidator( QRegExp( "([a-zA-Z0-9\\.%]+[\\+ ])*[a-zA-Z0-9\\.%]+" ), this );
  cw.leAddTag->setValidator( tagValidator );
  cw.cbDoTB->hide();

  // Set up main stack widget

  mainStack = new QStackedWidget( cWidget );
  previewWindow = new QTextBrowser( mainStack );
  previewWindowID = mainStack->addWidget( previewWindow );
#if QT_VERSION >= 0x040200
  previewWindow->setOpenExternalLinks( true );
#endif

  // Set up console
  console = new TEXTEDIT( mainStack );
  consoleID = mainStack->addWidget( console );
  console->setReadOnly( true );
  connect( ui.actionClear_console, SIGNAL( triggered( bool ) ),
           console, SLOT( clear() ) );

  // Set up editor widget
  ed = new TEXTEDIT( mainStack );
#if QT_VERSION < 0x040400 || defined DONT_USE_PTE
  EDITOR->setAcceptRichText( false );
#endif
  edID = mainStack->addWidget( ed );
  EDITOR->setReadOnly( false );
  previousRaisedLSWidget = edID;
  mainWindowLayout->addWidget( leftWidget, 3 );
  mainWindowLayout->addWidget( mainStack, 6 );
  mainWindowLayout->setSpacing( 1 );

  // Set up search widget
  mainWindowLayoutWithSearch = new QVBoxLayout( cWidget );
  searchWidget = new QijSearchWidget( EDITOR, this );
  searchWidget->hide();
  mainWindowLayoutWithSearch->setSpacing( 1 );
#if QT_VERSION >= 0x040300
  mainWindowLayoutWithSearch->setContentsMargins( 5, 5, 5, 5 );
#else
  mainWindowLayoutWithSearch->setMargin( 5 );
#endif
  mainWindowLayoutWithSearch->addLayout( mainWindowLayout );
  mainWindowLayoutWithSearch->addWidget( searchWidget );
  connect( ui.action_Find, SIGNAL( triggered( bool ) ),
           this, SLOT( handleFind() ) );
  connect( ui.actionFind_again, SIGNAL( triggered( bool ) ),
           searchWidget, SLOT( findAgain() ) );
  ui.action_Find->setShortcut( QKeySequence::fromString( "Ctrl+F" ) );
  ui.actionFind_again->setShortcut( QKeySequence::fromString( "Ctrl+G" ) );
  cWidget->setLayout( mainWindowLayoutWithSearch );
  setCentralWidget( cWidget );

  connect( cw.pbRefresh, SIGNAL( clicked( bool ) ),
           this, SLOT( refreshCategories() ) );
  connect( cw.pbRefresh, SIGNAL( clicked( bool ) ),
           cw.cbMainCat, SLOT( clear() ) );
  connect( cw.pbAddCategory, SIGNAL( clicked( bool ) ),
           this, SLOT( newCategory() ) ); 
  connect( cw.pbRefresh, SIGNAL( clicked( bool ) ),
           cw.lwOtherCats, SLOT( clear() ) );
  connect( ui.action_View_Console, SIGNAL( toggled( bool ) ),
           this, SLOT( handleConsole( bool ) ) );
  connect( cw.leTitle, SIGNAL( editingFinished() ),
           this, SLOT( changeCaptionAfterTitleChanged() ) );
  connect( cw.leAddTag, SIGNAL( returnPressed() ),
           this, SLOT( addTechTagFromAddButton() ) );
  connect( cw.tbAddTag, SIGNAL( clicked() ),
           this, SLOT( addTechTagFromLineEdit() ) );
  connect( cw.leTBPingURL, SIGNAL( returnPressed() ),
           this, SLOT( addTBPingFromLineEdit() ) );
  connect( cw.tbTBAdd, SIGNAL( clicked() ),
           this, SLOT( addTBPingFromLineEdit() ) );
  connect( cw.stackedWidget, SIGNAL( currentChanged( int ) ),
           this, SLOT( handleSideWidgetPageSwitch( int ) ) );
  connect( cw.tbSelectKeywordTag, SIGNAL( clicked( bool ) ),
           this, SLOT( addKeywordTagFromAvailTags() ) );
  connect( cw.tbRemoveKeywordTag, SIGNAL( clicked( bool ) ),
           this, SLOT( removeKeywordTag() ) );
  connect( cw.pbRefreshKeywordTags, SIGNAL( clicked( bool ) ),
           this, SLOT( refreshKeywordTags() ) );

  // Initialise recent file actions

  recentFilesMenu = new QMenu( this );
  noRecentFilesAction = new QAction( tr( "No recent files" ), this );
  noRecentFilesAction->setVisible( true );
  noRecentFilesAction->setEnabled( false );
  recentFilesMenu->addAction( noRecentFilesAction );
  ui.actionOpen_recent->setMenu( recentFilesMenu );
  for( int i = 0; i < 10; ++i ) {
    recentFileActions[i] = new QAction( this );
    recentFilesMenu->addAction( recentFileActions[i] );
    connect( recentFileActions[i], SIGNAL( triggered() ),
             this, SLOT( openRecentFile() ) );
  }

  cw.cbPageSelector->setCurrentIndex( 0 );
  cw.stackedWidget->setCurrentIndex( 0 );

  pbCopyURL = new QPushButton( this );
  pbCopyURL->setText( tr( "Copy URL" ) );
  pbCopyURL->setWhatsThis( tr( "Copy the location of the last uploaded file." ) );
  statusBar()->addPermanentWidget( pbCopyURL );
  connect( pbCopyURL, SIGNAL( clicked() ), this, SLOT( copyURL() ) );
  pbCopyURL->hide();

  progressBar = new QProgressBar;
  // statusBar()->addPermanentWidget( progressBar, 3 );
  progressBarContainer = new QWidget;
  //progressBarContainer->setContentsMargins( 0, 0, 0, 0 );
  progressBarLayout = new QHBoxLayout( progressBarContainer );
  progressBarLayout->setMargin( 0 );
  progressBarLayout->addWidget( progressBar, 1 );
  progressBarLayout->addStretch( 2 );
  progressBarAction = ui.toolBar->addWidget( progressBarContainer );
  progressBar->setEnabled( false );
  /* QSize pbSize( progressBar->size() );
  pbSize.setWidth( width() / 8 );
  progressBar->resize( pbSize ); */
  progressBarAction->setVisible( false );
  connect( progressBar, SIGNAL( valueChanged( int ) ),
           this, SLOT( hideProgressBarIfMaximum( int ) ) );

  dirtyIndicator = new QLabel( this );
  dirtyIndicator->setPixmap( QPixmap( filesave ) );
  statusBar()->addPermanentWidget( dirtyIndicator );
  setDirtySignals( true );
  dirtyIndicator->hide();

  // Set up hash of entry attributes
  accountAttributes["useHTTPS"] = &useHTTPS;
  accountAttributes["categoriesEnabled"] = &categoriesEnabled;
  accountAttributes["postDateTime"] = &postDateTime;
  accountAttributes["allowComments"] = &allowComments;
  accountAttributes["allowTB"] = &allowTB;
  accountAttributes["useWordpressAPI"] = &useWordpressAPI;

  accountStrings["server"] = &server;
  accountStrings["location"] = &location;
  accountStrings["port"] = &port;
  accountStrings["login"] = &login;
  accountStrings["password"] = &password;

  setWindowModified( false );
  entryEverSaved = false;
  cleanSave = false;
  loadAutoLinkDictionary();
}

bool EditingWindow::handleArguments()
{
  bool rv = true;
  int i;
  EditingWindow *c = 0;
  EditingWindow *d = 0;
  QStringList failedFiles;
  QStringList args = QApplication::arguments();

  if( args.size() > 1 ) {
    for( i = 1; i < args.size(); i++ ) {
      if( c ) // if there is a current new window
        d = c;
      c = new EditingWindow;
      if( c->load( args.at( i ) ) ) {
#ifdef USE_SYSTRAYICON
        c->setSTI( sti );
#endif
        if( d ) // if there's an old window
          positionWidget( c, d );
        c->show();
        rv = false;
      }
      else {
        failedFiles.append( args.at( i ) );
      }
      if( failedFiles.size() ) {
        if( failedFiles.size() < args.size()-1 ) {
          QMessageBox::information( this, tr( "Error" ),
                                    tr( "Could not load the following:\n\n%1" )
                                    .arg( failedFiles.join( "\n" ) ),
                                    QMessageBox::Ok );
          rv = false;
        }
        else {
          if( QMessageBox::question( 0, tr( "Error" ),
                                     tr( "Could not load the following:\n\n%1" )
                                     .arg( failedFiles.join( "\n" ) ),
                                     tr( "&Open blank window" ), tr( "E&xit" ), 0 ) )
            QApplication::exit();
          else
            rv = false;
        }
      }
    }
  }

  return rv;
}

void EditingWindow::about() // slot
{
  QDialog about_box( this );
  Ui::AboutBox abui;
  abui.setupUi( &about_box );
  abui.label->setText( abui.label->text().replace( "(VERSION)", QTM_VERSION ) );
  abui.label->setText( abui.label->text().replace( "(QT_VERSION)", QString( qVersion() ) ) );
  about_box.exec();
}

void EditingWindow::newDoc()
{
  EditingWindow *ed = new EditingWindow;
  ed->setWindowTitle( tr( "QTM - new entry [*]" ) );
#ifdef USE_SYSTRAYICON
  ed->setSTI( sti );
#endif

  positionWidget( ed, this );

  ed->show();
}

void EditingWindow::positionWidget( QWidget *w, QWidget *refWidget )
{
  QDesktopWidget *dw = QApplication::desktop();
  QRect r = dw->availableGeometry();
  QRect g = refWidget->geometry(); // of the reference widget

  if( (g.right() + 30) >= (r.right() + 30) &&
      (g.bottom() + 30 ) >= (r.bottom() + 30 ) )
    w->move( r.left(), r.top() );
  else
    w->move( refWidget->x() + 30, refWidget->y() + 30 );
}

void EditingWindow::changeCaptionAfterTitleChanged()
{
  if( cw.leTitle->text().isEmpty() )
    setWindowTitle( tr( "QTM - new entry [*]" ) );
  else
    setWindowTitle( QString( "%1 - QTM [*]" ).arg( cw.leTitle->text().trimmed() ) );
}

void EditingWindow::closeEvent( QCloseEvent *event )
{
  QSettings settings;

#ifndef NO_DEBUG_OUTPUT
  // qDebug( "close event" );
#endif

  if( isWindowModified() ) {
    if( !saveCheck() ) {
      event->ignore();
      qApp->setQuitOnLastWindowClosed( false );
    }
    else {
      settings.setValue( "account/lastAccountId", currentAccountId );
      event->accept();
    }
  } else {
    writeSettings();
    settings.setValue( "account/lastAccountId", currentAccountId );
    event->accept();
  }
}

void EditingWindow::showEvent( QShowEvent *event )
{
  // If the document is empty, the window unedited and the entry never saved,
  // chances are it's new
  if( EDITOR->document()->isEmpty() &&
      !dirtyIndicator->isVisible() &&
      !event->spontaneous() &&
      !entryEverSaved )
    cw.leTitle->setFocus( Qt::ActiveWindowFocusReason );

  QMainWindow::showEvent( event );
}

void EditingWindow::doQuit()
{
#ifndef NO_DEBUG_OUTPUT
  int i = QApplication::topLevelWidgets().size();
  // qDebug() << i << " top level widgets";
#endif

  qApp->setQuitOnLastWindowClosed( true );
  qApp->closeAllWindows();
}

void EditingWindow::checkForEmptySettings()
{
  //Check if this is a brand new user
  if( localStorageDirectory.isEmpty() || server.isEmpty() ) {
    if( QMessageBox::question( 0, tr( "Welcome to QTM" ),
                               tr( "You do not have any preferences set, and QTM "
                                   "needs to know where to find your blog, and where "
                                   "to store your data.\n\n"
                                   "Set these preferences now?" ),
                               QMessageBox::Yes | QMessageBox::Default,
                               QMessageBox::No ) == QMessageBox::Yes ) {
      getPreferences( tr( "Stage 1 of 2: Preferences" ));
      getAccounts( tr( "Stage 2 of 2: Accounts" ) );
    }
  }
}

void EditingWindow::setEditorColors()
{
  QPalette widgetPalette;

  // Set colours
  widgetPalette = EDITOR->palette();
  widgetPalette.setColor( QPalette::Base, editorBgColor );
  widgetPalette.setColor( QPalette::Text, editorFgColor );
  EDITOR->setPalette( widgetPalette );

  widgetPalette = previewWindow->palette();
  widgetPalette.setColor( QPalette::Base, previewBgColor );
  widgetPalette.setColor( QPalette::Text, previewFgColor );
  previewWindow->setPalette( widgetPalette );

  widgetPalette = console->palette();
  widgetPalette.setColor( QPalette::Base, consoleBgColor );
  widgetPalette.setColor( QPalette::Text, consoleFgColor );
  console->setPalette( widgetPalette );
}

inline void EditingWindow::setTextFonts()
{
  QFont f, g, h;

  if( editorFontString != "" ) {
    f.fromString( editorFontString );
    EDITOR->setFont( f );
  } else {
    f = EDITOR->font();
    editorFontString = f.toString();
  }
  if( previewFontString != "" ) {
    g.fromString( previewFontString );
    previewWindow->setFont( g );
  } else {
    g = previewWindow->font();
    previewFontString = g.toString();
  }
  if( consoleFontString != "" ) {
    h.fromString( consoleFontString );
    console->setFont( h );
  } else {
    h = console->font();
    consoleFontString = h.toString();
  }
}

void EditingWindow::setInitialAccount()
{
  int i;

  // qDebug() << "server is empty";
  QSettings settings;
  lastAccountID = settings.value( "account/lastAccountID", "" ).toString();
  QDomNodeList accountsList = accountsDom.documentElement()
    .elementsByTagName( "account" );
  QDomElement thisTitleElem;
  cw.cbAccountSelector->clear();

  if( accountsList.count() == 1 &&
      accountsList.at( 0 ).firstChildElement( "details" ).isNull() ) {
    // This is if there is just one legacy account
    readServerSettings();
    QDomElement detailElem, titleElem, serverElem, portElem, locElem,
                loginElem, pwdElem;
    detailElem = accountsDom.createElement( "details" );
    titleElem = accountsDom.createElement( "title" );
    titleElem.appendChild( accountsDom.createTextNode( tr( "Default account" ) ) );
    serverElem = accountsDom.createElement( "server" );
    serverElem.appendChild( accountsDom.createTextNode( server ) );
    locElem = accountsDom.createElement( "location" );
    locElem.appendChild( accountsDom.createTextNode( location ) );
    if( !port.isEmpty() ) {
      portElem = accountsDom.createElement( "port" );
      portElem.appendChild( accountsDom.createTextNode( port ) );
    }
    loginElem = accountsDom.createElement( "login" );
    loginElem.appendChild( accountsDom.createTextNode( login ) );
    pwdElem = accountsDom.createElement( "password" );
    pwdElem.appendChild( accountsDom.createTextNode( password ) );
    detailElem.appendChild( titleElem );
    detailElem.appendChild( serverElem );
    if( !portElem.isNull() )
      detailElem.appendChild( portElem );
    detailElem.appendChild( locElem );
    detailElem.appendChild( loginElem );
    detailElem.appendChild( pwdElem );
    accountsList.at( 0 ).insertBefore( detailElem, QDomNode() ); // i.e. insert it at the start
    accountsList.at( 0 ).toElement().setAttribute( "id", "default" );
  }

  for( i = 0; i < accountsList.count(); i++ ) {
    thisTitleElem = accountsList.at( i ).toElement().firstChildElement( "details" )
      .firstChildElement( "title" );
    if( !thisTitleElem.isNull() )
      cw.cbAccountSelector->addItem( decodeXmlEntities( thisTitleElem.text() ),
                                     accountsList.at( i ).toElement().attribute( "id" ) );
    else
      cw.cbAccountSelector->addItem( tr( "Unnamed account" ),
                                     accountsList.at( i ).toElement().attribute( "id" ).isEmpty() ?
                                     QString( "noid_%1" ).arg( i ) :
                                     accountsList.at( i ).toElement().attribute( "id" ) );
  }

  // Check if the last account is in the accounts list, and if so, make it current
  for( i = 0; i < accountsList.count(); i++ ) {
    if( accountsList.at( i ).toElement().attribute( "id" ) == lastAccountID ) {
      // qDebug() << "found it";
      currentAccountElement = accountsList.at( i ).toElement();
      currentAccountId = currentAccountElement.attribute( "id" );
      cw.cbAccountSelector->setCurrentIndex( i );
      extractAccountDetails();
      populateBlogList();
      setNetworkActionsEnabled( true );

      disconnect( cw.cbAccountSelector, SIGNAL( activated( int ) ),
                  this, SLOT( changeAccount( int ) ) );
      connect( cw.cbAccountSelector, SIGNAL( activated( int ) ),
               this, SLOT( changeAccount( int ) ) );
      break;
    }
    // If it reaches the end of the loop with no joy
    if( i == accountsList.count()-1 ) {
      // qDebug() << "using first account";
      currentAccountElement = accountsDom.documentElement()
        .firstChildElement( "account" );
      extractAccountDetails();
      populateBlogList();
      setNetworkActionsEnabled( true );
      disconnect( cw.cbAccountSelector, SIGNAL( activated( int ) ),
                  this, SLOT( changeAccount( int ) ) );
      connect( cw.cbAccountSelector, SIGNAL( activated( int ) ),
               this, SLOT( changeAccount( int ) ) );
    }
  }
}

void EditingWindow::readSettings()
{
  QString crf;
  Application::recentFile currentRF;
  QString defaultMarkdownPath, defaultPerlLocation;
  bool defaultUseMarkdown;

#ifdef Q_WS_MAC
     CFURLRef appUrlRef = CFBundleCopyBundleURL( CFBundleGetMainBundle() );
     CFStringRef macPath = CFURLCopyFileSystemPath( appUrlRef,
                                                    kCFURLPOSIXPathStyle);
     const char *pathPtr = CFStringGetCStringPtr( macPath,
                                                  CFStringGetSystemEncoding() );
     defaultMarkdownPath = QString( "%1/Contents/Resources/Markdown.pl" ).arg( pathPtr );
     CFRelease(appUrlRef);
     CFRelease(macPath);
     defaultUseMarkdown = true;
     defaultPerlLocation = "/usr/bin/perl";
#else
#ifdef Q_WS_WIN
     defaultMarkdownPath = QString( "%1/Markdown.pl" )
       .arg( QString( MARKDOWN_LOCATION ).replace( "%APPDIRPATH%", qApp->applicationDirPath() ) );
     defaultUseMarkdown = false;
     defaultPerlLocation = "C:\\Perl\\bin\\perl.exe";
#else
     // Presumably we're in X11
     defaultMarkdownPath = MARKDOWN_LOCATION;
     defaultUseMarkdown = true;
     defaultPerlLocation = "/usr/bin/perl";
#endif
#endif

#ifdef Q_WS_WIN
  QString defaultLocalStorageDir = QString( "%1\\QTM blog" ).arg( QDir::homePath() );
#else
  QString defaultLocalStorageDir = QString( "%1/qtm-blog" ).arg( QDir::homePath() );
#endif

  QSettings settings;
  applicationVersion = settings.value( "application/version", "" ).toString();
  settings.beginGroup( "geometry" );
  resize( settings.value( "size", QSize( 640, 450 )).toSize() );
  move( settings.value( "position", QPoint( 20, 20 )).toPoint() );
  settings.endGroup();
  settings.beginGroup( "account" );
  localStorageDirectory = settings.value( "localStorageDirectory", defaultLocalStorageDir ).toString();
  if( localStorageDirectory.contains( "~/" ) ) {
    localStorageDirectory.replace( "~", QDir::homePath() );
    settings.setValue( "localStorageDirectory", localStorageDirectory );
  }
  localStorageFileExtn = settings.value( "localStorageFileExtn", "cqt" ).toString();
  useMarkdown = settings.value( "useMarkdown", defaultUseMarkdown ).toBool();
  perlPath = settings.value( "perlPath", defaultPerlLocation ).toString();
  markdownPath = settings.value( "markdownPath", defaultMarkdownPath ).toString();
  doMarkdownWhenPosting = settings.value( "doMarkdownWhenPosting", useMarkdown ).toBool();
  stripParaTags = settings.value( "stripParaTags", false ).toBool();
  useHTTPS = settings.value( "useHTTPS", true ).toBool();
  categoriesEnabled = settings.value( "categoriesEnabled", true ).toBool();
  useNewWindows = settings.value( "useNewWindows", true ).toBool();
  savePassword = settings.value( "savePassword", false ).toBool();
  postAsSave = settings.value( "postAsSave", true ).toBool();
  allowComments = settings.value( "allowComments", true ).toBool();
  allowTB = settings.value( "allowTB", true ).toBool();
#ifdef USE_SYSTRAYICON
  copyTitle = settings.value( "copyTitle", true ).toBool();
#endif
#if QT_VERSION >= 0x040200
  allowRegexSearch = settings.value( "allowRegexSearch", false ).toBool();
#endif
  settings.endGroup();
  settings.beginGroup( "fonts" );
  editorFontString = settings.value( "editorFontString", "" ).toString();
  previewFontString = settings.value( "previewFontString", "" ).toString();
  consoleFontString = settings.value( "consoleFontString", "" ).toString();
  editorBgColor = QColor( settings.value( "editorBgColor", "#FFFFFF" ).toString() );
  editorFgColor = QColor( settings.value( "editorFgColor", "#000000" ).toString() );
  previewBgColor = QColor( settings.value( "previewBgColor", "#FFFFFF" ).toString() );
  previewFgColor = QColor( settings.value( "previewFgColor", "#000000" ).toString() );
  consoleBgColor = QColor( settings.value( "consoleBgColor", "#FFFFFF" ).toString() );
  consoleFgColor = QColor( settings.value( "consoleFgColor", "#000000" ).toString() );
  settings.endGroup();

#ifdef USE_SYSTRAYICON
  settings.beginGroup( "sysTrayIcon" );
  STI2ClickFunction = settings.value( "doubleClickFunction", 0 ).toInt();
  settings.endGroup();
#endif

  recentFiles = qtm->recentFiles();
  updateRecentFileMenu();
  connect( qtm, SIGNAL( recentFilesUpdated( QList<Application::recentFile> ) ),
           this, SLOT( setRecentFiles( QList<Application::recentFile> ) ) );

  if( server.isEmpty() || location.isEmpty() || login.isEmpty() ) {
    // Adequate network details absent, therefore disable all widgets and actions
    // leading to network use.
    setNetworkActionsEnabled( false );
  }

  cw.categoryPage->setEnabled( true );
  cw.chAllowComments->setEnabled( true );
  cw.chAllowTB->setEnabled( true );
#if QT_VERSION >= 0x040200
  searchWidget->setExpertEnabled( allowRegexSearch );
#endif
}

void EditingWindow::readServerSettings()
{
  //qDebug() << "getting server settings";
  QSettings settings;
    settings.beginGroup( "account" );      
    server = settings.value( "server", "" ).toString();
    location = settings.value( "location", "" ).toString();
    login = settings.value( "login", "" ).toString();
    password = settings.value( "password", "" ).toString();
}

void EditingWindow::handleEnableCategories()
{
  cw.gbCategory->setEnabled( categoriesEnabled );
  ui.actionRefresh_categories->setEnabled( categoriesEnabled );
  ui.actionSend_categories->setEnabled( categoriesEnabled );
}

void EditingWindow::setRecentFiles( const QList<Application::recentFile> &rfs )
{
  recentFiles = rfs;
  updateRecentFileMenu();
}

void EditingWindow::updateRecentFileMenu()
{
  QString text, t;
  int j;
  QMutableListIterator<Application::recentFile> i( recentFiles );

  while( i.hasNext() ) {
    if( !QFile::exists( i.next().filename ) )
      i.remove();
  }

  for( j = 0; j < 10; ++j ) {
    if( j < recentFiles.count() ) {
      t = recentFiles.value( j ).title.section( ' ', 0, 5 );
      if( t != recentFiles.value( j ).title )
        t.append( tr( " ..." ) );
      if( j == 9 )
        text = tr( "1&0 %1" )
          .arg( recentFiles.value( j ).title.isEmpty() ?
                recentFiles.value( j ).filename.section( "/", -1, -1 ) 
                : t.replace( '&', "&&" ) );
      else
        text  = tr("&%1 %2" )
          .arg( j + 1 )
          .arg( recentFiles.value( j ).title.isEmpty() ?
                recentFiles.value( j ).filename.section( "/", -1, -1 ) 
                : t.replace( '&', "&&" ) );
      recentFileActions[j]->setText( text );
      recentFileActions[j]->setData( recentFiles.value( j ).filename );
      recentFileActions[j]->setVisible( true );
      noRecentFilesAction->setVisible( false );
    }
    else {
      recentFileActions[j]->setVisible( false );
      if( !recentFiles.count() )
        noRecentFilesAction->setVisible( true );
    }
  }
}

void EditingWindow::openRecentFile()
{
  QAction *action = qobject_cast<QAction *>( sender() );
  if( action )
    choose( action->data().toString() );
}

void EditingWindow::writeSettings()
{
  QSettings settings;

  settings.beginGroup( "geometry" );
  settings.setValue( "size", size() );
  settings.setValue( "position", pos() );
  settings.endGroup();
}

void EditingWindow::callRefreshCategories()
{
  if( !currentHttpBusiness ) {
    cw.cbMainCat->clear();
    cw.lwOtherCats->clear();
    refreshCategories();
  }
  else {
#ifdef QTM_DEBUG
    if( currentHttpBusiness != _mt_getCategoryList ) {
      statusBar()->showMessage( tr( "changeBlog: All HTTP requests are blocked" ),
                                2000 );
      addToConsole( QString( "changeBlog %1 failed - HTTP job of type %2 ongoing" )
                    .arg( b )
                    .arg( (int)currentHttpBusiness ) );
    }

#else
    if( currentHttpBusiness != _mt_getCategoryList )
      statusBar()->showMessage( tr( "All HTTP requests are blocked." ), 2000 );
#endif
  }
#ifndef NO_DEBUG_OUTPUT
  // qDebug() << "Finishing changeblog";
#endif
}

void EditingWindow::refreshCategories()
{
  QDomElement param, value, integer, string;

  disconnect( SIGNAL( httpBusinessFinished() ) );
  if( !currentHttpBusiness ) {

    QDomDocument doc;
    QDomElement methodCall = doc.createElement( "methodCall" );
    methodCall.appendChild( XmlMethodName( doc, "mt.getCategoryList" ) );

    QDomElement params = doc.createElement( "params" );
    params.appendChild( XmlValue( doc, "string", currentBlogid ) );
    params.appendChild( XmlValue( doc, "string", currentAccountElement.firstChildElement( "details" )
                                  .firstChildElement( "login" ).text() ) );
    params.appendChild( XmlValue( doc, "string", currentAccountElement.firstChildElement( "details" )
                                  .firstChildElement( "password" ).text() ) );

    methodCall.appendChild( params );
    doc.appendChild( methodCall );
    doc.insertBefore( doc.createProcessingInstruction( "xml",
                                                       "version=\"1.0\" encoding=\"UTF-8\"" ),
                      doc.firstChild() );
    QByteArray requestArray( doc.toByteArray( 2 ) );
    responseData = "";
    QHttpRequestHeader header( "POST", location );
    header.setValue( "Host", server );
    header.setValue( "User-Agent", userAgentString );
    setHost( http, server, port, useHTTPS ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp );
    http->request( header, requestArray );

    addToConsole( header.toString() );
    addToConsole( doc.toString() );

    if( QApplication::overrideCursor() == 0 )
      QApplication::setOverrideCursor( QCursor( Qt::BusyCursor ) );

    currentHttpBusiness = _mt_getCategoryList;
    connect( http, SIGNAL( done( bool ) ),
             this, SLOT( handleDone( bool ) ) );
    connect( http, SIGNAL( readyRead( const QHttpResponseHeader & ) ),
             this, SLOT( handleResponseHeader( const QHttpResponseHeader & ) ) );
#ifndef DONT_USE_SSL
    connect( http, SIGNAL( sslErrors( const QList<QSslError> & ) ),
             this, SLOT( handleSSLErrors( const QList<QSslError> & ) ) );
#endif
#ifdef USE_SAFEHTTP
    connect( http, SIGNAL( hostLookupFailed() ),
             this, SLOT( handleHostLookupFailed() ) );
#endif
  }
  else {
#ifdef QTM_DEBUG
    statusBar()->showMessage( tr( "refreshCategories: All HTTP requests are blocked" ),
                              2000 );
#else
    statusBar()->showMessage( tr( "All HTTP requests are blocked." ), 2000 );
#endif
  }
}

QString EditingWindow::processWithMarkdown( const QString &text )
{
  QString conversionString = text;
  QString nullString, conversionStringB, tempFileName, mdPath;
  QTemporaryFile tf;

  if( tf.open() ) {
    tempFileName = tf.fileName();
    QTextStream tstream( &tf );
    tstream.setCodec( "UTF-8" );
    tstream << conversionString;
    tf.close();
  }
  else
    return QString();

  QStringList markdownPaths;
  markdownPaths << markdownPath
    << QString( "%1/Markdown/Markdown.pl" ).arg( QCoreApplication::applicationDirPath() )
    << QString( "%1/../Markdown/Markdown.pl" ).arg( QCoreApplication::applicationDirPath() )
    << "nofile";
  Q_FOREACH( QString mdp, markdownPaths ) {
    if( mdp == "nofile" )
      return QString();
    else
      if( QFile::exists( mdp ) ) {
        mdPath = mdp;
        break;
      }
  }

  QProcess proc;
  proc.start( perlPath, QStringList() << mdPath << tempFileName );
  if( !proc.waitForStarted() ) {
    statusBar()->showMessage( tr( "Failed to start conversion" ), 2000 );
    return QString();
  }

  // Now wait until the process finishes; use a loop and process events every 10th of a second
  for( int i = 0; i <= 300; ++i ) {
    if( i == 300 ) { // if 30 seconds has elapsed without a finish signal
      statusBar()->showMessage( tr( "Failed to convert" ), 2000 );
      return QString();
    }
    if( proc.waitForFinished( 100 ) )
      break;
    else
      qApp->processEvents();
  }
  conversionStringB = QString::fromUtf8( proc.readAllStandardOutput() );
  if( conversionStringB.length() < conversionString.length() ||
      proc.exitStatus() != QProcess::NormalExit ) {
    statusBar()->showMessage( tr( "Conversion failed" ), 2000 );
    if( proc.exitStatus() != QProcess::NormalExit )
      qDebug() << "Bad exit";
    // qDebug() << "Length:" << conversionStringB.length();
    return QString();
  }

  return conversionStringB;
}
void EditingWindow::getAccounts()
{
  getAccounts( QString() );
}

void EditingWindow::getAccounts( const QString &title )
{
  QList<AccountsDialog::Account> acctsList, returnedAccountsList;
  AccountsDialog::Account acct;
  QDomNodeList accountsList, thisAccountsAttribs;
  QDomDocument newAccountsDom;
  QDomElement newQTMAccounts, newAccount, detailElement, nameElement, serverElement, locationElement, 
              portElement, loginElement, pwdElement, blogsElement, boolElement, attribsElement, hbtElement;
  QString oldCurrentAccountId, oldBlogid, currentTitle;
  QStringList thisAccountsAttribStrings;
  int i, j;
  bool ok;

  // Extract accounts list from account tree
  accountsList = accountsDom.elementsByTagName( "account" );
  for( i = 0; i < accountsList.count(); i++ ) {
    acct = AccountsDialog::Account();
    acct.id = accountsList.at( i ).toElement().attribute( "id" );
    detailElement = accountsList.at( i ).firstChildElement( "details" );
    acct.name = detailElement.firstChildElement( "title" ).text();
    acct.server = detailElement.firstChildElement( "server" ).text();
    acct.location = detailElement.firstChildElement( "location" ).text();
    acct.port = detailElement.firstChildElement( "port" ).text();
    acct.login = detailElement.firstChildElement( "login" ).text();
    acct.password = detailElement.firstChildElement( "password" ).text();

    acct.hostedBlogType = 0;
    int hbt = detailElement.firstChildElement( "hostedBlogType" ).text().toInt( &ok );
    if( ok )
      acct.hostedBlogType = hbt;

    acct.useHTTPS = false;
    acct.categoriesEnabled = false;
    acct.postDateTime = false;
    acct.allowComments = false;
    acct.allowTB = false;
    acct.useWordpressAPI = false;

    thisAccountsAttribs = accountsList.at( i ).toElement().firstChildElement( "details" )
      .firstChildElement( "attributes" ).elementsByTagName( "attribute" );
    thisAccountsAttribStrings = QStringList();
    for( j = 0; j < thisAccountsAttribs.count(); j++ )
      thisAccountsAttribStrings << thisAccountsAttribs.at( j ).toElement().attribute( "name" );

    if( thisAccountsAttribStrings.contains( "useHTTPS" ) )
      acct.useHTTPS = true;

    if( thisAccountsAttribStrings.contains( "categoriesEnabled" ) ) {
      acct.categoriesEnabled = true;
    }
    if( thisAccountsAttribStrings.contains( "postDateTime" ) ) {
      acct.postDateTime = true;
    }
    if( thisAccountsAttribStrings.contains( "allowComments" ) ||
        thisAccountsAttribStrings.contains( "comments" ) ) {
      acct.allowComments = true;
    }
    if( thisAccountsAttribStrings.contains( "allowTB" ) ||
        thisAccountsAttribStrings.contains( "trackback" ) ) {
      acct.allowTB = true;
    }
    if( thisAccountsAttribStrings.contains( "useWordpressAPI" ) ) {
      acct.useWordpressAPI = true;
    }

    acctsList.append( acct );
  }

  oldCurrentAccountId = cw.cbAccountSelector->itemData( cw.cbAccountSelector->currentIndex() )
    .toString();
  oldBlogid = cw.cbBlogSelector->itemData( cw.cbBlogSelector->currentIndex() ).toString();
  int oldCurrentBlog = cw.cbAccountSelector->currentIndex();
  //accountsList = accountsDom.documentElement().elementsByTagName( "account" );

  AccountsDialog acctsDialog( acctsList, oldCurrentBlog, this );

  if( !title.isEmpty() )
    acctsDialog.setWindowTitle( title );

  if( acctsDialog.exec() ) {
    returnedAccountsList = acctsDialog.accounts();
    newQTMAccounts = newAccountsDom.createElement( "QTMAccounts" );

    for( i = 0; i < returnedAccountsList.count(); i++ ) {
      newAccount = newAccountsDom.createElement( "account" );
      newAccount.setAttribute( "id", returnedAccountsList.at( i ).id );
      detailElement = newAccountsDom.createElement( "details" );
      nameElement = newAccountsDom.createElement( "title" );
      nameElement.appendChild( newAccountsDom.createTextNode( returnedAccountsList.at( i ).name ) );
      hbtElement = newAccountsDom.createElement( "hostedBlogType" );
      hbtElement.appendChild( newAccountsDom.createTextNode( QString::number( returnedAccountsList.at( i ).hostedBlogType ) ) );
      serverElement = newAccountsDom.createElement( "server" );
      serverElement.appendChild( newAccountsDom.createTextNode( returnedAccountsList.at( i ).server ) );
      locationElement = newAccountsDom.createElement( "location" );
      locationElement.appendChild( newAccountsDom.createTextNode( returnedAccountsList.at( i ).location ) );
      portElement = newAccountsDom.createElement( "port" );
      portElement.appendChild( newAccountsDom.createTextNode( returnedAccountsList.at( i ).port ) );
      loginElement = newAccountsDom.createElement( "login" );
      loginElement.appendChild( newAccountsDom.createTextNode( returnedAccountsList.at( i ).login ) );
      pwdElement = newAccountsDom.createElement( "password" );
      pwdElement.appendChild( newAccountsDom.createTextNode( returnedAccountsList.at( i ).password ) );

      detailElement.appendChild( nameElement );
      detailElement.appendChild( hbtElement );
      detailElement.appendChild( serverElement );
      detailElement.appendChild( locationElement );
      detailElement.appendChild( portElement );
      detailElement.appendChild( loginElement );
      detailElement.appendChild( pwdElement );

      if( returnedAccountsList.at( i ).useHTTPS || returnedAccountsList.at( i ).categoriesEnabled 
          || returnedAccountsList.at( i ).postDateTime ||
          returnedAccountsList.at( i ).allowComments || returnedAccountsList.at( i ).allowTB )
        attribsElement = newAccountsDom.createElement( "attributes" );

      if( returnedAccountsList.at( i ).useHTTPS ) {
        boolElement = newAccountsDom.createElement( "attribute" );
        boolElement.setAttribute( "name", "useHTTPS" );
        attribsElement.appendChild( boolElement );
      }
      if( returnedAccountsList.at( i ).categoriesEnabled ) {
        boolElement = newAccountsDom.createElement( "attribute" );
        boolElement.setAttribute( "name", "categoriesEnabled" );
        attribsElement.appendChild( boolElement );
      }
      if( returnedAccountsList.at( i ).postDateTime ) {
        boolElement = newAccountsDom.createElement( "attribute" );
        boolElement.setAttribute( "name", "postDateTime" );
        attribsElement.appendChild( boolElement );
      }
      if( returnedAccountsList.at( i ).allowComments ) {
        // qDebug() << "comments attribute set";
        boolElement = newAccountsDom.createElement( "attribute" );
        boolElement.setAttribute( "name", "allowComments" );
        attribsElement.appendChild( boolElement );
      }
      if( returnedAccountsList.at( i ).allowTB ) {
        // qDebug() << "TB attribute set";
        boolElement = newAccountsDom.createElement( "attribute" );
        boolElement.setAttribute( "name", "allowTB" );
        attribsElement.appendChild( boolElement );
      }
      if( returnedAccountsList.at( i ).useWordpressAPI ) {
        boolElement = newAccountsDom.createElement( "attribute" );
        boolElement.setAttribute( "name", "useWordpressAPI" );
        attribsElement.appendChild( boolElement );
      }

      if( !attribsElement.isNull() )
        detailElement.appendChild( attribsElement );

      newAccount.appendChild( detailElement );

      // Check if each account is matched from the old list; if it is, copy the blogs list
      for( j = 0; j < accountsList.count(); j++ ) {
        if( accountsList.at( j ).toElement().attribute( "id" ) == returnedAccountsList.at( i ).id ) {
          blogsElement = accountsList.at( j ).toElement().firstChildElement( "blogs" );
          if( !blogsElement.isNull() )
            newAccount.appendChild( newAccountsDom.importNode( blogsElement, true ) );
          break;
        }
      }
      newQTMAccounts.appendChild( newAccount );
    }

    // Now add processing instruction and the whole QTMAccounts element, and replace the old main
    // accounts tree with this one
    newAccountsDom.appendChild( newAccountsDom.createProcessingInstruction( "xml",
                                                                            "version='1.0'" ) );
    newAccountsDom.appendChild( newQTMAccounts );
    accountsDom = newAccountsDom.cloneNode( true ).toDocument();

    cw.cbAccountSelector->clear();
    accountsList = accountsDom.documentElement().elementsByTagName( "account" );
    for( i = 0; i < accountsList.count(); ++i ) {
      currentTitle = decodeXmlEntities( accountsList.at( i ).firstChildElement( "details" )
                                        .firstChildElement( "title" ).text() );
      if( currentTitle.isEmpty() )
        currentTitle = tr( "(Unnamed account)" );
      cw.cbAccountSelector->addItem( currentTitle, accountsList.at( i ).toElement().
                                     attribute( "id" ) );
    }
    // Check if the old current account is in this list; if so, make it current again
    for( i = 0; i < accountsList.count(); ++i ) {
      if( accountsList.at( i ).toElement().attribute( "id" ) == oldCurrentAccountId ) {
        cw.cbAccountSelector->setCurrentIndex( i );
        currentAccountElement = accountsList.at( i ).toElement();
        extractAccountDetails();

        QStringList accountStringNames( accountStrings.keys() );
        Q_FOREACH( QString s, accountStringNames ) {
          *(accountStrings[s]) = currentAccountElement.firstChildElement( "details" )
            .firstChildElement( s ).text();
        }

        // Now check if the current account has any blogs
        if( !currentAccountElement.firstChildElement( "blogs" ).isNull() ) {
          // qDebug() << "blogs found";
          populateBlogList();
        }
        else {
          // qDebug() << "no blogs found";
          refreshBlogList();
        }
        break;
      }
      if( i == accountsList.count()-1 ) {
        //qDebug() << "reached end of account list";
        cw.cbAccountSelector->setCurrentIndex( 0 );
        currentAccountElement = accountsList.at( 0 ).toElement();
        currentAccountId = currentAccountElement.attribute( "id" );
        extractAccountDetails();
        refreshBlogList();
        setNetworkActionsEnabled( true );
      }
    }
    disconnect( cw.cbAccountSelector, SIGNAL( activated( int ) ),
                this, SLOT( changeAccount( int ) ) );
    connect( cw.cbAccountSelector, SIGNAL( activated( int ) ),
             this, SLOT( changeAccount( int ) ) );
    saveAccountsDom();
  }
}

void EditingWindow::getPreferences()
{
  getPreferences( QString() );
}

void EditingWindow::getPreferences( const QString &title )
{
  QSettings settings;
  QPalette palette, widgetPalette;

  PrefsDialog prefsDialog( this );
  if( localStorageDirectory.isEmpty() ) {
#ifdef Q_WS_WIN
    QString lsd = QString( "%1/QTM blog" ).arg( QDir::homePath() )
      .replace( "/", "\\" );
#else
    QString lsd = QString( "%1/qtm-blog" ).arg( QDir::homePath() );
#endif
    prefsDialog.leLocalDir->setText( lsd );
  }
  else
    prefsDialog.leLocalDir->setText( localStorageDirectory );
  prefsDialog.leFileExtn->setText( localStorageFileExtn );
  prefsDialog.chUseNewWindows->setCheckState( useNewWindows ? Qt::Checked :
                                              Qt::Unchecked );
  prefsDialog.cbPostAsSave->setCheckState( postAsSave ? Qt::Checked :
                                           Qt::Unchecked );
  prefsDialog.cbAllowComments->setCheckState( allowComments ? Qt::Checked :
                                              Qt::Unchecked );
  prefsDialog.cbAllowTB->setCheckState( allowTB ? Qt::Checked :
                                        Qt::Unchecked );
#if defined USE_SYSTRAYICON && QT_VERSION >= 0x040200
  prefsDialog.chCopyTitle->setCheckState( copyTitle ? Qt::Checked : Qt::Unchecked );
#else
#if QT_VERSION >= 0x040200
  prefsDialog.chCopyTitle->setVisible( false );
#endif
#endif
  prefsDialog.chUseMarkdown->setCheckState( useMarkdown ? Qt::Checked : Qt::Unchecked );
  prefsDialog.lePerlPath->setText( perlPath );
  prefsDialog.leMarkdownPath->setText( markdownPath );
  prefsDialog.chDoMarkdownWhenPosting->setCheckState( doMarkdownWhenPosting ? Qt::Checked
                                                      : Qt::Unchecked );
  prefsDialog.chStripParaTags->setCheckState( stripParaTags ? Qt::Checked : Qt::Unchecked );
  prefsDialog.chStripParaTags->setEnabled( doMarkdownWhenPosting );
#if QT_VERSION >= 0x040200
  if( !useMarkdown ) {
    prefsDialog.lineBelowFonts->setVisible( false );
    prefsDialog.gbMarkdown->setVisible( false );
  }
#endif

#if QT_VERSION >= 0x040200
  prefsDialog.chAllowRegexSearch->setCheckState( allowRegexSearch ? Qt::Checked : Qt::Unchecked );
#endif
#ifdef Q_WS_MAC
  prefsDialog.setWindowFlags( Qt::Sheet );
#endif

#if QT_VERSION >= 0x040200
  prefsDialog.tabWidget->setTabText( 0, tr( "General" ) );
  prefsDialog.tabWidget->setTabText( 1, tr( "Fonts && Markdown" ) );
  prefsDialog.tabWidget->setCurrentIndex( 0 );

  QFont editorFont = EDITOR->font();
  QFont previewFont = previewWindow->font();
  QFont consoleFont = console->font();
  prefsDialog.fcbComposer->setCurrentFont( editorFont );
  prefsDialog.sbComposer->setValue( editorFont.pointSize() );
  prefsDialog.fcbPreview->setCurrentFont( previewFont );
  prefsDialog.sbPreview->setValue( previewFont.pointSize() );
  prefsDialog.fcbConsole->setCurrentFont( consoleFont );
  prefsDialog.sbConsole->setValue( consoleFont.pointSize() );

  // Set editor colours
  palette = prefsDialog.lEditorExampleText->palette();
  palette.setColor( QPalette::Window, editorBgColor );
  palette.setColor( QPalette::WindowText, editorFgColor );
  prefsDialog.lEditorExampleText->setPalette( palette );

  // Set preview colours
  palette = prefsDialog.lPreviewExampleText->palette();
  palette.setColor( QPalette::Window, previewBgColor );
  palette.setColor( QPalette::WindowText, previewFgColor );
  prefsDialog.lPreviewExampleText->setPalette( palette );

  // Set console colours
  palette = prefsDialog.lConsoleExampleText->palette();
  palette.setColor( QPalette::Window, consoleBgColor );
  palette.setColor( QPalette::WindowText, consoleFgColor );
  prefsDialog.lConsoleExampleText->setPalette( palette );

#ifdef USE_SYSTRAYICON
  prefsDialog.cbSTI2ClickFunction->setCurrentIndex( STI2ClickFunction );
#else
  prefsDialog.cbSTI2ClickFunction->hide();
  prefsDialog.label_10->hide();
#endif
#endif
  prefsDialog.resize( QSize( prefsDialog.width(),
                             prefsDialog.minimumHeight() ) );
  if( !title.isEmpty() )
    prefsDialog.setWindowTitle( title );

  // Disable cbStripParaTags as this feature is not properly implemented
  prefsDialog.chStripParaTags->setVisible( false );

  if( prefsDialog.exec() ) {
#ifndef NO_DEBUG_OUTPUT
    // qDebug( "Setting account variables" );
#endif
    localStorageDirectory = prefsDialog.leLocalDir->text();
    localStorageFileExtn = prefsDialog.leFileExtn->text();
    useNewWindows = prefsDialog.chUseNewWindows->isChecked();
    postAsSave = prefsDialog.cbPostAsSave->isChecked();
    allowComments = prefsDialog.cbAllowComments->isChecked();
    allowTB = prefsDialog.cbAllowTB->isChecked();
#if defined USE_SYSTRAYICON && QT_VERSION >= 0x040200
    copyTitle = prefsDialog.chCopyTitle->isChecked();
#endif
    useMarkdown = prefsDialog.chUseMarkdown->isChecked();
    perlPath = prefsDialog.lePerlPath->text();
    markdownPath = prefsDialog.leMarkdownPath->text();
    doMarkdownWhenPosting = prefsDialog.chDoMarkdownWhenPosting->isChecked();
    stripParaTags = prefsDialog.chStripParaTags->isChecked();
#if QT_VERSION >= 0x040200
    allowRegexSearch = prefsDialog.chAllowRegexSearch->isChecked();
#endif
#if QT_VERSION >= 0x040200
#ifndef NO_DEBUG_OUTPUT
    // qDebug( "setting fonts" );
#endif
    QFont ef = prefsDialog.fcbComposer->currentFont();
    ef.setPointSize( prefsDialog.sbComposer->value() );
    editorFontString = ef.toString();
    EDITOR->setFont( ef );
    QFont pf = prefsDialog.fcbPreview->currentFont();
    pf.setPointSize( prefsDialog.sbPreview->value() );
    previewFontString = pf.toString();
    previewWindow->setFont( pf );
    QFont cf = prefsDialog.fcbConsole->currentFont();
    cf.setPointSize( prefsDialog.sbConsole->value() );
    consoleFontString = cf.toString();
    console->setFont( cf );

    // Set colours
    palette = prefsDialog.lEditorExampleText->palette();
    editorBgColor = palette.color( QPalette::Window );
    editorFgColor = palette.color( QPalette::WindowText );

    palette = prefsDialog.lPreviewExampleText->palette();
    previewBgColor = palette.color( QPalette::Window );
    previewFgColor = palette.color( QPalette::WindowText );

    palette = prefsDialog.lConsoleExampleText->palette();
    consoleBgColor = palette.color( QPalette::Window );
    consoleFgColor = palette.color( QPalette::WindowText );

    setEditorColors();
#endif
#if defined USE_SYSTRAYICON
    STI2ClickFunction = prefsDialog.cbSTI2ClickFunction->currentIndex();
    if( sti ) {
#ifndef NO_DEBUG_OUTPUT
      // qDebug( "setting double click function" );
#endif
      sti->setDoubleClickFunction( STI2ClickFunction );
      sti->setCopyTitle( copyTitle );
    }
#endif

    // Handle local directory settings; a default is used if none is specified
    if( localStorageDirectory.isEmpty() ) {
#ifdef Q_WS_WIN
      localStorageDirectory = PROPERSEPS( QString( "%1/QTM blog" ).arg( QDir::homePath() ) );
#else
      localStorageDirectory = QString( "%1/qtm-blog" ).arg( QDir::homePath() );
#endif
    }
    QDir qd( localStorageDirectory );
    if( !qd.exists() ) {
      addToConsole( tr( "Making directory %1" ).arg( localStorageDirectory ) );
      if( !qd.mkpath( localStorageDirectory ) )
        statusBar()->showMessage( tr( "Could not create QTM directory." ), 2000 );
      if( !noAutoSave )
        saveAccountsDom();
    }


    // Now check to see if this is an old-style Blogger account, which does not
    // support categories.

    if( server.contains( "blogger.com" ) ) {
      // Blogger no longer supports this API, so all these features are redundant.
      statusBar()->showMessage( tr( "Blogger no longer supports QTM or similar clients." ), 2000 );
      server = "";
      location = "";
    } else
      cw.categoryPage->setEnabled( true );

    handleEnableCategories();

#if QT_VERSION >= 0x040200
    searchWidget->setExpertEnabled( allowRegexSearch );
#endif

    settings.setValue( "application/version", QTM_VERSION );
    settings.beginGroup( "account" );
    settings.setValue( "localStorageDirectory",
                       localStorageDirectory.replace( "~", QDir::homePath() ) );
    settings.setValue( "localStorageFileExtn", localStorageFileExtn );
    settings.setValue( "useNewWindows", useNewWindows );
    settings.setValue( "postAsSave", postAsSave );
    settings.setValue( "allowComments", allowComments );
    settings.setValue( "allowTB", allowTB );
#if defined USE_SYSTRAYICON && QT_VERSION >= 0x040200
    settings.setValue( "copyTitle", copyTitle );
#endif
    settings.setValue( "useMarkdown", useMarkdown );
    settings.setValue( "perlPath", perlPath );
    settings.setValue( "markdownPath", markdownPath );
    settings.setValue( "doMarkdownWhenPosting", doMarkdownWhenPosting );
    settings.setValue( "stripParaTags", stripParaTags );
#if QT_VERSION >= 0x040200
    settings.setValue( "allowRegexSearch", allowRegexSearch );
#endif
    settings.endGroup();
#if QT_VERSION >= 0x040200
    settings.beginGroup( "fonts" );
    settings.setValue( "editorFontString", editorFontString );
    settings.setValue( "previewFontString", previewFontString );
    settings.setValue( "consoleFontString", consoleFontString );
    settings.setValue( "editorBgColor", editorBgColor.name() );
    settings.setValue( "editorFgColor", editorFgColor.name() );
    settings.setValue( "previewBgColor", previewBgColor.name() );
    settings.setValue( "previewFgColor", previewFgColor.name() );
    settings.setValue( "consoleBgColor", consoleBgColor.name() );
    settings.setValue( "consoleFgColor", consoleFgColor.name() );
    settings.endGroup();
#ifdef USE_SYSTRAYICON
    settings.beginGroup( "sysTrayIcon" );
    settings.setValue( "doubleClickFunction", STI2ClickFunction );
    settings.endGroup();
#endif
#endif
  }
}

void EditingWindow::saveAccountsDom()
{
  QFile domOut( PROPERSEPS( QString( "%1/qtmaccounts2.xml" ).arg( localStorageDirectory ) ) );
  if( domOut.open( QIODevice::WriteOnly ) ) {
    QTextStream domFileStream( &domOut );
    accountsDom.save( domFileStream, 2 );
    domOut.close();
  }
  else {
    QDir dir( localStorageDirectory );
    if( !dir.exists() ) {
      if( QMessageBox::question( 0, tr( "Cannot find storage directory" ),
                                 tr( "QTM cannot find the directory you specified to "
                                     "store your account data and files.\n\n"
                                     "Create it?" ),
                                 QMessageBox::Yes | QMessageBox::Default,
                                 QMessageBox::No ) == QMessageBox::Yes ) {
        if( dir.mkpath( localStorageDirectory ) ) {
          domOut.setFileName( PROPERSEPS( QString( "%1/qtmaccounts2.xml" ).arg( localStorageDirectory ) ) );
          if( domOut.open( QIODevice::WriteOnly ) ) {
            QTextStream dfs( &domOut );
            accountsDom.save( dfs, 2 );
            domOut.close();
          }
          else
            statusBar()->showMessage( tr( "Could not write to accounts file." ), 2000 );
        }
        else
          statusBar()->showMessage( tr( "Could not create the directory." ), 2000 );
      }
    }
  }
}

void EditingWindow::populateAccountList() // slot
{
  int i;
  QDomElement ct, detail;
  QString cid, cname;

  QDomNodeList accountNodeList = accountsDom.documentElement().elementsByTagName( "account" );
  int a = accountNodeList.count();

  if( a ) {
    // qDebug () << "populating:" << a << "accounts";
    cw.cbAccountSelector->clear();

    for( i = 0; i < a; i++ ) {
      cid = accountNodeList.at( i ).toElement().attribute( "id" );
      if( cid.isEmpty() )
        cid = QString( "nameless_%1" ).arg( i + 1 );
      detail = accountNodeList.at( i ).firstChildElement( "details" );
      if( !detail.isNull() ) {
        cname = detail.firstChildElement( "title" ).text();
        if( cname.isEmpty() )
          cname = tr( "Unnamed account %1" ).arg( i + 1 );
        cw.cbAccountSelector->addItem( decodeXmlEntities( cname ), cid );
      }
    }

  }
}

void EditingWindow::populateBlogList() // slot
{
  addToConsole( accountsDom.toString( 2 ) );

  QDomNodeList blogNodeList = currentAccountElement.firstChildElement( "blogs" )
    .elementsByTagName( "blog" );
  QDomNodeList catNodeList, tagNodeList;
  QDomElement catsElement, tagsElement;
  QDomElement ct;
  QString thisTagString;
  int a = blogNodeList.count();
#ifndef NO_DEBUG_OUTPUT
  // qDebug() << "Blogs: " << a;
#endif
  int b, i, j;
  QString catName;

  if( a ) {
    cw.cbBlogSelector->clear();
    for( i = 0; i < a; i++ ) {
      ct = blogNodeList.at( i ).firstChildElement( "blogName" );
      cw.cbBlogSelector->addItem( decodeXmlEntities( blogNodeList.at( i ).firstChildElement( "blogName" ).text() ),
                                  QVariant( blogNodeList.at( i ).firstChildElement( "blogid" ).text() ));
      currentBlog = i;
      currentBlogElement = currentAccountElement.firstChildElement( "blogs" )
        .elementsByTagName( "blog" ).at( currentBlog ).toElement();
      currentBlogid = currentBlogElement.firstChildElement( "blogid" ).text();
    }

    currentBlog = cw.cbBlogSelector->currentIndex();

    catsElement = blogNodeList.at( currentBlog ).firstChildElement( "categories" );
    if( !catsElement.isNull() ) {
      catNodeList = catsElement.elementsByTagName( "category" );
      b = catNodeList.count();
      if( b ) {
        cw.cbMainCat->clear();
        cw.lwOtherCats->clear();
        for( j = 0; j < b; j++ ) {
          catName = decodeXmlEntities( catNodeList.at( j ).firstChildElement( "categoryName" ).text() );
          cw.cbMainCat->addItem( catName, QVariant( catNodeList.at( j ).firstChildElement( "categoryId" ).text() ) );
          cw.lwOtherCats->addItem( catName );
        }
      }
      else {
        cw.chNoCats->setEnabled( false );
        cw.cbMainCat->setEnabled( false );
        cw.lwOtherCats->setEnabled( false );
      }


    }
    
    cw.lwAvailKeywordTags->clear();
    cw.lwKeywordTags->clear();
    if( useWordpressAPI ) {
      cw.lwAvailKeywordTags->setVisible( true );
      cw.tbSelectKeywordTag->setVisible( true );
      cw.tbRemoveKeywordTag->setVisible( true );
      cw.pbRefreshKeywordTags->setVisible( true );
      tagsElement = blogNodeList.at( currentBlog ).firstChildElement( "wpTags" );
      if( !tagsElement.isNull() ) {
        QStringList tagList;
        tagNodeList = tagsElement.elementsByTagName( "tag" );
        //qDebug() << "Tag nodes:" << tagNodeList.count();
        b = tagNodeList.count();
        for( j = 0; j < b; j++ ) {
          thisTagString = tagNodeList.at( j ).toElement().text();
          if( !tagList.contains( thisTagString ) )
            tagList += thisTagString;
        }
        // qDebug() << "Tags:" << tagList.count();
        cw.lwAvailKeywordTags->addItems( tagList );
      }
    }
    else {
      cw.lwAvailKeywordTags->setVisible( false );
      cw.tbSelectKeywordTag->setVisible( false );
      cw.tbRemoveKeywordTag->setVisible( false );
      cw.pbRefreshKeywordTags->setVisible( false );
    }

    disconnect( cw.cbBlogSelector, SIGNAL( activated( int ) ),
                this, SLOT( changeBlog( int ) ) );
    connect( cw.cbBlogSelector, SIGNAL( activated( int ) ),
             this, SLOT( changeBlog( int ) ) );
  }
  else {
    cw.cbBlogSelector->setEnabled( false );
    cw.chNoCats->setEnabled( false );
    cw.cbMainCat->setEnabled( false );
    cw.lwOtherCats->setEnabled( false );
  }
}

void EditingWindow::refreshBlogList() // slot
{
  QDomDocument doc;
  QDomElement methodCall = doc.createElement( "methodCall" );
  methodCall.appendChild( XmlMethodName( doc, "blogger.getUsersBlogs" ) );

  QDomElement params = doc.createElement( "params" );
  params.appendChild( XmlValue( doc, "string", "xxx" ) );
  params.appendChild( XmlValue( doc, "string", login ) );
  params.appendChild( XmlValue( doc, "string", password ) );
  methodCall.appendChild( params );

  doc.appendChild( methodCall );
  doc.insertBefore( doc.createProcessingInstruction( "xml",
                                                     "version=\"1.0\" encoding=\"UTF-8\"" ),
                    doc.firstChild() );

  responseData = "";
  QByteArray requestArray( doc.toByteArray( 2 ) );
  QHttpRequestHeader header( "POST", location );
  header.setValue( "Host", server );
  header.setValue( "User-Agent", userAgentString );
  setHost( http, server, port, useHTTPS ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp );
  http->request( header, requestArray );

  addToConsole( header.toString() );
  addToConsole( doc.toString() );

  if( QApplication::overrideCursor() == 0 )
    QApplication::setOverrideCursor( QCursor( Qt::BusyCursor ) );

  currentHttpBusiness = _blogger_getUsersBlogs;

  connect( http, SIGNAL( done( bool ) ),
           this, SLOT( handleDone( bool ) ) );
  connect( http, SIGNAL( readyRead( const QHttpResponseHeader & ) ),
           this, SLOT( handleResponseHeader( const QHttpResponseHeader & ) ) );
#ifndef DONT_USE_SSL
  connect( http, SIGNAL( sslErrors( const QList<QSslError> & ) ),
           this, SLOT( handleSSLErrors( const QList<QSslError> & ) ) );
#endif
#ifdef USE_SAFEHTTP
  connect( http, SIGNAL( hostLookupFailed() ),
           this, SLOT( handleHostLookupFailed() ) );
#endif
}

void EditingWindow::setHost( QHttp *h, QString &serv, QString &pt, bool cm )
{
  int p;
  bool ok;

  p = pt.toInt( &ok );
#ifdef DONT_USE_SSL
  if( !ok )
    p = 80;
  h->setHost( serv, QHttp::ConnectionModeHttp, p );
#else
  if( !ok )
    p = 0;
  h->setHost( serv, useHTTPS ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp, p );
#endif
}
  
void EditingWindow::handleResponseHeader( const QHttpResponseHeader &header ) // slot
{
  if( header.statusCode() == 404 ) {
    QMessageBox::warning( this, tr( "Error 404" ),
                          tr( "There is no web service at the location you\n"
                              "specified.  Please change it in the Preferences\n"
                              "window." ) );
    http->disconnect();
    http->abort();
    setNetworkActionsEnabled( false );
  }
  else
    responseData.append( http->readAll() );
}

void EditingWindow::stopThisJob()
{
#ifndef NO_DEBUG_OUTPUT
  // qDebug() << "Aborting.";
#endif

  http->disconnect();
  http->abort();

  currentHttpBusiness = None;
  disconnect( this, SIGNAL( httpBusinessFinished() ), 0, 0 );
  if( QApplication::overrideCursor() != 0 )
    QApplication::restoreOverrideCursor();
}

void EditingWindow::handleDone( bool error ) // slot
{
  if( error )
    statusBar()->showMessage( tr( "The request failed." ), 2000 );
  else
    statusBar()->showMessage( QString( tr( "The request succeeded; %1 bytes received" ) )
                              .arg( responseData.size() ), 2000 );

  switch( currentHttpBusiness ) {
    case _blogger_getUsersBlogs:      blogger_getUsersBlogs( responseData ); break;
    case _metaWeblog_newPost:         metaWeblog_newPost( responseData ); break;
    case _metaWeblog_editPost:        metaWeblog_editPost( responseData ); break;
    case _metaWeblog_newMediaObject:  metaWeblog_newMediaObject( responseData ); break;
    case _mt_publishPost:             mt_publishPost( responseData ); break;
    case _mt_getCategoryList:         mt_getCategoryList( responseData ); break;
    case _mt_setPostCategories:       mt_setPostCategories( responseData ); break;
    case _wp_getTags:                 wp_getTags( responseData ); break;
    case _wp_newCategory:             wp_newCategory( responseData ); break;  
  }

  http->disconnect();
  progressBar->setValue( progressBar->value() + 1 );
  currentHttpBusiness = None;
  emit httpBusinessFinished();
}

#ifndef DONT_USE_SSL
void EditingWindow::handleSSLErrors( const QList<QSslError> &errorList )
{
  int i = errorList.count();

  if( i )
    statusBar()->showMessage( tr( "%1 SSL errors" ).arg( i ), 2000 );
}
#endif

void EditingWindow::changeCurrentBlog( int b ) // slot
{
  currentBlog = b;
}

void EditingWindow::changeAccount( int a ) // slot
{
  QString currentBlogText;

  if( currentAccount != a ) {
    currentAccount = a;
    cw.cbBlogSelector->clear();
    cw.cbMainCat->clear();
    cw.lwOtherCats->clear();
    cw.lwAvailKeywordTags->clear();
    cw.lwKeywordTags->clear();

    currentAccountElement = accountsDom.documentElement()
      .elementsByTagName( "account" ).at( a ).toElement();
    currentAccountId = currentAccountElement.toElement().attribute( "id" );
    extractAccountDetails();
    /*qDebug() << "Current account: " << currentAccountElement.firstChildElement( "details" )
      .firstChildElement( "title" ).text();
*/
    QStringList accountStringNames( accountStrings.keys() );
    Q_FOREACH( QString s, accountStringNames )
      *(accountStrings[s]) = currentAccountElement.firstChildElement( "details" )
      .firstChildElement( s ).text();

    extractAccountAttributes();

    QDomElement blogsElement = currentAccountElement.firstChildElement( "blogs" );
    if( !blogsElement.isNull() ) {
      QDomNodeList blogsList = blogsElement.elementsByTagName( "blog" );
      int b = blogsList.count();
      if( b ) {
        // qDebug() << "Blogs: " << b;
        cw.cbBlogSelector->clear();
        for( int i = 0; i < b; i++ )
          cw.cbBlogSelector->addItem( decodeXmlEntities( blogsList.at( i ).firstChildElement( "blogName" ).text() ),
                                      blogsList.at( i ).firstChildElement( "blogid" ).text() );
        cw.cbBlogSelector->setEnabled( true );
        changeBlog( 0, true );
        currentBlogid = cw.cbBlogSelector->itemData( 0 ).toString();
        cw.cbBlogSelector->disconnect( this, SLOT( changeBlog( int ) ) ); // eliminate duplicate connections
        connect( cw.cbBlogSelector, SIGNAL( activated( int ) ),
                 this, SLOT( changeBlog( int ) ) );
        emit blogRefreshFinished();
        if( QApplication::overrideCursor() != 0 )
          QApplication::restoreOverrideCursor();
      }
      else
        refreshBlogList();
    }
    else
      refreshBlogList();
  }
}

void EditingWindow::extractAccountDetails() // slot
{
  QDomElement caDetails = currentAccountElement.firstChildElement( "details" ).toElement();
  server = caDetails.firstChildElement( "server" ).text();
  location = caDetails.firstChildElement( "location" ).text();
  port = caDetails.firstChildElement( "port" ).text();
  login = caDetails.firstChildElement( "login" ).text();
  password = caDetails.firstChildElement( "password" ).text();
  currentAccountId = currentAccountElement.attribute( "id" );

  extractAccountAttributes();
}

void EditingWindow::extractAccountAttributes()
{
  QStringList accountAttribNames( accountAttributes.keys() );
  QString attribName;
  QDomNodeList attribNodes = currentAccountElement.firstChildElement( "details" )
                             .elementsByTagName( "attribute" );

  Q_FOREACH( QString t, accountAttribNames ) {
    *(accountAttributes[t]) = false;
    for( int i = 0; i < attribNodes.count(); i++ ) {
      attribName = attribNodes.at( i ).toElement().attribute( "name" );

      if( attribName == "comments" )
        attribName = "allowComments";
      if( attribName == "trackback" )
        attribName = "allowTB";     

      if( attribName == t )
        *(accountAttributes[t]) = true;
    }
  }

  cw.chAllowComments->setCheckState( allowComments ? Qt::Checked : Qt::Unchecked );
  cw.chAllowTB->setCheckState( allowTB ? Qt::Checked : Qt::Unchecked );
  cw.pbAddCategory->setEnabled( useWordpressAPI );
  ui.action_Add_category->setEnabled( useWordpressAPI );
}


void EditingWindow::changeBlog( int b, bool fromChangeAccount ) // slot
{
  QString currentCategoryText;
  QDomElement tagsElement;
  QDomNodeList tagsList;
  int i;
  //qDebug() << "Starting changeblog" << b;

  if( currentBlog != b || fromChangeAccount ) {
    //qDebug() << "changing the blog anyway";
    currentBlog = b;
    cw.cbMainCat->clear();
    cw.lwOtherCats->clear();
    cw.lwAvailKeywordTags->clear();
    cw.lwKeywordTags->clear();

    currentBlogElement = currentAccountElement.elementsByTagName( "blog" ).at( currentBlog ).toElement();
    currentBlogid = currentBlogElement.firstChildElement( "blogid" ).text();
    // qDebug() << currentBlogid;

    if( useWordpressAPI ) {
      cw.lwAvailKeywordTags->setVisible( true );
      cw.tbSelectKeywordTag->setVisible( true );
      cw.tbRemoveKeywordTag->setVisible( true );
      cw.pbRefreshKeywordTags->setVisible( true );
      tagsElement = currentBlogElement.firstChildElement( "wpTags" );
      tagsList = tagsElement.elementsByTagName( "tag" );
      if( tagsList.count() ) {
        for( i = 0; i < tagsList.count(); i++ ) {
          cw.lwAvailKeywordTags->addItem( tagsList.at( i ).toElement().text() );
        }
      }
    }
    else {
      cw.lwAvailKeywordTags->setVisible( false );
      cw.tbSelectKeywordTag->setVisible( false );
      cw.tbRemoveKeywordTag->setVisible( false );
      cw.pbRefreshKeywordTags->setVisible( false );
    }

    QDomElement catsElement = currentBlogElement.firstChildElement( "categories" );
    if( !catsElement.isNull() ) {
      QDomNodeList catsList = catsElement.elementsByTagName( "category" );
      int c = catsList.count();
      if( c ) {
//#ifndef NO_DEBUG_OUTPUT
        // qDebug() << "Categories: " << c;
//#endif
        cw.cbMainCat->clear();
        cw.lwOtherCats->clear();
        for( i = 0; i < c; i++ ) {
          currentCategoryText = decodeXmlEntities( catsList.at( i ).firstChildElement( "categoryName" ).text() );
          cw.cbMainCat->addItem( currentCategoryText,
                                 QVariant( catsList.at( i ).firstChildElement( "categoryId" ).text() ) );
          cw.lwOtherCats->addItem( currentCategoryText );
          cw.chNoCats->setEnabled( true );
          cw.cbMainCat->setEnabled( true );
          cw.lwOtherCats->setEnabled( true );
          statusBar()->clearMessage(); // as otherwise, "there are no categories" would still show
        }
        emit categoryRefreshFinished();
        if( QApplication::overrideCursor() != 0 )
          QApplication::restoreOverrideCursor();
      }
      else
        callRefreshCategories();
    }
    else
      callRefreshCategories();
  }
}

bool EditingWindow::caseInsensitiveLessThan( const QString &s1, const QString &s2 )
{
  return s1.toLower() < s2.toLower();
}

void EditingWindow::mt_setPostCategories( QByteArray response )
{
  disconnect( this, SIGNAL( httpBusinessFinished() ), 0, 0 );

  QXmlInputSource xis;
  QXmlSimpleReader reader;
  XmlRpcHandler handler( currentHttpBusiness );
  QList<QString> parsedData;
  QString rdata( response );

  if( rdata.contains( "<fault>" ) ) {
    statusBar()->showMessage( tr( "Categories not set successfully; see console." ), 2000 );
    QTimer::singleShot( 1000, this, SLOT( hideProgressBar() ) );
  }
  else {
    statusBar()->showMessage( tr( "Categories set successfully." ), 2000 );

    if( location.contains( "mt-xmlrpc.cgi" ) && cw.cbStatus->currentIndex() == 1 )
      connect( this, SIGNAL( httpBusinessFinished() ),
               this, SLOT( publishPost() ) );
  }
  addToConsole( rdata );
  QApplication::restoreOverrideCursor();
}

void EditingWindow::handleConsole( bool isChecked )
{
  if( !isChecked ) {
    ui.actionP_review->setEnabled( true );
    mainStack->setCurrentIndex( previousRaisedLSWidget );
    searchWidget->setTextEdit( EDITOR );
    ui.action_View_Console->setText( tr( "&Console" ) );
    ui.action_View_Console->setIconText( tr( "Console" ) );
    ui.action_View_Console->setToolTip( tr( "Console" ) );
  }
  else {
    ui.actionP_review->setEnabled( false );
    previousRaisedLSWidget = mainStack->currentIndex();
    mainStack->setCurrentIndex( consoleID );
    searchWidget->setTextEdit( console );
    ui.action_View_Console->setText( tr( "Exit &console" ) );
    ui.action_View_Console->setIconText( tr( "Exit console" ) );
    ui.action_View_Console->setToolTip( tr( "Exit console" ) );
  }
}

void EditingWindow::makeBold()
{
  EDITOR->insertPlainText( QString( "<strong>%1</strong>" ).arg( EDITOR->textCursor().selectedText() ) );
}

void EditingWindow::makeItalic()
{
  EDITOR->insertPlainText( QString( "<em>%1</em>" ).arg( EDITOR->textCursor().selectedText() ) );
}

void EditingWindow::makeUnderline()
{
  EDITOR->insertPlainText( QString( "<u>%1</u>" ).arg( EDITOR->textCursor().selectedText() ) );
}

void EditingWindow::insertMore()
{
  if( !EDITOR->toPlainText().contains( "<!--more-->" ) )
    EDITOR->insertPlainText( "<!--more-->" );
  else
    statusBar()->showMessage( tr( "A 'more' tag already exists." ), 2000 );
}

void EditingWindow::makeBlockquote()
{
  EDITOR->insertPlainText( QString( "<blockquote>%1</blockquote>" )
                           .arg( EDITOR->textCursor().selectedText() ) );
}

void EditingWindow::makePara()
{
  EDITOR->insertPlainText( QString( "<p>%1</p>" ).arg( EDITOR->textCursor().selectedText() ) );
}

void EditingWindow::insertLink( bool isAutoLink )
{
  QString linkString, titleString;
  QString insertionString = "";
  QString selectedString = EDITOR->textCursor().selectedText();
  QString selectedStringLC;
  QDialog linkEntry( this );
  Ui::LinkEntry leui;
#ifdef Q_WS_MAC
  linkEntry.setWindowFlags( Qt::Sheet );
#endif
  leui.setupUi( &linkEntry );
  if( isAutoLink )
    leui.cbMakeAutoLink->setChecked( Qt::Checked );
  if( !selectedString.isEmpty() )
    leui.leLinkText->setText( selectedString );

  if( linkEntry.exec() ) {
    linkString = leui.leLinkURL->text();
    insertionString += QString( "<a href=\"%1\"" ).arg( linkString );
    if( leui.leLinkTitle->text().size() ) {
      titleString = leui.leLinkTitle->text();
      insertionString += QString( " title=\"%1\"" ).arg( titleString );
    }
    if( leui.chLinkTarget->isChecked() ) {
      switch( leui.cbLinkTarget->currentIndex() ) {
        case 0: insertionString += QString( " target=\"_top\"" );   break;
        case 1: insertionString += QString( " target=\"_blank\"" ); break;
        case 2: insertionString += QString( " target=\"view_window\"" ); break;
      }
    }
    insertionString += ">";
    EDITOR->insertPlainText( QString( "%1%2</a>" )
                             .arg( insertionString )
                             .arg( leui.leLinkText->text() ) );
  }
  if( leui.cbMakeAutoLink->isChecked() ) {
    selectedStringLC = selectedString.toLower().trimmed();
    autoLinkDictionary.insert( selectedStringLC, linkString );
    autoLinkTitleDictionary.insert( selectedStringLC, titleString );
    if( leui.chLinkTarget->isChecked() )
      autoLinkTargetDictionary.insert( selectedStringLC, leui.cbLinkTarget->currentIndex() );
    else
      autoLinkTargetDictionary.remove( selectedStringLC );
    saveAutoLinkDictionary();
  }
}

void EditingWindow::insertLinkFromClipboard()
{
  QString linkString( QApplication::clipboard()->text() );
  EDITOR->insertPlainText( QString( "<a href=\"%1\">%2</a>" )
                           .arg( linkString )
                           .arg( EDITOR->textCursor().selectedText() ) );
}

void EditingWindow::insertSelfLink()
{
  QString linkString( EDITOR->textCursor().selectedText() );

  if( QUrl( linkString, QUrl::StrictMode ).isValid() )
    EDITOR->insertPlainText( QString( "<a href=\"%1\">%1</a>" ).arg( linkString ) );
  else
    statusBar()->showMessage( tr( "The selection is not a valid URL." ), 2000 );
}

void EditingWindow::insertAutoLink()
{
  QString selectedText = EDITOR->textCursor().selectedText();
  QString selectedTextLC = selectedText.toLower().trimmed();
  QString titleString, targetString;
  QList<QString> targets;
  targets << "_top" << "_blank" << "view_window";

  if( autoLinkDictionary.contains( selectedTextLC ) ) {
    titleString = QString( " title=\"%1\"" )
      .arg( autoLinkTitleDictionary.value( selectedTextLC ) );
    if( autoLinkTargetDictionary.contains( selectedTextLC ) )
      targetString = QString( " target=\"%1\"" )
        .arg( targets.value( autoLinkTargetDictionary.value( selectedTextLC ) ) );

    EDITOR->insertPlainText( QString( "<a href=\"%1\"%2%3>%4</a>" )
                             .arg( autoLinkDictionary.value( selectedTextLC ) )
                             .arg( titleString )
                             .arg( targetString )
                             .arg( selectedText ) );
  }
  else
    insertLink( true );
}

void EditingWindow::insertImage()
{
  QString insertionString;
  QDialog image_entry( this );
  Ui::ImageEntry ieui;
#ifdef Q_WS_MAC
  image_entry.setWindowFlags( Qt::Sheet );
#endif
  ieui.setupUi( &image_entry );
  if( image_entry.exec() ) {
    insertionString = QString( "<img src=\"%1\"" )
      .arg( ieui.leImageURL->text() );
    if( ieui.leAltText->text().size() )
      insertionString += QString( " alt=\"%1\"" )
        .arg( ieui.leAltText->text() );
    if( ieui.chAlign->isChecked() ) {
      if( ieui.cbAlign->currentIndex() )
        insertionString += " align=\"right\"";
      else
        insertionString += " align=\"left\"";
    }
    insertionString += ">";
    EDITOR->insertPlainText( insertionString );
  }
}

void EditingWindow::insertImageFromClipboard()
{
  QString linkString( QApplication::clipboard()->text() );
  EDITOR->insertPlainText( QString( "<img src=\"%1\">%2</img>" )
                           .arg( linkString )
                           .arg( EDITOR->textCursor().selectedText() ) );
}

void EditingWindow::cut()
{
  EDITOR->cut();
}

void EditingWindow::copy()
{
  EDITOR->copy();
}

void EditingWindow::paste()
{
  EDITOR->paste();
}

void EditingWindow::tidyPaste()
{
  QString pastedText = QApplication::clipboard()->text();
  pastedText.replace( QRegExp( " {2,}" ), " " );
  pastedText.replace( QRegExp( " *\n{1} *" ), " " );
  EDITOR->insertPlainText( pastedText );
}

void EditingWindow::undo()
{
  EDITOR->document()->undo();
}

void EditingWindow::redo()
{
  EDITOR->document()->redo();
}

void EditingWindow::makeUnorderedList()
{
  QString listString = EDITOR->textCursor().selection().toPlainText();

  if( !listString.isEmpty() )
    EDITOR->insertPlainText( getHTMLList( QString( "ul" ), listString ) );
}

void EditingWindow::makeOrderedList()
{
  QString listString = EDITOR->textCursor().selection().toPlainText();

  if( !listString.isEmpty() )
    EDITOR->insertPlainText( getHTMLList( QString( "ol" ), listString ) );
}

QString & EditingWindow::getHTMLList( QString tag, QString & text )
{
  QString return_value, workstring;
  QStringList worklist;

  worklist = text.split( "\n" );
  for( int a = 0; a < worklist.count(); a++ ) {
    worklist[a].prepend( "<li>" );
    worklist[a].append( "</li>" );
  }
  text = worklist.join( "\n" );
  text.prepend( QString( "<%1>" ).arg( tag ) );
  text.append( QString( "</%1>" ).arg( tag ) );

  return text;
}

void EditingWindow::pasteAsMarkedParagraphs()
{
  QString insertion = QApplication::clipboard()->text().trimmed();

  if( !insertion.isEmpty() ) {
    insertion.replace( QRegExp( "\n+" ), "</p>\n<p>" );
    insertion.prepend( "<p>" );
    insertion.append( "</p>" );
    EDITOR->insertPlainText( insertion );
  }
}

void EditingWindow::pasteAsBlockquote()
{
  QString insertion = QApplication::clipboard()->text().trimmed();

  if( !insertion.isEmpty() ) {
    insertion.replace( QRegExp( "\n{1,2}" ), "\n\n" );
    EDITOR->insertPlainText( QString( "<blockquote>%1</blockquote>" )
                             .arg( insertion ) );
  }
}

void EditingWindow::pasteAsMarkdownBlockquote()
{
  QString insertion = QApplication::clipboard()->text().trimmed();
  QString separator = "\n>\n";

  if( !insertion.isEmpty() ) {
    insertion.prepend( ">" );
    insertion.replace( "\n", "\n>" );
    EDITOR->insertPlainText( insertion );
  }
}

void EditingWindow::pasteAsUnorderedList()
{
  QString insertion = QApplication::clipboard()->text().trimmed()
    .replace( QRegExp( "\n{2,}" ), "\n" );

  if( !insertion.isEmpty() )
    EDITOR->insertPlainText( getHTMLList( QString( "ul" ), insertion ) );
}

void EditingWindow::pasteAsOrderedList()
{
  QString insertion = QApplication::clipboard()->text().trimmed()
    .replace( QRegExp( "\n{2,}" ), "\n" );

  if( !insertion.isEmpty() )
    EDITOR->insertPlainText( getHTMLList( QString( "ol" ), insertion ) );
}

void EditingWindow::doPreview( bool isChecked, bool markdownFailed )
{
  QString line, techTagString;
  QString conversionString = "", conversionStringB = "";
  QTextDocument cDoc;
  // bool finished = false;
  bool isPre = false;

  if( isChecked ) {
    if( useMarkdown && !markdownFailed ) {
      conversionStringB = processWithMarkdown( EDITOR->toPlainText() );
      if( conversionStringB.isNull() ) {
        doPreview( isChecked, true );
        return;
      }

        // Now that the process has done its job, we can add the title and display
        // the preview

      conversionStringB.prepend( QString( "<strong>%1</strong>\n\n" )
				 .arg( cw.leTitle->text().size() ?
				       cw.leTitle->text() : "<em>Untitled</em>" ) );
      previewWindow->setHtml( conversionStringB );
      previousRaisedLSWidget = mainStack->currentIndex();
      connect( previewWindow, SIGNAL( highlighted( const QString & ) ),
	       this, SLOT( showHighlightedURL( const QString & ) ) );
      mainStack->setCurrentIndex( previewWindowID );
      searchWidget->setTextEdit( previewWindow );
      ui.actionP_review->setText( tr( "Exit p&review" ) );
      ui.actionP_review->setIconText( tr( "Exit preview" ) );
      ui.actionP_review->setToolTip( tr( "Exit preview" ) );
    }
    else {			// i.e. if not Markdown or Markdown failed
      ui.action_View_Console->setEnabled( false );
      conversionString += QString( "<b>%1</b>\n\n" )
        .arg( cw.leTitle->text().size() ?
              cw.leTitle->text() : "<i>Untitled</i>" );
      conversionString += EDITOR->toPlainText();
      QTextStream a( &conversionString );
      QRegExp re( "^(<table|thead|tfoot|caption|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|select|form|blockquote|address|math|p|h[1-6])>" );
      do {
        line = a.readLine();
        if( !line.isEmpty() ) {
          if( re.exactMatch( line ) )
            conversionStringB += line;
          else {
            if( line.startsWith( "<pre>" ) ) {
              isPre = true;
              conversionStringB += line;
            }
            else {
              conversionStringB += QString( isPre ? "%1\n" : "<p>%1</p>" ).arg( line );

              if( line.contains( "</pre>" ) )
                isPre = false;
            }
          }
        }
      } while( !a.atEnd() );

      previewWindow->setHtml( conversionStringB );
      previousRaisedLSWidget = mainStack->currentIndex();
      connect( previewWindow, SIGNAL( highlighted( const QString & ) ),
               this, SLOT( showHighlightedURL( const QString & ) ) );
      mainStack->setCurrentIndex( previewWindowID );
      searchWidget->setTextEdit( previewWindow );
      ui.actionP_review->setText( tr( "Exit p&review" ) );
      ui.actionP_review->setIconText( tr( "Exit preview" ) );
      ui.actionP_review->setToolTip( tr( "Exit preview" ) );
    }
  } else {			// i.e. if the preview button is being released
    ui.action_View_Console->setEnabled( true );
    mainStack->setCurrentIndex( previousRaisedLSWidget );
    previewWindow->disconnect( SIGNAL( highlighted( const QString & ) ) );
    searchWidget->setTextEdit( EDITOR );
    ui.actionP_review->setText( tr( "Entry in p&review" ) );
    ui.actionP_review->setIconText( tr( "Entry in preview" ) );
    ui.actionP_review->setToolTip( tr( "Entry in preview" ) );
  }
}

void EditingWindow::showHighlightedURL( const QString &highlightedURL )
{
  statusBar()->showMessage( highlightedURL, 2000 );
}

void EditingWindow::newMTPost()
{
  QDomDocument doc;
  QDomElement methodCall, params, param, member, value, integer,
              string, rpcstruct, rpcarray, actualValue;
  QString description, extEntry, techTagString, convertedString, keywordTagList;
  bool takeComms = cw.chAllowComments->isChecked();
  bool takeTB = cw.chAllowTB->isChecked();
  //bool blogidIsInt;
  int count, tags;
  QList<QString> tblist;

  if( !currentHttpBusiness ) {
    if( !entryBlogged ) {

      if( EDITOR->toPlainText().contains( "<!--more-->" ) ) {
        description = QString( EDITOR->toPlainText() )
          .section( "<!--more-->", 0, 0 );
        extEntry = QString( EDITOR->toPlainText() )
          .section( "<!--more-->", -1, -1 );
      } else {
        description = QString( EDITOR->toPlainText() );
        extEntry = "";
      }

      if( doMarkdownWhenPosting ) {
        convertedString = processWithMarkdown( description );
        if( !convertedString.isNull() )
          /* description = stripParaTags ?
             convertedString.remove( "<p>" ).remove( "</p>" ) : convertedString; */
          description = convertedString;
        else
          statusBar()->showMessage( tr( "Markdown conversion failed; posting main entry as is." ), 2000 );
        if( !extEntry.isEmpty() ) {
          convertedString = processWithMarkdown( extEntry );
          if( !convertedString.isNull() )
            /*extEntry = stripParaTags ?
              convertedString.remove( "<p>" ).remove( "</p>" ) : convertedString; */
            extEntry = convertedString;
          else
            statusBar()->showMessage( tr( "Markdown conversion failed; posting extension as is." ), 2000 );
        }
      }

      dateTime = QDateTime::currentDateTime().toString( Qt::ISODate );
      dateTime.remove( QChar( '-' ) );

      if( cw.lwTags->count() ) {
        tags = cw.lwTags->count();
        techTagString = "<p style=\"text-align:right;font-size:10px;\">Technorati Tags: ";
        for( count = 0; count < tags; count++ ) {
          techTagString.append( QString( "<a href=\"http://technorati.com/tag/%1\""
                                         " rel=\"tag\">%2</a>%3" )
                                .arg( cw.lwTags->item( count )->text().replace( ' ', '+' ) )
                                .arg( cw.lwTags->item( count )->text()
                                      .replace( "+", " " ) )
                                .arg( (count == tags-1) ? "</p>\n\n" : ", " ) );
        }

        if( cw.rbStartOfMainEntry->isChecked() )
          description.insert( 0, techTagString );
        else
          description.append( techTagString );
      }

      QString blogid = cw.cbBlogSelector->itemData( cw.cbBlogSelector->currentIndex() ).toString();
/*      QRegExp blogidRegExp( "^[0-9]+$" );
      blogidIsInt = blogidRegExp.exactMatch( blogid ); */

      methodCall = doc.createElement( "methodCall" );
      methodCall.appendChild( XmlMethodName( doc, "metaWeblog.newPost" ) );

      params = doc.createElement( "params" );
      params.appendChild( XmlValue( doc, "string", blogid ) );
      params.appendChild( XmlValue( doc, "string", login ) );
      params.appendChild( XmlValue( doc, "string", password ) );

      param = doc.createElement( "param" );
      value = doc.createElement( "value" );
      rpcstruct = doc.createElement( "struct" );
      rpcstruct.appendChild( XmlMember( doc, "title", "string",
                                        cw.leTitle->text() ) );
      rpcstruct.appendChild( XmlMember( doc, "description", "string", description ) );
      if( postDateTime )
        rpcstruct.appendChild( XmlMember( doc, "dateCreated", "dateTime.iso8601", dateTime ) );
      rpcstruct.appendChild( XmlMember( doc, "mt_allow_comments", "boolean",
                                        takeComms ? "1" : "0" ) );
      rpcstruct.appendChild( XmlMember( doc, "mt_allow_pings", "boolean",
                                        takeTB ? "1" : "0" ) );
      rpcstruct.appendChild( XmlMember( doc, "mt_text_more", "string", extEntry ) );
      if( cw.teExcerpt->toPlainText().length() )
        rpcstruct.appendChild( XmlMember( doc, "mt_excerpt", "string",
                                          cw.teExcerpt->toPlainText().replace( QChar( '&' ), "&amp;" ) ) );
      else
        rpcstruct.appendChild( XmlMember( doc, "mt_excerpt", "string", "" ) );
      if( !cw.lwKeywordTags->count() )
        rpcstruct.appendChild( XmlMember( doc, "mt_keywords", "string", "" ) );
      else {
        for( count = 0; count < cw.lwKeywordTags->count(); count++ ) {
          keywordTagList.append( cw.lwKeywordTags->item( count )->text() );
          if( count != cw.lwKeywordTags->count() - 1 )
            keywordTagList.append( ", " );
        }
        rpcstruct.appendChild( XmlMember( doc, "mt_keywords", "string", keywordTagList ) );
      }

      if( cw.lwTBPings->count() ) {
        for( count = 0; count < cw.lwTBPings->count(); count++ )
          tblist.append( cw.lwTBPings->item( count )->text() );
        rpcstruct.appendChild( XmlRpcArray( doc, "mt_tb_ping_urls", tblist ) );
      }

      value.appendChild( rpcstruct );
      param.appendChild( value );
      params.appendChild( param );
      params.appendChild( XmlValue( doc, "boolean",
                                    cw.cbStatus->currentIndex() ? "1" : "0" ) );
      methodCall.appendChild( params );
      doc.appendChild( methodCall );
      doc.insertBefore( doc.createProcessingInstruction( "xml",
                                                         "version=\"1.0\" encoding=\"UTF-8\"" ),
                        doc.firstChild() );

      QByteArray requestArray( doc.toByteArray() );
      responseData = "";
      QHttpRequestHeader header( "POST", location );
      header.setValue( "Host", server );
      header.setValue( "User-Agent", userAgentString );
      setHost( http, server, port, useHTTPS ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp );
      http->request( header, requestArray );

      addToConsole( header.toString() );
      addToConsole( doc.toString() );

      if( QApplication::overrideCursor() == 0 )
        QApplication::setOverrideCursor( QCursor( Qt::BusyCursor ) );
      if( postAsSave && !entryEverSaved ) {
        cleanSave = true;
        setDirtySignals( true );
      }
      currentHttpBusiness = _metaWeblog_newPost;
      disconnect( this, SIGNAL( httpBusinessFinished() ) );
      connect( http, SIGNAL( done( bool ) ),
               this, SLOT( handleDone( bool ) ) );
      connect( http, SIGNAL( readyRead( const QHttpResponseHeader & ) ),
               this, SLOT( handleResponseHeader( const QHttpResponseHeader & ) ) );
#ifndef DONT_USE_SSL
      connect( http, SIGNAL( sslErrors( const QList<QSslError> & ) ),
               this, SLOT( handleSSLErrors( const QList<QSslError> & ) ) );
#endif
#ifdef USE_SAFEHTTP
      
               this, SLOT( handleHostLookupFailed() ) );
#endif

      if( location.contains( "mt-xmlrpc.cgi" ) && cw.cbStatus->currentIndex() == 1 )
        progressBar->setMaximum( 6 );
      else
        progressBar->setMaximum( 4 );
      progressBar->setValue( 1 );
#ifndef Q_WS_MAC
      progressBarAction->setVisible( true );
#endif
    }
    else
      submitMTEdit();
  }
  else {
#ifdef QTM_DEBUG
      statusBar()->showMessage( tr( "refreshCategories: All HTTP requests are blocked" ),
                                2000 );
#else
      statusBar()->showMessage( tr( "All HTTP requests are blocked." ), 2000 );
#endif
  }
}

void EditingWindow::submitMTEdit()
{
  QDomDocument doc;
  QDomElement methodCall, params, param, value, rpcstruct, rpcarray;
  QString description, extEntry, techTagString, convertedString, keywordTagList;
  int count, tags;
  bool takeComms = cw.chAllowComments->isChecked();
  bool takeTB = cw.chAllowTB->isChecked();
  QList<QString> tblist;

  if( EDITOR->toPlainText().contains( "<!--more-->" ) ) {
    description = QString( EDITOR->toPlainText() )
      .section( "<!--more-->", 0, 0 );
    extEntry = QString( EDITOR->toPlainText() )
      .section( "<!--more-->", -1, -1 );
  } else {
    description = QString( EDITOR->toPlainText() );
    extEntry = "";
  }

  if( doMarkdownWhenPosting ) {
    convertedString = processWithMarkdown( description );
    if( !convertedString.isNull() )
      /* description = stripParaTags ?
        convertedString.remove( "<p>" ).remove( "</p>" ) : convertedString; */
      description = convertedString;
    else
      statusBar()->showMessage( tr( "Markdown conversion failed; posting main entry as is." ), 2000 );
    if( !extEntry.isEmpty() ) {
      convertedString = processWithMarkdown( extEntry );
      if( !convertedString.isNull() )
        /* extEntry = stripParaTags ?
          convertedString.remove( "<p>" ).remove( "</p>" ) : convertedString; */
        extEntry = convertedString;
      else
        statusBar()->showMessage( tr( "Markdown conversion failed; posting extension as is." ), 2000 );
    }
  }

  if( cw.lwTags->count() ) {
    tags = cw.lwTags->count();
    techTagString = "<p style=\"text-align:right;font-size:10px;\">Technorati Tags: ";
    for( count = 0; count < tags; count++ ) {
      techTagString.append( QString( "<a href=\"http://technorati.com/tag/%1\""
                                     " rel=\"tag\">%2</a>%3" )
                            .arg( cw.lwTags->item( count )->text() )
                            .arg( cw.lwTags->item( count )->text()
                                  .replace( "+", " " ) )
                            .arg( (count == tags-1) ? "</p>" : ", " ) );
    }

    if( cw.rbStartOfMainEntry->isChecked() )
      description.insert( 0, techTagString );
    else
      description.append( techTagString );
  }

  methodCall = doc.createElement( "methodCall" );
  methodCall.appendChild( XmlMethodName( doc, "metaWeblog.editPost" ) );

  params = doc.createElement( "params" );
  params.appendChild( XmlValue( doc, "string", entryNumber ) );
  params.appendChild( XmlValue( doc, "string", login ) );
  params.appendChild( XmlValue( doc, "string", password ) );

  param = doc.createElement( "param" );
  value = doc.createElement( "value" );
  rpcstruct = doc.createElement( "struct" );
  rpcstruct.appendChild( XmlMember( doc, "title", "string",
                                    cw.leTitle->text() ) );
  rpcstruct.appendChild( XmlMember( doc, "description", "string", description ) );
  rpcstruct.appendChild( XmlMember( doc, "dateCreated", "dateTime.iso8601", dateTime ) );
  rpcstruct.appendChild( XmlMember( doc, "mt_allow_comments", "boolean",
                                    takeComms ? "1" : "0" ) );
  rpcstruct.appendChild( XmlMember( doc, "mt_allow_pings", "boolean",
                                    takeTB ? "1" : "0" ) );
  rpcstruct.appendChild( XmlMember( doc, "mt_text_more", "string", extEntry ) );

  if( cw.teExcerpt->toPlainText().length() )
    rpcstruct.appendChild( XmlMember( doc, "mt_excerpt", "string",
                                      cw.teExcerpt->toPlainText().replace( QChar( '&' ), "&amp;" ) ) );
  else
    rpcstruct.appendChild( XmlMember( doc, "mt_excerpt", "string", "" ) );

  if( !cw.lwKeywordTags->count() )
    rpcstruct.appendChild( XmlMember( doc, "mt_keywords", "string", "" ) );
  else {
    for( count = 0; count < cw.lwKeywordTags->count(); count++ ) {
      keywordTagList.append( cw.lwKeywordTags->item( count )->text() );
      if( count != cw.lwKeywordTags->count() - 1 )
        keywordTagList.append( ", " );
    }
    rpcstruct.appendChild( XmlMember( doc, "mt_keywords", "string", keywordTagList ) );
  }

  if( cw.lwTBPings->count() ) {
    for( count = 0; count < cw.lwTBPings->count(); count++ )
      tblist.append( cw.lwTBPings->item( count )->text() );
    rpcstruct.appendChild( XmlRpcArray( doc, "mt_tb_ping_urls", tblist ) );
  }

  value.appendChild( rpcstruct );
  param.appendChild( value );
  params.appendChild( param );
  params.appendChild( XmlValue( doc, "boolean",
                                cw.cbStatus->currentIndex() ? "1" : "0" ) );
  methodCall.appendChild( params );
  doc.appendChild( methodCall );
  doc.insertBefore( doc.createProcessingInstruction( "xml",
                                                     "version=\"1.0\" encoding=\"UTF-8\"" ),
                    doc.firstChild() );

  QByteArray requestArray( doc.toByteArray() );
  responseData = "";
  QHttpRequestHeader header( "POST", location );
  header.setValue( "Host", server );
  header.setValue( "User-Agent", userAgentString );
  setHost( http, server, port, useHTTPS ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp );
  http->request( header, requestArray );

  addToConsole( header.toString() );
  addToConsole( doc.toString() );

  if( QApplication::overrideCursor() == 0 )
    QApplication::setOverrideCursor( QCursor( Qt::BusyCursor ) );
  if( postAsSave && !entryEverSaved ) {
    cleanSave = true;
    setDirtySignals( true );
  }

  if( location.contains( "mt-xmlrpc.cgi" ) && cw.cbStatus->currentIndex() == 1 )
    progressBar->setMaximum( 6 );
  else
    progressBar->setMaximum( 4 );
  progressBar->setValue( 1 );
#ifndef Q_WS_MAC
  progressBarAction->setVisible( true );
#endif

  currentHttpBusiness = _metaWeblog_editPost;
  connect( http, SIGNAL( done( bool ) ),
           this, SLOT( handleDone( bool ) ) );
  connect( http, SIGNAL( readyRead( const QHttpResponseHeader & ) ),
           this, SLOT( handleResponseHeader( const QHttpResponseHeader & ) ) );
#ifndef DONT_USE_SSL
  connect( http, SIGNAL( sslErrors( const QList<QSslError> & ) ),
           this, SLOT( handleSSLErrors( const QList<QSslError> & ) ) );
#endif
#ifdef USE_SAFEHTTP
  connect( http, SIGNAL( hostLookupFailed() ),
           this, SLOT( handleHostLookupFailed() ) );
#endif
}

void EditingWindow::updatePostCategories()
{
  if( !entryNumber.isEmpty() )
    setPostCategories();
  else
    statusBar()->showMessage( tr( "This entry has not been posted yet." ), 2000 );
}

void EditingWindow::setPostCategories()
{
  QDomDocument doc;
  QString secCatId, secCatName;
  QDomElement cat, methodCall, params, param, value, array, _data, arrayValue, arrayStruct;

//#ifndef NO_DEBUG_OUTPUT
//  qDebug() << "starting to post categories";
//#endif
  if( categoriesEnabled ) {
    //qDebug() << "categories enabled";
    if( !currentHttpBusiness ) {
      //qDebug() << "no biz";
      methodCall = doc.createElement( "methodCall" );
      methodCall.appendChild( XmlMethodName( doc, "mt.setPostCategories" ) );
      params = doc.createElement( "params" );
      params.appendChild( XmlValue( doc, "string", entryNumber ) );
      params.appendChild( XmlValue( doc, "string", login ) );
      params.appendChild( XmlValue( doc, "string", password ) );

      param = doc.createElement( "param" );
      value = doc.createElement( "value" );
      array = doc.createElement( "array" );
      _data = doc.createElement( "data" );
      arrayValue = doc.createElement( "value" );
      arrayStruct = doc.createElement( "struct" );

      if( !cw.chNoCats->isChecked() ) {
#ifndef NO_DEBUG_OUTPUT
        // qDebug() << "posting prim cat";
#endif
        cat = currentBlogElement.firstChildElement( "categories" )
          .childNodes().at( cw.cbMainCat->currentIndex() ).toElement();
        QString primCat = cw.cbMainCat->itemData( cw.cbMainCat->currentIndex() ).toString();
#ifndef NO_DEBUG_OUTPUT
        // qDebug() << "posted prim cat";
#endif
        arrayStruct.appendChild( XmlMember( doc, "categoryId", "string", primCat.trimmed() ) );
        arrayStruct.appendChild( XmlMember( doc, "isPrimary", "boolean", "1" ) );
        arrayValue.appendChild( arrayStruct );
        _data.appendChild( arrayValue );

        for( int a = 0; a < cw.lwOtherCats->count(); a++ ) {
          if( cw.lwOtherCats->isItemSelected( cw.lwOtherCats->item( a ) ) ) {
            cat = currentBlogElement.firstChildElement( "categories" ).childNodes().at( a ).toElement();
            secCatId = cw.cbMainCat->itemData( a ).toString();
            secCatName = cw.cbMainCat->itemText( a );
            arrayValue = doc.createElement( "value" );
            arrayStruct = doc.createElement( "struct" );
            arrayStruct.appendChild( XmlMember( doc, "categoryId", "int", secCatId ) );
            arrayStruct.appendChild( XmlMember( doc, "categoryName", "string",
                                                secCatName ) );
            arrayStruct.appendChild( XmlMember( doc, "isPrimary", "boolean", "0" ) );
            arrayValue.appendChild( arrayStruct );
            _data.appendChild( arrayValue );
          }
        }
      }

      array.appendChild( _data );
      value.appendChild( array );
      param.appendChild( value );
      params.appendChild( param );
      methodCall.appendChild( params );
      doc.appendChild( methodCall );
      doc.insertBefore( doc.createProcessingInstruction( "xml",
                                                         "version=\"1.0\" encoding=\"UTF-8\"" ),
                        doc.firstChild() );
      QByteArray requestArray( doc.toByteArray( 2 ) );

      responseData = "";
      QHttpRequestHeader header( "POST", location );
      header.setValue( "Host", server );
      header.setValue( "User-Agent", userAgentString );
      setHost( http, server, port, useHTTPS ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp );
      http->request( header, requestArray );

      if( progressBarAction->isVisible() )
        progressBar->setValue( progressBar->value() + 1 );

      addToConsole( header.toString() );
      addToConsole( doc.toString() );

      if( QApplication::overrideCursor() == 0 )
        QApplication::setOverrideCursor( QCursor( Qt::BusyCursor ) );
#ifndef NO_DEBUG_OUTPUT
      // qDebug() << "posted categories";
#endif
      currentHttpBusiness = _mt_setPostCategories;
      connect( http, SIGNAL( done( bool ) ),
               this, SLOT( handleDone( bool ) ) );
      connect( http, SIGNAL( readyRead( const QHttpResponseHeader & ) ),
               this, SLOT( handleResponseHeader( const QHttpResponseHeader & ) ) );
#ifndef DONT_USE_SSL
      connect( http, SIGNAL( sslErrors( const QList<QSslError> & ) ),
               this, SLOT( handleSSLErrors( const QList<QSslError> & ) ) );
#endif
#ifdef USE_SAFEHTTP
      connect( http, SIGNAL( hostLookupFailed() ),
               this, SLOT( handleHostLookupFailed() ) );
#endif
    }
    else {
#ifdef QTM_DEBUG
      statusBar()->showMessage( tr( "setPostCategories: All HTTP requests are blocked" ),
                                2000 );
#else
      statusBar()->showMessage( tr( "All HTTP requests are blocked." ), 2000 );
#endif
      QApplication::restoreOverrideCursor();
    }
  }
  else {
    // An override cursor might have been set when posting an entry in a
    // non-category-enabled blog
    qDebug() << "categories not enabled";
    if( QApplication::overrideCursor() != 0 )
      QApplication::restoreOverrideCursor();
  }
}

void EditingWindow::publishPost() // slot
{
  QDomDocument doc;

  if( !currentHttpBusiness ) {
    QDomElement methodCall = doc.createElement( "methodCall" );
    methodCall.appendChild( XmlMethodName( doc, "mt.publishPost" ) );
    QDomElement params = doc.createElement( "params" );

    params.appendChild( XmlValue( doc, "string", entryNumber ) );
    params.appendChild( XmlValue( doc, "string", login ) );
    params.appendChild( XmlValue( doc, "string", password ) );
    methodCall.appendChild( params );
    doc.appendChild( methodCall );
    doc.insertBefore( doc.createProcessingInstruction( "xml",
                                                       "version=\"1.0\" encoding=\"UTF-8\"" ),
                      doc.firstChild() );

    QByteArray requestArray( doc.toByteArray() );

    responseData = "";
    QHttpRequestHeader header( "POST", location );
    header.setValue( "Host", server );
    header.setValue( "User-Agent", userAgentString );
    setHost( http, server, port, useHTTPS ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp );
    http->request( header, requestArray );

    if( progressBarAction->isVisible() )
      progressBar->setValue( progressBar->value() + 1 );

    addToConsole( header.toString() );
    addToConsole( doc.toString() );

    if( QApplication::overrideCursor() == 0 )
      QApplication::setOverrideCursor( QCursor( Qt::BusyCursor ) );
    currentHttpBusiness = _mt_publishPost;
    connect( http, SIGNAL( done( bool ) ),
             this, SLOT( handleDone( bool ) ) );
    connect( http, SIGNAL( readyRead( const QHttpResponseHeader & ) ),
             this, SLOT( handleResponseHeader( const QHttpResponseHeader & ) ) );
#ifndef DONT_USE_SSL
    connect( http, SIGNAL( sslErrors( const QList<QSslError> & ) ),
             this, SLOT( handleSSLErrors( const QList<QSslError> & ) ) );
#endif
#ifdef USE_SAFEHTTP
    connect( http, SIGNAL( hostLookupFailed() ),
             this, SLOT( handleHostLookupFailed() ) );
#endif

  }
  else
    statusBar()->showMessage( tr( "Cannot publish; HTTP is blocked" ), 2000 );
}

void EditingWindow::exportEntry()
{
  saveAs( true );
}

void EditingWindow::saveAll()
{
  qtm->saveAll();
}

void EditingWindow::saveAs( bool exp )
{
  QString suggestedFilename;

  if( cw.leTitle->text().isEmpty() )
    suggestedFilename = localStorageDirectory;
  else {
    suggestedFilename = QString( "%1/%2" )
      .arg( localStorageDirectory )
      .arg( cw.leTitle->text().remove( QRegExp( "[\"/\\\\<>\\?:\\*\\|]+" ) ) );
  }

  QString extn = QString( "%1 (*.%2)" ).arg( tr( "Blog entries" ) )
    .arg( localStorageFileExtn );
  QString fn = QFileDialog::getSaveFileName( this, tr( "Choose a filename" ),
                                             suggestedFilename, extn );

  if ( !fn.isEmpty() ) {
    if( !localStorageFileExtn.isEmpty() )
      if( !fn.endsWith( QString( ".%1" ).arg( localStorageFileExtn ) ) )
        fn.append( QString( ".%1" ).arg( localStorageFileExtn ) );
    filename = fn;
    /*
       This section has been commented out as unnecessary; the getSaveFileName function
       already checks for the existence of a file.  Keeping in code until tested on other platforms.

       if( QFile::exists( fn ) ) {
       if( !QMessageBox::warning( 0, tr( "File exists" ),
       tr( "A file by this name already exists. Continue?" ),
       QMessageBox::Yes, QMessageBox::No | QMessageBox::Default ) ) {
       QFile::remove( fn );
       save( fn );
       }
       }
       else */
    save( fn, exp );

    qtm->addRecentFile( cw.leTitle->text(), fn );
  }
  else
    statusBar()->showMessage( tr("Saving aborted"), 2000 );
}


void EditingWindow::save()
{
  if ( filename.isEmpty() ) {
    saveAs();
    return;
  }

  save( filename );
}

void EditingWindow::save( const QString &fname, bool exp )
{
  int count, tags;
  QString text = EDITOR->document()->toPlainText();

  // Rename the old file to a back-up file
  if( QFile::exists( fname ) )
    QFile::rename( fname, QString( "%1~" ).arg( fname ) );

  QFile f( fname );

  if( !f.open( QIODevice::WriteOnly ) ) {
    statusBar()->showMessage( tr( "Could not write to %1" ).arg(fname),
                              2000 );
    return;
  }

  QTextStream out( &f );
  out << (exp ? "QTM saved blog entry v2.0\n" : "QTM saved blog entry v3.0\n");
  out << QString( "Title:%1\n" ).arg( cw.leTitle->text() );
  out << QString( "Publish:%1\n" ).arg( QString::number( cw.cbStatus->currentIndex() ) );
  if( entryBlogged )
    out << QString( "EntryNumber:%1\n" ).arg( entryNumber );
  out << QString( "Comments:%1\n" ).arg( cw.chAllowComments->isChecked() ? "1" : "0" );
  out << QString( "TB:%1\n" ).arg( cw.chAllowTB->isChecked() ? "1" : "0" );
  if( exp ) {
    out << QString( "Server:%1\n" ).arg( server );
    out << QString( "Location:%1\n" ).arg( location );
    out << QString( "Login:%1\n" ).arg( login );
    out << QString( "Password:%1\n" ).arg( password );
    out << QString( "Blog:%1\n" ).arg( cw.cbBlogSelector->currentIndex() );
  }
  else {
    out << QString( "AcctBlog:%1@%2 (%3)\n" ) // Include the blog name so it can be relayed to the user later
      .arg( currentBlogid )
      .arg( currentAccountId )
      .arg( cw.cbBlogSelector->itemText( cw.cbBlogSelector->currentIndex() ) );
  }
  tags = cw.lwTags->count();
  if( tags ) {
    out << "Tags:";
    for( count = 0; count < tags; count++ ) {
      out << QString( count ? ";%1" : "%1" )
        .arg( cw.lwTags->item( count )->text().replace( ' ', '+' ) );
    }
    out << "\n";
  }
  tags = cw.lwKeywordTags->count();
  if( tags ) {
    out << "Keywords:";
    for( count = 0; count < tags; count++ ) {
      out << QString( count ? ",%1" : "%1" )
        .arg( cw.lwKeywordTags->item( count )->text() );
    }
    out << "\n";
  }

  if( !cw.chNoCats->isChecked() ) {
    QDomNodeList catNodeList = currentBlogElement.firstChildElement( "categories" ).elementsByTagName( "category" );
    out << QString( "PrimaryID:%1\n" ).arg( cw.cbMainCat->itemData( cw.cbMainCat->currentIndex() ).toString() );
    QString catsList;
    int cats = 0;
    for( int a = 0; a < cw.lwOtherCats->count(); a++ ) {
      if( cw.lwOtherCats->isItemSelected( cw.lwOtherCats->item( a ) ) ) {
        if( cats )
          catsList.append( QString( ";%1" ).arg( cw.cbMainCat->itemData( a ).toString() ) );
        else
          catsList.append( cw.cbMainCat->itemData( a ).toString() );
        cats++;
      }
    }
    out << QString( "CatIDs:%1\n" ).arg( catsList );
  }
  else
    out << "PrimaryID:none\n";
  if( cw.teExcerpt->toPlainText().length() > 0 )
    out << QString( "Excerpt:%1\n" )
      .arg( cw.teExcerpt->toPlainText().replace( QChar( '\n' ), "\\n" ) );
  out << QString( "Text:\n%1" ).arg( text );
  f.close();

  dirtyIndicator->hide();
  setWindowModified( false );
  setDirtySignals( true );

  entryEverSaved = true;
}

void EditingWindow::choose( QString fname )
{
  QString fn;
  QString extn( QString( "%1 (*.%2)" ).arg( tr( "Blog entries" ) )
                .arg( localStorageFileExtn ) );

  if( fname.isEmpty() )
    fn = QFileDialog::getOpenFileName( this, tr( "Choose a file to open" ),
                                       localStorageDirectory, extn );
  else
    fn = fname;

  if ( !fn.isEmpty() ) {
    if( !useNewWindows ) {
      if( saveCheck( true ) ) {
        if( !load( fn ) )
          statusBar()->showMessage( tr( "File could not be loaded." ), 2000 );
        else {
          qtm->addRecentFile( cw.leTitle->text(), fn );

          dirtyIndicator->hide();
          setWindowModified( false );
          setDirtySignals( true );
        }
      }
    }
    else {
      EditingWindow *e = new EditingWindow;
      if( e->load( fn, true ) ) {
#ifdef USE_SYSTRAYICON
        e->setSTI( sti );
#endif

        positionWidget( e, this );
        qtm->addRecentFile( e->postTitle(), fn );

        e->show();
      }
      else {
        statusBar()->showMessage( "Loading of new window failed", 2000 );
        e->deleteLater();
      }
    }
  }
  else
    statusBar()->showMessage( tr("Loading aborted"), 2000 );
}

void EditingWindow::updateRecentFileList( const QString &title, const QString &filename )
{
  Application::recentFile thisFile;
  int i;

  thisFile.title = title;
  thisFile.filename = filename;

  for( i = 0; i < 20; ++i ) {
    if( i == recentFiles.count() )
      break;
    if( recentFiles.value( i ).filename == filename )
      recentFiles.removeAt( i );
  }
  recentFiles.prepend( thisFile );
}

bool EditingWindow::load( const QString &fname, QDomDocument &dd )
{
  accountsDom = dd;

  return load( fname );
}


bool EditingWindow::load( const QString &fname, bool fromSTI )
{
  Ui::dPassword pui;
  addToConsole( "Starting load" );
  QMap<QString, QString> emap;
  QString currentLine, key, value, fetchedText, tags, keywords;
  QString catName;
  QStringList otherCatStringList;
  QDomNodeList accts;
  bool getDetailsAgain = false;
  bool isOK;
  int b, c, d, g, h, hh;
  noAutoSave = true;
  QFile f( fname );
  QDomElement details; 

  ui.actionSave_blogs->setEnabled( true );
  ui.actionSave_blogs->setVisible( true );

  if( fromSTI ) {
    accountsElement = accountsDom.createElement( "QTMAccounts" );
    currentAccountElement = accountsDom.createElement( "account" );
    accountsElement.appendChild( currentAccountElement );
    accountsDom.appendChild( accountsElement );
    accountsDom.insertBefore( accountsDom.createProcessingInstruction( "xml", "version=\"1.0\"" ),
                              accountsDom.firstChild() );
  }


  if( !f.open( QIODevice::ReadOnly ) ) {
    addToConsole( "Cannot open file" );
    statusBar()->showMessage( tr( "Cannot open file." ), 2000 );
    return false;
  }

  QTextStream t( &f );
  if( !t.readLine().startsWith( "QTM saved blog entry" ) ) {
    addToConsole( "Not a QTM blog entry" );
    statusBar()->showMessage( tr( "This is not a QTM blog entry." ), 2000 );
    return false;
  }

  do {
    currentLine = t.readLine();
    if( currentLine.startsWith( "Text:" ) )
      break;
    key = currentLine.section( QChar( ':' ), 0, 0 );
    value = currentLine.section( QChar( ':' ), 1 );
    emap[key] = value;
    addToConsole( currentLine );
  } while( !t.atEnd() );

  if( emap.contains( "Title" ) ) {
    cw.leTitle->setText( emap.value( "Title" ) );
    setWindowTitle( QString( "%1 - QTM [*]" ). arg( emap.value( "Title" ) ) );
  }

  if( emap.contains( "Publish" ) )
    cw.cbStatus->setCurrentIndex( emap.value( "Publish" ) == "1" ? 1 : 0 );

  if( emap.contains( "EntryNumber" ) ) {
    entryNumber = emap.value( "EntryNumber" );
    entryBlogged = true;
  }

  if( emap.contains( "Comments" ) )
    cw.chAllowComments->setChecked( emap.value( "Comments" ) == "1" ? true : false );

  if( emap.contains( "TB" ) )
    cw.chAllowTB->setChecked( emap.value( "TB" ) == "1" ? true : false );

  if( emap.contains( "Server" ) ) {
    if( emap.value( "Server" ) != server ) {
      server = emap.value( "Server" );
      getDetailsAgain = true;
    }
  }

  if( emap.contains( "Location" ) ) {
    if( emap.value( "Location" ) != location ) {
      location = emap.value( "Location" );
      getDetailsAgain = true;
    }
  }

  if( emap.contains( "Login" ) ) {
    if( emap.value( "Login" ) != login ) {
      login = emap.value( "Login" );
      getDetailsAgain = true;
    }
  }

  if( emap.contains( "Password" ) ) {
    if( emap.value( "Password" ) != password ) {
      password = emap.value( "Password" );
      getDetailsAgain = true;
    }
    noPassword = false;
  } else {
    password = "";
    noPassword = true;
  }

  if( emap.contains( "Tags" ) ) {
    tags = emap.value( "Tags" );
    d = tags.count( QChar( ';' ) );
    if( d ) {
      for( c = 0; c <= d; c++ )
        cw.lwTags->addItem( tags.section( QChar( ';' ), c, c ) );
    } else
      cw.lwTags->addItem( tags );
  }

  if( emap.contains( "Keywords" ) ) {
    keywords = emap.value( "Keywords" );
    d = keywords.count( QChar( ',' ) );
    if( d ) {
      for( c = 0; c <= d; c++ )
        cw.lwKeywordTags->addItem( keywords.section( QChar( ',' ), c, c ) );
    } else
      cw.lwKeywordTags->addItem( keywords );
  }

  if( emap.contains( "Blog" ) ) {
    b = emap.value( "Blog" ).toInt( &isOK );
    if( isOK ) {
      currentBlog = b;
      loadedEntryBlog = b;
    }
  }

  if( emap.contains( "AcctBlog" ) ) {
    currentBlogid = emap.value( "AcctBlog" ).section( "@", 0, 0 );
    loadedAccountId = emap.value( "AcctBlog" ).section( "@", 1, 1 ).section( " (", 0, 0 );
    b = emap.value( "AcctBlog" ).section( "@", 0, 0 ).toInt( &isOK );
    if( isOK ) {
      currentBlog = b;
      loadedEntryBlog = b;
    }
  }

  // Get old-style index categories
  if( emap.contains( "Primary" ) ) {
    b = emap.value( "Primary" ).toInt( &isOK );
    if( isOK ) {
      primaryCat = b;
      noAlphaCats = true;
      getDetailsAgain = true;
    }
    else {
      primaryCat = 0;
      addToConsole( tr( "Assignation of primary category failed" ) );
    }
  }

  if( emap.contains( "Cats" ) ) {
    otherCatsList = emap.value( "Cats" );
    otherCatStringList = otherCatsList.split( ';' );
    noAlphaCats = true;
    getDetailsAgain = true;
  }

  // Get new-style ID categories
  if( emap.contains( "PrimaryID" ) ) {
    b = emap.value( "PrimaryID" ).toInt( &isOK );
    if( isOK )
      primaryCat = b;
    else {
      primaryCat = 0;
      addToConsole( tr( "Assignation of primary category failed" ) );
    }
  }

  if( emap.contains( "CatIDs" ) ) {
    otherCatsList = emap.value( "CatIDs" );
    otherCatStringList = otherCatsList.split( ';' );
  }

  if( emap.contains( "Excerpt" ) )
    cw.teExcerpt->setPlainText( QString( emap.value( "Excerpt" ) ).replace( "\\n", "\n" ) );

  while( !t.atEnd() )
    fetchedText += QString( "%1\n" ).arg( t.readLine() );

  EDITOR->setPlainText( fetchedText );
  f.close();
  setDirtySignals( true );
  dirtyIndicator->hide();
  setWindowModified( false );

  // First of all, deal with entries saved to accounts

  if( !loadedAccountId.isNull() ) {
    accts = accountsDom.elementsByTagName( "account" );
    for( g = 0; g <= accts.count(); g++ ) {
      if( g == accts.count() ) {
        // qDebug() << accts.count() << "accounts";
        // i.e. if it gets to the end of the accounts tree without finding the account
        QMessageBox::information( 0, tr( "QTM - No such account" ),
                                  tr( "QTM could not find this account (perhaps it was deleted).\n\n"
                                      "Will set up a blank default account; you will need to fill in the access "
                                      "details by choosing Accounts from the File menu." ),
                                  QMessageBox::Ok );
        QDomElement newDefaultAccount = accountsDom.createElement( "account" );
        newDefaultAccount.setAttribute( "id", QString( "newAccount_%1" ).arg( QDateTime::currentDateTime().toString( Qt::ISODate ) ) );
        QDomElement newDetailElement = accountsDom.createElement( "details" );
        QDomElement newNameElement = accountsDom.createElement( "title" );
        newNameElement.appendChild( QDomText( accountsDom.createTextNode( tr( "New blank element" ) ) ) );
        newDetailElement.appendChild( newNameElement );
        newDefaultAccount.appendChild( newDetailElement );
        accountsDom.firstChildElement( "accounts" ).appendChild( newDefaultAccount );
        currentAccountElement = newDefaultAccount;
        cw.cbAccountSelector->addItem( tr( "New blank element" ),
                                       newDefaultAccount.attribute( "id" ) );
        cw.cbAccountSelector->setCurrentIndex( cw.cbAccountSelector->count()-1 );
        cw.cbBlogSelector->clear();
        cw.cbBlogSelector->setEnabled( false );
        cw.chNoCats->setEnabled( false );
        cw.cbMainCat->clear();
        cw.cbMainCat->setEnabled( false );
        cw.lwOtherCats->clear();
        cw.lwOtherCats->setEnabled( false );
        setPostClean();
        return true;
      }

      if( accts.at( g ).toElement().attribute( "id" ) == loadedAccountId ) {
        // qDebug() << "found the account:" << loadedAccountId;
        populateAccountList();
        currentAccountElement = accts.at( g ).toElement();
        extractAccountDetails();

        QString st;
        for( h = 0; h < cw.cbAccountSelector->count(); h++ ) {
          st = cw.cbAccountSelector->itemData( h ).toString();
          if( st == loadedAccountId )
            cw.cbAccountSelector->setCurrentIndex( h );
        }

        // Now populate the blog list
        QDomNodeList blogNodeList = currentAccountElement.elementsByTagName( "blog" );
        cw.cbBlogSelector->clear();
        for( hh = 0; hh < blogNodeList.count(); hh++ ) {
          cw.cbBlogSelector->addItem( decodeXmlEntities( blogNodeList.at( hh ).toElement()
                                                         .firstChildElement( "blogName" ).text() ),
                                      blogNodeList.at( hh ).toElement()
                                      .firstChildElement( "blogid" ).text() );

          if( blogNodeList.at( hh ).firstChildElement( "blogid" ).text() == currentBlogid )
            currentBlogElement = blogNodeList.at( hh ).toElement();
        }
        cw.cbBlogSelector->disconnect( SIGNAL( activated( int ) ), this, 0 );
        // qDebug() << "connecting changeBlog";
        connect( cw.cbBlogSelector, SIGNAL( activated( int ) ),
                 this, SLOT( changeBlog( int ) ) );
        if( !isOK ) {
          QMessageBox::information( 0, tr( "QTM - Invalid blog" ),
                                    tr( "Could not get a valid blog number.  Please set it again." ),
                                    QMessageBox::Ok );
          return true;
        }

        for( hh = 0; hh < cw.cbBlogSelector->count(); hh++ ) {
          if( cw.cbBlogSelector->itemData( hh ) == currentBlogid ) {
            cw.cbBlogSelector->setCurrentIndex( hh );
            break;
          }
        }

        // Now populate and set the categories
        QDomElement catsElement = currentBlogElement.firstChildElement( "categories" );
        if( !catsElement.isNull() ) {
          cw.cbMainCat->clear();
          cw.lwOtherCats->clear();

          QDomNodeList catNodeList = catsElement.elementsByTagName( "category" );
          int b = catNodeList.count();
          if( b ) {
            // qDebug() << "categories:" << b;
            cw.cbMainCat->clear();
            cw.lwOtherCats->clear();
            for( int j = 0; j < b; j++ ) {
              catName = decodeXmlEntities( catNodeList.at( j ).firstChildElement( "categoryName" ).text() );
              cw.cbMainCat->addItem( catName, QVariant( catNodeList.at( j ).firstChildElement( "categoryId" ).text() ) );
              cw.lwOtherCats->addItem( catName );
            }
            // qDebug() << "primaryCat is" << QString::number( primaryCat );
            for( int i = 0; i < catNodeList.size(); i++ ) {
              QString cc = catNodeList.at( i ).firstChildElement( "categoryId" ).text();
              // qDebug() << "cc is" << cc;
              if( cc == QString::number( primaryCat ) ) {
                // qDebug() << "found the primary category";
                cw.cbMainCat->setCurrentIndex( i );
              }
              else {
                if( otherCatStringList.contains( cc ) )
                  cw.lwOtherCats->setItemSelected( cw.lwOtherCats->item( i ), true );
              }
            }
          }
          else {
            cw.chNoCats->setEnabled( false );
            cw.cbMainCat->setEnabled( false );
            cw.lwOtherCats->setEnabled( false );
          }
        }
        filename = fname;
        setPostClean();
        return true;
      }
    }

    filename = fname;
    setPostClean();
    return true;
  }

  // Now we know this isn't an account entry, check whether the saved details actually
  // belong to an account; if it does, there is no need to check for the password

  // qDebug() << "this is an old-style account";
  QDomNodeList blogs;

  accts = accountsDom.documentElement().elementsByTagName( "account" );
  for( int e = 0; e <= accts.count(); e++ ) {
    if( e == accts.count() )
      break;

    details = accts.at( e ).toElement().firstChildElement( "details" );
    // qDebug() << "matching against" << details.firstChildElement( "title" ).text();
    if( details.firstChildElement( "server" ).text() == server &&
        details.firstChildElement( "location" ).text() == location &&
        details.firstChildElement( "login" ).text() == login ) {
      // qDebug() << "match found";
      currentAccountElement = accts.at( e ).toElement();
      cw.cbAccountSelector->setCurrentIndex( e );
      extractAccountDetails();
      // First check whether the blog still exists
      blogs = currentAccountElement.elementsByTagName( "blog" );
      if( currentBlog > blogs.count() ) {
        connect( this, SIGNAL( categoryRefreshFinished() ),
                 this, SLOT( setLoadedPostCategories() ) );
        refreshBlogList();
        setPostClean();
        return true;
      }
      else {

        // qDebug() << "now setting categories";
        if( blogs.at( currentBlog ).toElement().elementsByTagName( "category" ).count() ) {
          cw.cbBlogSelector->clear();
          for( hh = 0; hh < blogs.count(); hh++ ) {
            cw.cbBlogSelector->addItem( decodeXmlEntities( blogs.at( hh ).firstChildElement( "blogName" ).text() ),
                                        QVariant( blogs.at( hh ).firstChildElement( "blogid" ).text() ));
          }
          setLoadedPostCategories();
          setPostClean();
          return true;
        }
        else {
          connect( this, SIGNAL( categoryRefreshFinished() ),
                   this, SLOT( setLoadedPostCategories() ) );
          changeBlog( currentBlog );
          setPostClean();
          return true;	  
        }
      }
    }
  }

  if( noPassword ) {
    QDialog pwd;
    pui.setupUi( &pwd );
    if( pwd.exec() ) {
      password = pui.lePassword->text();
    }
    else
      QMessageBox::warning( 0, tr( "No password" ),
                            tr( "This entry was saved without a password.\n"
                                "You will need to set one, using the\n"
                                "Preferences window." ),
                            QMessageBox::Ok, QMessageBox::NoButton );

  }

  // This is an old-style account which isn't in the database
  // qDebug() << "old-style, not found";

  QDomElement newAcct, newDetails, newTitle, newServer, newLocation, newLogin, newPwd;
  newAcct = accountsDom.createElement( "account" );
  currentAccountId = tr( "newAccount_%1" ).arg( QDateTime::currentDateTime().toString( Qt::ISODate ) );
  newAcct.setAttribute( "id", currentAccountId );
  newDetails = accountsDom.createElement( "details" );
  newTitle = accountsDom.createElement( "title" );
  newTitle.appendChild( QDomText( accountsDom.createTextNode( tr( "New un-named account" ) ) ) );
  newServer = accountsDom.createElement( "server" );
  newServer.appendChild( QDomText( accountsDom.createTextNode( server ) ) );
  newLocation = accountsDom.createElement( "location" );
  newLocation.appendChild( QDomText( accountsDom.createTextNode( location ) ) );
  newLogin = accountsDom.createElement( "login" );
  newLogin.appendChild( QDomText( accountsDom.createTextNode( login ) ) );
  newPwd = accountsDom.createElement( "password" );
  newPwd.appendChild( QDomText( accountsDom.createTextNode( password ) ) );
  newDetails.appendChild( newTitle );
  newDetails.appendChild( newServer );
  newDetails.appendChild( newLocation );
  newDetails.appendChild( newLogin );
  newDetails.appendChild( newPwd );
  newAcct.appendChild( newDetails );
  accountsDom.documentElement().appendChild( newAcct );
  currentAccountElement = newAcct;
  cw.cbAccountSelector->addItem( newTitle.text(), newAcct.attribute( "id" ) );
  cw.cbAccountSelector->setCurrentIndex( cw.cbAccountSelector->count()-1 );

  connect( this, SIGNAL( categoryRefreshFinished() ),
           this, SLOT( setLoadedPostCategories() ) );
  refreshBlogList();
  saveBlogs();

  filename = fname;
  entryEverSaved = true;
  setPostClean();
  return true;

}

void EditingWindow::setLoadedPostCategories() // slot
{
  int a, b, j, z;
  int i = 0;
  QString c, cc, d;
  bool isOK;

  disconnect( SIGNAL( categoryRefreshFinished() ) );
  disconnect( SIGNAL( httpBusinessFinished() ) );

  QDomNodeList blogNodes = currentAccountElement.firstChildElement( "blogs" )
    .elementsByTagName( "blog" );

  if( !cw.cbBlogSelector->count() ) {
    j = blogNodes.size();
    for( z = 0; z < j; z++ )
      cw.cbBlogSelector->addItem( decodeXmlEntities( blogNodes.at( z ).firstChildElement( "blogName" ).text() ),
                                  QVariant( blogNodes.at( z ).firstChildElement( "blogName" ).text() ) );
    cw.cbBlogSelector->setCurrentIndex( currentBlog );
  }

  currentBlogElement = blogNodes.at( currentBlog ).toElement();
  cw.cbBlogSelector->setCurrentIndex( currentBlog );
  cw.cbMainCat->clear();
  cw.lwOtherCats->clear();
  QDomNodeList catNodeList = currentBlogElement.elementsByTagName( "category" );
  b = catNodeList.count();
  if( b ) {
    // qDebug() << "populating cat list";
    cw.cbMainCat->clear();
    cw.lwOtherCats->clear();
    for( j = 0; j < b; j++ ) {
      cw.cbMainCat->addItem( catNodeList.at( j ).firstChildElement( "categoryName" ).text(),
                             QVariant( catNodeList.at( j ).firstChildElement( "categoryId" ).text() ) );
      cw.lwOtherCats->addItem( catNodeList.at( j ).firstChildElement( "categoryName" ).text() );
    }
  }
  else {
    // qDebug() << "no categories found";
    connect( this, SIGNAL( categoryRefreshFinished() ),
             this, SLOT( setLoadedPostCategories() ) );
    return;
  }

  if( noAlphaCats ) {
    cw.cbMainCat->setCurrentIndex( primaryCat );

    QString f( otherCatsList.section( QChar( ';' ), -1, -1 ) );

    do {
      c = otherCatsList.section( QChar( ';' ), i, i );
      a = c.toInt( &isOK );
      if( isOK ) {
        cw.lwOtherCats->setItemSelected( cw.lwOtherCats->item( a ), true );
      }
      else
        break;
      i++;
    } while( c != f );
    initialChangeBlog = false;
  }
  else {
    QDomNodeList catNodes = currentBlogElement.firstChildElement( "categories" ).elementsByTagName( "category" );
    QStringList catStringList = otherCatsList.split( ";" );
    // qDebug() << "current Blog is" << currentBlogElement.firstChildElement( "blogName" ).text();
    // qDebug() << "primaryCat is" << primaryCat;

    for( i = 0; i < catNodes.size(); i++ ) {
      cc = catNodes.at( i ).firstChildElement( "categoryId" ).text();
      if( cc == QString::number( primaryCat ) ) {
        // qDebug() << "found primary category";
        cw.cbMainCat->setCurrentIndex( i );
      }
      else {
        if( catStringList.contains( cc ) )
          cw.lwOtherCats->setItemSelected( cw.lwOtherCats->item( i ), true );
      }
    }
    initialChangeBlog = false;
  }
}

void EditingWindow::saveBlogs()
{
  QFile domOut( PROPERSEPS( QString( "%1/qtmaccounts2.xml" ).arg( localStorageDirectory ) ) );
  if( domOut.open( QIODevice::WriteOnly ) ) {
    QTextStream domFileStream( &domOut );
    accountsDom.save( domFileStream, 2 );
    domOut.close();
  }
  else
    statusBar()->showMessage( tr( "Could not write to accounts file (error %1)" ).arg( (int)domOut.error() ), 2000 );
}

void EditingWindow::uploadFile()
{
  QString fileInBase64;
  QByteArray conversionBuffer;
  QFile inFile;
  QDomDocument doc;

  if( !currentHttpBusiness ) {
    QString uploadFilename = QFileDialog::getOpenFileName( this,
                                                           tr( "Select file to upload" ),
                                                           QDir::homePath() );
    if( !uploadFilename.isEmpty() ) {
      if( QFile::exists( uploadFilename ) ){
        inFile.setFileName( uploadFilename );
        if( inFile.open( QIODevice::ReadOnly ) ) {
          conversionBuffer = inFile.readAll();
          if( conversionBuffer.isEmpty() )
            statusBar()->showMessage( tr( "This file was empty, or an error occurred." ), 2000 );
          else {
            QApplication::processEvents();
            fileInBase64 = toBase64( conversionBuffer );

            if( !fileInBase64.isEmpty() ) {
              QDomElement methodCall = doc.createElement( "methodCall" );
              methodCall.appendChild( XmlMethodName( doc, "metaWeblog.newMediaObject" ) );
              QDomElement params = doc.createElement( "params" );

              QString blogid = currentBlogElement.firstChildElement( "blogid" ).text();
/*              QRegExp blogidRegExp( "^[0-9]+$" );
              bool blogidIsInt = blogidRegExp.exactMatch( blogid ); */

              params.appendChild( XmlValue( doc, "string", blogid ) );
              params.appendChild( XmlValue( doc, "string", login ) );
              params.appendChild( XmlValue( doc, "string", password ) );

              QDomElement param = doc.createElement( "param" );
              QDomElement value = doc.createElement( "value" );
              QDomElement rpcStruct = doc.createElement( "struct" );
              rpcStruct.appendChild( XmlMember( doc, "bits", "base64", fileInBase64 ) );
              rpcStruct.appendChild( XmlMember( doc, "name", "string",
                                                QFileInfo( uploadFilename ).fileName() ) );
              value.appendChild( rpcStruct );
              param.appendChild( value );
              params.appendChild( param );

              methodCall.appendChild( params );
              doc.appendChild( methodCall );
              doc.insertBefore( doc.createProcessingInstruction( "xml",
                                                                 "version=\"1.0\" encoding=\"UTF-8\"" ),
                                doc.firstChild() );

              currentHttpBusiness = _metaWeblog_newMediaObject;

              QByteArray requestArray( doc.toByteArray() );
              responseData = "";
              QHttpRequestHeader header( "POST", location );
              header.setValue( "Host", server );
              header.setValue( "User-Agent", userAgentString );
              setHost( http, server, port, useHTTPS ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp );
              http->request( header, requestArray );

              addToConsole( header.toString() );
              addToConsole( doc.toString() );

              if( QApplication::overrideCursor() == 0 )
                QApplication::setOverrideCursor( QCursor( Qt::BusyCursor ) );

              connect( http, SIGNAL( done( bool ) ),
                       this, SLOT( handleDone( bool ) ) );
              connect( http, SIGNAL( readyRead( const QHttpResponseHeader & ) ),
                       this, SLOT( handleResponseHeader( const QHttpResponseHeader & ) ) );
#ifndef DONT_USE_SSL
              connect( http, SIGNAL( sslErrors( const QList<QSslError> & ) ),
                       this, SLOT( handleSSLErrors( const QList<QSslError> & ) ) );
#endif
#ifdef USE_SAFEHTTP
              connect( http, SIGNAL( hostLookupFailed() ),
                       this, SLOT( handleHostLookupFailed() ) );
#endif
#ifndef NO_DEBUG_OUTPUT
              // qDebug() << "Posted image.";
#endif
            }
            else
              statusBar()->showMessage( tr( "Upload was cancelled." ), 2000 );
          }
          inFile.close();
        }
        else
          statusBar()->showMessage( tr( "Could not open the file." ), 2000 );
      }
      else
        statusBar()->showMessage( tr( "That file could not be found." ), 2000 );
    }
  }
  else
    statusBar()->showMessage( tr( "HTTP requests are blocked." ), 2000 );
}

void EditingWindow::doWhatsThis()
{
  QWhatsThis::enterWhatsThisMode();
}

void EditingWindow::doViewBasicSettings()
{
  cw.cbPageSelector->setCurrentIndex( 0 );
}

void EditingWindow::doViewCategories()
{
  cw.cbPageSelector->setCurrentIndex( 1 );
}

void EditingWindow::changeOtherCatsHeading()
{
  int c = cw.lwOtherCats->selectedItems().count();
  if( c )
    cw.lOtherCats->setText( tr( "Others (%1)" ).arg( c ) );
  else
    cw.lOtherCats->setText( tr( "Others" ) );
}

void EditingWindow::doViewExcerpt()
{
  cw.cbPageSelector->setCurrentIndex( 2 );
  cw.teExcerpt->setFocus();
}

void EditingWindow::doViewKeywordTags()
{
  cw.cbPageSelector->setCurrentIndex( 3 );
}

void EditingWindow::doViewTechTags()
{
  cw.cbPageSelector->setCurrentIndex( 4 );
}

void EditingWindow::doViewTBPings()
{
  cw.cbPageSelector->setCurrentIndex( 5 );
}

// This slot is to refresh categories automatically if there are none when the user
// switches to the category page
void EditingWindow::handleSideWidgetPageSwitch( int index )
{
  QDomNodeList cl;
  QString currentCatName;

  if( index == 1 ) {
    if( cw.cbMainCat->count() == 0 && networkActionsEnabled 
        && categoriesEnabled ) {
      /*if( currentBlogElement.isNull() )
        qDebug() << "currentBlogElement is null"; */
      cl = currentBlogElement.firstChildElement( "categories" ).elementsByTagName( "category" );
      if( cl.count() == 0 ) {
        statusBar()->showMessage( tr( "Getting categories, please wait" ), 2000 );
        refreshCategories();
      }
      else {
        for( int i = 0; i < cl.count(); i++ ) {
          currentCatName = cl.at( i ).firstChildElement( "categoryName" ).text();
          cw.cbMainCat->clear();
          cw.cbMainCat->addItem( currentCatName,
                                 cl.at( i ).firstChildElement( "categoryId" ).text() );
          cw.lwOtherCats->clear();
          cw.lwOtherCats->addItem( currentCatName );
        }
      }
    }
  }
}

void EditingWindow::newChildCategory()
{
  newCategory( cw.lwOtherCats->currentRow() + 1 );
}

void EditingWindow::newCategory( int parentCategory )
{
  QDomElement catsElement;
  QDomDocument doc;
  QDomElement methodCall, params, param, member, value,
              string, rpcstruct, actualValue;
  QDomNodeList catNodeList;
  int b, j;

  // This feature uses a Wordpress API call
  if( useWordpressAPI ) {
    QDialog newCategoryDialog( this );
    Ui::NewCategoryForm ncui;
    ncui.setupUi( &newCategoryDialog );

    catsElement = currentBlogElement.firstChildElement( "categories" );
    if( !catsElement.isNull() ) {
      catNodeList = catsElement.elementsByTagName( "category" );
      b = catNodeList.count();
      if( b ) {
        ncui.cbParent->clear();
        ncui.cbParent->addItem( "(Top level)", QVariant( "0" ) );
        for( j = 0; j < b; j++ )
          ncui.cbParent->addItem( catNodeList.at( j ).firstChildElement( "categoryName" ).text(),
                                 QVariant( catNodeList.at( j ).firstChildElement( "categoryId" ).text() ) );
        ncui.cbParent->setCurrentIndex( parentCategory );
      }

      if( newCategoryDialog.exec() ) {
        if( !ncui.leName->text().isEmpty() ) {
          if( !currentHttpBusiness ) {
            QString blogid = cw.cbBlogSelector->itemData( cw.cbBlogSelector->currentIndex() ).toString();
/*            QRegExp blogidRegExp( "^[0-9]+$" );
            bool blogidIsInt = blogidRegExp.exactMatch( blogid ); */

            methodCall = doc.createElement( "methodCall" );
            methodCall.appendChild( XmlMethodName( doc, "wp.newCategory" ) );

            params = doc.createElement( "params" );
            params.appendChild( XmlValue( doc, "string", blogid ) );
            params.appendChild( XmlValue( doc, "string", login ) );
            params.appendChild( XmlValue( doc, "string", password ) );

            param = doc.createElement( "param" );
            value = doc.createElement( "value" );
            rpcstruct = doc.createElement( "struct" );

            rpcstruct.appendChild( XmlMember( doc, "name", "string",
                                              ncui.leName->text() ) );
            rpcstruct.appendChild( XmlMember( doc, "slug", "string", "" ) );
            rpcstruct.appendChild( XmlMember( doc, "parent_id", "int",
                                              ncui.cbParent->itemData( ncui.cbParent->currentIndex() ).toString() ) );
            rpcstruct.appendChild( XmlMember( doc, "description", "string",
                                              ncui.teDescription->toPlainText().simplified() ) );

            value.appendChild( rpcstruct );
            param.appendChild( value );
            params.appendChild( param );

            methodCall.appendChild( params );
            doc.appendChild( methodCall );
            doc.insertBefore( doc.createProcessingInstruction( "xml",
                                                               "version=\"1.0\" encoding=\"UTF-8\"" ),
                              doc.firstChild() );

            QByteArray requestArray( doc.toByteArray() );
            responseData = "";
            QHttpRequestHeader header( "POST", location );
            header.setValue( "Host", server );
            header.setValue( "User-Agent", userAgentString );
            setHost( http, server, port, useHTTPS ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp );
            http->request( header, requestArray );

            addToConsole( header.toString() );
            addToConsole( doc.toString() );

            if( QApplication::overrideCursor() == 0 )
              QApplication::setOverrideCursor( QCursor( Qt::BusyCursor ) );
            currentHttpBusiness = _wp_newCategory;
            disconnect( this, SIGNAL( httpBusinessFinished() ) );

            connect( http, SIGNAL( done( bool ) ),
                     this, SLOT( handleDone( bool ) ) );
            connect( http, SIGNAL( readyRead( const QHttpResponseHeader & ) ),
                     this, SLOT( handleResponseHeader( const QHttpResponseHeader & ) ) );
#ifndef DONT_USE_SSL
            connect( http, SIGNAL( sslErrors( const QList<QSslError> & ) ),
                     this, SLOT( handleSSLErrors( const QList<QSslError> & ) ) );
#endif
#ifdef USE_SAFEHTTP
            connect( http, SIGNAL( hostLookupFailed() ),
                     this, SLOT( handleHostLookupFailed() ) );
#endif
          }
          else {
            statusBar()->showMessage( tr( "All HTTP requests are blocked." ), 2000 );
          }
        }
        else {
          statusBar()->showMessage( tr( "Your category must have a name." ), 2000 );
        }
      }
    }
  }
}

void EditingWindow::addKeywordTag()
{
  cw.cbPageSelector->setCurrentIndex( 3 );
  cw.leAddKeywordTag->setFocus();
}

void EditingWindow::addKeywordTagFromLineEdit()
{
  QString text( cw.leAddKeywordTag->text() );

  if( !text.isEmpty() ) {
    text.remove( QRegExp( "^\"" ) );
    text.remove( QRegExp( "\"$" ) );

    cw.lwKeywordTags->addItem( text );
    cw.leAddKeywordTag->clear();

    if( !isWindowModified() )
      dirtify();
  }
}

void EditingWindow::addKeywordTagFromAvailTags()
{
  if( cw.lwAvailKeywordTags->count() && cw.lwAvailKeywordTags->currentRow() != -1 ) {
    // Check whether the tag selected is already in use
    QListWidgetItem *currentItem = cw.lwAvailKeywordTags->currentItem();
    QList<QListWidgetItem *> matches = cw.lwKeywordTags->findItems( currentItem->text(),
                                                                    Qt::MatchFixedString | Qt::MatchCaseSensitive );

    if( !matches.count() )
    cw.lwKeywordTags->addItem( currentItem->text() );
  }
}

void EditingWindow::refreshKeywordTags()
{
  if( !currentHttpBusiness ) {
    if( useWordpressAPI ) {
      QDomDocument doc;
      QDomElement methodCall = doc.createElement( "methodCall" );
      methodCall.appendChild( XmlMethodName( doc, "wp.getTags" ) );

      QDomElement params = doc.createElement( "params" );
      params.appendChild( XmlValue( doc, "int", currentBlogid ) );
      params.appendChild( XmlValue( doc, "string", currentAccountElement.firstChildElement( "details" )
                                    .firstChildElement( "login" ).text() ) );
      params.appendChild( XmlValue( doc, "string", currentAccountElement.firstChildElement( "details" )
                                    .firstChildElement( "password" ).text() ) );

      methodCall.appendChild( params );
      doc.appendChild( methodCall );
      doc.insertBefore( doc.createProcessingInstruction( "xml",
                                                         "version=\"1.0\" encoding=\"UTF-8\"" ),
                        doc.firstChild() );
      QByteArray requestArray( doc.toByteArray( 2 ) );
      responseData = "";
      QHttpRequestHeader header( "POST", location );
      header.setValue( "Host", server );
      header.setValue( "User-Agent", userAgentString );
      setHost( http, server, port, useHTTPS ? QHttp::ConnectionModeHttps : QHttp::ConnectionModeHttp );
      http->request( header, requestArray );
      /*if( http->connectionMode() == QHttp::ConnectionModeHttps )
        qDebug() << "using HTTPS"; */

      addToConsole( header.toString() );
      addToConsole( doc.toString() );

      if( QApplication::overrideCursor() == 0 )
        QApplication::setOverrideCursor( QCursor( Qt::BusyCursor ) );

      currentHttpBusiness = _wp_getTags;
      connect( http, SIGNAL( done( bool ) ),
               this, SLOT( handleDone( bool ) ) );
      connect( http, SIGNAL( readyRead( const QHttpResponseHeader & ) ),
               this, SLOT( handleResponseHeader( const QHttpResponseHeader & ) ) );
#ifndef DONT_USE_SSL
      connect( http, SIGNAL( sslErrors( const QList<QSslError> & ) ),
               this, SLOT( handleSSLErrors( const QList<QSslError> & ) ) );
#endif
#ifdef USE_SAFEHTTP
      connect( http, SIGNAL( hostLookupFailed() ),
               this, SLOT( handleHostLookupFailed() ) );
#endif
    }
    else {
      statusBar()->showMessage( tr( "This feature only works on Wordpress." ), 2000 );
    }
  }
  else {
#ifdef QTM_DEBUG
    statusBar()->showMessage( tr( "refreshCategories: All HTTP requests are blocked" ),
                              2000 );
#else
    statusBar()->showMessage( tr( "All HTTP requests are blocked." ), 2000 );
#endif
  }
}

void EditingWindow::removeKeywordTag()
{
  int c = cw.lwKeywordTags->currentRow();
  if( c != -1 ) {
    cw.lwKeywordTags->takeItem( c );
    if( !isWindowModified() )
      dirtify();
  }
}

void EditingWindow::addTechTag()
{
  cw.cbPageSelector->setCurrentIndex( 4 );
  cw.leAddTag->setFocus();
}

void EditingWindow::addClipTag()
{
  int l;
  QRegExpValidator tagFormat( QRegExp( "^http:\\/\\/(www\\.)?technorati\\.com\\/tag\\/([a-zA-Z0-9\\.%]+[\\+ ])*[a-zA-Z0-9\\.%]+$" ), 
                              this );
  QString tagText = QApplication::clipboard()->text();

  cw.cbPageSelector->setCurrentIndex( 4 );
  addToConsole( QString( "Validating %1" ).arg( tagText ) );
  if( tagFormat.validate( tagText, l ) != QValidator::Acceptable ) {
    statusBar()->showMessage( tr( "This is not a valid tag." ), 2000 );
  } else {
    statusBar()->showMessage( tr( "This tag validates OK." ), 2000 );
    tagText.remove( QRegExp( "(http:\\/\\/)?(www\\.)?technorati\\.com\\/tag\\/" ) );
    cw.lwTags->addItem( tagText );
    if( !isWindowModified() )
      dirtify();
  }
}

void EditingWindow::addTechTagFromLineEdit()
{
  if( !cw.leAddTag->text().isEmpty() ) {
    cw.lwTags->addItem( cw.leAddTag->text() );
    cw.leAddTag->clear();
    if( !isWindowModified() )
      dirtify();
  }
}

void EditingWindow::addTechTagFromAddButton()
{
  int i;
  QString lineEditText = cw.leAddTag->text();

  if( !lineEditText.isEmpty() ) {
    if( tagValidator->validate( lineEditText, i ) == QValidator::Acceptable ) {
      statusBar()->showMessage( tr( "This tag validates." ), 2000 );
      cw.lwTags->addItem( cw.leAddTag->text() );
      cw.leAddTag->clear();
      if( !isWindowModified() )
        dirtify();
    } else {
      statusBar()->showMessage( tr( "This is not a valid tag." ), 2000 );
    }
  }
}

void EditingWindow::addTBPing()
{
  cw.cbPageSelector->setCurrentIndex( 5 );
  cw.leTBPingURL->setFocus();
}


void EditingWindow::addClipTBPing()
{
  QString clipboardText = QApplication::clipboard()->text();

  if( !clipboardText.isEmpty() ) {
    if( QUrl( clipboardText ).isValid() ) {
      statusBar()->showMessage( tr( "This URL validates." ) );
      cw.lwTBPings->addItem( clipboardText );
      if( !isWindowModified() )
        dirtify();
    } else
      statusBar()->showMessage( tr( "This is not a valid URL." ), 2000 );
  }
}

void EditingWindow::addTBPingFromLineEdit()
{
  QString lineEditText = cw.leTBPingURL->text();

  if( !lineEditText.isEmpty() ) {
    if( QUrl( lineEditText ).isValid() ) {
      statusBar()->showMessage( tr( "This URL validates." ), 2000 );
      cw.lwTBPings->addItem( lineEditText );
      cw.leTBPingURL->clear();
      if( !isWindowModified() )
        dirtify();
    } else
      statusBar()->showMessage( tr( "This is not a valid URL." ), 2000 );
  }
}

void EditingWindow::removeTechTag()
{
  int c = cw.lwTags->currentRow();
  cw.lwTags->takeItem( c );
  if( !isWindowModified() )
    dirtify();
}

void EditingWindow::addTBPingFromAddButton()
{
  QString lineEditText = cw.leTBPingURL->text();

  if( !lineEditText.isEmpty() ) {
    if( QUrl( lineEditText ).isValid() ) {
      statusBar()->showMessage( tr( "This URL validates." ), 2000 );
      cw.lwTBPings->addItem( cw.leTBPingURL->text() );
      cw.leTBPingURL->clear();
      if( !isWindowModified() )
        dirtify();
    } else
      statusBar()->showMessage( tr( "This is not a valid URL." ), 2000 );
  }
}

void EditingWindow::removeTBPing()
{
  int c = cw.lwTBPings->currentRow();
  cw.lwTBPings->takeItem( c );
  if( !isWindowModified() )
    dirtify();
}

void EditingWindow::doFont()
{
#if QT_VERSION < 0x040200
  bool isOK;
  QSettings settings;
  QFont f( QFontDialog::getFont( &isOK, EDITOR->font() ) );
  EDITOR->setFont( f );
  editorFontString = f.toString();
  settings.beginGroup( "fonts" );
  settings.setValue( "editorFontString", editorFontString );
  settings.endGroup();
#endif
}

void EditingWindow::doPreviewFont()
{
#if QT_VERSION < 0x040200
  bool isOK;
  QSettings settings;
  QFont f( QFontDialog::getFont( &isOK, previewWindow->font() ) );
  previewWindow->setFont( f );
  previewFontString = f.toString();
  settings.beginGroup( "fonts" );
  settings.setValue( "previewFontString", previewFontString );
  settings.endGroup();
#endif
}

void EditingWindow::doConsoleFont()
{
#if QT_VERSION < 0x040200
  bool isOK;
  QSettings settings;
  QFont f( QFontDialog::getFont( &isOK, console->font() ) );
  console->setFont( f );
  consoleFontString = f.toString();
  settings.beginGroup( "fonts" );
  settings.setValue( "consoleFontString", consoleFontString );
  settings.endGroup();
#endif
}

void EditingWindow::dirtify()
{
  dirtyIndicator->show();
  setWindowModified( true );
  setDirtySignals( false );
  cleanSave = false;
}

void EditingWindow::dirtifyIfText()
{
  if( !EDITOR->document()->isEmpty() ) {
    dirtyIndicator->show();
    setWindowModified( true );
    setDirtySignals( false );
    cleanSave = false;
  }
}

void EditingWindow::setDirtySignals( bool d )
{
  QList<QWidget *> widgetList;
  widgetList << EDITOR << cw.cbAccountSelector << cw.cbBlogSelector << cw.cbStatus
    << cw.chAllowComments << cw.chAllowTB << cw.cbMainCat << cw.lwOtherCats << cw.teExcerpt;

  if( d ) {
    connect( EDITOR, SIGNAL( textChanged() ), this, SLOT( dirtify() ) );
    connect( cw.cbAccountSelector, SIGNAL( activated( int ) ), this, SLOT( dirtifyIfText() ) );
    connect( cw.cbBlogSelector, SIGNAL( activated( int ) ), this, SLOT( dirtifyIfText() ) );
    connect( cw.cbStatus, SIGNAL( activated( int ) ), this, SLOT( dirtifyIfText() ) );
    connect( cw.chAllowComments, SIGNAL( clicked( bool ) ), this, SLOT( dirtifyIfText() ) );
    connect( cw.chAllowTB, SIGNAL( clicked( bool ) ), this, SLOT( dirtifyIfText() ) );
    connect( cw.cbMainCat, SIGNAL( activated( int ) ), this, SLOT( dirtifyIfText() ) );
    connect( cw.lwOtherCats, SIGNAL( activated( const QModelIndex & ) ),
             this, SLOT( dirtifyIfText() ) );
    connect( cw.teExcerpt, SIGNAL( textChanged() ), this, SLOT( dirtify() ) );
  }
  else {
    foreach( QWidget *w, widgetList )
      disconnect( w, 0, this, SLOT( dirtify() ) );
  }
}

void EditingWindow::setPostClean()
{
  dirtyIndicator->hide();
  setWindowModified( false );
  setDirtySignals( true );
  cleanSave = false;
}

void EditingWindow::showStatusBarMessage( const QString &msg )
{
  statusBar()->showMessage( msg, 2000 );
}

bool EditingWindow::saveCheck( bool )
{
  bool return_value;

  if( !isWindowModified() )
    return_value = true;
  else
    return_value = saveCheck();

  return return_value;
}

bool EditingWindow::saveCheck()
{
  bool return_value;

  activateWindow();
  int a = QMessageBox::warning( this, tr( "Not saved" ),
                                tr( "You have not saved this file.\n"
                                    "Save first?" ),
                                QMessageBox::Yes | QMessageBox::Default,
                                QMessageBox::No, QMessageBox::Cancel );
  switch( a ) {
    case QMessageBox::Cancel:
      return_value = false;
      break;
    case QMessageBox::Yes:
      save();
    default:
      return_value = true;
  }

  return return_value;
}

void EditingWindow::doInitialChangeBlog()
{
#ifdef QTM_DEBUG
  addToConsole( QString( "loadedEntryBlog: %1\n" ).arg( loadedEntryBlog ) );
#endif
  disconnect( this, SIGNAL( httpBusinessFinished() ), 0, 0 );
  if( loadedEntryBlog != 999 ) {
    currentBlog = loadedEntryBlog;
    loadedEntryBlog = 999;
    cw.cbBlogSelector->setCurrentIndex( currentBlog );
    currentBlogElement = currentAccountElement.firstChildElement( "blogs" )
      .elementsByTagName( "blog" ).at( currentBlog ).toElement();
    currentBlogid = currentBlogElement.firstChildElement( "blogid" ).text();
#ifndef NO_DEBUG_OUTPUT
    // qDebug() << currentBlogid;
#endif

  }
  changeBlog( currentBlog );

  disconnect( cw.cbBlogSelector, SIGNAL( activated( int ) ),
              this, SLOT( changeBlog( int ) ) );
  connect( cw.cbBlogSelector, SIGNAL( activated( int ) ),
           this, SLOT( changeBlog( int ) ) );
}

void EditingWindow::copyURL()
{
  QApplication::clipboard()->setText( remoteFileLocation );
  ui.actionCopy_upload_location->setVisible( false );
  pbCopyURL->hide();
}

void EditingWindow::handleFind()
{
  if( searchWidget->isVisible() ) {
    ui.action_Find->setText( tr( "&Find ..." ) );
    searchWidget->close();
  }
  else {
    ui.action_Find->setText( tr( "Exit &find" ) );
    searchWidget->find();
  }
}

QDomElement EditingWindow::XmlValue( QDomDocument &doc, QString valueType,
                                     QString actualValue, QString memberType )
{
  QDomElement param = doc.createElement( memberType );
  QDomElement value = doc.createElement( "value" );
  QDomElement realValue = doc.createElement( valueType );
  realValue.appendChild( QDomText( doc.createTextNode( actualValue ) ) );
  value.appendChild( realValue );
  param.appendChild( value );

  return param;
}

QDomElement EditingWindow::XmlMember( QDomDocument &doc, QString valueName,
                                      QString valueType, QString actualValue )
{
  QDomElement mem = doc.createElement( "member" );
  QDomElement name = doc.createElement( "name" );
  name.appendChild( QDomText( doc.createTextNode( valueName ) ) );
  mem.appendChild( name );
  QDomElement value = doc.createElement( "value" );
  QDomElement realValue = doc.createElement( valueType );
  realValue.appendChild( QDomText( doc.createTextNode( actualValue ) ) );
  value.appendChild( realValue );
  mem.appendChild( value );

  return mem;
}

QDomElement EditingWindow::XmlMethodName( QDomDocument &doc, QString methodName )
{
  QDomElement methName = doc.createElement( "methodName" );
  methName.appendChild( QDomText( doc.createTextNode( methodName ) ) );

  return methName;
}

QDomElement EditingWindow::XmlRpcArray( QDomDocument &doc, QString valueName,
                                        QList<QString> text )
{
  QDomElement arrayValue, arrayValueString;
  int i;

  QDomElement mem = doc.createElement( "member" );
  QDomElement name = doc.createElement( "name" );
  name.appendChild( QDomText( doc.createTextNode( valueName ) ) );
  mem.appendChild( name );
  QDomElement value = doc.createElement( "value" );
  QDomElement array = doc.createElement( "array" );
  QDomElement arrayData = doc.createElement( "data" );

  for( i = 0; i < text.count(); i++ ) {
    arrayValue = doc.createElement( "value" );
    arrayValueString = doc.createElement( "string" );
    arrayValueString.appendChild( QDomText( doc.createTextNode( text.value( i ) ) ) );
    arrayValue.appendChild( arrayValueString );
    arrayData.appendChild( arrayValue );
  }

  array.appendChild( arrayData );
  value.appendChild( array );
  mem.appendChild( value );

  return mem;
}

void EditingWindow::setNetworkActionsEnabled( bool a )
{
  networkActionsEnabled = a;
  ui.actionRefresh_blog_list->setEnabled( a );
  ui.actionRefresh_categories->setEnabled( categoriesEnabled ? a : false );
  ui.actionSend_categories->setEnabled( categoriesEnabled ? a : false );
  ui.action_Blog_this->setEnabled( a );
  cw.lBlog->setEnabled( a );
  cw.cbBlogSelector->setEnabled( a );
  cw.pbRefresh->setEnabled( a );
}

void EditingWindow::handleInitialLookup( const QHostInfo &hostInfo )
{
  if( hostInfo.error() == QHostInfo::NoError ) {
    refreshBlogList();
    setNetworkActionsEnabled( true );
  }
  else
    setNetworkActionsEnabled( false );
}

void EditingWindow::handleHostLookupFailed()
{
  statusBar()->showMessage( tr( "The host specified could not be found." ), 2000 );

  http->disconnect();
  http->abort();

  disconnect( SIGNAL( httpBusinessFinished() ) );
  if( QApplication::overrideCursor() != 0 )
    QApplication::restoreOverrideCursor();
}

void EditingWindow::configureQuickpostTemplates()
{
#if QT_VERSION >= 0x040200
#if defined USE_SYSTRAYICON
  if( sti )
    sti->configureQuickpostTemplates( this );
#endif
#endif
}

void EditingWindow::setPublishStatus( int publishStatus )
{
  cw.cbStatus->setCurrentIndex( publishStatus );
}

QString EditingWindow::postTitle()
{
  return cw.leTitle->text();
}

void EditingWindow::setPostTitle( const QString &t )
{
  cw.leTitle->setText( t );
}

void EditingWindow::saveAutoLinkDictionary()
{
  QDomDocument doc;
  QDomElement currentElement, currentKey, currentValue, currentTitle, currentTarget;
  QDomText titleText, targetText;

  QDomElement autoLinkDictionaryElement = doc.createElement( "AutoLinkDictionary" );
  QHashIterator<QString, QString> aldIterator( autoLinkDictionary );

  while( aldIterator.hasNext() ) {
    aldIterator.next();
    currentElement = doc.createElement( "entry" );
    currentKey = doc.createElement( "key" );
    currentKey.appendChild( QDomText( doc.createTextNode( aldIterator.key() ) ) );
    currentValue = doc.createElement( "URL" );
    currentValue.appendChild( QDomText( doc.createTextNode( aldIterator.value() ) ) );
    currentElement.appendChild( currentKey );
    currentElement.appendChild( currentValue );
    if( autoLinkTitleDictionary.contains( aldIterator.key() ) ) {
      currentTitle = doc.createElement( "title" );
      titleText = doc.createTextNode( autoLinkTitleDictionary.value( aldIterator.key() ) );
      currentTitle.appendChild( titleText );
      currentElement.appendChild( currentTitle );
    }
    if( autoLinkTargetDictionary.contains( aldIterator.key() ) ) {
      currentTarget = doc.createElement( "target" );
      targetText = doc.createTextNode( QString::number( autoLinkTargetDictionary
                                                        .value( aldIterator.key() ) ) );
      currentTarget.appendChild( targetText );
      currentElement.appendChild( currentTarget );
    }
    autoLinkDictionaryElement.appendChild( currentElement );
  }

  doc.appendChild( autoLinkDictionaryElement );
  doc.insertBefore( doc.createProcessingInstruction( "xml",
                                                     "version=\"1.0\" encoding=\"UTF-8\"" ),
                    doc.firstChild() );

  QSettings settings;
  settings.beginGroup( "account" );
  QString dictionaryFileName = QString( "%1/qtmautolinkdict.xml" )
    .arg( settings.value( "localStorageDirectory", "" ).toString() );
  settings.endGroup();
  QFile dictionaryFile( dictionaryFileName );
  if( dictionaryFile.open( QIODevice::WriteOnly ) ) {
    QTextStream dictionaryFileStream( &dictionaryFile );
    doc.save( dictionaryFileStream, 4 );
    dictionaryFile.close();
  }
  else
    statusBar()->showMessage(  tr( "Could not write to dictionary file" ), 2000 );
}

void EditingWindow::loadAutoLinkDictionary()
{
  QString dictionaryFileName, errorString, currentKey, currentURL;
  int currentTarget;
  QDomElement currentKeyElement, currentURLElement, currentTitleElement, currentTargetElement;
  QSettings settings;
  int errorLine, errorCol;
  bool ok;

  settings.beginGroup( "account" );
  dictionaryFileName = QString( "%1/qtmautolinkdict.xml" ).
    arg( settings.value( "localStorageDirectory", "" ).toString() );
  settings.endGroup();

  if( QFile::exists( dictionaryFileName ) ) {
    QDomDocument dictDoc( "autoLinkDictionary" );
    QFile file( dictionaryFileName );
    if( !dictDoc.setContent( &file, true, &errorString, &errorLine, &errorCol ) )
      QMessageBox::warning( 0, tr( "Failed to read templates" ),
                            QString( tr( "Error: %1\n"
                                         "Line %2, col %3" ) )
                            .arg( errorString ).arg( errorLine )
                            .arg( errorCol ) );
    else {
      QDomNodeList entryList = dictDoc.elementsByTagName( "entry" );
      for( int i = 0; i < entryList.count(); i++ ) {
        currentKeyElement = entryList.at( i ).firstChildElement( "key" );
        currentURLElement = entryList.at( i ).firstChildElement( "URL" );
        currentTitleElement = entryList.at( i ).firstChildElement( "title" );
        currentTargetElement = entryList.at( i ).firstChildElement( "target" );
        if( currentKeyElement.isNull() || currentURLElement.isNull() )
          continue;
        else {
          currentKey = currentKeyElement.text();
          currentURL = currentURLElement.text();
          autoLinkDictionary.insert( currentKey, currentURL );
          if( !currentTitleElement.isNull() )
            autoLinkTitleDictionary.insert( currentKey, currentTitleElement.text() );
          if( !currentTargetElement.isNull() ) {
            currentTarget = currentTargetElement.text().toInt( &ok );
            if( ok )
              autoLinkTargetDictionary.insert( currentKey, currentTarget );
          }
        }
      }
    }
  }
}

// This method was adapted from the QByteArray source code in Qt v4.3.1

QByteArray EditingWindow::toBase64( QByteArray &qbarray )
{
  QProgressDialog pdialog( tr( "Converting file to Base64" ),
                           tr( "Cancel" ),
                           0, qbarray.size(), 0 );
  pdialog.setWindowModality( Qt::WindowModal );
  pdialog.setMinimumDuration( 2000 );
  pdialog.setWindowTitle( "QTM" );

  const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
    "ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
  const char padchar = '=';
  int padlen = 0;

  char *data = qbarray.data();
  int size = qbarray.size();

  QByteArray tmp;
  tmp.resize(((size * 4) / 3) + 3);

  int i = 0;
  char *out = tmp.data();
  while (i < size) {
    int chunk = 0;
    chunk |= int(uchar(data[i++])) << 16;
    if (i == size) {
      padlen = 2;
    } else {
      chunk |= int(uchar(data[i++])) << 8;
      if (i == size) padlen = 1;
      else chunk |= int(uchar(data[i++]));
    }

    int j = (chunk & 0x00fc0000) >> 18;
    int k = (chunk & 0x0003f000) >> 12;
    int l = (chunk & 0x00000fc0) >> 6;
    int m = (chunk & 0x0000003f);
    *out++ = alphabet[j];
    *out++ = alphabet[k];
    if (padlen > 1) *out++ = padchar;
    else *out++ = alphabet[l];
    if (padlen > 0) *out++ = padchar;
    else *out++ = alphabet[m];

    if( pdialog.wasCanceled() )
      break;
    if( i % 1024 == 0 ) {
      pdialog.setValue( i );
      qApp->processEvents();
    }
  }

  tmp.truncate(out - tmp.data());
  if( pdialog.wasCanceled() )
    return QByteArray();
  else
    return tmp;
}

void EditingWindow::addToConsole( const QString &t )
{
  QString text = t;
#ifndef NO_DEBUG_OUTPUT
  if( currentHttpBusiness == _metaWeblog_newMediaObject )
    // qDebug() << "Adding image to console";
#endif
    text.replace( QString( "<string>%1</string>" ).arg( password ),
                  tr( "<string>(password omitted)</string>" ) );
  QTextCursor cursor( console->textCursor() );

  cursor.movePosition( QTextCursor::End );
  console->setTextCursor( cursor );
  if( text.contains( "<base64>" ) )
    console->insertPlainText( text.section( "<base64>", 0, 0, QString::SectionIncludeTrailingSep )
                              .append( tr( " ... base64 encoded file omitted ... " ) )
                              .append( text.section( "</base64>", 1, 1, QString::SectionIncludeLeadingSep ) ) );
  else
    console->insertPlainText( text );

}

void EditingWindow::hideProgressBarIfMaximum( int val )
{
  if( val == progressBar->maximum() )
    QTimer::singleShot( 1000, this, SLOT( hideProgressBar() ) );
}

void EditingWindow::hideProgressBar()
{
  progressBarAction->setVisible( false );
  progressBar->reset();
}

QString EditingWindow::checkBoxName( QString source )
{
  QChar firstLetter( source.at( 1 ) );
  return QString( "%1%2%3" )
    .arg( "ch" )
    .arg( firstLetter.toUpper() )
    .arg( source.section( 1, -1 ) );
}

QString EditingWindow::decodeXmlEntities( QString source )
{
  QString rv;
  int i, tc;
  int pos = 0;
  QChar thisChar;
  QString key, thisCap;
  bool ok;
  QStringList lst, caps;
 
  QRegExp rx1( "&(\\S+);" );       // Detects named entities
  QRegExp rx2( "&#(\\d{1-3});" );  // Detects only numerically-defined characters
  int index = rx1.indexIn( source );
 
  if( index == -1 )
    return source;
  else {
    lst = source.split( rx1 );

    while(( pos = rx1.indexIn( source, pos )) != -1 ) {
      caps += rx1.cap( 0 );
      //qDebug() << "Matched" << rx1.cap( 0 );
      pos += rx1.matchedLength();
    }
    //qDebug() << "Occurrences:" << caps.length();

    for( i = 0; i < lst.count(); ++i ) {
      rv += lst.value( i );
      thisCap = caps.value( i );
      //qDebug() << "i =" << i;

      if( !thisCap.isNull() ) {
        if( rx2.exactMatch( caps.value( i ) ) ) {
          tc = rx2.cap( 0 ).toInt( &ok );
          if( ok && tc < 256 )
            rv += QChar( tc );
          else
            rv += caps.value( i );
        }
        else {
          rx1 = QRegExp( rx1 );
          rx1.indexIn( thisCap );
          key = rx1.cap( 1 );
          //qDebug() << "Using caps value" << i;
          //qDebug() << thisCap << "is not a numerical: caps:" << rx1.numCaptures();
          if( xmlEntities.contains( key ) )
            rv += xmlEntities.value( key );
          else
           rv += rx1.cap( 0 );
        }
      }
    }
    return rv;
  }
}