summaryrefslogtreecommitdiffstats
path: root/kspread/kspread_doc.cpp
blob: 17f02d487f7da5161d50cb03ecd01b0c291bdc48 (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
/* This file is part of the KDE project
   Copyright (C) 2005-2006 Inge Wallin <[email protected]>
             (C) 2004 Ariya Hidayat <[email protected]>
             (C) 2002-2003 Norbert Andres <[email protected]>
             (C) 2000-2002 Laurent Montel <[email protected]>
             (C) 2002 John Dailey <[email protected]>
             (C) 2002 Phillip Mueller <[email protected]>
             (C) 2000 Werner Trobin <[email protected]>
             (C) 1999-2000 Simon Hausmann <[email protected]>
             (C) 1999 David Faure <[email protected]>
             (C) 1998-2000 Torben Weis <[email protected]>

   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 <unistd.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <pwd.h>

#include <tqapplication.h>
#include <tqfileinfo.h>
#include <tqfont.h>
#include <tqpair.h>

#include <kstandarddirs.h>
#include <kdebug.h>
#include <tdeconfig.h>
#include <tdemessagebox.h>
#include <ksconfig.h>
#include <tdetempfile.h>

#include <KoApplication.h>
#include <KoCommandHistory.h>
#include <KoDocumentInfo.h>
#include <KoDom.h>
#include <KoMainWindow.h>
#include <KoOasisSettings.h>
#include <KoOasisStyles.h>
#include <KoStoreDevice.h>
#include <KoTemplateChooseDia.h>
#include <KoVariable.h>
#include <KoXmlNS.h>
#include <KoXmlWriter.h>

#include "kspread_canvas.h"
#include "kspread_locale.h"
#include "kspread_map.h"
#include "kspread_sheet.h"
#include "kspread_sheetprint.h"
#include "kspread_style_manager.h"
#include "kspread_undo.h"
#include "kspread_util.h"
#include "kspread_view.h"

#include "commands.h"
#include "damages.h"
#include "formula.h"
#include "functions.h"
#include "ksploadinginfo.h"
#include "selection.h"
#include "valuecalc.h"
#include "valueconverter.h"
#include "valueformatter.h"
#include "valueparser.h"

#include "KSpreadDocIface.h"

#include "kspread_doc.h"

using namespace std;
using namespace KSpread;

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

class Doc::Private
{
public:

  Map *map;
  TDELocale *locale;
  StyleManager *styleManager;
  ValueParser *parser;
  ValueFormatter *formatter;
  ValueConverter *converter;
  ValueCalc *calc;

  Sheet *activeSheet;
    KSPLoadingInfo *m_loadingInfo;
  static TQValueList<Doc*> s_docs;
  static int s_docId;

  DCOPObject* dcop;

  // URL of the this part. This variable is only set if the load() function
  // had been called with an URL as argument.
  TQString fileURL;

  // for undo/redo
  int undoLocked;
  KoCommandHistory* commandHistory;

  // true if loading is in process, otherwise false.
  // This flag is used to avoid updates etc. during loading.
  bool isLoading;

  TQColor pageBorderColor;

  TQPtrList<Plugin> plugins;

  TQValueList<Reference> refs;
  TDECompletion listCompletion;

  int numOperations;

  TQValueList<Damage*> damages;

  // document properties
  int syntaxVersion;
  bool verticalScrollBar:1;
  bool horizontalScrollBar:1;
  bool columnHeader:1;
  bool rowHeader:1;
  TQColor gridColor;
  double indentValue;
  bool showStatusBar:1;
  bool showTabBar:1;
  bool showFormulaBar:1;
  bool showError:1;
  TDEGlobalSettings::Completion completionMode;
  KSpread::MoveTo moveTo;
  MethodOfCalc calcMethod;
  bool delayCalculation:1;
  KSpellConfig *spellConfig;
  bool dontCheckUpperWord:1;
  bool dontCheckTitleCase:1;
    bool configLoadFromFile:1;
  TQStringList spellListIgnoreAll;
  /// list of all objects
  TQPtrList<EmbeddedObject> m_embeddedObjects;
  KoPictureCollection m_pictureCollection;
  TQValueList<KoPictureKey> usedPictures;
  bool m_savingWholeDocument;
};

/*****************************************************************************
 *
 * Doc
 *
 *****************************************************************************/

TQValueList<Doc*> Doc::Private::s_docs;
int Doc::Private::s_docId = 0;

Doc::Doc( TQWidget *parentWidget, const char *widgetName, TQObject* parent, const char* name, bool singleViewMode )
  : KoDocument( parentWidget, widgetName, parent, name, singleViewMode )
{
  d = new Private;
  d->m_loadingInfo = 0L;

  d->map = new Map( this, "Map" );
  d->locale = new Locale;
  d->styleManager = new StyleManager();

  d->parser = new ValueParser( d->locale );
  d->converter = new ValueConverter ( d->parser );
  d->calc = new ValueCalc( d->converter );
  d->calc->setDoc (this);
  d->formatter = new ValueFormatter( d->converter );

  d->activeSheet = 0;

  d->pageBorderColor = TQt::red;
  d->configLoadFromFile = false;

  TQFont f( KoGlobal::defaultFont() );
  Format::setGlobalRowHeight( f.pointSizeFloat() + 3 );
  Format::setGlobalColWidth( ( f.pointSizeFloat() + 3 ) * 5 );

  d->plugins.setAutoDelete( false );

  d->delayCalculation = false;

  documents().append( this );

  setInstance( Factory::global(), false );
  setTemplateType( "kspread_template" );

  d->dcop = 0;
  d->isLoading = false;
  d->numOperations = 1; // don't start repainting before the GUI is done...

  d->undoLocked = 0;
  d->commandHistory = new KoCommandHistory( actionCollection() );
  connect( d->commandHistory, TQ_SIGNAL( commandExecuted() ), TQ_SLOT( commandExecuted() ) );
  connect( d->commandHistory, TQ_SIGNAL( documentRestored() ), TQ_SLOT( documentRestored() ) );


  // Make us scripsheet if the document has a name
  // Set a name if there is no name specified
  if ( !name )
  {
      TQString tmp( "Document%1" );
      tmp = tmp.arg( d->s_docId++ );
      setName( tmp.local8Bit());//tmp.latin1() );
      dcopObject();
  }
  else
      dcopObject();

  // default document properties
  d->syntaxVersion = CURRENT_SYNTAX_VERSION;
  d->verticalScrollBar = true;
  d->horizontalScrollBar = true;
  d->columnHeader = true;
  d->rowHeader = true;
  d->gridColor = TQt::lightGray;
  d->indentValue = 10.0;
  d->showStatusBar = true;
  d->showFormulaBar = true;
  d->showTabBar = true;
  d->showError = false;
  d->calcMethod = SumOfNumber;
  d->moveTo = KSpread::Bottom;
  d->completionMode = TDEGlobalSettings::CompletionAuto;
  d->spellConfig = 0;
  d->dontCheckUpperWord = false;
  d->dontCheckTitleCase = false;
}

Doc::~Doc()
{
  //don't save config when kword is embedded into konqueror
  if(isReadWrite())
    saveConfig();

  delete d->dcop;
  d->s_docs.remove( this );

  kdDebug(36001) << "alive 1" << endl;

  delete d->commandHistory;

  delete d->spellConfig;

  delete d->locale;
  delete d->map;
  delete d->styleManager;
  delete d->parser;
  delete d->formatter;
  delete d->converter;
  delete d->calc;

  delete d;
}

TQValueList<Doc*> Doc::documents()
{
  return Private::s_docs;
}

bool Doc::initDoc(InitDocFlags flags, TQWidget* parentWidget)
{
  //  ElapsedTime et( "      initDoc        " );

    TQString f;

    if (flags==KoDocument::InitDocEmpty)
    {
        TDEConfig *config = Factory::global()->config();
        int _page=1;
        if( config->hasGroup("Parameters" ))
        {
                config->setGroup( "Parameters" );
                _page=config->readNumEntry( "NbPage",1 ) ;
        }

        for( int i=0; i<_page; i++ )
          map()->addNewSheet();

        resetURL();
        setEmpty();
        initConfig();
        styleManager()->createBuiltinStyles();

        return true;
    }

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

    ret = KoTemplateChooseDia::choose( Factory::global(), f,
                                       dlgtype, "kspread_template", parentWidget );

    if ( ret == KoTemplateChooseDia::File )
    {
  KURL url( f );

  bool ok=openURL(url);

  while (KoDocument::isLoading())
    kapp->processEvents();

  return ok;


    }

    if ( ret == KoTemplateChooseDia::Empty )
    {
  TDEConfig *config = Factory::global()->config();
  int _page=1;
  if( config->hasGroup("Parameters" ))
  {
    config->setGroup( "Parameters" );
    _page=config->readNumEntry( "NbPage",1 ) ;
  }

  for( int i=0; i<_page; i++ )
    map()->addNewSheet ();

  resetURL();
  setEmpty();
  initConfig();
        styleManager()->createBuiltinStyles();
  return true;
    }

    if ( ret == KoTemplateChooseDia::Template )
    {
        resetURL();
        d->m_loadingInfo = new KSPLoadingInfo;
        d->m_loadingInfo->setLoadTemplate( true );
        bool ok = loadNativeFormat( f );
        if ( !ok )
        {
            showLoadingErrorDialog();
            deleteLoadingInfo();
        }
        setEmpty();
        initConfig();
        return ok;
    }

    return false;
}

void Doc::openTemplate (const TQString& file)
{
    d->m_loadingInfo = new KSPLoadingInfo;
    d->m_loadingInfo->setLoadTemplate( true );
    KoDocument::openTemplate( file );
    deleteLoadingInfo();
    initConfig();
}

void Doc::initEmpty()
{
    TDEConfig *config = Factory::global()->config();
    int _page=1;
    if( config->hasGroup("Parameters" ))
    {
        config->setGroup( "Parameters" );
        _page=config->readNumEntry( "NbPage",1 ) ;
    }

    for( int i=0; i<_page; i++ )
        map()->addNewSheet();

    resetURL();
    initConfig();
    styleManager()->createBuiltinStyles();

    KoDocument::initEmpty();
}

TDELocale *Doc::locale () const
{
  return d->locale;
}

Map *Doc::map () const
{
  return d->map;
}

StyleManager *Doc::styleManager () const
{
  return d->styleManager;
}

ValueParser *Doc::parser () const
{
  return d->parser;
}

ValueFormatter *Doc::formatter () const
{
  return d->formatter;
}

ValueConverter *Doc::converter () const
{
  return d->converter;
}

ValueCalc *Doc::calc () const
{
  return d->calc;
}

void Doc::saveConfig()
{
    if ( isEmbedded() ||!isReadWrite())
        return;
    TDEConfig *config = Factory::global()->config();
    config->setGroup( "Parameters" );
    config->writeEntry( "Zoom", m_zoom );

}

void Doc::initConfig()
{
    TDEConfig *config = Factory::global()->config();

    if( config->hasGroup("KSpread Page Layout" ))
    {
      config->setGroup( "KSpread Page Layout" );
      setUnit( (KoUnit::Unit)config->readNumEntry( "Default unit page" ,0));
    }
    if( config->hasGroup("Parameters" ))
    {
        config->setGroup( "Parameters" );
        m_zoom = config->readNumEntry( "Zoom", 100 );
    }
    else
      m_zoom = 100;

    int undo=30;
    if(config->hasGroup("Misc" ) )
    {
        config->setGroup( "Misc" );
        undo=config->readNumEntry("UndoRedo",-1);
    }
    if(undo!=-1)
        setUndoRedoLimit(undo);

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

int Doc::syntaxVersion() const
{
  return d->syntaxVersion;
}

bool Doc::isLoading() const
{
  return d->isLoading || KoDocument::isLoading();
}

void Doc::doNotPaint(bool status)
{
  d->isLoading = status;
}


TQColor Doc::pageBorderColor() const
{
  return d->pageBorderColor;
}

void Doc::changePageBorderColor( const TQColor  & _color)
{
  d->pageBorderColor = _color;
}

const TQValueList<Reference>  &Doc::listArea()
{
  return d->refs;
}

TDECompletion& Doc::completion()
{
  return d->listCompletion;
}

KoView* Doc::createViewInstance( TQWidget* parent, const char* name )
{
    if ( name == 0 )
        name = "View";
    return new View( parent, name, this );
}

bool Doc::saveChildren( KoStore* _store )
{
  return map()->saveChildren( _store );
}

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

bool Doc::completeSaving( KoStore* _store )
{
    d->m_pictureCollection.saveToStore( KoPictureCollection::CollectionPicture, _store, d->usedPictures );

    return true;
}


TQDomDocument Doc::saveXML()
{
    //Terminate current cell edition, if any
    TQPtrListIterator<KoView> it( views() );

    /* don't pull focus away from the editor if this is just a background
       autosave */
    if (!isAutosaving())
    {
        for (; it.current(); ++it )
            static_cast<View *>( it.current() )->deleteEditor( true );
    }

    TQDomDocument doc = createDomDocument( "spreadsheet", CURRENT_DTD_VERSION );
    TQDomElement spread = doc.documentElement();
    spread.setAttribute( "editor", "KSpread" );
    spread.setAttribute( "mime", "application/x-kspread" );
    spread.setAttribute( "syntaxVersion", CURRENT_SYNTAX_VERSION );

    TQDomElement dlocale = ((Locale *)locale())->save( doc );
    spread.appendChild( dlocale );

    if (d->refs.count() != 0 )
    {
        TQDomElement areaname = saveAreaName( doc );
        spread.appendChild( areaname );
    }

    if( !d->spellListIgnoreAll.isEmpty() )
    {
        TQDomElement spellCheckIgnore = doc.createElement( "SPELLCHECKIGNORELIST" );
        spread.appendChild( spellCheckIgnore );
        for ( TQStringList::Iterator it = d->spellListIgnoreAll.begin(); it != d->spellListIgnoreAll.end(); ++it )
        {
            TQDomElement spellElem = doc.createElement( "SPELLCHECKIGNOREWORD" );
            spellCheckIgnore.appendChild( spellElem );
            spellElem.setAttribute( "word", *it );
        }
    }

    SavedDocParts::const_iterator iter = m_savedDocParts.begin();
    SavedDocParts::const_iterator end  = m_savedDocParts.end();
    while ( iter != end )
    {
      // save data we loaded in the beginning and which has no owner back to file
      spread.appendChild( iter.data() );
      ++iter;
    }

    TQDomElement defaults = doc.createElement( "defaults" );
    defaults.setAttribute( "row-height", Format::globalRowHeight() );
    defaults.setAttribute( "col-width", Format::globalColWidth() );
    spread.appendChild( defaults );

    Plugin * plugin = d->plugins.first();
    for ( ; plugin != 0; plugin = d->plugins.next() )
    {
      TQDomElement data( plugin->saveXML( doc ) );
      if ( !data.isNull() )
        spread.appendChild( data );
    }

    TQDomElement s = styleManager()->save( doc );
    spread.appendChild( s );
    TQDomElement e = map()->save( doc );
    spread.appendChild( e );

    setModified( false );

    return doc;
}

bool Doc::loadChildren( KoStore* _store )
{
    return map()->loadChildren( _store );
}

bool Doc::saveOasis( KoStore* store, KoXmlWriter* manifestWriter )
{
  emitBeginOperation(true);
  	bool result=saveOasisHelper( store, manifestWriter, SaveAll );
  emitEndOperation();

  return result;
}

bool Doc::saveOasisHelper( KoStore* store, KoXmlWriter* manifestWriter, SaveFlag saveFlag,
                            TQString* /*plainText*/, KoPicture* /*picture*/ )
{
    d->m_pictureCollection.assignUniqueIds();
    //Terminate current cell edition, if any
    TQPtrListIterator<KoView> it2( views() );
    d->m_savingWholeDocument = saveFlag == SaveAll ? true : false;

    /* don't pull focus away from the editor if this is just a background
       autosave */
    if (!isAutosaving())
    {
        for (; it2.current(); ++it2 )
            static_cast<View *>( it2.current() )->deleteEditor( true );
    }
    if ( !store->open( "content.xml" ) )
        return false;

    KoStoreDevice dev( store );
    KoXmlWriter* contentWriter = createOasisXmlWriter( &dev, "office:document-content" );
    KoGenStyles mainStyles;//for compile

    KTempFile contentTmpFile;
    //Check that temp file was successfully created
    if (contentTmpFile.status() != 0)
    {
	    tqWarning("Creation of temporary file to store document content failed.");
	    return false;
    }

    contentTmpFile.setAutoDelete( true );
    TQFile* tmpFile = contentTmpFile.file();
    KoXmlWriter contentTmpWriter( tmpFile, 1 );



    //todo fixme just add a element for testing saving content.xml
    contentTmpWriter.startElement( "office:body" );
    contentTmpWriter.startElement( "office:spreadsheet" );

    int indexObj = 1;
    int partIndexObj = 0;

    // Saving the custom cell styles including the default cell style.
    styleManager()->saveOasis( mainStyles );

    // Saving the default column style
    KoGenStyle defaultColumnStyle( Doc::STYLE_COLUMN_USER, "table-column" );
    defaultColumnStyle.addPropertyPt( "style:column-width", Format::globalColWidth() );
    defaultColumnStyle.setDefaultStyle( true );
    mainStyles.lookup( defaultColumnStyle, "Default", KoGenStyles::DontForceNumbering );

    // Saving the default row style
    KoGenStyle defaultRowStyle( Doc::STYLE_ROW_USER, "table-row" );
    defaultRowStyle.addPropertyPt( "style:row-height", Format::globalRowHeight() );
    defaultRowStyle.setDefaultStyle( true );
    mainStyles.lookup( defaultRowStyle, "Default", KoGenStyles::DontForceNumbering );

    // Saving the map.
    map()->saveOasis( contentTmpWriter, mainStyles, store,  manifestWriter, indexObj, partIndexObj );

    saveOasisAreaName( contentTmpWriter );
    contentTmpWriter.endElement(); ////office:spreadsheet
  contentTmpWriter.endElement(); ////office:body

    // Done with writing out the contents to the tempfile, we can now write out the automatic styles
    contentWriter->startElement( "office:automatic-styles" );

    TQValueList<KoGenStyles::NamedStyle> styles = mainStyles.styles( KoGenStyle::STYLE_AUTO );
    TQValueList<KoGenStyles::NamedStyle>::const_iterator it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( contentWriter, mainStyles, "style:style", (*it).name, "style:paragraph-properties" );
    }

    styles = mainStyles.styles( STYLE_PAGE );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( contentWriter, mainStyles, "style:style", (*it).name, "style:table-properties" );
    }

    styles = mainStyles.styles( STYLE_COLUMN_AUTO );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( contentWriter, mainStyles, "style:style", (*it).name, "style:table-column-properties" );
    }

    styles = mainStyles.styles( STYLE_ROW_AUTO );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( contentWriter, mainStyles, "style:style", (*it).name, "style:table-row-properties" );
    }

    styles = mainStyles.styles( STYLE_CELL_AUTO );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( contentWriter, mainStyles, "style:style", (*it).name, "style:table-cell-properties" );
    }

    styles = mainStyles.styles( KoGenStyle::STYLE_NUMERIC_NUMBER );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
      (*it).style->writeStyle( contentWriter, mainStyles, "number:number-style", (*it).name, 0 /*TODO ????*/  );
    }

    //TODO FIXME !!!!
    styles = mainStyles.styles( KoGenStyle::STYLE_NUMERIC_DATE );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( contentWriter, mainStyles, "number:date-style", (*it).name, 0 /*TODO ????*/  );
    }

    styles = mainStyles.styles( KoGenStyle::STYLE_NUMERIC_TIME );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( contentWriter, mainStyles, "number:time-style", (*it).name, 0 /*TODO ????*/  );
    }

    styles = mainStyles.styles( KoGenStyle::STYLE_NUMERIC_FRACTION );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( contentWriter, mainStyles, "number:number-style", (*it).name, 0 /*TODO ????*/  );
    }

    //TODO FIME !!!!!
    styles = mainStyles.styles( KoGenStyle::STYLE_NUMERIC_PERCENTAGE );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( contentWriter, mainStyles, "number:percentage-style", (*it).name, 0 /*TODO ????*/  );
    }

    //TODO FIME !!!!!
    styles = mainStyles.styles( KoGenStyle::STYLE_NUMERIC_CURRENCY );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( contentWriter, mainStyles, "number:currency-style", (*it).name, 0 /*TODO ????*/  );
    }

    styles = mainStyles.styles( KoGenStyle::STYLE_NUMERIC_SCIENTIFIC );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( contentWriter, mainStyles, "number:number-style", (*it).name, 0 /*TODO ????*/  );
    }


    contentWriter->endElement(); // office:automatic-styles


   // And now we can copy over the contents from the tempfile to the real one
    tmpFile->close();
    contentWriter->addCompleteElement( tmpFile );
    contentTmpFile.close();


    contentWriter->endElement(); // root element
    contentWriter->endDocument();
    delete contentWriter;
    if ( !store->close() )
        return false;
    //add manifest line for content.xml
    manifestWriter->addManifestEntry( "content.xml",  "text/xml" );

    //todo add manifest line for style.xml
    if ( !store->open( "styles.xml" ) )
        return false;

    manifestWriter->addManifestEntry( "styles.xml",  "text/xml" );
    saveOasisDocumentStyles( store, mainStyles );

    if ( !store->close() ) // done with styles.xml
        return false;

    makeUsedPixmapList();
    d->m_pictureCollection.saveOasisToStore( store, d->usedPictures, manifestWriter);

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

    KoXmlWriter* settingsWriter = createOasisXmlWriter(&dev, "office:document-settings");
    settingsWriter->startElement("office:settings");
    settingsWriter->startElement("config:config-item-set");
    settingsWriter->addAttribute("config:name", "view-settings");

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

    saveOasisSettings( *settingsWriter );

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

    settingsWriter->startElement("config:config-item-set");
    settingsWriter->addAttribute("config:name", "configuration-settings");
    settingsWriter->addConfigItem("SpellCheckerIgnoreList", d->spellListIgnoreAll.join( "," ) );
    settingsWriter->endElement(); // config:config-item-set
    settingsWriter->endElement(); // office:settings
    settingsWriter->endElement(); // Root:element
    settingsWriter->endDocument();
    delete settingsWriter;

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

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


    if ( saveFlag == SaveSelected )
    {
      TQPtrListIterator<EmbeddedObject> it(embeddedObjects() );
      for( ; it.current(); ++it )
      {
        if ( it.current()->getType() != OBJECT_CHART  && it.current()->getType() != OBJECT_KOFFICE_PART )
          continue;
        KoDocumentChild *embedded = dynamic_cast<EmbeddedKOfficeObject *>(it.current() )->embeddedObject();
            //NOTE: If an application's .desktop file lies about opendocument support (ie. it indicates that it has
            //a native OASIS mime type, when it doesn't, this causes a crash when trying to reload and paint
            //the object, since it won't have an associated document.
          if ( !embedded->saveOasis( store, manifestWriter ) )
            continue;
      }
    }


    setModified( false );

    return true;
}

