summaryrefslogtreecommitdiffstats
path: root/kexi/formeditor/formIO.cpp
blob: 639b4a8314ffb8ec83801f3c22bf8bcd335de6da (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
/* This file is part of the KDE project
   Copyright (C) 2004 Cedric Pasteur <cedric.pasteur@free.fr>
   Copyright (C) 2005-2007 Jaroslaw Staniek <js@iidea.pl>

   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 <kdebug.h>

#include <tqmetaobject.h>
#include <tqdom.h>
#include <tqfile.h>
#include <tqtextstream.h>
#include <tqcursor.h>
#include <tqbuffer.h>
#include <tqimage.h>
#include <tqlayout.h>
#include <tqobjectlist.h>
#include <tqdatetime.h>
#include <tqlabel.h>
#include <tqpainter.h>

#include <kfiledialog.h>
#include <klocale.h>
#include <kcommand.h>
#include <kaccelmanager.h>

#include "form.h"
#include "container.h"
#include "objecttree.h"
#include "formmanager.h"
#include "widgetlibrary.h"
#include "spring.h"
#include "pixmapcollection.h"
#include "events.h"
#include "utils.h"
#include "kexiflowlayout.h"
#include "widgetwithsubpropertiesinterface.h"
#include "formIO.h"

/// A blank widget used when the class name is not supported
CustomWidget::CustomWidget(const TQCString &className, TQWidget *tqparent, const char *name)
: TQWidget(tqparent, name), m_className(className)
{
	setBackgroundMode(TQt::PaletteDark);
}

CustomWidget::~CustomWidget()
{
}

void
CustomWidget::paintEvent(TQPaintEvent *)
{
	TQPainter p(this);
	p.setPen(tqpalette().active().text());
	TQRect r(rect());
	r.setX(r.x()+2);
	p.drawText(r, TQt::AlignTop, m_className);
}

using namespace KFormDesigner;

TQDict<TQLabel> *FormIO::m_buddies = 0;
ObjectTreeItem *FormIO::m_currentItem = 0;
Form *FormIO::m_currentForm = 0;
bool FormIO::m_savePixmapsInline = false;

// FormIO itself

KFORMEDITOR_EXPORT uint KFormDesigner::version()
{
	return KFORMDESIGNER_VERSION;
}

/////////////////////////////////////////////////////////////////////////////
///////////// Saving/loading functions //////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

FormIO::FormIO()
{
}

FormIO::~FormIO()
{
}

bool
FormIO::saveFormToFile(Form *form, const TQString &filename)
{
	TQString m_filename;
	if(!form->filename().isNull() && filename.isNull())
		m_filename = form->filename();

	if(filename.isNull())
	{
		m_filename = KFileDialog::getSaveFileName(TQString(), i18n("*.ui|TQt Designer UI Files"));
		if(m_filename.isNull())
			return false;
	}
	else
		m_filename = filename;
	form->setFilename(m_filename);

	TQDomDocument domDoc;
	if (!saveFormToDom(form, domDoc))
		return false;

	TQFile file(m_filename);
	if (!file.open(IO_WriteOnly))
		return false;

	TQTextStream stream(&file);
	stream << domDoc.toString(3) << endl;
	file.close();

	return true;
}

bool
FormIO::saveFormToByteArray(Form *form, TQByteArray &dest)
{
	TQDomDocument domDoc;
	if (!saveFormToDom(form, domDoc))
		return false;
	dest = domDoc.toCString();
	return true;
}

bool
FormIO::saveFormToString(Form *form, TQString &dest, int indent)
{
	TQDomDocument domDoc;
	if (!saveFormToDom(form, domDoc))
		return false;
	dest = domDoc.toString(indent);
	return true;
}

bool
FormIO::saveFormToDom(Form *form, TQDomDocument &domDoc)
{
	m_currentForm = form;

	domDoc = TQDomDocument("UI");
	TQDomElement uiElement = domDoc.createElement("UI");
	domDoc.appendChild(uiElement);
	uiElement.setAttribute("version", "3.1");
	uiElement.setAttribute("stdsetdef", 1);

	//update format version information
	form->headerProperties()->insert("version", TQString::number(form->formatVersion()));
	//custom properties
	TQDomElement headerPropertiesEl = domDoc.createElement("kfd:customHeader");
	for (TQMapConstIterator<TQCString,TQString> it=form->headerProperties()->constBegin(); it!=form->headerProperties()->constEnd(); ++it) {
		headerPropertiesEl.setAttribute(it.key(), it.data());
	}
	uiElement.appendChild(headerPropertiesEl);

	/// We save the savePixmapsInline property in the Form
	TQDomElement inlinePix = domDoc.createElement("pixmapinproject");
	uiElement.appendChild(inlinePix);

	// We create the top class element
	TQDomElement baseClass = domDoc.createElement("class");
	uiElement.appendChild(baseClass);
	TQDomText baseClassV = domDoc.createTextNode(TQWIDGET_OBJECT_NAME_STRING);
	baseClass.appendChild(baseClassV);

	// Save the toplevel widgets, and so the whole Form
	saveWidget(form->objectTree(), uiElement, domDoc);

	// We then save the layoutdefaults element
	TQDomElement layoutDefaults = domDoc.createElement("layoutDefaults");
	layoutDefaults.setAttribute("spacing", TQString::number(form->defaultSpacing()));
	layoutDefaults.setAttribute("margin", TQString::number(form->defaultMargin()));
	uiElement.appendChild(layoutDefaults);

	/// Save tab Stops
	if(form->autoTabStops())
		form->autoAssignTabStops();
	TQDomElement tabStops = domDoc.createElement("tabstops");
	uiElement.appendChild(tabStops);
	for(ObjectTreeListIterator it( form->tabStopsIterator() ); it.current(); ++it)
	{
		TQDomElement tabstop = domDoc.createElement("tabstop");
		tabStops.appendChild(tabstop);
		TQDomText tabStopText = domDoc.createTextNode(it.current()->name());
		tabstop.appendChild(tabStopText);
	}

	// Save the Form 's PixmapCollection
	form->pixmapCollection()->save(uiElement);
	// Save the Form connections
	form->connectionBuffer()->save(uiElement);

	form->commandHistory()->documentSaved();

	m_currentForm = 0;
	m_currentItem = 0;
	//m_currentWidget = 0;

	return true;
}

bool
FormIO::loadFormFromByteArray(Form *form, TQWidget *container, TQByteArray &src, bool preview)
{
	TQString errMsg;
	int errLine;
	int errCol;

	TQDomDocument inBuf;
	bool parsed = inBuf.setContent(src, false, &errMsg, &errLine, &errCol);

	if(!parsed)
	{
		kdDebug() << "WidgetWatcher::load(): " << errMsg << endl;
		kdDebug() << "WidgetWatcher::load(): line: " << errLine << " col: " << errCol << endl;
		return false;
	}

	if (!loadFormFromDom(form, container, inBuf))
		return false;
	if(preview)
		form->setDesignMode(false);
	return true;
}

bool
FormIO::loadFormFromString(Form *form, TQWidget *container, TQString &src, bool preview)
{
	TQString errMsg;
	int errLine;
	int errCol;

#ifdef KEXI_DEBUG_GUI
	form->m_recentlyLoadedUICode = src;
#endif

	TQDomDocument inBuf;
	bool parsed = inBuf.setContent(src, false, &errMsg, &errLine, &errCol);

	if(!parsed)
	{
		kdDebug() << "WidgetWatcher::load(): " << errMsg << endl;
		kdDebug() << "WidgetWatcher::load(): line: " << errLine << " col: " << errCol << endl;
		return false;
	}

	if (!loadFormFromDom(form, container, inBuf))
		return false;
	if(preview)
		form->setDesignMode(false);
	return true;
}

bool
FormIO::loadFormFromFile(Form *form, TQWidget *container, const TQString &filename)
{
	TQString errMsg;
	int errLine;
	int errCol;
	TQString m_filename;

	if(filename.isNull())
	{
		m_filename = KFileDialog::getOpenFileName(TQString(), i18n("*.ui|TQt Designer UI Files"));
		if(m_filename.isNull())
			return false;
	}
	else
		m_filename = filename;

	TQFile file(m_filename);
	if(!file.open(IO_ReadOnly))
	{
		kdDebug() << "Cannot open the file " << filename << endl;
		return false;
	}
	TQTextStream stream(&file);
	TQString text = stream.read();

	TQDomDocument inBuf;
	bool parsed = inBuf.setContent(text, false, &errMsg, &errLine, &errCol);

	if(!parsed)
	{
		kdDebug() << "WidgetWatcher::load(): " << errMsg << endl;
		kdDebug() << "WidgetWatcher::load(): line: " << errLine << " col: " << errCol << endl;
		return false;
	}

	return loadFormFromDom(form, container, inBuf);
}

bool
FormIO::loadFormFromDom(Form *form, TQWidget *container, TQDomDocument &inBuf)
{
	m_currentForm = form;

	TQDomElement ui = inBuf.namedItem("UI").toElement();

	//custom properties
	form->headerProperties()->clear();
	TQDomElement headerPropertiesEl = ui.namedItem("kfd:customHeader").toElement();
	TQDomAttr attr = headerPropertiesEl.firstChild().toAttr();
	while (!attr.isNull() && attr.isAttr()) {
		form->headerProperties()->insert(attr.name().latin1(), attr.value());
		attr = attr.nextSibling().toAttr();
	}
	//update format version information
	uint ver = 1; //the default
	if (form->headerProperties()->contains("version")) {
		bool ok;
		uint v = (*form->headerProperties())["version"].toUInt(&ok);
		if (ok)
			ver = v;
	}
	kdDebug() << "FormIO::loadFormFromDom(): original format version: " << ver << endl;
	form->setOriginalFormatVersion( ver );
	if (ver < KFormDesigner::version()) {
//! @todo We can either 1) convert from old format and later save in a new one or 2) keep old format.
//!     To do this we may need to look at the original format version number.
		kdDebug() << "FormIO::loadFormFromDom(): original format is older than current: " << KFormDesigner::version() << endl;
		form->setFormatVersion( KFormDesigner::version() );
	}
	else
		form->setFormatVersion( ver );

	if (ver > KFormDesigner::version()) {
//! @todo display information about too new format and that "some information will not be available".
		kdDebug() << "FormIO::loadFormFromDom(): original format is newer than current: " << KFormDesigner::version() << endl;
	}

	// Load the pixmap collection
	m_savePixmapsInline = ( (ui.namedItem("pixmapinproject").isNull()) || (!ui.namedItem("images").isNull()) );
	form->pixmapCollection()->load(ui.namedItem("collection"));

	TQDomElement element = ui.namedItem("widget").toElement();
	createToplevelWidget(form, container, element);

	// Loading the tabstops
	TQDomElement tabStops = ui.namedItem("tabstops").toElement();
//	if(tabStops.isNull())
//		return 1;
	if(!tabStops.isNull()) {
		int i = 0;
		uint itemsNotFound = 0;
		for(TQDomNode n = tabStops.firstChild(); !n.isNull(); n = n.nextSibling(), i++)
		{
			TQString name = n.toElement().text();
			ObjectTreeItem *item = form->objectTree()->lookup(name);
			if(!item)
			{
				kdDebug() << "FormIO::loadFormFromDom ERROR : no ObjectTreeItem " << endl;
				continue;
			}
			const int index = form->tabStops()->findRef(item);
			/* Compute a real destination index: "a number of not found items so far". */
			const int realIndex = i - itemsNotFound;
			if((index != -1) && (index != realIndex)) // the widget is not in the same place, so we move it
			{
				form->tabStops()->remove(item);
				form->tabStops()->insert(realIndex, item);
			}
			if(index == -1) {
				itemsNotFound++;
				kdDebug() << "FormIO: item '" << name << "' not in list" << endl;
			}
		}
	}

	// Load the form connections
	form->connectionBuffer()->load(ui.namedItem("connections"));

	m_currentForm = 0;
	m_currentItem = 0;

	return true;
}

