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

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
*/

#include "KWDocument.h"

#include "KWordDocIface.h"
#include "KWBgSpellCheck.h"
#include "KoTextBookmark.h"
#include "KWCanvas.h"
#include "KWCommand.h"
#include "KWFormulaFrameSet.h"
#include "KWFrameLayout.h"
#include "KWPictureFrameSet.h"
#include "KWPartFrameSet.h"
#include "KWTableFrameSet.h"
#include "KWTableStyle.h"
#include "KWTableTemplate.h"
#include "KWTextImage.h"
#include "KWVariable.h"
#include "KWView.h"
#include "KWViewMode.h"
#include "KWMailMergeDataBase.h"
#include "KWLoadingInfo.h"
#include "KWCollectFramesetsVisitor.h"
#include "KWOasisLoader.h"
#include "KWOasisSaver.h"
#include "KWFrameList.h"
#include "KWPageManager.h"
#include "KWPage.h"
#include "KWFrameView.h"
#include "KWFrameViewManager.h"
#include "KWStartupWidget.h"

#include <KoPictureCollection.h>
#include <KoTemplateChooseDia.h>
#include <KoMainWindow.h>
#include <KoDocumentInfo.h>
#include <KoGlobal.h>
#include <KoParagCounter.h>
#include <KoTextObject.h>
#include <KoAutoFormat.h>
#include <KoVariable.h>
#include <kformuladocument.h>
#include <KoApplication.h>
#include <KoOasisContext.h>
#include <KoCommandHistory.h>
#include <KoGenStyles.h>
#include <KoStore.h>
#include <KoStoreDrag.h>
#include <KoStoreDevice.h>
#include <KoXmlWriter.h>
#include <KoOasisStore.h>
#include <KoOasisStyles.h>
#include <KoXmlNS.h>
#include <KoDom.h>

#include <kcursor.h>
#include <kdebug.h>
#include <kglobalsettings.h>
#include <klibloader.h>
#include <kmultipledrag.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kspell.h>
#include <kstandarddirs.h>

#include <kspell2/settings.h>

#include <tqfileinfo.h>
#include <tqregexp.h>
#include <tqtimer.h>
#include <tqbuffer.h>

#include <unistd.h>
#include <math.h>

//#define DEBUG_PAGES
//#define DEBUG_SPEED

// Make sure an appropriate DTD is available in www/koffice/DTD if changing this value
static const char * CURRENT_DTD_VERSION = "1.2";

/******************************************************************/
/* Class: KWCommandHistory                                        */
/******************************************************************/
class KWCommandHistory : public KoCommandHistory
{
public:
    KWCommandHistory( KWDocument * doc ) : KoCommandHistory( doc->actionCollection(),  true ), m_pDoc( doc ) {}
public /*slots*/: // They are already slots in the parent. Running tqmoc on the inherited class shouldn't be necessary AFAICS.
    virtual void undo();
    virtual void redo();
private:
    KWDocument * m_pDoc;
};

void KWCommandHistory::undo()
{
    m_pDoc->clearUndoRedoInfos();
    KoCommandHistory::undo();
}

void KWCommandHistory::redo()
{
    m_pDoc->clearUndoRedoInfos();
    KoCommandHistory::redo();
}

/******************************************************************/
/* Class: KWDocument                                              */
/******************************************************************/
void KWDocument::clearUndoRedoInfos()
{
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
    {
        KWTextFrameSet *fs = dynamic_cast<KWTextFrameSet *>( fit.current() );
        if ( fs )
            fs->clearUndoRedoInfo();
    }
}

/**
 * Temporary storage for the initial edition info
 * (activeFrameset, cursorParagraph and cursorIndex attributes of the XML)
 */
class KWDocument::InitialEditing {
public:
    TQString m_initialFrameSet;
    int m_initialCursorParag;
    int m_initialCursorIndex;
};

const int KWDocument::CURRENT_SYNTAX_VERSION = 3;

KWDocument::KWDocument(TQWidget *parentWidget, const char *widname, TQObject* parent, const char* name, bool singleViewMode )
    : KoDocument( parentWidget, widname, parent, name, singleViewMode ),
      m_urlIntern()
{
    KWStatisticVariable::setExtendedType(  true );
    dcop = 0;
    m_framesChangedHandler = 0;
    m_pageManager = new KWPageManager();
    m_pageManager->appendPage();
    m_loadingInfo = 0L;
    m_tabStop = MM_TO_POINT( 15.0 );
    m_processingType = WP;

//    varFormats.setAutoDelete(true);
    m_lstFrameSet.setAutoDelete( true );
    // m_textImageRequests does not create or delete the KWTextImage classes
    m_textImageRequests.setAutoDelete(false);

    m_styleColl = new KoStyleCollection();
    m_frameStyleColl = new KWFrameStyleCollection();
    m_tableStyleColl = new KWTableStyleCollection();
    m_tableTemplateColl = new KWTableTemplateCollection();
    m_pictureCollection = new KoPictureCollection();

    m_personalExpressionPath = KWFactory::instance()->dirs()->resourceDirs("expression");

    m_bShowGrid = false;
    m_bSnapToGrid = false;


    setInstance( KWFactory::instance(), false );
    setTemplateType( "kword_template" );

    m_gridX = m_gridY = MM_TO_POINT(5.0 );
    m_indent = MM_TO_POINT( 10.0 );

    m_iNbPagePerRow = 4;
    m_maxRecentFiles = 10;
    m_bShowRuler = true;

    m_footNoteSeparatorLinePos=SLP_LEFT;

    m_viewFormattingChars = false;

    m_viewFormattingEndParag = true;
    m_viewFormattingSpace = true;
    m_viewFormattingTabs = true;
    m_viewFormattingBreak = true;

    m_viewFrameBorders = true;
    m_repaintAllViewsPending = false;
    m_recalcFramesPending = -1;
    m_bShowDocStruct = true;
    m_bShowRuler = true;
    m_bShowStatusBar = true;
    m_bAllowAutoFormat = true;
    m_pgUpDownMovesCaret = true;
    m_bShowScrollBar = true;
    m_cursorInProtectectedArea = true;
    m_bHasEndNotes = false;

    m_bInsertDirectCursor=false;
    m_globalLanguage = KGlobal::locale()->language();
    m_bGlobalHyphenation = false;
    m_bGeneratingPreview = false;
    m_viewModeType="ModeNormal";
    m_layoutViewMode = 0;

    m_commandHistory = new KWCommandHistory( this );
    connect( m_commandHistory, TQT_SIGNAL( documentRestored() ), this, TQT_SLOT( slotDocumentRestored() ) );
    connect( m_commandHistory, TQT_SIGNAL( commandExecuted() ), this, TQT_SLOT( slotCommandExecuted() ) );

    //styleMask = U_FONT_FAMILY_ALL_SIZE | U_COLOR | U_BORDER | U_INDENT |
    //                     U_NUMBERING | U_ALIGN | U_TABS | U_SMART;
    m_headerVisible = false;
    m_footerVisible = false;

    m_pasteFramesetsMap = 0L;
    m_initialEditing = 0L;
    m_bufPixmap = 0L;
    m_varFormatCollection = new KoVariableFormatCollection;
    m_varColl = new KWVariableCollection( new KWVariableSettings(), m_varFormatCollection );

    m_autoFormat = new KoAutoFormat(this,m_varColl,m_varFormatCollection );
    m_bgSpellCheck = new KWBgSpellCheck(this);
    m_slDataBase = new KWMailMergeDataBase( this );
    m_bookmarkList = new KoTextBookmarkList;
    slRecordNum = -1;

    m_syntaxVersion = CURRENT_SYNTAX_VERSION;

    m_hasTOC=false;

    // It's important to call this to have the kformula actions
    // created. The real document is still to be created if needed.
    m_formulaDocumentWrapper =
        new KFormula::DocumentWrapper( instance()->config(),
                                       actionCollection(),
                                       m_commandHistory );

    setEmpty();
    setModified(false);

    initConfig();

    // Get default font from the KWord config file
    KConfig *config = KWFactory::instance()->config();
    config->setGroup("Document defaults" );
    TQString defaultFontname=config->readEntry("DefaultFont");
    if ( !defaultFontname.isEmpty() )
        m_defaultFont.fromString( defaultFontname );
    // If not found, we automatically fallback to the application font (the one from KControl's font module)

    // Try to force a scalable font.
    m_defaultFont.setStyleStrategy( TQFont::ForceOutline );

    int ptSize = m_defaultFont.pointSize();
    if ( ptSize == -1 ) // specified with a pixel size ?
        ptSize = TQFontInfo(m_defaultFont).pointSize();

    //kdDebug() << "Default font: requested family: " << m_defaultFont.family() << endl;
    //kdDebug() << "Default font: real family: " << TQFontInfo(m_defaultFont).family() << endl;

    if ( name )
        dcopObject();
}

DCOPObject* KWDocument::dcopObject()
{
    if ( !dcop )
        dcop = new KWordDocIface( this );
    return dcop;
}

KWDocument::~KWDocument()
{
    //don't save config when kword is embedded into konqueror
    if(isReadWrite())
        saveConfig();
    // formula frames have to be deleted before m_formulaDocumentWrapper
    m_lstFrameSet.clear();
    delete m_loadingInfo;
    delete m_autoFormat;
    delete m_formulaDocumentWrapper;
    delete m_commandHistory;
    delete m_varColl;
    delete m_varFormatCollection;
    delete m_slDataBase;
    delete dcop;
    delete m_bgSpellCheck;
    delete m_styleColl;
    delete m_frameStyleColl;
    delete m_tableStyleColl;
    delete m_tableTemplateColl;
    delete m_layoutViewMode;
    delete m_bufPixmap;
    delete m_pictureCollection;
    delete m_pageManager;
    delete m_bookmarkList;
}

void KWDocument::initConfig()
{
  KConfig *config = KWFactory::instance()->config();
  if( config->hasGroup("KSpell kword" ) )
  {
      config->setGroup( "KSpell kword" );

      // Default is false for spellcheck, but the spell-check config dialog
      // should write out "true" when the user configures spell checking.
      if ( isReadWrite() )
          m_bgSpellCheck->setEnabled(config->readBoolEntry( "SpellCheck", false ));
      else
          m_bgSpellCheck->setEnabled( false );
  }

  if(config->hasGroup("Interface" ) )
  {
      config->setGroup( "Interface" );
      setGridY(TQMAX( config->readDoubleNumEntry("GridY",MM_TO_POINT(5.0) ), 0.1));
      setGridX(TQMAX( config->readDoubleNumEntry("GridX",MM_TO_POINT(5.0) ), 0.1));
      setCursorInProtectedArea( config->readBoolEntry( "cursorInProtectArea", true ));
      // Config-file value in mm, default 10 pt
      double indent = config->readDoubleNumEntry("Indent", MM_TO_POINT(10.0) ) ;
      setIndentValue(indent);
      setShowRuler(config->readBoolEntry("Rulers",true));
      int defaultAutoSave = KoDocument::defaultAutoSave()/60; // in minutes
      setAutoSave(config->readNumEntry("AutoSave",defaultAutoSave)*60); // read key in minutes, call setAutoSave(seconds)
      setBackupFile( config->readBoolEntry("BackupFile", true) );

      setNbPagePerRow(config->readNumEntry("nbPagePerRow",4));
      m_maxRecentFiles = config->readNumEntry( "NbRecentFile", 10 );

      m_viewFormattingChars = config->readBoolEntry( "ViewFormattingChars", false );
      m_viewFormattingBreak = config->readBoolEntry( "ViewFormattingBreaks", true );
      m_viewFormattingSpace = config->readBoolEntry( "ViewFormattingSpace", true );
      m_viewFormattingEndParag = config->readBoolEntry( "ViewFormattingEndParag", true );
      m_viewFormattingTabs = config->readBoolEntry( "ViewFormattingTabs", true );

      m_viewFrameBorders = config->readBoolEntry( "ViewFrameBorders", true );

      m_zoom = config->readNumEntry( "Zoom", 100 );
      m_zoomMode = static_cast<KoZoomMode::Mode> (
              config->readNumEntry( "ZoomMode", KoZoomMode::ZOOM_CONSTANT )
      );

      m_bShowDocStruct = config->readBoolEntry( "showDocStruct", true );
      m_viewModeType = config->readEntry( "viewmode", "ModeNormal" );
      setShowStatusBar( config->readBoolEntry( "ShowStatusBar" , true ) );
      setAllowAutoFormat( config->readBoolEntry( "AllowAutoFormat" , true ) );
      setShowScrollBar( config->readBoolEntry( "ShowScrollBar", true ) );
      if ( isEmbedded() )
          m_bShowDocStruct = false; // off by default for embedded docs, but still toggleable
      m_pgUpDownMovesCaret = config->readBoolEntry( "PgUpDownMovesCaret", true );
      m_bInsertDirectCursor= config->readBoolEntry( "InsertDirectCursor", false );
      m_globalLanguage=config->readEntry("language", KGlobal::locale()->language());
      m_bGlobalHyphenation=config->readBoolEntry("hyphenation", false);

      setShowGrid( config->readBoolEntry( "ShowGrid" , false ));
      setSnapToGrid( config->readBoolEntry( "SnapToGrid", false ));
      setGridX( config->readDoubleNumEntry( "ResolutionX", MM_TO_POINT( 5.0 ) ));
      setGridY( config->readDoubleNumEntry( "ResolutionY", MM_TO_POINT( 5.0 ) ));
  }
  else
  {
      m_zoom = 100;
      m_zoomMode = KoZoomMode::ZOOM_WIDTH;
  }
  int undo=30;
  if(config->hasGroup("Misc" ) )
  {
      config->setGroup( "Misc" );
      undo=config->readNumEntry("UndoRedo",-1);

      //load default unit setting - this is only used for new files (from templates) or empty files
      if ( config->hasKey( "Units" ) )
          setUnit( KoUnit::unit( config->readEntry("Units") ) );
      m_defaultColumnSpacing = config->readDoubleNumEntry( "ColumnSpacing", 3.0 );
  }

  if(undo!=-1)
      setUndoRedoLimit(undo);

  setZoomAndResolution( m_zoom, KoGlobal::dpiX(), KoGlobal::dpiY() );

  //text mode view is not a good default for a readonly document...
  if ( !isReadWrite() && m_viewModeType =="ModeText" )
      m_viewModeType= "ModeNormal";

  m_layoutViewMode = KWViewMode::create( m_viewModeType, this, 0 /*no canvas*/);

  if(config->hasGroup("Kword Path" ) )
  {
      config->setGroup( "Kword Path" );
      if ( config->hasKey( "expression path" ) )
          m_personalExpressionPath = config->readPathListEntry( "expression path" );
      setBackupPath(config->readPathEntry( "backup path" ));
  }

  // Load personal dict
  KConfigGroup group( KoGlobal::kofficeConfig(), "Spelling" );
  m_spellCheckPersonalDict = group.readListEntry( "PersonalDict" );
}

void KWDocument::saveConfig()
{
    if ( !isReadWrite() )
        return;
    KConfigGroup group( KoGlobal::kofficeConfig(), "Spelling" );
    group.writeEntry( "PersonalDict", m_spellCheckPersonalDict );

    if ( !isEmbedded() )
    {
        // Only save the config that is manipulated by the UI directly.
        // The config from the config dialog is saved by the dialog itself.
        KConfig *config = KWFactory::instance()->config();
        config->setGroup( "Interface" );
        config->writeEntry( "ViewFormattingChars", m_viewFormattingChars );
        config->writeEntry( "ViewFormattingBreaks", m_viewFormattingBreak );
        config->writeEntry( "ViewFormattingEndParag", m_viewFormattingEndParag );
        config->writeEntry( "ViewFormattingTabs", m_viewFormattingTabs );
        config->writeEntry( "ViewFormattingSpace", m_viewFormattingSpace );
        config->writeEntry( "ViewFrameBorders", m_viewFrameBorders );
        config->writeEntry( "Zoom", m_zoom );
        config->writeEntry( "ZoomMode", m_zoomMode );
        config->writeEntry( "showDocStruct", m_bShowDocStruct );
        config->writeEntry( "Rulers", m_bShowRuler );
        config->writeEntry( "viewmode", m_viewModeType) ;
        config->writeEntry( "AllowAutoFormat", m_bAllowAutoFormat );
        config->writeEntry( "ShowGrid" , m_bShowGrid );
        config->writeEntry( "SnapToGrid" , m_bSnapToGrid );
        config->writeEntry( "ResolutionX", m_gridX );
        config->writeEntry( "ResolutionY", m_gridY );
    }
}

void KWDocument::setZoomAndResolution( int zoom, int dpiX, int dpiY )
{
    KoTextZoomHandler::setZoomAndResolution( zoom, dpiX, dpiY );
    if ( KFormula::Document* formulaDocument = m_formulaDocumentWrapper->document() )
        formulaDocument->setZoomAndResolution( zoom, dpiX, dpiY );
}

KWTextFrameSet * KWDocument::textFrameSet ( unsigned int num ) const
{
    unsigned int i=0;
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
    {
        if(fit.current()->isDeleted()) continue;
        if(fit.current()->type()==FT_TEXT)
        {
            if(i==num)
                return static_cast<KWTextFrameSet*>(fit.current());
            i++;
        }
    }
    return static_cast<KWTextFrameSet*>(m_lstFrameSet.getFirst());
}

void KWDocument::newZoomAndResolution( bool updateViews, bool forPrint )
{
    if ( KFormula::Document* formulaDocument = m_formulaDocumentWrapper->document() )
        formulaDocument->newZoomAndResolution( updateViews,forPrint );
#if 0
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
        fit.current()->zoom( forPrint );
#endif

    // First recalc all frames (including the kotextdocument width)
    updateAllFrames();
    // Then relayout the text inside the frames
    layout();
    if ( updateViews )
    {
        emit newContentsSize();
        repaintAllViews( true );
    }
}

bool KWDocument::initDoc(InitDocFlags flags, TQWidget* parentWidget)
{
    m_pageColumns.columns = 1;
    m_pageColumns.ptColumnSpacing = m_defaultColumnSpacing;

    m_pageHeaderFooter.header = HF_SAME;
    m_pageHeaderFooter.footer = HF_SAME;
    m_pageHeaderFooter.ptHeaderBodySpacing = 10;
    m_pageHeaderFooter.ptFooterBodySpacing = 10;
    m_pageHeaderFooter.ptFootNoteBodySpacing = 10;

    bool ok = FALSE;

    if ( isEmbedded() )
    {
      TQString fileName( locate( "kword_template", "Normal/.source/Embedded.kwt" , KWFactory::instance() ) );
      resetURL();
     ok = loadNativeFormat( fileName );
      if ( !ok )
        showLoadingErrorDialog();
      setEmpty();
      setModified( FALSE );
      return ok;
    }
    else if (flags==KoDocument::InitDocEmpty)
    {
        TQString fileName( locate( "kword_template", "Normal/.source/PlainText.kwt" , KWFactory::instance() ) );
        resetURL();
        ok = loadNativeFormat( fileName );
        if ( !ok )
            showLoadingErrorDialog();
        setEmpty();
        setModified( FALSE );
        return ok;
    }

    KoTemplateChooseDia::DialogType dlgtype;

    if (flags != KoDocument::InitDocFileNew)
        dlgtype = KoTemplateChooseDia::Everything;
    else
        dlgtype = KoTemplateChooseDia::OnlyTemplates;


    TQString file;
    KoTemplateChooseDia::ReturnType ret = KoTemplateChooseDia::choose(
        KWFactory::instance(), file,
        dlgtype, "kword_template", parentWidget );
    if ( ret == KoTemplateChooseDia::Template ) {
        resetURL();
        ok = loadNativeFormat( file );
        if ( !ok )
            showLoadingErrorDialog();
        setEmpty();
    } else if ( ret == KoTemplateChooseDia::File ) {
        KURL url( file );
        //kdDebug() << "KWDocument::initDoc opening URL " << url.prettyURL() << endl;
        ok = openURL( url );
    } else if ( ret == KoTemplateChooseDia::Empty ) {
        TQString fileName( locate( "kword_template", "Normal/.source/PlainText.kwt" , KWFactory::instance() ) );
        resetURL();
        ok = loadNativeFormat( fileName );
        if ( !ok )
            showLoadingErrorDialog();
        setEmpty();
    }
    setModified( FALSE );
    return ok;
}

void KWDocument::openExistingFile( const TQString& file )
{
  m_pageColumns.columns = 1;
  m_pageColumns.ptColumnSpacing = m_defaultColumnSpacing;

  m_pageHeaderFooter.header = HF_SAME;
  m_pageHeaderFooter.footer = HF_SAME;
  m_pageHeaderFooter.ptHeaderBodySpacing = 10;
  m_pageHeaderFooter.ptFooterBodySpacing = 10;
  m_pageHeaderFooter.ptFootNoteBodySpacing = 10;

  KoDocument::openExistingFile( file );
}

void KWDocument::openTemplate( const TQString& file )
{
  m_pageColumns.columns = 1;
  m_pageColumns.ptColumnSpacing = m_defaultColumnSpacing;

  m_pageHeaderFooter.header = HF_SAME;
  m_pageHeaderFooter.footer = HF_SAME;
  m_pageHeaderFooter.ptHeaderBodySpacing = 10;
  m_pageHeaderFooter.ptFooterBodySpacing = 10;
  m_pageHeaderFooter.ptFootNoteBodySpacing = 10;

  KoDocument::openTemplate( file );
}

void KWDocument::initEmpty()
{
    m_pageColumns.columns = 1;
    m_pageColumns.ptColumnSpacing = m_defaultColumnSpacing;

    m_pageHeaderFooter.header = HF_SAME;
    m_pageHeaderFooter.footer = HF_SAME;
    m_pageHeaderFooter.ptHeaderBodySpacing = 10;
    m_pageHeaderFooter.ptFooterBodySpacing = 10;
    m_pageHeaderFooter.ptFootNoteBodySpacing = 10;

    TQString fileName( locate( "kword_template", "Normal/.source/PlainText.kwt" , KWFactory::instance() ) );
    bool ok = loadNativeFormat( fileName );
    if ( !ok )
        showLoadingErrorDialog();
    resetURL();
    setModified( FALSE );
    setEmpty();
}

KoPageLayout KWDocument::pageLayout(int pageNumber /* = 0 */) const
{
    if( pageNumber < startPage()) // impossible page..
        pageNumber = startPage();
    return pageManager()->pageLayout(pageNumber);
}

void KWDocument::setPageLayout( const KoPageLayout& layout, const KoColumns& cl, const KoKWHeaderFooter& hf, bool updateViews )
{
    m_pageLayout = layout;
    if ( m_processingType == WP ) {
        m_pageColumns = cl;
    }
    if ( m_processingType == DTP || isEmbedded() ) {
        m_pageLayout.ptLeft = 0;
        m_pageLayout.ptRight = 0;
        m_pageLayout.ptTop = 0;
        m_pageLayout.ptBottom = 0;
    }
    pageManager()->setDefaultPage(m_pageLayout);
    m_pageHeaderFooter = hf;

    // pages have a different size -> update framesInPage
    // TODO: it would be better to move stuff so that text boxes remain in the same page...
    // (page-number preservation instead of Y preservation)
    updateAllFrames( KWFrameSet::UpdateFramesInPage );

    recalcFrames();

    updateAllFrames();

    if ( updateViews )
    {
        // Invalidate document layout, for proper repaint
        this->layout();
        emit pageLayoutChanged( m_pageLayout );
        updateContentsSize();
    }
}


double KWDocument::ptColumnWidth() const
{
    KWPage *page = pageManager()->page(pageManager()->startPage());
    return ( page->width() - page->leftMargin() - page->rightMargin() -
             ptColumnSpacing() * ( m_pageColumns.columns - 1 ) )
        / m_pageColumns.columns;
}

class KWFootNoteFrameSetList : public TQPtrList<KWFootNoteFrameSet>
{
public:
    KWFootNoteFrameSetList( bool reversed ) : m_reversed( reversed ) {}
protected:
    // Compare the order of the associated variables
    virtual int compareItems(TQPtrCollection::Item a, TQPtrCollection::Item b)
    {
        KWFootNoteFrameSet* fsa = ((KWFootNoteFrameSet *)a);
        KWFootNoteFrameSet* fsb = ((KWFootNoteFrameSet *)b);
        Q_ASSERT( fsa->footNoteVariable() );
        Q_ASSERT( fsb->footNoteVariable() );
        if ( fsa->footNoteVariable() && fsb->footNoteVariable() )
        {
            int numa = fsa->footNoteVariable()->num();
            int numb = fsb->footNoteVariable()->num();
            if (numa == numb) return 0;
            if (numa > numb) return m_reversed ? -1 : 1;
            return m_reversed ? 1 : -1;
        }
        return -1; // whatever
    }
private:
    bool m_reversed;
};

