aboutsummaryrefslogtreecommitdiffstats
path: root/src/modules/classeditor/classeditor.cpp
blob: ef8c1e187de1459c21acb20e5c0723799f42fcba (about) (plain) (blame)
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
/************************************************************************
 * UnrealIRCd - Unreal Internet Relay Chat Daemon - src/api-rpc.c
 * (c) 2022- Bram Matthys and The UnrealIRCd Team
 * License: GPLv2 or later
 */

/** @file
 * @brief RPC API
 */
#include "unrealircd.h"

/** This is the RPC API used for web requests.
 * For an overview of available RPC's (not the API)
 * see https://www.unrealircd.org/docs/RPC
 * @defgroup RPCAPI RPC API
 * @{
 */

/** List of RPC handlers */
MODVAR RPCHandler *rpchandlers = NULL;

/* Forward declarations */
static void unload_rpc_handler_commit(RPCHandler *m);

/** Adds a new RPC handler.
 * @param module The module which owns this RPC handler.
 * @param mreq   The details of the request such as the method name, callback, etc.
 * @return Returns the handle to the RPC handler if successful, otherwise NULL.
 *         The module's error code contains specific information about the
 *         error.
 */
RPCHandler *RPCHandlerAdd(Module *module, RPCHandlerInfo *mreq)
{
	RPCHandler *m;
	ModuleObject *mobj;

	/* Some consistency checks to avoid a headache for module devs later on: */
	if (!mreq->method || !mreq->call)
	{
		unreal_log(ULOG_ERROR, "module", "RPCHANDLERADD_API_ERROR", NULL,
			   "RPCHandlerAdd() from module $module_name: "
			   "Missing required fields.",
			   log_data_string("module_name", module->header->name));
		abort();
	}

	m = RPCHandlerFind(mreq->method);
	if (m)
	{
		if (m->unloaded)
		{
			m->unloaded = 0;
		} else {
			if (module)
				module->errorcode = MODERR_EXISTS;
			return NULL;
		}
	} else {
		/* New RPC handler */
		m = safe_alloc(sizeof(RPCHandler));
		safe_strdup(m->method, mreq->method);
		AddListItem(m, rpchandlers);
	}
	/* Add or update the following fields: */
	m->owner = module;
	m->flags = mreq->flags;
	m->loglevel = mreq->loglevel;
	if (!valid_loglevel(m->loglevel))
		m->loglevel = ULOG_INFO;
	m->call = mreq->call;

	/* Add module object */
	mobj = safe_alloc(sizeof(ModuleObject));
	mobj->type = MOBJ_RPC;
	mobj->object.rpc = m;
	AddListItem(mobj, module->objects);
	module->errorcode = MODERR_NOERROR;

	return m;
}

/** Returns the RPC handler for the given method name.
 * @param method The method to search for.
 * @return Returns the handle to the RPC handler,
 *         or NULL if not found.
 */
RPCHandler *RPCHandlerFind(const char *method)
{
	RPCHandler *m;

	for (m = rpchandlers; m; m = m->next)
	{
		if (!strcasecmp(method, m->method))
			return m;
	}
	return NULL;
}

/** Remove the specified RPC handler - modules should not call this.
 * This is done automatically for modules on unload, so is only called internally.
 * @param m The PRC handler to remove.
 */
void RPCHandlerDel(RPCHandler *m)
{
	if (m->owner)
	{
		ModuleObject *mobj;
		for (mobj = m->owner->objects; mobj; mobj = mobj->next) {
			if (mobj->type == MOBJ_RPC && mobj->object.rpc == m)
			{
				DelListItem(mobj, m->owner->objects);
				safe_free(mobj);
				break;
			}
		}
		m->owner = NULL;
	}

	if (loop.rehashing)
		m->unloaded = 1;
	else
		unload_rpc_handler_commit(m);
}

/** @} */

static void unload_rpc_handler_commit(RPCHandler *m)
{
	/* This is an unusual operation, I think we should log it. */
	unreal_log(ULOG_INFO, "module", "UNLOAD_RPC_HANDLER", NULL,
	           "Unloading RPC handler for '$method'",
	           log_data_string("method", m->method));

	/* Destroy the object */
	DelListItem(m, rpchandlers);
	safe_free(m->method);
	safe_free(m);
}

void unload_all_unused_rpc_handlers(void)
{
	RPCHandler *m, *m_next;

	for (m = rpchandlers; m; m = m_next)
	{
		m_next = m->next;
		if (m->unloaded)
			unload_rpc_handler_commit(m);
	}
}
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
//=============================================================================
//
//   File : classeditor.cpp
//   Creation date : Mon Feb 15 2010 14:35:55 CEST by Carbone Alessandro
//
//   This file is part of the KVirc irc client distribution
//   Copyright (C) 2010 Alessandro Carbone (elfonol at gmail dot com)
//
//   This program is FREE software. You can redistribute it and/or
//   modify it under the linkss of the GNU General Public License
//   as published by the Free Software Foundation; either version 2
//   of the License, or (at your opinion) any later version.
//
//   This program is distributed in the HOPE that it will be USEFUL,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//   See the GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program. If not, write to the Free Software Foundation,
//   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//=============================================================================


#include "classeditor.h"

#include "kvi_iconmanager.h"
#include "kvi_options.h"
#include "kvi_locale.h"
#include "kvi_imagedialog.h"
#include "kvi_config.h"
#include "kvi_filedialog.h"
#include "kvi_fileutils.h"
#include "kvi_scripteditor.h"
#include "kvi_debug.h"
#include "kvi_app.h"
#include "kvi_frame.h"
#include "kvi_qstring.h"
#include "kvi_kvs_kernel.h"
#include "kvi_kvs_object_class.h"
#include "kvi_kvs_object_controller.h"
#include "kvi_filedialog.h"
#include "kvi_cmdformatter.h"
#include "kvi_module.h"
#include "kvi_tal_vbox.h"
#include "kvi_fileextensions.h"
#include "kvi_modulemanager.h"

#include <QList>
#include <QSplitter>
#include <QLayout>
#include <QToolTip>
#include <QPushButton>
#include <QDir>
#include <QMessageBox>
#include <QInputDialog>
#include <QRegExp>
#include <QTreeWidget>
#include <QMouseEvent>
#include <QList>
#include <QPainter>
#include <QBrush>

extern KviClassEditorWindow * g_pClassEditorWindow;
extern KviModule * g_pClassEditorModule;

KviClassEditorTreeWidgetItem::KviClassEditorTreeWidgetItem(QTreeWidget * pTreeWidget,Type eType,const QString &szName)
: QTreeWidgetItem(pTreeWidget), KviHeapObject(), m_eType(eType)
{
	setName(szName);
	m_cPos=0;

	if(eType==KviClassEditorTreeWidgetItem::Namespace) setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NAMESPACE))));
	else setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_CLASS))));
	m_bClassModified=false;
}

KviClassEditorTreeWidgetItem::KviClassEditorTreeWidgetItem(KviClassEditorTreeWidgetItem * pParentItem,Type eType,const QString &szName)
: QTreeWidgetItem(pParentItem), m_eType(eType)
{
	setName(szName);
	m_cPos=0;
	setFlags(Qt::ItemIsEditable|Qt::ItemIsEnabled|Qt::ItemIsSelectable);
	if(eType==KviClassEditorTreeWidgetItem::Namespace)
		setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NAMESPACE))));
	else if(eType==KviClassEditorTreeWidgetItem::Class)
		setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_CLASS))));
	else setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_FUNCTION))));
	m_bClassModified=false;
}

void KviClassEditorTreeWidgetItem::setClassNotBuilt(bool bModified)
{
	m_bClassModified=bModified;
	if (bModified)
		setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_CLASSNOTBUILT))));
	else setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_CLASS))));
}

void KviClassEditorTreeWidgetItem::setName(const QString & szName)
{
	m_szName = szName;
	setText(0,m_szName);
}

void KviClassEditorTreeWidgetItem::setType(Type t)
{
	m_eType=t;
	if(t==KviClassEditorTreeWidgetItem::Namespace)
		setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NAMESPACE))));
	else if(t==KviClassEditorTreeWidgetItem::Class)
		setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_ALIAS))));
	else setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SPAM))));
}

KviClassEditorTreeWidget::KviClassEditorTreeWidget(QWidget * par)
: QTreeWidget(par)
{
	setColumnCount (1);
	setHeaderLabel(__tr2qs_ctx("Class","editor"));
	setSelectionMode(QAbstractItemView::ExtendedSelection);
	setSortingEnabled(true);
	setRootIsDecorated(true);
	setAnimated(true);
}

KviClassEditorTreeWidget::~KviClassEditorTreeWidget()
{
	//remove and delete all items
	clear();
}