/////////////////////////////////////////////////////////////////////////////
///////////// Functions to save/load properties /////////////////////////////
/////////////////////////////////////////////////////////////////////////////

void
FormIO::savePropertyValue(TQDomElement &parentNode, TQDomDocument &tqparent, const char *name, 
	const TQVariant &value, TQWidget *w, WidgetLibrary *lib)
{
	// Widget specific properties and attributes ///////////////
//	kdDebug() << "FormIO::savePropertyValue()  Saving the property: " << name << endl;
	WidgetWithSubpropertiesInterface* subpropIface = dynamic_cast<WidgetWithSubpropertiesInterface*>(w);
	TQWidget *subwidget = w;
	bool addSubwidgetFlag = false;
	int propertyId = w->tqmetaObject()->findProperty(name, true);
	if (propertyId == -1 && subpropIface && subpropIface->subwidget()) { // try property from subwidget
		subwidget = subpropIface->subwidget();
		propertyId = subpropIface->subwidget()->tqmetaObject()->findProperty(name, true);
		addSubwidgetFlag = true;
	}
	if(propertyId == -1)
	{
		kdDebug() << "FormIO::savePropertyValue()  The object doesn't have this property. Let's try the WidgetLibrary." << endl;
		if(lib)
			lib->saveSpecialProperty(w->className(), name, value, w, parentNode, tqparent);
		return;
	}

	const TQMetaProperty *meta = subwidget->tqmetaObject()->property(propertyId, true);
	if (!meta->stored( subwidget )) //not storable
		return;
	TQDomElement propertyE = tqparent.createElement("property");
	propertyE.setAttribute("name", name);
	if (addSubwidgetFlag)
		propertyE.setAttribute("subwidget", "true");

	if(meta && meta->isEnumType())
	{
		// this property is enum or set type
		TQDomElement type;
		TQDomText valueE;

		if(meta->isSetType())
		{
			TQStringList list = TQStringList::fromStrList(meta->valueToKeys(value.toInt()));
			type = tqparent.createElement("set");
			valueE = tqparent.createTextNode(list.join("|"));
			type.appendChild(valueE);
		}
		else
		{
			TQString s = meta->valueToKey(value.toInt());
			type = tqparent.createElement("enum");
			valueE = tqparent.createTextNode(s);
			type.appendChild(valueE);
		}
		propertyE.appendChild(type);
		parentNode.appendChild(propertyE);
		return;
	}

	if(value.type() == TQVariant::Pixmap) {
		TQDomText valueE;
		TQDomElement type = tqparent.createElement("pixmap");
		TQCString property = propertyE.attribute("name").latin1();
//todo		TQCString pixmapName = m_currentItem->widget()->property("pixmapName").toCString();
		if(m_savePixmapsInline /* (js)too risky: || m_currentItem->pixmapName(property).isNull() */)
			valueE = tqparent.createTextNode(saveImage(tqparent, value.toPixmap()));
		else
			valueE = tqparent.createTextNode(m_currentItem->pixmapName(property));
		type.appendChild(valueE);
		propertyE.appendChild(type);
		parentNode.appendChild(propertyE);
		return;
	}

	// Saving a "normal" property
	writeVariant(tqparent, propertyE, value);
	parentNode.appendChild(propertyE);
}