void Doc::loadOasisSettings( const TQDomDocument&settingsDoc )
{
    KoOasisSettings settings( settingsDoc );
    KoOasisSettings::Items viewSettings = settings.itemSet( "view-settings" );
    if ( !viewSettings.isNull() )
    {
        setUnit(KoUnit::unit(viewSettings.parseConfigItemString("unit")));
    }
    map()->loadOasisSettings( settings );
    loadOasisIgnoreList( settings );
}

void Doc::saveOasisSettings( KoXmlWriter &settingsWriter )
{
    settingsWriter.startElement("config:config-item-map-indexed");
    settingsWriter.addAttribute("config:name", "Views");
    settingsWriter.startElement( "config:config-item-map-entry" );
    map()->saveOasisSettings( settingsWriter );
    settingsWriter.endElement();
    settingsWriter.endElement();
}


void Doc::loadOasisIgnoreList( const KoOasisSettings& settings )
{
    KoOasisSettings::Items configurationSettings = settings.itemSet( "configuration-settings" );
    if ( !configurationSettings.isNull() )
    {
        const TQString ignorelist = configurationSettings.parseConfigItemString( "SpellCheckerIgnoreList" );
        //kdDebug()<<" ignorelist :"<<ignorelist<<endl;
        d->spellListIgnoreAll = TQStringList::split( ',', ignorelist );
    }
}