/* append headers and footers if needed, and create enough pages for all the existing frames */
void KWDocument::recalcFrames( int fromPage, int toPage /*-1 for all*/, uint flags )
{
    fromPage = TQMAX(pageManager()->startPage(), fromPage);
    if ( m_lstFrameSet.isEmpty() )
        return;
    //printDebug();
    kdDebug(32002) << "KWDocument::recalcFrames from=" << fromPage << " to=" << toPage << endl;

    KWFrameSet *frameset = m_lstFrameSet.getFirst();

    if ( m_processingType == WP ) { // In WP mode the pages are created automatically. In DTP not...

        KWTextFrameSet *firstHeader = 0L, *evenHeader = 0L, *oddHeader = 0L;
        KWTextFrameSet *firstFooter = 0L, *evenFooter = 0L, *oddFooter = 0L;
        m_bHasEndNotes = false; // will be set to true if we find any endnote

        // Lookup the various header / footer framesets into the variables above
        // [Done in all cases, in order to hide unused framesets]

        KWFootNoteFrameSetList footnotesList( true ); // Reversed, we want footnotes from bottom to top
        KWFootNoteFrameSetList endnotesList( false ); // Endnotes are in top to bottom order
        TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
        for ( ; fit.current() ; ++fit )
        {
            KWFrameSet * fs = fit.current();
            switch ( fs->frameSetInfo() ) {
            case KWFrameSet::FI_FIRST_HEADER:
                if ( isHeaderVisible() ) {
                    firstHeader = dynamic_cast<KWTextFrameSet*>( fs );
                } else { fs->setVisible( false ); fs->deleteAllCopies(); }
                break;
            case KWFrameSet::FI_ODD_HEADER:
                if ( isHeaderVisible() ) {
                    oddHeader = dynamic_cast<KWTextFrameSet*>( fs );
                } else { fs->setVisible( false ); fs->deleteAllCopies(); }
                break;
            case KWFrameSet::FI_EVEN_HEADER:
                if ( isHeaderVisible() ) {
                    evenHeader = dynamic_cast<KWTextFrameSet*>( fs );
                } else { fs->setVisible( false ); fs->deleteAllCopies(); }
                break;
            case KWFrameSet::FI_FIRST_FOOTER:
                if ( isFooterVisible() ) {
                    firstFooter = dynamic_cast<KWTextFrameSet*>( fs );
                } else { fs->setVisible( false ); fs->deleteAllCopies(); }
                break;
            case KWFrameSet::FI_ODD_FOOTER:
                if ( isFooterVisible() ) {
                    oddFooter = dynamic_cast<KWTextFrameSet*>( fs );
                } else { fs->setVisible( false ); fs->deleteAllCopies(); }
                break;
            case KWFrameSet::FI_EVEN_FOOTER:
                if ( isFooterVisible() ) {
                    evenFooter = dynamic_cast<KWTextFrameSet*>( fs );
                } else { fs->setVisible( false ); fs->deleteAllCopies(); }
                break;
            case KWFrameSet::FI_FOOTNOTE: {
                KWFootNoteFrameSet* fnfs = dynamic_cast<KWFootNoteFrameSet *>(fs);
                if ( fnfs && fnfs->isVisible() ) // not visible is when the footnote has been deleted
                {
                    if ( fnfs->isFootNote() )
                        footnotesList.append( fnfs );
                    else if ( fnfs->isEndNote() ) {
                        endnotesList.append( fnfs );
                        m_bHasEndNotes = true;
                    }
                }
            }
                break;
            default: break;
            }
        }

        // This allocation each time might slow things down a bit.
        // TODO KWHeaderFooterFrameSet : public KWTextFrameSet, and store the HeaderFooterFrameset data into there.
        // ... hmm, and then KWFootNoteFrameSet needs to inherit KWHeaderFooterFrameSet
        TQPtrList<KWFrameLayout::HeaderFooterFrameset> headerFooterList;
        headerFooterList.setAutoDelete( true );
        const int firstPageNum = startPage();

        // Now hide & forget the unused header/footer framesets (e.g. 'odd pages' if we are in 'all the same' mode etc.)
        if ( isHeaderVisible() ) {
            Q_ASSERT( firstHeader );
            Q_ASSERT( oddHeader );
            Q_ASSERT( evenHeader );
            switch ( headerType() ) {
            case HF_SAME:
                oddHeader->setVisible( true );
                evenHeader->setVisible( false );
                evenHeader->deleteAllCopies();
                firstHeader->setVisible( false );
                firstHeader->deleteAllCopies();

                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             oddHeader, firstPageNum, -1, m_pageHeaderFooter.ptHeaderBodySpacing ) );
                break;
            case HF_FIRST_EO_DIFF: // added for koffice-1.2-beta2
                firstHeader->setVisible( true );
                oddHeader->setVisible( true );
                evenHeader->setVisible( true );

                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             firstHeader, firstPageNum, firstPageNum, m_pageHeaderFooter.ptHeaderBodySpacing ) );
                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             oddHeader, firstPageNum + 2, -1, m_pageHeaderFooter.ptHeaderBodySpacing,
                                             KWFrameLayout::HeaderFooterFrameset::Odd ) );
                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             evenHeader, firstPageNum + 1, -1, m_pageHeaderFooter.ptHeaderBodySpacing,
                                             KWFrameLayout::HeaderFooterFrameset::Even ) );
                break;
            case HF_FIRST_DIFF:
                oddHeader->setVisible( true );
                evenHeader->setVisible( false );
                evenHeader->deleteAllCopies();
                firstHeader->setVisible( true );

                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             firstHeader, firstPageNum, firstPageNum, m_pageHeaderFooter.ptHeaderBodySpacing ) );
                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             oddHeader, firstPageNum + 1, -1, m_pageHeaderFooter.ptHeaderBodySpacing ) );
                break;
            case HF_EO_DIFF:
                oddHeader->setVisible( true );
                evenHeader->setVisible( true );
                firstHeader->setVisible( false );
                firstHeader->deleteAllCopies();

                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             oddHeader, firstPageNum, -1, m_pageHeaderFooter.ptHeaderBodySpacing,
                                             KWFrameLayout::HeaderFooterFrameset::Odd ) );
                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             evenHeader, firstPageNum + 1, -1, m_pageHeaderFooter.ptHeaderBodySpacing,
                                             KWFrameLayout::HeaderFooterFrameset::Even ) );
                break;
            }
        }
        if ( isFooterVisible() ) {
            Q_ASSERT( firstFooter );
            Q_ASSERT( oddFooter );
            Q_ASSERT( evenFooter );
            switch ( footerType() ) {
            case HF_SAME:
                oddFooter->setVisible( true );
                evenFooter->setVisible( false );
                evenFooter->deleteAllCopies();
                firstFooter->setVisible( false );
                firstFooter->deleteAllCopies();

                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             oddFooter, firstPageNum, -1, m_pageHeaderFooter.ptFooterBodySpacing ) );
                break;
            case HF_FIRST_EO_DIFF: // added for koffice-1.2-beta2
                firstFooter->setVisible( true );
                oddFooter->setVisible( true );
                evenFooter->setVisible( true );

                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             firstFooter, firstPageNum, firstPageNum, m_pageHeaderFooter.ptFooterBodySpacing ) );
                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             oddFooter, firstPageNum + 2, -1, m_pageHeaderFooter.ptFooterBodySpacing,
                                             KWFrameLayout::HeaderFooterFrameset::Odd ) );
                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             evenFooter, firstPageNum + 1, -1, m_pageHeaderFooter.ptFooterBodySpacing,
                                             KWFrameLayout::HeaderFooterFrameset::Even ) );
                break;
            case HF_FIRST_DIFF:
                oddFooter->setVisible( true );
                evenFooter->setVisible( false );
                evenFooter->deleteAllCopies();
                firstFooter->setVisible( true );

                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             firstFooter, firstPageNum, firstPageNum, m_pageHeaderFooter.ptFooterBodySpacing ) );
                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             oddFooter, firstPageNum + 1, -1, m_pageHeaderFooter.ptFooterBodySpacing ) );
                break;
            case HF_EO_DIFF:
                oddFooter->setVisible( true );
                evenFooter->setVisible( true );
                firstFooter->setVisible( false );
                firstFooter->deleteAllCopies();

                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             oddFooter, firstPageNum, -1, m_pageHeaderFooter.ptFooterBodySpacing,
                                             KWFrameLayout::HeaderFooterFrameset::Odd ) );
                headerFooterList.append( new KWFrameLayout::HeaderFooterFrameset(
                                             evenFooter, firstPageNum + 1, -1, m_pageHeaderFooter.ptFooterBodySpacing,
                                             KWFrameLayout::HeaderFooterFrameset::Even ) );
                break;
            }
        }

        // The frameset order _on screen_ is:
        // Header
        // Main text frame (if WP)
        // Footnote_s_
        // Footer
        // In the list it will have to be from top and from bottom:
        // Header, Footer, Footnote from bottom to top
        TQPtrList<KWFrameLayout::HeaderFooterFrameset> footnotesHFList;
        footnotesHFList.setAutoDelete( true );

        footnotesList.sort();
        TQPtrListIterator<KWFootNoteFrameSet> fnfsIt( footnotesList );  // fnfs == "footnote frameset"
        for ( ; fnfsIt.current() ; ++fnfsIt )
        {
            KWFootNoteFrameSet* fnfs = fnfsIt.current();
            int pageNum = -42; //fnfs->footNoteVariable()->pageNumber(); // determined by KWFrameLayout
            KWFrameLayout::HeaderFooterFrameset* hff = new KWFrameLayout::HeaderFooterFrameset(
                fnfs, pageNum, pageNum,
                m_pageHeaderFooter.ptFootNoteBodySpacing,
                KWFrameLayout::HeaderFooterFrameset::All );

            // With other kind of framesets, the height is simply frame->height.
            // But for footnotes, the height to pass to KWFrameLayout is the sum of the frame heights.
            hff->m_height = 0;
            for (TQPtrListIterator<KWFrame> f = fnfs->frameIterator(); f.current() ; ++f )
                hff->m_height += f.current()->height();

            footnotesHFList.append( hff );
        }

        // Endnotes, however are laid out from top to bottom.
        TQPtrList<KWFrameLayout::HeaderFooterFrameset> endnotesHFList;
        endnotesHFList.setAutoDelete( true );

        endnotesList.sort();
        TQPtrListIterator<KWFootNoteFrameSet> enfsIt( endnotesList );  // enfs == "endnote frameset"
        for ( ; enfsIt.current() ; ++enfsIt )
        {
            KWFootNoteFrameSet* enfs = enfsIt.current();
            KWFrameLayout::HeaderFooterFrameset* hff = new KWFrameLayout::HeaderFooterFrameset(
                enfs, -42, -42, // determined by KWFrameLayout
                m_pageHeaderFooter.ptFootNoteBodySpacing,
                KWFrameLayout::HeaderFooterFrameset::All );

            // The height to pass to KWFrameLayout is the sum of the frame heights.
            hff->m_height = 0;
            for (TQPtrListIterator<KWFrame> f = enfs->frameIterator(); f.current() ; ++f )
                hff->m_height += f.current()->height();

            endnotesHFList.append( hff );
        }

        // append pages as needed.
        double maxBottom = 0;
        for (TQPtrListIterator<KWFrameSet> fsit = framesetsIterator(); fsit.current() ; ++fsit ) {
            KWFrameSet *fs = fsit.current();
            if ( !fs->isVisible() || fs->isAHeader() || !fs->isAFooter() ||
                    !fs->isFloating() || !fs->isFootEndNote() )
                continue;
            for (TQPtrListIterator<KWFrame> fit = fs->frameIterator(); fit.current() ; ++fit )
                maxBottom = TQMAX(maxBottom, fit.current()->bottom());
        }
        KWPage *last = pageManager()->page(lastPage());
        double docHeight = last->offsetInDocument() + last->height();
        while(docHeight <= maxBottom) {
            last = pageManager()->appendPage();
            docHeight += last->height();
        }
        int oldPages = pageCount();

        if ( toPage == -1 )
            toPage = lastPage();
        if ( fromPage > toPage ) // this can happen with "endnotes only" pages :) // ### really?
            fromPage = toPage; // ie. start at the last real page
        KWFrameLayout frameLayout( this, headerFooterList, footnotesHFList, endnotesHFList );
        frameLayout.layout( frameset, m_pageColumns.columns, fromPage, toPage, flags );

        // If the number of pages changed, update views and variables etc.
        // (now that the frame layout has been done)
        if ( pageCount() != oldPages && !m_bGeneratingPreview )
        {
            // Very much like the end of appendPage, but we don't want to call recalcFrames ;)
            emit newContentsSize();
            emit numPagesChanged();
            recalcVariables( VT_PGNUM );
        }

    }
    else {
        // DTP mode: calculate the number of pages from the frames.
        double maxBottom=0;
        for (TQPtrListIterator<KWFrameSet> fit = framesetsIterator(); fit.current() ; ++fit ) {
            if(fit.current()->isDeleted()) continue;
            if(fit.current()->frameSetInfo()==KWFrameSet::FI_BODY && !fit.current()->isFloating()) {
                KWFrameSet * fs = fit.current();
                for (TQPtrListIterator<KWFrame> f = fs->frameIterator(); f.current() ; ++f )
                    maxBottom=TQMAX(maxBottom, f.current()->bottom());
            }
        }
        KWPage *last = pageManager()->page(lastPage());
        Q_ASSERT(last);
        if(last) { // hack to work around bug #132338
            double docHeight = last->offsetInDocument() + last->height();
            while(docHeight <= maxBottom) {
                last = pageManager()->appendPage();
                docHeight += last->height();
            }
        }
        if ( toPage == -1 )
            toPage = pageCount() - 1;
        KWFrameList::recalcFrames(this, fromPage, toPage);
    }
    kdDebug(32002) << "            ~recalcFrames" << endl;
}

bool KWDocument::loadChildren( KoStore *store )
{
    //kdDebug(32001) << "KWDocument::loadChildren" << endl;
    TQPtrListIterator<KoDocumentChild> it( children() );
    for( ; it.current(); ++it ) {
        if ( !it.current()->loadDocument( store ) )
            return FALSE;
    }

    return TRUE;
}

void KWDocument::loadPictureMap ( TQDomElement& domElement )
{
    m_pictureMap.clear();

    // <PICTURES>
    TQDomElement picturesElem = domElement.namedItem( "PICTURES" ).toElement();
    if ( !picturesElem.isNull() )
    {
       m_pictureCollection->readXML( picturesElem, m_pictureMap );
    }

    // <PIXMAPS>
    TQDomElement pixmapsElem = domElement.namedItem( "PIXMAPS" ).toElement();
    if ( !pixmapsElem.isNull() )
    {
       m_pictureCollection->readXML( pixmapsElem, m_pictureMap );
    }

    // <CLIPARTS>
    TQDomElement clipartsElem = domElement.namedItem( "CLIPARTS" ).toElement();
    if ( !clipartsElem.isNull() )
    {
       m_pictureCollection->readXML( pixmapsElem, m_pictureMap );
    }
}


bool KWDocument::loadOasis( const TQDomDocument& doc, KoOasisStyles& oasisStyles, const TQDomDocument& settings, KoStore* store )
{
    TQTime dt;
    dt.start();
    emit sigProgress( 0 );
    clear();
    kdDebug(32001) << "KWDocument::loadOasis" << endl;

    TQDomElement content = doc.documentElement();
    TQDomElement realBody ( KoDom::namedItemNS( content, KoXmlNS::office, "body" ) );
    if ( realBody.isNull() )
    {
        kdError(32001) << "No office:body found!" << endl;
        setErrorMessage( i18n( "Invalid OASIS OpenDocument file. No office:body tag found." ) );
        return false;
    }
    TQDomElement body = KoDom::namedItemNS( realBody, KoXmlNS::office, "text" );
    if ( body.isNull() )
    {
        kdError(32001) << "No office:text found!" << endl;
        TQDomElement childElem;
        TQString localName;
        forEachElement( childElem, realBody ) {
            localName = childElem.localName();
        }
        if ( localName.isEmpty() )
            setErrorMessage( i18n( "Invalid OASIS OpenDocument file. No tag found inside office:body." ) );
        else
            setErrorMessage( i18n( "This is not a word processing document, but %1. Please try opening it with the appropriate application." ).arg( KoDocument::tagNameToDocumentType( localName ) ) );
        return false;
    }

    // TODO check versions and mimetypes etc.

    KoOasisContext context( this, *m_varColl, oasisStyles, store );

    createLoadingInfo();

    // In theory the page format is the style:master-page-name of the first paragraph...
    // But, hmm, in a doc with only a table there was no reference to the master page at all...
    // So we load the standard page layout to start with, and in KWTextParag
    // we might overwrite it with another one.
    m_loadingInfo->m_currentMasterPage = "Standard";
    if ( !loadOasisPageLayout( m_loadingInfo->m_currentMasterPage, context ) )
        return false;

    KWOasisLoader oasisLoader( this );

    // <text:page-sequence> oasis extension for DTP (2003-10-27 post by Daniel)
    m_processingType = ( !KoDom::namedItemNS( body, KoXmlNS::text, "page-sequence" ).isNull() )
                       ? DTP : WP;

    m_hasTOC = false;
    m_tabStop = MM_TO_POINT(15);
    const TQDomElement* defaultParagStyle = oasisStyles.defaultStyle( "paragraph" );
    if ( defaultParagStyle ) {
        KoStyleStack stack;
        stack.push( *defaultParagStyle );
        stack.setTypeProperties( "paragraph" );
        TQString tabStopVal = stack.attributeNS( KoXmlNS::style, "tab-stop-distance" );
        if ( !tabStopVal.isEmpty() )
            m_tabStop = KoUnit::parseValue( tabStopVal );
    }
    m_initialEditing = 0;

    // TODO MAILMERGE

    // Variable settings
    // By default display real variable value
    if ( !isReadWrite())
        m_varColl->variableSetting()->setDisplayFieldCode(false);

    // Load all styles before the corresponding paragraphs try to use them!
    m_styleColl->loadOasisStyles( context );
    if ( m_frameStyleColl->loadOasisStyles( context ) == 0 ) {
         // no styles loaded -> load default styles
        loadDefaultFrameStyleTemplates();
    }

    if ( m_tableStyleColl->loadOasisStyles( context, *m_styleColl, *m_frameStyleColl ) == 0 ) {
        // no styles loaded -> load default styles
        loadDefaultTableStyleTemplates();
    }

    static_cast<KWVariableSettings *>( m_varColl->variableSetting() )
        ->loadNoteConfiguration( oasisStyles.officeStyle() );

    loadDefaultTableTemplates();

    if ( m_processingType == WP ) {
        // Create main frameset
        KWTextFrameSet *fs = new KWTextFrameSet( this, i18n( "Main Text Frameset" ) );
        m_lstFrameSet.append( fs ); // don't use addFrameSet here. We'll call finalize() once and for all in completeLoading
        fs->loadOasisContent( body, context );
        KWFrame* frame = new KWFrame( fs, 29, 42, 566-29, 798-42 );
        frame->setFrameBehavior( KWFrame::AutoCreateNewFrame );
        frame->setNewFrameBehavior( KWFrame::Reconnect );
        fs->addFrame( frame );

        // load padding, background and borders for the main frame
        const TQDomElement* masterPage = context.oasisStyles().masterPages()[ m_loadingInfo->m_currentMasterPage ];
        const TQDomElement *masterPageStyle = masterPage ? context.oasisStyles().findStyle(masterPage->attributeNS( KoXmlNS::style, "page-layout-name", TQString() ) ) : 0;
        if ( masterPageStyle )
        {
          KoStyleStack styleStack;
          styleStack.push(  *masterPageStyle );
          styleStack.setTypeProperties( "page-layout" );
          frame->loadBorderProperties( styleStack );
        }
        fs->renumberFootNotes( false /*no repaint*/ );

    } else {
        // DTP mode: the items in the body are page-sequence and then frames
        TQDomElement tag;
        forEachElement( tag, body )
        {
            context.styleStack().save();
            const TQString localName = tag.localName();
            if ( localName == "page-sequence" && tag.namespaceURI() == KoXmlNS::text )
            {
                // We don't have support for changing the page layout yet, so just take the
                // number of pages
                int pages=1;
                TQDomElement page;
                forEachElement( page, tag )
                    ++pages;
                kdDebug() << "DTP mode: found " << pages << "pages" << endl;
                //setPageCount ( pages );
            }
            else if ( localName == "frame" && tag.namespaceURI() == KoXmlNS::draw )
                oasisLoader.loadFrame( tag, context, KoPoint() );
            else
                kdWarning(32001) << "Unsupported tag in DTP loading:" << tag.tagName() << endl;
        }
    }

    if ( !loadMasterPageStyle( m_loadingInfo->m_currentMasterPage, context ) )
        return false;

    if ( context.cursorTextParagraph() ) {
        // Maybe, once 1.3-support is dropped, we can get rid of InitialEditing and fetch the
        // values from KoOasisContext? But well, it lives a bit longer.
        // At least we could store a KWFrameSet* and a KoTextParag* instead of a name and an id.
        m_initialEditing = new InitialEditing();
        KWTextFrameSet* fs = static_cast<KWTextDocument *>( context.cursorTextParagraph()->textDocument() )->textFrameSet();
        m_initialEditing->m_initialFrameSet = fs->name();
        m_initialEditing->m_initialCursorParag = context.cursorTextParagraph()->paragId();
        m_initialEditing->m_initialCursorIndex = context.cursorTextIndex();
    }

    if ( !settings.isNull() )
    {
        oasisLoader.loadOasisSettings( settings );
    }

    kdDebug(32001) << "Loading took " << (float)(dt.elapsed()) / 1000 << " seconds" << endl;
    endOfLoading();

    // This sets the columns and header/footer flags, and calls recalcFrames,
    // so it must be done last.
    setPageLayout( m_pageLayout, m_loadingInfo->columns, m_loadingInfo->hf, false );

    //printDebug();
    return true;
}

bool KWDocument::loadOasisPageLayout( const TQString& masterPageName, KoOasisContext& context )
{
    KoColumns& columns = m_loadingInfo->columns;

    const KoOasisStyles& oasisStyles = context.oasisStyles();
    const TQDomElement* masterPage = oasisStyles.masterPages()[ masterPageName ];
    Q_ASSERT( masterPage );
    const TQDomElement *masterPageStyle = masterPage ? oasisStyles.findStyle( masterPage->attributeNS( KoXmlNS::style, "page-layout-name", TQString() ) ) : 0;
    Q_ASSERT( masterPageStyle );
    if ( masterPageStyle )
    {
        m_pageLayout.loadOasis( *masterPageStyle );
        pageManager()->setDefaultPage(m_pageLayout);

        const TQDomElement properties( KoDom::namedItemNS( *masterPageStyle, KoXmlNS::style, "page-layout-properties" ) );
        const TQDomElement footnoteSep = KoDom::namedItemNS( properties, KoXmlNS::style, "footnote-sep" );
        if ( !footnoteSep.isNull() ) {
            // style:width="0.018cm" style:distance-before-sep="0.101cm"
            // style:distance-after-sep="0.101cm" style:adjustment="left"
            // style:rel-width="25%" style:color="#000000"
            const TQString width = footnoteSep.attributeNS( KoXmlNS::style, "width", TQString() );
            if ( !width.isEmpty() ) {
                m_footNoteSeparatorLineWidth = KoUnit::parseValue( width );
            }

            TQString pageWidth = footnoteSep.attributeNS( KoXmlNS::style, "rel-width", TQString() );
            if ( pageWidth.endsWith( "%" ) ) {
                pageWidth.truncate( pageWidth.length() - 1 ); // remove '%'
                m_iFootNoteSeparatorLineLength = tqRound( pageWidth.toDouble() );
            }
            // Not in KWord: color, distance before and after separator

            const TQString style = footnoteSep.attributeNS( KoXmlNS::style, "line-style", TQString() );
            if ( style == "solid" || style.isEmpty() )
                m_footNoteSeparatorLineType = SLT_SOLID;
            else if ( style == "dash" )
                m_footNoteSeparatorLineType = SLT_DASH;
            else if ( style == "dotted" )
                m_footNoteSeparatorLineType = SLT_DOT;
            else if ( style == "dot-dash" )
                m_footNoteSeparatorLineType = SLT_DASH_DOT;
            else if ( style == "dot-dot-dash" )
                m_footNoteSeparatorLineType = SLT_DASH_DOT_DOT;
            else
                kdDebug() << "Unknown value for m_footNoteSeparatorLineType: " << style << endl;

            const TQString pos = footnoteSep.attributeNS( KoXmlNS::style, "adjustment", TQString() );
            if ( pos == "centered" )
                m_footNoteSeparatorLinePos = SLP_CENTERED;
            else if ( pos == "right")
                m_footNoteSeparatorLinePos = SLP_RIGHT;
            else // if ( pos == "left" )
                m_footNoteSeparatorLinePos = SLP_LEFT;
        }

        const TQDomElement columnsElem = KoDom::namedItemNS( properties, KoXmlNS::style, "columns" );
        if ( !columnsElem.isNull() )
        {
            columns.columns = columnsElem.attributeNS( KoXmlNS::fo, "column-count", TQString() ).toInt();
            if ( columns.columns == 0 )
                columns.columns = 1;
            // TODO OASIS OpenDocument supports columns of different sizes, using <style:column style:rel-width="...">
            // (with fo:start-indent/fo:end-indent for per-column spacing)
            // But well, it also allows us to specify a single gap.
            if ( columnsElem.hasAttributeNS( KoXmlNS::fo, "column-gap" ) )
                columns.ptColumnSpacing = KoUnit::parseValue( columnsElem.attributeNS( KoXmlNS::fo, "column-gap", TQString() ) );
            // It also supports drawing a vertical line as a separator...
        }

        m_headerVisible = false;
        m_footerVisible = false;

        // TODO spHeadBody (where is this in OOo?)
        // TODO spFootBody (where is this in OOo?)
        // Answer: margins of the <style:header-footer> element
    }
    else // this doesn't happen with normal documents, but it can happen if copying something,
         // pasting into konq as foo.odt, then opening that...
    {
        columns.columns = 1;
        columns.ptColumnSpacing = 2;
        m_headerVisible = false;
        m_footerVisible = false;
        m_pageLayout = KoPageLayout::standardLayout();
        pageManager()->setDefaultPage(m_pageLayout);
    }
    return true;
}