void
FormIO::writeVariant(TQDomDocument &tqparent, TQDomElement &parentNode, TQVariant value)
{
	TQDomElement type;
	TQDomText valueE;

	switch(value.type())
	{
		case TQVariant::String:
		{
			type = tqparent.createElement("string");
			valueE = tqparent.createTextNode(value.toString());
			type.appendChild(valueE);
			break;
		}
		case TQVariant::CString:
		{
			type = tqparent.createElement("cstring");
			valueE = tqparent.createTextNode(value.toString());
			type.appendChild(valueE);
			break;
		}
		case TQVariant::Rect:
		{
			type = tqparent.createElement("rect");
			TQDomElement x = tqparent.createElement("x");
			TQDomElement y = tqparent.createElement("y");
			TQDomElement w = tqparent.createElement("width");
			TQDomElement h = tqparent.createElement("height");
			TQDomText valueX = tqparent.createTextNode(TQString::number(value.toRect().x()));
			TQDomText valueY = tqparent.createTextNode(TQString::number(value.toRect().y()));
			TQDomText valueW = tqparent.createTextNode(TQString::number(value.toRect().width()));
			TQDomText valueH = tqparent.createTextNode(TQString::number(value.toRect().height()));

			x.appendChild(valueX);
			y.appendChild(valueY);
			w.appendChild(valueW);
			h.appendChild(valueH);

			type.appendChild(x);
			type.appendChild(y);
			type.appendChild(w);
			type.appendChild(h);
			break;
		}
		case TQVariant::Color:
		{
			type = tqparent.createElement("color");
			TQDomElement r = tqparent.createElement("red");
			TQDomElement g = tqparent.createElement("green");
			TQDomElement b = tqparent.createElement("blue");
			TQDomText valueR = tqparent.createTextNode(TQString::number(value.toColor().red()));
			TQDomText valueG = tqparent.createTextNode(TQString::number(value.toColor().green()));
			TQDomText valueB = tqparent.createTextNode(TQString::number(value.toColor().blue()));

			r.appendChild(valueR);
			g.appendChild(valueG);
			b.appendChild(valueB);

			type.appendChild(r);
			type.appendChild(g);
			type.appendChild(b);
			break;
		}
		case TQVariant::Bool:
		{
			type = tqparent.createElement("bool");
			//valueE = tqparent.createTextNode(TQString::number(value.toBool()));
			valueE = tqparent.createTextNode(value.toBool() ? "true" : "false");
			type.appendChild(valueE);
			break;
		}
		case TQVariant::Int:
		case TQVariant::UInt:
		{
			type = tqparent.createElement("number");
			valueE = tqparent.createTextNode(TQString::number(value.toInt()));
			type.appendChild(valueE);
			break;
		}
		case TQVariant::Size:
		{
			type = tqparent.createElement("size");
			TQDomElement w = tqparent.createElement("width");
			TQDomElement h = tqparent.createElement("height");
			TQDomText valueW = tqparent.createTextNode(TQString::number(value.toSize().width()));
			TQDomText valueH = tqparent.createTextNode(TQString::number(value.toSize().height()));

			w.appendChild(valueW);
			h.appendChild(valueH);

			type.appendChild(w);
			type.appendChild(h);
			break;
		}
		case TQVariant::Point:
		{
			type = tqparent.createElement("point");
			TQDomElement x = tqparent.createElement("x");
			TQDomElement y = tqparent.createElement("y");
			TQDomText valueX = tqparent.createTextNode(TQString::number(value.toPoint().x()));
			TQDomText valueY = tqparent.createTextNode(TQString::number(value.toPoint().y()));

			x.appendChild(valueX);
			y.appendChild(valueY);

			type.appendChild(x);
			type.appendChild(y);
			break;
		}
		case TQVariant::Font:
		{
			type = tqparent.createElement("font");
			TQDomElement f = tqparent.createElement("family");
			TQDomElement p = tqparent.createElement("pointsize");
			TQDomElement w = tqparent.createElement("weight");
			TQDomElement b = tqparent.createElement("bold");
			TQDomElement i = tqparent.createElement("italic");
			TQDomElement u = tqparent.createElement("underline");
			TQDomElement s = tqparent.createElement("strikeout");
			TQDomText valueF = tqparent.createTextNode(value.toFont().family());
			TQDomText valueP = tqparent.createTextNode(TQString::number(value.toFont().pointSize()));
			TQDomText valueW = tqparent.createTextNode(TQString::number(value.toFont().weight()));
			TQDomText valueB = tqparent.createTextNode(TQString::number(value.toFont().bold()));
			TQDomText valueI = tqparent.createTextNode(TQString::number(value.toFont().italic()));
			TQDomText valueU = tqparent.createTextNode(TQString::number(value.toFont().underline()));
			TQDomText valueS = tqparent.createTextNode(TQString::number(value.toFont().strikeOut()));

			f.appendChild(valueF);
			p.appendChild(valueP);
			w.appendChild(valueW);
			b.appendChild(valueB);
			i.appendChild(valueI);
			u.appendChild(valueU);
			s.appendChild(valueS);

			type.appendChild(f);
			type.appendChild(p);
			type.appendChild(w);
			type.appendChild(b);
			type.appendChild(i);
			type.appendChild(u);
			type.appendChild(s);
			break;
		}
		case TQVariant::Cursor:
		{
			type = tqparent.createElement("cursor");
			valueE = tqparent.createTextNode(TQString::number(value.toCursor().tqshape()));
			type.appendChild(valueE);
			break;
		}
		case TQVariant::SizePolicy:
		{
			type = tqparent.createElement("sizepolicy");
			TQDomElement h = tqparent.createElement("hsizetype");
			TQDomElement v = tqparent.createElement("vsizetype");
			TQDomElement hs = tqparent.createElement("horstretch");
			TQDomElement vs = tqparent.createElement("verstretch");
			TQDomText valueH = tqparent.createTextNode(TQString::number(value.toSizePolicy().horData()));
			TQDomText valueV = tqparent.createTextNode(TQString::number(value.toSizePolicy().verData()));
			TQDomText valueHS = tqparent.createTextNode(TQString::number(value.toSizePolicy().horStretch()));
			TQDomText valueVS = tqparent.createTextNode(TQString::number(value.toSizePolicy().verStretch()));

			h.appendChild(valueH);
			v.appendChild(valueV);
			hs.appendChild(valueHS);
			vs.appendChild(valueVS);

			type.appendChild(h);
			type.appendChild(v);
			type.appendChild(hs);
			type.appendChild(vs);
			break;
		}
		case TQVariant::Time:
		{
			type = tqparent.createElement("time");
			TQDomElement h = tqparent.createElement("hour");
			TQDomElement m = tqparent.createElement("minute");
			TQDomElement s = tqparent.createElement("second");
			TQDomText valueH = tqparent.createTextNode(TQString::number(value.toTime().hour()));
			TQDomText valueM = tqparent.createTextNode(TQString::number(value.toTime().minute()));
			TQDomText valueS = tqparent.createTextNode(TQString::number(value.toTime().second()));

			h.appendChild(valueH);
			m.appendChild(valueM);
			s.appendChild(valueS);

			type.appendChild(h);
			type.appendChild(m);
			type.appendChild(s);
			break;
		}
		case TQVariant::Date:
		{
			type = tqparent.createElement("date");
			TQDomElement y = tqparent.createElement("year");
			TQDomElement m = tqparent.createElement("month");
			TQDomElement d = tqparent.createElement("day");
			TQDomText valueY = tqparent.createTextNode(TQString::number(value.toDate().year()));
			TQDomText valueM = tqparent.createTextNode(TQString::number(value.toDate().month()));
			TQDomText valueD = tqparent.createTextNode(TQString::number(value.toDate().day()));

			y.appendChild(valueY);
			m.appendChild(valueM);
			d.appendChild(valueD);

			type.appendChild(y);
			type.appendChild(m);
			type.appendChild(d);
			break;
		}
		case TQVariant::DateTime:
		{
			type = tqparent.createElement("datetime");
			TQDomElement h = tqparent.createElement("hour");
			TQDomElement m = tqparent.createElement("minute");
			TQDomElement s = tqparent.createElement("second");
			TQDomElement y = tqparent.createElement("year");
			TQDomElement mo = tqparent.createElement("month");
			TQDomElement d = tqparent.createElement("day");
			TQDomText valueH = tqparent.createTextNode(TQString::number(value.toDateTime().time().hour()));
			TQDomText valueM = tqparent.createTextNode(TQString::number(value.toDateTime().time().minute()));
			TQDomText valueS = tqparent.createTextNode(TQString::number(value.toDateTime().time().second()));
			TQDomText valueY = tqparent.createTextNode(TQString::number(value.toDateTime().date().year()));
			TQDomText valueMo = tqparent.createTextNode(TQString::number(value.toDateTime().date().month()));
			TQDomText valueD = tqparent.createTextNode(TQString::number(value.toDateTime().date().day()));

			h.appendChild(valueH);
			m.appendChild(valueM);
			s.appendChild(valueS);
			y.appendChild(valueY);
			mo.appendChild(valueMo);
			d.appendChild(valueD);

			type.appendChild(h);
			type.appendChild(m);
			type.appendChild(s);
			type.appendChild(y);
			type.appendChild(mo);
			type.appendChild(d);
			break;
		}
		default:
			break;
	}

	parentNode.appendChild(type);
}