void Doc::saveOasisDocumentStyles( KoStore* store, KoGenStyles& mainStyles ) const
{
    KoStoreDevice stylesDev( store );
    KoXmlWriter* stylesWriter = createOasisXmlWriter( &stylesDev, "office:document-styles" );

    stylesWriter->startElement( "office:styles" );
    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" );
    }

    // Writing out the common column styles.
    styles = mainStyles.styles( Doc::STYLE_COLUMN_USER );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
      if ( (*it).style->isDefaultStyle() ) {
        (*it).style->writeStyle( stylesWriter, mainStyles, "style:default-style", (*it).name, "style:table-column-properties" );
      }
      else {
        (*it).style->writeStyle( stylesWriter, mainStyles, "style:style", (*it).name, "style:table-column-properties" );
      }
    }

    // Writing out the row column styles.
    styles = mainStyles.styles( Doc::STYLE_ROW_USER );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
      if ( (*it).style->isDefaultStyle() ) {
        (*it).style->writeStyle( stylesWriter, mainStyles, "style:default-style", (*it).name, "style:table-row-properties" );
      }
      else {
        (*it).style->writeStyle( stylesWriter, mainStyles, "style:style", (*it).name, "style:table-row-properties" );
      }
    }

    // Writing out the common cell styles.
    styles = mainStyles.styles( Doc::STYLE_CELL_USER );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        if ( (*it).style->isDefaultStyle() ) {
          (*it).style->writeStyle( stylesWriter, mainStyles, "style:default-style", (*it).name, "style:table-cell-properties" );
        }
        else {
          (*it).style->writeStyle( stylesWriter, mainStyles, "style:style", (*it).name, "style:table-cell-properties" );
        }
    }

    styles = mainStyles.styles( KoGenStyle::STYLE_HATCH );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( stylesWriter, mainStyles, "draw:hatch", (*it).name, "style:graphic-properties" ,  true,  true /*add draw:name*/);
    }
    styles = mainStyles.styles( KoGenStyle::STYLE_GRAPHICAUTO );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( stylesWriter, mainStyles, "style:style", (*it).name , "style:graphic-properties"  );
    }

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

    stylesWriter->startElement( "office:automatic-styles" );
    styles = mainStyles.styles( KoGenStyle::STYLE_PAGELAYOUT );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( stylesWriter, mainStyles, "style:page-layout", (*it).name, "style:page-layout-properties", false /*don't close*/ );
        stylesWriter->endElement();
    }

    stylesWriter->endElement(); // office:automatic-styles
    //code from kword
    stylesWriter->startElement( "office:master-styles" );

    styles = mainStyles.styles( Doc::STYLE_PAGEMASTER );
    it = styles.begin();
    for ( ; it != styles.end() ; ++it ) {
        (*it).style->writeStyle( stylesWriter, mainStyles, "style:master-page", (*it).name, "" );
    }

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


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