void KviClassEditorTreeWidget::mousePressEvent (QMouseEvent * e)
{
	if (e->button() == Qt::RightButton)
	{
		QTreeWidgetItem *i=itemAt(e->pos());
		if (i) emit rightButtonPressed(i,QCursor::pos());
	}
	QTreeWidget::mousePressEvent(e);
}
KviClassEditor::KviClassEditor(QWidget * par)
: QWidget(par)
{
	m_pClasses=new KviPointerHashTable<QString,KviClassEditorTreeWidgetItem>(100,false);
	m_pClasses->setAutoDelete(false);
	// m_bSaving = false;
	m_pLastEditedItem = 0;
	m_pLastClickedItem = 0;
	m_szDir = QDir::homePath();

	QGridLayout * l = new QGridLayout(this);

	m_pSplitter = new QSplitter(Qt::Horizontal,this);
	m_pSplitter->setOpaqueResize(false);
	l->addWidget(m_pSplitter,0,0);

	KviTalVBox * box = new KviTalVBox(m_pSplitter);
	box->setSpacing(0);
	box->setMargin(0);
	m_pTreeWidget = new KviClassEditorTreeWidget(box);

	box = new KviTalVBox(m_pSplitter);

	KviTalHBox * hbox = new KviTalHBox(box);
	hbox->setSpacing(0);
	hbox->setMargin(0);
	m_pClassNameLabel = new QLabel(__tr2qs_ctx("No item selected","editor"),hbox);
	m_pClassNameRenameButton = new QPushButton(__tr2qs_ctx("Rename","editor"),hbox);
	m_pClassNameRenameButton->setEnabled(false);
	connect(m_pClassNameRenameButton,SIGNAL(clicked()),this,SLOT(renameItem()));
	hbox->setStretchFactor(m_pClassNameLabel,2);
	m_pClassNameRenameButton->setToolTip(__tr2qs_ctx("Edit the class or namespace name","editor"));

	hbox = new KviTalHBox(box);
	hbox->setSpacing(0);
	hbox->setMargin(0);

	m_pInheritsClassNameLabel=new QLabel(__tr2qs_ctx("No item selected","editor"),hbox);

	hbox = new KviTalHBox(box);
	hbox->setSpacing(0);
	hbox->setMargin(0);
	m_pMemberFunctionNameLabel = new QLabel(__tr2qs_ctx("No item selected","editor"),hbox);
	m_pMemberFunctionNameRenameButton = new QPushButton(__tr2qs_ctx("Rename","editor"),hbox);
	m_pMemberFunctionNameRenameButton->setEnabled(false);
	connect(m_pMemberFunctionNameRenameButton,SIGNAL(clicked()),this,SLOT(renameItem()));
	hbox->setStretchFactor(m_pMemberFunctionNameLabel,2);
	m_pMemberFunctionNameRenameButton->setToolTip(__tr2qs_ctx("Edit the function member name","editor"));



	m_pEditor = KviScriptEditor::createInstance(box);
	m_pEditor->setFocus();

	/*  connect(m_pEditor,SIGNAL(find(const QString &)),this,SLOT(slotFindWord(const QString &)));
	connect(m_pEditor,SIGNAL(replaceAll(const QString &,const QString &)),this,SLOT(slotReplaceAll(const QString &,const QString &)));
	*/
	m_pContextPopup = new KviTalPopupMenu(this);

	oneTimeSetup();

	currentItemChanged(0,0);
}
KviClassEditor::~KviClassEditor()
{
	m_pClasses->clear();
	delete m_pClasses;
}

void KviClassEditor::buildFullItemPath(KviClassEditorTreeWidgetItem * it, QString & szBuffer)
{
	if (!it) return;
	szBuffer.prepend(it->name()+"::");
	it=(KviClassEditorTreeWidgetItem*)it->parent();
	while(it)
	{
		QString tmp = it->name();
		if(!tmp.isEmpty())
		{
			szBuffer.prepend("::");
			szBuffer.prepend(tmp);
		}
		it = (KviClassEditorTreeWidgetItem*)it->parent();
	}
}

QString KviClassEditor::buildFullClassName(KviClassEditorTreeWidgetItem * it)
{
	if(!it) return QString();
	QString szName = it->name();
	KviClassEditorTreeWidgetItem * nit =(KviClassEditorTreeWidgetItem *)it->parent();
	while(nit)
	{
		QString tmp = nit->name();
		if(!tmp.isEmpty())
		{
			szName.prepend("::");
			szName.prepend(tmp);
		}
		nit = (KviClassEditorTreeWidgetItem *)nit->parent();
	}
	return szName;
}

KviClassEditorTreeWidgetItem * KviClassEditor::findTopLevelItem(const QString & szName)
{
	for(int i=0;i<m_pTreeWidget->topLevelItemCount();i++)
	{
	if (KviQString::equalCI(m_pTreeWidget->topLevelItem(i)->text(0),szName))
		return (KviClassEditorTreeWidgetItem*)m_pTreeWidget->topLevelItem(i);
	}
	return 0;
}

KviClassEditorTreeWidgetItem * KviClassEditor::findItem(const QString & szFullName)
{
	QStringList lNamespaces=szFullName.split("::");
	if(!lNamespaces.count()) return 0;
	KviClassEditorTreeWidgetItem *pItem=findTopLevelItem(lNamespaces.at(0));
	if (!pItem) return 0;
	bool bFound;
	for(int i=1;i<lNamespaces.count();i++)
	{
		bFound=false;
		for(int j=0;j<pItem->childCount();j++)
		{
			if (KviQString::equalCI(pItem->child(j)->text(0),lNamespaces.at(i)))
			{
				pItem=( KviClassEditorTreeWidgetItem *)pItem->child(j);
				bFound=true;
				break;
			}
		}
		if (!bFound) return 0;
	}
	return  (KviClassEditorTreeWidgetItem *)pItem;
}

bool KviClassEditor::itemExists(const QString & szFullName)
{
	if (findItem(szFullName)) return true;
	else return false;
}

KviClassEditorTreeWidgetItem * KviClassEditor::createFullItem(const QString & szFullName)
{
	QStringList lNamespaces=szFullName.split("::");
	if(!lNamespaces.count()) return 0;
	if (lNamespaces.count()==1) return new KviClassEditorTreeWidgetItem(m_pTreeWidget,KviClassEditorTreeWidgetItem::Class,lNamespaces.at(0));
	KviClassEditorTreeWidgetItem *pItem=findTopLevelItem(lNamespaces.at(0));
	if (!pItem) pItem=new KviClassEditorTreeWidgetItem(m_pTreeWidget,KviClassEditorTreeWidgetItem::Namespace,lNamespaces.at(0));
	bool bFound;
	int i;
	for(i=1;i<lNamespaces.count()-1;i++)
	{
		bFound=false;
		for(int j=0;j<pItem->childCount();j++)
		{
			if (KviQString::equalCI(pItem->child(j)->text(0),lNamespaces.at(i)))
			{
				pItem=( KviClassEditorTreeWidgetItem *)pItem->child(j);
				bFound=true;
				break;
			}
		}
		if (!bFound)
		pItem=new KviClassEditorTreeWidgetItem(pItem,KviClassEditorTreeWidgetItem::Namespace,lNamespaces.at(i));
	}
	return new KviClassEditorTreeWidgetItem(pItem,KviClassEditorTreeWidgetItem::Class,lNamespaces.at(i));
}
KviClassEditorTreeWidgetItem * KviClassEditor::createFullNamespace(const QString & szFullName)
{
	QStringList lNamespaces=szFullName.split("::");
	debug("createfullnamespace %s",szFullName.toUtf8().data());
	if(!lNamespaces.count()) return 0;
	KviClassEditorTreeWidgetItem *pItem=findTopLevelItem(lNamespaces.at(0));
	if (!pItem) pItem=new KviClassEditorTreeWidgetItem(m_pTreeWidget,KviClassEditorTreeWidgetItem::Namespace,lNamespaces.at(0));
	if (lNamespaces.count()==1) return pItem;
	bool bFound;
	int i;
	for(i=1;i<lNamespaces.count()-1;i++)
	{
		bFound=false;
		for(int j=0;j<pItem->childCount();j++)
		{
			if (KviQString::equalCI(pItem->child(j)->text(0),lNamespaces.at(i)))
			{
				pItem=( KviClassEditorTreeWidgetItem *)pItem->child(j);
				bFound=true;
				break;
			}
		}
		if (!bFound)
			pItem=new KviClassEditorTreeWidgetItem(pItem,KviClassEditorTreeWidgetItem::Namespace,lNamespaces.at(i));
	}
	return new KviClassEditorTreeWidgetItem(pItem,KviClassEditorTreeWidgetItem::Namespace,lNamespaces.at(i));
}

void KviClassEditor::oneTimeSetup()
{
	QString szPath;
	g_pApp->getLocalKvircDirectory(szPath,KviApp::Classes);
	QDir d(szPath);
	QStringList sl;
	sl = d.entryList(QDir::Files);
	KviKvsObjectClass *pClass;
	KviClassEditorTreeWidgetItem *pClassItem;
	for(int i=0;i<sl.count();i++)
	{
		QString szClassName=sl.at(i);
		szClassName.replace("--","::");
		if (szClassName!=".." && szClassName!=".")
		{
			szClassName.chop(4);
			pClassItem = createFullItem(szClassName);
			pClass = KviKvsKernel::instance()->objectController()->lookupClass(szClassName);
			KviClassEditorTreeWidgetItem *pFunctionItem;
			if (pClass)
			{
				KviPointerHashTableIterator<QString,KviKvsObjectFunctionHandler>  it(* pClass->getHandlers());
				m_pClasses->insert(szClassName,pClassItem);
				KviKvsObjectClass *pParentClass=pClass->parentClass();
				pClassItem->setInheritsClass(pParentClass->name());
				while(it.current())
				{
					QString szCode;
					KviKvsObjectFunctionHandler *handler=pClass->lookupFunctionHandler(it.currentKey());
					if (pClass->isScriptHandler(it.currentKey()))
					{
						pFunctionItem=new KviClassEditorTreeWidgetItem(pClassItem,KviClassEditorTreeWidgetItem::Method,it.currentKey());
						pClass->getFunctionCode(szCode,*handler);
						pFunctionItem->setBuffer(szCode);
						if(handler->flags() & KviKvsObjectFunctionHandler::Internal) pFunctionItem->setInternalFunction(true);
					}
					++it;
				}
			}
		}
	}

	g_pModuleManager->getModule("objects");
	KviPointerHashTableIterator<QString,KviKvsObjectClass> it(*KviKvsKernel::instance()->objectController()->classDict());
	while(KviKvsObjectClass * pClass=it.current())
	{
		if (pClass->isBuiltin())m_pClasses->insert(it.currentKey(),0);
		++it;
	}
	loadNotBuiltClasses();
	connect(m_pTreeWidget,SIGNAL(currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)),this,SLOT(currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)));
	m_pTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(m_pTreeWidget,SIGNAL(customContextMenuRequested(const QPoint &)),this,SLOT(customContextMenuRequested(const QPoint &)));
}