void
FormIO::savePropertyElement(TQDomElement &parentNode, TQDomDocument &domDoc, const TQString &tagName, const TQString &property, const TQVariant &value)
{
	TQDomElement propertyE = domDoc.createElement(tagName);
	propertyE.setAttribute("name", property);
	writeVariant(domDoc, propertyE, value);
	parentNode.appendChild(propertyE);
}

TQVariant
FormIO::readPropertyValue(TQDomNode node, TQObject *obj, const TQString &name)
{
	TQDomElement tag = node.toElement();
	TQString text = tag.text();
	TQString type = tag.tagName();

	if(type == "string" || type == "cstring")
		return text;
	else if(type == "rect")
	{
		TQDomElement x = node.namedItem("x").toElement();
		TQDomElement y = node.namedItem("y").toElement();
		TQDomElement w = node.namedItem("width").toElement();
		TQDomElement h = node.namedItem("height").toElement();

		int rx = x.text().toInt();
		int ry = y.text().toInt();
		int rw = w.text().toInt();
		int rh = h.text().toInt();

		return TQRect(rx, ry, rw, rh);
	}
	else if(type == "color")
	{
		TQDomElement r = node.namedItem("red").toElement();
		TQDomElement g = node.namedItem("green").toElement();
		TQDomElement b = node.namedItem("blue").toElement();

		int red = r.text().toInt();
		int green = g.text().toInt();
		int blue = b.text().toInt();

		return TQColor(red, green, blue);
	}
	else if(type == "bool")
	{
		if(text == "true")
			return TQVariant(true, 3);
		else if(text == "false")
			return TQVariant(false, 3);
		return TQVariant(text.toInt(), 3);
	}
	else if(type == "number")
	{
		return text.toInt();
	}
	else if(type == "size")
	{
		TQDomElement w = node.namedItem("width").toElement();
		TQDomElement h = node.namedItem("height").toElement();

		return TQSize(w.text().toInt(), h.text().toInt());
	}
	else if(type == "point")
	{
		TQDomElement x = node.namedItem("x").toElement();
		TQDomElement y = node.namedItem("y").toElement();

		return TQPoint(x.text().toInt(), y.text().toInt());
	}
	else if(type == "font")
	{
		TQDomElement fa = node.namedItem("family").toElement();
		TQDomElement p = node.namedItem("pointsize").toElement();
		TQDomElement w = node.namedItem("weight").toElement();
		TQDomElement b = node.namedItem("bold").toElement();
		TQDomElement i = node.namedItem("italic").toElement();
		TQDomElement u = node.namedItem("underline").toElement();
		TQDomElement s = node.namedItem("strikeout").toElement();

		TQFont f;
		f.setFamily(fa.text());
		f.setPointSize(p.text().toInt());
		f.setWeight(w.text().toInt());
		f.setBold(b.text().toInt());
		f.setItalic(i.text().toInt());
		f.setUnderline(u.text().toInt());
		f.setStrikeOut(s.text().toInt());

		return f;
	}
	else if(type == "cursor")
	{
		return TQCursor(text.toInt());
	}
	else if(type == "time")
	{
		TQDomElement h = node.namedItem("hour").toElement();
		TQDomElement m = node.namedItem("minute").toElement();
		TQDomElement s = node.namedItem("second").toElement();

		return TQTime(h.text().toInt(), m.text().toInt(), s.text().toInt());
	}
	else if(type == "date")
	{
		TQDomElement y = node.namedItem("year").toElement();
		TQDomElement m = node.namedItem("month").toElement();
		TQDomElement d = node.namedItem("day").toElement();

		return TQDate(y.text().toInt(), m.text().toInt(), d.text().toInt());
	}
	else if(type == "datetime")
	{
		TQDomElement h = node.namedItem("hour").toElement();
		TQDomElement m = node.namedItem("minute").toElement();
		TQDomElement s = node.namedItem("second").toElement();
		TQDomElement y = node.namedItem("year").toElement();
		TQDomElement mo = node.namedItem("month").toElement();
		TQDomElement d = node.namedItem("day").toElement();

		TQTime t(h.text().toInt(), m.text().toInt(), s.text().toInt());
		TQDate da(y.text().toInt(), mo.text().toInt(), d.text().toInt());

		return TQDateTime(da, t);
	}
	else if(type == "sizepolicy")
	{
		TQDomElement h = node.namedItem("hsizetype").toElement();
		TQDomElement v = node.namedItem("vsizetype").toElement();
		TQDomElement hs = node.namedItem("horstretch").toElement();
		TQDomElement vs = node.namedItem("verstretch").toElement();

		TQSizePolicy s;
		s.setHorData((TQSizePolicy::SizeType)h.text().toInt());
		s.setVerData((TQSizePolicy::SizeType)v.text().toInt());
		s.setHorStretch(hs.text().toInt());
		s.setVerStretch(vs.text().toInt());
		return s;
	}
	else if(type == "pixmap")
	{
		if(m_savePixmapsInline || !m_currentForm || !m_currentItem || !m_currentForm->pixmapCollection()->contains(text))
			return loadImage(tag.ownerDocument(), text);
		else
		{
			m_currentItem->setPixmapName(name.latin1(), text);
			return m_currentForm->pixmapCollection()->getPixmap(text);
		}
		return TQVariant(TQPixmap());
	}
	else if(type == "enum")
		return text;
	else if(type == "set")
	{
		WidgetWithSubpropertiesInterface* subpropIface = dynamic_cast<WidgetWithSubpropertiesInterface*>(obj);
		TQObject *subobject = (subpropIface && subpropIface->subwidget()) ? TQT_TQOBJECT(subpropIface->subwidget()) : obj;
		const int count = subobject->tqmetaObject()->findProperty(name.latin1(), true);
		const TQMetaProperty *meta = count!=-1 ? subobject->tqmetaObject()->property(count, true) : 0;

		if (meta) {
			if (meta->isSetType()) {
				TQStrList keys;
				const TQStringList list( TQStringList::split("|", text) );
				for (TQStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it)
					keys.append((*it).latin1());

				return meta->keysToValue(keys);
			}
		}
		else {
			// Metaproperty not found, probably because subwidget is not created.
			// We will return a string list here with hope that names will 
			// be resolved and translated into an integer value later when subwidget is created,
			// e.g. near KexiFormView::updateValuesForSubproperties()
			return TQStringList::split("|", text);
		}
	}
	return TQVariant();
}