bool KWDocument::loadMasterPageStyle( const TQString& masterPageName, KoOasisContext& context )
{
    const KoOasisStyles& oasisStyles = context.oasisStyles();
    const TQDomElement* masterPage = oasisStyles.masterPages()[ masterPageName ];
    Q_ASSERT( masterPage );
    const TQDomElement *masterPageStyle = masterPage ? oasisStyles.findStyle( masterPage->attributeNS( KoXmlNS::style, "page-layout-name", TQString() ) ) : 0;
    Q_ASSERT( masterPageStyle );

    // This check is done here and not in loadOasisPageLayout in case the Standard master-page
    // has no page information but the first paragraph points to a master-page that does (#129585)
    if ( m_pageLayout.ptWidth <= 1e-13 || m_pageLayout.ptHeight <= 1e-13 )
    {
        // Loading page layout failed, try to see why.
        TQDomElement properties( KoDom::namedItemNS( *masterPageStyle, KoXmlNS::style, "page-layout-properties" ) );
        //if ( properties.isNull() )
        //    setErrorMessage( i18n( "Invalid document. No page layout properties were found. The application which produced this document isn't OASIS-compliant." ) );
        //else if ( properties.hasAttributeNS( KoXmlNS::fo, "page-width" ) )
        //    setErrorMessage( i18n( "Invalid document. Page layout has no page width. The application which produced this document isn't OASIS-compliant." ) );
        //else
        if ( properties.hasAttributeNS( "http://www.w3.org/1999/XSL/Format", "page-width" ) )
            setErrorMessage( i18n( "Invalid document. 'fo' has the wrong namespace. The application which produced this document is not OASIS-compliant." ) );
        else
            setErrorMessage( i18n( "Invalid document. Paper size: %1x%2" ).arg( m_pageLayout.ptWidth ).arg( m_pageLayout.ptHeight ) );
        return false;
    }


    KoKWHeaderFooter& hf = m_loadingInfo->hf;

    bool hasEvenOddHeader = false;
    bool hasEvenOddFooter = false;
    if ( masterPageStyle )
    {
        KWOasisLoader oasisLoader( this );

        TQDomElement headerStyle = KoDom::namedItemNS( *masterPageStyle, KoXmlNS::style, "header-style" );
        TQDomElement footerStyle = KoDom::namedItemNS( *masterPageStyle, KoXmlNS::style, "footer-style" );
        TQDomElement headerLeftElem = KoDom::namedItemNS( *masterPage, KoXmlNS::style, "header-left" );
        TQDomElement headerFirstElem = KoDom::namedItemNS( *masterPage, KoXmlNS::style, "header-first" ); // hack, not oasis compliant
        const bool hasFirstHeader = !headerFirstElem.isNull();
        if ( !headerLeftElem.isNull() )
        {
            hasEvenOddHeader = true;
            hf.header = hasFirstHeader ? HF_FIRST_EO_DIFF : HF_EO_DIFF;
            oasisLoader.loadOasisHeaderFooter( headerLeftElem, hasEvenOddHeader, headerStyle, context );
        }
        else
        {
            hf.header = hasFirstHeader ? HF_FIRST_DIFF : HF_SAME;
        }
        if ( hasFirstHeader )
        {
            oasisLoader.loadOasisHeaderFooter( headerFirstElem, hasEvenOddHeader, headerStyle, context );
        }

        TQDomElement headerElem = KoDom::namedItemNS( *masterPage, KoXmlNS::style, "header" );
        if ( !headerElem.isNull() )
        {
            oasisLoader.loadOasisHeaderFooter( headerElem, hasEvenOddHeader, headerStyle, context );
        }

        // -- and now footers

        TQDomElement footerLeftElem = KoDom::namedItemNS( *masterPage, KoXmlNS::style, "footer-left" );
        TQDomElement footerFirstElem = KoDom::namedItemNS( *masterPage, KoXmlNS::style, "footer-first" ); // hack, not oasis compliant
        const bool hasFirstFooter = !footerFirstElem.isNull();
        if ( !footerLeftElem.isNull() )
        {
            hasEvenOddFooter = true;
            hf.footer = hasFirstFooter ? HF_FIRST_EO_DIFF : HF_EO_DIFF;
            oasisLoader.loadOasisHeaderFooter( footerLeftElem, hasEvenOddFooter, footerStyle, context );
        }
        else
        {
            hf.footer = hasFirstFooter ? HF_FIRST_DIFF : HF_SAME;
        }
        if ( hasFirstFooter )
        {
            oasisLoader.loadOasisHeaderFooter( footerFirstElem, hasEvenOddFooter, footerStyle, context );
        }
        TQDomElement footerElem = KoDom::namedItemNS( *masterPage, KoXmlNS::style, "footer" );
        if ( !footerElem.isNull() )
        {
            oasisLoader.loadOasisHeaderFooter( footerElem, hasEvenOddFooter, footerStyle, context );
        }

        // The bottom margin of headers is what we call headerBodySpacing
        // (TODO support the 3 other margins)
        if ( !headerStyle.isNull() ) {
            context.styleStack().push( headerStyle );
            context.styleStack().setTypeProperties( "header-footer" );
            hf.ptHeaderBodySpacing = KoUnit::parseValue( context.styleStack().attributeNS( KoXmlNS::fo, "margin-bottom" ) );
            context.styleStack().pop();
        }
        // The top margin of footers is what we call footerBodySpacing
        // (TODO support the 3 other margins)
        if ( !footerStyle.isNull() ) {
            context.styleStack().push( footerStyle );
            context.styleStack().setTypeProperties( "header-footer" );
            hf.ptFooterBodySpacing = KoUnit::parseValue( context.styleStack().attributeNS( KoXmlNS::fo, "margin-top" ) );
            context.styleStack().pop();
        }
        // TODO ptFootNoteBodySpacing
    }
    return true;
}

// Called before loading
// It's important to clear out anything that might be in the document already,
// for things like using DCOP to load multiple documents into the same KWDocument,
// or "reload" when kword is embedded into konqueror.
void KWDocument::clear()
{
    m_pictureMap.clear();
    m_textImageRequests.clear();
    m_pictureRequests.clear();
    m_anchorRequests.clear();
    m_footnoteVarRequests.clear();
    m_spellCheckIgnoreList.clear();

    m_pageHeaderFooter.header = HF_SAME;
    m_pageHeaderFooter.footer = HF_SAME;
    m_pageHeaderFooter.ptHeaderBodySpacing = 10;
    m_pageHeaderFooter.ptFooterBodySpacing = 10;
    m_pageHeaderFooter.ptFootNoteBodySpacing = 10;
    m_pageColumns.columns = 1;
    m_pageColumns.ptColumnSpacing = m_defaultColumnSpacing;
    m_bHasEndNotes = false;

    m_iFootNoteSeparatorLineLength = 20; // 20%, i.e. 1/5th
    m_footNoteSeparatorLineWidth = 0.5; // like in OOo
    m_footNoteSeparatorLineType = SLT_SOLID;

    m_lstFrameSet.clear();

    m_varColl->clear();
    m_pictureCollection->clear();
    m_varFormatCollection->clear();

    m_styleColl->clear();
    m_frameStyleColl->clear();
    m_tableStyleColl->clear();
    m_tableTemplateColl->clear();

    // Some simple import filters don't define any style,
    // so let's have a Standard style at least
    KoParagStyle * standardStyle = new KoParagStyle( "Standard" ); // This gets translated later on
    //kdDebug() << "KWDocument::KWDocument creating standardStyle " << standardStyle << endl;
    standardStyle->format().setFont( m_defaultFont );
    m_styleColl->addStyle( standardStyle );

    // And let's do the same for framestyles
    KWFrameStyle * standardFrameStyle = new KWFrameStyle( "Plain" );
    standardFrameStyle->setBackgroundColor(TQt::white);
    standardFrameStyle->setTopBorder(KoBorder(TQt::black,KoBorder::SOLID,0));
    standardFrameStyle->setRightBorder(KoBorder(TQt::black,KoBorder::SOLID,0));
    standardFrameStyle->setLeftBorder(KoBorder(TQt::black,KoBorder::SOLID,0));
    standardFrameStyle->setBottomBorder(KoBorder(TQt::black,KoBorder::SOLID,0));
    m_frameStyleColl->addStyle( standardFrameStyle );

    // And let's do the same for tablestyles
    KWTableStyle *standardTableStyle = new KWTableStyle( "Plain", standardStyle, standardFrameStyle );
    m_tableStyleColl->addStyle( standardTableStyle );
}

bool KWDocument::loadXML( TQIODevice *, const TQDomDocument & doc )
{
    TQTime dt;
    dt.start();
    emit sigProgress( 0 );
    kdDebug(32001) << "KWDocument::loadXML" << endl;
    clear();

    KoPageLayout pgLayout;
    KoColumns columns;
    columns.columns = 1;
    columns.ptColumnSpacing = m_defaultColumnSpacing;
    KoKWHeaderFooter hf;
    hf.header = HF_SAME;
    hf.footer = HF_SAME;
    hf.ptHeaderBodySpacing = 10.0;
    hf.ptFooterBodySpacing = 10.0;
    hf.ptFootNoteBodySpacing = 10.0;

    TQString value;
    TQDomElement word = doc.documentElement();

    value = KWDocument::getAttribute( word, "mime", TQString() );
    if ( value.isEmpty() )
    {
        kdError(32001) << "No mime type specified!" << endl;
        setErrorMessage( i18n( "Invalid document. No mimetype specified." ) );
        return false;
    }
    else if ( value != "application/x-kword" && value != "application/vnd.kde.kword" )
    {
        kdError(32001) << "Unknown mime type " << value << endl;
        setErrorMessage( i18n( "Invalid document. Expected mimetype application/x-kword or application/vnd.kde.kword, got %1" ).arg( value ) );
        return false;
    }
    m_syntaxVersion = KWDocument::getAttribute( word, "syntaxVersion", 0 );
    if ( m_syntaxVersion > CURRENT_SYNTAX_VERSION )
    {
        int ret = KMessageBox::warningContinueCancel(
            0, i18n("This document was created with a newer version of KWord (syntax version: %1)\n"
                    "Opening it in this version of KWord will lose some information.").arg(m_syntaxVersion),
            i18n("File Format Mismatch"), KStdGuiItem::cont() );
        if ( ret == KMessageBox::Cancel )
        {
            setErrorMessage( "USER_CANCELED" );
            return false;
        }
    }

    createLoadingInfo();

    // Looks like support for the old way of naming images internally,
    // see completeLoading.
    value = KWDocument::getAttribute( word, "url", TQString() );
    if ( !value.isNull() )
    {
        m_urlIntern = KURL( value ).path();
    }

    emit sigProgress(5);

    // <PAPER>
    TQDomElement paper = word.namedItem( "PAPER" ).toElement();
    if ( !paper.isNull() )
    {
        pgLayout.format = static_cast<KoFormat>( KWDocument::getAttribute( paper, "format", 0 ) );
        pgLayout.orientation = static_cast<KoOrientation>( KWDocument::getAttribute( paper, "orientation", 0 ) );
        pgLayout.ptWidth = getAttribute( paper, "width", 0.0 );
        pgLayout.ptHeight = getAttribute( paper, "height", 0.0 );
        kdDebug() << " ptWidth=" << pgLayout.ptWidth << endl;
        kdDebug() << " ptHeight=" << pgLayout.ptHeight << endl;
        if ( pgLayout.ptWidth <= 0 || pgLayout.ptHeight <= 0 )
        {
            // Old document?
            pgLayout.ptWidth = getAttribute( paper, "ptWidth", 0.0 );
            pgLayout.ptHeight = getAttribute( paper, "ptHeight", 0.0 );
            kdDebug() << " ptWidth=" << pgLayout.ptWidth << endl;
            kdDebug() << " ptHeight=" << pgLayout.ptHeight << endl;

            // Still wrong?
            if ( pgLayout.ptWidth <= 0 || pgLayout.ptHeight <= 0 )
            {
                setErrorMessage( i18n( "Invalid document. Paper size: %1x%2" )
                    .arg( pgLayout.ptWidth ).arg( pgLayout.ptHeight ) );
                return false;
            }
        }

        hf.header = static_cast<KoHFType>( KWDocument::getAttribute( paper, "hType", 0 ) );
        hf.footer = static_cast<KoHFType>( KWDocument::getAttribute( paper, "fType", 0 ) );
        hf.ptHeaderBodySpacing = getAttribute( paper, "spHeadBody", 0.0 );
        hf.ptFooterBodySpacing  = getAttribute( paper, "spFootBody", 0.0 );
        hf.ptFootNoteBodySpacing  = getAttribute( paper, "spFootNoteBody", 10.0 );
        m_iFootNoteSeparatorLineLength = getAttribute( paper, "slFootNoteLength", 20);
        if ( paper.hasAttribute( "slFootNoteWidth" ) )
            m_footNoteSeparatorLineWidth = paper.attribute( "slFootNoteWidth" ).toDouble();
        m_footNoteSeparatorLineType = static_cast<SeparatorLineLineType>(getAttribute( paper, "slFootNoteType",0));

        if ( paper.hasAttribute("slFootNotePosition"))
        {
            TQString tmp =paper.attribute("slFootNotePosition");
            if ( tmp =="centered" )
                m_footNoteSeparatorLinePos = SLP_CENTERED;
            else if ( tmp =="right")
                m_footNoteSeparatorLinePos = SLP_RIGHT;
            else if ( tmp =="left" )
                m_footNoteSeparatorLinePos = SLP_LEFT;
        }
        columns.columns = KWDocument::getAttribute( paper, "columns", 1 );
        columns.ptColumnSpacing = KWDocument::getAttribute( paper, "columnspacing", 0.0 );
        // Now part of the app config
        //m_zoom = KWDocument::getAttribute( paper, "zoom", 100 );
        //if(m_zoom!=100)
        //    setZoomAndResolution( m_zoom, KoGlobal::dpiX(), KoGlobal::dpiY(), false, false );


        // Support the undocumented syntax actually used by KDE 2.0 for some of the above (:-().
        // Do not add anything to this block!
        if ( pgLayout.ptWidth == 0.0 )
            pgLayout.ptWidth = getAttribute( paper, "ptWidth", 0.0 );
        if ( pgLayout.ptHeight == 0.0 )
            pgLayout.ptHeight = getAttribute( paper, "ptHeight", 0.0 );
        if ( hf.ptHeaderBodySpacing == 0.0 )
            hf.ptHeaderBodySpacing = getAttribute( paper, "ptHeadBody", 0.0 );
        if ( hf.ptFooterBodySpacing == 0.0 )
            hf.ptFooterBodySpacing = getAttribute( paper, "ptFootBody", 0.0 );
        if ( columns.ptColumnSpacing == 0.0 )
            columns.ptColumnSpacing = getAttribute( paper, "ptColumnspc", 0.0 );

        // <PAPERBORDERS>
        TQDomElement paperborders = paper.namedItem( "PAPERBORDERS" ).toElement();
        if ( !paperborders.isNull() )
        {
            pgLayout.ptLeft = getAttribute( paperborders, "left", 0.0 );
            pgLayout.ptTop = getAttribute( paperborders, "top", 0.0 );
            pgLayout.ptRight = getAttribute( paperborders, "right", 0.0 );
            pgLayout.ptBottom = getAttribute( paperborders, "bottom", 0.0 );

            // Support the undocumented syntax actually used by KDE 2.0 for some of the above (:-().
            if ( pgLayout.ptLeft == 0.0 )
                pgLayout.ptLeft = getAttribute( paperborders, "ptLeft", 0.0 );
            if ( pgLayout.ptTop == 0.0 )
                pgLayout.ptTop = getAttribute( paperborders, "ptTop", 0.0 );
            if ( pgLayout.ptRight == 0.0 )
                pgLayout.ptRight = getAttribute( paperborders, "ptRight", 0.0 );
            if ( pgLayout.ptBottom == 0.0 )
                pgLayout.ptBottom = getAttribute( paperborders, "ptBottom", 0.0 );
        }
        else
            kdWarning() << "No <PAPERBORDERS> tag!" << endl;
    }
    else
        kdWarning() << "No <PAPER> tag! This is a mandatory tag! Expect weird page sizes..." << endl;

    // <ATTRIBUTES>
    TQDomElement attributes = word.namedItem( "ATTRIBUTES" ).toElement();
    if ( !attributes.isNull() )
    {
        m_processingType = static_cast<ProcessingType>( KWDocument::getAttribute( attributes, "processing", 0 ) );
        //KWDocument::getAttribute( attributes, "standardpage", TQString() );
        m_headerVisible = static_cast<bool>( KWDocument::getAttribute( attributes, "hasHeader", 0 ) );
        m_footerVisible = static_cast<bool>( KWDocument::getAttribute( attributes, "hasFooter", 0 ) );
        if ( attributes.hasAttribute( "unit" ) )
            setUnit( KoUnit::unit( attributes.attribute( "unit" ) ) );
        m_hasTOC =  static_cast<bool>(KWDocument::getAttribute( attributes,"hasTOC", 0 ) );
        m_tabStop = KWDocument::getAttribute( attributes, "tabStopValue", MM_TO_POINT(15) );
        m_initialEditing = new InitialEditing();
        m_initialEditing->m_initialFrameSet = attributes.attribute( "activeFrameset" );
        m_initialEditing->m_initialCursorParag = attributes.attribute( "cursorParagraph" ).toInt();
        m_initialEditing->m_initialCursorIndex = attributes.attribute( "cursorIndex" ).toInt();
    } else {
        m_processingType = WP;
        m_headerVisible = false;
        m_footerVisible = false;
        m_hasTOC = false;
        m_tabStop = MM_TO_POINT(15);
        delete m_initialEditing;
        m_initialEditing = 0L;
    }

    setPageLayout( pgLayout, columns, hf, false );

    variableCollection()->variableSetting()->load(word );
    //by default display real variable value
    if ( !isReadWrite())
        variableCollection()->variableSetting()->setDisplayFieldCode(false);

    emit sigProgress(10);

    TQDomElement mailmerge = word.namedItem( "MAILMERGE" ).toElement();
    if (mailmerge!=TQDomElement())
    {
        m_slDataBase->load(mailmerge);
    }

    emit sigProgress(15);

    // Load all styles before the corresponding paragraphs try to use them!
    TQDomElement stylesElem = word.namedItem( "STYLES" ).toElement();
    if ( !stylesElem.isNull() )
        loadStyleTemplates( stylesElem );

    emit sigProgress(17);

    TQDomElement frameStylesElem = word.namedItem( "FRAMESTYLES" ).toElement();
    if ( !frameStylesElem.isNull() )
        loadFrameStyleTemplates( frameStylesElem );
    else // load default styles
        loadDefaultFrameStyleTemplates();

    emit sigProgress(18);

    TQDomElement tableStylesElem = word.namedItem( "TABLESTYLES" ).toElement();
    if ( !tableStylesElem.isNull() )
        loadTableStyleTemplates( tableStylesElem );
    else // load default styles
        loadDefaultTableStyleTemplates();

    emit sigProgress(19);

    loadDefaultTableTemplates();

    emit sigProgress(20);

    TQDomElement bookmark = word.namedItem( "BOOKMARKS" ).toElement();
    if( !bookmark.isNull() )
    {
        TQDomElement bookmarkitem = word.namedItem("BOOKMARKS").toElement();
        bookmarkitem = bookmarkitem.firstChild().toElement();

        while ( !bookmarkitem.isNull() )
        {
            if ( bookmarkitem.tagName() == "BOOKMARKITEM" )
            {
                KWLoadingInfo::BookMark bk;
                bk.bookname=bookmarkitem.attribute("name");
                bk.cursorStartIndex=bookmarkitem.attribute("cursorIndexStart").toInt();
                bk.frameSetName=bookmarkitem.attribute("frameset");
                bk.paragStartIndex = bookmarkitem.attribute("startparag").toInt();
                bk.paragEndIndex = bookmarkitem.attribute("endparag").toInt();
                bk.cursorEndIndex = bookmarkitem.attribute("cursorIndexEnd").toInt();
                Q_ASSERT( m_loadingInfo );
                m_loadingInfo->bookMarkList.append( bk );
            }
            bookmarkitem = bookmarkitem.nextSibling().toElement();
        }
    }

    TQStringList lst;
    TQDomElement spellCheckIgnore = word.namedItem( "SPELLCHECKIGNORELIST" ).toElement();
    if( !spellCheckIgnore.isNull() )
    {
        TQDomElement spellWord=word.namedItem("SPELLCHECKIGNORELIST").toElement();
        spellWord=spellWord.firstChild().toElement();
        while ( !spellWord.isNull() )
        {
            if ( spellWord.tagName()=="SPELLCHECKIGNOREWORD" )
                lst.append(spellWord.attribute("word"));
            spellWord=spellWord.nextSibling().toElement();
        }
    }
    setSpellCheckIgnoreList( lst );

    emit sigProgress(25);


    TQDomElement framesets = word.namedItem( "FRAMESETS" ).toElement();
    if ( !framesets.isNull() )
        loadFrameSets( framesets );

    emit sigProgress(85);

    loadPictureMap( word );

    emit sigProgress(90);

    // <EMBEDDED>
    loadEmbeddedObjects( word );

    emit sigProgress(100); // the rest is only processing, not loading

    kdDebug(32001) << "Loading took " << (float)(dt.elapsed()) / 1000 << " seconds" << endl;

    endOfLoading();
    return true;
}

void KWDocument::endOfLoading() // called by both oasis and oldxml
{
    // insert pages
    double maxBottom = 0;
    for (TQPtrListIterator<KWFrameSet> fsit = framesetsIterator(); fsit.current() ; ++fsit ) {
        KWFrameSet *fs = fsit.current();
        for (TQPtrListIterator<KWFrame> fit = fs->frameIterator(); fit.current() ; ++fit ) {
            KWFrame *frame = fit.current();
            maxBottom = TQMAX(maxBottom, frame->bottom());
        }
    }
    KWPage *last = pageManager()->page(lastPage());
    double docHeight = last->offsetInDocument() + last->height();
    while(docHeight <= maxBottom) {
        kdDebug(32001) << "KWDocument::loadXML appends a page\n";
        last = pageManager()->appendPage();
        docHeight += last->height();
    }

    bool first_footer = false, even_footer = false, odd_footer = false;
    bool first_header = false, even_header = false, odd_header = false;

    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
    {
        switch( fit.current()->frameSetInfo() ) {
        case KWFrameSet::FI_FIRST_HEADER: first_header = true; break;
        case KWFrameSet::FI_ODD_HEADER: odd_header = true; break;
        case KWFrameSet::FI_EVEN_HEADER: even_header = true; break;
        case KWFrameSet::FI_FIRST_FOOTER: first_footer = true; break;
        case KWFrameSet::FI_ODD_FOOTER: odd_footer = true; break;
        case KWFrameSet::FI_EVEN_FOOTER: even_footer = true; break;
        case KWFrameSet::FI_FOOTNOTE: break;
        default: break;
        }
    }

    // Create defaults if they were not in the input file.

    // Where to insert the new frames: not at the end, since that breaks oasis-kword.sh
    uint newFramesetsIndex = m_lstFrameSet.isEmpty() ? 0 : 1;

    if ( !first_header ) {
        KWTextFrameSet *fs = new KWTextFrameSet( this, i18n( "First Page Header" ) );
        //kdDebug(32001) << "KWDocument::loadXML KWTextFrameSet created " << fs << endl;
        fs->setFrameSetInfo( KWFrameSet::FI_FIRST_HEADER );
        KWPage *page = pageManager()->page(startPage());
        KWFrame *frame = new KWFrame(fs, page->leftMargin(), page->topMargin(),
                page->width() - page->leftMargin() - page->rightMargin(), 20 );
        //kdDebug(32001) << "KWDocument::loadXML KWFrame created " << frame << endl;
        frame->setFrameBehavior( KWFrame::AutoExtendFrame );
        frame->setNewFrameBehavior( KWFrame::Copy );
        fs->addFrame( frame );
        m_lstFrameSet.insert( newFramesetsIndex++, fs );
    }

    if ( !odd_header ) {
        KWTextFrameSet *fs = new KWTextFrameSet( this, i18n( "Odd Pages Header" ) );
        //kdDebug(32001) << "KWDocument::loadXML KWTextFrameSet created " << fs << endl;
        fs->setFrameSetInfo( KWFrameSet::FI_ODD_HEADER );
        KWPage *page = pageManager()->page(TQMIN(startPage()+2, lastPage()));
        KWFrame *frame = new KWFrame(fs, page->leftMargin(), page->topMargin(),
                page->width() - page->leftMargin() - page->rightMargin(), 20 );
        //kdDebug(32001) << "KWDocument::loadXML KWFrame created " << *frame << endl;
        frame->setFrameBehavior( KWFrame::AutoExtendFrame );
        frame->setNewFrameBehavior( KWFrame::Copy );
        fs->addFrame( frame );
        m_lstFrameSet.insert( newFramesetsIndex++, fs );
    }

    if ( !even_header ) {
        KWTextFrameSet *fs = new KWTextFrameSet( this, i18n( "Even Pages Header" ) );
        //kdDebug(32001) << "KWDocument::loadXML KWTextFrameSet created " << fs << endl;
        fs->setFrameSetInfo( KWFrameSet::FI_EVEN_HEADER );
        KWPage *page = pageManager()->page(TQMIN(startPage()+1, lastPage()));
        KWFrame *frame = new KWFrame(fs, page->leftMargin(), page->topMargin(), page->width() -
                page->leftMargin() - page->rightMargin(), 20 );
        //kdDebug(32001) << "KWDocument::loadXML KWFrame created " << *frame << endl;
        frame->setFrameBehavior( KWFrame::AutoExtendFrame );
        frame->setNewFrameBehavior( KWFrame::Copy );
        fs->addFrame( frame );
        m_lstFrameSet.insert( newFramesetsIndex++, fs );
    }

    if ( !first_footer ) {
        KWTextFrameSet *fs = new KWTextFrameSet( this, i18n( "First Page Footer" ) );
        //kdDebug(32001) << "KWDocument::loadXML KWTextFrameSet created " << fs << endl;
        fs->setFrameSetInfo( KWFrameSet::FI_FIRST_FOOTER );
        KWPage *page = pageManager()->page(pageManager()->startPage());
        KWFrame *frame = new KWFrame(fs, page->leftMargin(), page->height() - page->topMargin()- 20,
                page->width() - page->leftMargin() - page->rightMargin(), 20 );
        //kdDebug(32001) << "KWDocument::loadXML KWFrame created " << *frame << endl;
        frame->setFrameBehavior( KWFrame::AutoExtendFrame );
        frame->setNewFrameBehavior( KWFrame::Copy );
        fs->addFrame( frame );
        m_lstFrameSet.insert( newFramesetsIndex++, fs );
    }

    if ( !odd_footer ) {
        KWTextFrameSet *fs = new KWTextFrameSet( this, i18n( "Odd Pages Footer" ) );
        //kdDebug(32001) << "KWDocument::loadXML KWTextFrameSet created " << fs << endl;
        fs->setFrameSetInfo( KWFrameSet::FI_ODD_FOOTER );
        KWPage *page = pageManager()->page(TQMIN(startPage()+2, lastPage()));
        KWFrame *frame = new KWFrame(fs, page->leftMargin(), page->height()- page->topMargin() - 20,
                page->width() - page->leftMargin() - page->rightMargin(), 20 );
        //kdDebug(32001) << "KWDocument::loadXML KWFrame created " << *frame << endl;
        frame->setFrameBehavior( KWFrame::AutoExtendFrame );
        frame->setNewFrameBehavior( KWFrame::Copy );
        fs->addFrame( frame );
        m_lstFrameSet.insert( newFramesetsIndex++, fs );
    }

    if ( !even_footer ) {
        KWTextFrameSet *fs = new KWTextFrameSet( this, i18n( "Even Pages Footer" ) );
        //kdDebug(32001) << "KWDocument::loadXML KWTextFrameSet created " << fs << endl;
        fs->setFrameSetInfo( KWFrameSet::FI_EVEN_FOOTER );
        KWPage *page = pageManager()->page(TQMIN(startPage()+1, lastPage()));
        KWFrame *frame = new KWFrame(fs, page->leftMargin(), page->height() - page->topMargin()- 20,
                page->width() - page->leftMargin() - page->rightMargin(), 20 );
        //kdDebug(32001) << "KWDocument::loadXML KWFrame created " << *frame << endl;
        frame->setFrameBehavior( KWFrame::AutoExtendFrame );
        frame->setNewFrameBehavior( KWFrame::Copy );
        fs->addFrame( frame );
        m_lstFrameSet.insert( newFramesetsIndex++, fs );
    }

    // do some sanity checking on document.
    for (int i = frameSetCount()-1; i>-1; i--) {
        KWFrameSet *fs = frameSet(i);
        if(!fs) {
            kdWarning() << "frameset " << i << " is NULL!!" << endl;
            m_lstFrameSet.remove(i);
            continue;
        }
        if( fs->type()==FT_TABLE) {
            static_cast<KWTableFrameSet *>( fs )->validate();
        } else if (fs->type() == FT_TEXT) {
            for (int f=fs->frameCount()-1; f>=0; f--) {
                KWFrame *frame = fs->frame(f);
                if(frame->left() < 0) {
                    kdWarning() << fs->name() << " frame " << f << " pos.x is < 0, moving frame" << endl;
                    frame->moveBy( 0- frame->left(), 0);
                }
                if(frame->right() > m_pageLayout.ptWidth) {
                    kdWarning() << fs->name() << " frame " << f << " rightborder outside page ("
                        << frame->right() << ">" << m_pageLayout.ptWidth << "), shrinking" << endl;
                    frame->setRight(m_pageLayout.ptWidth);
                }
                if(fs->isProtectSize())
                    continue; // don't make frames bigger of a protected frameset.
                if(frame->height() < s_minFrameHeight) {
                    kdWarning() << fs->name() << " frame " << f << " height is so small no text will fit, adjusting (was: "
                                << frame->height() << " is: " << s_minFrameHeight << ")" << endl;
                    frame->setHeight(s_minFrameHeight);
                }
                if(frame->width() < s_minFrameWidth) {
                    kdWarning() << fs->name() << " frame " << f << " width is so small no text will fit, adjusting (was: "
                                << frame->width() << " is: " << s_minFrameWidth  << ")" << endl;
                    frame->setWidth(s_minFrameWidth);
                }
            }
            if(fs->frameCount() == 0) {
                KWPage *page = pageManager()->page(startPage());
                KWFrame *frame = new KWFrame(fs, page->leftMargin(), page->topMargin(),
                        page->width() - page->leftMargin() - page->rightMargin(),
                        page->height() - page->topMargin() - page->bottomMargin());
                //kdDebug(32001) << "KWDocument::loadXML main-KWFrame created " << *frame << endl;
                fs->addFrame( frame );
            }
        } else if(fs->frameCount() == 0) {
            kdWarning () << "frameset " << i << " " << fs->name() << " has no frames" << endl;
            removeFrameSet(fs);
            if ( fs->type() == FT_PART )
                delete static_cast<KWPartFrameSet *>(fs)->getChild();
            delete fs;
            continue;
        }
        if(fs->frameCount() > 0) {
            KWFrame *frame = fs->frame(0);
            if(frame->isCopy()) {
                kdWarning() << "First frame in a frameset[" << fs->name() << "] was set to be a copy; resetting\n";
                frame->setCopy(false);
            }
        }
    }

    // Renumber footnotes
    KWTextFrameSet *frameset = dynamic_cast<KWTextFrameSet *>( m_lstFrameSet.getFirst() );
    if ( frameset  )
        frameset->renumberFootNotes( false /*no repaint*/ );

    emit sigProgress(-1);

    //kdDebug(32001) << "KWDocument::loadXML done" << endl;

    // Connect to notifications from main text-frameset
    if ( frameset ) {
        connect( frameset->textObject(), TQT_SIGNAL( chapterParagraphFormatted( KoTextParag * ) ),
                 TQT_SLOT( slotChapterParagraphFormatted( KoTextParag * ) ) );
        connect( frameset, TQT_SIGNAL( mainTextHeightChanged() ),
                 TQT_SIGNAL( mainTextHeightChanged() ) );
    }

    // Note that more stuff will happen in completeLoading
}