bool Doc::loadOasis( const TQDomDocument& doc, KoOasisStyles& oasisStyles, const TQDomDocument& settings, KoStore* store)
{
    if ( !d->m_loadingInfo )
        d->m_loadingInfo = new KSPLoadingInfo;

    TQTime dt;
    dt.start();

    emit sigProgress( 0 );
    d->isLoading = true;
    d->spellListIgnoreAll.clear();

    d->refs.clear();

    TQDomElement content = doc.documentElement();
    TQDomElement realBody ( KoDom::namedItemNS( content, KoXmlNS::office, "body" ) );
    if ( realBody.isNull() )
    {
        setErrorMessage( i18n( "Invalid OASIS OpenDocument file. No office:body tag found." ));
        deleteLoadingInfo();
        return false;
    }
    TQDomElement body = KoDom::namedItemNS( realBody, KoXmlNS::office, "spreadsheet" );

    if ( body.isNull() )
    {
        kdError(32001) << "No office:spreadsheet 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 document is not a spreadsheet, but %1. Please try opening it with the appropriate application." ).arg( KoDocument::tagNameToDocumentType( localName ) ) );
        deleteLoadingInfo();
        return false;
    }

    KoOasisLoadingContext context( this, oasisStyles, store );

    //load in first
    styleManager()->loadOasisStyleTemplate( oasisStyles );

    // load default column style
    const TQDomElement* defaultColumnStyle = oasisStyles.defaultStyle( "table-column" );
    if ( defaultColumnStyle )
    {
//       kDebug() << "style:default-style style:family=\"table-column\"" << endl;
      KoStyleStack styleStack;
      styleStack.push( *defaultColumnStyle );
      styleStack.setTypeProperties( "table-column" );
      if ( styleStack.hasAttributeNS( KoXmlNS::style, "column-width" ) )
      {
        const double width = KoUnit::parseValue( styleStack.attributeNS( KoXmlNS::style, "column-width" ), -1.0 );
        if ( width != -1.0 )
        {
//           kDebug() << "\tstyle:column-width: " << width << endl;
          Format::setGlobalColWidth( width );
        }
      }
    }

    // load default row style
    const TQDomElement* defaultRowStyle = oasisStyles.defaultStyle( "table-row" );
    if ( defaultRowStyle )
    {
//       kDebug() << "style:default-style style:family=\"table-row\"" << endl;
      KoStyleStack styleStack;
      styleStack.push( *defaultRowStyle );
      styleStack.setTypeProperties( "table-row" );
      if ( styleStack.hasAttributeNS( KoXmlNS::style, "row-height" ) )
      {
        const double height = KoUnit::parseValue( styleStack.attributeNS( KoXmlNS::style, "row-height" ), -1.0 );
        if ( height != -1.0 )
        {
//           kDebug() << "\tstyle:row-height: " << height << endl;
          Format::setGlobalRowHeight( height );
        }
      }
    }

    // TODO check versions and mimetypes etc.
    loadOasisAreaName( body );
    loadOasisCellValidation( body );

    // all <sheet:sheet> goes to workbook
    if ( !map()->loadOasis( body, context ) )
    {
        d->isLoading = false;
        deleteLoadingInfo();
        return false;
    }


    if ( !settings.isNull() )
    {
        loadOasisSettings( settings );
    }
    emit sigProgress( 90 );
    initConfig();
    emit sigProgress(-1);

    //display loading time
    kdDebug(36001) << "Loading took " << (float)(dt.elapsed()) / 1000.0 << " seconds" << endl;
    return true;
}

bool Doc::loadXML( TQIODevice *, const TQDomDocument& doc )
{
  TQTime dt;
  dt.start();

  emit sigProgress( 0 );
  d->isLoading = true;
  d->spellListIgnoreAll.clear();
  // <spreadsheet>
  TQDomElement spread = doc.documentElement();

  if ( spread.attribute( "mime" ) != "application/x-kspread" && spread.attribute( "mime" ) != "application/vnd.kde.kspread" )
  {
    d->isLoading = false;
    setErrorMessage( i18n( "Invalid document. Expected mimetype application/x-kspread or application/vnd.kde.kspread, got %1" ).arg( spread.attribute("mime") ) );
    return false;
  }

  d->syntaxVersion = Doc::getAttribute( spread, "syntaxVersion", 0 );
  if ( d->syntaxVersion > CURRENT_SYNTAX_VERSION )
  {
      int ret = KMessageBox::warningContinueCancel(
          0, i18n("This document was created with a newer version of KSpread (syntax version: %1)\n"
                  "When you open it with this version of KSpread, some information may be lost.").arg(d->syntaxVersion),
          i18n("File Format Mismatch"), KStdGuiItem::cont() );
      if ( ret == KMessageBox::Cancel )
      {
          setErrorMessage( "USER_CANCELED" );
          return false;
      }
  }

  // <locale>
  TQDomElement loc = spread.namedItem( "locale" ).toElement();
  if ( !loc.isNull() )
      ((Locale *) locale())->load( loc );

  emit sigProgress( 5 );

  TQDomElement defaults = spread.namedItem( "defaults" ).toElement();
  if ( !defaults.isNull() )
  {
    bool ok = false;
    double d = defaults.attribute( "row-height" ).toDouble( &ok );
    if ( !ok )
      return false;
    Format::setGlobalRowHeight( d );

    d = defaults.attribute( "col-width" ).toDouble( &ok );

    if ( !ok )
      return false;

    Format::setGlobalColWidth( d );
  }

  d->refs.clear();
  //<areaname >
  TQDomElement areaname = spread.namedItem( "areaname" ).toElement();
  if ( !areaname.isNull())
    loadAreaName(areaname);

  TQDomElement ignoreAll = spread.namedItem( "SPELLCHECKIGNORELIST").toElement();
  if ( !ignoreAll.isNull())
  {
      TQDomElement spellWord=spread.namedItem("SPELLCHECKIGNORELIST").toElement();

      spellWord=spellWord.firstChild().toElement();
      while ( !spellWord.isNull() )
      {
          if ( spellWord.tagName()=="SPELLCHECKIGNOREWORD" )
          {
              d->spellListIgnoreAll.append(spellWord.attribute("word"));
          }
          spellWord=spellWord.nextSibling().toElement();
      }
  }

  emit sigProgress( 40 );
  // In case of reload (e.g. from konqueror)
  map()->sheetList().clear(); // it's set to autoDelete

  TQDomElement styles = spread.namedItem( "styles" ).toElement();
  if ( !styles.isNull() )
  {
    if ( !styleManager()->loadXML( styles ) )
    {
      setErrorMessage( i18n( "Styles cannot be loaded." ) );
      d->isLoading = false;
      return false;
    }
  }

  // <map>
  TQDomElement mymap = spread.namedItem( "map" ).toElement();
  if ( mymap.isNull() )
  {
      setErrorMessage( i18n("Invalid document. No map tag.") );
      d->isLoading = false;
      return false;
  }
  if ( !map()->loadXML( mymap ) )
  {
      d->isLoading = false;
      return false;
  }

  //Backwards compatibility with older versions for paper layout
  if ( d->syntaxVersion < 1 )
  {
    TQDomElement paper = spread.namedItem( "paper" ).toElement();
    if ( !paper.isNull() )
    {
      loadPaper( paper );
    }
  }

  emit sigProgress( 85 );

  TQDomElement element( spread.firstChild().toElement() );
  while ( !element.isNull() )
  {
    TQString tagName( element.tagName() );

    if ( tagName != "locale" && tagName != "map" && tagName != "styles"
         && tagName != "SPELLCHECKIGNORELIST" && tagName != "areaname"
         && tagName != "paper" )
    {
      // belongs to a plugin, load it and save it for later use
      m_savedDocParts[ tagName ] = element;
    }

    element = element.nextSibling().toElement();
  }

  emit sigProgress( 90 );
  initConfig();
  emit sigProgress(-1);

   kdDebug(36001) << "Loading took " << (float)(dt.elapsed()) / 1000.0 << " seconds" << endl;

  emit sig_refreshView();

  return true;
}