/////////////////////////////////////////////////////////////////////////////
///////////// Functions to save/load widgets ////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

void
FormIO::saveWidget(ObjectTreeItem *item, TQDomElement &tqparent, TQDomDocument &domDoc, bool insideGridLayout)
{
	if (!item)
		return;
	bool savedAlignment = false;
	// we let Spring class handle saving itself
	if(item->className() == "Spring")
	{
		Spring::saveSpring(item, tqparent, domDoc, insideGridLayout);
		return;
	}

	bool resetCurrentForm = false;
	m_currentItem = item;
	if(!m_currentForm) // copying widget
	{
		resetCurrentForm = true;
		m_currentForm = item->container() ? item->container()->form() : item->tqparent()->container()->form();
	}


	WidgetLibrary *lib = m_currentForm->library();
//	if(item->container())
//		lib = item->container()->form()->manager()->lib();
//	else
//		lib = item->tqparent()->container()->form()->manager()->lib();

	// We create the "widget" element
	TQDomElement tclass = domDoc.createElement("widget");
	tqparent.appendChild(tclass);

	if(insideGridLayout)
	{
		tclass.setAttribute("row", item->gridRow());
		tclass.setAttribute("column", item->gridCol());
		if(item->spanMultipleCells())
		{
			tclass.setAttribute("rowspan", item->gridRowSpan());
			tclass.setAttribute("colspan", item->gridColSpan());
		}
	}

	if(!item->tqparent()) // Toplevel widget
		tclass.setAttribute("class", TQWIDGET_OBJECT_NAME_STRING);
	// For compatibility, HBox, VBox and Grid are saved as TQLAYOUTWIDGET_OBJECT_NAME_STRING
	else if(item->widget()->isA("HBox") || item->widget()->isA("VBox") || item->widget()->isA("Grid")
			|| item->widget()->isA("HFlow") || item->widget()->isA("VFlow"))
		tclass.setAttribute("class", TQLAYOUTWIDGET_OBJECT_NAME_STRING);
	else if(item->widget()->isA("CustomWidget"))
		tclass.setAttribute("class", item->className());
	else // Normal widgets
		tclass.setAttribute("class", lib->savingName(item->widget()->className()) );

	savePropertyValue(tclass, domDoc, "name", item->widget()->property("name"), item->widget());

	// Important: save dataSource property FIRST before properties like "tqalignment"
	// - needed when subproperties are defined after subwidget creation, and subwidget is created after setting "dataSource"
	//   (this is the case for KexiDBAutoField)
//! @todo more properties like "dataSource" may needed here...
//	if (-1 != item->widget()->tqmetaObject()->findProperty("dataSource"))
	//	savePropertyValue(tclass, domDoc, "dataSource", item->widget()->property("dataSource"), item->widget());

	// We don't want to save the tqgeometry if the widget is inside a tqlayout (so tqparent.tagName() == "grid" for example)
	if(item && !item->tqparent()) {
		// save form widget size, but not its position
		savePropertyValue(tclass, domDoc, "geometry",
			TQRect( TQPoint(0,0), item->widget()->size()),
			item->widget());
	}
	// normal widget (if == "UI', it means we're copying widget)
	else if(tqparent.tagName() == "widget" || tqparent.tagName() == "UI")
		savePropertyValue(tclass, domDoc, "geometry", item->widget()->property("geometry"), item->widget());

	// Save the buddy widget for a label
	if(item->widget()->inherits(TQLABEL_OBJECT_NAME_STRING) && ((TQLabel*)item->widget())->buddy())
		savePropertyElement(tclass, domDoc, "property", "buddy", ((TQLabel*)item->widget())->buddy()->name());

	// We save every property in the modifProp list of the ObjectTreeItem
	TQVariantMap *map = new TQVariantMap( *(item->modifiedProperties()) );
	TQMap<TQString,TQVariant>::ConstIterator endIt = map->constEnd();
	for(TQMap<TQString,TQVariant>::ConstIterator it = map->constBegin(); it != endIt; ++it)
	{
		const TQCString name( it.key().latin1() );
		if(name == "hAlign" || name == "vAlign" || name == "wordbreak" || name == "tqalignment") {
			if(!savedAlignment) // not to save it twice
			{
				savePropertyValue(tclass, domDoc, "tqalignment", item->widget()->property("tqalignment"), item->widget());
				savedAlignment = true;
			}
		}
		else if(name == "name" || name == "geometry" || name == "tqlayout") {
			// these have already been saved
		}
		else {
			savePropertyValue(tclass, domDoc, it.key().latin1(), item->widget()->property(it.key().latin1()), 
				item->widget(), lib);
		}
	}
	delete map;

	if(item->widget()->isA("CustomWidget")) {
		TQDomDocument doc("TEMP");
		doc.setContent(item->m_unknownProps);
		for(TQDomNode n = doc.firstChild(); !n.isNull(); n = n.nextSibling()) {
			tclass.appendChild(n.cloneNode());
		}

	}
	// Saving container 's tqlayout if there is one
	TQDomElement tqlayout;
	if(item->container() && item->container()->layoutType() != Container::NoLayout)
	{
		if(item->container()->tqlayout()) // there is a tqlayout
		{
			tqlayout = domDoc.createElement("temp");
			savePropertyValue(tqlayout, domDoc, "name", "unnamed", item->widget());
			if(item->modifiedProperties()->contains("layoutMargin"))
				savePropertyElement(tqlayout, domDoc, "property", "margin", item->container()->layoutMargin());
			if(item->modifiedProperties()->contains("layoutSpacing"))
				savePropertyElement(tqlayout, domDoc, "property", "spacing", item->container()->layoutSpacing());
			tclass.appendChild(tqlayout);
		}
	}

	int layoutType = item->container() ? item->container()->layoutType() : Container::NoLayout;
	switch(layoutType) {
		case Container::Grid: // grid tqlayout
		{
			tqlayout.setTagName("grid");
			for(ObjectTreeItem *objIt = item->tqchildren()->first(); objIt; objIt = item->tqchildren()->next())
				saveWidget(objIt, tqlayout, domDoc, true);
			break;
		}
		case Container::HBox: case Container::VBox:
		{
			// as we don't save tqgeometry, we need to sort widgets in the right order, not creation order
			WidgetList *list;
			if(tqlayout.tagName() == "hbox") {
				list = new HorWidgetList(item->container()->form()->toplevelContainer()->widget());
				tqlayout.setTagName("hbox");
			}
			else {
				list = new VerWidgetList(item->container()->form()->toplevelContainer()->widget());
				tqlayout.setTagName("vbox");
			}

			for(ObjectTreeItem *objTree = item->tqchildren()->first(); objTree; objTree = item->tqchildren()->next())
				list->append(objTree->widget());
			list->sort();

			for(TQWidget *obj = list->first(); obj; obj = list->next()) {
				ObjectTreeItem *titem = item->container()->form()->objectTree()->lookup(obj->name());
				if(item)
					saveWidget(titem, tqlayout, domDoc);
			}
			delete list;
			break;
		}
		case Container::HFlow: case Container::VFlow:
		{
			tqlayout.setTagName("grid");
			KexiFlowLayout *flow = static_cast<KexiFlowLayout*>(item->container()->tqlayout());
			if(!flow)  break;
			WidgetList *list = (WidgetList*)flow->widgetList();

			// save some special properties
			savePropertyElement(tqlayout, domDoc, "property", "customLayout", Container::layoutTypeToString(item->container()->layoutType()) );
			savePropertyElement(tqlayout, domDoc, "property", "justify", TQVariant(static_cast<KexiFlowLayout*>(item->container()->tqlayout())->isJustified(), 3) );

			// fill the widget's grid info, ie just simulate grid tqlayout
			item->container()->createGridLayout(true);
			for(TQWidget *obj = list->first(); obj; obj = list->next()) {
				ObjectTreeItem *titem = item->container()->form()->objectTree()->lookup(obj->name());
				if(item)
					saveWidget(titem, tqlayout, domDoc, true); // save grid info for compatibility with TQtDesigner
			}
			delete list;
			break;
		}
		default:
		{
			for(ObjectTreeItem *objIt = item->tqchildren()->first(); objIt; objIt = item->tqchildren()->next())
				saveWidget(objIt, tclass, domDoc);
		}
	}

	addIncludeFileName(lib->includeFileName(item->widget()->className()), domDoc);

	if(resetCurrentForm)
		m_currentForm = 0;
	m_currentItem = 0;
}