void KWDocument::startBackgroundSpellCheck()
{
    if ( backgroundSpellCheckEnabled() && isReadWrite() )
    {
        m_bgSpellCheck->start();
    }
}

void KWDocument::loadEmbeddedObjects( TQDomElement& word )
{
    TQDomNodeList listEmbedded = word.elementsByTagName ( "EMBEDDED" );
    for (unsigned int item = 0; item < listEmbedded.count(); item++)
    {
        TQDomElement embedded = listEmbedded.item( item ).toElement();
        loadEmbedded( embedded );
    }
}

void KWDocument::loadEmbedded( const TQDomElement &embedded )
{
    TQDomElement object = embedded.namedItem( "OBJECT" ).toElement();
    if ( !object.isNull() )
    {
        KWDocumentChild *ch = new KWDocumentChild( this );
        ch->load( object, true );
        insertChild( ch );
        TQDomElement settings = embedded.namedItem( "SETTINGS" ).toElement();
        TQString name;
        if ( !settings.isNull() )
            name = settings.attribute( "name" );
        KWPartFrameSet *fs = new KWPartFrameSet( this, ch, name );
        m_lstFrameSet.append( fs );
        if ( !settings.isNull() )
        {
            kdDebug(32001) << "KWDocument::loadXML loading embedded object" << endl;
            fs->load( settings );
        }
        else
            kdError(32001) << "No <SETTINGS> tag in EMBEDDED" << endl;

    } else
        kdError(32001) << "No <OBJECT> tag in EMBEDDED" << endl;
}


void KWDocument::loadStyleTemplates( const TQDomElement &stylesElem )
{
    TQValueList<TQString> followingStyles;
    TQDomNodeList listStyles = stylesElem.elementsByTagName( "STYLE" );
    if( listStyles.count() > 0) { // we are going to import at least one style.
        KoParagStyle *s = m_styleColl->findStyle("Standard");
        //kdDebug(32001) << "KWDocument::loadStyleTemplates looking for Standard, to delete it. Found " << s << endl;
        if(s) // delete the standard style.
            m_styleColl->removeStyle(s);
    }
    for (unsigned int item = 0; item < listStyles.count(); item++) {
        TQDomElement styleElem = listStyles.item( item ).toElement();

        KoParagStyle *sty = new KoParagStyle( TQString() );
        // Load the style from the <STYLE> element
        sty->loadStyle( styleElem, m_syntaxVersion );

        //kdDebug(32001) << "KoParagStyle created name=" << sty->name() << endl;

        if ( m_syntaxVersion < 3 )
        {
            // Convert old style (up to 1.2.x included)
            // "include in TOC if chapter numbering" to the new attribute
            if ( sty->paragLayout().counter && sty->paragLayout().counter->numbering() == KoParagCounter::NUM_CHAPTER )
                sty->setOutline( true );
        }

        // the real value of followingStyle is set below after loading all styles
        sty->setFollowingStyle( sty );

        TQDomElement formatElem = styleElem.namedItem( "FORMAT" ).toElement();
        if ( !formatElem.isNull() )
            sty->format() = KWTextParag::loadFormat( formatElem, 0L, defaultFont(), globalLanguage(), globalHyphenation() );
        else
            kdWarning(32001) << "No FORMAT tag in <STYLE>" << endl; // This leads to problems in applyStyle().

        // Style created, now let's try to add it
        sty = m_styleColl->addStyle( sty );

        if(m_styleColl->styleList().count() > followingStyles.count() )
        {
            TQString following = styleElem.namedItem("FOLLOWING").toElement().attribute("name");
            followingStyles.append( following );
        }
        else
            kdWarning () << "Found duplicate style declaration, overwriting former " << sty->name() << endl;
    }

    Q_ASSERT( followingStyles.count() == m_styleColl->styleList().count() );

    unsigned int i=0;
    for( TQValueList<TQString>::Iterator it = followingStyles.begin(); it != followingStyles.end(); ++it ) {
        KoParagStyle * style = m_styleColl->findStyle(*it);
        m_styleColl->styleAt(i++)->setFollowingStyle( style );
    }

}

void KWDocument::loadFrameStyleTemplates( const TQDomElement &stylesElem )
{
    TQDomNodeList listStyles = stylesElem.elementsByTagName( "FRAMESTYLE" );
    if( listStyles.count() > 0) { // we are going to import at least one style.
        KWFrameStyle *s = m_frameStyleColl->findStyle("Plain");
        if(s) // delete the standard style.
            m_frameStyleColl->removeStyle(s);
    }
    for (unsigned int item = 0; item < listStyles.count(); item++) {
        TQDomElement styleElem = listStyles.item( item ).toElement();

        KWFrameStyle *sty = new KWFrameStyle( styleElem );
        m_frameStyleColl->addStyle( sty );
    }
}

void KWDocument::loadDefaultFrameStyleTemplates()
{
    const TQString fsfileName( locate("data", "kword/framestyles.xml") );

    kdDebug(30003) << "Data directory: " << KGlobal::dirs()->resourceDirs( "data" ) << endl;
    kdDebug(30003) << "Directory searched: " << KGlobal::dirs()->resourceDirs( "data" ) << endl;
    kdDebug(30003) << "File framestyles.xml searched at: " << fsfileName << endl;

    m_frameStyleColl->setDefault( true );

    if ( ! TQFile::exists( fsfileName ) )
    {
        kdWarning(30003) << "Cannot find any framestyles.xml" << endl;
        if (!m_frameStyleColl->findStyle("Plain")) {
            KWFrameStyle * standardFrameStyle = new KWFrameStyle( "Plain" );
            standardFrameStyle->setBackgroundColor(TQColor("white"));
            standardFrameStyle->setTopBorder(KoBorder(TQColor("black"),KoBorder::SOLID,0));
            standardFrameStyle->setRightBorder(KoBorder(TQColor("black"),KoBorder::SOLID,0));
            standardFrameStyle->setLeftBorder(KoBorder(TQColor("black"),KoBorder::SOLID,0));
            standardFrameStyle->setBottomBorder(KoBorder(TQColor("black"),KoBorder::SOLID,0));
            m_frameStyleColl->addStyle( standardFrameStyle );
        }
        return;
    }

    kdDebug(30003) << "File framestyles.xml found!" << endl;

    // Open file and parse it
    TQFile in( fsfileName );
    if ( !in.open( IO_ReadOnly ) )
    {
        //i18n( "Couldn't open the file for reading (check read permissions)" );
        kdWarning(30003) << "Couldn't open the file for reading (check read permissions)" << endl;
        return;
    }
    TQString errorMsg;
    int errorLine;
    int errorColumn;
    TQDomDocument doc;
    if ( ! doc.setContent( &in , &errorMsg, &errorLine, &errorColumn ) )
    {
        kdError (30003) << "Parsing Error! Aborting! (in KWDocument::loadDefaultFrameStyleTemplates())" << endl
                        << "  Line: " << errorLine << " Column: " << errorColumn << endl
                        << "  Message: " << errorMsg << endl;
    }
    in.close();

    // Start adding framestyles
    TQDomElement stylesElem = doc.documentElement();

    TQDomNodeList listStyles = stylesElem.elementsByTagName( "FRAMESTYLE" );
    if( listStyles.count() > 0) { // we are going to import at least one style.
        KWFrameStyle *s = m_frameStyleColl->findStyle("Plain");
        if(s) // delete the standard style.
            m_frameStyleColl->removeStyle(s);
    }
    for (unsigned int item = 0; item < listStyles.count(); item++) {
        TQDomElement styleElem = listStyles.item( item ).toElement();

        KWFrameStyle *sty = new KWFrameStyle( styleElem );
        m_frameStyleColl->addStyle( sty );
    }
}

void KWDocument::loadTableStyleTemplates( const TQDomElement& stylesElem )
{
    TQDomNodeList listStyles = stylesElem.elementsByTagName( "TABLESTYLE" );
    if( listStyles.count() > 0) { // we are going to import at least one style.
        KWTableStyle *s = m_tableStyleColl->findStyle("Plain");
        if(s) // delete the standard style.
            m_tableStyleColl->removeStyle(s);
    }
    for (unsigned int item = 0; item < listStyles.count(); item++) {
        TQDomElement styleElem = listStyles.item( item ).toElement();

        KWTableStyle *sty = new KWTableStyle( styleElem, this );
        m_tableStyleColl->addStyle( sty );
    }
}

void KWDocument::loadDefaultTableStyleTemplates()
{
    KURL fsfile;

    m_tableStyleColl->setDefault( true );

    if ( ! TQFile::exists(locate("data", "kword/tablestyles.xml")) )
    {
        if (!m_tableStyleColl->findStyle("Plain")) {
            m_tableStyleColl->addStyle( new KWTableStyle( "Plain", m_styleColl->styleAt(0), m_frameStyleColl->frameStyleAt(0) ) );
        }
        return;
    }

    fsfile.setPath( locate("data", "kword/tablestyles.xml") );

    // Open file and parse it
    TQFile in( fsfile.path() );
    if ( !in.open( IO_ReadOnly ) )
    {
        //i18n( "Couldn't open the file for reading (check read permissions)" );
        return;
    }
    in.at(0);
    TQString errorMsg;
    int errorLine;
    int errorColumn;
    TQDomDocument doc;
    if ( doc.setContent( &in , &errorMsg, &errorLine, &errorColumn ) ) {
    }
    else
    {
        kdError (30003) << "Parsing Error! Aborting! (in KWDocument::loadDefaultTableStyleTemplates())" << endl
                        << "  Line: " << errorLine << " Column: " << errorColumn << endl
                        << "  Message: " << errorMsg << endl;
    }
    in.close();

    // Start adding tablestyles
    TQDomElement stylesElem = doc.documentElement();

    TQDomNodeList listStyles = stylesElem.elementsByTagName( "TABLESTYLE" );
    if( listStyles.count() > 0) { // we are going to import at least one style.
        KWTableStyle *s = m_tableStyleColl->findStyle("Plain");
        if(s) // delete the standard style.
            m_tableStyleColl->removeStyle(s);
    }
    for (unsigned int item = 0; item < listStyles.count(); item++) {
        TQDomElement styleElem = listStyles.item( item ).toElement();

        KWTableStyle *sty = new KWTableStyle( styleElem, this );
        m_tableStyleColl->addStyle( sty );
    }
}

void KWDocument::loadDefaultTableTemplates()
{
    KURL fsfile;

    if ( ! TQFile::exists(locate("data", "kword/tabletemplates.xml")) )
    {
        if (!m_tableTemplateColl->findTableTemplate("Plain")) {
            KWTableTemplate * standardTableTemplate = new KWTableTemplate( "Plain" );
            KWTableStyle* defaultTableStyle = tableStyleCollection()->findStyle("Plain");
            standardTableTemplate->setFirstRow( defaultTableStyle );
            standardTableTemplate->setLastRow( defaultTableStyle );
            standardTableTemplate->setFirstCol( defaultTableStyle );
            standardTableTemplate->setLastCol( defaultTableStyle );
            standardTableTemplate->setBodyCell( defaultTableStyle );
            standardTableTemplate->setTopLeftCorner( defaultTableStyle );
            standardTableTemplate->setTopRightCorner( defaultTableStyle );
            standardTableTemplate->setBottomLeftCorner( defaultTableStyle );
            standardTableTemplate->setBottomRightCorner( defaultTableStyle );
            m_tableTemplateColl->addTableTemplate( standardTableTemplate );
        }
        return;
    }

    fsfile.setPath( locate("data", "kword/tabletemplates.xml") );

    // Open file and parse it
    TQFile in( fsfile.path() );
    if ( !in.open( IO_ReadOnly ) )
    {
        //i18n( "Couldn't open the file for reading (check read permissions)" );
        return;
    }
    in.at(0);
    TQString errorMsg;
    int errorLine;
    int errorColumn;
    TQDomDocument doc;
    if ( doc.setContent( &in , &errorMsg, &errorLine, &errorColumn ) ) {
    }
    else
    {
        kdError (30003) << "Parsing Error! Aborting! (in KWDocument::readTableTemplates())" << endl
                        << "  Line: " << errorLine << " Column: " << errorColumn << endl
                        << "  Message: " << errorMsg << endl;
    }
    in.close();

    // Start adding framestyles
    TQDomElement templatesElem = doc.documentElement();

    TQDomNodeList listTemplates = templatesElem.elementsByTagName( "TABLETEMPLATE" );
    if( listTemplates.count() > 0) {
        KWTableTemplate *s = m_tableTemplateColl->findTableTemplate("Plain");
        if(s)
            m_tableTemplateColl->removeTableTemplate(s);
    }
    for (unsigned int item = 0; item < listTemplates.count(); item++) {
        TQDomElement templateElem = listTemplates.item( item ).toElement();

        KWTableTemplate *temp = new KWTableTemplate( templateElem, this );
        m_tableTemplateColl->addTableTemplate( temp );
    }
}

void KWDocument::progressItemLoaded()
{
    if ( !m_nrItemsToLoad ) // happens when pasting
        return;
    m_itemsLoaded++;
    // We progress from 20 to 85 -> 65-wide range, 20 offset.
    unsigned int perc = 65 * m_itemsLoaded / m_nrItemsToLoad;
    if ( perc != 65 * (m_itemsLoaded-1) / m_nrItemsToLoad ) // only emit if different from previous call
    {
        //kdDebug(32001) << m_itemsLoaded << " items loaded. %=" << perc + 20 << endl;
        emit sigProgress( perc + 20 );
    }
}

void KWDocument::loadFrameSets( const TQDomElement &framesetsElem )
{
    // <FRAMESET>
    // First prepare progress info
    m_nrItemsToLoad = 0; // total count of items (mostly paragraph and frames)
    TQDomElement framesetElem = framesetsElem.firstChild().toElement();
    // Workaround the slowness of TQDom's elementsByTagName
    TQValueList<TQDomElement> framesets;
    for ( ; !framesetElem.isNull() ; framesetElem = framesetElem.nextSibling().toElement() )
    {
        if ( framesetElem.tagName() == "FRAMESET" )
        {
            framesets.append( framesetElem );
            m_nrItemsToLoad += framesetElem.childNodes().count();
        }
    }

    m_itemsLoaded = 0;

    TQValueList<TQDomElement>::Iterator it = framesets.begin();
    TQValueList<TQDomElement>::Iterator end = framesets.end();
    for ( ; it != end ; ++it )
    {
        (void) loadFrameSet( *it );
    }
}

KWFrameSet * KWDocument::loadFrameSet( TQDomElement framesetElem, bool loadFrames, bool loadFootnote )
{
    FrameSetType frameSetType = static_cast<FrameSetType>( KWDocument::getAttribute( framesetElem, "frameType", FT_BASE ) );
    TQString fsname = KWDocument::getAttribute( framesetElem, "name", "" );

    switch ( frameSetType ) {
    case FT_TEXT: {
        TQString tableName = KWDocument::getAttribute( framesetElem, "grpMgr", "" );
        if ( !tableName.isEmpty() ) {
            // Text frameset belongs to a table -> find table by name
            KWTableFrameSet *table = 0L;
            TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
            for ( ; fit.current() ; ++fit ) {
                KWFrameSet *f = fit.current();
                if( f->type() == FT_TABLE &&
                    f->isVisible() &&
                    f->name() == tableName ) {
                    table = static_cast<KWTableFrameSet *> (f);
                    break;
                }
            }
            // No such table yet -> create
            if ( !table ) {
                table = new KWTableFrameSet( this, tableName );
                addFrameSet(table, false);
            }
            // Load the cell
            return table->loadCell( framesetElem );
        }
        else
        {
            KWFrameSet::Info info = static_cast<KWFrameSet::Info>( framesetElem.attribute("frameInfo").toInt() );
            if ( info == KWFrameSet::FI_FOOTNOTE )
            {
                if ( !loadFootnote )
                    return 0L;
                // Footnote -> create a KWFootNoteFrameSet
                KWFootNoteFrameSet *fs = new KWFootNoteFrameSet( this, fsname );
                fs->load( framesetElem, loadFrames );
                addFrameSet(fs, false);
                return fs;
            }
            else // Normal text frame
            {
                KWTextFrameSet *fs = new KWTextFrameSet( this, fsname );
                fs->load( framesetElem, loadFrames );
                addFrameSet(fs, false);

                // Old file format had autoCreateNewFrame as a frameset attribute
                if ( framesetElem.hasAttribute( "autoCreateNewFrame" ) )
                {
                    KWFrame::FrameBehavior behav = static_cast<KWFrame::FrameBehavior>( framesetElem.attribute( "autoCreateNewFrame" ).toInt() );
                    TQPtrListIterator<KWFrame> frameIt( fs->frameIterator() );
                    for ( ; frameIt.current() ; ++frameIt ) // Apply it to all frames
                        frameIt.current()->setFrameBehavior( behav );
                }
                return fs;
            }
        }
    } break;
    case FT_CLIPART:
    {
        kdError(32001) << "FT_CLIPART used! (in KWDocument::loadFrameSet)" << endl;
        // Do not break!
    }
    case FT_PICTURE:
    {
        KWPictureFrameSet *fs = new KWPictureFrameSet( this, fsname );
        fs->load( framesetElem, loadFrames );
        addFrameSet(fs, false);
        return fs;
    } break;
    case FT_FORMULA: {
        KWFormulaFrameSet *fs = new KWFormulaFrameSet( this, fsname );
        fs->load( framesetElem, loadFrames );
        addFrameSet(fs, false);
        return fs;
    } break;
    // Note that FT_PART cannot happen when loading from a file (part frames are saved into the SETTINGS tag)
    // and FT_TABLE can't happen either.
    case FT_PART:
        kdWarning(32001) << "loadFrameSet: FT_PART: impossible case" << endl;
        break;
    case FT_TABLE:
        kdWarning(32001) << "loadFrameSet: FT_TABLE: impossible case" << endl;
        break;
    case FT_BASE:
        kdWarning(32001) << "loadFrameSet: FT_BASE !?!?" << endl;
        break;
    }
    return 0L;
}

void KWDocument::loadImagesFromStore( KoStore *store )
{
    if ( store && !m_pictureMap.isEmpty() ) {
        m_pictureCollection->readFromStore( store, m_pictureMap );
        m_pictureMap.clear(); // Release memory
    }
}

bool KWDocument::completeLoading( KoStore *store )
{
    kdDebug() << k_funcinfo << endl;
    // Old-XML stuff. No-op when loading OASIS.
    loadImagesFromStore( store );
    processPictureRequests();
    processAnchorRequests();
    processFootNoteRequests();

    // Save memory
    m_urlIntern = TQString();

    // The fields and dates just got loaded -> update vars
    recalcVariables( VT_FIELD );
    recalcVariables( VT_DATE );
    recalcVariables( VT_STATISTIC ); // e.g. number of words etc.

    // Finalize all the existing [non-inline] framesets
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
        fit.current()->finalize();

    // This computes the number of pages (from the frames)
    // for the first time (and adds footers/headers/footnotes etc.)
    // ## Note: with OASIS the frame loading appends pages as necessary,
    // so maybe we don't need to calculate the pages from the frames anymore.
    recalcFrames();

    // Fix z orders on older documents
    fixZOrders();

    emit newContentsSize();
    repaintAllViews( true );     // in case any view exists already
    reactivateBgSpellChecking();
    connect( documentInfo(), TQT_SIGNAL( sigDocumentInfoModifed()),this,TQT_SLOT(slotDocumentInfoModifed() ) );

    //desactivate bgspellchecking
    //attributes isReadWrite is not placed at the beginning !
    if ( !isReadWrite())
        enableBackgroundSpellCheck( false );

    // Load bookmarks
    initBookmarkList();

    deleteLoadingInfo();

    setModified( false );

    return true;
}

KWLoadingInfo* KWDocument::createLoadingInfo()
{
    Q_ASSERT( !m_loadingInfo );
    m_loadingInfo = new KWLoadingInfo();
    m_loadingInfo->columns.ptColumnSpacing = m_defaultColumnSpacing;
    return m_loadingInfo;
}

void KWDocument::deleteLoadingInfo()
{
    Q_ASSERT( m_loadingInfo );
    delete m_loadingInfo;
    m_loadingInfo = 0;
}

void KWDocument::processPictureRequests()
{
    TQPtrListIterator<KWTextImage> it2 ( m_textImageRequests );
    for ( ; it2.current() ; ++it2 )
    {
        it2.current()->setImage( *m_pictureCollection );
    }
    m_textImageRequests.clear();

    //kdDebug(32001) << m_pictureRequests.count() << " picture requests." << endl;
    TQPtrListIterator<KWPictureFrameSet> it3( m_pictureRequests );
    for ( ; it3.current() ; ++it3 )
        it3.current()->setPicture( m_pictureCollection->findPicture( it3.current()->key() ) );
    m_pictureRequests.clear();
}

void KWDocument::processAnchorRequests()
{
    TQMapIterator<TQString, KWAnchorPosition> itanch = m_anchorRequests.begin();
    for ( ; itanch != m_anchorRequests.end(); ++itanch )
    {
        TQString fsname = itanch.key();
        if ( m_pasteFramesetsMap && m_pasteFramesetsMap->contains( fsname ) )
            fsname = (*m_pasteFramesetsMap)[ fsname ];
        kdDebug(32001) << "KWDocument::processAnchorRequests anchoring frameset " << fsname << endl;
        KWFrameSet * fs = frameSetByName( fsname );
        Q_ASSERT( fs );
        if ( fs )
            fs->setAnchored( itanch.data().textfs, itanch.data().paragId, itanch.data().index, true, false /*don't repaint yet*/ );
    }
    m_anchorRequests.clear();
}

bool KWDocument::processFootNoteRequests()
{
    bool ret = false;
    TQMapIterator<TQString, KWFootNoteVariable *> itvar = m_footnoteVarRequests.begin();
    for ( ; itvar != m_footnoteVarRequests.end(); ++itvar )
    {
        TQString fsname = itvar.key();
        if ( m_pasteFramesetsMap && m_pasteFramesetsMap->contains( fsname ) )
            fsname = (*m_pasteFramesetsMap)[ fsname ];
        //kdDebug(32001) << "KWDocument::processFootNoteRequests binding footnote var " << itvar.data() << " and frameset " << fsname << endl;
        KWFrameSet * fs = frameSetByName( fsname );
        Q_ASSERT( fs );
        if ( !fs ) // #104431
            continue;
        Q_ASSERT( fs->type() == FT_TEXT );
        Q_ASSERT( fs->frameSetInfo() == KWFrameSet::FI_FOOTNOTE );
        KWFootNoteFrameSet* fnfs = dynamic_cast<KWFootNoteFrameSet *>(fs);
        if ( fnfs )
        {
            fnfs->setFootNoteVariable( itvar.data() );
            itvar.data()->setFrameSet( fnfs );
            ret = true;
        }
    }
    m_footnoteVarRequests.clear();
    // Renumber footnotes
    if ( ret ) {
        KWFrameSet *frameset = m_lstFrameSet.getFirst();
        if ( frameset && frameset->type() == FT_TEXT )
            static_cast<KWTextFrameSet *>(frameset)->renumberFootNotes( false /*no repaint*/ );
    }
    return ret;
}

TQString KWDocument::uniqueFramesetName( const TQString& oldName )
{
    TQString newName = oldName;
    if (frameSetByName( oldName ))//rename it if name frameset exists
    {
        // make up a new name for the frameset, use Copy[digits]-[oldname] as template.
        // Fully translatable naturally :)
        TQString searchString( "^(" + i18n("Copy%1-%2").arg("\\d*").arg("){0,1}") );
        searchString = searchString.replace(TQRegExp("\\-"), "\\-"); // escape the '-'
        TQRegExp searcher(searchString);
        int count=0;
        do {
            newName=oldName;
            newName.replace(searcher,i18n("Copy%1-%2").arg(count > 0? TQString("%1").arg(count):"").arg(""));
            count++;
        } while ( frameSetByName( newName ) );
    }
    return newName;
}