/*
void KviClassEditor::classRefresh(const QString & szName)
{
	if(m_bSaving)
		return;
	KviClassEditorTreeWidgetItem * item;
	KviKvsScript * class = KviKvsClassManager::instance()->classDict()->find(szName);
	item = createFullItem(szName);
	if(item!=m_pLastEditedItem)
	{
		item->setBuffer(class->code());
		return;
	}
	if(
		QMessageBox::warning(0,__tr2qs_ctx("OverWrite Current Class","editor"),
				__tr2qs_ctx("An external script has changed the class you are currently editing. Do you want to accept the external changes?","editor"),
				QMessageBox::Yes,QMessageBox::No|QMessageBox::Default|QMessageBox::Escape) != QMessageBox::Yes
		)
		return;
	item->setBuffer(class->code());
	m_pEditor->setText(class->code());
}

void KviClassEditor::itemRenamed(QTreeWidgetItem * it, int col)
{
	if(it!=m_pLastEditedItem) return;

	((KviClassEditorTreeWidgetItem *)it)->setName(it->text(col));
	QString szNam = buildFullItemName((KviClassEditorTreeWidgetItem *)it);
	QString szLabelText;
	if(((KviClassEditorTreeWidgetItem *)it)->isNamespace())
		szLabelText = __tr2qs_ctx("Namespace","editor");
	else
		szLabelText = __tr2qs_ctx("Class","editor");
	szLabelText += ": <b>";
	szLabelText += szNam;
	szLabelText += "</b>";
	m_pClassNameLabel->setText(szLabelText);
}
*/

bool KviClassEditor::hasSelectedItems()
{
	return m_pTreeWidget->selectedItems().count() ? 1 : 0;
}

bool KviClassEditor::itemExists(QTreeWidgetItem * pSearchFor)
{
	if(!pSearchFor) return false;
	if(m_pClasses->findRef((KviClassEditorTreeWidgetItem*) pSearchFor)) return true;
	else return false;
}

/*
void KviClassEditor::appendAllItems(KviPointerList<KviClassEditorTreeWidgetItem> * l, KviClassEditorTreeWidgetItem::Type eType)
{
	for (int i=0;i<m_pTreeWidget->topLevelItemCount();i++)
	{
		if (((KviClassEditorTreeWidgetItem *)m_pTreeWidget->topLevelItem(i))->type()==eType)
		{
			l->append(((KviClassEditorTreeWidgetItem *)m_pTreeWidget->topLevelItem(i)));
		}
		else
		{
			appendAllItemsRecursive(l,m_pTreeWidget->topLevelItem(i),eType);
		}
	}
}

void KviClassEditor::appendAllItemsRecursive(KviPointerList<KviClassEditorTreeWidgetItem> * l, QTreeWidgetItem * pStartFrom, KviClassEditorTreeWidgetItem::Type eType)
{
	for (int i=0;i<pStartFrom->childCount();i++)
	{
		if (((KviClassEditorTreeWidgetItem *)pStartFrom->child(i))->type()==eType)
		{
			l->append((KviClassEditorTreeWidgetItem *)pStartFrom->child(i));
		}
		else
		{
			appendAllItemsRecursive(l,pStartFrom->child(i),eType);
		}
	}
}
*/
bool KviClassEditor::classExists(QString & szFullItemName)
{
	if (m_pClasses->find(szFullItemName)) return true;
	else return false;
}

bool KviClassEditor::namespaceExists(QString & szFullItemName)
{
	/*KviPointerList<KviClassEditorTreeWidgetItem> l;
	l.setAutoDelete(false);

	appendAllItems(&l,KviClassEditorTreeWidgetItem::Namespace);
	for(KviClassEditorTreeWidgetItem * it = l.first();it;it = l.next())
	{
		if (KviQString::equalCI(buildFullItemName(it),szFullItemName))
		{
			return true;
		}
	}*/
	return false;
}
void KviClassEditor::renameFunction()
{
	KviClassEditorTreeWidgetItem *pFunction=m_pLastEditedItem;
	QString szClassName = ((KviClassEditorTreeWidgetItem*)pFunction->parent())->name();
	QString szFunctionName = pFunction->name();
	KviClassEditorTreeWidgetItem *pParentClass = (KviClassEditorTreeWidgetItem*) pFunction->parent();

	QString szNewFunctionName = szFunctionName;
	bool bInternal;
	bool bOldinternal=bInternal;
	askForFunction(szNewFunctionName, &bInternal,szClassName);
	if (KviQString::equalCI(szFunctionName,szNewFunctionName) && (bInternal==bOldinternal)) return;
	if (functionExists(szNewFunctionName,pParentClass))
	{
		g_pClassEditorModule->lock();
		QMessageBox::information(this,
			__tr2qs_ctx("Function already exists","editor"),
			__tr2qs_ctx("This name is already in use. Please choose another one.","editor"),
			__tr2qs_ctx("Ok, Let me try again...","editor"));
		g_pClassEditorModule->unlock();
		return;
	}
	pFunction->setName(szNewFunctionName);
	pFunction->setInternalFunction(bInternal);
	pParentClass->setClassNotBuilt(true);
	KviPointerList<KviClassEditorTreeWidgetItem> pInheritedClasses;
	searchInheritedClasses(szClassName,pInheritedClasses);
	for(unsigned int i=0;i<pInheritedClasses.count();i++)
		pInheritedClasses.at(i)->setClassNotBuilt(true);
	activateItem(pFunction);
	KviKvsObjectClass *pClass;
	pClass = KviKvsKernel::instance()->objectController()->lookupClass(szClassName);
	//if (pClass) KviKvsKernel::instance()->objectController()->deleteClass(pClass);

}
bool KviClassEditor::functionExists(const QString &szFunctionName, KviClassEditorTreeWidgetItem *pClass)
{
	for(int i=0;i<pClass->childCount();i++)
	{
		if(KviQString::equalCI(szFunctionName,((KviClassEditorTreeWidgetItem *)pClass->child(i))->name())) return true;
	}
	return false;
}

void KviClassEditor::renameItem()
{
	if(!m_pLastEditedItem)return;
	if(m_pLastEditedItem->isClass()) renameClass(m_pLastEditedItem);
	else if(m_pLastEditedItem->isNamespace()) renameNamespace(m_pLastEditedItem);
	else renameFunction();
}
void KviClassEditor::renameClass(KviClassEditorTreeWidgetItem *pClassItem)
{
	QString szClassName = buildFullClassName(pClassItem);
	QString szNewClassName = szClassName;

	QString szInheritsClassName = pClassItem->InheritsClass();
	QString szNewInheritsClassName = szInheritsClassName;
	bool bOk=askForClassName(szNewClassName,szNewInheritsClassName,true);
	if (!bOk) return;
	if (KviQString::equalCI(szClassName,szNewClassName) && KviQString::equalCI(szInheritsClassName,szNewInheritsClassName)) return;
	if (classExists(szNewClassName) && KviQString::equalCI(szInheritsClassName,szNewInheritsClassName))
	{
		g_pClassEditorModule->lock();
		QMessageBox::information(this,
			__tr2qs_ctx("Class already exists","editor"),
			__tr2qs_ctx("This name is already in use. Please choose another one.","editor"),
			__tr2qs_ctx("Ok, Let me try again...","editor"));
		g_pClassEditorModule->unlock();
		return;
	}
	/*if(szNewClassName.tmp.indexOf("@@",Qt::CaseInsensitive) != -1)
	{
		g_pClassEditorModule->lock();
		QMessageBox::information(this,
			__tr2qs_ctx("Bad Namespace Name","editor"),
			__tr2qs_ctx("Found an empty namespace in namespace name","editor"),
			__tr2qs_ctx("Ok, Let me try again...","editor"));
		g_pClassEditorModule->unlock();
		szNewName = "";
		continue;
	}*/
	KviClassEditorTreeWidgetItem *pNewItem=0;
	m_pClasses->remove(szClassName);
	cutItem(pClassItem);
	if(szNewClassName.contains("::"))
	{
		pNewItem=createFullNamespace(szNewClassName.left(szNewClassName.lastIndexOf("::")));
		pClassItem->setName(szNewClassName.section("::",-1,-1));
		pNewItem->addChild(pClassItem);
		m_pClasses->insert(szNewClassName,pNewItem);
	}
	else
	{
		pClassItem->setName(szNewClassName);
		m_pTreeWidget->addTopLevelItem(pClassItem);
		m_pClasses->insert(szNewClassName,pClassItem);
	}
	pClassItem->setInheritsClass(szNewInheritsClassName);
	pClassItem->setClassNotBuilt(true);
	KviPointerList<KviClassEditorTreeWidgetItem> pInheritedClasses;
	searchInheritedClasses(szClassName,pInheritedClasses);
	for(unsigned int i=0;i<pInheritedClasses.count();i++)
	{
		pInheritedClasses.at(i)->setClassNotBuilt(true);
		pInheritedClasses.at(i)->setExpanded(true);
		pInheritedClasses.at(i)->setInheritsClass(szNewClassName);
	}
	if (pNewItem){
		activateItem(pNewItem);
		pNewItem->setExpanded(true);
	}
	else{
		activateItem(pClassItem);
		pClassItem->setExpanded(true);
	}
}
void KviClassEditor::cutItem(KviClassEditorTreeWidgetItem *pItem)
{
	int iIdx=m_pTreeWidget->indexOfTopLevelItem(pItem);
	if (iIdx!=-1){
		m_pTreeWidget->takeTopLevelItem(iIdx);
	}
	else
	{
		KviClassEditorTreeWidgetItem *pParent= (KviClassEditorTreeWidgetItem*)pItem->parent();
		pParent->removeChild(pItem);
	}
}