void
FormIO::cleanClipboard(TQDomElement &uiElement)
{
	// remove includehints element not needed
	if(!uiElement.namedItem("includehints").isNull())
		uiElement.removeChild(uiElement.namedItem("includehints"));
	// and ensure images and connection are at the end
	if(!uiElement.namedItem("connections").isNull())
		uiElement.insertAfter(uiElement.namedItem("connections"), TQDomNode());
	if(!uiElement.namedItem("images").isNull())
		uiElement.insertAfter(uiElement.namedItem("images"), TQDomNode());
}

void
FormIO::loadWidget(Container *container, const TQDomElement &el, TQWidget *tqparent)
{
	bool resetCurrentForm = false;
	if(!m_currentForm) // pasting widget
	{
		resetCurrentForm = true;
		m_currentForm = container->form();
	}

	// We first look for the widget's name
	TQString wname;
	for(TQDomNode n = el.firstChild(); !n.isNull(); n = n.nextSibling())
	{
		if((n.toElement().tagName() == "property") && (n.toElement().attribute("name") == "name"))
		{
			wname = n.toElement().text();
			break;
		}
	}

	TQWidget *w;
	TQCString classname, alternate;
	// We translate some name (for compatibility)
	if(el.tagName() == "spacer")
		classname = "Spring";
	else if(el.attribute("class") == TQLAYOUTWIDGET_OBJECT_NAME_STRING)
	{
		for(TQDomNode n = el.firstChild(); !n.isNull(); n = n.nextSibling())
		{
			TQString tagName = n.toElement().tagName();
			if(tagName == "property")
				continue;
			if(tagName == "hbox")
				classname = "HBox";
			else if(tagName == "vbox")
				classname = "VBox";
			else if(tagName == "grid") {
				// first, see if it is flow tqlayout
				for(TQDomNode child = n.firstChild(); !child.isNull(); child = child.nextSibling())  {
					if((child.toElement().tagName() == "property") 
						&& (child.toElement().attribute("name") == "customLayout"))
					{
						classname = child.toElement().text().latin1();
						break;
					}
				}

				if(classname.isEmpty()) // normal grid
					classname = "Grid";
			}
		}
	}
	else
	// We check if this classname is an alternate one, and replace it if necessary
	{
		classname = el.attribute("class").latin1();
		alternate = container->form()->library()->classNameForAlternate(classname);
	}

	if(alternate == "CustomWidget")
		w = new CustomWidget(classname, container->widget(), wname.latin1());
	else
	{
		if(!alternate.isNull())
			classname = alternate;

		int widgetOptions = WidgetFactory::DefaultOptions;
		if (!container->form()->designMode()) {
			widgetOptions ^= WidgetFactory::DesignViewMode;
		}

		if(!tqparent)
			w = container->form()->library()->createWidget(classname, container->widget(), 
				wname.latin1(), container, widgetOptions);
		else
			w = container->form()->library()->createWidget(classname, tqparent, wname.latin1(), 
				container, widgetOptions);
	}

	if(!w)
		return;
#if KDE_VERSION >= KDE_MAKE_VERSION(3,4,0) 
//! @todo allow setting this for data view mode as well
	if (m_currentForm->designMode()) {
		//don't generate accelerators for widgets in design mode
		KAcceleratorManager::setNoAccel(w);
	}
#endif
	w->setStyle(&(container->widget()->tqstyle()));
	w->show();

	// We create and insert the ObjectTreeItem at the good place in the ObjectTree
	ObjectTreeItem *item = container->form()->objectTree()->lookup(wname);
	if (!item)  {
		// not yet created
		item =  new ObjectTreeItem(container->form()->library()->displayName(classname), 
			wname, w, container);
		if(tqparent)  {
			ObjectTreeItem *titem = container->form()->objectTree()->lookup(tqparent->name());
			if(titem)
				container->form()->objectTree()->addItem(titem, item);
			else
				kdDebug() << "FORMIO :: ERROR no tqparent widget "  << endl;
		}
		else
			container->form()->objectTree()->addItem(container->objectTree(), item);
	}
	//assign item for its widget if it supports DesignTimeDynamicChildWidgetHandler interface
	//(e.g. KexiDBAutoField)
	if (container->form()->designMode() && dynamic_cast<DesignTimeDynamicChildWidgetHandler*>(w)) {
		dynamic_cast<DesignTimeDynamicChildWidgetHandler*>(w)->assignItem(item);
	}

	m_currentItem = item;
	// if we are inside a Grid, we need to insert the widget in the good cell
	if(container->layoutType() == Container::Grid)  {
		TQGridLayout *tqlayout = (TQGridLayout*)container->tqlayout();
		if(el.hasAttribute("rowspan")) { // widget spans multiple cells
			if(tqlayout)
				tqlayout->addMultiCellWidget(w, el.attribute("row").toInt(), el.attribute("row").toInt() + el.attribute("rowspan").toInt()-1,
					 el.attribute("column").toInt(),  el.attribute("column").toInt() + el.attribute("colspan").toInt()-1);
			 item->setGridPos(el.attribute("row").toInt(),  el.attribute("column").toInt(), el.attribute("rowspan").toInt(),
			   el.attribute("colspan").toInt());
		}
		else  {
			if(tqlayout)
				tqlayout->addWidget(w, el.attribute("row").toInt(), el.attribute("column").toInt());
			item->setGridPos(el.attribute("row").toInt(),  el.attribute("column").toInt(), 0, 0);
		}
	}
	else if(container->tqlayout())
		container->tqlayout()->add(w);

	readChildNodes(item, container, el, w);

	if(item->container() && item->container()->tqlayout())
		item->container()->tqlayout()->activate();

	// We add the autoSaveProperties in the modifProp list of the ObjectTreeItem, so that they are saved later
	TQValueList<TQCString> list(container->form()->library()->autoSaveProperties(w->className()));
	TQValueList<TQCString>::ConstIterator endIt = list.constEnd();
	KFormDesigner::WidgetWithSubpropertiesInterface* subpropIface 
		= dynamic_cast<KFormDesigner::WidgetWithSubpropertiesInterface*>(w);
	TQWidget *subwidget = (subpropIface && subpropIface->subwidget()) ? subpropIface->subwidget() : w;
	for(TQValueList<TQCString>::ConstIterator it = list.constBegin(); it != endIt; ++it) {
		if(subwidget->tqmetaObject()->findProperty(*it, true) != -1)
			item->addModifiedProperty(*it, subwidget->property(*it));
	}

	if(resetCurrentForm)
		m_currentForm = 0;
	m_currentItem = 0;
}