void KWDocument::pasteFrames( TQDomElement topElem, KMacroCommand * macroCmd, bool copyFootNote, bool loadFootNote, bool selectFrames )
{
    m_pasteFramesetsMap = new TQMap<TQString, TQString>();
    //TQPtrList<KWFrameSet> frameSetsToFinalize;
    int ref=0;
    int nb = 0;
    TQDomElement elem = topElem.firstChild().toElement();
    for ( ; !elem.isNull() ; elem = elem.nextSibling().toElement() )
    {
        //kdDebug() << "pasteFrames: elem=" << elem.tagName() << endl;
        TQDomElement frameElem;
        KWFrameSet * fs = 0L;
        if ( elem.tagName() == "FRAME" )
        {
            TQString frameSetName = frameElem.attribute( "parentFrameset" );
            fs = frameSetByName( frameSetName );
            if ( !fs )
            {
                kdWarning(32001) << "pasteFrames: Frameset '" << frameSetName << "' not found" << endl;
                continue;
            }
            frameElem = elem;
        }
        else if ( elem.tagName() == "FRAMESET" )
        {
            // Prepare a new name for the frameset
            TQString oldName = elem.attribute( "name" );
            TQString newName = uniqueFramesetName( oldName ); // make up a new name for the frameset

            m_pasteFramesetsMap->insert( oldName, newName ); // remember the name transformation
            if(oldName != newName)
                kdDebug(32001) << "KWDocument::pasteFrames new frameset: " << oldName << "->" << newName << endl;
            FrameSetType frameSetType = static_cast<FrameSetType>( KWDocument::getAttribute( elem, "frameType", FT_BASE ) );
            switch ( frameSetType ) {
            case FT_TABLE: {
                KWTableFrameSet *table = new KWTableFrameSet( this, newName );
                table->fromXML( elem, true, false /*don't apply names*/ );
                table->moveBy( 20.0, 20.0 );
                m_lstFrameSet.append( table );
                table->setZOrder();
                if ( macroCmd )
                    macroCmd->addCommand( new KWCreateTableCommand( TQString(), table ) );
                fs = table;
                break;
            }
            case FT_PART:
            {
                ref |= Embedded;
#if 0
                KWPartFrameSet *part = new KWPartFrameSet( this, newName );
                part->fromXML( elem, true, false /*don't apply names*/ );
                part->moveBy( 20.0, 20.0 );
                m_lstFrameSet.append( part );
                part->setZOrder();
                fs = part;
#endif
                break;
            }
            default:
                fs = loadFrameSet( elem, false, loadFootNote );
                if ( fs )
                {
                    kdDebug() << "KWDocument::pasteFrames created frameset: '" << newName << "'\n";
                    fs->setName( newName );
                    frameElem = elem.namedItem( "FRAME" ).toElement();
                }
            }
            //when we paste a header/footer we transforme it in a body frame
            if(fs && (fs->isHeaderOrFooter() || ( !copyFootNote && fs->isFootEndNote())))
                fs->setFrameSetInfo(KWFrameSet::FI_BODY);
        }
        // Test commented out since the toplevel element can contain "PARAGRAPH" now
        //else
        //kdWarning(32001) << "Unsupported toplevel-element in KWCanvas::pasteFrames : '" << elem.tagName() << "'" << endl;

        if ( fs )
        {
            //if ( frameSetsToFinalize.findRef( fs ) == -1 )
            //    frameSetsToFinalize.append( fs );

            // Load the frame
            if ( !frameElem.isNull() )
            {
                double offs = 20.0;
                KoRect rect;
                rect.setLeft( KWDocument::getAttribute( frameElem, "left", 0.0 ) + offs );
                rect.setTop( KWDocument::getAttribute( frameElem, "top", 0.0 ) + offs );
                rect.setRight( KWDocument::getAttribute( frameElem, "right", 0.0 ) + offs );
                rect.setBottom( KWDocument::getAttribute( frameElem, "bottom", 0.0 ) + offs );
                KWFrame * frame = new KWFrame( fs, rect.x(), rect.y(), rect.width(), rect.height() );
                frame->load( frameElem, fs, KWDocument::CURRENT_SYNTAX_VERSION );
                frame->setZOrder( maxZOrder( frame->pageNumber(this) ) + 1 +nb ); // make sure it's on top
                nb++;
                fs->addFrame( frame, false );
                if ( selectFrames ) {
                    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin();
                            it != m_lstViews.end(); ++it ) {
                        KWFrameView *fv = (*it)->frameViewManager()->view(frame);
                        if(fv)
                            fv->setSelected(true);
                    }
                }
                if ( macroCmd )
                {
                    KWCreateFrameCommand *cmd = new KWCreateFrameCommand( TQString(), frame );
                    macroCmd->addCommand(cmd);
                }
            }
            int type=0;
            // Please move this to some common method somewhere (e.g. in KWDocument) (David)
            switch(fs->type())
            {
            case FT_TEXT:
                type=(int)TextFrames;
                break;
            case FT_CLIPART:
            {
                kdError(32001) << "FT_CLIPART used! (in KWDocument::loadFrameSet)" << endl;
                // Do not break!
            }
            case FT_PICTURE:
                type=(int)Pictures;
                break;
            case FT_PART:
                type=(int)Embedded;
                break;
            case FT_FORMULA:
                type=(int)FormulaFrames;
                break;
            case FT_TABLE:
                type=(int)Tables;
                break;
            default:
                type=(int)TextFrames;
            }
            ref|=type;
        }
    }
    refreshDocStructure(ref);
}

void KWDocument::completePasting()
{
    processPictureRequests();
    processAnchorRequests();
    if ( processFootNoteRequests() )
    {
        // We pasted footnotes. Relayout frames.
        recalcFrames();
    }

    // Finalize afterwards - especially in case of inline frames, made them inline in processAnchorRequests
    //for ( TQPtrListIterator<KWFrameSet> fit( frameSetsToFinalize ); fit.current(); ++fit )

    // Do it on all of them (we'd need to store frameSetsToFinalize as member var if this is really slow)
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
        fit.current()->finalize();
    repaintAllViews();
    delete m_pasteFramesetsMap;
    m_pasteFramesetsMap = 0L;
}

void KWDocument::completeOasisPasting()
{
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
        fit.current()->finalize();
    repaintAllViews();
}

void KWDocument::insertEmbedded( KoStore *store, TQDomElement topElem, KMacroCommand * macroCmd, double offset )
{
    if ( !m_pasteFramesetsMap ) // may have been created by pasteFrames
        m_pasteFramesetsMap = new TQMap<TQString, TQString>();

    TQDomElement elem = topElem.firstChild().toElement();
    for ( ; !elem.isNull() ; elem = elem.nextSibling().toElement() )
    {
        if ( elem.tagName() == "EMBEDDED" )
        {
            kdDebug()<<"KWDocument::insertEmbedded() Embedded object"<<endl;
            TQDomElement object = elem.namedItem( "OBJECT" ).toElement();
            TQDomElement settings = elem.namedItem( "SETTINGS" ).toElement();
            if ( object.isNull() || settings.isNull() )
            {
                kdError() << "No <OBJECT> or <SETTINGS> tag" << endl;
            }
            else
            {
                KWDocumentChild *ch = new KWDocumentChild( this );
                kdDebug()<<"KWDocument::insertEmbedded() loading document"<<endl;
                if ( ch->load( object, true ) )
                {
                    ch->loadDocument( store );
                    insertChild( ch );
                    TQString oldName = settings.attribute( "name" );
                    TQString newName = uniqueFramesetName( oldName );
                    m_pasteFramesetsMap->insert( oldName, newName ); // remember the name transformation
                    KWPartFrameSet *part = new KWPartFrameSet( this, ch, newName );
                    m_lstFrameSet.append( part );
                    kdDebug() << "KWDocument::insertEmbedded loading embedded object" << endl;
                    part->load( settings );
                    if ( offset != 0 ) {
                        TQRect r = ch->geometry();
                        r.moveBy( (int)offset, (int)offset );
                        ch->setGeometry( r );
                    }
                    part->setZOrder();
                    if ( macroCmd )
                    {
                        TQPtrListIterator<KWFrame> frameIt( part->frameIterator() );
                        for ( ; frameIt.current(); ++frameIt )
                        {
                            macroCmd->addCommand( new KWCreateFrameCommand( TQString(), frameIt.current() ) );
                        }
                    }
                }
            }
        }
    }
    refreshDocStructure( (int)Embedded );
}

bool KWDocument::saveOasis( KoStore* store, KoXmlWriter* manifestWriter )
{
    TQValueList<KWFrameView*> noFrames;
    return saveOasisHelper( store, manifestWriter, SaveAll, noFrames);
}

// can't be const due to recalcVariables()
bool KWDocument::saveOasisHelper( KoStore* store, KoXmlWriter* manifestWriter, SaveFlag saveFlag, const TQValueList<KWFrameView*> &selectedFrames, TQString* plainText, KoPicture* picture, KWTextFrameSet* fs) {
    m_pictureCollection->assignUniqueIds();
    fixZOrders();

    manifestWriter->addManifestEntry( "content.xml", "text/xml" );
    KoOasisStore oasisStore( store );

    KoXmlWriter* contentWriter = oasisStore.contentWriter();
    if ( !contentWriter )
        return false;

    TQValueList<KoPictureKey> pictureList;
    if ( saveFlag == SaveAll )
        pictureList = savePictureList();

    m_varColl->variableSetting()->setModificationDate(TQDateTime::currentDateTime());
    recalcVariables( VT_DATE );
    recalcVariables( VT_TIME ); // for "current time"
    recalcVariables( VT_STATISTIC );
    m_syntaxVersion = CURRENT_SYNTAX_VERSION; // ### clean this up once we remove the old format

    KoGenStyles mainStyles;
    KoSavingContext savingContext( mainStyles, m_varColl->variableSetting(), m_pageColumns.columns > 1, KoSavingContext::Store );

    // Save user styles as KoGenStyle objects
    m_styleColl->saveOasis( mainStyles, KoGenStyle::STYLE_USER, savingContext );

    TQByteArray headerFooterContent;
    if ( saveFlag == SaveAll )
    {
        // Save visual info for the first view, such as the active frameset and cursor position
        // It looks like a hack, but reopening a document creates only one view anyway (David)
        KWView * view = static_cast<KWView*>(views().getFirst());
        if ( view ) // no view if embedded document
        {
            KWFrameSetEdit* edit = view->getGUI()->canvasWidget()->currentFrameSetEdit();
            if ( edit )
            {
                KWTextFrameSetEdit* textedit = dynamic_cast<KWTextFrameSetEdit *>(edit);
                if ( textedit && textedit->cursor() ) {
                    KoTextCursor* cursor = textedit->cursor();
                    savingContext.setCursorPosition( cursor->parag(),
                                                     cursor->index() );
                }
            }
        }

        // Header and footers save their content into master-styles/master-page, and their
        // styles into the page-layout automatic-style.
        // However the paragraph styles used by header/footers need to be known before
        // hand, to promote them to styles.xml. So we collect them first, which means
        // storing the content into a buffer.
        TQBuffer buffer( headerFooterContent );
        buffer.open( IO_WriteOnly );
        KoXmlWriter headerFooterTmpWriter( TQT_TQIODEVICE(&buffer) );  // TODO pass indentation level

        // The order we write out header, header-left, etc. is important. So, we go here
        // the dirty way to collect them first and then flush them ordered out.
        TQMap<KWFrameSet::Info,const KWFrameSet*> tempmap;

        // ## This loop is duplicated in saveOasisDocumentStyles
        for (TQPtrListIterator<KWFrameSet> fit = framesetsIterator(); fit.current() ; ++fit ) {
            const KWFrameSet* fs = fit.current();
            if ( fs->isVisible() && // HACK to avoid saving [hidden] headers/footers framesets for now
                 !fs->isFloating() &&
                 !fs->isDeleted() &&
                 fs->type() == FT_TEXT &&
                 fs->isHeaderOrFooter() )
            {
                tempmap.insert(fs->frameSetInfo(), fs);
            }
        }

        TQValueList<KWFrameSet::Info> order;
        order << KWFrameSet::FI_FIRST_HEADER << KWFrameSet::FI_ODD_HEADER << KWFrameSet::FI_EVEN_HEADER
              << KWFrameSet::FI_FIRST_FOOTER << KWFrameSet::FI_ODD_FOOTER << KWFrameSet::FI_EVEN_FOOTER;
        for (uint i=0; i<order.count(); ++i) {
            KWFrameSet::Info info = order[i];
            if (tempmap.contains(info)) {
                const KWFrameSet* fs = tempmap[info];

                // Save content
                headerFooterTmpWriter.startElement( fs->headerFooterTag() ); // e.g. style:header
                static_cast<const KWTextFrameSet *>(fs)->saveOasisContent( headerFooterTmpWriter, savingContext );
                headerFooterTmpWriter.endElement();
            }
        }

        // Add trailing '0'  (TQt4: remove)
        headerFooterContent.resize( headerFooterContent.size() + 1 );
        headerFooterContent[headerFooterContent.size()-1] = '\0';

        // Now mark all autostyles as "for styles.xml" since headers/footers need them
        TQValueList<KoGenStyles::NamedStyle> autoStyles = mainStyles.styles( KoGenStyle::STYLE_AUTO );
        for ( TQValueList<KoGenStyles::NamedStyle>::const_iterator it = autoStyles.begin();
              it != autoStyles.end(); ++it ) {
            mainStyles.markStyleForStylesXml( (*it).name );
        }
    }

    KoXmlWriter* bodyWriter = oasisStore.bodyWriter();
    bodyWriter->startElement( "office:body" );
    bodyWriter->startElement( "office:text" );

    if ( saveFlag == SaveAll )
    {
        // save the body into bodyWriter
        saveOasisBody( *bodyWriter, savingContext );
    }
    else // SaveSelected
    {
        // In theory we should pass a view to this method, in order to
        // copy what is currently selected in that view only. But selection
        // is currently part of the KoTextParag data, so it's shared between views.
        if ( fs ) {
            *plainText = fs->textDocument()->copySelection( *bodyWriter, savingContext, KoTextDocument::Standard );
            // Collect inline framesets for e.g. pictures
            KWCollectFramesetsVisitor visitor;
            fs->textDocument()->visitSelection( KoTextDocument::Standard, &visitor );
            const TQValueList<KWFrameSet *>& frameset = visitor.frameSets();
            kdDebug(32001) << frameset.count() << " inline framesets" << endl;
            for ( TQValueList<KWFrameSet *>::ConstIterator it = frameset.begin(); it != frameset.end(); ++it )
            {
                switch ( (*it)->type() ) {
                case FT_PICTURE:
                {
                    const KoPictureKey key = static_cast<KWPictureFrameSet *>( *it )->key();
                    if ( !pictureList.contains( key ) )
                        pictureList.append( key );
                }
                break;
                case FT_PART:
                    // TODO
                default:
                    break;
                }
            }
        }

        // write selected (non-inline) frames
        TQString newText;
        saveSelectedFrames( *bodyWriter, savingContext, pictureList,
                            selectedFrames, &newText ); // output vars
        *plainText += newText;
        // Single image -> return it
        if ( picture && pictureList.count() == 1 )
        {
            *picture = m_pictureCollection->findPicture( pictureList.first() );
        }
    }

    bodyWriter->endElement(); // office:text
    bodyWriter->endElement(); // office:body

    savingContext.writeFontFaces( *contentWriter );
    contentWriter->startElement( "office:automatic-styles" );
    KWOasisSaver::writeAutomaticStyles( *contentWriter, mainStyles, false );
    contentWriter->endElement(); // office:automatic-styles

    oasisStore.closeContentWriter();

    // Done with content.xml

    if ( !store->open( "styles.xml" ) )
        return false;
    manifestWriter->addManifestEntry( "styles.xml", "text/xml" );
    saveOasisDocumentStyles( store, mainStyles, savingContext, saveFlag, headerFooterContent );
    if ( !store->close() ) // done with styles.xml
        return false;

    //kdDebug(32001) << "saveOasis: " << pictureList.count() << " pictures" << endl;
    m_pictureCollection->saveOasisToStore( store, pictureList, manifestWriter );

    if ( saveFlag == SaveSelected ) {
        // Save embedded objects - code inspired from KoDocument::saveChildrenOasis,
        // for the case where we're saving only some embedded objects, like with Ctrl+C.

        // IMPORTANT: This must be done *after* we're done with writing content.xml,
        // not while writing it (like in saveSelectedFrames).
        // We can't be writing to two files at the same time.

        TQValueList<KoDocumentChild*> embeddedObjects;
        TQValueListConstIterator<KWFrameView*> framesIterator = selectedFrames.begin();
        for(; framesIterator != selectedFrames.end(); ++framesIterator) {
            KWFrame *frame = (*framesIterator)->frame();
            KWFrameSet *fs = frame->frameSet();
            if ( fs->isVisible() && fs->type() == FT_PART) {
                embeddedObjects.append( static_cast<KWPartFrameSet *>(fs)->getChild() );
            }
        }

        TQValueList<KoDocumentChild *>::const_iterator chl = embeddedObjects.begin();
        for( ; chl != embeddedObjects.end(); ++chl ) {
            if ( !(*chl)->saveOasis( store, manifestWriter ) )
                return false;
        }
    }

    if ( saveFlag == SaveAll )
    {

        if(!store->open("settings.xml"))
            return false;

        KoStoreDevice contentDev( store );
        KoXmlWriter* settingsWriter = createOasisXmlWriter(&contentDev, "office:document-settings");
        saveOasisSettings( *settingsWriter );
        delete settingsWriter;

        if(!store->close())
            return false;

        manifestWriter->addManifestEntry("settings.xml", "text/xml");
    }
    return true;
}

// can't be const due to recalcVariables()
TQDragObject* KWDocument::dragSelected( const TQValueList<KWFrameView*> &selectedFrames) {
    return dragSelectedPrivate(0, selectedFrames, 0);
}
// can't be const due to recalcVariables()
TQDragObject* KWDocument::dragSelected( TQWidget *parent, KWTextFrameSet* fs) {
    TQValueList<KWFrameView*> noFrames;
    return dragSelectedPrivate(parent, noFrames, fs);
}
// can't be const due to recalcVariables()
TQDragObject* KWDocument::dragSelectedPrivate( TQWidget *parent, const TQValueList<KWFrameView*> &selectedFrames, KWTextFrameSet* fs)
{
    // We'll create a store (ZIP format) in memory
    TQBuffer buffer;
    TQCString mimeType = KWOasisSaver::selectionMimeType();
    KoStore* store = KoStore::createStore( TQT_TQIODEVICE(&buffer), KoStore::Write, mimeType );
    Q_ASSERT( store );
    Q_ASSERT( !store->bad() );
    KoOasisStore oasisStore( store );

    KoXmlWriter* manifestWriter = oasisStore.manifestWriter( mimeType );

    TQString plainText;
    KoPicture picture;
    if ( !saveOasisHelper( store, manifestWriter, KWDocument::SaveSelected, selectedFrames, &plainText, &picture, fs )
         || !oasisStore.closeManifestWriter() )
    {
        delete store;
        return 0;
    }

    delete store;

    KMultipleDrag* multiDrag = new KMultipleDrag( parent );
    if ( !plainText.isEmpty() )
        multiDrag->addDragObject( new TQTextDrag( plainText, 0 ) );
    if ( !picture.isNull() )
        multiDrag->addDragObject( picture.dragObject( 0 ) );
    KoStoreDrag* storeDrag = new KoStoreDrag( KWOasisSaver::selectionMimeType(), 0 );
    kdDebug() << k_funcinfo << "setting zip data: " << buffer.buffer().size() << " bytes." << endl;
    storeDrag->setEncodedData( buffer.buffer() );
    multiDrag->addDragObject( storeDrag );
    return multiDrag;
}

void KWDocument::saveSelectedFrames( KoXmlWriter& bodyWriter, KoSavingContext& savingContext, TQValueList<KoPictureKey>& pictureList, const TQValueList<KWFrameView*> &selectedFrames, TQString* plainText ) const {
    TQPtrList<KoDocumentChild> embeddedObjects;
    TQValueListConstIterator<KWFrameView*> framesIterator = selectedFrames.begin();
    for(; framesIterator != selectedFrames.end(); ++framesIterator) {
        KWFrame *frame = (*framesIterator)->frame();
        KWFrameSet *fs = frame->frameSet();
        if ( fs->isVisible() && fs->type() == FT_PART) {
            embeddedObjects.append( static_cast<KWPartFrameSet *>(fs)->getChild() );
        }
        bool isTable = fs->type() == FT_TABLE;

        // Two cases to be distinguished here
        // If it's the first frame of a frameset, then copy the frameset contents and the frame itself
        // Otherwise copy only the frame information
        if ( frame == fs->frame(0) || isTable ) {
            fs->saveOasis( bodyWriter, savingContext, false );
            if ( plainText )
                *plainText += fs->toPlainText();
        }
        else if ( !isTable ) {
#if 0
            // Save the frame information
            TQDomElement frameElem = parentElem.ownerDocument().createElement( "FRAME" );
            parentElem.appendChild( frameElem );
            frame->save( frameElem );
            if ( frame != firstFrame )
            {
                // Frame saved alone -> remember which frameset it's part of
                frameElem.setAttribute( "parentFrameset", fs->name() );
            }
#endif
        }
        if ( fs->type() == FT_PICTURE ) {
            kdDebug(32001) << "found non-inline picture framesets" << endl;

            const KoPictureKey key = static_cast<KWPictureFrameSet *>( fs )->key();
            if ( !pictureList.contains( key ) )
                pictureList.append( key );
        }
        if ( isTable ) // Copy tables only once, even if they have many cells selected
            break;
    }
}

void KWDocument::saveOasisSettings( KoXmlWriter& settingsWriter ) const
{
    settingsWriter.startElement("office:settings");
    settingsWriter.startElement("config:config-item-set");

    settingsWriter.addAttribute("config:name", "view-settings");

    KoUnit::saveOasis(&settingsWriter, unit());

    settingsWriter.endElement(); // config:config-item-set

    settingsWriter.startElement("config:config-item-set");
    settingsWriter.addAttribute("config:name", "configuration-settings");
    settingsWriter.addConfigItem("SpellCheckerIgnoreList", m_spellCheckIgnoreList.join( "," ) );
    settingsWriter.endElement(); // config:config-item-set

    m_varColl->variableSetting()->saveOasis( settingsWriter );

    settingsWriter.endElement(); // office:settings
    settingsWriter.endElement(); // Root element
    settingsWriter.endDocument();
}

void KWDocument::saveOasisDocumentStyles( KoStore* store, KoGenStyles& mainStyles, KoSavingContext& savingContext, SaveFlag saveFlag, const TQByteArray& headerFooterContent ) const
{
    if ( saveFlag == SaveAll )
    {
        m_frameStyleColl->saveOasis( mainStyles, savingContext );
        m_tableStyleColl->saveOasis( mainStyles, savingContext );
    }

    KoStoreDevice stylesDev( store );
    KoXmlWriter* stylesWriter = createOasisXmlWriter( &stylesDev, "office:document-styles" );

    // Yeah we need to save the same font faces in both content.xml and styles.xml...
    savingContext.writeFontFaces( *stylesWriter );

    stylesWriter->startElement( "office:styles" );

    if ( saveFlag == SaveAll )
    {
        stylesWriter->startElement( "style:default-style" );
        stylesWriter->addAttribute( "style:family", "paragraph" );
        stylesWriter->startElement( "style:paragraph-properties" );
        stylesWriter->addAttributePt( "style:tab-stop-distance", m_tabStop );
        stylesWriter->endElement(); // paragraph-properties
        stylesWriter->endElement(); // default-style
    }

    TQValueList<KoGenStyles::NamedStyle> styles = mainStyles.styles( KoGenStyle::STYLE_USER );
    TQValueList<KoGenStyles::NamedStyle>::const_iterator it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( stylesWriter, mainStyles, "style:style", (*it).name, "style:paragraph-properties" );
    }
    styles = mainStyles.styles( KWDocument::STYLE_FRAME_USER );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( stylesWriter, mainStyles, "style:style", (*it).name , "style:graphic-properties"  );
    }
    styles = mainStyles.styles( KWDocument::STYLE_TABLE_CELL_USER );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( stylesWriter, mainStyles, "style:style", (*it).name , "style:table-cell-properties"  );
    }
    styles = mainStyles.styles( KoGenStyle::STYLE_LIST );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( stylesWriter, mainStyles, "text:list-style", (*it).name, 0 );
    }
    m_styleColl->saveOasisOutlineStyles( *stylesWriter );
    if ( saveFlag == SaveAll )
        static_cast<KWVariableSettings *>( m_varColl->variableSetting() )->saveNoteConfiguration( *stylesWriter );
    stylesWriter->endElement(); // office:styles

    TQString pageLayoutName;
    if ( saveFlag == SaveAll )
    {
        stylesWriter->startElement( "office:automatic-styles" );

        KoGenStyle pageLayout = m_pageLayout.saveOasis();
        pageLayout.addAttribute( "style:page-usage", "all" ); // needed?
        // This is for e.g. spreadsheets, not for word-processors.
        //pageLayout.addProperty( "style:first-page-number", m_varColl->variableSetting()->startingPage() );

        if ( m_processingType == WP )
        {
            KWTextFrameSet *frameset = dynamic_cast<KWTextFrameSet *>( m_lstFrameSet.getFirst() );
            if ( frameset ) {
                frameset->frame(0)->saveBorderProperties( pageLayout );
            }
        }

        TQBuffer buffer;
        buffer.open( IO_WriteOnly );
        KoXmlWriter footnoteSepTmpWriter( TQT_TQIODEVICE(&buffer) );  // TODO pass indentation level
        footnoteSepTmpWriter.startElement( "style:footnote-sep" );
        TQString tmp;
        switch( m_footNoteSeparatorLinePos )
        {
        case SLP_CENTERED:
            tmp = "centered";
            break;
        case SLP_RIGHT:
            tmp = "right";
            break;
        case SLP_LEFT:
            tmp = "left";
            break;
        }

        footnoteSepTmpWriter.addAttribute( "style:adjustment", tmp );
        footnoteSepTmpWriter.addAttributePt( "style:width", m_footNoteSeparatorLineWidth );
        footnoteSepTmpWriter.addAttribute( "style:rel-width", TQString::number( footNoteSeparatorLineLength() ) + "%" );
        switch( m_footNoteSeparatorLineType )
        {
        case SLT_SOLID:
            tmp = "solid";
            break;
        case SLT_DASH:
            tmp = "dash";
            break;
        case SLT_DOT:
            tmp = "dotted";
            break;
        case SLT_DASH_DOT:
            tmp = "dot-dash";
            break;
        case SLT_DASH_DOT_DOT:
            tmp = "dot-dot-dash";
            break;
        }

        footnoteSepTmpWriter.addAttribute( "style:line-style", tmp );

        footnoteSepTmpWriter.endElement();
        const TQString elementContents = TQString::fromUtf8( buffer.buffer(), buffer.buffer().size() );
        pageLayout.addChildElement( "separator", elementContents );
        buffer.close();

        if ( m_pageColumns.columns > 1 ) {
            buffer.setBuffer(TQByteArray()); // clear data
            buffer.open( IO_WriteOnly );
            KoXmlWriter columnsTmpWriter( TQT_TQIODEVICE(&buffer) );  // TODO pass indentation level
            columnsTmpWriter.startElement( "style:columns" );
            columnsTmpWriter.addAttribute( "fo:column-count", m_pageColumns.columns );
            columnsTmpWriter.addAttributePt( "fo:column-gap", m_pageColumns.ptColumnSpacing );
            columnsTmpWriter.endElement(); // style:columns
            buffer.close();
            const TQString elementContents = TQString::fromUtf8( buffer.buffer(), buffer.buffer().size() );
            pageLayout.addChildElement( "columns", elementContents );
        }

        // This is a bit of a hack, which only works as long as we have only one page master
        // if there's more than one pagemaster we need to rethink all this

        pageLayoutName = mainStyles.lookup( pageLayout, "pm" );
        pageLayout.writeStyle( stylesWriter, mainStyles, "style:page-layout", pageLayoutName,
                               "style:page-layout-properties", false /*don't close*/ );

        // Ouch another problem: there is only one header style in oasis
        // ##### can't have different borders for even/odd headers...
        bool headerStyleSaved = false;
        bool footerStyleSaved = false;
        // ## This loop is duplicated in saveOasis
        TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
        for ( ; fit.current() ; ++fit ) {
            const KWFrameSet* fs = fit.current();
            if ( fs->isVisible() && // HACK to avoid saving [hidden] headers/footers framesets for now
                 !fs->isFloating() &&
                 !fs->isDeleted() &&
                 fs->type() == FT_TEXT &&
                 fs->isHeaderOrFooter() )
            {
                // Save header/footer style
                KWFrame* frame = fs->frame(0);
                if ( fs->isAHeader() ) {
                    if ( headerStyleSaved )
                        continue;
                    headerStyleSaved = true;
                    stylesWriter->startElement( "style:header-style" );
                } else {
                    if ( footerStyleSaved )
                        continue;
                    footerStyleSaved = true;
                    stylesWriter->startElement( "style:footer-style" );
                }
#if 0 // more code reuse, but harder to integrate
                KoGenStyle hfStyle;
                hfStyle.addPropertyPt( "fo:min-height", frame->minimumFrameHeight() );
                frame->saveBorderProperties( hfStyle );
                frame->saveMarginProperties( hfStyle );
                ...
#endif
                stylesWriter->startElement( "style:header-footer-properties" );
                stylesWriter->addAttributePt( "fo:min-height", frame->minimumFrameHeight() );
                if ( fs->isAHeader() )
                    stylesWriter->addAttributePt( "fo:margin-bottom", m_pageHeaderFooter.ptHeaderBodySpacing );
                else
                    stylesWriter->addAttributePt( "fo:margin-top", m_pageHeaderFooter.ptFooterBodySpacing );
                // TODO frame->saveBorderAttributes( *stylesWriter );
                // Interesting idea, but we can't set margins (runaround) on
                //frame->saveMarginAttributes( *stylesWriter );
                stylesWriter->endElement(); // header-footer-properties
                stylesWriter->endElement(); // header-style
            }
        }
        stylesWriter->endElement(); // style:page-layout

        // Headers and footers might have created new automatic parag/text styles -> save those
        KWOasisSaver::writeAutomaticStyles( *stylesWriter, mainStyles, true );

        stylesWriter->endElement(); // office:automatic-styles
    }


    stylesWriter->startElement( "office:master-styles" );
    stylesWriter->startElement( "style:master-page" );
    stylesWriter->addAttribute( "style:name", "Standard" );
    stylesWriter->addAttribute( "style:page-layout-name", pageLayoutName );

    if ( isHeaderVisible() || isFooterVisible() ) { // ### TODO save them even when hidden (and not empty)?
        stylesWriter->addCompleteElement( headerFooterContent.data() );
    }

    stylesWriter->endElement();
    stylesWriter->endElement(); // office:master-styles

    stylesWriter->endElement(); // root element (office:document-styles)
    stylesWriter->endDocument();
    delete stylesWriter;
}