void KviClassEditor::renameNamespace(KviClassEditorTreeWidgetItem *pOldNamespaceItem)
{
	QString szName = buildFullClassName(m_pLastEditedItem);
	QString szNewNameSpaceName;
	if (!askForNamespaceName(__tr2qs_ctx("Rename Namespace","editor"),__tr2qs_ctx("Please enter the new name for the namespace","editor"),szName,szNewNameSpaceName)) return;
	if (KviQString::equalCI(szName,szNewNameSpaceName)) return;
	KviClassEditorTreeWidgetItem *pNewItem=findItem(szNewNameSpaceName);
	if (pNewItem)
	{
		g_pClassEditorModule->lock();
		if (pNewItem->isClass())
		{
			QMessageBox::information(this,
				__tr2qs_ctx("Name already exists as Class name","editor"),
				__tr2qs_ctx("This name is already in use as Class name. Please choose another one.","editor"),
				__tr2qs_ctx("Ok, Let me try again...","editor"));
		}
		else
		{
			QMessageBox::information(this,
			__tr2qs_ctx("Namespace already exists","editor"),
			__tr2qs_ctx("This name is already in use. Please choose another one.","editor"),
			__tr2qs_ctx("Ok, Let me try again...","editor"));
		}
		g_pClassEditorModule->unlock();
	}
	KviPointerList<KviClassEditorTreeWidgetItem> pList;
	pList.setAutoDelete(false);
	appendAllClassItemsRecursive(&pList,pOldNamespaceItem);
	cutItem(pOldNamespaceItem);
	if(szNewNameSpaceName.contains("::"))
	{
		pNewItem=createFullNamespace(szNewNameSpaceName.left(szNewNameSpaceName.lastIndexOf("::")));
		pOldNamespaceItem->setName(szNewNameSpaceName.section("::",-1,-1));
		pNewItem->addChild(pOldNamespaceItem);
	}
	else
	{
		m_pTreeWidget->addTopLevelItem(pOldNamespaceItem);
		pOldNamespaceItem->setName(szNewNameSpaceName);
	}
	for(unsigned int i=0;i<pList.count();i++)
	{
		KviPointerHashTableEntry<QString,KviClassEditorTreeWidgetItem> *entry=m_pClasses->findRef(pList.at(i));
		if (entry)
		{
			KviPointerList<KviClassEditorTreeWidgetItem> pInheritedClasses;
			searchInheritedClasses(entry->key(),pInheritedClasses);
			QString szNewName = buildFullClassName(pList.at(i));
			for(unsigned int j=0;j<pInheritedClasses.count();j++)
			{
				pInheritedClasses.at(j)->setClassNotBuilt(true);
				pInheritedClasses.at(j)->setExpanded(true);
				pInheritedClasses.at(j)->setInheritsClass(szNewName);
			}
			m_pClasses->removeRef(pList.at(i));
			m_pClasses->insert(szNewName,pList.at(i));
			pList.at(i)->setClassNotBuilt(true);
		}

	}

	if (pNewItem){
		activateItem(pNewItem);
		pNewItem->setExpanded(true);
	}
	else{
		activateItem(pOldNamespaceItem);
		pOldNamespaceItem->setExpanded(true);
	}
}
void KviClassEditor::saveLastEditedItem()
{
	if(!m_pLastEditedItem)
		return;
	if(!m_pEditor->isModified() || m_pLastEditedItem->isNamespace() || m_pLastEditedItem->isClass())
		return;

	((KviClassEditorTreeWidgetItem *)m_pLastEditedItem)->setCursorPosition(m_pEditor->getCursor());
	QString newCode;
	m_pEditor->getText(newCode);
	((KviClassEditorTreeWidgetItem *)m_pLastEditedItem)->setBuffer(newCode);
	((KviClassEditorTreeWidgetItem *)m_pLastEditedItem->parent())->setClassNotBuilt(true);
}

void KviClassEditor::currentItemChanged(QTreeWidgetItem * it, QTreeWidgetItem *)
{
	saveLastEditedItem();
	m_pLastEditedItem = (KviClassEditorTreeWidgetItem *)it;

	if(!m_pLastEditedItem)
	{
		m_pClassNameLabel->setText(__tr2qs_ctx("No item selected","editor"));
		m_pClassNameRenameButton->setEnabled(false);
		m_pEditor->setText("");
		m_pEditor->setEnabled(false);
		return;
	}
	KviClassEditorTreeWidgetItem * pClassItem;
	if(m_pLastEditedItem->isMethod()) pClassItem=(KviClassEditorTreeWidgetItem *)m_pLastEditedItem->parent();
	else pClassItem=m_pLastEditedItem;
	QString szClassName = buildFullClassName(pClassItem);
	if(m_pLastEditedItem->isNamespace())
	{
		QString szLabelText = __tr2qs_ctx("Namespace","editor");
		szLabelText += ": <b>";
		szLabelText += szClassName;
		szLabelText += "</b>";
		m_pClassNameLabel->setText(szLabelText);
		m_pClassNameRenameButton->setEnabled(true);
		m_pMemberFunctionNameRenameButton->setEnabled(false);
		m_pInheritsClassNameLabel->setText("");
		m_pMemberFunctionNameLabel->setText("");
		m_pEditor->setText("");
		m_pEditor->setEnabled(false);
		m_pTreeWidget->setFocus();
		return;
	}
	QString szLabelText = __tr2qs_ctx("Class","editor");
	szLabelText += ": <b>";
	szLabelText += szClassName;
	szLabelText += "</b>";
	m_pClassNameLabel->setText(szLabelText);

	szLabelText = __tr2qs_ctx("Inherits Class","editor");
	szLabelText += ": <b>";
	szLabelText += pClassItem->InheritsClass();
	szLabelText += "</b>";
	m_pInheritsClassNameLabel->setText(szLabelText);

	szLabelText = __tr2qs_ctx("Member Function:","editor");
	if(m_pLastEditedItem->isMethod())
	{
		szLabelText += ": <b>";
		szLabelText += m_pLastEditedItem->text(0);
		szLabelText += "</b>";
		m_pMemberFunctionNameRenameButton->setEnabled(true);
	}
	else m_pClassNameRenameButton->setEnabled(true);
	m_pMemberFunctionNameLabel->setText(szLabelText);
	if(m_pLastEditedItem->isClass())
	{
		m_pMemberFunctionNameRenameButton->setEnabled(false);
		m_pEditor->setText("");
		m_pEditor->setEnabled(false);
		m_pTreeWidget->setFocus();
		return;
	}

	m_pEditor->setText(((KviClassEditorTreeWidgetItem *)it)->buffer());
	m_pEditor->setFocus();
	m_pEditor->setCursorPosition(((KviClassEditorTreeWidgetItem *)it)->cursorPosition());
	m_pEditor->setEnabled(true);
}