void Doc::loadPaper( TQDomElement const & paper )
{
  // <paper>
  TQString format = paper.attribute( "format" );
  TQString orientation = paper.attribute( "orientation" );

  // <borders>
  TQDomElement borders = paper.namedItem( "borders" ).toElement();
  if ( !borders.isNull() )
  {
    float left = borders.attribute( "left" ).toFloat();
    float right = borders.attribute( "right" ).toFloat();
    float top = borders.attribute( "top" ).toFloat();
    float bottom = borders.attribute( "bottom" ).toFloat();

    //apply to all sheet
    TQPtrListIterator<Sheet> it ( map()->sheetList() );
    for( ; it.current(); ++it )
    {
      it.current()->print()->setPaperLayout( left, top, right, bottom,
                                             format, orientation );
    }
  }

  TQString hleft, hright, hcenter;
  TQString fleft, fright, fcenter;
  // <head>
  TQDomElement head = paper.namedItem( "head" ).toElement();
  if ( !head.isNull() )
  {
    TQDomElement left = head.namedItem( "left" ).toElement();
    if ( !left.isNull() )
      hleft = left.text();
    TQDomElement center = head.namedItem( "center" ).toElement();
    if ( !center.isNull() )
      hcenter = center.text();
    TQDomElement right = head.namedItem( "right" ).toElement();
    if ( !right.isNull() )
      hright = right.text();
  }
  // <foot>
  TQDomElement foot = paper.namedItem( "foot" ).toElement();
  if ( !foot.isNull() )
  {
    TQDomElement left = foot.namedItem( "left" ).toElement();
    if ( !left.isNull() )
      fleft = left.text();
    TQDomElement center = foot.namedItem( "center" ).toElement();
    if ( !center.isNull() )
      fcenter = center.text();
    TQDomElement right = foot.namedItem( "right" ).toElement();
    if ( !right.isNull() )
      fright = right.text();
  }
  //The macro "<sheet>" formerly was typed as "<table>"
  hleft   = hleft.replace(   "<table>", "<sheet>" );
  hcenter = hcenter.replace( "<table>", "<sheet>" );
  hright  = hright.replace(  "<table>", "<sheet>" );
  fleft   = fleft.replace(   "<table>", "<sheet>" );
  fcenter = fcenter.replace( "<table>", "<sheet>" );
  fright  = fright.replace(  "<table>", "<sheet>" );

  TQPtrListIterator<Sheet> it ( map()->sheetList() );
  for( ; it.current(); ++it )
  {
    it.current()->print()->setHeadFootLine( hleft, hcenter, hright,
                                            fleft, fcenter, fright);
  }
}

bool Doc::completeLoading( KoStore* /* _store */ )
{
  kdDebug(36001) << "------------------------ COMPLETING --------------------" << endl;

  d->isLoading = false;

  //  map()->update();

  TQPtrListIterator<KoView> it( views() );
  for (; it.current(); ++it )
    ((View*)it.current())->initialPosition();

  kdDebug(36001) << "------------------------ COMPLETION DONE --------------------" << endl;

  setModified( false );
  return true;
}


void Doc::registerPlugin( Plugin * plugin )
{
  d->plugins.append( plugin );
}

void Doc::deregisterPlugin( Plugin * plugin )
{
  d->plugins.remove( plugin );
}

bool Doc::docData( TQString const & xmlTag, TQDomElement & data )
{
  SavedDocParts::iterator iter = m_savedDocParts.find( xmlTag );
  if ( iter == m_savedDocParts.end() )
    return false;

  data = iter.data();
  m_savedDocParts.erase( iter );

  return true;
}

void Doc::setShowVerticalScrollBar(bool _show)
{
  d->verticalScrollBar=_show;
}

bool Doc::showVerticalScrollBar()const
{
  return  d->verticalScrollBar;
}

void Doc::setShowHorizontalScrollBar(bool _show)
{
  d->horizontalScrollBar=_show;
}

bool Doc::showHorizontalScrollBar()const
{
  return  d->horizontalScrollBar;
}

TDEGlobalSettings::Completion Doc::completionMode( ) const
{
  return d->completionMode;
}

void Doc::setShowColumnHeader(bool _show)
{
  d->columnHeader=_show;
}

bool Doc::showColumnHeader() const
{
  return  d->columnHeader;
}

void Doc::setShowRowHeader(bool _show)
{
  d->rowHeader=_show;
}

bool Doc::showRowHeader() const
{
  return  d->rowHeader;
}

void Doc::setGridColor( const TQColor& color )
{
  d->gridColor = color;
}

TQColor Doc::gridColor() const
{
  return d->gridColor;
}

void Doc::setCompletionMode( TDEGlobalSettings::Completion complMode)
{
  d->completionMode= complMode;
}

double Doc::indentValue() const
{
  return d->indentValue;
}

void Doc::setIndentValue( double val )
{
  d->indentValue = val;
}

void Doc::setShowStatusBar(bool _statusBar)
{
  d->showStatusBar=_statusBar;
}

bool Doc::showStatusBar() const
{
  return  d->showStatusBar;
}

void Doc::setShowTabBar(bool _tabbar)
{
  d->showTabBar=_tabbar;
}

bool Doc::showTabBar()const
{
  return  d->showTabBar;
}

void Doc::setShowFormulaBar(bool _formulaBar)
{
  d->showFormulaBar=_formulaBar;
}

bool Doc::showFormulaBar() const
{
  return  d->showFormulaBar;
}

void Doc::setShowMessageError(bool _show)
{
  d->showError=_show;
}

bool Doc::showMessageError() const
{
  return  d->showError;
}

KSpread::MoveTo Doc::getMoveToValue() const
{
  return d->moveTo;
}

void Doc::setMoveToValue(KSpread::MoveTo _moveTo)
{
  d->moveTo = _moveTo;
}

void Doc::setTypeOfCalc( MethodOfCalc _calc)
{
  d->calcMethod=_calc;
}

MethodOfCalc Doc::getTypeOfCalc() const
{
  return d->calcMethod;
}

void Doc::setKSpellConfig(KSpellConfig _tdespell)
{
  if (d->spellConfig == 0 )
    d->spellConfig = new KSpellConfig();

  d->spellConfig->setNoRootAffix(_tdespell.noRootAffix ());
  d->spellConfig->setRunTogether(_tdespell.runTogether ());
  d->spellConfig->setDictionary(_tdespell.dictionary ());
  d->spellConfig->setDictFromList(_tdespell.dictFromList());
  d->spellConfig->setEncoding(_tdespell.encoding());
  d->spellConfig->setClient(_tdespell.client());
}

KSpellConfig * Doc::getKSpellConfig()
{
    if (!d->spellConfig)
    {
    	KSpellConfig ksconfig;

    	TDEConfig *config = Factory::global()->config();
    	if( config->hasGroup("KSpell kspread" ) )
    	{
        	config->setGroup( "KSpell kspread" );
        	ksconfig.setNoRootAffix(config->readNumEntry ("KSpell_NoRootAffix", 0));
        	ksconfig.setRunTogether(config->readNumEntry ("KSpell_RunTogether", 0));
        	ksconfig.setDictionary(config->readEntry ("KSpell_Dictionary", ""));
        	ksconfig.setDictFromList(config->readNumEntry ("KSpell_DictFromList", false));
        	ksconfig.setEncoding(config->readNumEntry ("KSpell_Encoding", KS_E_ASCII));
        	ksconfig.setClient(config->readNumEntry ("KSpell_Client", KS_CLIENT_ISPELL));
        	setKSpellConfig(ksconfig);

        	setDontCheckUpperWord(config->readBoolEntry("KSpell_IgnoreUppercaseWords", false));
        	setDontCheckTitleCase(config->readBoolEntry("KSpell_IgnoreTitleCaseWords", false));
    	}
    }
  return d->spellConfig;
}

bool Doc::dontCheckUpperWord() const
{
  return d->dontCheckUpperWord;
}

void Doc::setDontCheckUpperWord( bool b )
{
  d->dontCheckUpperWord = b;
}

bool Doc::dontCheckTitleCase() const
{
  return  d->dontCheckTitleCase;
}

void Doc::setDontCheckTitleCase( bool b )
{
  d->dontCheckTitleCase = b;
}

TQString Doc::unitName() const
{
  return KoUnit::unitName( unit() );
}

void Doc::increaseNumOperation()
{
  ++d->numOperations;
}

void Doc::decreaseNumOperation()
{
  --d->numOperations;
}

void Doc::addIgnoreWordAllList( const TQStringList & _lst)
{
  d->spellListIgnoreAll = _lst;
}

TQStringList Doc::spellListIgnoreAll() const
{
  return d->spellListIgnoreAll;
}

void Doc::setZoomAndResolution( int zoom, int dpiX, int dpiY )
{
    KoZoomHandler::setZoomAndResolution( zoom, dpiX, dpiY );
}

void Doc::newZoomAndResolution( bool updateViews, bool /*forPrint*/ )
{
/*    layout();
    updateAllFrames();*/
    if ( updateViews )
    {
        emit sig_refreshView();
    }
}

void Doc::addCommand( KCommand* command )
{
  if (undoLocked()) return;
  d->commandHistory->addCommand( command, false );
  setModified( true );
}

void Doc::addCommand( UndoAction* undo )
{
  if (undoLocked()) return;
  UndoWrapperCommand* command = new UndoWrapperCommand( undo );
  addCommand( command );
  setModified( true );
}

void Doc::undo()
{
  undoLock ();
  d->commandHistory->undo();
  undoUnlock ();
}

void Doc::redo()
{
  undoLock ();
  d->commandHistory->redo();
  undoUnlock ();
}

void Doc::commandExecuted()
{
  setModified( true );
}

void Doc::documentRestored()
{
  setModified( false );
}

void Doc::undoLock()
{
  d->undoLocked++;
}

void Doc::undoUnlock()
{
  d->undoLocked--;
}

bool Doc::undoLocked() const
{
  return (d->undoLocked > 0);
}

KoCommandHistory* Doc::commandHistory()
{
  return d->commandHistory;
}

void Doc::enableUndo( bool _b )
{
    TQPtrListIterator<KoView> it( views() );
    for (; it.current(); ++it )
      static_cast<View *>( it.current() )->enableUndo( _b );
}

void Doc::enableRedo( bool _b )
{
    TQPtrListIterator<KoView> it( views() );
    for (; it.current(); ++it )
      static_cast<View *>( it.current() )->enableRedo( _b );
}