void KWDocument::saveOasisCustomFied( KoXmlWriter &writer )const
{
    bool customVariableFound = false;
    TQPtrListIterator<KoVariable> it( m_varColl->getVariables() );
    for ( ; it.current() ; ++it )
    {
        if ( it.current()->type() == VT_CUSTOM )
        {
            if ( !customVariableFound )
            {
                writer.startElement( "text:user-field-decls" );
                customVariableFound = true;
            }
            //<text:user-field-decl office:value-type="string" office:string-value="dfddd" text:name="cvbcbcbx"/>
            writer.startElement( "text:user-field-decl" );
            writer.addAttribute( "office:value-type", "string" );
            writer.addAttribute( "office:string-value", static_cast<KoCustomVariable *>( it.current() )->value() );
            writer.addAttribute( "text:name", static_cast<KoCustomVariable*>( it.current() )->name() );
            writer.endElement();
        }
    }
    if ( customVariableFound )
        writer.endElement();
}

void KWDocument::saveOasisBody( KoXmlWriter& writer, KoSavingContext& context ) const
{
    saveOasisCustomFied( writer );
    if ( m_processingType == WP ) {

        // Write out the non-inline framesets first; OOo wants it that way...
        TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
        ++fit; // skip main text frameset
        for ( ; fit.current() ; ++fit ) {
            KWFrameSet* fs = fit.current();
            if ( !fs->isFloating() &&
                 !fs->isDeleted() &&
                // footnotes already saved inline, header/footers elsewhere
                 fs->frameSetInfo() == KWFrameSet::FI_BODY )
            {
                fs->saveOasis( writer, context, true );
            }
        }

        // Write out the main text frameset's contents
        KWTextFrameSet *frameset = dynamic_cast<KWTextFrameSet *>( m_lstFrameSet.getFirst() );
        if ( frameset ) {
            frameset->saveOasisContent( writer, context );
        }

    } else { // DTP mode: all framesets are equal
        // write text:page-sequence, one item per page.
        writer.startElement( "text:page-sequence" );
        for ( int page = 0; page < pageCount(); ++page )
        {
            writer.startElement( "text:page" );
            // "pm" is a hack, see mainStyles.lookup( pageLayout, "pm" ) in saveOasis
            // [which currently happens afterwards...]
            writer.addAttribute( "text:master-page-name", "pm" );
            writer.endElement(); // text:page
        }
        writer.endElement() ; // "text:page-sequence";
        // Now write the framesets
        TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
        for ( ; fit.current() ; ++fit ) {
            KWFrameSet* fs = fit.current();
            if ( !fs->isFloating() &&
                 !fs->isDeleted() &&
                 fs->frameSetInfo() == KWFrameSet::FI_BODY )
            {
                fs->saveOasis( writer, context, true );
            }
        }
     }
}

TQDomDocument KWDocument::saveXML()
{
    m_varColl->variableSetting()->setModificationDate(TQDateTime::currentDateTime());
    recalcVariables( VT_DATE );
    recalcVariables( VT_TIME ); // for "current time"
    recalcVariables( VT_STATISTIC );
    TQDomDocument doc = createDomDocument( "DOC", CURRENT_DTD_VERSION );
    TQDomElement kwdoc = doc.documentElement();
    kwdoc.setAttribute( "editor", "KWord" );
    kwdoc.setAttribute( "mime", "application/x-kword" );
    m_syntaxVersion = CURRENT_SYNTAX_VERSION;
    kwdoc.setAttribute( "syntaxVersion", m_syntaxVersion );

    TQDomElement paper = doc.createElement( "PAPER" );
    kwdoc.appendChild( paper );
    paper.setAttribute( "format", static_cast<int>( m_pageLayout.format ) );
    paper.setAttribute( "pages", pageCount() );
    paper.setAttribute( "width", m_pageLayout.ptWidth );
    paper.setAttribute( "height", m_pageLayout.ptHeight );
    paper.setAttribute( "orientation", static_cast<int>( m_pageLayout.orientation ) );
    paper.setAttribute( "columns", m_pageColumns.columns );
    paper.setAttribute( "columnspacing", m_pageColumns.ptColumnSpacing );
    paper.setAttribute( "hType", static_cast<int>( m_pageHeaderFooter.header ) );
    paper.setAttribute( "fType", static_cast<int>( m_pageHeaderFooter.footer ) );
    paper.setAttribute( "spHeadBody", m_pageHeaderFooter.ptHeaderBodySpacing );
    paper.setAttribute( "spFootBody", m_pageHeaderFooter.ptFooterBodySpacing );
    paper.setAttribute( "spFootNoteBody", m_pageHeaderFooter.ptFootNoteBodySpacing );
    if ( m_footNoteSeparatorLinePos!=SLP_LEFT )
    {
        if (m_footNoteSeparatorLinePos==SLP_CENTERED )
            paper.setAttribute( "slFootNotePosition", "centered" );
        else if ( m_footNoteSeparatorLinePos==SLP_RIGHT )
            paper.setAttribute( "slFootNotePosition", "right" );
        else if ( m_footNoteSeparatorLinePos==SLP_LEFT ) //never !
            paper.setAttribute( "slFootNotePosition", "left" );
    }
    if ( m_footNoteSeparatorLineType != SLT_SOLID )
        paper.setAttribute( "slFootNoteType", static_cast<int>(m_footNoteSeparatorLineType) );


    paper.setAttribute("slFootNoteLength", m_iFootNoteSeparatorLineLength);
    paper.setAttribute("slFootNoteWidth", m_footNoteSeparatorLineWidth);

    // Now part of the app config
    //paper.setAttribute( "zoom",m_zoom );

    TQDomElement borders = doc.createElement( "PAPERBORDERS" );
    paper.appendChild( borders );
    borders.setAttribute( "left", m_pageLayout.ptLeft );
    borders.setAttribute( "top", m_pageLayout.ptTop );
    borders.setAttribute( "right", m_pageLayout.ptRight );
    borders.setAttribute( "bottom", m_pageLayout.ptBottom );

    TQDomElement docattrs = doc.createElement( "ATTRIBUTES" );
    kwdoc.appendChild( docattrs );
    docattrs.setAttribute( "processing", static_cast<int>( m_processingType ) );
    docattrs.setAttribute( "standardpage", 1 );
    docattrs.setAttribute( "hasHeader", static_cast<int>(isHeaderVisible()) );
    docattrs.setAttribute( "hasFooter", static_cast<int>(isFooterVisible()) );
    docattrs.setAttribute( "unit", KoUnit::unitName(unit()) );
    docattrs.setAttribute( "hasTOC", static_cast<int>(m_hasTOC));
    docattrs.setAttribute( "tabStopValue", m_tabStop );

    // Save visual info for the first view, such as the active frameset and cursor position
    // It looks like a hack, but reopening a document creates only one view anyway (David)
    KWView * view = static_cast<KWView*>(views().getFirst());
    if ( view ) // no view if embedded document
    {
        KWFrameSetEdit* edit = view->getGUI()->canvasWidget()->currentFrameSetEdit();
        if ( edit )
        {
            docattrs.setAttribute( "activeFrameset", edit->frameSet()->name() );
            KWTextFrameSetEdit* textedit = dynamic_cast<KWTextFrameSetEdit *>(edit);
            if ( textedit && textedit->cursor() ) {
                KoTextCursor* cursor = textedit->cursor();
                docattrs.setAttribute( "cursorParagraph", cursor->parag()->paragId() );
                docattrs.setAttribute( "cursorIndex", cursor->index() );
            }
        }
    }

    if( !m_bookmarkList->isEmpty() )
    {
        TQDomElement bookmark = doc.createElement( "BOOKMARKS" );
        kwdoc.appendChild( bookmark );

        for ( KoTextBookmarkList::const_iterator it = m_bookmarkList->begin();
              it != m_bookmarkList->end() ; ++it )
        {
            const KoTextBookmark& book = *it;
            KWTextFrameSet* fs = static_cast<KWTextDocument*>(book.textDocument())->textFrameSet();
            if ( book.startParag() &&
                 book.endParag() &&
                 fs && !fs->isDeleted() )
            {
                TQDomElement bookElem = doc.createElement( "BOOKMARKITEM" );
                bookmark.appendChild( bookElem );
                bookElem.setAttribute( "name", book.bookmarkName() );
                bookElem.setAttribute( "frameset", fs->name() );
                bookElem.setAttribute( "startparag", book.startParag()->paragId() );
                bookElem.setAttribute( "endparag", book.endParag()->paragId() );

                bookElem.setAttribute( "cursorIndexStart", book.bookmarkStartIndex() );
                bookElem.setAttribute( "cursorIndexEnd", book.bookmarkEndIndex() );
            }
        }
    }
    variableCollection()->variableSetting()->save(kwdoc );

    TQDomElement framesets = doc.createElement( "FRAMESETS" );
    kwdoc.appendChild( framesets );

    m_textImageRequests.clear(); // for KWTextImage
    TQValueList<KoPictureKey> savePictures;

    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
    {
        KWFrameSet *frameSet = fit.current();
        // Save non-part framesets ( part are saved further down )
        if ( frameSet->type() != FT_PART )
            frameSet->save( framesets );

        // If picture frameset, make a note of the image it needs.
        if ( !frameSet->isDeleted() && ( frameSet->type() == FT_PICTURE ) )
        {
            KoPictureKey key = static_cast<KWPictureFrameSet *>( frameSet )->key();
            if ( !savePictures.contains( key ) )
                savePictures.append( key );
        }
    }

    // Process the data of the KWTextImage classes.
    TQPtrListIterator<KWTextImage> textIt ( m_textImageRequests );
    for ( ; textIt.current() ; ++textIt )
    {
        KoPictureKey key = textIt.current()->getKey();
        kdDebug(32001) << "KWDocument::saveXML registering text image " << key.toString() << endl;
        if ( !savePictures.contains( key ) )
            savePictures.append( key );
    }

    TQDomElement styles = doc.createElement( "STYLES" );
    kwdoc.appendChild( styles );
    TQValueList<KoUserStyle *> styleList(m_styleColl->styleList());
    for ( TQValueList<KoUserStyle *>::const_iterator it = styleList.begin(), end = styleList.end();
          it != end ; ++it )
        saveStyle( static_cast<KoParagStyle *>( *it ), styles );

    TQDomElement frameStyles = doc.createElement( "FRAMESTYLES" );
    kwdoc.appendChild( frameStyles );
    TQValueList<KoUserStyle *> frameStyleList(m_frameStyleColl->styleList());
    for ( TQValueList<KoUserStyle *>::const_iterator it = frameStyleList.begin(), end = frameStyleList.end();
          it != end ; ++it )
        saveFrameStyle( static_cast<KWFrameStyle *>(*it), frameStyles );

    TQDomElement tableStyles = doc.createElement( "TABLESTYLES" );
    kwdoc.appendChild( tableStyles );
    TQValueList<KoUserStyle *> tableStyleList(m_tableStyleColl->styleList());
    for ( TQValueList<KoUserStyle *>::const_iterator it = tableStyleList.begin(), end = tableStyleList.end();
          it != end ; ++it )
        saveTableStyle( static_cast<KWTableStyle *>(*it), tableStyles );

    TQDomElement pictures = m_pictureCollection->saveXML( KoPictureCollection::CollectionPicture, doc, savePictures );
    kwdoc.appendChild( pictures );

    // Not needed anymore
#if 0
    // Write out the list of parags (id) that form the table of contents, see KWContents::createContents
    if ( contents->hasContents() ) {
        TQDomElement cParags = doc.createElement( "CPARAGS" );
        kwdoc.appendChild( cParags );
        TQValueList<int>::Iterator it = contents->begin();
        for ( ; it != contents->end(); ++it )
        {
            TQDomElement paragElem = doc.createElement( "PARAG" );
            cParags.appendChild( paragElem );
            paragElem.setAttribute( "name", TQString::number( *it ) ); // write parag id
        }
    }
#endif

    TQDomElement mailMerge=m_slDataBase->save(doc);
    kwdoc.appendChild(mailMerge);

    if( !m_spellCheckIgnoreList.isEmpty() )
    {
        TQDomElement spellCheckIgnore = doc.createElement( "SPELLCHECKIGNORELIST" );
        kwdoc.appendChild( spellCheckIgnore );
        for ( TQStringList::ConstIterator it = m_spellCheckIgnoreList.begin(); it != m_spellCheckIgnoreList.end(); ++it )
        {
            TQDomElement spellElem = doc.createElement( "SPELLCHECKIGNOREWORD" );
            spellCheckIgnore.appendChild( spellElem );
            spellElem.setAttribute( "word", *it );
        }
    }

    // Save embedded objects
    saveEmbeddedObjects( kwdoc, children() );
    return doc;
}

// KWord-1.3 format
void KWDocument::saveEmbeddedObjects( TQDomElement& parentElem, const TQPtrList<KoDocumentChild>& childList )
{
    // Write "OBJECT" tag for every child, appending "EMBEDDING" tags to the main XML
    TQPtrListIterator<KoDocumentChild> chl( childList );
    TQDomDocument doc = parentElem.ownerDocument();
    for( ; chl.current(); ++chl ) {
        KWDocumentChild* curr = static_cast<KWDocumentChild*>(chl.current());
        if ( !curr->isDeleted() )
        {
            TQDomElement embeddedElem = doc.createElement( "EMBEDDED" );
            parentElem.appendChild( embeddedElem );

            TQDomElement objectElem = curr->save( doc, true );
            embeddedElem.appendChild( objectElem );

            TQDomElement settingsElem = doc.createElement( "SETTINGS" );
            embeddedElem.appendChild( settingsElem );

            curr->partFrameSet()->save( settingsElem );
        }
    }
}

// KWord-1.3 format
void KWDocument::saveStyle( KoParagStyle *sty, TQDomElement parentElem )
{
    TQDomDocument doc = parentElem.ownerDocument();
    TQDomElement styleElem = doc.createElement( "STYLE" );
    parentElem.appendChild( styleElem );

    sty->saveStyle( styleElem );

    TQDomElement formatElem = KWTextParag::saveFormat( doc, &sty->format(), 0L, 0, 0 );
    styleElem.appendChild( formatElem );
}

// KWord-1.3 format
void KWDocument::saveFrameStyle( KWFrameStyle *sty, TQDomElement parentElem )
{
    TQDomDocument doc = parentElem.ownerDocument();
    TQDomElement frameStyleElem = doc.createElement( "FRAMESTYLE" );
    parentElem.appendChild( frameStyleElem );

    sty->saveFrameStyle( frameStyleElem );
}

// KWord-1.3 format
void KWDocument::saveTableStyle( KWTableStyle *sty, TQDomElement parentElem )
{
    TQDomDocument doc = parentElem.ownerDocument();
    TQDomElement tableStyleElem = doc.createElement( "TABLESTYLE" );
    parentElem.appendChild( tableStyleElem );

    sty->saveTableStyle( tableStyleElem );
}


TQValueList<KoPictureKey> KWDocument::savePictureList()
{
    TQValueList<KoPictureKey> savePictures;

    // At first, we must process the data of the KWTextImage classes.
    // Process the data of the KWTextImage classes.
    TQPtrListIterator<KWTextImage> textIt ( m_textImageRequests );
    for ( ; textIt.current() ; ++textIt )
    {
        KoPictureKey key = textIt.current()->getKey();
        kdDebug(32001) << "KWDocument::saveXML registering text image " << key.toString() << endl;
        if ( !savePictures.contains( key ) )
            savePictures.append( key );
    }
    m_textImageRequests.clear(); // Save some memory!

    // Now do the images/cliparts in frames.
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
    {
        KWFrameSet *frameSet = fit.current();
        // If picture frameset, make a note of the image it needs.
        if ( !frameSet->isDeleted() && ( frameSet->type() == FT_PICTURE ) )
        {
            KoPictureKey key = static_cast<KWPictureFrameSet *>( frameSet )->key();
            if ( !savePictures.contains( key ) )
                savePictures.append( key );
        }
    }
    return savePictures;
}

// KWord-1.3 format
bool KWDocument::completeSaving( KoStore *store )
{
    if ( !store )
        return TRUE;

    TQString u = KURL( url() ).path();

    TQValueList<KoPictureKey> savePictures( savePictureList() );

    return m_pictureCollection->saveToStore( KoPictureCollection::CollectionPicture, store, savePictures );
}

int KWDocument::supportedSpecialFormats() const
{
    return KoDocument::supportedSpecialFormats();
}

void KWDocument::addView( KoView *view )
{
    m_lstViews.append( (KWView*)view );
    KoDocument::addView( view );
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it ) {
        (*it)->deselectAllFrames();
    }
}

void KWDocument::removeView( KoView *view )
{
    m_lstViews.remove( static_cast<KWView*>(view) );
    KoDocument::removeView( view );
}

void KWDocument::addShell( KoMainWindow *shell )
{
    connect( shell, TQT_SIGNAL( documentSaved() ), m_commandHistory, TQT_SLOT( documentSaved() ) );
    connect( shell, TQT_SIGNAL( saveDialogShown() ), this, TQT_SLOT( saveDialogShown() ) );
    KoDocument::addShell( shell );
}

KoView* KWDocument::createViewInstance( TQWidget* parent, const char* name )
{
    if ( isEmbedded() )
        return new KWView( "ModeEmbedded", parent, name, this );
    else
        return new KWView( m_viewModeType, parent, name, this );
}

// Paint this document when it's embedded
// This is also used to paint the preview.png that goes into the ZIP file
void KWDocument::paintContent( TQPainter& painter, const TQRect& rectangle, bool transparent, double zoomX, double zoomY )
{
    //kdDebug(32001) << "KWDocument::paintContent m_zoom=" << m_zoom << " zoomX=" << zoomX << " zoomY=" << zoomY << " transparent=" << transparent << " rectangle=" << rectangle << endl;
    Q_ASSERT( zoomX != 0 );
    Q_ASSERT( zoomY != 0 );

    setZoom( 100 );
    m_zoomMode = KoZoomMode::ZOOM_CONSTANT;

    // The caller doesn't care about DPI, that's our own internal zooming done on top of it:
    zoomX *= POINT_TO_INCH( static_cast<double>( KoGlobal::dpiX() ) );
    zoomY *= POINT_TO_INCH( static_cast<double>( KoGlobal::dpiY() ) );

    if ( m_zoomedResolutionX != zoomX || m_zoomedResolutionY != zoomY )
    {
        //kdDebug(32001) << "m_zoomedResolutionX=" << m_zoomedResolutionX << " != " << zoomX << " -> calling setResolution(" << zoomX << ")" << endl;
        int zoomLevel = tqRound( 100 * zoomY / m_zoomedResolutionY ); // ## ignores the case where the x and y scaling differs
        setZoom( zoomLevel );
        bool forPrint = painter.device() && painter.device()->devType() == TQInternal::Printer;
        newZoomAndResolution( false, forPrint );
        if ( KFormula::Document* formulaDocument = m_formulaDocumentWrapper->document() )
            formulaDocument->setZoomAndResolution( zoomLevel, zoomX, zoomY, false, forPrint );
        // Note that this zoom and resolution are then used when activating the embedded object!
    }

    TQRect rect( rectangle );
    painter.save();
    painter.translate( rect.x(), rect.y() );
    TQRect clipRect( 0, 0, rect.width(), rect.height() );

    KWViewModeEmbedded * viewMode = new KWViewModeEmbedded( this, 0 /*no canvas*/ );
    viewMode->setDrawFrameBackground( !transparent );
    viewMode->setDrawSelections( false );

    TQColorGroup cg = TQApplication::palette().active();

    if (!transparent)
    {
        TQRegion emptyRegion( rect );
        createEmptyRegion( rect, emptyRegion, viewMode );
        eraseEmptySpace( &painter, emptyRegion, cg.brush( TQColorGroup::Base ) );
    }

    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
    {
        KWFrameSet * frameset = fit.current();
        if ( frameset->isVisible( viewMode ) && !frameset->isFloating() )
            frameset->drawContents( &painter, clipRect, cg,
                                    false /*onlyChanged*/, true /*resetChanged*/,
                                    0L, viewMode, 0 );
    }
    delete viewMode;

    painter.restore();
}

TQPixmap KWDocument::generatePreview( const TQSize& size )
{
    int oldZoom = m_zoom;
    double oldResolutionX = resolutionX();
    double oldResolutionY = resolutionY();
    double oldZoomX = zoomedResolutionX();
    double oldZoomY = zoomedResolutionY();

    // Sometimes (due to the different resolution?) the layout creates a new page
    // while saving the preview. If this happens, we don't want to repaint the real views
    // (due to KWCanvas::slotNewContentsSize)
    // ##### One day when we have real doc/view separation in kotextparag, we shouldn't mess with
    // the real view's resolution, we should instead create a fake view for the preview itself.
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it ) {
        (*it)->getGUI()->canvasWidget()->setUpdatesEnabled( false );
    }
    Q_ASSERT( !m_bGeneratingPreview );
    m_bGeneratingPreview = true;
    TQPixmap pix = KoDocument::generatePreview(size);

    // Restore everything as it was before
    setResolution( oldResolutionX, oldResolutionY );
    setZoom( oldZoom );

    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it ) {
        (*it)->getGUI()->canvasWidget()->setUpdatesEnabled( true );
    }
    newZoomAndResolution( true /*set contents size again*/, false );
    m_bGeneratingPreview = false;
    if ( KFormula::Document* formulaDocument = m_formulaDocumentWrapper->document() ) {
        formulaDocument->setZoomAndResolution( oldZoom, oldZoomX, oldZoomY );
    }
    return pix;
}

void KWDocument::createEmptyRegion( const TQRect & crect, TQRegion & emptyRegion, KWViewMode * viewMode )
{
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
    {
        KWFrameSet *frameset = fit.current();
        if ( frameset->isVisible( viewMode ) )
            frameset->createEmptyRegion( crect, emptyRegion, viewMode );
    }
}

void KWDocument::eraseEmptySpace( TQPainter * painter, const TQRegion & emptySpaceRegion, const TQBrush & brush )
{
    painter->save();
    painter->setClipRegion( emptySpaceRegion, TQPainter::CoordPainter );
    painter->setPen( TQt::NoPen );

    //kdDebug(32001) << "KWDocument::eraseEmptySpace emptySpaceRegion: " << emptySpaceRegion << endl;
    //kdDebug(32001) << "                            boundingRect: " << DEBUGRECT( emptySpaceRegion.boundingRect() ) << endl;
    painter->fillRect( emptySpaceRegion.boundingRect(), brush );
    painter->restore();
}

KWDocumentChild* KWDocument::createChildDoc( const KoRect& rect, KoDocument* childDoc )
{
    KWDocumentChild* ch = new KWDocumentChild( this, rect.toTQRect(), childDoc );
    insertChild( ch );
    return ch;
}