void KviClassEditor::customContextMenuRequested(QPoint pnt)
{
	m_pContextPopup->clear();

	m_pLastClickedItem = (KviClassEditorTreeWidgetItem *)m_pTreeWidget->itemAt(pnt);

	int id;

	id = m_pContextPopup->insertItem(
			*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NAMESPACE)),
			__tr2qs_ctx("Add Namespace","editor"),
			this,SLOT(newNamespace()));
	if (!m_pLastClickedItem)m_pContextPopup->setItemEnabled(id,true);
	else m_pContextPopup->setItemEnabled(id,m_pLastClickedItem->isNamespace());

	id = m_pContextPopup->insertItem(
			*(g_pIconManager->getSmallIcon(KVI_SMALLICON_CLASS)),
			__tr2qs_ctx("Add Class","editor"),
			this,SLOT(newClass()));
	if (!m_pLastClickedItem)m_pContextPopup->setItemEnabled(id,true);
	else m_pContextPopup->setItemEnabled(id,m_pLastClickedItem->isNamespace());


	id = m_pContextPopup->insertItem(
			*(g_pIconManager->getSmallIcon(KVI_SMALLICON_FUNCTION)),
			__tr2qs_ctx("Add Member Function","editor"),
			this,SLOT(newMemberFunction()));
	if (!m_pLastClickedItem)m_pContextPopup->setItemEnabled(id,false);
	else m_pContextPopup->setItemEnabled(id,m_pLastClickedItem->isClass()| m_pLastClickedItem->isMethod());


	bool bHasItems = m_pTreeWidget->topLevelItemCount();
	bool bHasSelected = hasSelectedItems();

	m_pContextPopup->insertSeparator();

	id = m_pContextPopup->insertItem(
			*(g_pIconManager->getSmallIcon(KVI_SMALLICON_QUIT)),
			__tr2qs_ctx("Remove Selected","editor"),
			this,SLOT(removeSelectedItems()));
	m_pContextPopup->setItemEnabled(id,bHasSelected);

	m_pContextPopup->insertSeparator();

	m_pContextPopup->insertItem(
			*(g_pIconManager->getSmallIcon(KVI_SMALLICON_FOLDER)),
			__tr2qs_ctx("Export Selected...","editor"),
			this,SLOT(exportSelected()));
	m_pContextPopup->setItemEnabled(id,bHasSelected);

	m_pContextPopup->insertItem(
			*(g_pIconManager->getSmallIcon(KVI_SMALLICON_FOLDER)),
			__tr2qs_ctx("Export Selected in singles files...","editor"),
			this,SLOT(exportSelectedSepFiles()));

	m_pContextPopup->setItemEnabled(id,bHasSelected);

	m_pContextPopup->insertItem(
			*(g_pIconManager->getSmallIcon(KVI_SMALLICON_FOLDER)),
			__tr2qs_ctx("Export All...","editor"),
			this,SLOT(exportAll()));
	m_pContextPopup->setItemEnabled(id,bHasItems);

	m_pContextPopup->insertSeparator();

	m_pContextPopup->insertItem(
			*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SEARCH)),
			__tr2qs_ctx("Find In Classes...","editor"),
			this,SLOT(slotFind()));
	m_pContextPopup->setItemEnabled(id,bHasItems);

	m_pContextPopup->insertItem(
			*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NAMESPACE)),
			__tr2qs_ctx("Collapse All Namespaces","editor"),
			this,SLOT(slotCollapseNamespaces()));

	m_pContextPopup->setItemEnabled(id,bHasItems);
	m_pContextPopup->popup( m_pTreeWidget->mapToGlobal(pnt));
}
/*
void KviClassEditor::recursiveSearchReplace(const QString &szSearch,KviClassEditorTreeWidgetItem * it,bool bReplace,const QString &szReplace)
{

        if(!it)return;
        for(int i=0;i< it->childCount();i++)
        {
                if(((KviClassEditorTreeWidgetItem *)it->child(i))->isClass())
                {
                        if(((KviClassEditorTreeWidgetItem *)it->child(i))->buffer().indexOf(szSearch,0,Qt::CaseInsensitive) != -1)
                        {
                                it->child(i)->setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_ALIASHIGHLIGHTED))));
                                if (bReplace) ((QString &)((KviClassEditorTreeWidgetItem *)it->child(i))->buffer()).replace(szSearch,szReplace,Qt::CaseInsensitive);
                                it->setExpanded(true);
                        }
                        else
                        it->child(i)->setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_ALIAS))));
                }
                else {
                        recursiveSearchReplace(szSearch,(KviClassEditorTreeWidgetItem *)(it->child(i)),bReplace,szReplace);
                }
        }

}

void KviClassEditor::slotFind()
{

        g_pClassEditorModule->lock();
        bool bOk;

        QString szSearch = QInputDialog::getText(this,
                __tr2qs_ctx("Find In Classes","editor"),
                __tr2qs_ctx("Please enter the text to be searched for. The matching classes will be highlighted.","editor"),
                QLineEdit::Normal,
                "",
                &bOk);


        g_pClassEditorModule->unlock();
        if(!bOk)return;
        if(szSearch.isEmpty())return;
        m_pEditor->setFindText(szSearch);
        for (int i=0;i<m_pTreeWidget->topLevelItemCount();i++)
        {
                if(((KviClassEditorTreeWidgetItem *)m_pTreeWidget->topLevelItem(i))->isClass())
                {
                        if(((KviClassEditorTreeWidgetItem *)m_pTreeWidget->topLevelItem(i))->buffer().indexOf(szSearch,0,Qt::CaseInsensitive) != -1)
                        {
                                m_pTreeWidget->topLevelItem(i)->setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_ALIASHIGHLIGHTED))));
                        } else {
                                m_pTreeWidget->topLevelItem(i)->setIcon(0,QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_ALIAS))));
                        }
                } else {
                        recursiveSearchReplace(szSearch,(KviClassEditorTreeWidgetItem *)m_pTreeWidget->topLevelItem(i));
                }
        }
}

void KviClassEditor::slotFindWord(const QString &szSearch)
{
	m_pEditor->setFindText(szSearch);
}

void KviClassEditor::recursiveCollapseNamespaces(KviClassEditorTreeWidgetItem * it)
{
	if(!it)return;
	for (int i=0;i<it->childCount();i++)
	{
		if(it->child(i)->childCount())
		{
			it->child(i)->setExpanded(false);
			recursiveCollapseNamespaces((KviClassEditorTreeWidgetItem *)it->child(i));
		}
	}
}

void KviClassEditor::slotCollapseNamespaces()
{
	for (int i=0;i<m_pTreeWidget->topLevelItemCount();i++)
	{
		if (m_pTreeWidget->topLevelItem(i)->childCount()){
			m_pTreeWidget->topLevelItem(i)->setExpanded(false);
			recursiveCollapseNamespaces((KviClassEditorTreeWidgetItem *)m_pTreeWidget->topLevelItem(i));
		}
	}
}

void KviClassEditor::slotReplaceAll(const QString &szFind,const QString &szReplace)
{
	m_pEditor->setFindText(szReplace);

	for (int i=0;i<m_pTreeWidget->topLevelItemCount();i++)
	{
		recursiveSearchReplace(szFind,(KviClassEditorTreeWidgetItem *)m_pTreeWidget->topLevelItem(i),true,szReplace);
	}
}
*/
void KviClassEditor::getExportClassBuffer(QString &buffer,KviClassEditorTreeWidgetItem * it)
{
	QString szBuf = it->buffer();
	KviCommandFormatter::blockFromBuffer(szBuf);
	QString szNam = buildFullClassName(it);

	buffer = "class(\"";
	buffer += szNam;
	if(!it->InheritsClass().isEmpty())
	{
		buffer+="\",\"";
		buffer+=it->InheritsClass();
	}
	buffer += "\")\n{\n";
	for(int i=0;i<it->childCount();i++)
	{
		KviClassEditorTreeWidgetItem * pFunction= (KviClassEditorTreeWidgetItem *)it->child(i);
		if(pFunction->isMethod())
		{
			buffer += "\t";
			if (pFunction->isInternalFunction()) buffer+="internal ";
			buffer += "function ";
			buffer += pFunction->name();
			buffer += "\n\t{\n";
			buffer += pFunction->buffer();
			buffer += "\n\t}\n";
		}
		i++;
	}
	buffer += "}\n";
}

void KviClassEditor::exportAll()
{
	exportClasses(false);
}

void KviClassEditor::exportSelectedSepFiles()
{
	exportClasses (true,true);
}

void KviClassEditor::exportSelected()
{
	exportClasses(true);
}

void KviClassEditor::exportSelectionInSinglesFiles(KviPointerList<KviClassEditorTreeWidgetItem> *l)
{
	if(!m_szDir.endsWith(QString(KVI_PATH_SEPARATOR)))m_szDir += KVI_PATH_SEPARATOR;
	if (!l->first())
	{
		g_pClassEditorModule->lock();
		QMessageBox::warning(this,__tr2qs_ctx("Class Export","editor"),__tr2qs_ctx("There is no selection!","editor"),__tr2qs_ctx("OK","editor"));
		g_pClassEditorModule->unlock();
		return;
	}
	g_pClassEditorModule->lock();

	if(!KviFileDialog::askForDirectoryName(m_szDir,__tr2qs_ctx("Choose a Directory - KVIrc","editor"),m_szDir)){
		g_pClassEditorModule->unlock();
		return;
	}

	if(!m_szDir.endsWith(QString(KVI_PATH_SEPARATOR)))m_szDir += KVI_PATH_SEPARATOR;

	bool bReplaceAll=false;

	for(KviClassEditorTreeWidgetItem * it = l->first();it;it = l->next())
	{
		QString tmp;
		getExportClassBuffer(tmp,it);
		QString szFileName=buildFullClassName(it);
		szFileName += ".kvs";
		szFileName.replace("::","_");
		QString szCompletePath=m_szDir+szFileName;
		if (KviFileUtils::fileExists(szCompletePath) && !bReplaceAll)
		{
			QString szMsg;
			KviQString::sprintf(szMsg,__tr2qs_ctx("The file \"%Q\" exists. Do you want to replace it ?","editor"),&szFileName);
			int ret = QMessageBox::question(this,__tr2qs_ctx("Replace file","editor"),szMsg,__tr2qs_ctx("Yes","editor"),__tr2qs_ctx("Yes to All","editor"),__tr2qs_ctx("No","editor"));
			if (ret!=2)
			{
				KviFileUtils::writeFile(szCompletePath,tmp);
				if (ret==1) bReplaceAll=true;
			}
		}
		else
		KviFileUtils::writeFile(szCompletePath,tmp);
	}
	g_pClassEditorModule->unlock();
}

void KviClassEditor::exportClasses(bool bSelectedOnly, bool bSingleFiles)
{
	saveLastEditedItem();

	KviPointerList<KviClassEditorTreeWidgetItem> l;
	l.setAutoDelete(false);

	QString out;
	if (bSelectedOnly) appendSelectedClassItems(&l);
	else appendAllClassItems(&l);
	if (bSingleFiles)
	{
		exportSelectionInSinglesFiles(&l);
		return;
        }
	int count=0;
	KviClassEditorTreeWidgetItem * tempitem=0;
	for(KviClassEditorTreeWidgetItem * it = l.first();it;it = l.next())
	{
		tempitem=it;
		count ++;
		QString tmp;
		getExportClassBuffer(tmp,it);
		out += tmp;
		out += "\n";
	}
	QString szNameFile;
	if(out.isEmpty())
	{
		g_pClassEditorModule->lock();
		QMessageBox::warning(this,__tr2qs_ctx("Class Export","editor"),__tr2qs_ctx("The exported file would be empty: cowardly refusing to write it","editor"),__tr2qs_ctx("OK","editor"));
		g_pClassEditorModule->unlock();
		return;
	}

	QString szName = m_szDir;

	if(!szName.endsWith(QString(KVI_PATH_SEPARATOR)))szName += KVI_PATH_SEPARATOR;
	QString szFile;
	g_pClassEditorModule->lock();

	if (count==1)
	{
			QString tmp=buildFullClassName(tempitem);
			szNameFile = tmp.replace("::","_");
	}
	else szNameFile="classes";
	szName += szNameFile;
	szName += ".kvs";
	if(!KviFileDialog::askForSaveFileName(szFile,__tr2qs_ctx("Choose a Filename - KVIrc","editor"),szName,KVI_FILTER_SCRIPT,false,true,true))
	{
		g_pClassEditorModule->unlock();
		return;
	}
	m_szDir=QFileInfo(szFile).absolutePath();
	g_pClassEditorModule->unlock();

	if(!KviFileUtils::writeFile(szFile,out))
	{
		g_pClassEditorModule->lock();
		QMessageBox::warning(this,__tr2qs_ctx("Write Failed - KVIrc","editor"),__tr2qs_ctx("Unable to write to the class file.","editor"),__tr2qs_ctx("OK","editor"));
		g_pClassEditorModule->unlock();
	}
}

void KviClassEditor::saveProperties(KviConfig * cfg)
{
	cfg->writeEntry("Sizes",m_pSplitter->sizes());
	QString szName;
	if(m_pLastEditedItem)
		szName = buildFullClassName(m_pLastEditedItem);
	cfg->writeEntry("LastClass",szName);
}