void Doc::paintContent( TQPainter& painter, const TQRect& rect,
                               bool transparent, double zoomX, double /*zoomY*/ )
{
    kdDebug(36001) << "paintContent() called on " << rect << endl;

  //  ElapsedTime et( "Doc::paintContent1" );
    //kdDebug(36001) << "Doc::paintContent m_zoom=" << m_zoom << " zoomX=" << zoomX << " zoomY=" << zoomY << " transparent=" << transparent << endl;

    // save current zoom
    int oldZoom = m_zoom;

    // choose sheet: the first or the active
    Sheet* sheet = 0L;
    if ( !d->activeSheet )
        sheet = map()->firstSheet();
    else
        sheet = d->activeSheet;
    if ( !sheet )
        return;

    // only one zoom is supported
    double d_zoom = 1.0;
    setZoomAndResolution( 100, KoGlobal::dpiX(), KoGlobal::dpiY() );
    if ( m_zoomedResolutionX != zoomX )
        d_zoom *= ( zoomX / m_zoomedResolutionX );

    // KSpread support zoom, therefore no need to scale with worldMatrix
    TQWMatrix matrix = painter.worldMatrix();
    matrix.setMatrix( 1, 0, 0, 1, matrix.dx(), matrix.dy() );
    TQRect prect = rect;
    prect.setWidth( (int) (prect.width() * painter.worldMatrix().m11()) );
    prect.setHeight( (int) (prect.height() * painter.worldMatrix().m22()) );
    setZoomAndResolution( (int) ( d_zoom * 100 ), KoGlobal::dpiX(), KoGlobal::dpiY() );
    // paint the content, now zoom is correctly set
    kdDebug(36001)<<"paintContent-------------------------------------\n";
    painter.save();
    painter.setWorldMatrix( matrix );
    paintContent( painter, prect, transparent, sheet, false );
    painter.restore();

    // restore zoom
    m_zoom = oldZoom;
    setZoomAndResolution( oldZoom, KoGlobal::dpiX(), KoGlobal::dpiY() );
}

void Doc::paintContent( TQPainter& painter, const TQRect& rect, bool /*transparent*/, Sheet* sheet, bool drawCursor )
{
    if ( isLoading() )
        return;
    //    ElapsedTime et( "Doc::paintContent2" );

    // if ( !transparent )
    // painter.eraseRect( rect );

    double xpos;
    double ypos;
    int left_col   = sheet->leftColumn( unzoomItX( rect.x() ), xpos );
    int right_col  = sheet->rightColumn( unzoomItX( rect.right() ) );
    int top_row    = sheet->topRow( unzoomItY( rect.y() ), ypos );
    int bottom_row = sheet->bottomRow( unzoomItY( rect.bottom() ) );
    TQPen pen;
    pen.setWidth( 1 );
    painter.setPen( pen );

    /* Update the entire visible area. */
    TQValueList<TQRect>  cellAreaList;
    cellAreaList.append( TQRect( left_col,
                                top_row,
                                right_col - left_col + 1,
                                bottom_row - top_row + 1) );

    paintCellRegions(painter, rect, NULL, cellAreaList, sheet, drawCursor);
}

void Doc::paintUpdates()
{
  //  ElapsedTime et( "Doc::paintUpdates" );

  TQPtrListIterator<KoView> it( views() );
  View  * view  = NULL;
  Sheet * sheet = NULL;

  for (; it.current(); ++it )
  {
    view = static_cast<View *>( it.current() );
    view->paintUpdates();
  }

  for (sheet = map()->firstSheet(); sheet != NULL;
       sheet = map()->nextSheet())
  {
    sheet->clearPaintDirtyData();
  }
}

void Doc::paintCellRegions(TQPainter& painter, const TQRect &viewRect,
			   View* view,
			   TQValueList<TQRect> cellRegions,
			   const Sheet* sheet, bool /*drawCursor*/)
{
  //
  // Clip away children
  //

  TQRegion rgn = painter.clipRegion();
  if ( rgn.isEmpty() )
    rgn = TQRegion( TQRect( 0, 0, viewRect.width(), viewRect.height() ) );

  TQWMatrix matrix;
  if ( view ) {
    matrix.scale( zoomedResolutionX(),
                  zoomedResolutionY() );
    matrix.translate( - view->canvasWidget()->xOffset(),
                      - view->canvasWidget()->yOffset() );
  }
  else {
    matrix = painter.worldMatrix();
  }

//   TQPtrListIterator<KoDocumentChild> it( children() );
//   for( ; it.current(); ++it ) {
//     // if ( ((Child*)it.current())->sheet() == sheet &&
//     //    !m_pView->hasDocumentInWindow( it.current()->document() ) )
//     if ( ((Child*)it.current())->sheet() == sheet)
//       rgn -= it.current()->region( matrix );
//   }
  painter.setClipRegion( rgn );

  TQPen pen;
  pen.setWidth( 1 );
  painter.setPen( pen );

  TQRect cellRegion;
  KoRect unzoomedViewRect = unzoomRect( viewRect );

  for (unsigned int i=0; i < cellRegions.size(); i++) {
    cellRegion = cellRegions[i];

    PaintRegion(painter, unzoomedViewRect, view, cellRegion, sheet);
  }
}


void Doc::PaintRegion(TQPainter &painter, const KoRect &viewRegion,
		      View* view, const TQRect &paintRegion,
		      const Sheet* sheet)
{
  // Paint region has cell coordinates (col,row) while viewRegion has
  // world coordinates.  paintRegion is the cells to update and
  // viewRegion is the area actually onscreen.

  if ( paintRegion.left() <= 0 || paintRegion.top() <= 0 )
    return;

  // Get the world coordinates of the upper left corner of the
  // paintRegion The view is NULL, when paintRegion is called from
  // paintContent, which itself is only called, when we should paint
  // the output for INACTIVE embedded view.  If inactive embedded,
  // then there is no view and we alwas start at top/left, so the
  // offset is 0.
  //
  KoPoint  dblCorner;
  if ( view == 0L ) //Most propably we are embedded and inactive, so no offset
    dblCorner = KoPoint( sheet->dblColumnPos( paintRegion.left() ),
			 sheet->dblRowPos( paintRegion.top() ) );
  else
    dblCorner = KoPoint( sheet->dblColumnPos( paintRegion.left() )
			 - view->canvasWidget()->xOffset(),
			 sheet->dblRowPos( paintRegion.top() )
			 - view->canvasWidget()->yOffset() );
  KoPoint dblCurrentCellPos( dblCorner );

  int regionBottom = paintRegion.bottom();
  int regionRight  = paintRegion.right();
  int regionLeft   = paintRegion.left();
  int regionTop    = paintRegion.top();

  TQValueList<TQPoint>  mergedCellsPainted;
  for ( int y = regionTop;
        y <= regionBottom && dblCurrentCellPos.y() <= viewRegion.bottom();
        ++y )
  {
    const RowFormat * row_lay = sheet->rowFormat( y );
    dblCurrentCellPos.setX( dblCorner.x() );

    for ( int x = regionLeft;
          x <= regionRight && dblCurrentCellPos.x() <= viewRegion.right();
          ++x )
    {
      const ColumnFormat *col_lay = sheet->columnFormat( x );
      Cell* cell = sheet->cellAt( x, y );

      TQPoint cellRef( x, y );

#if 0
      bool paintBordersBottom = false;
      bool paintBordersRight  = false;
      bool paintBordersLeft   = false;
      bool paintBordersTop    = false;
#endif
      int paintBorder = Cell::Border_None;

      TQPen rightPen( cell->effRightBorderPen( x, y ) );
      TQPen leftPen( cell->effLeftBorderPen( x, y ) );
      TQPen topPen( cell->effTopBorderPen( x, y ) );
      TQPen bottomPen( cell->effBottomBorderPen( x, y ) );

      // Paint border if outermost cell or if the pen is more "worth"
      // than the border pen of the cell on the other side of the
      // border or if the cell on the other side is not painted. In
      // the latter case get the pen that is of more "worth"

      // right border:
      if ( x >= KS_colMax )
        //paintBordersRight = true;
        paintBorder |= Cell::Border_Right;
      else if ( x == regionRight ) {
	paintBorder |= Cell::Border_Right;
	if ( cell->effRightBorderValue( x, y )
	     < sheet->cellAt( x + 1, y )->effLeftBorderValue( x + 1, y ) )
	  rightPen = sheet->cellAt( x + 1, y )->effLeftBorderPen( x + 1, y );
      }
      else {
	paintBorder |= Cell::Border_Right;
	if ( cell->effRightBorderValue( x, y )
	     < sheet->cellAt( x + 1, y )->effLeftBorderValue( x + 1, y ) )
	  rightPen = sheet->cellAt( x + 1, y )->effLeftBorderPen( x + 1, y );
      }

      // Similiar for other borders...
      // bottom border:
      if ( y >= KS_rowMax )
        paintBorder |= Cell::Border_Bottom;
      else if ( y == regionBottom ) {
	paintBorder |= Cell::Border_Bottom;
	if ( cell->effBottomBorderValue( x, y )
	     < sheet->cellAt( x, y + 1 )->effTopBorderValue( x, y + 1) )
	  bottomPen = sheet->cellAt( x, y + 1 )->effTopBorderPen( x, y + 1 );
      }
      else {
        paintBorder |= Cell::Border_Bottom;
        if ( cell->effBottomBorderValue( x, y )
	     < sheet->cellAt( x, y + 1 )->effTopBorderValue( x, y + 1) )
          bottomPen = sheet->cellAt( x, y + 1 )->effTopBorderPen( x, y + 1 );
      }

      // left border:
      if ( x == 1 )
        paintBorder |= Cell::Border_Left;
      else if ( x == regionLeft ) {
	paintBorder |= Cell::Border_Left;
	if ( cell->effLeftBorderValue( x, y )
	     < sheet->cellAt( x - 1, y )->effRightBorderValue( x - 1, y ) )
	  leftPen = sheet->cellAt( x - 1, y )->effRightBorderPen( x - 1, y );
      }
      else {
        paintBorder |= Cell::Border_Left;
        if ( cell->effLeftBorderValue( x, y )
	     < sheet->cellAt( x - 1, y )->effRightBorderValue( x - 1, y ) )
          leftPen = sheet->cellAt( x - 1, y )->effRightBorderPen( x - 1, y );
      }

      // top border:
      if ( y == 1 )
        paintBorder |= Cell::Border_Top;
      else if ( y == regionTop ) {
	paintBorder |= Cell::Border_Top;
	if ( cell->effTopBorderValue( x, y )
	     < sheet->cellAt( x, y - 1 )->effBottomBorderValue( x, y - 1 ) )
	  topPen = sheet->cellAt( x, y - 1 )->effBottomBorderPen( x, y - 1 );
      }
      else {
        paintBorder |= Cell::Border_Top;
        if ( cell->effTopBorderValue( x, y )
	     < sheet->cellAt( x, y - 1 )->effBottomBorderValue( x, y - 1 ) )
          topPen = sheet->cellAt( x, y - 1 )->effBottomBorderPen( x, y - 1 );
      }

#if 0
      cell->paintCell( viewRegion, painter, view, dblCurrentCellPos, cellRef,
		       paintBordersRight, paintBordersBottom,
		       paintBordersLeft, paintBordersTop,
		       rightPen, bottomPen, leftPen, topPen,
		       mergedCellsPainted, false );

      Cell::BorderSides highlightBorder=Cell::Border_None;
      TQPen highlightPen;
#endif

      cell->paintCell( viewRegion, painter, view, dblCurrentCellPos, cellRef,
		       paintBorder,
		       rightPen, bottomPen, leftPen, topPen,
		       mergedCellsPainted, false );


      dblCurrentCellPos.setX( dblCurrentCellPos.x() + col_lay->dblWidth() );
    }
    dblCurrentCellPos.setY( dblCurrentCellPos.y() + row_lay->dblHeight() );
  }
}


