summaryrefslogtreecommitdiffstats
path: root/kchart/kchart_part.cc
blob: f0fda2f0798d78ffeecabd140871a393327f9190 (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
/**
 *
 * Kalle Dalheimer <kalle@kde.org>
 */

#include <float.h> // For basic data types characteristics.

// For debugging
#include <iostream>
using std::cout;
using std::cerr;

#include "kchart_part.h"
#include "kchart_view.h"
#include "kchart_factory.h"
#include "kchartWizard.h"
#include "kchart_params.h"
#include "kdchart/KDChart.h"
#include "kdchart/KDChartTable.h"

#include <KoTemplateChooseDia.h>
#include <KoDom.h>
#include <KoXmlNS.h>
#include <KoXmlWriter.h>
#include <KoOasisStore.h>
#include <KoOasisLoadingContext.h>

#include <kstandarddirs.h>
#include <kglobal.h>
#include <kdebug.h>

#include <tqdom.h>
#include <tqtextstream.h>
#include <tqbuffer.h>
#include <tqpainter.h>

using namespace std;

// Some hardcoded data for a chart

/* ----- set some data ----- */
// float   a[6]  = { 0.5, 0.09, 0.6, 0.85, 0.0, 0.90 },
// b[6]  = { 1.9, 1.3,  0.6, 0.75, 0.1, -2.0 };
/* ----- X labels ----- */
// char    *t[6] = { "Chicago", "New York", "L.A.", "Atlanta", "Paris, MD\n(USA) ", "London" };
/* ----- data set colors (RGB) ----- */
// TQColor   sc[2]    = { TQColor( 255, 128, 128 ), TQColor( 128, 128, 255 ) };


namespace KChart
{

KChartPart::KChartPart( TQWidget *parentWidget, const char *widgetName,
			TQObject* parent, const char* name,
			bool singleViewMode )
  : KoChart::Part( parentWidget, widgetName, parent, name, singleViewMode ),
    m_params( 0 ),
    m_parentWidget( parentWidget ),
    m_rowLabels(), m_colLabels()
{
    kdDebug(35001) << "Constructor started!" << endl;

    setInstance( KChartFactory::global(), false );
    setTemplateType( "kchart_template" );

    // Init some members that need it.
    {
	// Create the chart parameters and let the default be a bar chart
	// with 3D looks.
	m_params = new KChartParams( this );
	m_params->setChartType( KChartParams::Bar );
	m_params->setBarChartSubType( KChartParams::BarNormal );
	m_params->setThreeDBars( true );

        //Changed this to use columns rather than rows by default
        //because I believe that this is the more common format for
        //entering data (you can see this looking at the fact that
        //most spreadsheet packages allow far more rows than columns)
        //-- Robert Knight

	// Handle data in columns by default
	m_params->setDataDirection( KChartParams::DataColumns );
    }

    (void)new WizardExt( this );
    m_bCanChangeValue = true;

    // Display parameters
    m_displayData = m_currentData;

    // Set the size to minimal.
    initEmpty();
}


KChartPart::~KChartPart()
{
    //kdDebug(35001) << "Part is going to be destroyed now!!!" << endl;
    delete m_params;
}


// Reimplement KoDocument::initDoc()

bool KChartPart::initDoc(InitDocFlags flags, TQWidget* parentWidget)
{
    // Initialize the parameter set for this chart document
#if 0
    kdDebug(35001) << "================================================================" << endl;
    kdDebug(35001) << "InitDOC: flags = " << flags << endl;
    kdDebug(35001) << "================================================================" << endl;
#endif

    TQString f;

    // Embedded documents are initially created like a normal empty
    // document.  If this is in KSpread or another program where the
    // data is external then the document will be updated later on in
    // the creation process anyway.
    if (flags == KoDocument::InitDocEmbedded) {
	initEmpty();
	return true;
    }

    // If we are supposed to create a new, empty document, then do so.
    if (flags == KoDocument::InitDocEmpty) {
	initEmpty();
	return true;
    }

    KoTemplateChooseDia::ReturnType  ret;
    KoTemplateChooseDia::DialogType  dlgtype;

    // If we must create a new document, then only present templates
    // to the user, otherwise also present existing documents and
    // recent documents.
    if (flags == KoDocument::InitDocFileNew )
	dlgtype = KoTemplateChooseDia::OnlyTemplates;
    else
	dlgtype = KoTemplateChooseDia::Everything;
    ret = KoTemplateChooseDia::choose( KChartFactory::global(), f,
                                       dlgtype, "kchart_template",
				       parentWidget );

    if ( ret == KoTemplateChooseDia::File ) {
	KURL url( f );
	return openURL( url );
    }
    else if ( ret == KoTemplateChooseDia::Empty ) {
	initEmpty();
	return true;
    }
    else if ( ret == KoTemplateChooseDia::Template ) {
		//TODO: Activate this for KOffice 1.5/2.0
// 		if ( f.endsWith("/templates/chart/.source/BarChart.chrt") ) {
// 			generateBarChartTemplate();
// 			return true;
// 		}
        TQFileInfo fileInfo( f );
        TQString fileName( fileInfo.dirPath( true ) + "/" +
            fileInfo.baseName() + ".chrt" );

        resetURL();
        bool ok = loadNativeFormat( fileName );
        if ( !ok )
            showLoadingErrorDialog();
        setEmpty();
        //initConfig();
        return ok;
    }

    return false;
}

void KChartPart::initEmpty()
{
    initNullChart();

    resetURL();
    setEmpty();
}


// This method creates the simplest chart imaginable:
// Data size 1x1, empty, no headers
//
void KChartPart::initNullChart()
{
    // Fill cells with data if there is none.
    //kdDebug(35001) << "Initialize null chart." << endl;

    // Empty data.  Note, we don't use (0,0) or (1,1) for the size
    // here, because otherwise KDChart won't draw anything
    m_currentData.expand(2, 2);
    m_params->setFirstRowAsLabel(false);
    m_params->setFirstColAsLabel(false);

    // Fill column and row labels.
    m_colLabels << TQString("");
    m_rowLabels << TQString("");

    setChartDefaults();

    m_params->setDrawSolidExcessArrows(true);
}


void KChartPart::generateBarChartTemplate()
{
    int  col;
    int  row;

    kdDebug()<<"KChartPart::initTestChart()\n";

    // Fill cells with data if there is none.
    if (m_currentData.rows() == 0) {
        //kdDebug(35001) << "Initialize with some data!!!" << endl;
        m_currentData.expand( 4, 4 );
        m_currentData.setUsedRows( 4 );
        m_currentData.setUsedCols( 4 );
        for (row = 0; row < 4; row++) {
            for (col = 0; col < 4; col++) {
                m_currentData.setCell(row, col,
				      static_cast <double> (row + col));

		// Fill column label, but only on the first iteration.
		if (row == 0) {
		    m_colLabels << i18n("Column %1").tqarg(col + 1);
		}
            }

	    // Fill row label.
	    m_rowLabels << i18n("Row %1").tqarg(row + 1);
	}
    }

    setChartDefaults();
    // FIXME: Should this go into setChartDefaults()?
    m_params->setDrawSolidExcessArrows(true);
}


KoView* KChartPart::createViewInstance( TQWidget* parent, const char* name )
{
    return new KChartView( this, parent, name );
}


// ================================================================
//                              Painting


void KChartPart::paintContent( TQPainter& painter, const TQRect& rect,
			       bool /*transparent*/,
			       double /*zoomX*/, double /*zoomY*/ )
{
    int  numDatasets;

    // If params is 0, initDoc() has not been called.
    Q_ASSERT( m_params != 0 );

    KDChartAxisParams  xAxisParms;
    xAxisParms = m_params->axisParams( KDChartAxisParams::AxisPosBottom );

    // Handle data in rows or columns.
    //
    // This means getting row or column headers from the document and
    // set them as X axis labels or legend according to the current
    // setting.  Also, transpose the data if it should be displayed in
    // columns instead of in rows.


    // Create the displayData table.
    numDatasets = createDisplayData();

    // Create and set the axis labels and legend.
    TQStringList  longLabels;
    TQStringList  shortLabels;
    createLabelsAndLegend(longLabels, shortLabels);

    // Set the x axis labels.
    xAxisParms.setAxisLabelStringLists( &longLabels, &shortLabels );
    m_params->setAxisParams(KDChartAxisParams::AxisPosBottom, xAxisParms);


    // Handle some types or subtypes of charts specially, notably:
    //  - Bar charts with lines in them

    if ( m_params->chartType() == KChartParams::Bar) {
	if ( m_params->barNumLines() > 0 ) {

	    // If this is a bar chart and the user wants a few lines in
	    // it, we need to create an additional chart in the same
	    // drawing area.

	    // Specify that we want to have an additional chart.
	    m_params->setAdditionalChartType( KDChartParams::Line );

	    const int numBarDatasets = numDatasets - m_params->barNumLines();

	    // Assign the datasets to the charts: DataEntry, from, to, chart#
	    m_params->setChartSourceMode( KDChartParams::DataEntry,
					  0, numBarDatasets - 1,
					  0 ); // The bar chart
	    m_params->setChartSourceMode( KDChartParams::DataEntry,
					  numBarDatasets, numDatasets - 1,
					  1 ); // The line chart
	}
	else {
	    // Otherwise we don't want any extra chart.
	    m_params->setAdditionalChartType( KDChartParams::NoType );
	}
    }

    // Ok, we have now created a data set for display, and params with
    // suitable legends and axis labels.  Now start the real painting.

    // Handle transparency.
    // Wrong: this flickers; better do this as part of the double-buffering.
    //if ( !transparent )
    //    painter.eraseRect( rect );

    // ## TODO: support zooming

    // Double-buffering
    if ( m_bufferPixmap.width() < rect.width()
	 || m_bufferPixmap.height() < rect.height() )
    {
    	m_bufferPixmap.resize( rect.size() );
    }

    TQPainter bufferPainter( &m_bufferPixmap );

    // We only need to draw the document rectangle "rect".
    KDChart::paint( &bufferPainter, m_params, &m_displayData, 0, &rect );

    // This is always the empty rect...
    // Shouldn't creating a TQPainter in a paintEvent set up clipping automatically?
    // I thought it did (DF)
    //const TQRect clipRect = painter.clipRegion().boundingRect();
    //painter.drawPixmap( clipRect.topLeft(), m_bufferPixmap, clipRect );

    painter.drawPixmap( 0, 0, m_bufferPixmap );
}


// Create the data table m_displayData from m_currentData, taking into
// account if the first row or line contains headers.  The chart type
// HiLo demands special handling.
//
// Return number of datasets.
//
// Note: While the current KD Chart 1.1.3 version is still expecting data
//       to be in rows, the upcoming KD Chart 2.0 release will be using
//       data in columns instead, to it will be matching KSpread's way.
//       -khz, 2005-11-15
//
// FIXME: Rewrite so that we only copy data when necessary.
//        On the other hand, the next version of KDChart is able to
//        get data directly without storing it into a KDChartData
//        class first, so we might never need to.
//
int  KChartPart::createDisplayData()
{
    int  rowOffset   = 0;
    int  colOffset   = 0;
    int  numDatasets = 0;

    if ( !canChangeValue() ) {
	if ( m_params->firstRowAsLabel() )
	    rowOffset++;
	if ( m_params->firstColAsLabel() )
	    colOffset++;
    }

    // After this sequence, m_DisplayData contains the data in the
    // correct transposition, and the X axis and the legend contain
    // the correct labels.
    TQVariant  value1;
    TQVariant  value2;
    int       prop;
    if (m_params->dataDirection() == KChartParams::DataRows) {
	// Data is handled in rows.  This is the way KDChart works also.

	numDatasets = m_currentData.usedRows() - rowOffset;
	m_displayData.expand( numDatasets,
			      m_currentData.usedCols() - colOffset );

	// Remove the first row and/or col if they are used for headers.
	for (uint row = rowOffset; row < m_currentData.usedRows(); row++) {
	    for (uint col = colOffset; col < m_currentData.usedCols(); col++) {
		if ( m_currentData.cellContent( row, col,
						value1, value2, prop ) ) {
		    m_displayData.setCell(row - rowOffset, col - colOffset,
					  value1, value2);
		    m_displayData.setProp(row - rowOffset, col - colOffset,
					  prop);
                }
	    }
	}
    }
    else {
	// Data is handled in columns.  We will have to transpose
	// everything since KDChart wants its data in rows.

	// Resize displayData so that the transposed data has room.
	numDatasets = m_currentData.usedCols() - colOffset;
	m_displayData.expand( numDatasets,
			      m_currentData.usedRows() - rowOffset );

	// Copy data and transpose it.
	for (uint row = colOffset; row < m_currentData.usedCols(); row++) {
	    for (uint col = rowOffset; col < m_currentData.usedRows(); col++) {
                if ( m_currentData.cellContent( col, row,
						value1, value2, prop ) ) {
		    m_displayData.setCell(row - colOffset, col - rowOffset,
					  value1, value2);
		    m_displayData.setProp(row - colOffset, col - rowOffset,
					  prop);
                }
	    }
	}
    }

    // If this is a HiLo chart, we need to manually create the correct
    // values.  This is not done by KDChart.
    //
    // Here we don't need to transpose, since we can start from the
    // newly generated displayData.
    if (m_params->chartType() == KChartParams::HiLo) {
	KDChartTableData  tmpData = m_displayData;

	// Calculate the min, max, open and close values for each row.
	m_displayData.expand(tmpData.usedRows(), 4);
	for (uint row = 0; row < tmpData.usedRows(); row++) {
	    double  minVal   = DBL_MAX;
	    double  maxVal   = -DBL_MAX;

	    // Calculate min and max for this row.
	    //
	    // Note that we have already taken care of different data
	    // directions above.
	    for (uint col = 0; col < tmpData.usedCols(); col++) {
		double  data = tmpData.cellVal(row, col).toDouble();

		if (data < minVal)
		    minVal = data;
		if (data > maxVal)
		    maxVal = data;
	    }
	    m_displayData.setCell(row, 0, minVal); // min
	    m_displayData.setCell(row, 1, maxVal); // max
	    m_displayData.setCell(row, 2, tmpData.cellVal(row, 0).toDouble());   // open
	    m_displayData.setCell(row, 3,                          // close
				  tmpData.cellVal(row, tmpData.usedCols() - 1).toDouble());
	}
    }

    return numDatasets;
}


void KChartPart::createLabelsAndLegend( TQStringList  &longLabels,
					TQStringList  &shortLabels )
{
    longLabels.clear();
    shortLabels.clear();

    const uint dataColumnCount  = m_currentData.cols();
    const uint dataRowCount     = m_currentData.rows();
    const uint columnLabelCount = m_colLabels.count();
    const uint rowLabelCount    = m_rowLabels.count();

    // Handle HiLo charts separately.
    if (m_params->chartType() == KChartParams::HiLo) {

      // FIXME: In a HiLo chart, the Legend should be the same as the
      //        labels on the X Axis.  Should we disable one of them?

	// Set the correct X axis labels and legend.
	longLabels.clear();
	shortLabels.clear();
	if (m_params->dataDirection() == KChartParams::DataRows) {

	    // If data are in rows, then the X axis labels should be
	    // taken from the row headers.
	    for ( uint row = 0; row < dataRowCount ; row++ ) {

                TQString label = (row < rowLabelCount) ? m_rowLabels[row] : TQString();

                longLabels  << label;
		shortLabels << label.left( 3 );
	    }
	}
	else {
	    // If data are in columns, then the X axis labels should
	    // be taken from the column headers.
	    for ( uint col = 0; col < dataColumnCount; col++ ) {

                TQString label = (col < columnLabelCount) ? m_colLabels[col] : TQString();

                longLabels  << m_colLabels[col];
		shortLabels << m_colLabels[col].left( 3 );
	    }
	}
    }
    else if (m_params->dataDirection() == KChartParams::DataRows) {
	// Data is handled in rows.  This is the way KDChart works also.

	// Set X axis labels from column headers.
	for ( uint col = 0; col < dataColumnCount; col++ ) {

            TQString label = (col < columnLabelCount) ? m_colLabels[col] : TQString();

            longLabels  << label;
	    shortLabels << label.left( 3 );
	}

	// Set legend from row headers.
        for ( uint row = 0; row < dataRowCount; row++ ) {
            TQString label = (row < rowLabelCount) ? m_rowLabels[row] : TQString();

            m_params->setLegendText( row, label );
        }
    }
    else {
	// Data is handled in columns.

	// Set X axis labels from row headers.
	for ( uint row = 0; row < dataRowCount; row++ ) {

            TQString label = (row < rowLabelCount) ? m_rowLabels[row] : TQString();

            longLabels  << label;
	    shortLabels << label.left( 3 );
	}

	// Set legend from column headers.
        for ( uint col = 0; col < dataColumnCount ; col++ ) {
            TQString label = (col < columnLabelCount) ? m_colLabels[col] : TQString();

            m_params->setLegendText( col, label );
        }
    }
}



// ================================================================


void KChartPart::analyzeHeaders()
{
#if 0
    analyzeHeaders( m_currentData );
#else
    doSetData( m_currentData,
	       m_params->firstRowAsLabel(), m_params->firstColAsLabel());
#endif
}


// This function sets the data from an external source.  It is called,
// for instance, when the chart is initialized from a spreadsheet in
// KSpread.
//
void KChartPart::analyzeHeaders( const KDChartTableData& data )
{
    // FIXME(khz): replace this when automatic string detection works in KDChart
    // Does the top/left cell contain a string?
    bool isStringTopLeft = (data.cellVal( 0, 0 ).type() == TQVariant::String);

    // Does the first row (without first cell) contain only strings?
    bool isStringFirstRow = true;
    for ( uint col = 1; isStringFirstRow && col < data.cols(); col++ ) {
        isStringFirstRow = (data.cellVal( 0, col ).type() == TQVariant::String);
    }

    // Just in case, we only have 1 row, we never use it for label text.
    // This prevents a crash.
    //
    // FIXME: Wonder if this is still true for KDChart 1.1.3 / iw
    //        Disabling...
#if 1
    if ( data.rows() == 1 )
        isStringFirstRow = false;
#endif

    // Does the first column (without first cell) contain only strings?
    bool isStringFirstCol = true;
    for ( uint row = 1; isStringFirstCol && row < data.rows(); row++ ) {
        isStringFirstCol = (data.cellVal( row, 0 ).type() == TQVariant::String);
    }

    // Just in case, we only have 1 column, we never use it for axis
    // label text => prevents crash.
#if 1
    if ( data.cols() == 1 )
        isStringFirstRow = FALSE;
#endif

    bool hasColHeader = false;
    bool hasRowHeader = false;

    // Let's check if we have a full axis label text column
    if ( isStringFirstCol && isStringTopLeft
	 || isStringFirstCol && isStringFirstRow )
        hasColHeader = true;

    // Let's check if we have a full label text row.
    if ( isStringFirstRow && isStringTopLeft
	 || isStringFirstCol && isStringFirstRow )
        hasRowHeader = true;

    m_params->setFirstRowAsLabel( hasRowHeader );
    m_params->setFirstColAsLabel( hasColHeader );

    doSetData(data, hasRowHeader, hasColHeader);
}



void KChartPart::doSetData( const KDChartTableData&  data,
			    bool  firstRowHeader,
			    bool  firstColHeader )
{
    uint  rowStart = 0;
    uint  colStart = 0;
    uint  col;
    uint  row;

    // From this point, we know that the labels and legend are going
    // to be taken from the data if firstRowHeader or firstColheader
    // is true.

    if (firstRowHeader)
        rowStart = 1;
    if (firstColHeader)
        colStart = 1;

    // Generate m_rowlabels from the column headers if applicable.
    m_rowLabels.clear();
    if ( firstColHeader ) {
	for( row = rowStart; row < data.rows(); row++ ) {
	    m_rowLabels << data.cellVal( row, 0 ).toString();
	}
    }
    else {
	for( row = rowStart; row < data.rows(); row++ )
	    m_rowLabels << "";

	// FIXME: Check what this does, and if we don't have to check
	//        the data order (rows / cols).
	m_params->setLegendSource( KDChartParams::LegendAutomatic );
    }

    // Generate X labels from the row headers if applicable
    m_colLabels.clear();
    if ( firstRowHeader ) {
        for( col = colStart; col < data.cols(); col++ ) {
	    m_colLabels << data.cellVal( 0, col ).toString();
	}
    }
    else {
	for( col = colStart; col < data.cols(); col++ )
	    m_colLabels << "";
    }

    // Doesn't hurt if data == m_currentData, but necessary if not.
    m_currentData = data;

    //setChartDefaults();

    emit docChanged();
}


void KChartPart::resizeData( int rows, int cols )
{
    m_currentData.expand( rows, cols );
    m_currentData.setUsedRows( rows );
    m_currentData.setUsedCols( cols );
}


void KChartPart::setCellData( int row, int column, const TQVariant &val)
{
    m_currentData.setCell( row, column, val );
}


bool KChartPart::showWizard( TQString &dataArea )
{
    KChartWizard  *wizard = new KChartWizard( this, m_parentWidget, "wizard" );

    connect( wizard, TQT_SIGNAL(finished()), this, TQT_SLOT(slotModified()) );

    wizard->setDataArea( dataArea );

    bool  ret = wizard->exec();

    delete wizard;
    return ret;
}


void KChartPart::initLabelAndLegend()
{
    // Labels and legends are automatically initialized to reasonable
    // default values in KDChart
}


// Set up some values for the chart Axis, that are not well chosen by
// default by KDChart.
//

void KChartPart::setChartDefaults()
{
  //
  // Settings for the Y axis.
  //
  KDChartAxisParams  yAxis;
  yAxis = m_params->axisParams( KDChartAxisParams::AxisPosLeft );

  // decimal symbol and thousands separator
  yAxis.setAxisLabelsRadix( KGlobal::locale()->decimalSymbol(),
			    KGlobal::locale()->thousandsSeparator() );

  m_params->setAxisParams( KDChartAxisParams::AxisPosLeft, yAxis );

  //
  // Settings for the X axis.
  //
  KDChartAxisParams  xAxis;
  xAxis = m_params->axisParams( KDChartAxisParams::AxisPosBottom );

  // These two shouldn't be necessary to set.
  xAxis.setAxisFirstLabelText();
  xAxis.setAxisLastLabelText();

  m_params->setAxisParams( KDChartAxisParams::AxisPosBottom, xAxis );

  // Other parameters for various things.
  m_params->setLineColor();

  // Setting the background layer.
  KDFrame frame;
  frame.setBackground( TQBrush( TQColor( 230, 222, 222 ) ) );
  m_params->setFrame( KDChartEnums::AreaInnermost, frame, 0, 0, 0, 0 );
}


// ================================================================
//                     Loading and Storing


// ----------------------------------------------------------------
//                 Save and Load program configuration



void KChartPart::loadConfig( KConfig *conf )
{
    conf->setGroup("ChartParameters");

    // TODO: the fonts
    // PENDING(kalle) Put the applicable ones of these back in
    //   TQFont tempfont;
    //   tempfont = conf->readFontEntry("titlefont", &titlefont);
    //   setTitleFont(tempfont);
    //   tempfont = conf->readFontEntry("ytitlefont", &ytitlefont);
    //   setYTitleFont(tempfont);
    //   tempfont = conf->readFontEntry("xtitlefont", &xtitlefont);
    //   setXTitleFont(tempfont);
    //   tempfont = conf->readFontEntry("yaxisfont", &yaxisfont);
    //   setYAxisFont(tempfont);
    //   tempfont = conf->readFontEntry("xaxisfont", &xaxisfont);
    //   setXAxisFont(tempfont);
    //   tempfont = conf->readFontEntry("labelfont", &labelfont);
    //   setLabelFont(tempfont);
    //   tempfont = conf->readFontEntry("annotationfont", &annotationfont);
    //   setAnnotationFont(tempfont);

    //   ylabel_fmt = conf->readEntry("ylabel_fmt", ylabel_fmt );
    //   ylabel2_fmt = conf->readEntry("ylabel2_fmt", ylabel2_fmt);
    //   xlabel_spacing = conf->readNumEntry("xlabel_spacing");
    //   ylabel_density = conf->readNumEntry("ylabel_density", ylabel_density);
    //   requested_ymin = conf->readDoubleNumEntry("requested_ymin", requested_ymin);
    //   requested_ymax = conf->readDoubleNumEntry("requested_ymax", requested_ymax );
    //   requested_yinterval = conf->readDoubleNumEntry("requested_yinterval",
    // 					   requested_yinterval);
    //   shelf = conf->readBoolEntry("shelf", shelf);
    //   grid = conf->readBoolEntry("grid", grid);
    //   xaxis = conf->readBoolEntry("xaxis", xaxis);
    //   yaxis = conf->readBoolEntry("yaxis", yaxis);
    //   yaxis2 = conf->readBoolEntry("yaxis2", yaxis);
    //   llabel = conf->readBoolEntry("llabel", llabel);
    //   yval_style = conf->readNumEntry("yval_style", yval_style);
    //   stack_type = (KChartStackType)conf->readNumEntry("stack_type", stack_type);
    m_params->setLineMarker(conf->readBoolEntry("lineMarker",
						m_params->lineMarker()));
    m_params->setThreeDBarDepth( conf->readDoubleNumEntry("_3d_depth",
							  m_params->threeDBarDepth() ) );
    m_params->setThreeDBarAngle( conf->readNumEntry( "_3d_angle",
						     m_params->threeDBarAngle() ) );

    KDChartAxisParams  leftparams;
    leftparams = m_params->axisParams( KDChartAxisParams::AxisPosLeft );
    KDChartAxisParams  rightparams;
    rightparams = m_params->axisParams( KDChartAxisParams::AxisPosRight );
    KDChartAxisParams  bottomparams;
    bottomparams = m_params->axisParams( KDChartAxisParams::AxisPosBottom );

    bottomparams.setAxisLineColor( conf->readColorEntry( "XTitleColor", 0 ) );
    leftparams.setAxisLineColor( conf->readColorEntry( "YTitleColor", 0 ) );
    rightparams.setAxisLineColor( conf->readColorEntry( "YTitle2Color", 0 ) );
    bottomparams.setAxisLabelsColor( conf->readColorEntry( "XLabelColor", 0 ) );
    leftparams.setAxisLabelsColor( conf->readColorEntry( "YLabelColor", 0 ) );
    rightparams.setAxisLabelsColor( conf->readColorEntry( "YLabel2Color", 0 ) );
    leftparams.setAxisGridColor( conf->readColorEntry( "GridColor", 0 ) );
    m_params->setOutlineDataColor( conf->readColorEntry( "LineColor", 0 ) );
    m_params->setAxisParams( KDChartAxisParams::AxisPosLeft,
                            leftparams );
    m_params->setAxisParams( KDChartAxisParams::AxisPosRight,
                            rightparams );
    m_params->setAxisParams( KDChartAxisParams::AxisPosBottom,
                            bottomparams );

    //   hlc_style = (KChartHLCStyle)conf->readNumEntry("hlc_style", hlc_style);
    //   hlc_cap_width = conf->readNumEntry("hlc_cap_width", hlc_cap_width);
    //   // TODO: Annotation font
    //   num_scatter_pts = conf->readNumEntry("num_scatter_pts", num_scatter_pts);
    //   // TODO: Scatter type
    //   thumbnail = conf->readBoolEntry("thumbnail", thumbnail);
    //   thumblabel = conf->readEntry("thumblabel", thumblabel);
    //   border = conf->readBoolEntry("border", border);
    //   BGColor = conf->readColorEntry("BGColor", &BGColor);
    //   PlotColor = conf->readColorEntry("PlotColor", &PlotColor);
    //   VolColor = conf->readColorEntry("VolColor", &VolColor);
    //   EdgeColor = conf->readColorEntry("EdgeColor", &EdgeColor);
    //   loadColorArray(conf, &SetColor, "SetColor");
    //   loadColorArray(conf, &ExtColor, "ExtColor");
    //   loadColorArray(conf, &ExtVolColor, "ExtVolColor");
    //   transparent_bg = conf->readBoolEntry("transparent_bg", transparent_bg);
    //   // TODO: explode, missing
    //   percent_labels = (KChartPercentType)conf->readNumEntry("percent_labels",
    // 							 percent_labels);
    //   label_dist = conf->readNumEntry("label_dist", label_dist);
    //   label_line = conf->readBoolEntry("label_line", label_line);
    m_params->setChartType( (KChartParams::ChartType)conf->readNumEntry( "type", m_params->chartType() ) );
    //   other_threshold = conf->readNumEntry("other_threshold", other_threshold);

    //   backgroundPixmapName = conf->readPathEntry( "backgroundPixmapName" );
    //   if( !backgroundPixmapName.isNull() ) {
    //     backgroundPixmap.load( locate( "wallpaper", backgroundPixmapName ));
    //     backgroundPixmapIsDirty = true;
    //   } else
    //     backgroundPixmapIsDirty = false;
    //   backgroundPixmapScaled = conf->readBoolEntry( "backgroundPixmapScaled", true );
    //   backgroundPixmapCentered = conf->readBoolEntry( "backgroundPixmapCentered", true );
    //   backgroundPixmapIntensity = conf->readDoubleNumEntry( "backgroundPixmapIntensity", 0.25 );
}


void KChartPart::defaultConfig(  )
{
    delete m_params;
    m_params = new KChartParams( this );
    setChartDefaults();
}


void KChartPart::saveConfig( KConfig *conf )
{
    conf->setGroup("ChartParameters");

    // PENDING(kalle) Put some of these back in
    // the fonts
    //   conf->writeEntry("titlefont", titlefont);
    //   conf->writeEntry("ytitlefont", ytitlefont);
    //   conf->writeEntry("xtitlefont", xtitlefont);
    //   conf->writeEntry("yaxisfont", yaxisfont);
    //   conf->writeEntry("xaxisfont", xaxisfont);
    //   conf->writeEntry("labelfont", labelfont);

    //   conf->writeEntry("ylabel_fmt", ylabel_fmt);
    //   conf->writeEntry("ylabel2_fmt", ylabel2_fmt);
    //   conf->writeEntry("xlabel_spacing", xlabel_spacing);
    //   conf->writeEntry("ylabel_density", ylabel_density);
    //   conf->writeEntry("requested_ymin", requested_ymin);
    //   conf->writeEntry("requested_ymax", requested_ymax);
    //   conf->writeEntry("requested_yinterval", requested_yinterval);

    //   conf->writeEntry("shelf", shelf);
    //   conf->writeEntry("grid", grid );
    //   conf->writeEntry("xaxis", xaxis);
    //   conf->writeEntry("yaxis", yaxis);
    //   conf->writeEntry("yaxis2", yaxis2);
    //   conf->writeEntry("llabel", llabel);
    //   conf->writeEntry("yval_style", yval_style );
    //   conf->writeEntry("stack_type", (int)stack_type);

    conf->writeEntry( "_3d_depth", m_params->threeDBarDepth() );
    conf->writeEntry( "_3d_angle", m_params->threeDBarAngle() );

    KDChartAxisParams leftparams;
    leftparams   = m_params->axisParams( KDChartAxisParams::AxisPosLeft );
    KDChartAxisParams rightparams;
    rightparams  = m_params->axisParams( KDChartAxisParams::AxisPosRight );
    KDChartAxisParams bottomparams;
    bottomparams = m_params->axisParams( KDChartAxisParams::AxisPosBottom );
    conf->writeEntry( "LineColor",    m_params->outlineDataColor() );
    conf->writeEntry( "XTitleColor",  bottomparams.axisLineColor() );
    conf->writeEntry( "YTitleColor",  leftparams.axisLineColor() );
    conf->writeEntry( "YTitle2Color", rightparams.axisLineColor() );
    conf->writeEntry( "XLabelColor",  bottomparams.axisLabelsColor() );
    conf->writeEntry( "YLabelColor",  leftparams.axisLabelsColor() );
    conf->writeEntry( "YLabel2Color", rightparams.axisLabelsColor() );
    conf->writeEntry( "GridColor",    leftparams.axisGridColor() );

    //   conf->writeEntry("hlc_style", (int)hlc_style);
    //   conf->writeEntry("hlc_cap_width", hlc_cap_width );
    //   // TODO: Annotation type!!!
    //   conf->writeEntry("annotationfont", annotationfont);
    //   conf->writeEntry("num_scatter_pts", num_scatter_pts);
    //   // TODO: Scatter type!!!
    //   conf->writeEntry("thumbnail", thumbnail);
    //   conf->writeEntry("thumblabel", thumblabel);
    //   conf->writeEntry("thumbval", thumbval);
    //   conf->writeEntry("border", border);
    //   conf->writeEntry("BGColor", BGColor);
    //   conf->writeEntry("PlotColor", PlotColor);
    //   conf->writeEntry("VolColor", VolColor);
    //   conf->writeEntry("EdgeColor", EdgeColor);
    //   saveColorArray(conf, &SetColor, "SetColor");
    //   saveColorArray(conf, &ExtColor, "ExtColor");
    //   saveColorArray(conf, &ExtVolColor, "ExtVolColor");


    //   conf->writeEntry("transparent_bg", transparent_bg);
    //   // TODO: explode, missing
    //   conf->writeEntry("percent_labels",(int) percent_labels );
    //   conf->writeEntry("label_dist", label_dist);
    //   conf->writeEntry("label_line", label_line);
    conf->writeEntry( "type", (int) m_params->chartType() );
    //   conf->writeEntry("other_threshold", other_threshold);

    // background pixmap stuff
    //   if( !backgroundPixmapName.isNull() )
    // 	conf->writePathEntry( "backgroundPixmapName", backgroundPixmapName );
    //   conf->writeEntry( "backgroundPixmapIsDirty", backgroundPixmapIsDirty );
    //   conf->writeEntry( "backgroundPixmapScaled", backgroundPixmapScaled );
    //   conf->writeEntry( "backgroundPixmapCentered", backgroundPixmapCentered );
    //   conf->writeEntry( "backgroundPixmapIntensity", backgroundPixmapIntensity );
    conf->writeEntry( "lineMarker", (int) m_params->lineMarker());
}


// ----------------------------------------------------------------
//              Save and Load OpenDocument file format


bool KChartPart::loadOasis( const TQDomDocument& doc,
			    KoOasisStyles&      oasisStyles,
			    const TQDomDocument& /*settings*/,
			    KoStore            *store )
{
    kdDebug(35001) << "kchart loadOasis called" << endl;

    // Set some sensible defaults.
    setChartDefaults();

    TQDomElement  content = doc.documentElement();
    TQDomElement  bodyElem ( KoDom::namedItemNS( content,
						KoXmlNS::office, "body" ) );
    if ( bodyElem.isNull() ) {
        kdError(32001) << "No office:body found!" << endl;
        setErrorMessage( i18n( "Invalid OASIS OpenDocument file. No office:body tag found." ) );
        return false;
    }

    // Get the office:chart element.
    TQDomElement officeChartElem = KoDom::namedItemNS( bodyElem,
						      KoXmlNS::office, "chart" );
    if ( officeChartElem.isNull() ) {
        kdError(32001) << "No office:chart found!" << endl;
        TQDomElement  childElem;
        TQString      localName;
        forEachElement( childElem, bodyElem ) {
            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 chart, but %1. Please try opening it with the appropriate application." ).tqarg( KoDocument::tagNameToDocumentType( localName ) ) );

        return false;
    }

    TQDomElement chartElem = KoDom::namedItemNS( officeChartElem,
						KoXmlNS::chart, "chart" );
    if ( chartElem.isNull() ) {
        setErrorMessage( i18n( "Invalid OASIS OpenDocument file. No chart:chart tag found." ) );
        return false;
    }

    // Get the loading context and stylestack from the styles.
    KoOasisLoadingContext  loadingContext( this, oasisStyles, store );
    //KoStyleStack          &styleStack = loadingContext.styleStack();

#if 0  // Example code!!
    // load chart properties into the stylestack.
    styleStack.save();
    styleStack.setTypeProperties( "chart" ); // load chart properties
    loadingContext.fillStyleStack( chartElem, KoXmlNS::chart, "style-name" );

    const TQString fillColor = styleStack.attributeNS( KoXmlNS::draw, "fill-color" );
    kdDebug() << "fillColor=" << fillColor << endl;

    styleStack.restore();
#endif

    // Load chart parameters, most of these are stored in the
    // chart:plot-area element within chart:chart.
    TQString  errorMessage;
    bool     ok = m_params->loadOasis( chartElem, loadingContext, errorMessage,
				       store);
    if ( !ok ) {
        setErrorMessage( errorMessage );
        return false;
    }

    // TODO Load data direction (see loadAuxiliary)

    // Load the data table.
    TQDomElement tableElem = KoDom::namedItemNS( chartElem,
						KoXmlNS::table, "table" );
    if ( !tableElem.isNull() ) {
        ok = loadOasisData( tableElem );
        if ( !ok )
            return false; // TODO setErrorMessage
    }

    return true;
}


bool KChartPart::loadOasisData( const TQDomElement& tableElem )
{
    int          numberHeaderColumns = 0;
    TQDomElement  tableHeaderColumns = KoDom::namedItemNS( tableElem,
							  KoXmlNS::table,
							  "table-header-columns" );

    TQDomElement  elem;
    forEachElement( elem, tableHeaderColumns ) {
        if ( elem.localName() == "table-column" ) {
            int repeated = elem.attributeNS( KoXmlNS::table, "number-columns-repeated", TQString() ).toInt();
            numberHeaderColumns += TQMAX( 1, repeated );
        }
    }

    // With 0 you get no titles, and with more than 1 we ignore the others.
    Q_ASSERT( numberHeaderColumns == 1 );

    int numberDataColumns = 0;
    TQDomElement tableColumns = KoDom::namedItemNS( tableElem, KoXmlNS::table, "table-columns" );
    forEachElement( elem, tableColumns ) {
        if ( elem.localName() == "table-column" ) {
            int repeated = elem.attributeNS( KoXmlNS::table, "number-columns-repeated", TQString() ).toInt();
            numberDataColumns += TQMAX( 1, repeated );
        }
    }

    // Parse table-header-rows for the column names.
    m_colLabels.clear();
    TQDomElement tableHeaderRows = KoDom::namedItemNS( tableElem, KoXmlNS::table, "table-header-rows" );
    if ( tableHeaderRows.isNull() )
        kdWarning(35001) << "No table-header-rows element found!" << endl;
    TQDomElement tableHeaderRow = KoDom::namedItemNS( tableHeaderRows, KoXmlNS::table, "table-row" );
    if ( tableHeaderRow.isNull() )
        kdWarning(35001) << "No table-row inside table-header-rows!" << endl;

    int cellNum = 0;
    forEachElement( elem, tableHeaderRow ) {
        if ( elem.localName() == "table-cell" ) {
            ++cellNum;
            if ( cellNum > numberHeaderColumns ) {
                TQDomElement pElem = KoDom::namedItemNS( elem, KoXmlNS::text, "p" );
                m_colLabels.append( pElem.text() );
            }
        }
    }
    numberDataColumns = TQMAX( numberDataColumns, cellNum - numberHeaderColumns );
    if ( (int)m_colLabels.count() != numberDataColumns )
        kdWarning(35001) << "Got " << m_colLabels.count()
			 << " column titles, expected " << numberDataColumns
			 << endl;

    // Get the number of rows, and read row labels
    int          numberDataRows = 0;
    TQDomElement  tableRows = KoDom::namedItemNS( tableElem, KoXmlNS::table, "table-rows" );

    m_rowLabels.clear();
    forEachElement( elem, tableRows ) {
        if ( elem.localName() == "table-row" ) {
            int repeated = elem.attributeNS( KoXmlNS::table, "number-rows-repeated", TQString() ).toInt();
            Q_ASSERT( repeated <= 1 ); // we don't handle yet the case where data rows are repeated (can this really happen?)
            numberDataRows += TQMAX( 1, repeated );
            if ( numberHeaderColumns > 0 ) {
                TQDomElement firstCell = KoDom::namedItemNS( elem, KoXmlNS::table, "table-cell" );
                TQDomElement pElem = KoDom::namedItemNS( firstCell, KoXmlNS::text, "p" );
                m_rowLabels.append( pElem.text() );
            }
        }
    }

    kdDebug(35001) << "numberHeaderColumns=" << numberHeaderColumns
		   << " numberDataColumns=" << numberDataColumns
                   << " numberDataRows=" << numberDataRows << endl;

    if ( (int)m_rowLabels.count() != numberDataRows)
        kdWarning(35001) << "Got " << m_rowLabels.count()
			 << " row labels, expected " << numberDataRows << endl;

    m_currentData.expand( numberDataRows, numberDataColumns );
    m_currentData.setUsedCols( numberDataColumns );
    m_currentData.setUsedRows( numberDataRows );

    // Now really load the cells.
    int row = 0;
    TQDomElement rowElem;
    forEachElement( rowElem, tableRows ) {
        if ( rowElem.localName() == "table-row" ) {
            int col = 0;
            int cellNum = 0;
            TQDomElement cellElem;
            forEachElement( cellElem, rowElem ) {
                if ( cellElem.localName() == "table-cell" ) {
                    ++cellNum;
                    if ( cellNum > numberHeaderColumns ) {
                        TQString valueType = cellElem.attributeNS( KoXmlNS::office, "value-type", TQString() );
                        if ( valueType != "float" )
                            kdWarning(35001) << "Don't know how to handle value-type " << valueType << endl;
                        else {
                            TQString  value = cellElem.attributeNS( KoXmlNS::office, "value", TQString() );
                            double   val = value.toDouble();

                            m_currentData.setCell( row, col, val );
                        }
                        ++col;
                    }
                }
            }
            ++row;
        }
    }

    return true;
}


bool KChartPart::saveOasis( KoStore* store, KoXmlWriter* manifestWriter )
{
    manifestWriter->addManifestEntry( "content.xml", "text/xml" );
    KoOasisStore oasisStore( store );

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

    KoGenStyles mainStyles;

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

    // Indent to indicate that this is inside some tags.
    {
        // Saves chart class, title, legend, plot-area
        m_params->saveOasis( bodyWriter, mainStyles );

	// Save the data table.
        saveOasisData( bodyWriter, mainStyles );
    }

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

    contentWriter->startElement( "office:automatic-styles" );
    writeAutomaticStyles( *contentWriter, mainStyles );
    contentWriter->endElement(); // office:automatic-styles

    oasisStore.closeContentWriter();

    // Done with content.xml

#if 0
    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;
#endif

    return true;
}


void KChartPart::saveOasisData( KoXmlWriter* bodyWriter,
				KoGenStyles& mainStyles ) const
{
    Q_UNUSED( mainStyles );

    const int cols = m_currentData.usedCols()
                     ? TQMIN(m_currentData.usedCols(), m_currentData.cols())
                     : m_currentData.cols();
    const int rows = m_currentData.usedRows()
                     ? TQMIN(m_currentData.usedRows(), m_currentData.rows())
                     : m_currentData.rows();

    bodyWriter->startElement( "table:table" );
    bodyWriter->addAttribute( "table:name", "local-table" );

    // Exactly one header column, always.
    bodyWriter->startElement( "table:table-header-columns" );
    bodyWriter->startElement( "table:table-column" );
    bodyWriter->endElement(); // table:table-column
    bodyWriter->endElement(); // table:table-header-columns

    // Then "cols" columns
    bodyWriter->startElement( "table:table-columns" );
    bodyWriter->startElement( "table:table-column" );
    bodyWriter->addAttribute( "table:number-columns-repeated", cols );
    bodyWriter->endElement(); // table:table-column
    bodyWriter->endElement(); // table:table-columns

    // Exactly one header row, always.
    bodyWriter->startElement( "table:table-header-rows" );
    bodyWriter->startElement( "table:table-row" );

    // The first column in header row is just the header column - no title needed
    bodyWriter->startElement( "table:table-cell" );
    bodyWriter->addAttribute( "office:value-type", "string" );
    bodyWriter->startElement( "text:p" );
    bodyWriter->endElement(); // text:p
    bodyWriter->endElement(); // table:table-cell

    // Save column labels in the first header row, for instance:
    //          <table:table-cell office:value-type="string">
    //            <text:p>Column 1 </text:p>
    //          </table:table-cell>
    TQStringList::const_iterator colLabelIt = m_colLabels.begin();
    for ( int col = 0; col < cols ; ++col ) {
        if ( colLabelIt != m_colLabels.end() ) {
            bodyWriter->startElement( "table:table-cell" );
            bodyWriter->addAttribute( "office:value-type", "string" );
            bodyWriter->startElement( "text:p" );
            bodyWriter->addTextNode( *colLabelIt );
            bodyWriter->endElement(); // text:p
            bodyWriter->endElement(); // table:table-cell
            ++colLabelIt;
        }
    }

    bodyWriter->endElement(); // table:table-row
    bodyWriter->endElement(); // table:table-header-rows
    bodyWriter->startElement( "table:table-rows" );

    TQStringList::const_iterator rowLabelIt = m_rowLabels.begin();
    for ( int row = 0; row < rows ; ++row ) {
        bodyWriter->startElement( "table:table-row" );

        if ( rowLabelIt != m_rowLabels.end() ) {
            // Save row labels, similar to column labels
            bodyWriter->startElement( "table:table-cell" );
            bodyWriter->addAttribute( "office:value-type", "string" );

            bodyWriter->startElement( "text:p" );
            bodyWriter->addTextNode( *rowLabelIt );
            bodyWriter->endElement(); // text:p

            bodyWriter->endElement(); // table:table-cell
            ++rowLabelIt;
        }

        for ( int col = 0; col < cols; ++col ) {
            TQVariant value( m_currentData.cellVal( row, col ) );
            TQString  valType;
            TQString  valStr;

            switch ( value.type() ) {
            case TQVariant::Invalid:
		break;
            case TQVariant::String:
		valType = "string";
		valStr  = value.toString();
		break;
            case TQVariant::Double:
		valType = "float";
		valStr  = TQString::number( value.toDouble(), 'g', DBL_DIG );
		break;
            case TQVariant::DateTime:
		valType = "date";
		valStr  = ""; /* like in saveXML, but why? */
		break;
            default: {
                kdDebug(35001) << "ERROR: cell " << row << "," << col
                               << " has unknown type." << endl;
                }
            }

	    // Add the value type and the string to the XML tree.
            bodyWriter->startElement( "table:table-cell" );
            if ( !valType.isEmpty() ) {
                bodyWriter->addAttribute( "office:value-type", valType );
                if ( value.type() == TQVariant::Double )
                    bodyWriter->addAttribute( "office:value", valStr );

                bodyWriter->startElement( "text:p" );
                bodyWriter->addTextNode( valStr );
                bodyWriter->endElement(); // text:p
            }
	    bodyWriter->endElement(); // table:table-cell
        }
        bodyWriter->endElement(); // table:table-row
    }

    bodyWriter->endElement(); // table:table-rows
    bodyWriter->endElement(); // table:table
}

void KChartPart::writeAutomaticStyles( KoXmlWriter& contentWriter, KoGenStyles& mainStyles ) const
{
    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:chart-properties" );
    }

}

// ----------------------------------------------------------------
//             Save and Load old KChart file format


TQDomDocument KChartPart::saveXML()
{
    TQDomElement  tmpElem;

    //kdDebug(35001) << "kchart saveXML called" << endl;

    // The biggest part of the saving is done by KDChart itself, so we
    // don't have to do it.
    TQDomDocument doc = m_params->saveXML( false );

    // ----------------------------------------------------------------
    // The rest of the saving has to be done by us.

    TQDomElement docRoot = doc.documentElement();

    // Save auxiliary data.
    TQDomElement aux = doc.createElement( "KChartAuxiliary" );
    docRoot.appendChild( aux );

    // The data direction (rows/columns).
    tmpElem = doc.createElement( "direction" );
    tmpElem.setAttribute( "value", (int) m_params->dataDirection() );
    aux.appendChild( tmpElem );

    tmpElem = doc.createElement( "dataaslabel" );
    tmpElem.setAttribute( "firstrow",
			  m_params->firstRowAsLabel() ? "true" : "false" );
    tmpElem.setAttribute( "firstcol",
			  m_params->firstColAsLabel() ? "true" : "false" );
    aux.appendChild( tmpElem );

    tmpElem = doc.createElement( "barnumlines" );
    tmpElem.setAttribute( "value", (int) m_params->barNumLines() );
    aux.appendChild( tmpElem );

    // Save the data values.
    TQDomElement data = doc.createElement( "data" );
    docRoot.appendChild( data );

    int cols = m_currentData.usedCols()
             ? TQMIN(m_currentData.usedCols(), m_currentData.cols())
             : m_currentData.cols();
    int rows = m_currentData.usedRows()
             ? TQMIN(m_currentData.usedRows(), m_currentData.rows())
             : m_currentData.rows();
    data.setAttribute( "cols", cols );
    data.setAttribute( "rows", rows );
    kdDebug(35001) << "      writing  " << cols << "," << rows << "  (cols,rows)." << endl;

    for (int i=0; i!=rows; ++i) {
        for (int j=0; j!=cols; ++j) {
            TQDomElement e = doc.createElement( "cell" );
            data.appendChild( e );
            TQString valType;
            TQVariant value( m_currentData.cellVal( i,j ) );
            switch ( value.type() ) {
                case TQVariant::Invalid:  valType = "NoValue";   break;
                case TQVariant::String:   valType = "String";    break;
                case TQVariant::Double:   valType = "Double";    break;
                case TQVariant::DateTime: valType = "DateTime";  break;
                default: {
                    valType = "(unknown)";
                    kdDebug(35001) << "ERROR: cell " << i << "," << j
				   << " has unknown type." << endl;
                }
            }

            e.setAttribute( "valType", valType );
            //kdDebug(35001) << "      cell " << i << "," << j
	    //	   << " saved with type '" << valType << "'." << endl;
            switch ( value.type() ) {
                case TQVariant::String:  e.setAttribute( "value", value.toString() );
                              break;
                case TQVariant::Double:  e.setAttribute( "value", TQString::number( value.toDouble() ) );
                              break;
                case TQVariant::DateTime:e.setAttribute( "value", "" );
                              break;
                default: {
                    e.setAttribute( "value", "" );
                    if( TQVariant::Invalid != value.type() )
                        kdDebug(35001) << "ERROR: cell " << i << "," << j
				       << " has unknown type." << endl;
                }
            }
        }
    }

    return doc;
}


bool KChartPart::loadXML( TQIODevice*, const TQDomDocument& doc )
{
    kdDebug(35001) << "kchart loadXML called" << endl;

    // Set some sensible defaults.
    setChartDefaults();

    // First try to load the KDChart parameters.
    bool  result = m_params->loadXML( doc );

    // If went well, try to load the auxiliary data and the data...
    if (result) {
        result = loadAuxiliary(doc) && loadData( doc, m_currentData );
    }
    else {
	// ...but if it did, try to load the old XML format.
        result = loadOldXML( doc );
    }

    // If everything is OK, then get the headers from the KDChart parameters.
    if (result) {
        TQStringList        legendLabels;
        KDChartAxisParams  params;
        params = m_params->axisParams( KDChartAxisParams::AxisPosBottom );

	// Get the legend.
	TQString  str;
	uint     index = 0;
	while ((str = m_params->legendText(index++)) != TQString())
	    legendLabels << str;

	if (m_params->dataDirection() == KChartParams::DataRows) {
	    m_colLabels = params.axisLabelStringList();
	    m_rowLabels = legendLabels;
	}
	else {
	    m_colLabels = legendLabels;
	    m_rowLabels = params.axisLabelStringList();
	}

    }

    m_params->setDrawSolidExcessArrows(true);

    return result;
}


// Load the auxiliary data.
//
// Currently, that means the data direction.
//
bool KChartPart::loadAuxiliary( const TQDomDocument& doc )
{
    TQDomElement  chart = doc.documentElement();
    TQDomElement  aux   = chart.namedItem("KChartAuxiliary").toElement();

    // Older XML files might be missing this section.  That is OK; the
    // defaults will be used.
    if (aux.isNull())
	return true;

    TQDomNode node = aux.firstChild();

    // If the aux section exists, it should contain data.
    while (!node.isNull()) {

	TQDomElement e = node.toElement();
	if (e.isNull()) {
	    // FIXME: Should this be regarded as an error?
	    node = node.nextSibling();
	    continue;
	}

	// Check for direction
	if ( e.tagName() == "direction" ) {
	    if ( e.hasAttribute("value") ) {
		bool  ok;

		// Read the direction. On failure, use the default.
		int   dir = e.attribute("value").toInt(&ok);
		if ( !ok )
		    dir = (int) KChartParams::DataColumns;

		//kdDebug(35001) << "Got aux value \"direction\": " << dir << endl;
		m_params->setDataDirection( (KChartParams::DataDirection) dir );
	    }
	    else {
		kdDebug(35001) << "Error in direction tag." << endl;
	    }
	}

	// Check for first row / col as label
	else if ( e.tagName() == "dataaslabel" ) {
	    TQString  val;

	    if ( e.hasAttribute("firstrow") ) {
		// Read the direction. On failure, use the default.
		val = e.attribute("firstrow");
		if ( val == "true" )
		    m_params->setFirstRowAsLabel( true );
		else
		    m_params->setFirstRowAsLabel( false );
	    }
	    else {
		kdDebug(35001) << "Error in barnumlines tag." << endl;
		m_params->setFirstRowAsLabel( false );
	    }

	    if ( e.hasAttribute("firstcol") ) {
		// Read the direction. On failure, use the default.
		val = e.attribute("firstcol");
		if ( val == "true" )
		    m_params->setFirstColAsLabel( true );
		else
		    m_params->setFirstColAsLabel( false );
	    }
	    else {
		kdDebug(35001) << "Error in barnumlines tag." << endl;
		m_params->setFirstColAsLabel( false );
	    }
	}

	// Check for number of lines in a bar chart.
	else if ( e.tagName() == "barnumlines" ) {
	    if ( e.hasAttribute("value") ) {
		bool  ok;

		// Read the number of lines. On failure, use the default.
		int   barNumLines = e.attribute("value").toInt(&ok);
		if ( !ok )
		    barNumLines = 0;

		//kdDebug(35001) << "Got aux value \"barnumlines\": "
		//	       << barNumLines << endl;
		m_params->setBarNumLines( barNumLines );
	    }
	    else {
		kdDebug(35001) << "Error in barnumlines tag." << endl;
	    }
	}
#if 0
	// Expand with more auxiliary types when needed.
	else if ( e.tagName() == "..." ) {
	}
	and so on...
#endif

	node = node.nextSibling();
    }

    return true;
}


bool KChartPart::loadData( const TQDomDocument& doc,
			   KDChartTableData& m_currentData )
{
    kdDebug(35001) << "kchart loadData called" << endl;

    TQDomElement chart = doc.documentElement();
    TQDomElement data = chart.namedItem("data").toElement();
    bool ok;
    int cols = data.attribute("cols").toInt(&ok);
    kdDebug(35001) << "cols readed as:" << cols << endl;
    if ( !ok ){
         return false;
    }

    int rows = data.attribute("rows").toInt(&ok);
    if ( !ok ){
         return false;
    }

    kdDebug(35001) << rows << " x " << cols << endl;
    m_currentData.expand(rows, cols);
    m_currentData.setUsedCols( cols );
    m_currentData.setUsedRows( rows );
    kdDebug(35001) << "Expanded!" << endl;
    TQDomNode n = data.firstChild();
    //TQArray<int> tmpExp(rows*cols);
    //TQArray<bool> tmpMissing(rows*cols);
    for (int i=0; i!=rows; i++) {
        for (int j=0; j!=cols; j++) {
            if (n.isNull()) {
                kdDebug(35001) << "Some problems, there is less data than it should be!" << endl;
                break;
            }
            TQDomElement e = n.toElement();
            if ( !e.isNull() && e.tagName() == "cell" ) {
                // add the cell to the corresponding place...
                TQVariant t;
                if ( e.hasAttribute("value") && e.hasAttribute("valType") ) {
                    TQString valueType = e.attribute("valType").lower();
                    if ( "string" == valueType ) {
                        t = e.attribute("value");
                    }
                    else if ( "double" == valueType ) {
                        bool bOk;
                        double val = e.attribute("value").toDouble(&bOk);
                        if ( !bOk )
                            val = 0.0;
                        t = val;
                    /*
                    } else if ( "datetime" == valueType ) {
                        t = . . .
                    */
                    } else {
                        t.clear();
                        if ( "novalue" != valueType )
                            kdDebug(35001) << "ERROR: cell " << i << "," << j << " has unknown type '" << valueType << "'." << endl;
                    }
                } else
                    t.clear();

                m_currentData.setCell(i,j, t );

		/*
                if ( e.hasAttribute( "hide" ) ) {
                    tmpMissing[cols*j+i] = (bool)e.attribute("hide").toInt( &ok );
                    if ( !ok )
                        return false;
                } else {
                    tmpMissing[cols*j+i] = false;
                }
                if ( e.hasAttribute( "dist" ) ) {
                    tmpExp[cols*j+i] = e.attribute("dist").toInt( &ok );
                    if ( !ok )
                        return false;
                } else {
                    tmpExp[cols*j+i] = 0;
                }
		*/

                n = n.nextSibling();
            }
        }
    }
    /*
    m_params->missing=tmpMissing;
    m_params->explode=tmpExp;
    */
    return true;
}


// ----------------------------------------------------------------
//         Save and Load real old KChart file format


bool KChartPart::loadOldXML( const TQDomDocument& doc )
{
    kdDebug(35001) << "kchart loadOldXML called" << endl;
    if ( doc.doctype().name() != "chart" )
        return false;

    kdDebug(35001) << "Ok, it is a chart" << endl;

    TQDomElement chart = doc.documentElement();
    if ( chart.attribute( "mime" ) != "application/x-kchart" && chart.attribute( "mime" ) != "application/vnd.kde.kchart" )
        return false;

    kdDebug(35001) << "Mimetype ok" << endl;

#if 0
    TQDomElement data = chart.namedItem("data").toElement();
    bool ok;
    int cols = data.attribute("cols").toInt(&ok);
    kdDebug(35001) << "cols readed as:" << cols << endl;
    if (!ok)  { return false; }
    int rows = data.attribute("rows").toInt(&ok);
    if (!ok)  { return false; }
    kdDebug(35001) << rows << " x " << cols << endl;
    m_currentData.expand(rows, cols);
    kdDebug(35001) << "Expanded!" << endl;
    TQDomNode n = data.firstChild();
    TQArray<int> tmpExp(rows*cols);
    TQArray<bool> tmpMissing(rows*cols);

    for (int i=0; i!=rows; i++) {
        for (int j=0; j!=cols; j++) {
            if (n.isNull()) {
                kdDebug(35001) << "Some problems, there is less data than it should be!" << endl;
                break;
            }

            TQDomElement e = n.toElement();
            if ( !e.isNull() && e.tagName() == "cell" ) {
                // add the cell to the corresponding place...
                double val = e.attribute("value").toDouble(&ok);
                if (!ok)  {  return false; }
                kdDebug(35001) << i << " " << j << "=" << val << endl;
                KoChart::Value t( val );
                // kdDebug(35001) << "Set cell for " << row << "," << col << endl;
                m_currentData.setCell(i,j,t);
                if ( e.hasAttribute( "hide" ) ) {
                    tmpMissing[cols*j+i] = (bool)e.attribute("hide").toInt( &ok );
                    if ( !ok )
                        return false;
                } else {
                    tmpMissing[cols*j+i] = false;
                }
                if ( e.hasAttribute( "dist" ) ) {
                    tmpExp[cols*j+i] = e.attribute("dist").toInt( &ok );
                    if ( !ok )
                        return false;
                } else {
                    tmpExp[cols*j+i] = 0;
                }

                n = n.nextSibling();
            }
        }
    }
    m_params->missing=tmpMissing;
    m_params->explode=tmpExp;
#endif


/*
  enum KChartType {
  KCHARTTYPE_LINE,
  KCHARTTYPE_AREA,
  KCHARTTYPE_BAR,
  KCHARTTYPE_HILOCLOSE,
  KCHARTTYPE_COMBO_LINE_BAR, aka, VOL[ume]
  KCHARTTYPE_COMBO_HLC_BAR,
  KCHARTTYPE_COMBO_LINE_AREA,
  KCHARTTYPE_COMBO_HLC_AREA,
  KCHARTTYPE_3DHILOCLOSE,
  KCHARTTYPE_3DCOMBO_LINE_BAR,
  KCHARTTYPE_3DCOMBO_LINE_AREA,
  KCHARTTYPE_3DCOMBO_HLC_BAR,
  KCHARTTYPE_3DCOMBO_HLC_AREA,
  KCHARTTYPE_3DBAR,
  KCHARTTYPE_3DAREA,
  KCHARTTYPE_3DLINE,
  KCHARTTYPE_3DPIE,
  KCHARTTYPE_2DPIE
  };
*/
    bool ok;
    TQDomElement params = chart.namedItem( "params" ).toElement();
    if ( params.hasAttribute( "type" ) ) {
        int type=params.attribute("type").toInt( &ok );
        if ( !ok )
            return false;
        switch(type)
        {
        case 1:
            m_params->setChartType(KChartParams::Line);
            break;
        case 2:
            m_params->setChartType(KChartParams::Area);
            break;
        case 3:
            m_params->setChartType(KChartParams::Bar);
            break;
        case 4:
            m_params->setChartType(KChartParams::HiLo);
            break;
        case 5:
        case 6:
        case 7:
        case 8:
            /*     KCHARTTYPE_COMBO_LINE_BAR, aka, VOL[ume]
                   KCHARTTYPE_COMBO_HLC_BAR,
                   KCHARTTYPE_COMBO_LINE_AREA,
                   KCHARTTYPE_COMBO_HLC_AREA,
            */
            /* line by default*/
            m_params->setChartType(KChartParams::Line);
            break;
        case 9:
            m_params->setChartType(KChartParams::HiLo);
            break;
        case 10:
            m_params->setChartType(KChartParams::Bar);
            break;
        case 11:
            m_params->setChartType(KChartParams::Area);
            break;
        case 12:
            m_params->setChartType(KChartParams::Bar);
            break;
        case 13:
            m_params->setChartType(KChartParams::Area);
            break;
        case 14:
            m_params->setChartType(KChartParams::Bar);
            break;
        case 15:
            m_params->setChartType(KChartParams::Area);
            break;
        case 16:
            m_params->setChartType(KChartParams::Line);
            break;
        case 17:
        case 18:
            m_params->setChartType(KChartParams::Pie);
            break;

        }
        if ( !ok )
            return false;
    }
#if 0
    if ( params.hasAttribute( "subtype" ) ) {
        m_params->stack_type = (KChartStackType)params.attribute("subtype").toInt( &ok );
        if ( !ok )
            return false;
    }
    if ( params.hasAttribute( "hlc_style" ) ) {
        m_params->hlc_style = (KChartHLCStyle)params.attribute("hlc_style").toInt( &ok );
        if ( !ok )
            return false;
    }
    if ( params.hasAttribute( "hlc_cap_width" ) ) {
        m_params->hlc_cap_width = (short)params.attribute( "hlc_cap_width" ).toShort( &ok );
        if ( !ok )
            return false;
    }

    TQDomElement title = params.namedItem( "title" ).toElement();
    if ( !title.isNull()) {
        TQString t = title.text();
        m_params->title=t;
    }
    TQDomElement titlefont = params.namedItem( "titlefont" ).toElement();
    if ( !titlefont.isNull()) {
        TQDomElement font = titlefont.namedItem( "font" ).toElement();
        if ( !font.isNull() )
            m_params->setTitleFont(toFont(font));
    }
    TQDomElement xtitle = params.namedItem( "xtitle" ).toElement();
    if ( !xtitle.isNull()) {
        TQString t = xtitle.text();
        m_params->xtitle=t;
    }
    TQDomElement xtitlefont = params.namedItem( "xtitlefont" ).toElement();
    if ( !xtitlefont.isNull()) {
        TQDomElement font = xtitlefont.namedItem( "font" ).toElement();
        if ( !font.isNull() )
            m_params->setXTitleFont(toFont(font));
    }
    TQDomElement ytitle = params.namedItem( "ytitle" ).toElement();
    if ( !ytitle.isNull()) {
        TQString t = ytitle.text();
        m_params->ytitle=t;
    }
    TQDomElement ytitle2 = params.namedItem( "ytitle2" ).toElement();
    if ( !ytitle2.isNull()) {
        TQString t = ytitle2.text();
        m_params->ytitle2=t;
    }
    TQDomElement ytitlefont = params.namedItem( "ytitlefont" ).toElement();
    if ( !ytitlefont.isNull()) {
        TQDomElement font = ytitlefont.namedItem( "font" ).toElement();
        if ( !font.isNull() )
            m_params->setYTitleFont(toFont(font));
    }
    TQDomElement ylabelfmt = params.namedItem( "ylabelfmt" ).toElement();
    if ( !ylabelfmt.isNull()) {
        TQString t = ylabelfmt.text();
        m_params->ylabel_fmt=t;
    }
    TQDomElement ylabel2fmt = params.namedItem( "ylabel2fmt" ).toElement();
    if ( !ylabel2fmt.isNull()) {
        TQString t = ylabel2fmt.text();
        m_params->ylabel2_fmt=t;
    }
    TQDomElement labelfont = params.namedItem( "labelfont" ).toElement();
    if ( !labelfont.isNull()) {
        TQDomElement font = labelfont.namedItem( "font" ).toElement();
        if ( !font.isNull() )
            m_params->setLabelFont(toFont(font));
    }

    TQDomElement yaxisfont = params.namedItem( "yaxisfont" ).toElement();
    if ( !yaxisfont.isNull()) {
        TQDomElement font = yaxisfont.namedItem( "font" ).toElement();
        if ( !font.isNull() )
            m_params->setYAxisFont(toFont(font));
    }

    TQDomElement xaxisfont = params.namedItem( "xaxisfont" ).toElement();
    if ( !xaxisfont.isNull()) {
        TQDomElement font = xaxisfont.namedItem( "font" ).toElement();
        if ( !font.isNull() )
            m_params->setXAxisFont(toFont(font));
    }
    TQDomElement annotationFont = params.namedItem("annotationfont").toElement();
    if ( !annotationFont.isNull()) {
        TQDomElement font = annotationFont.namedItem( "font" ).toElement();
        if ( !font.isNull() )
            m_params->setAnnotationFont(toFont(font));
    }

    TQDomElement yaxis = params.namedItem( "yaxis" ).toElement();
    if ( !yaxis.isNull()) {
        if (yaxis.hasAttribute( "yinterval" )) {
            m_params->requested_yinterval= yaxis.attribute("yinterval").toDouble( &ok );
            if ( !ok ) return false;
        }
        if (yaxis.hasAttribute( "ymin" )) {
            m_params->requested_ymin= yaxis.attribute("ymin").toDouble( &ok );
            if ( !ok ) return false;
        }
        if (yaxis.hasAttribute( "ymax" ) ) {
            m_params->requested_ymax= yaxis.attribute("ymax").toDouble( &ok );
            if ( !ok ) return false;
        }
    }
#endif

    TQDomElement graph = params.namedItem( "graph" ).toElement();
    if (!graph.isNull()) {
        if (graph.hasAttribute( "grid" )) {
            bool b=(bool) graph.attribute("grid").toInt( &ok );
            m_params->setAxisShowGrid(KDChartAxisParams::AxisPosLeft,b );
            m_params->setAxisShowGrid(KDChartAxisParams::AxisPosBottom,b );
            if (!ok) return false;
        }
        if (graph.hasAttribute( "xaxis" )) {
            bool b=(bool) graph.attribute("xaxis").toInt( &ok );
            if (!ok) return false;
            m_params->setAxisVisible(KDChartAxisParams::AxisPosBottom,b);
        }
        if (graph.hasAttribute( "yaxis" )) {
            bool b=(bool) graph.attribute("yaxis").toInt( &ok );
            if (!ok) return false;
            m_params->setAxisVisible(KDChartAxisParams::AxisPosLeft,b);
        }
#if 0
        //no implemented
        if (graph.hasAttribute( "shelf" )) {
            m_params->shelf=(bool) graph.attribute("shelf").toInt( &ok );
            if (!ok) return false;
        }
#endif
        if (graph.hasAttribute( "yaxis2" )) {
            bool b=(bool) graph.attribute("yaxis2").toInt( &ok );
            if (!ok) return false;
            m_params->setAxisVisible(KDChartAxisParams::AxisPosRight,b);
        }

#if 0
        //no implemented
        if (graph.hasAttribute( "ystyle" )) {
            m_params->yval_style=(bool) graph.attribute("ystyle").toInt( &ok );
            if (!ok) return false;
        }
        if (graph.hasAttribute( "border" )) {
            m_params->border=(bool) graph.attribute("border").toInt( &ok );
            if (!ok) return false;
        }
        if (graph.hasAttribute( "transbg" )) {
            m_params->transparent_bg=(bool) graph.attribute("transbg").toInt( &ok );
            if (!ok) return false;
        }
        if (graph.hasAttribute( "xlabel" )) {
            m_params->hasxlabel=(bool) graph.attribute("xlabel").toInt( &ok );
            if (!ok) return false;
        }
        if ( graph.hasAttribute( "xlabel_spacing" ) ) {
            m_params->xlabel_spacing = (short)graph.attribute( "xlabel_spacing" ).toShort( &ok );
            if ( !ok )
                return false;
        }
        if ( graph.hasAttribute( "ylabel_density" ) ) {
            m_params->ylabel_density = (short)graph.attribute( "ylabel_density" ).toShort( &ok );
            if ( !ok )
                return false;
        }
        if (graph.hasAttribute( "line")) {
            m_params->label_line=(bool) graph.attribute("line").toInt( &ok );
            if (!ok) return false;
        }
        if (graph.hasAttribute( "percent")) {
            m_params->percent_labels=(KChartPercentType) graph.attribute("percent").toInt( &ok );
            if (!ok) return false;
        }
        if (graph.hasAttribute("cross")) {
            m_params->cross=(bool) graph.attribute("cross").toInt( &ok );
            if (!ok) return false;
        }
        if (graph.hasAttribute("thumbnail")) {
            m_params->thumbnail=(bool) graph.attribute("thumbnail").toInt( &ok );
            if (!ok) return false;
        }
        if (graph.hasAttribute("thumblabel")) {
            m_params->thumblabel= graph.attribute("thumblabel");
        }
        if (graph.hasAttribute("thumbval")) {
            m_params->thumbval=(bool) graph.attribute("thumbval").toDouble( &ok );
            if (!ok)
                return false;
        }
#endif
    }

#if 0
    TQDomElement graphparams = params.namedItem( "graphparams" ).toElement();
    if (!graphparams.isNull()) {
        if (graphparams.hasAttribute( "dept3d" )) {
            m_params->_3d_depth=graphparams.attribute("dept3d").toDouble( &ok );
            if (!ok) return false;
        }
        if (graphparams.hasAttribute( "angle3d" )) {
            m_params->_3d_angle=graphparams.attribute("angle3d").toShort( &ok );
            if (!ok) return false;
        }
        if (graphparams.hasAttribute( "barwidth" )) {
            m_params->bar_width=graphparams.attribute("barwidth").toShort( &ok );
            if (!ok) return false;
        }
        if (graphparams.hasAttribute( "colpie" )) {
            m_params->colPie=graphparams.attribute("colpie").toInt( &ok );
            if (!ok) return false;
        }
        if (graphparams.hasAttribute( "other_threshold" )) {
            m_params->other_threshold=graphparams.attribute("other_threshold").toShort( &ok );
            if (!ok)
                return false;
        }
        if (graphparams.hasAttribute( "offsetCol" )) {
            m_params->offsetCol = graphparams.attribute("offsetCol").toInt( &ok );
            if (!ok)
                return false;
        }
        if (graphparams.hasAttribute( "hard_size" )) {
            m_params->hard_size = (bool)graphparams.attribute("hard_size").toInt( &ok );
            if (!ok)
                return false;
        }
        if (graphparams.hasAttribute( "hard_graphheight" )) {
            m_params->hard_graphheight = graphparams.attribute("hard_graphheight").toInt( &ok );
            if (!ok)
                return false;
        }
        if (graphparams.hasAttribute( "hard_graphwidth" )) {
            m_params->hard_graphwidth = graphparams.attribute("hard_graphwidth").toInt( &ok );
            if (!ok)
                return false;
        }
        if (graphparams.hasAttribute( "hard_xorig" )) {
            m_params->hard_xorig = graphparams.attribute("hard_xorig").toInt( &ok );
            if (!ok)
                return false;
        }
        if (graphparams.hasAttribute( "hard_yorig" )) {
            m_params->hard_yorig = graphparams.attribute("hard_yorig").toInt( &ok );
            if (!ok)
                return false;
        }
        if (graphparams.hasAttribute( "labeldist" )) {
            m_params->label_dist=graphparams.attribute("labeldist").toInt( &ok );
            if (!ok) return false;
        }
    }

    TQDomElement graphcolor = params.namedItem( "graphcolor" ).toElement();
    if (!graphcolor.isNull()) {
        if (graphcolor.hasAttribute( "bgcolor" )) {
            m_params->BGColor= TQColor( graphcolor.attribute( "bgcolor" ) );
        }
        if (graphcolor.hasAttribute( "gridcolor" )) {
            m_params->GridColor= TQColor( graphcolor.attribute( "gridcolor" ) );
        }
        if (graphcolor.hasAttribute( "linecolor" )) {
            m_params->LineColor= TQColor( graphcolor.attribute( "linecolor" ) );
        }
        if (graphcolor.hasAttribute( "plotcolor" )) {
            m_params->PlotColor= TQColor( graphcolor.attribute( "plotcolor" ) );
        }
        if (graphcolor.hasAttribute( "volcolor" )) {
            m_params->VolColor= TQColor( graphcolor.attribute( "volcolor" ) );
        }
        if (graphcolor.hasAttribute( "titlecolor" )) {
            m_params->TitleColor= TQColor( graphcolor.attribute( "titlecolor" ) );
        }
        if (graphcolor.hasAttribute( "xtitlecolor" )) {
            m_params->XTitleColor= TQColor( graphcolor.attribute( "xtitlecolor" ) );
        }
        if (graphcolor.hasAttribute( "ytitlecolor" )) {
            m_params->YTitleColor= TQColor( graphcolor.attribute( "ytitlecolor" ) );
        }
        if (graphcolor.hasAttribute( "ytitle2color" )) {
            m_params->YTitle2Color= TQColor( graphcolor.attribute( "ytitle2color" ) );
        }
        if (graphcolor.hasAttribute( "xlabelcolor" )) {
            m_params->XLabelColor= TQColor( graphcolor.attribute( "xlabelcolor" ) );
        }
        if (graphcolor.hasAttribute( "ylabelcolor" )) {
            m_params->YLabelColor= TQColor( graphcolor.attribute( "ylabelcolor" ) );
        }
        if (graphcolor.hasAttribute( "ylabel2color" )) {
            m_params->YLabel2Color= TQColor( graphcolor.attribute( "ylabel2color" ) );
        }
    }

    TQDomElement annotation = params.namedItem( "annotation" ).toElement();
    if (!annotation.isNull()) {
        m_params->annotation=new KChartAnnotationType;
        if (annotation.hasAttribute( "color" )) {
            m_params->annotation->color= TQColor( annotation.attribute( "color" ) );
        }
        if (annotation.hasAttribute( "point" )) {
            m_params->annotation->point=annotation.attribute("point").toDouble( &ok );
            if (!ok) return false;
        }
    }

    TQDomElement note = params.namedItem( "note" ).toElement();
    if ( !note.isNull()) {
        TQString t = note.text();
        m_params->annotation->note=t;
    }

    TQDomElement scatter = params.namedItem( "scatter" ).toElement();
    if ( !scatter.isNull() ) {
        m_params->scatter = new KChartScatterType;
        if ( scatter.hasAttribute( "point" ) ) {
            m_params->scatter->point = scatter.attribute( "point" ).toDouble( &ok );
            if ( !ok )
                return false;
        }
        if ( scatter.hasAttribute( "val" ) ) {
            m_params->scatter->val = scatter.attribute( "val" ).toDouble( &ok );
            if ( !ok )
                return false;
        }
        if ( scatter.hasAttribute( "width" ) ) {
            m_params->scatter->width = scatter.attribute( "val" ).toUShort( &ok );
            if ( !ok )
                return false;
        }
        if ( scatter.hasAttribute( "color" )) {
            m_params->scatter->color= TQColor( scatter.attribute( "color" ) );
        }
        if ( scatter.hasAttribute( "ind" ) ) {
            m_params->scatter->ind = (KChartScatterIndType)scatter.attribute( "ind" ).toInt( &ok );
            if ( !ok )
                return false;
        }
    }

    TQDomElement legend = chart.namedItem("legend").toElement();
    if (!legend.isNull()) {
        int number = legend.attribute("number").toInt(&ok);
        if (!ok)  { return false; }
        TQDomNode name = legend.firstChild();
        m_params->legend.clear();
        for(int i=0; i<number; i++) {
            if (name.isNull()) {
                kdDebug(35001) << "Some problems, there is less data than it should be!" << endl;
                break;
            }
            TQDomElement element = name.toElement();
            if ( !element.isNull() && element.tagName() == "name" ) {
                TQString t = element.text();
                m_params->legend+=t;
                name = name.nextSibling();
            }
        }
    }

    TQDomElement xlbl = chart.namedItem("xlbl").toElement();
    if (!xlbl.isNull()) {
        int number = xlbl.attribute("number").toInt(&ok);
        if (!ok)  { return false; }
        TQDomNode label = xlbl.firstChild();
        m_params->xlbl.clear();
        for (int i=0; i<number; i++) {
            if (label.isNull()) {
                kdDebug(35001) << "Some problems, there is less data than it should be!" << endl;
                break;
            }
            TQDomElement element = label.toElement();
            if ( !element.isNull() && element.tagName() == "label" ) {
                TQString t = element.text();
                m_params->xlbl+=t;
                label = label.nextSibling();
            }
        }
    }

    TQDomElement backgroundPixmap = chart.namedItem( "backgroundPixmap" ).toElement();
    if ( !backgroundPixmap.isNull() ) {
        if ( backgroundPixmap.hasAttribute( "name" ) )
            m_params->backgroundPixmapName = backgroundPixmap.attribute( "name" );
        if ( backgroundPixmap.hasAttribute( "isDirty" ) ) {
            m_params->backgroundPixmapIsDirty = (bool)backgroundPixmap.attribute( "isDirty" ).toInt( &ok );
            if ( !ok )
                return false;
        }
        if ( backgroundPixmap.hasAttribute( "scaled" ) ) {
            m_params->backgroundPixmapScaled = (bool)backgroundPixmap.attribute( "scaled" ).toInt( &ok );
            if ( !ok )
                return false;
        }
        if ( backgroundPixmap.hasAttribute( "centered" ) ) {
            m_params->backgroundPixmapCentered = (bool)backgroundPixmap.attribute( "centered" ).toInt( &ok );
            if ( !ok )
                return false;
        }
        if ( backgroundPixmap.hasAttribute( "intensity" ) ) {
            m_params->backgroundPixmapIntensity = backgroundPixmap.attribute( "intensity" ).toFloat( &ok );
            if ( !ok )
                return false;
        }
    }

    TQDomElement extcolor = chart.namedItem("extcolor").toElement();
    if (!extcolor.isNull()) {
        unsigned int number = extcolor.attribute("number").toInt(&ok);
        if (!ok)  { return false; }
        TQDomNode color = extcolor.firstChild();

        for (unsigned int i=0; i<number; i++) {
            if (color.isNull()) {
                kdDebug(35001) << "Some problems, there is less data than it should be!" << endl;
                break;
            }
            TQDomElement element = color.toElement();
            if ( !element.isNull()) {
                if (element.hasAttribute( "name" )) {
                    m_params->ExtColor.setColor(i,TQColor( element.attribute( "name" ) ));
                }
                color = color.nextSibling();
            }
        }
    }

    if ( !m_params->backgroundPixmapName.isNull() ) {
        m_params->backgroundPixmap.load( locate( "wallpaper",
						 m_params->backgroundPixmapName ));
        m_params->backgroundPixmapIsDirty = true;
    }
#endif
    return true;
}



void  KChartPart::slotModified()
{
    kdDebug(35001) << "slotModified called!" << endl;

    setModified(true);
}


bool KChartPart::showEmbedInitDialog(TQWidget* /*parent*/)
{
  // Don't show an embed dialog
  return true;
}


}  //KChart namespace

#include "kchart_part.moc"