void
FormIO::createToplevelWidget(Form *form, TQWidget *container, TQDomElement &el)
{
	// We first look for the widget's name
	TQString wname;
	for(TQDomNode n = el.firstChild(); !n.isNull(); n = n.nextSibling())
	{
		if((n.toElement().tagName() == "property") && (n.toElement().attribute("name") == "name"))
		{
			wname = n.toElement().text();
			break;
		}

	}
	// And rename the widget and its ObjectTreeItem
	container->setName(wname.latin1());
	if(form->objectTree())
		form->objectTree()->rename(form->objectTree()->name(), wname);
	form->setInteractiveMode(false);

	TQDict<TQLabel>  *oldBuddies = 0;
	if(m_buddies)  // save old buddies (for subforms)
		oldBuddies = m_buddies;
	m_buddies = new TQDict<TQLabel>();
	m_currentItem = form->objectTree();

	readChildNodes(form->objectTree(), form->toplevelContainer(), el, container);

	// Now the Form is fully loaded, we can assign the buddies
	TQDictIterator<TQLabel> it(*m_buddies);
	for(; it.current(); ++it)
	{
		ObjectTreeItem *item = form->objectTree()->lookup(it.currentKey());
		if(!item || !item->widget())
		{
			kdDebug() << "Cannot assign buddy for widget " << it.current()->name() << " to " << it.currentKey() << endl;
			continue;
		}
		it.current()->setBuddy(item->widget());
	}
	delete m_buddies;
	m_buddies = oldBuddies; // and restore it

	m_currentItem = 0;

	form->setInteractiveMode(true);
}

void
FormIO::readChildNodes(ObjectTreeItem *item, Container *container, const TQDomElement &el, TQWidget *w)
{
	TQString eltag = el.tagName();

	WidgetWithSubpropertiesInterface* subpropIface = dynamic_cast<WidgetWithSubpropertiesInterface*>(w);
	TQWidget *subwidget = (subpropIface && subpropIface->subwidget()) ? subpropIface->subwidget() : w;

	for(TQDomNode n = el.firstChild(); !n.isNull(); n = n.nextSibling())
	{
		TQString tag = n.toElement().tagName();
		TQDomElement node = n.toElement();

		if((tag == "property") || (tag == "attribute"))
		{
			TQString name = node.attribute("name");
			//if(name == "geometry")
			//	hasGeometryProp = true;
			if( ((eltag == "grid") || (eltag == "hbox") || (eltag == "vbox")) &&
			      (name == "name")) // we don't care about tqlayout names
				continue;

			if (node.attribute("subwidget")=="true") {
				//this is property for subwidget: remember it for delayed setting
				//because now the subwidget could be not created yet (true e.g. for KexiDBAutoField)
				const TQVariant val( readPropertyValue(node.firstChild(), TQT_TQOBJECT(w), name) );
				kdDebug() << val.toStringList() << endl;
				item->addSubproperty( name.latin1(), val );
				//subwidget->setProperty(name.latin1(), val);
				item->addModifiedProperty( name.latin1(), val );
				continue;
			}

			// We cannot assign the buddy now as the buddy widget may not be created yet
			if(name == "buddy")
				m_buddies->insert(readPropertyValue(node.firstChild(), TQT_TQOBJECT(w), name).toString(), (TQLabel*)w);
			else if(((eltag == "grid") || (eltag == "hbox") || (eltag == "vbox")) &&
			  item->container() && item->container()->tqlayout()) {
			  // We load the margin of a Layout
				if(name == "margin")  {
					int margin = readPropertyValue(node.firstChild(), TQT_TQOBJECT(w), name).toInt();
					item->container()->setLayoutMargin(margin);
					item->container()->tqlayout()->setMargin(margin);
				}
				// We load the spacing of a Layout
				else if(name == "spacing")  {
					int spacing = readPropertyValue(node.firstChild(), TQT_TQOBJECT(w), name).toInt();
					item->container()->setLayoutSpacing(spacing);
					item->container()->tqlayout()->setSpacing(spacing);
				}
				else if((name == "justify")){
					bool justify = readPropertyValue(node.firstChild(), TQT_TQOBJECT(w), name).toBool();
					KexiFlowLayout *flow = static_cast<KexiFlowLayout*>(item->container()->tqlayout());
					if(flow)
						flow->setJustified(justify);
				}
			}
			// If the object doesn't have this property, we let the Factory handle it (maybe a special property)
			else if(subwidget->tqmetaObject()->findProperty(name.latin1(), true) == -1)
			{
				if(w->className() == TQString::tqfromLatin1("CustomWidget"))
					item->storeUnknownProperty(node);
				else {
					bool read = container->form()->library()->readSpecialProperty(
						w->className(), node, w, item);
					if(!read) // the factory doesn't support this property neither
						item->storeUnknownProperty(node);
				}
			}
			else // we have a normal property, let's load it
			{
				TQVariant val( readPropertyValue(node.firstChild(), TQT_TQOBJECT(w), name) );
				if(name == "geometry" && dynamic_cast<FormWidget*>(w)) {
					//fix tqgeometry if needed - this is top level form widget
					TQRect r( val.toRect() );
					if (r.left()<0) //negative X!
						r.moveLeft(0);
					if (r.top()<0) //negative Y!
						r.moveTop(0);
					val = r;
				}
				subwidget->setProperty(name.latin1(), val);
//				int count = w->tqmetaObject()->findProperty(name, true);
//				const TQMetaProperty *meta = w->tqmetaObject()->property(count, true);
//				if(meta && meta->isEnumType()) {
//					val = w->property(name.latin1()); //update: we want a numeric value of enum
//				}
				item->addModifiedProperty(name.latin1(), val);
			}
		}
		else if(tag == "widget") // a child widget
		{
			if(item->container()) // we are a Container
				loadWidget(item->container(), node);
			else
				loadWidget(container, node, w);
		}
		else if(tag == "spacer")  {
			loadWidget(container, node, w);
		}
		else if(tag == "grid") {
			// first, see if it is flow tqlayout
			TQString layoutName;
			for(TQDomNode child = node.firstChild(); !child.isNull(); child = child.nextSibling())  {
				if((child.toElement().tagName() == "property") && (child.toElement().attribute("name") == "customLayout"))  {
					layoutName = child.toElement().text();
					break;
				}
			}

			 if(layoutName == "HFlow") {
				item->container()->m_layType = Container::HFlow;
				KexiFlowLayout *tqlayout = new KexiFlowLayout(item->widget());
				tqlayout->setOrientation(Qt::Horizontal);
				item->container()->m_layout = (TQLayout*)tqlayout;
			}
			else if(layoutName == "VFlow") {
				item->container()->m_layType = Container::VFlow;
				KexiFlowLayout *tqlayout = new KexiFlowLayout(item->widget());
				tqlayout->setOrientation(Qt::Vertical);
				item->container()->m_layout = (TQLayout*)tqlayout;
			}
			else { // grid tqlayout
				item->container()->m_layType = Container::Grid;
				TQGridLayout *tqlayout = new TQGridLayout(item->widget(), 1, 1);
				item->container()->m_layout = (TQLayout*)tqlayout;
			}
			readChildNodes(item, container, node, w);
		}
		else if(tag == "vbox")  {
			item->container()->m_layType = Container::VBox;
			TQVBoxLayout *tqlayout = new TQVBoxLayout(item->widget());
			item->container()->m_layout = (TQLayout*)tqlayout;
			readChildNodes(item, container, node, w);
		}
		else if(tag == "hbox") {
			item->container()->m_layType = Container::HBox;
			TQHBoxLayout *tqlayout = new TQHBoxLayout(item->widget());
			item->container()->m_layout = (TQLayout*)tqlayout;
			readChildNodes(item, container, node, w);
		}
		else {// unknown tag, we let the Factory handle it
			if(w->className() == TQString::tqfromLatin1("CustomWidget"))
				item->storeUnknownProperty(node);
			else {
				bool read = container->form()->library()->readSpecialProperty(
					w->className(), node, w, item);
				if(!read) // the factory doesn't suport this property neither
					item->storeUnknownProperty(node);
			}
		}
	}
}