KWPartFrameSet* KWDocument::insertObject( const KoRect& rect, KoDocumentEntry& e, TQWidget* parentWidget )
{
    KoDocument* doc = e.createDoc( this );
    if ( !doc )
        return 0;
    if ( !doc->showEmbedInitDialog( parentWidget )  )
        return 0;

    KWDocumentChild* ch = createChildDoc( rect, doc );
    setModified( TRUE );

    KWPartFrameSet *frameset = new KWPartFrameSet( this, ch, TQString() );
    KWFrame *frame = new KWFrame(frameset, rect.x(), rect.y(), rect.width(), rect.height() );
    frame->setZOrder( maxZOrder( frame->pageNumber(this) ) + 1 ); // make sure it's on top
    frameset->addFrame( frame );
    addFrameSet( frameset );

    KWCreateFrameCommand *cmd = new KWCreateFrameCommand( i18n("Create Part Frame"), frame);
    addCommand(cmd);

    frameChanged( frame ); // repaint etc.

    return frameset;
}


void KWDocument::delayedRepaintAllViews() {
    if (!m_repaintAllViewsPending) {
        TQTimer::singleShot( 0, this, TQT_SLOT( slotRepaintAllViews() ) );
        m_repaintAllViewsPending=true;
    }
}

void KWDocument::slotRepaintAllViews() {
    m_repaintAllViewsPending=false;
    repaintAllViews( false );
}

void KWDocument::delayedRecalcFrames( int fromPage ) {
    //kdDebug() << k_funcinfo << fromPage << endl;
    if ( m_recalcFramesPending == -1 || fromPage < m_recalcFramesPending )
    {
        m_recalcFramesPending = fromPage;
        TQTimer::singleShot( 0, this, TQT_SLOT( slotRecalcFrames() ) );
    }
}

void KWDocument::slotRecalcFrames() {
    int from = m_recalcFramesPending;
    kdDebug() << k_funcinfo << "from=" << from << endl;
    m_recalcFramesPending = -1;
    if ( from != -1 )
        recalcFrames( from );
}

void KWDocument::repaintAllViewsExcept( KWView *view, bool erase )
{
    //kdDebug(32001) << "KWDocument::repaintAllViewsExcept" << endl;
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it ) {
        KWView* viewPtr = *it;
        if ( viewPtr != view /*&& viewPtr->getGUI() && viewPtr->getGUI()->canvasWidget()*/ ) {
            viewPtr->getGUI()->canvasWidget()->repaintAll( erase );
        }
    }
}

void KWDocument::updateAllStyleLists()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->updateStyleList();
}

void KWDocument::updateStyleListOrder( const TQStringList &list )
{
    styleCollection()->updateStyleListOrder( list );
}

void KWDocument::applyStyleChange( KoStyleChangeDefMap changed )
{
    TQPtrList<KWTextFrameSet> textFramesets = allTextFramesets( true );

    KWTextFrameSet *frm;
    for ( frm=textFramesets.first(); frm != 0; frm=textFramesets.next() ){
        frm->applyStyleChange( changed );
    }
}

void KWDocument::updateAllFrameStyleLists()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->updateFrameStyleList();
}

void KWDocument::updateAllTableStyleLists()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->updateTableStyleList();
}

void KWDocument::repaintAllViews( bool erase )
{
    //kdDebug(32001) << "KWDocument::repaintAllViews" << endl;
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->getGUI()->canvasWidget()->repaintAll( erase );
}

TQPtrList<KWFrame> KWDocument::framesToCopyOnNewPage( int afterPageNum ) const {
    // afterPageNum can be -1 for 'before page 1'

    // Look at frames on pages afterPageNum and afterPageNum-1 (for sheetside stuff)
    TQPtrList<KWFrame> framesToLookAt;
    if ( afterPageNum >= startPage() )
        framesToLookAt = framesInPage( afterPageNum, false );

    if ( afterPageNum >= startPage() + 1 )
    {
        TQPtrList<KWFrame> framesToAlsoLookAt = framesInPage( afterPageNum-1, false ); // order doesn't matter

        // Merge into single list. Other alternative, two loops, code inside moved to another method.
        TQPtrListIterator<KWFrame> frameAlsoIt( framesToAlsoLookAt );
        for ( ; frameAlsoIt.current(); ++frameAlsoIt )
            framesToLookAt.append( frameAlsoIt.current() );
    }

    TQPtrList<KWFrame> framesToCopy; // the result

    TQPtrListIterator<KWFrame> frameIt( framesToLookAt );
    for ( ; frameIt.current(); ++frameIt )
    {
        KWFrame * frame = frameIt.current();
        KWFrameSet* frameSet = frame->frameSet();

        // don't add tables! A table cell ( frameset ) _must_ not have cells auto-added to them!
        if ( frameSet->type() == FT_TABLE ) continue;

        // NewFrameBehavior == Copy is handled here except for headers/footers, which
        // are created in recalcFrames()
        if(frameSet->isAHeader() || frameSet->isAFooter()) continue;

#ifdef DEBUG_PAGES
        kdDebug(32002) << "KWDocument::framesToCopyOnNewPage looking at frame " << frame << ", pageNum=" << frame->pageNumber() << " from " << frameSet->name() << endl;
        static const char * newFrameBh[] = { "Reconnect", "NoFollowup", "Copy" };
        kdDebug(32002) << "   frame->newFrameBehavior()==" << newFrameBh[frame->newFrameBehavior()] << endl;
#endif
        const int frameIsOnPage = frame->pageNumber();
        if (frame->newFrameBehavior() == KWFrame::Copy &&
                (frameIsOnPage == afterPageNum && frame->sheetSide() == KWFrame::AnySide ||
                 frameIsOnPage == afterPageNum -1 && frame->sheetSide() != KWFrame::AnySide))
            framesToCopy.append( frame );
    }
    return framesToCopy;
}

KWPage* KWDocument::insertPage( int afterPageNum ) // can be -1 for 'before page 0'
{
#ifdef DEBUG_PAGES
    kdDebug(32002) << "insertPage: afterPageNum=" << afterPageNum << endl;
#endif
    if ( processingType() == WP )
        Q_ASSERT( afterPageNum == lastPage() ); // WP mode: can only append.

    double pageHeight = pageManager()->page( afterPageNum )->height();
    // If not appending, move down everything after 'afterPageNum', to make room.
    for ( int pg = pageCount () -1 ; pg > afterPageNum ; --pg )
    {
        // pg is the 'src' page. Its contents must be moved to the page pg+1
        TQPtrList<KWFrame> frames = framesInPage( pg, false );
#ifdef DEBUG_PAGES
        kdDebug(32002) << "insertPage: moving " << frames.count() << " frames down, from page " << pg << endl;
#endif
        TQPtrListIterator<KWFrame> frameIt( frames );
        for ( ; frameIt.current(); ++frameIt )
            frameIt.current()->moveBy( 0, pageHeight );
    }

    KWPage *page = pageManager()->insertPage(afterPageNum+1);

    // Fill in the new page
    TQPtrList<KWFrame> framesToCopy = framesToCopyOnNewPage( afterPageNum );
    TQPtrListIterator<KWFrame> frameIt( framesToCopy );
    for ( ; frameIt.current(); ++frameIt )
    {
        KWFrame * frame = frameIt.current();

        KWFrame *newFrame = frame->getCopy();
        newFrame->moveBy( 0, pageHeight );
        frame->frameSet()->addFrame( newFrame );

        if ( frame->newFrameBehavior()==KWFrame::Copy )
            newFrame->setCopy( true );
        //kdDebug(32002) << "   => created frame " << newFrame << " " << *newFrame << endl;
    }
    return page;
}

KWPage* KWDocument::appendPage()
{
#ifdef DEBUG_PAGES
    kdDebug(32002) << "KWDocument::appendPage pageCount()=" << pageCount() << " -> insertPage(" << lastPage() << ")" << endl;
#endif
    return insertPage( lastPage() );
}

void KWDocument::afterInsertPage( int pageNum )
{
#ifdef DEBUG_PAGES
    kdDebug(32002) << "KWDocument::afterInsertPage " << pageNum << endl;
#endif
    if ( !m_bGeneratingPreview )
        emit newContentsSize();

    // Get headers and footers on the new page
    // This shouldn't delete the newly created page because it's still empty though
    recalcFrames( pageNum, -1, KWFrameLayout::DontRemovePages );
    // Take into account the frames on the new page, and run updateFramesOnTopOrBelow (#73819)
    updateAllFrames();

    recalcVariables( VT_PGNUM );
    emit numPagesChanged();
    if ( m_viewModeType == "ModePreview" )
        repaintAllViews();
}

bool KWDocument::canRemovePage( int num )
{
kdDebug() << "KWDocument::canRemovePage " << num<< endl;
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
    {
        KWFrameSet * frameSet = fit.current();
        if ( frameSet->isHeaderOrFooter() ) // don't look at headers/footers, but look at footnotes/endnotes
            continue;
        if ( frameSet->isVisible() && !frameSet->canRemovePage( num ) )
            return false;
    }
#ifdef DEBUG_PAGES
    kdDebug(32002) << "KWDocument::canRemovePage " << num << "-> TRUE" << endl;
#endif
    return true;
}

void KWDocument::removePage( int pageNum )
{
    if ( processingType() == WP )
        Q_ASSERT( pageNum == lastPage() ); // WP mode: can only remove last page.
    Q_ASSERT( pageCount() > 1 );
    if ( pageCount() == 1 )
        return;

    // ## This assumes that framesInPage is up-to-date.
    TQPtrList<KWFrame> framesToDelete = framesInPage( pageNum, false );
#ifdef DEBUG_PAGES
    kdDebug(32002) << "KWDocument::removePage " << pageNum << ", " << framesToDelete.count() << " frames to delete" << endl;
#endif
    TQPtrListIterator<KWFrame> frameIt( framesToDelete );
    for ( ; frameIt.current(); ++frameIt )
    {
        KWFrame * frame = frameIt.current();
        KWFrameSet * frameSet = frame->frameSet();
        if ( frameSet->frameSetInfo() != KWFrameSet::FI_BODY )
            continue;
        frameSet->deleteFrame( frame, true );
    }

    // If not removing the last one, move up everything after the one we removed.
    for ( int pg = pageNum+1 ; pg < pageCount() ; ++pg )
    {
        // pg is the 'src' page. Its contents must be moved to the page pg-1
        TQPtrList<KWFrame> frames = framesInPage( pg, false );
#ifdef DEBUG_PAGES
        kdDebug(32002) << "removePage: moving " << frames.count() << " frames up, from page " << pg << endl;
#endif
        TQPtrListIterator<KWFrame> frameIt( frames );
        for ( ; frameIt.current(); ++frameIt )
            frameIt.current()->moveBy( 0, pageManager()->page(0)->height() );
    }

    pageManager()->removePage(pageNum);
#ifdef DEBUG_PAGES
    kdDebug(32002) << "KWDocument::removePage -- -> " << pageCount() << endl;
#endif
    // Emitting this one for each page being removed helps giving the user some feedback
    emit numPagesChanged();
}

void KWDocument::afterRemovePages()
{
    //### IMHO recalcFrames should take care of updateAllFrames (it already does it partially).
    recalcFrames();
    // Do this before recalcVariables (which repaints). The removed frames must be removed from the frame caches.
    // We don't call updateAllFrames() directly, because it still calls
    // updateFramesOnTopOrBelow, which is useless (and slow) here.
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
        fit.current()->updateFrames();

    recalcVariables( VT_PGNUM );
    if ( !m_bGeneratingPreview )
        emit newContentsSize();
    if ( m_viewModeType == "ModePreview" )
        repaintAllViews();
}

bool KWDocument::tryRemovingPages()
{
    int last = lastPage();
    bool removed = false;
    // Last frame is empty -> try removing last page, and more if necessary
    while ( last > startPage() && canRemovePage( last ) )
    {
        removePage( last ); // this modifies pageCount
        if ( last <= lastPage() )
        {
            kdWarning() << "Didn't manage to remove page " << last << " (still having " << pageCount() << " pages ). Aborting" << endl;
            break;
        }
        removed = true;
        last = lastPage();
    }
    // Don't call afterRemovePages or recalcFrames from here, since this method is
    // itself called from KWFrameLayout (#95047)
    return removed;
}


KWFrameSet * KWDocument::frameSetByName( const TQString & name )
{
    // Note: this isn't recursive, so it won't find table cells.
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
        if ( fit.current()->name() == name )
            return fit.current();
    return 0L;
}

//#define DEBUG_FRAMESELECT

TQString KWDocument::generateFramesetName( const TQString & templateName )
{
    TQString name;
    int num = 1;
    bool exists;
    do {
        name = templateName.arg( num );
        exists = frameSetByName( name );
        ++num;
    } while ( exists );
    return name;
}

void KWDocument::fixZOrders() {
    //KWFrame *frameFixed = 0;
    for (int pgnum = startPage() ; pgnum <= lastPage() ; pgnum++) {
        TQPtrList<KWFrame> frames = framesInPage(pgnum);
        // scan this page to see if we need to fixup:
        // fix up if two frames have the same zOrder,
        // or if a zOrder is negative (not allowed by OASIS)
        bool need_fixup = false;
        KWFrame *f = frames.last();
        if ( !f )
            continue;
        int lastZOrder = f->zOrder();
        f = frames.prev();
        for ( ; f ; f=frames.prev() ) {
            if ( !f->frameSet()->isFloating() &&
                 ( f->zOrder() == lastZOrder || f->zOrder() < 0 ) ) {
                need_fixup = true;
                break;
            }
            lastZOrder = f->zOrder();
        }
        if ( need_fixup ) {
            int current_zorder=0;
            kdDebug() << "fixing page " << pgnum << " z-orders " << endl;
            for (KWFrame *fr = frames.first();fr;fr=frames.next()) {
                // only consider non-inline framesets.
                if (fr->frameSet()->isFloating())
                    continue;
                current_zorder++;
                fr->setZOrder(current_zorder);
                //frameFixed = f;
            }
        }

        if ( m_processingType == KWDocument::WP )
        {
            // In all cases, ensure the main frames are below the rest.
            // (This could not be the case after e.g. an import filter does it wrong)
            lowerMainFrames( pgnum );
        }
    }
    //if ( frameFixed )
    //    frameFixed->frameStack()->recalcAllFrames();
    KWFrameList::recalcAllFrames(this);
}

void KWDocument::lowerMainFrames( int pageNum )
{
    TQPtrList<KWFrame> framesInPage = this->framesInPage(pageNum);
    int lowestZOrder=10000;
    for ( TQPtrListIterator<KWFrame> frameIt( framesInPage ); frameIt.current(); ++frameIt )
        lowestZOrder=TQMIN(lowestZOrder, frameIt.current()->zOrder());
    lowerMainFrames( pageNum, lowestZOrder );
}

// separated from the above one for KWView (which knows lowestZOrder already)
void KWDocument::lowerMainFrames( int pageNum, int lowestZOrder )
{
    // Get the main frameset and see if we have to lower its frame(s).
    TQPtrList<KWFrame> framesInPage = this->framesInPage(pageNum);
    for ( TQPtrListIterator<KWFrame> frameIt( framesInPage ); frameIt.current(); ++frameIt ) {
        if(frameIt.current()->frameSet()->isMainFrameset()) {
            if(lowestZOrder <= frameIt.current()->zOrder())
                frameIt.current()->setZOrder(lowestZOrder-1);
            // keep going, in case of multiple columns
        }
    }
}

TQPtrList<KWFrame> KWDocument::framesInPage( int pageNum, bool sorted ) const {

    ZOrderedFrameList frames;
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
    {
        KWFrameSet *frameSet = fit.current();
        if ( !frameSet->isVisible() )
            continue;
        // Append all frames from frameSet in page pageNum
        TQPtrListIterator<KWFrame> it( frameSet->framesInPage( pageNum ) );
        for ( ; it.current() ; ++it )
            frames.append( it.current() );
    }
    if (sorted) frames.sort();
    return frames;
}

void KWDocument::updateAllFrames( int flags )
{
#ifdef DEBUG_SPEED
    TQTime dt;
    dt.start();
#endif
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit )
        fit.current()->updateFrames( flags );

#ifdef DEBUG_SPEED
    kdDebug(32001) << "updateAllFrames(" << flags << ") took " << (float)(dt.elapsed()) / 1000 << " seconds" << endl;
#endif

    // TODO: check all calls to updateAllFrames, and fix them.
    // E.g., if one frame moved, updateAllFrames isn't necessary,
    // only fs->updateFrames() and doc->updateFramesOnTopOrBelow() are necessary.

    // Update frames ontop and below _afterwards_,
    // it needs the 'frames in page' array (in other framesets)
    KWFrameList::recalcAllFrames(this);
}

// Tell this method when a frame is moved / resized / created / deleted
// and everything will be update / repainted accordingly
void KWDocument::frameChanged( KWFrame * frame )
{
    if(! m_framesChangedHandler) {
        m_framesChangedHandler = new FramesChangedHandler(this);
        TQTimer::singleShot( 0, this, TQT_SLOT( updateFramesChanged() ) );
    }
    m_framesChangedHandler->addFrame(frame);
}

void KWDocument::framesChanged( const TQPtrList<KWFrame> & frames, KWView * view )
{
    Q_UNUSED( view ); // DF: seems my idea of excluding one view got thrown away
    TQPtrListIterator<KWFrame> it( frames );
    for ( ; it.current() ; ++it )
        frameChanged(it.current());
}

void KWDocument::updateFramesChanged() { // slot called from frameChanged()
    if(!m_framesChangedHandler) return;
    m_framesChangedHandler->execute();
    delete m_framesChangedHandler;
    m_framesChangedHandler = 0;
}

void KWDocument::framesChanged( const TQValueList<KWFrame*> &frames) {
    TQValueListConstIterator<KWFrame*> framesIterator = frames.begin();
    for(;framesIterator != frames.end(); ++framesIterator)
        frameChanged(*framesIterator);
}

void KWDocument::setHeaderVisible( bool h )
{
    m_headerVisible = h;
    recalcFrames();
    updateAllFrames();
    layout();
    setModified(true);
    repaintAllViews( true );
}

void KWDocument::setFooterVisible( bool f )
{
    m_footerVisible = f;
    recalcFrames();
    updateAllFrames();
    layout();
    setModified(true);
    repaintAllViews( true );
}

bool KWDocument::hasEndNotes() const
{
    return m_bHasEndNotes;
}

void KWDocument::updateHeaderButton()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
    {
        (*it)->updateHeaderFooterButton();
        (*it)->updateHeader();
    }
}

void KWDocument::updateFooterButton()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
    {
        (*it)->updateHeaderFooterButton();
        (*it)->updateFooter();
    }
}

void KWDocument::addTextImageRequest( KWTextImage *img )
{
    m_textImageRequests.append( img );
}

void KWDocument::addPictureRequest( KWPictureFrameSet *fs )
{
    m_pictureRequests.append( fs );
}

void KWDocument::addAnchorRequest( const TQString &framesetName, const KWAnchorPosition &anchorPos )
{
    m_anchorRequests.insert( framesetName, anchorPos );
}

void KWDocument::addFootNoteRequest( const TQString &framesetName, KWFootNoteVariable* var )
{
    if ( var->noteType() == EndNote )
        m_bHasEndNotes = true;
    m_footnoteVarRequests.insert( framesetName, var );
}

void KWDocument::refreshMenuCustomVariable()
{
   emit sig_refreshMenuCustomVariable();
}

void KWDocument::recalcVariables( int type )
{
    const TQValueList<KoVariable *> modifiedVariables = m_varColl->recalcVariables(type);
    if ( m_bGeneratingPreview )
        return;

    TQMap<KoTextDocument *, bool> modifiedTextDocuments; // TQt4: TQSet
    for ( TQValueList<KoVariable *>::const_iterator it = modifiedVariables.begin(), end = modifiedVariables.end() ; it != end ; ++it ) {
        KoTextDocument* textdoc = (*it)->textDocument();
        if ( modifiedTextDocuments.find( textdoc ) != modifiedTextDocuments.end() ) // TQt4: !contains
        {
            modifiedTextDocuments.insert( textdoc, true );
            KWTextFrameSet * textfs = static_cast<KWTextDocument *>(textdoc)->textFrameSet();
            slotRepaintChanged( textfs );
        }
    }
}

int KWDocument::mailMergeRecord() const
{
    return slRecordNum;
}

void KWDocument::setMailMergeRecord( int r )
{
    slRecordNum = r;
}

void KWDocument::getPageLayout( KoPageLayout& layout, KoColumns& cl, KoKWHeaderFooter& hf )
{
    layout = m_pageLayout;
    cl = m_pageColumns;
    hf = m_pageHeaderFooter;
}

void KWDocument::addFrameSet( KWFrameSet *f, bool finalize /*= true*/ )
{
    if(m_lstFrameSet.contains(f) > 0) {
        kdWarning(32001) << "Frameset " << f << " " << f->name() << " already in list!" << endl;
        return;
    }
    m_lstFrameSet.append(f);

    KWFrameList::createFrameList(f, this);

    if ( finalize )
        f->finalize();
    setModified( true );
    emit sigFrameSetAdded(f);
}

void KWDocument::removeFrameSet( KWFrameSet *f )
{
    emit sig_terminateEditing( f );
    m_lstFrameSet.take( m_lstFrameSet.find(f) );
    setModified( true );
    emit sigFrameSetRemoved(f);
}

void KWDocument::addCommand( KCommand * cmd )
{
    Q_ASSERT( cmd );
    //kdDebug(32001) << "KWDocument::addCommand " << cmd->name() << endl;
    m_commandHistory->addCommand( cmd, false );
    setModified( true );
}

void KWDocument::slotDocumentRestored()
{
    setModified( false );
}

void KWDocument::slotCommandExecuted()
{
    setModified( true );
}

#ifndef NDEBUG
void KWDocument::printStyleDebug()
{
    kdDebug() << "----------------------------------------"<<endl;
    m_styleColl->printDebug();
    kdDebug() << m_frameStyleColl->count() << " frame styles" << endl;
    kdDebug() << m_tableStyleColl->count() << " table-cell styles" << endl;
}

void KWDocument::printDebug()
{
    kdDebug() << "----------------------------------------"<<endl;
    kdDebug() << "                 Debug info"<<endl;
    kdDebug() << "Document:" << this <<endl;
    kdDebug() << "Type of document: (0=WP, 1=DTP) " << processingType() <<endl;
    kdDebug() << "Header visible: " << isHeaderVisible() << endl;
    kdDebug() << "Footer visible: " << isFooterVisible() << endl;
    kdDebug() << "Units: " << unit() <<endl;
    kdDebug() << "# Framesets: " << frameSetCount() <<endl;
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( unsigned int iFrameset = 0; fit.current() ; ++fit, iFrameset++ )
    {
        KWFrameSet * frameset = fit.current();
        kdDebug() << "Frameset " << iFrameset << ": '" <<
            frameset->name() << "' (" << frameset << ")" << (frameset->isDeleted()?" Deleted":"")<<endl;
        if ( frameset->isVisible())
            frameset->printDebug();
        else
            kdDebug() << "  [hidden] #" << frameset->frameCount() << " frames" << endl;
    }

    for ( uint pgNum = 0 ; pgNum < m_sectionTitles.size() ; ++pgNum ) {
        kdDebug() << "Page " << pgNum << "  Section: '" << m_sectionTitles[ pgNum ] << "'"<< endl;
    }
    /*
    kdDebug() << "# Images: " << getImageCollection()->iterator().count() <<endl;
    TQDictIterator<KWImage> it( getImageCollection()->iterator() );
    while ( it.current() ) {
        kdDebug() << " + " << it.current()->getFilename() << ": "<<it.current()->refCount() <<endl;
        ++it;
    }
    */

    kdDebug() << "PageManager holds "<< pageCount() << " pages in the range: " << startPage() <<
        "-" << lastPage() << endl;
    for (int pgnum = startPage() ; pgnum <= lastPage() ; pgnum++) {
        KWPage *page = pageManager()->page(pgnum);
        kdDebug() << "Page " << pgnum << " width=" << page->width() << " height=" << page->height() << endl;
    }
    kdDebug() << "  The height of the doc (in pt) is: " << pageManager()->
        bottomOfPage(lastPage()) << endl;
}
#endif

void KWDocument::layout()
{
    TQPtrListIterator<KWFrameSet> it = framesetsIterator();
    for (; it.current(); ++it )
        if ( it.current()->isVisible() )
            it.current()->layout();
}

void KWDocument::invalidate(const KWFrameSet *skipThisFrameSet)
{
    TQPtrListIterator<KWFrameSet> it = framesetsIterator();
    for (; it.current(); ++it )
        if(it.current()!=skipThisFrameSet)
            it.current()->invalidate();
}

KFormula::Document* KWDocument::formulaDocument( bool init )
{
    KFormula::Document* formulaDocument = m_formulaDocumentWrapper->document();
    if (!formulaDocument) {
        kdDebug() << k_funcinfo << endl;
        formulaDocument = new KFormula::Document;
        m_formulaDocumentWrapper->document( formulaDocument, init );
        if ( formulaDocument != 0 ) {
            // re-calculate dpiX and dpiY
            formulaDocument->setZoomAndResolution( m_zoom,
                                                   tqRound(INCH_TO_POINT( m_resolutionX )),
                                                   tqRound(INCH_TO_POINT( m_resolutionY )) );
            formulaDocument->newZoomAndResolution(false,false);
        }
    }
    return formulaDocument;
}


void KWDocument::slotRepaintChanged( KWFrameSet * frameset )
{
    // This has to be a loop instead of a signal, so that we can
    // send "true" for the last view (see KWFrameSet::drawContents)
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it ) {
        (*it)->getGUI()->canvasWidget()->repaintChanged( frameset, it == m_lstViews.fromLast() );
    }
}

void KWDocument::deleteTable( KWTableFrameSet *table )
{
    if ( !table )
        return;
    if ( table->isFloating() )
    {
        emit sig_terminateEditing( table ); // to unselect its cells, especially
        KWAnchor * anchor = table->findAnchor( 0 );
        addCommand( table->anchorFrameset()->deleteAnchoredFrame( anchor ) );
    }
    else
    {
        KWDeleteTableCommand *cmd = new KWDeleteTableCommand( i18n("Delete Table"), table );
        addCommand( cmd );
        cmd->execute();
    }
}

void KWDocument::deleteFrame( KWFrame * frame )
{
    KWFrameSet * fs = frame->frameSet();
    kdDebug(32002) << "KWDocument::deleteFrame frame=" << frame << " fs=" << fs << endl;
    TQString cmdName;
    TypeStructDocItem docItem = (TypeStructDocItem) 0;
    switch (fs->type() ) {
    case FT_TEXT:
        cmdName=i18n("Delete Text Frame");
        docItem=TextFrames;
        break;
    case FT_FORMULA:
        cmdName=i18n("Delete Formula Frame");
        docItem=FormulaFrames;
        break;
    case FT_CLIPART:
        kdError(32001) << "FT_CLIPART used! (in KWDocument::deleteFrame)" << endl;
        break;
    case FT_PICTURE:
        cmdName=i18n("Delete Picture Frame");
        docItem=Pictures;
        break;
    case FT_PART:
        cmdName=i18n("Delete Object Frame");
        docItem=Embedded;
        break;
    case FT_TABLE:
    case FT_BASE:
        Q_ASSERT( 0 );
        break;
    }
    if ( fs->isFloating() )
    {
        KWAnchor * anchor = fs->findAnchor( 0 );
        addCommand( fs->anchorFrameset()->deleteAnchoredFrame( anchor ) );
    }
    else
    {
        KWDeleteFrameCommand *cmd = new KWDeleteFrameCommand( cmdName, frame );
        addCommand( cmd );
        cmd->execute();
    }
    emit docStructureChanged(docItem);
}