void KviClassEditor::loadProperties(KviConfig * cfg)
{
	QList<int> def;
	def.append(20);
	def.append(80);
	m_pSplitter->setSizes(cfg->readIntListEntry("Sizes",def));
	QString tmp = cfg->readEntry("LastClass",QString());

	KviClassEditorTreeWidgetItem * it = findItem(tmp);
	activateItem(it);
}

void KviClassEditor::appendSelectedClassItems(KviPointerList<KviClassEditorTreeWidgetItem> * l)
{
	QList<QTreeWidgetItem *> list=m_pTreeWidget->selectedItems();
	for(int i=0;i<list.count();i++)
	{
		if (((KviClassEditorTreeWidgetItem *)list.at(i))->isClass())
			l->append((KviClassEditorTreeWidgetItem *)list.at(i));
		else
		{
			appendSelectedClassItemsRecursive(l,list.at(i));
		}
	}
}
void KviClassEditor::appendSelectedClassItemsRecursive(KviPointerList<KviClassEditorTreeWidgetItem> * l,QTreeWidgetItem * pStartFrom)
{
        for (int i=0;i<pStartFrom->childCount();i++)
        {

            if (((KviClassEditorTreeWidgetItem *)pStartFrom->child(i))->isClass())
                    l->append(((KviClassEditorTreeWidgetItem *)pStartFrom->child(i)));
            else
                    appendSelectedClassItemsRecursive(l,pStartFrom->child(i));
        }
}

void KviClassEditor::appendAllClassItems(KviPointerList<KviClassEditorTreeWidgetItem> * l)
{
	KviPointerHashTableIterator<QString,KviClassEditorTreeWidgetItem> it (*m_pClasses);
	while(it.current())
	{
		l->append(it.current());
		++it;
	}


}

void KviClassEditor::appendAllClassItemsRecursive(KviPointerList<KviClassEditorTreeWidgetItem> * l,QTreeWidgetItem * pStartFrom)
{
        for (int i=0;i<pStartFrom->childCount();i++)
        {
                if (((KviClassEditorTreeWidgetItem *)pStartFrom->child(i))->isClass())
                {
                        l->append((KviClassEditorTreeWidgetItem *)pStartFrom->child(i));
                }
                else
                {
                        appendAllClassItemsRecursive(l,pStartFrom->child(i));
                }
        }

}
/*
void KviClassEditor::removeItemChildren(KviClassEditorTreeWidgetItem *it)
{
        while(it->childCount() > 0)
        {
                KviClassEditorTreeWidgetItem * pChild = (KviClassEditorTreeWidgetItem *)(it->child(0));
                if(pChild->childCount())
                        removeItemChildren(pChild);
                delete pChild;
        }
}

bool KviClassEditor::removeItem(KviClassEditorTreeWidgetItem *it,bool * pbYesToAll,bool)
{
        if(!it)return true;
        QString szMsg;
        QString szName = it->name();

        if(!*pbYesToAll)saveLastEditedItem();
        {
                if(it->isClass())
                        KviQString::sprintf(szMsg,__tr2qs_ctx("Do you really want to remove the class \"%Q\" ?","editor"),&szName);
                else {
                        KviQString::sprintf(szMsg,__tr2qs_ctx("Do you really want to remove the namespace \"%Q\" ?","editor"),&szName);
                        szMsg += "<br>";
                        szMsg += __tr2qs_ctx("Please note that all the children items will be deleted too.","editor");
                }

                g_pClassEditorModule->lock();
                int ret = QMessageBox::question(this,__tr2qs_ctx("Remove item","editor"),szMsg,__tr2qs_ctx("Yes","editor"),__tr2qs_ctx("Yes to All","editor"),__tr2qs_ctx("No","editor"));
                g_pClassEditorModule->unlock();
                switch(ret)
                {
                        case 0:
                                // nothing
                        break;
                        case 1:
                                *pbYesToAll = true;
                        break;
                        default:
                                return false;
                        break;
                }
        }

        if(it == m_pLastEditedItem)
                m_pLastEditedItem = 0;
        if(it == m_pLastClickedItem)
                m_pLastClickedItem = 0;
        if (it->childCount())
                removeItemChildren(it);
        delete it;
        return true;
}

void KviClassEditor::removeSelectedItems()
{
        KviPointerList<KviClassEditorTreeWidgetItem> l;
        l.setAutoDelete(false);
        appendSelectedClassItems(&l);

        bool bYesToAll = false;

        for(KviClassEditorTreeWidgetItem *it = l.first();it;it = l.next())
        {
                if(!removeItem(it,&bYesToAll,false))return;
        }


}
*/

bool KviClassEditor::askForClassName(QString &szClassName,QString &szInheritsClassName, bool bEdit)
{
	KviClassEditorDialog *pDialog=new KviClassEditorDialog(this,"classdialog",m_pClasses,szClassName,szInheritsClassName,bEdit);
	szClassName="";
	g_pClassEditorModule->lock();
	bool bOk=pDialog->exec();
	g_pClassEditorModule->unlock();
	if(bOk)
	{
		szClassName=pDialog->getClassName();
		szInheritsClassName=pDialog->getInheritsClassName();
		delete pDialog;
		return true;
	}
        delete pDialog;
	return false;
}

bool KviClassEditor::askForFunction(QString &szFunctionName,bool * bInternal,const QString &szClassName)
{
	KviClassEditorFunctionDialog *pDialog=new KviClassEditorFunctionDialog(this,"function",szClassName,szFunctionName);
	szFunctionName="";
	g_pClassEditorModule->lock();
	bool bOk=pDialog->exec();
	g_pClassEditorModule->unlock();
	if(bOk)
	{
		szFunctionName=pDialog->getFunctionName();
		*bInternal=pDialog->isInternalFunction();
		delete pDialog;
		return true;
	}
	delete pDialog;
	return false;
}

bool KviClassEditor::askForNamespaceName(const QString &szAction,const QString &szText,const QString &szInitialText, QString &szNewName)
{
        bool bOk = false;
	while(szNewName.isEmpty())
        {
                g_pClassEditorModule->lock();
                szNewName = QInputDialog::getText(this,
                                                szAction,
                                                szText,
                                                QLineEdit::Normal,
                                                szInitialText,
                                                &bOk);
                g_pClassEditorModule->unlock();
		if(!bOk)return false;
                if(szNewName.isEmpty())
                {
                        g_pClassEditorModule->lock();
                        QMessageBox::warning(this,
                                __tr2qs_ctx("Missing Namespace Name","editor"),
                                __tr2qs_ctx("You must specify a valid name for the namespace","editor"),
                                __tr2qs_ctx("Ok, Let me try again...","editor"));
                        g_pClassEditorModule->unlock();
                        continue;
                }

                // we allow only [\w:]+
                QRegExp re("[\\w:]+");
                if(!re.exactMatch(szNewName))
                {
                        g_pClassEditorModule->lock();
                        QMessageBox::information(this,
                                __tr2qs_ctx("Bad Namespace Name","editor"),
                                __tr2qs_ctx("Namespace names can contain only letters, digits, underscores and '::' namespace separators","editor"),
                                __tr2qs_ctx("Ok, Let me try again...","editor"));
                        g_pClassEditorModule->unlock();
                        szNewName = "";
                        continue;
                }
                // make sure that we have only doubled "::" and not ":" or ":::..."
                QString tmp = szNewName;
                tmp.replace("::","@"); // @ is not allowed by the rule above
                if(tmp.indexOf(":",Qt::CaseInsensitive) != -1)
                {
                        g_pClassEditorModule->lock();
                        QMessageBox::information(this,
                                __tr2qs_ctx("Bad Namespace Name","editor"),
                                __tr2qs_ctx("Stray ':' character in namespace name: did you mean ...<namespace>::<name> ?","editor"),
                                __tr2qs_ctx("Ok, Let me try again...","editor"));
                        g_pClassEditorModule->unlock();
                        szNewName = "";
                        continue;
                }
                if(tmp.indexOf("@@",Qt::CaseInsensitive) != -1)
                {
                        g_pClassEditorModule->lock();
                        QMessageBox::information(this,
                                __tr2qs_ctx("Bad Namespace Name","editor"),
                                __tr2qs_ctx("Found an empty namespace in namespace name","editor"),
                                __tr2qs_ctx("Ok, Let me try again...","editor"));
                        g_pClassEditorModule->unlock();
                        szNewName = "";
                        continue;
                }
        }
	return true;
}

void KviClassEditor::openParentItems(QTreeWidgetItem * it)
{
        if(it->parent())
        {
                it->parent()->setExpanded(true);
                openParentItems(it->parent());
        }
}

void KviClassEditor::activateItem(QTreeWidgetItem * it)
{
        if (!it) return;
        openParentItems(it);
        m_pTreeWidget->setCurrentItem(it);
}

void KviClassEditor::newClass()
{
       QString szClassName,szInheritsClassName;
       askForClassName(szClassName,szInheritsClassName,false);
       if(szClassName.isEmpty())return;
       KviClassEditorTreeWidgetItem *it=newItem(szClassName,KviClassEditorTreeWidgetItem::Class);
       QString szClass="class\(";
       szClass+=szClassName+","+szInheritsClassName;
       szClass+="){}\n";
       it->setInheritsClass(szInheritsClassName);
       activateItem(it);
       m_pClasses->insert(szClassName,it);
       debug("run class script");
       KviKvsScript::run(szClass,g_pActiveWindow);
}
void KviClassEditor::newNamespace()
{
       QString szName;
       if(!askForNamespaceName(__tr2qs_ctx("Add Namespace","editor"),__tr2qs_ctx("Please enter the name for the new namespace","editor"),"mynamespace",szName)) return;
       if(szName.isEmpty())return;
       KviClassEditorTreeWidgetItem *it=newItem(szName,KviClassEditorTreeWidgetItem::Namespace);
       activateItem(it);
}