DCOPObject* Doc::dcopObject()
{
    if ( !d->dcop )
        d->dcop = new DocIface( this );

    return d->dcop;
}

void Doc::addAreaName(const TQRect &_rect,const TQString & name,const TQString & sheetName)
{
  setModified( true );
  Reference tmp;
  tmp.rect = _rect;
  tmp.sheet_name = sheetName;
  tmp.ref_name = name;
  d->refs.append( tmp);
  emit sig_addAreaName( name );
}

void Doc::removeArea( const TQString & name)
{
    TQValueList<Reference>::Iterator it2;
    for ( it2 = d->refs.begin(); it2 != d->refs.end(); ++it2 )
    {
        if((*it2).ref_name==name)
        {
            d->refs.remove(it2);
            emit sig_removeAreaName( name );
            return;
        }
    }
}

void Doc::changeAreaSheetName(const TQString & oldName,const TQString & sheetName)
{
  TQValueList<Reference>::Iterator it2;
  for ( it2 = d->refs.begin(); it2 != d->refs.end(); ++it2 )
        {
        if((*it2).sheet_name==oldName)
                   (*it2).sheet_name=sheetName;
        }
}

TQRect Doc::getRectArea(const TQString  &_sheetName)
{
  TQValueList<Reference>::Iterator it2;
  for ( it2 = d->refs.begin(); it2 != d->refs.end(); ++it2 )
        {
        if((*it2).ref_name==_sheetName)
                {
                return (*it2).rect;
                }
        }
  return TQRect(-1,-1,-1,-1);
}

TQDomElement Doc::saveAreaName( TQDomDocument& doc )
{
   TQDomElement element = doc.createElement( "areaname" );
   TQValueList<Reference>::Iterator it2;
   for ( it2 = d->refs.begin(); it2 != d->refs.end(); ++it2 )
   {
        TQDomElement e = doc.createElement("reference");
        TQDomElement tabname = doc.createElement( "tabname" );
        tabname.appendChild( doc.createTextNode( (*it2).sheet_name ) );
        e.appendChild( tabname );

        TQDomElement refname = doc.createElement( "refname" );
        refname.appendChild( doc.createTextNode( (*it2).ref_name ) );
        e.appendChild( refname );

        TQDomElement rect = doc.createElement( "rect" );
        rect.setAttribute( "left-rect", ((*it2).rect).left() );
        rect.setAttribute( "right-rect",((*it2).rect).right() );
        rect.setAttribute( "top-rect", ((*it2).rect).top() );
        rect.setAttribute( "bottom-rect", ((*it2).rect).bottom() );
        e.appendChild( rect );
        element.appendChild(e);
   }
   return element;
}

void Doc::loadOasisCellValidation( const TQDomElement&body )
{
    TQDomNode validation = KoDom::namedItemNS( body, KoXmlNS::table, "content-validations" );
    kdDebug()<<"void Doc::loadOasisCellValidation( const TQDomElement&body ) \n";
    kdDebug()<<"validation.isNull ? "<<validation.isNull()<<endl;
    if ( !validation.isNull() )
    {
        TQDomNode n = validation.firstChild();
        for( ; !n.isNull(); n = n.nextSibling() )
        {
            if ( n.isElement() )
            {
                TQDomElement element = n.toElement();
                //kdDebug()<<" loadOasisCellValidation element.tagName() :"<<element.tagName()<<endl;
                if ( element.tagName() ==  "content-validation" && element.namespaceURI() == KoXmlNS::table ) {
                    d->m_loadingInfo->appendValidation(element.attributeNS( KoXmlNS::table, "name", TQString() ), element );
                    kdDebug()<<" validation found :"<<element.attributeNS( KoXmlNS::table, "name", TQString() )<<endl;
                }
                else {
                    kdDebug()<<" Tag not recognize :"<<element.tagName()<<endl;
                }
            }
        }
    }
}

void Doc::saveOasisAreaName( KoXmlWriter & xmlWriter )
{
    if ( listArea().count()>0 )
    {
        xmlWriter.startElement( "table:named-expressions" );
        TQValueList<Reference>::Iterator it;
        for ( it = d->refs.begin(); it != d->refs.end(); ++it )
        {
            xmlWriter.startElement( "table:named-range" );

            xmlWriter.addAttribute( "table:name", ( *it ).ref_name );
            xmlWriter.addAttribute( "table:base-cell-address", convertRefToBase( ( *it ).sheet_name, ( *it ).rect ) );
            xmlWriter.addAttribute( "table:cell-range-address", convertRefToRange( ( *it ).sheet_name, ( *it ).rect ) );

            xmlWriter.endElement();
        }
        xmlWriter.endElement();
    }
}

void Doc::loadOasisAreaName( const TQDomElement& body )
{
    kdDebug()<<"void Doc::loadOasisAreaName( const TQDomElement& body ) \n";
    TQDomNode namedAreas = KoDom::namedItemNS( body, KoXmlNS::table, "named-expressions" );
    if ( !namedAreas.isNull() )
    {
        kdDebug()<<" area name exist \n";
        TQDomNode area = namedAreas.firstChild();
        while ( !area.isNull() )
        {
            TQDomElement e = area.toElement();

            if ( e.localName() == "named-range" )
            {
                if ( !e.hasAttributeNS( KoXmlNS::table, "name" ) || !e.hasAttributeNS( KoXmlNS::table, "cell-range-address" ) )
                {
                    kdDebug() << "Reading in named area failed" << endl;
                    area = area.nextSibling();
                    continue;
                }

                // TODO: what is: sheet:base-cell-address
                TQString name  = e.attributeNS( KoXmlNS::table, "name", TQString() );
                TQString range = e.attributeNS( KoXmlNS::table, "cell-range-address", TQString() );
                kdDebug()<<"area name : "<<name<<" range :"<<range<<endl;
                d->m_loadingInfo->addWordInAreaList( name );
                kdDebug() << "Reading in named area, name: " << name << ", area: " << range << endl;

                range = Oasis::decodeFormula( range );

                if ( range.find( ':' ) == -1 )
                {
                    Point p( range );

                    int n = range.find( '!' );
                    if ( n > 0 )
                        range = range + ":" + range.right( range.length() - n - 1);

                    kdDebug() << "=> Area: " << range << endl;
                }

                if ( range.contains( '!' ) && range[0] == '$' )
                {
                    // cut absolute sheet indicator
                    range.remove( 0, 1 );
                }

                Range p( range );

                addAreaName( p.range(), name, p.sheetName() );
                kdDebug() << "Area range: " << p.toString() << endl;
            }
            else if ( e.localName() == "named-expression" )
            {
                kdDebug() << "Named expression found." << endl;
                // TODO
            }

            area = area.nextSibling();
        }
    }
}