/////////////////////////////////////////////////////////////////////////////
///////////// Helper functions //////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

void
FormIO::addIncludeFileName(const TQString &include, TQDomDocument &domDoc)
{
	if(include.isEmpty())
		return;

	TQDomElement includes;
	TQDomElement uiEl = domDoc.namedItem("UI").toElement();
	if(uiEl.namedItem("includehints").isNull())
	{
		includes = domDoc.createElement("includehints");
		uiEl.appendChild(includes);
	}
	else
		includes = uiEl.namedItem("includehints").toElement();

	// Check if this include has already been saved, and return if it is the case
	for(TQDomNode n = includes.firstChild(); !n.isNull(); n = n.nextSibling())
	{
		if(n.toElement().text() == include)
			return;
	}

	TQDomElement includeHint = domDoc.createElement("includehint");
	includes.appendChild(includeHint);
	TQDomText includeText = domDoc.createTextNode(include);
	includeHint.appendChild(includeText);
}

////////  TQt Designer code: these two functions were copied (and adapted) from TQt Designer for compatibility ////////

TQString
FormIO::saveImage(TQDomDocument &domDoc, const TQPixmap &pixmap)
{
	TQDomNode node = domDoc.namedItem("images");
	TQDomElement images;
	if(node.isNull())
	{
		images = domDoc.createElement("images");
		TQDomElement ui = domDoc.namedItem("UI").toElement();
		ui.appendChild(images);
	}
	else
		images = node.toElement();

	int count = images.childNodes().count();
	TQDomElement image = domDoc.createElement("image");
	TQString name = "image" + TQString::number(count);
	image.setAttribute("name", name);

	TQImage img = pixmap.convertToImage();
	TQByteArray ba;
	TQBuffer buf(ba);
	buf.open( IO_WriteOnly | IO_Translate );
	TQString format = img.depth() > 1 ? "XPM" : "XBM";
	TQImageIO iio( &buf, format.latin1() );
	iio.setImage( img );
	iio.write();
	buf.close();
	TQByteArray bazip = tqCompress( ba );
	ulong len = bazip.size();

	TQDomElement data = domDoc.createElement("data");
	data.setAttribute("format", format + ".GZ");
	data.setAttribute("length", ba.size());

	static const char hexchars[] = "0123456789abcdef";
	TQString content;
	for(int i = 4; i < (int)len; ++i)
	{
	uchar s = (uchar) bazip[i];
	content += hexchars[s >> 4];
	content += hexchars[s & 0x0f];
	}

	TQDomText text = domDoc.createTextNode(content);
	data.appendChild(text);
	image.appendChild(data);
	images.appendChild(image);

	return name;
}

TQPixmap
FormIO::loadImage(TQDomDocument domDoc, const TQString& name)
{
	TQDomElement images = domDoc.namedItem("UI").namedItem("images").toElement();
	if(images.isNull())
		return 0;

	TQDomElement image;
	for(TQDomNode n = images.firstChild(); !n.isNull(); n = n.nextSibling())
	{
		if((n.toElement().tagName() == "image") && (n.toElement().attribute("name") == name))
		{
			image = n.toElement();
			break;
		}
	}

	TQPixmap pix;
	TQString data = image.namedItem("data").toElement().text();
	const int lengthOffset = 4;
	int baSize = data.length() / 2 + lengthOffset;
	uchar *ba = new uchar[baSize];
	for(int i = lengthOffset; i < baSize; ++i)
	{
		char h = data[2 * (i-lengthOffset)].latin1();
		char l = data[2 * (i-lengthOffset) + 1].latin1();
		uchar r = 0;
		if(h <= '9')
		    r += h - '0';
		else
		    r += h - 'a' + 10;
		r = r << 4;
		if(l <= '9')
		    r += l - '0';
		else
		    r += l - 'a' + 10;
		ba[i] = r;
	}

	TQString format = image.namedItem("data").toElement().attribute("format", "PNG");
	if((format == "XPM.GZ") || (format == "XBM.GZ"))
	{
		ulong len = image.attribute("length").toULong();
		if(len < data.length() * 5)
		    len = data.length() * 5;
		// tqUncompress() expects the first 4 bytes to be the expected length of
		// the uncompressed data
		ba[0] = ( len & 0xff000000 ) >> 24;
		ba[1] = ( len & 0x00ff0000 ) >> 16;
		ba[2] = ( len & 0x0000ff00 ) >> 8;
		ba[3] = ( len & 0x000000ff );
		TQByteArray baunzip = tqUncompress(ba, baSize);
		pix.loadFromData( (const uchar*)baunzip.data(), baunzip.size(), format.left(format.find('.')).latin1() );
	}
	else
		pix.loadFromData( (const uchar*)ba+lengthOffset, baSize-lengthOffset, format.latin1() );

	delete[] ba;

	return pix;
}

//////// End of TQt Designer code ////////////////////////////////////////////////////////

#include "formIO.moc"