void KviClassEditor::newMemberFunction()
{
       QString szFunctionName,szClassName;
       if(m_pLastClickedItem->isMethod()) m_pLastClickedItem= (KviClassEditorTreeWidgetItem*)m_pLastClickedItem->parent();
       szClassName=buildFullClassName(m_pLastClickedItem);
       bool bInternal;
       askForFunction(szFunctionName, &bInternal,szClassName);
       if(szFunctionName.isEmpty())return;
       KviClassEditorTreeWidgetItem *it=newItem(szFunctionName,KviClassEditorTreeWidgetItem::Method);
       it->setInternalFunction(bInternal);
       activateItem(it);
       ((KviClassEditorTreeWidgetItem*)it->parent())->setClassNotBuilt(true);
}

KviClassEditorTreeWidgetItem *  KviClassEditor::newItem(QString &szName,KviClassEditorTreeWidgetItem::Type eType)
{
        if(m_pLastClickedItem)
            buildFullItemPath(m_pLastClickedItem,szName);
        QString szTmp;
        if(findItem(szName)) szName.append("1");
        int idx=2;
        while(findItem(szName))
        {
              szTmp.setNum(idx);
              szName.chop(szTmp.length());
              szName.append(szTmp);
              idx++;
        }
        KviClassEditorTreeWidgetItem * it;
        it=createFullItem(szName);
        it->setType(eType);

        return it;
}

void KviClassEditor::build()
{
    saveLastEditedItem();
    KviPointerHashTableIterator<QString,KviClassEditorTreeWidgetItem> it (*m_pClasses);
    KviPointerList<KviClassEditorTreeWidgetItem> pLinkedClasses;
    pLinkedClasses.setAutoDelete(false);
    KviPointerList<KviClassEditorTreeWidgetItem> pSkipClasses;
    pSkipClasses.setAutoDelete(false);
    while(it.current())
    {
        KviClassEditorTreeWidgetItem *pClass=it.current();
        if (pSkipClasses.findRef(it.current())!=-1)
	{
		++it;
		continue;
        }
        if (pClass->classNotBuilt())
        {
		KviClassEditorTreeWidgetItem *pParentClass=m_pClasses->find(pClass->InheritsClass());
		debug("append to build last class %s",pClass->name().toUtf8().data());


		pLinkedClasses.append(pClass);
		while(pParentClass)
		{
			if (pParentClass->classNotBuilt())
			{
				debug("append to build parent class %s",pParentClass->name().toUtf8().data());
				pLinkedClasses.append(pParentClass);
			}
			pParentClass=m_pClasses->find(pParentClass->InheritsClass());
		}
		for(int i=pLinkedClasses.count()-1;i>=0;i--)
		{
			KviKvsObjectClass *pClass;
			debug("parsing class %s",pLinkedClasses.at(i)->name().toUtf8().data());
			pClass = KviKvsKernel::instance()->objectController()->lookupClass(pLinkedClasses.at(i)->name());
			if (pClass) KviKvsKernel::instance()->objectController()->deleteClass(pClass);
			QString szClass="class\(";
			szClass+=pLinkedClasses.at(i)->name()+","+pLinkedClasses.at(i)->InheritsClass()+")\n{\n";
			for(int j=0;j<pLinkedClasses.at(i)->childCount();j++)
			{
				QString szFunction;
				KviClassEditorTreeWidgetItem *pFunction=( KviClassEditorTreeWidgetItem *)pLinkedClasses.at(i)->child(j);
				if (pFunction->isInternalFunction()) szFunction+="internal ";
				szFunction+=pFunction->name()+"()\n{\n";
				szFunction+=pFunction->buffer()+"\n}\n";
				szClass+=szFunction;
			}
			szClass+="}\n";
			debug ("class %s",szClass.toUtf8().data());
			KviKvsScript::run(szClass,g_pActiveWindow);
			pClass = KviKvsKernel::instance()->objectController()->lookupClass(pLinkedClasses.at(i)->name());
			if (!pClass)
			{
				QString szError=__tr2qs_ctx("Unable to compile class: ","editor");
				szError+=pLinkedClasses.at(i)->name()+"\n";
				KviPointerList<KviClassEditorTreeWidgetItem> pInheritedClasses;
				searchInheritedClasses(pLinkedClasses.at(i)->name(),pInheritedClasses);
				if (pInheritedClasses.count())
				{
					szError+=__tr2qs_ctx("These Inheritsed classes will be not compiled too:","editor");
					szError+="\n";
					for(unsigned int j=0;j<pInheritedClasses.count();j++)
					{
						szError+=pInheritedClasses.at(j)->name()+"\n";
						pInheritedClasses.at(j)->setClassNotBuilt(true);
						pSkipClasses.append(pInheritedClasses.at(j));
					}
				}
				QMessageBox::critical(this,__tr2qs_ctx("Compilation error - KVIrc","editor"),szError,
				QMessageBox::Ok,QMessageBox::NoButton,QMessageBox::NoButton);
				break;
			}
			pLinkedClasses.at(i)->setClassNotBuilt(false);
		}

        }
         ++it;
    }
    KviKvsKernel::instance()->objectController()->flushUserClasses();

}
void KviClassEditor::loadNotBuiltClasses()
{
        QString szFileName = "libkviclasseditortmp.kvc";
        QString szBuffer;
        g_pApp->getLocalKvircDirectory(szBuffer,KviApp::ConfigPlugins,szFileName);
        KviConfig cfg(szBuffer,KviConfig::Read);
        KviConfigIterator it(*(cfg.dict()));

        KviPointerList<QString> l;
        l.setAutoDelete(true);

        while(it.current())
        {
                l.append(new QString(it.currentKey()));
                ++it;
        }

        for(QString * s = l.first();s;s = l.next())
        {
                cfg.setGroup(*s);
                KviClassEditorTreeWidgetItem *pClassItem = createFullItem(*s);
                 m_pClasses->insert(*s,pClassItem);
                pClassItem->setClassNotBuilt(true);
                KviConfigGroup * pDict = cfg.dict()->find(*s);
                if(pDict)
                {
                        KviConfigGroupIterator it(*pDict);
                        KviPointerList<QString> names;
                        names.setAutoDelete(true);

                        while(it.current())
                        {
                                names.append(new QString(it.currentKey()));
                                ++it;
                        }
                        for(QString * s = names.first(); s; s = names.next())
                        {
				if (KviQString::equalCI(*s,"@Inherits"))
				{
					pClassItem->setInheritsClass(cfg.readQStringEntry(*s,""));
					continue;
				}
				QString szCode = cfg.readQStringEntry(*s,"");
                                KviClassEditorTreeWidgetItem *pFunctionItem=new KviClassEditorTreeWidgetItem(pClassItem,KviClassEditorTreeWidgetItem::Method,*s);
                                pFunctionItem->setBuffer(szCode);
                        }
                }
        }
}

void KviClassEditor::saveNotBuiltClasses()
{
        saveLastEditedItem();
        KviPointerHashTableIterator<QString,KviClassEditorTreeWidgetItem> it (*m_pClasses);
        QString szFileName = "libkviclasseditortmp.kvc";
        QString szBuffer;
        g_pApp->getLocalKvircDirectory(szBuffer,KviApp::ConfigPlugins,szFileName);
        KviConfig cfg(szBuffer,KviConfig::Write);
	while(it.current())
        {
		if (it.current()->classNotBuilt())
		{
			debug("saving class %s",it.currentKey().toUtf8().data());
			cfg.setGroup(it.currentKey());
			cfg.writeEntry("@Inherits",it.current()->InheritsClass());
			for(int i=0;i<it.current()->childCount();i++)
				cfg.writeEntry(((KviClassEditorTreeWidgetItem*)it.current()->child(i))->name(),((KviClassEditorTreeWidgetItem*)it.current()->child(i))->buffer());
		}
		++it;
        }
}

void KviClassEditor::searchInheritedClasses(const QString szClass,KviPointerList<KviClassEditorTreeWidgetItem> & pInheritedClasses)
{
        KviPointerHashTableIterator<QString,KviClassEditorTreeWidgetItem> it (*m_pClasses);
	debug("into searchInherits");
        while(it.current())
        {
		//debug("class %s",it.current()->name().toUtf8().data());
		//debug("inerits class %s",it.current()->InheritsClass().toUtf8().data());

	    if (KviQString::equalCI(szClass,it.current()->InheritsClass())) pInheritedClasses.append(it.current());
            ++it;
        }
}

KviClassEditorWindow::KviClassEditorWindow(KviFrame * lpFrm)
: KviWindow(KVI_WINDOW_TYPE_SCRIPTEDITOR,lpFrm,"classeditor",0)
{
        g_pClassEditorWindow = this;

        setFixedCaption(__tr2qs_ctx("Class Editor","editor"));

        QGridLayout * g = new QGridLayout();

        m_pEditor = new KviClassEditor(this);
        g->addWidget(m_pEditor,0,0,1,4);

        QPushButton * btn = new QPushButton(__tr2qs_ctx("&Build","editor"),this);
        connect(btn,SIGNAL(clicked()),this,SLOT(buildClicked()));
        btn->setIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_ACCEPT)));
        g->addWidget(btn,1,1);

        btn = new QPushButton(__tr2qs_ctx("&Save","editor"),this);
        connect(btn,SIGNAL(clicked()),this,SLOT(saveClicked()));
        btn->setIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_ACCEPT)));
        g->addWidget(btn,1,2);

        btn = new QPushButton(__tr2qs_ctx("Cancel","editor"),this);
        connect(btn,SIGNAL(clicked()),this,SLOT(cancelClicked()));
        btn->setIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_DISCARD)));
        g->addWidget(btn,1,3);

        g->setRowStretch(0,1);
        g->setColumnStretch(0,1);
        setLayout(g);
}