void Doc::loadAreaName( const TQDomElement& element )
{
  TQDomElement tmp=element.firstChild().toElement();
  for( ; !tmp.isNull(); tmp=tmp.nextSibling().toElement()  )
  {
    if ( tmp.tagName() == "reference" )
    {
        TQString tabname;
        TQString refname;
        int left=0;
        int right=0;
        int top=0;
        int bottom=0;
        TQDomElement sheetName = tmp.namedItem( "tabname" ).toElement();
        if ( !sheetName.isNull() )
        {
          tabname=sheetName.text();
        }
        TQDomElement referenceName = tmp.namedItem( "refname" ).toElement();
        if ( !referenceName.isNull() )
        {
          refname=referenceName.text();
        }
        TQDomElement rect =tmp.namedItem( "rect" ).toElement();
        if (!rect.isNull())
        {
          bool ok;
          if ( rect.hasAttribute( "left-rect" ) )
            left=rect.attribute("left-rect").toInt( &ok );
          if ( rect.hasAttribute( "right-rect" ) )
            right=rect.attribute("right-rect").toInt( &ok );
          if ( rect.hasAttribute( "top-rect" ) )
            top=rect.attribute("top-rect").toInt( &ok );
          if ( rect.hasAttribute( "bottom-rect" ) )
            bottom=rect.attribute("bottom-rect").toInt( &ok );
        }
        TQRect _rect;
        _rect.setCoords(left,top,right,bottom);
        addAreaName(_rect,refname,tabname);
    }
  }
}

void Doc::addStringCompletion(const TQString &stringCompletion)
{
  if ( d->listCompletion.items().contains(stringCompletion) == 0 )
    d->listCompletion.addItem( stringCompletion );
}

void Doc::refreshInterface()
{
  emit sig_refreshView();
}

void Doc::refreshLocale()
{
    emit sig_refreshLocale();
}


void Doc::emitBeginOperation(bool waitCursor)
{
    //If an emitBeginOperation occurs with waitCursor enabled, then the waiting cursor is set
    //until all operations have been completed.
    //
    //The reason being that any operations started before the first one with waitCursor set
    //are expected to be completed in a short time anyway.
    TQCursor* activeOverride = static_cast<TQCursor*>(TQApplication::overrideCursor());

    if (waitCursor && ( (!activeOverride) || (activeOverride->shape() != TQt::waitCursor.shape()) )  )
    {
        TQApplication::setOverrideCursor(TQt::waitCursor);
    }

//    /* just duplicate the current cursor on the stack, then */
//  else if (TQApplication::overrideCursor() != NULL)
//    {
//        TQApplication::setOverrideCursor(TQApplication::overrideCursor()->shape());
//    }

    KoDocument::emitBeginOperation();
    d->delayCalculation = true;
    d->numOperations++;
}

void Doc::emitBeginOperation(void)
{
  emitBeginOperation(true);
}


void Doc::emitEndOperation()
{
   d->numOperations--;

   if (d->numOperations <= 0)
   {
     d->numOperations = 0;
     d->delayCalculation = false;
   }

   KoDocument::emitEndOperation();

   if (d->numOperations == 0)
   {
   	TQApplication::restoreOverrideCursor();

     /* do this after the parent class emitEndOperation because that allows updates
        on the view again
     */
     paintUpdates();
   }
}

void Doc::emitEndOperation( const Region& /*region*/ )
{
  d->numOperations--;

  if ( d->numOperations > 0 || !d->activeSheet )
  {
    KoDocument::emitEndOperation();
    return;
  }

  d->numOperations = 0;
  d->delayCalculation = false;

  KoDocument::emitEndOperation();

  TQApplication::restoreOverrideCursor();

    /* do this after the parent class emitEndOperation because that allows updates
    on the view again
    */
  paintUpdates();
}

bool Doc::delayCalculation() const
{
   return d->delayCalculation;
}

void Doc::updateBorderButton()
{
    TQPtrListIterator<KoView> it( views() );
    for (; it.current(); ++it )
      static_cast<View *>( it.current() )->updateBorderButton();
}

void Doc::insertSheet( Sheet * sheet )
{
    TQPtrListIterator<KoView> it( views() );
    for (; it.current(); ++it )
  ((View*)it.current())->insertSheet( sheet );
}

void Doc::takeSheet( Sheet * sheet )
{
    TQPtrListIterator<KoView> it( views() );
    for (; it.current(); ++it )
  ((View*)it.current())->removeSheet( sheet );
}

void Doc::addIgnoreWordAll( const TQString & word)
{
    if( d->spellListIgnoreAll.findIndex( word )==-1)
        d->spellListIgnoreAll.append( word );
}

void Doc::clearIgnoreWordAll( )
{
    d->spellListIgnoreAll.clear();
}

void Doc::setDisplaySheet(Sheet *_sheet )
{
    d->activeSheet = _sheet;
}

KSPLoadingInfo * Doc::loadingInfo() const
{
    return d->m_loadingInfo;
}

void Doc::deleteLoadingInfo()
{
    delete d->m_loadingInfo;
    d->m_loadingInfo = 0;
}

Sheet * Doc::displaySheet() const
{
    return d->activeSheet;
}

void Doc::addView( KoView *_view )
{
    KoDocument::addView( _view );
    TQPtrListIterator<KoView> it( views() );
    for (; it.current(); ++it )
  ((View*)it.current())->closeEditor();
}

void Doc::addDamage( Damage* damage )
{
    d->damages.append( damage );

    if( d->damages.count() == 1 )
        TQTimer::singleShot( 0, this, TQ_SLOT( flushDamages() ) );
}

void Doc::flushDamages()
{
    emit damagesFlushed( d->damages );
    TQValueList<Damage*>::Iterator it;
    for( it = d->damages.begin(); it != d->damages.end(); ++it )
      delete *it;
    d->damages.clear();
}

void Doc::loadConfigFromFile()
{
    d->configLoadFromFile = true;
}

bool Doc::configLoadFromFile() const
{
    return d->configLoadFromFile;
}


void Doc::insertObject( EmbeddedObject * obj )
{
  switch ( obj->getType() )
  {
    case OBJECT_KOFFICE_PART: case OBJECT_CHART:
    {
      KoDocument::insertChild( dynamic_cast<EmbeddedKOfficeObject*>(obj)->embeddedObject() );
      break;
    }
    default:
      ;
  }
  d->m_embeddedObjects.append( obj );
}

TQPtrList<EmbeddedObject>& Doc::embeddedObjects()
{
    return d->m_embeddedObjects;
}

KoPictureCollection *Doc::pictureCollection()
{
  return &d->m_pictureCollection;
}

void Doc::repaint( const TQRect& rect )
{
  TQRect r;
  TQPtrListIterator<KoView> it( views() );
  for( ; it.current(); ++it )
  {
    r = rect;
    Canvas* canvas = ((View*)it.current())->canvasWidget();
    r.moveTopLeft( TQPoint( r.x() - (int) canvas->xOffset(),
                           r.y() - (int) canvas->yOffset() ) );
    canvas->update( r );
  }
}

void Doc::repaint( EmbeddedObject *obj )
{
  TQPtrListIterator<KoView> it( views() );
  for( ; it.current(); ++it )
  {
    Canvas* canvas = ((View*)it.current())->canvasWidget();
    if ( obj->sheet() == canvas->activeSheet() )
        canvas->repaintObject( obj );
  }
}

void Doc::repaint( const KoRect& rect )
{
  TQRect r;
  TQPtrListIterator<KoView> it( views() );
  for( ; it.current(); ++it )
  {
    Canvas* canvas = ((View*)it.current())->canvasWidget();

    r = zoomRect( rect );
    r.moveBy( (int)( -canvas->xOffset()*zoomedResolutionX() ) ,
                        (int)( -canvas->yOffset() *zoomedResolutionY()) );
    canvas->update( r );
  }
}

void Doc::addShell( KoMainWindow *shell )
{
  connect( shell, TQ_SIGNAL( documentSaved() ), d->commandHistory, TQ_SLOT( documentSaved() ) );
  KoDocument::addShell( shell );
}

int Doc::undoRedoLimit() const
{
  return d->commandHistory->undoLimit();
}

void Doc::setUndoRedoLimit(int val)
{
  d->commandHistory->setUndoLimit(val);
  d->commandHistory->setRedoLimit(val);
}

void Doc::insertPixmapKey( KoPictureKey key )
{
    if ( !d->usedPictures.contains( key ) )
        d->usedPictures.append( key );
}

void Doc::makeUsedPixmapList()
{
    d->usedPictures.clear();
    TQPtrListIterator<EmbeddedObject> it( d->m_embeddedObjects );
    for ( ; it.current() ; ++it )
    {
        if( it.current()->getType() == OBJECT_PICTURE && ( d->m_savingWholeDocument || it.current()->isSelected() ) )
            insertPixmapKey( static_cast<EmbeddedPictureObject*>( it.current() )->getKey() );
    }
}

bool Doc::savingWholeDocument()
{
    return d->m_savingWholeDocument;
}

#include "kspread_doc.moc"