void KWDocument::reorganizeGUI()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->getGUI()->reorganize();
}

void KWDocument::slotDocumentInfoModifed()
{
    if (!variableCollection()->variableSetting()->displayFieldCode())
        recalcVariables( VT_FIELD );
}

void KWDocument::refreshDocStructure(int type)
{
     emit docStructureChanged(type);
}

int KWDocument::typeItemDocStructure(FrameSetType type)
{
    int typeItem;
    switch(type)
    {
        case FT_TEXT:
            typeItem=(int)TextFrames;
            break;
        case FT_PICTURE:
            typeItem=(int)Pictures;
            break;
        case FT_PART:
            typeItem=(int)Embedded;
            break;
        case FT_FORMULA:
            typeItem=(int)FormulaFrames;
            break;
        case FT_TABLE:
            typeItem=(int)Tables;
            break;
        default:
            typeItem=(int)TextFrames;
    }
    return typeItem;
}

void KWDocument::refreshDocStructure(FrameSetType type)
{
    emit docStructureChanged(typeItemDocStructure(type));
}

TQBrush KWDocument::resolveBgBrush( const TQBrush & brush, TQPainter * painter )
{
    if ( brush.color().isValid() )
        return brush;
    TQBrush ret( brush );
    ret.setColor( defaultBgColor( painter ) );
    return ret;
}

TQColor KWDocument::resolveBgColor( const TQColor & col, TQPainter * painter )
{
    if (col.isValid())
        return col;

    return defaultBgColor( painter );
}

TQColor KWDocument::defaultBgColor( TQPainter * painter )
{
    if ( painter && painter->device()->devType() == TQInternal::Printer )
        return TQt::white;
    return TQApplication::palette().color( TQPalette::Active, TQColorGroup::Base );
}


void KWDocument::setTocPresent(bool hasToc)
{
    m_hasTOC=hasToc;
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->updateTocActionText(hasToc);
}

void KWDocument::refreshMenuExpression()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->refreshMenuExpression();
}

void KWDocument::updateZoomRuler()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it ) {
        (*it)->getGUI()->getHorzRuler()->setZoom( zoomedResolutionX() );
        (*it)->getGUI()->getVertRuler()->setZoom( zoomedResolutionY() );
        (*it)->slotUpdateRuler();
    }
}

void KWDocument::updateRulerFrameStartEnd()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->slotUpdateRuler();
}

int KWDocument::undoRedoLimit() const
{
    return m_commandHistory->undoLimit();
}

void KWDocument::setUndoRedoLimit(int val)
{
    m_commandHistory->setUndoLimit(val);
    m_commandHistory->setRedoLimit(val);
}

void KWDocument::setGridX(double gridx) {
    m_gridX = gridx;
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->getGUI()->getHorzRuler()->setGridSize(gridx);
}

TQValueList<KoTextObject *> KWDocument::visibleTextObjects(KWViewMode *viewmode) const
{
    TQValueList<KoTextObject *> lst;
    TQPtrList<KWTextFrameSet> textFramesets = allTextFramesets( true );

    KWTextFrameSet *frm;
    for ( frm=textFramesets.first(); frm != 0; frm=textFramesets.next() ) {
        if ( frm && frm->isVisible(viewmode) && !frm->textObject()->protectContent() )
        {
            lst.append( frm->textObject() );
        }
    }

    return lst;
}

void KWDocument::refreshGUIButton()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->initGUIButton();
}

void KWDocument::enableBackgroundSpellCheck( bool b )
{
    m_bgSpellCheck->setEnabled(b);
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->updateBgSpellCheckingState();
}

bool KWDocument::backgroundSpellCheckEnabled() const
{
    return m_bgSpellCheck->enabled();
}

void KWDocument::reactivateBgSpellChecking()
{
    TQPtrList<KWTextFrameSet> textFramesets = allTextFramesets( true );

    KWTextFrameSet *frm;
    for ( frm=textFramesets.first(); frm != 0; frm=textFramesets.next() ){
        frm->textObject()->setNeedSpellCheck(true);
    }
    repaintAllViews();
    startBackgroundSpellCheck();
}

void KWDocument::slotChapterParagraphFormatted( KoTextParag* /*parag*/ )
{
    // Attempt at invalidating from the parag's page only
    // But that's not good enough - if a header gets moved down,
    // we also need to invalidate the previous page, from where the paragraph disappeared.
    /*
      KoPoint p;
    KWFrame* frame = internalToDocument( parag->rect().topLeft(), p );
    Q_ASSERT( frame );
    if ( frame )
        // Remove any information from this page and further pages.
        m_sectionTitles.resize( frame->pageNumber() );
    */

    m_sectionTitles.resize( 0 ); // clear up the entire cache

    // Don't store info from parag into m_sectionTitles here.
    // It breaks when having two headings in the same page
    // (or if it keeps existing info then it can't update properly)
}

TQString KWDocument::checkSectionTitleInParag( KoTextParag* parag, KWTextFrameSet* frameset, int pageNum ) const
{
    if ( parag->counter() && parag->counter()->numbering() == KoParagCounter::NUM_CHAPTER
         && parag->counter()->depth() == 0 )
    {
        TQString txt = parag->string()->toString();
        txt = txt.left( txt.length() - 1 ); // remove trailing space
#ifndef NDEBUG // not needed, just checking
        KoPoint p;
        KWFrame* frame = frameset->internalToDocument( parag->rect().topLeft(), p );
        Q_ASSERT( frame );
        if ( frame ) {
            int pgNum = frame->pageNumber();
            if( pgNum != pageNum )
                kdWarning() << "sectionTitle: was looking for pageNum " << pageNum << ", got frame " << frame << " page " << pgNum << endl;
        }
        kdDebug(32001) << "KWDocument::sectionTitle for " << pageNum << ":" << txt << endl;
#endif
        // Ensure array is big enough
        if ( pageNum > (int)m_sectionTitles.size()-1 )
            const_cast<KWDocument*>(this)->m_sectionTitles.resize( pageNum + 1 );
        const_cast<KWDocument*>(this)->m_sectionTitles[ pageNum ] = txt;
        return txt;
    }
    return TQString();
}

TQString KWDocument::sectionTitle( int pageNum ) const
{
    //kdDebug(32001) << "KWDocument::sectionTitle(pageNum=" << pageNum << ") m_sectionTitles.size()=" << m_sectionTitles.size() << endl;
    // First look in the cache. If info is present, it's uptodate (see slotChapterParagraphFormatted)
    if ( (int)m_sectionTitles.size() > pageNum )
    {
        // Look whether this page has a section title, and if not, go back pages, one by one
        for ( int i = pageNum; i >= 0 ; --i )
        {
            const TQString& s = m_sectionTitles[i];
            if ( !s.isEmpty() )
            {
                // Update cache, to make this faster next time
                if ( pageNum > (int)m_sectionTitles.size()-1 )
                    const_cast<KWDocument*>(this)->m_sectionTitles.resize( pageNum + 1 );
                const_cast<KWDocument*>(this)->m_sectionTitles[ pageNum ] = s;
                return s;
            }
        }
    }

    // If not in the cache, determine from the paragraphs in the page.

    if ( m_lstFrameSet.isEmpty() )
        return TQString();
    // We use the "main" frameset to determine section titles.
    KWTextFrameSet *frameset = dynamic_cast<KWTextFrameSet *>( m_lstFrameSet.getFirst() );
    if ( !frameset )
        return TQString();

    int topLUpix, bottomLUpix;
    if ( !frameset->minMaxInternalOnPage( pageNum, topLUpix, bottomLUpix ) )
        return TQString();

    KoTextParag* parag = frameset->textDocument()->firstParag();
    //kdDebug(32001) << "KWDocument::sectionTitle " << pageNum
    //          << " topLUpix=" << topLUpix << " bottomLUpix=" << bottomLUpix << endl;

    KoTextParag* lastParagOfPageAbove = parag;
    for ( ; parag ; parag = parag->next() )
    {
        if ( parag->rect().bottom() < topLUpix ) // too early
        {
            lastParagOfPageAbove = parag;
            continue;
        }
        if ( parag->rect().top() > bottomLUpix ) // done
            break;
        TQString txt = checkSectionTitleInParag( parag, frameset, pageNum );
        if ( !txt.isEmpty() )
            return txt;
    }

    // No heading found in page.
    // Go back up until the first section parag
    parag = lastParagOfPageAbove;
    for (  ; parag ; parag = parag->prev() )
    {
        TQString txt = checkSectionTitleInParag( parag, frameset, pageNum );
        if ( !txt.isEmpty() )
            return txt;
    }

    // First page, no heading found
    return TQString();
}


void KWDocument::setSpellCheckIgnoreList( const TQStringList& lst )
{
    m_spellCheckIgnoreList = lst;
    m_bgSpellCheck->settings()->setCurrentIgnoreList( m_spellCheckIgnoreList + m_spellCheckPersonalDict );
    setModified( true );
}

void KWDocument::addSpellCheckIgnoreWord( const TQString & word )
{
    // ### missing: undo/redo support
    if( m_spellCheckIgnoreList.findIndex( word ) == -1 )
        m_spellCheckIgnoreList.append( word );
    setSpellCheckIgnoreList( m_spellCheckIgnoreList );
    if ( backgroundSpellCheckEnabled() )
        // Re-check everything to make this word normal again
        reactivateBgSpellChecking();
}

int KWDocument::maxZOrder( int pageNum) const
{
    bool first = true;
    int maxZOrder = 0; //this value is only used if there's no frame on the page
    TQPtrList<KWFrame> frames = framesInPage( pageNum );
    TQPtrListIterator<KWFrame> frameIt( frames );
    for ( ; frameIt.current(); ++frameIt ) {
        if ( first || frameIt.current()->zOrder() > maxZOrder ) {
            maxZOrder = frameIt.current()->zOrder();
            first = false;
        }
    }
    return maxZOrder;
}

TQPtrList<KWTextFrameSet> KWDocument::allTextFramesets(bool onlyReadWrite) const
{
    TQPtrList<KWTextFrameSet> textFramesets;
    TQPtrListIterator<KWFrameSet> fit = framesetsIterator();
    for ( ; fit.current() ; ++fit ) {
        if(fit.current()->isDeleted()) continue;
        fit.current()->addTextFrameSets(textFramesets, onlyReadWrite);
    }
    return textFramesets;
}

TQValueList<KoTextDocument *> KWDocument::allTextDocuments() const
{
    TQValueList<KoTextDocument *> lst;
    const TQPtrList<KWTextFrameSet> textFramesets = allTextFramesets(false);
    TQPtrListIterator<KWTextFrameSet> fit( textFramesets );
    for ( ; fit.current() ; ++fit ) {
        lst.append( fit.current()->textObject()->textDocument() );
    }
    return lst;
}

int KWDocument::numberOfTextFrameSet( KWFrameSet* fs, bool onlyReadWrite )
{
    TQPtrList<KWTextFrameSet> textFramesets = allTextFramesets( onlyReadWrite );
    return textFramesets.findRef( static_cast<KWTextFrameSet*>(fs) );
}

KWFrameSet * KWDocument::textFrameSetFromIndex( unsigned int num, bool onlyReadWrite )
{
    return allTextFramesets( onlyReadWrite ).at( num );
}

void KWDocument::updateTextFrameSetEdit()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->slotFrameSetEditChanged();

}

void KWDocument::displayFootNoteFieldCode()
{
    TQPtrListIterator<KoVariable> it( m_varColl->getVariables() );
    for ( ; it.current() ; ++it )
    {
        if ( it.current()->type() == VT_FOOTNOTE )
        {
            static_cast<KWFootNoteVariable *>(it.current())->resize();
            static_cast<KWFootNoteVariable *>(it.current())->frameSet()->setCounterText( static_cast<KWFootNoteVariable *>(it.current())->text() );

            KoTextParag * parag = it.current()->paragraph();
            if ( parag )
            {
                parag->invalidate( 0 );
                parag->setChanged( true );
            }
        }
    }
}

void KWDocument::changeFootNoteConfig()
{
    TQMap<KoTextDocument *, bool> modifiedTextDocuments; // TQt4: TQSet
    TQPtrListIterator<KoVariable> it( m_varColl->getVariables() );
    for ( ; it.current() ; ++it )
    {
        if ( it.current()->type() == VT_FOOTNOTE )
        {
            KWFootNoteVariable* footNoteVar = static_cast<KWFootNoteVariable *>(it.current());
            footNoteVar->formatedNote();
            if(footNoteVar->frameSet()->isDeleted())
                    continue;
            footNoteVar->resize();
            footNoteVar->frameSet()->setCounterText( footNoteVar->text() );

            KoTextParag * parag = footNoteVar->paragraph();
            if ( parag )
            {
                parag->invalidate( 0 );
                parag->setChanged( true );
            }
            KoTextDocument* textdoc = parag->textDocument();
            if ( modifiedTextDocuments.find( textdoc ) != modifiedTextDocuments.end() ) // TQt4: !contains
                modifiedTextDocuments.insert( textdoc, true );
        }
    }
    for( TQMap<KoTextDocument *,bool>::const_iterator it = modifiedTextDocuments.begin();
         it != modifiedTextDocuments.end(); ++it ) {
        KoTextDocument* textdoc = it.key();
        KWTextFrameSet * textfs = static_cast<KWTextDocument *>(textdoc)->textFrameSet();
        slotRepaintChanged( textfs );
    }
}


void KWDocument::setTabStopValue ( double tabStop )
{
    m_tabStop = tabStop;
    TQPtrList<KWTextFrameSet> textFramesets = allTextFramesets( true );

    KWTextFrameSet *frm;
    for ( frm=textFramesets.first(); frm != 0; frm=textFramesets.next() ){
        frm->textDocument()->setTabStops( ptToLayoutUnitPixX( tabStop ));
        frm->layout();
    }
    repaintAllViews();
}

void KWDocument::setGlobalHyphenation( bool hyphen )
{
    m_bGlobalHyphenation = hyphen;
    // This is only used as a default setting for the default format in new documents;
    // In existing documents the hyphenation comes from the existing formats.
}

void KWDocument::setViewFrameBorders( bool b )
{
    m_viewFrameBorders = b;
    m_layoutViewMode->setDrawFrameBorders( b );
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->getGUI()->canvasWidget()->viewMode()->setDrawFrameBorders( b );
}

void KWDocument::switchViewMode( const TQString& newViewModeType )
{
    // Don't compare m_viewModeType and newViewMode here, it would break
    // changing the number of pages per row for the preview mode, in kwconfig.
    m_viewModeType = newViewModeType;
    delete m_layoutViewMode;
    m_layoutViewMode = KWViewMode::create( m_viewModeType, this, 0 /*no canvas */ );

    //necessary to switchmode view in all canvas in first.
    //otherwise with more than one view kword crashes !
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->getGUI()->canvasWidget()->switchViewMode( m_viewModeType );

    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->switchModeView();
    emit newContentsSize();

    // Since the text layout depends on the view mode, we need to redo it
    // But after telling the canvas about the new viewmode, otherwise stuff like
    // slotNewContentsSize will crash.
    updateAllFrames();
    layout();

    repaintAllViews( true );
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->getGUI()->canvasWidget()->ensureCursorVisible();
}

void KWDocument::changeBgSpellCheckingState( bool b )
{
    enableBackgroundSpellCheck( b );
    reactivateBgSpellChecking();
    KConfig *config = KWFactory::instance()->config();
    config->setGroup("KSpell kword" );
    config->writeEntry( "SpellCheck", (int)b );
}

TQString KWDocument::initialFrameSet() const
{
    return m_initialEditing ? m_initialEditing->m_initialFrameSet : TQString();
}

int KWDocument::initialCursorParag() const
{
    return m_initialEditing ? m_initialEditing->m_initialCursorParag : 0;
}

int KWDocument::initialCursorIndex() const
{
    return m_initialEditing ? m_initialEditing->m_initialCursorIndex : 0;
}

void KWDocument::deleteInitialEditingInfo()
{
    delete m_initialEditing;
    m_initialEditing = 0L;
}

bool KWDocument::cursorInProtectedArea()const
{
    return m_cursorInProtectectedArea;
}

void KWDocument::setCursorInProtectedArea( bool b )
{
    m_cursorInProtectectedArea=b;
    testAndCloseAllFrameSetProtectedContent();
}


void KWDocument::testAndCloseAllFrameSetProtectedContent()
{
    if ( !m_cursorInProtectectedArea )
    {
        for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
            (*it)->testAndCloseAllFrameSetProtectedContent();
    }
}

void KWDocument::updateRulerInProtectContentMode()
{
    for( TQValueList<KWView *>::const_iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->updateRulerInProtectContentMode();
}


void KWDocument::insertBookmark( const TQString &name, KoTextParag *startparag, KoTextParag *endparag, int start, int end )
{
    m_bookmarkList->append( KoTextBookmark( name, startparag, endparag, start, end ) );
}

void KWDocument::deleteBookmark( const TQString &name )
{
    if ( m_bookmarkList->removeByName( name ) )
        setModified(true);
}

void KWDocument::renameBookmark( const TQString &oldName, const TQString &newName )
{
    if ( oldName == newName )
        return;

    KoTextBookmarkList::iterator it = m_bookmarkList->findByName( oldName );
    if ( it != m_bookmarkList->end() )
    {
        (*it).setBookmarkName( newName );
        setModified(true);
    }
}

const KoTextBookmark * KWDocument::bookmarkByName( const TQString & name ) const
{
    KoTextBookmarkList::const_iterator it = m_bookmarkList->findByName( name );
    if ( it != m_bookmarkList->end() )
        return &(*it);
    return 0;
}

TQStringList KWDocument::listOfBookmarkName( KWViewMode * viewMode ) const
{
    TQStringList list;
    KoTextBookmarkList::const_iterator it = m_bookmarkList->begin();
    const KoTextBookmarkList::const_iterator end = m_bookmarkList->end();
    for ( ; it != end ; ++it )
    {
        const KoTextBookmark& book = *it;
        KWFrameSet* fs = static_cast<KWTextDocument *>(book.textDocument())->textFrameSet();
        if ( fs->isVisible( viewMode ) && !fs->isDeleted() )
            list.append( book.bookmarkName() );
    }
    return list;
}

void KWDocument::paragraphModified(KoTextParag* /*parag*/, int /*KoTextParag::ParagModifyType*/ /*type*/, int /*start*/, int /*length*/)
{
    //kdDebug()<<" parag :"<<parag<<" start :"<<start<<" length :"<<length<<endl;
    emit docStructureChanged( Tables | TextFrames );
}


void KWDocument::paragraphDeleted( KoTextParag *parag, KWFrameSet *frm )
{
    KWTextFrameSet* textfs = dynamic_cast<KWTextFrameSet *>( frm );
    if ( textfs )
    {
        // For speed KoTextBookmarkList should probably be a per-paragraph map.
        // The problem is that a bookmark is associated with TWO paragraphs...

        KoTextBookmarkList::iterator it = m_bookmarkList->begin();
        const KoTextBookmarkList::iterator end = m_bookmarkList->end();
        for ( ; it != end ; ++it )
        {
            KoTextBookmark& book = *it;

            // Adjust bookmark to point to a valid paragraph, below or above the deleted one.
            // The old implementation turned the bookmark into a useless one. OOo simply deletes the bookmark...
            if ( book.startParag() == parag )
                book.setStartParag( parag->next() ? parag->next() : parag->prev() );
            if ( book.endParag() == parag )
                book.setEndParag( parag->next() ? parag->next() : parag->prev() );
        }
    }
}

void KWDocument::initBookmarkList()
{
    Q_ASSERT( m_loadingInfo );
    if ( !m_loadingInfo )
        return;
    KWLoadingInfo::BookMarkList::Iterator it = m_loadingInfo->bookMarkList.begin();
    KWLoadingInfo::BookMarkList::Iterator end = m_loadingInfo->bookMarkList.end();
    for( ; it != end; ++it )
    {
        KWFrameSet * fs = 0L;
        TQString fsName = (*it).frameSetName;
        if ( !fsName.isEmpty() )
            fs = frameSetByName( fsName );
        if ( fs )
        {
            KWTextFrameSet *frm = dynamic_cast<KWTextFrameSet *>(fs);
            if ( frm )
            {
                KoTextDocument* textdoc = frm->textDocument();
                KoTextParag* startparag = textdoc->paragAt( (*it).paragStartIndex );
                KoTextParag* endparag = textdoc->paragAt( (*it).paragEndIndex );
                if ( startparag && endparag )
                {
                    m_bookmarkList->append( KoTextBookmark( (*it).bookname,
                                                            startparag, endparag,
                                                            (*it).cursorStartIndex, (*it).cursorEndIndex ) );
                }
            }
        }
    }
}

TQPixmap* KWDocument::doubleBufferPixmap( const TQSize& s )
{
    if ( !m_bufPixmap ) {
        int w = TQABS( s.width() );
        int h = TQABS( s.height() );
        m_bufPixmap = new TQPixmap( w, h );
    } else {
        if ( m_bufPixmap->width() < s.width() ||
                m_bufPixmap->height() < s.height() ) {
            m_bufPixmap->resize( TQMAX( s.width(), m_bufPixmap->width() ),
                    TQMAX( s.height(), m_bufPixmap->height() ) );
        }
    }

    return m_bufPixmap;
}

void KWDocument::maybeDeleteDoubleBufferPixmap()
{
    if ( m_bufPixmap && m_bufPixmap->height() * m_bufPixmap->width() > 400*400 )
    {
        delete m_bufPixmap;
        m_bufPixmap = 0L;
    }
}

void KWDocument::setPersonalExpressionPath( const TQStringList & lst)
{
    m_personalExpressionPath = lst;
    refreshMenuExpression();
}

void KWDocument::updateDirectCursorButton()
{
    for( TQValueList<KWView *>::Iterator it = m_lstViews.begin(); it != m_lstViews.end(); ++it )
        (*it)->updateDirectCursorButton();
}

void KWDocument::setInsertDirectCursor(bool b)
{
    m_bInsertDirectCursor=b;
    KConfig *config = KWFactory::instance()->config();
    config->setGroup( "Interface" );
    config->writeEntry( "InsertDirectCursor", b );
    updateDirectCursorButton();
}

void KWDocument::saveDialogShown()
{
    if ( !textFrameSet(0) )
        return;
    // Grab first 50 chars from the main frameset's document
    // ### This is a somewhat slow method, if the document is huge - better iterate
    // over the first few parags until 50 chars have been collected.
    TQString first_row = textFrameSet(0)->textDocument()->plainText().left(50);
    bool truncate = false;
    TQChar ch;
    for (int i=0; i < (int)first_row.length(); i++)
    {
        ch = first_row.at(i);
        if (!truncate)
            if (ch.isPunct() || ch.isSpace() || ch == '.' )
            {
                first_row.remove(i,1);
                --i;
            }
            else
                truncate = true;
        else if ( truncate && (ch.isPunct() || ch == '.' || ch == '\n' ) )
        {
            first_row.truncate(i);
            break;
        }
    }
    first_row = first_row.stripWhiteSpace();
    kdDebug() << "Suggested filename:" << first_row << endl;
    setURL(first_row);
}

void KWDocument::addWordToDictionary( const TQString& word )
{
    if ( m_bgSpellCheck )
    {
        if( m_spellCheckPersonalDict.findIndex( word ) == -1 )
            m_spellCheckPersonalDict.append( word );
        m_bgSpellCheck->settings()->setCurrentIgnoreList( m_spellCheckIgnoreList + m_spellCheckPersonalDict );
        if ( backgroundSpellCheckEnabled() )
            // Re-check everything to make this word normal again
            reactivateBgSpellChecking();
    }
}

void KWDocument::setEmpty()
{
    KoDocument::setEmpty();
    // Whether loaded from template or from empty doc: this is a new one -> set creation date
    m_varColl->variableSetting()->setCreationDate(TQDateTime::currentDateTime());
    recalcVariables( VT_DATE ); // , VST_CREATION_DATE ...
    // If we then load a document, it will override that date.
}

void KWDocument::updateGridButton()
{
  TQPtrListIterator<KoView> it( views() );
  for (; it.current(); ++it )
    ((KWView*)it.current())->updateGridButton();

}

unsigned int KWDocument::paperHeight(int pageNum) const {
    return static_cast<unsigned int>(zoomItY( pageManager()->pageLayout(pageNum).ptHeight ));
}

unsigned int KWDocument::paperWidth(int pageNum) const {
    return static_cast<unsigned int>(zoomItX( pageManager()->pageLayout(pageNum).ptWidth ));
}

unsigned int KWDocument::pageTop( int pgNum ) const {
    return zoomItY( pageManager()->topOfPage( pgNum ) );
}

int KWDocument::pageCount() const {
    return pageManager()->pageCount();
}

int KWDocument::startPage() const {
    return pageManager()->startPage();
}
int KWDocument::lastPage() const {
    return pageManager()->lastPageNumber();
}

TQWidget* KWDocument::createCustomDocumentWidget(TQWidget *parent) {
    KoColumns columns;
    columns.columns = 1;
    columns.ptColumnSpacing = m_defaultColumnSpacing;
    return new KWStartupWidget(parent, this, columns);
}

KWDocument::FramesChangedHandler::FramesChangedHandler(KWDocument *parent) {
    m_parent = parent;
    m_needLayout = false;
}

void KWDocument::FramesChangedHandler::addFrame(KWFrame *frame) {
    if(frame == 0) return;
    if(m_frameSets.contains(frame->frameSet())) return;
    m_frameSets.append(frame->frameSet());
    if( frame->runAround() != KWFrame::RA_NO )
        m_needLayout = true;
}

void KWDocument::FramesChangedHandler::addFrameSet(KWFrameSet *fs) {
    if(m_frameSets.contains(fs)) return;
    m_frameSets.append(fs);
    m_needLayout = true;
}

void KWDocument::FramesChangedHandler::execute() {
    if(m_frameSets.count() == 0)
        m_parent->updateAllFrames();
    else {
        TQValueListIterator<KWFrameSet*> iter = m_frameSets.begin();
        for(;iter != m_frameSets.end(); ++iter) {
            KWFrameSet *fs = *iter;
            fs->updateFrames();
            if(!m_needLayout)
                fs->layout();
        }

        KWFrameList::recalcAllFrames(m_parent);
    }

    // If frame with text flowing around it -> re-layout all frames
    if ( m_needLayout)
        m_parent->layout();
    //m_parent->repaintAllViewsExcept( 0 );
    m_parent->repaintAllViews();
    m_parent->updateRulerFrameStartEnd();
}

#include "KWDocument.moc"