KviClassEditorWindow::~KviClassEditorWindow()
{
        g_pClassEditorWindow = 0;
}

void KviClassEditorWindow::buildClicked()
{
        m_pEditor->build();
}

void KviClassEditorWindow::saveClicked()
{
        m_pEditor->saveNotBuiltClasses();
}

void KviClassEditorWindow::cancelClicked()
{
        close();
}

QPixmap * KviClassEditorWindow::myIconPtr()
{
        return g_pIconManager->getSmallIcon(KVI_SMALLICON_ALIAS);
}

void KviClassEditorWindow::getConfigGroupName(QString &szName)
{
        szName = "classeditor";
}

void KviClassEditorWindow::saveProperties(KviConfig *cfg)
{
        m_pEditor->saveProperties(cfg);
}

void KviClassEditorWindow::loadProperties(KviConfig *cfg)
{
        m_pEditor->loadProperties(cfg);
}

KviClassEditorDialog::KviClassEditorDialog(QWidget * pParent, const QString & szName,KviPointerHashTable<QString,KviClassEditorTreeWidgetItem> *pClasses,const QString &szClassName, const QString &szInheritsClassName,bool bRenameMode)
: QDialog(pParent)
{
        setObjectName(szName);

        QPalette p = palette();
        p.setColor(foregroundRole(),QColor( 0, 0, 0 ));
        p.setColor(backgroundRole(),QColor( 236, 233, 216 ));
        setPalette(p);

        QGridLayout * pLayout = new QGridLayout(this);

        KviTalHBox * hbox = new KviTalHBox(this);
        hbox->setSpacing(0);
        hbox->setMargin(0);
        pLayout->addWidget(hbox,0,0);

        QLabel * pClassNameLabel = new QLabel(hbox);
        pClassNameLabel->setObjectName("classnamelabel");

        pClassNameLabel->setText(__tr2qs_ctx("Please enter the name for the new class:","editor"));

        m_pClassNameLineEdit = new QLineEdit(hbox);
        m_pClassNameLineEdit->setObjectName("classnameineedit");
	m_pClassNameLineEdit->setText(szClassName);
	if (!bRenameMode)
	{
		debug(" normal mode");
		// we allow only [\w:]+ class name
		QRegExp re("[\\w]+");
		QRegExpValidator *pValidator=new QRegExpValidator(re,this);
		m_pClassNameLineEdit->setValidator(pValidator);
		m_pClassNameLineEdit->setObjectName("functionameineedit");
		m_pClassNameLineEdit->setToolTip(__tr2qs_ctx("Class names can contain only letters, digits and underscores","editor"));
	}
	else
	{
		debug(" rename mode");
		// in editor mode we allow [\w:]+ and namespace separator
		QRegExp re("[\\w]+(::[\\w]+)+");
		QRegExpValidator *pValidator=new QRegExpValidator(re,this);
		m_pClassNameLineEdit->setValidator(pValidator);
		m_pClassNameLineEdit->setObjectName("functionameineedit");
		m_pClassNameLineEdit->setToolTip(__tr2qs_ctx("In rename mode class names can contain only letters, digits and underscores and namespaces :: separator","editor"));
	}
        hbox = new KviTalHBox(this);
        hbox->setSpacing(0);
        hbox->setMargin(0);
        pLayout->addWidget(hbox,1,0);

	QLabel * pInheritsClassLabel = new QLabel(hbox);
	pInheritsClassLabel->setObjectName("Inheritsclasslabel");
	pInheritsClassLabel->setText(__tr2qs_ctx("Inherits Class:","editor"));

	m_pInheritsClassComboBox=new QComboBox(hbox);
        KviPointerHashTableIterator<QString,KviClassEditorTreeWidgetItem> pClassesIt(*pClasses);

      /*  m_pInheritsClassComboBox->addItem("Object");
	m_pInheritsClassComboBox->addItem("Widget");
*/
        QStringList szClasses;
        while(pClassesIt.current())
        {
            szClasses.append(pClassesIt.currentKey());
            ++pClassesIt;
        }
        KviPointerHashTableIterator<QString,KviKvsObjectClass> pBuiltinClasses(*KviKvsKernel::instance()->objectController()->classDict());
        while(pBuiltinClasses.current())
        {
             if (pBuiltinClasses.current()->isBuiltin())
                  szClasses.append(pBuiltinClasses.currentKey());
             ++pBuiltinClasses;
        }
        szClasses.sort();
        for(int i=0;i<szClasses.count();i++)
	    m_pInheritsClassComboBox->addItem(szClasses.at(i));
	if (!szInheritsClassName.isEmpty())
	{
		int iCurrentIdx=m_pInheritsClassComboBox->findText(szInheritsClassName);
		m_pInheritsClassComboBox->setCurrentIndex(iCurrentIdx);
	}
	m_pClassNameLineEdit->setFocus();

        hbox = new KviTalHBox(this);
        hbox->setSpacing(0);
        hbox->setMargin(0);
        pLayout->addWidget(hbox,2,0);

        m_pNewClassButton = new QPushButton(hbox);
        m_pNewClassButton->setObjectName("newclassbutton");
	if (!bRenameMode)
	{
		m_pNewClassButton->setText(__tr2qs_ctx("&Create Class","editor"));
		m_pNewClassButton->setEnabled(false);
	}
	else m_pNewClassButton->setText(__tr2qs_ctx("&Rename Class","editor"));

        QPushButton * pCancelButton = new QPushButton(hbox);
        pCancelButton->setObjectName("cancelButton");
        pCancelButton->setText(__tr2qs_ctx("&Cancel","editor"));

        setLayout(pLayout);

        // signals and slots connections
        connect(pCancelButton, SIGNAL(clicked()), this, SLOT(reject()));
        connect(m_pNewClassButton, SIGNAL(clicked()), this, SLOT(accept()));
        connect(m_pClassNameLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(textChanged(const QString &)));
}

KviClassEditorDialog::~KviClassEditorDialog()
{
}

void KviClassEditorDialog::textChanged(const QString & szText)
{
    m_pNewClassButton->setEnabled(!szText.isEmpty());
}

KviClassEditorFunctionDialog::KviClassEditorFunctionDialog(QWidget * pParent, const QString & szName, const QString &szClassName, const QString &szFunctionName)
: QDialog(pParent)
{
        setObjectName(szName);

        QPalette p = palette();
        p.setColor(foregroundRole(),QColor( 0, 0, 0 ));
        p.setColor(backgroundRole(),QColor( 236, 233, 216 ));
        setPalette(p);

        QGridLayout * pLayout = new QGridLayout(this);

        KviTalHBox * hbox = new KviTalHBox(this);
        hbox->setSpacing(0);
        hbox->setMargin(0);
        pLayout->addWidget(hbox,0,0);

        QLabel * pClassNameLabel = new QLabel(hbox);
        pClassNameLabel->setObjectName("classnamelabel");
        pClassNameLabel->setText("Class: <b>"+szClassName+"</b>");

        hbox = new KviTalHBox(this);
        hbox->setSpacing(0);
        hbox->setMargin(0);
        pLayout->addWidget(hbox,1,0);

        QLabel * pFunctionNameLabel = new QLabel(hbox);
        pFunctionNameLabel->setObjectName("functionnamelabel");
        pFunctionNameLabel->setText(__tr2qs_ctx("Please enter the name for the new member function:","editor"));

        m_pFunctionNameLineEdit = new QLineEdit(hbox);

	// we allow only [\w:]+ function name
	QRegExp re("[\\w]+");
	QRegExpValidator *pValidator=new QRegExpValidator(re,this);
	m_pFunctionNameLineEdit->setValidator(pValidator);
        m_pFunctionNameLineEdit->setObjectName("functionameineedit");
	m_pFunctionNameLineEdit->setToolTip(__tr2qs_ctx("Function names can contain only letters, digits and underscores","editor"));
	m_pFunctionNameLineEdit->setText(szFunctionName);

        hbox = new KviTalHBox(this);
        hbox->setSpacing(0);
        hbox->setMargin(0);
        pLayout->addWidget(hbox,2,0);


        QLabel * pFunctionInternalLabel = new QLabel(hbox);
        pFunctionInternalLabel->setObjectName("functionnamelabel");
        pFunctionInternalLabel->setText(__tr2qs_ctx("Set as <b>Internal</b> Function: ","editor"));

        m_pInternalCheckBox=new QCheckBox(hbox);
        m_pInternalCheckBox->setChecked(false);
        m_pFunctionNameLineEdit->setFocus();
        hbox->setAlignment(m_pInternalCheckBox,Qt::AlignLeft);
        hbox->setStretchFactor(m_pInternalCheckBox,70);
        hbox->setStretchFactor(pFunctionInternalLabel,30);


        hbox = new KviTalHBox(this);
        hbox->setSpacing(0);
        hbox->setMargin(0);
        pLayout->addWidget(hbox,3,0);

        m_pNewFunctionButton = new QPushButton(hbox);
        m_pNewFunctionButton->setObjectName("newfunctionbutton");
        m_pNewFunctionButton->setText(__tr2qs_ctx("&Add","editor"));
	if (szFunctionName.isEmpty()) m_pNewFunctionButton->setEnabled(false);

        QPushButton * pCancelButton = new QPushButton(hbox);
        pCancelButton->setObjectName("cancelButton");
        pCancelButton->setText(__tr2qs_ctx("&Cancel","editor"));

        setLayout(pLayout);

        // signals and slots connections
        connect(pCancelButton, SIGNAL(clicked()), this, SLOT(reject()));
        connect(m_pNewFunctionButton, SIGNAL(clicked()), this, SLOT(accept()));
        connect(m_pFunctionNameLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(textChanged(const QString &)));
}

KviClassEditorFunctionDialog::~KviClassEditorFunctionDialog()
{
}

void KviClassEditorFunctionDialog::textChanged(const QString & szText)
{
    m_pNewFunctionButton->setEnabled(!szText.isEmpty());
}