summaryrefslogtreecommitdiffstats
path: root/src/kvirc/ui/kvi_input.cpp
blob: 50693056373bc7670bd49e4861112414505af1bb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
//=============================================================================
//
//   File : kvi_input.cpp
//   Creation date : Sun Jan 3 1999 23:11:50 by Szymon Stefanek
//
//   This file is part of the KVirc irc client distribution
//   Copyright (C) 1999-2007 Szymon Stefanek (pragma at kvirc dot net)
//
//   This program is FREE software. You can redistribute it and/or
//   modify it under the terms 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.
//
//=============================================================================

#define __KVIRC__
#define _KVI_DEBUG_CHECK_RANGE_
#include "kvi_debug.h"

#define _KVI_INPUT_CPP_

#include "kvi_options.h"
#include "kvi_app.h"
#include "kvi_settings.h"
#include "kvi_defaults.h"
#include "kvi_colorwin.h"
#include "kvi_texticonwin.h"
#include "kvi_window.h"

#include "kvi_locale.h"
#include "kvi_mirccntrl.h"
#include "kvi_userlistview.h"
#include "kvi_ircview.h"
#include "kvi_console.h"
#include "kvi_out.h"
#include "kvi_iconmanager.h"
#include "kvi_scripteditor.h"
#include "kvi_config.h"
#include "kvi_historywin.h"
#include "kvi_input.h"
#include "kvi_userinput.h"
#include "kvi_kvs_script.h"
#include "kvi_kvs_kernel.h"
#include "kvi_doublebuffer.h"
#include "kvi_styled_controls.h"
#include "kvi_texticonmanager.h"
#include "kvi_draganddrop.h"

#include <tqlabel.h>
#include <ctype.h>
#include <stdlib.h>
#include <tqfiledialog.h>
#include "kvi_tal_popupmenu.h"
#include <tqpainter.h>
#include <tqclipboard.h>
#include <tqstringlist.h>
#include "kvi_pointerlist.h"
#include <tqapplication.h>
#include <tqclipboard.h>
#include <tqmessagebox.h>
#include "kvi_tal_hbox.h"
#include <tqlayout.h> 
#include <tqstyle.h>
#include <tqevent.h>


#ifndef ACCEL_KEY
#define ACCEL_KEY(k) "\t" + TQString(TQKeySequence( TQt::CTRL | TQt::Key_ ## k ))
#endif

#include <tqcursor.h>

//This comes from kvi_app.cpp
extern KviColorWindow    * g_pColorWindow;
extern KviTextIconWindow * g_pTextIconWindow;
extern KviHistoryWindow  * g_pHistoryWindow;
extern KviTalPopupMenu        * g_pInputPopup;

static TQFontMetrics             * g_pLastFontMetrics = 0;


#ifdef COMPILE_PSEUDO_TRANSPARENCY
	extern TQPixmap * g_pShadedChildGlobalDesktopBackground;
#endif


#define KVI_INPUT_MAX_GLOBAL_HISTORY_ENTRIES 100
#define KVI_INPUT_MAX_LOCAL_HISTORY_ENTRIES 20


extern KviInputHistory * g_pInputHistory;


KviInputHistory::KviInputHistory()
{
	m_pStringList = new KviPointerList<TQString>;
	m_pStringList->setAutoDelete(true);
}

KviInputHistory::~KviInputHistory()
{
	delete m_pStringList;
}

void KviInputHistory::add(TQString * s)
{
	m_pStringList->insert(0,s);
	if(m_pStringList->count() > KVI_INPUT_MAX_GLOBAL_HISTORY_ENTRIES)m_pStringList->removeLast();
}

void KviInputHistory::load(const char * filename)
{
	KviConfig c(filename,KviConfig::Read);

	int cnt = c.readIntEntry("Count",0);

	if(cnt > KVI_INPUT_MAX_GLOBAL_HISTORY_ENTRIES)cnt = KVI_INPUT_MAX_GLOBAL_HISTORY_ENTRIES;

	KviStr tmp;

	for(int i=0;i<cnt;i++)
	{
		tmp.sprintf("S%d",i);
		TQString entry = c.readTQStringEntry(tmp.ptr(),"");
		if(!entry.isEmpty())add(new TQString(entry));
	}
}

void KviInputHistory::save(const char * filename)
{
	KviConfig c(filename,KviConfig::Write);
	c.clear();

	c.writeEntry("Count",m_pStringList->count());

	KviStr tmp;
	int idx = 0;

	for(TQString * s = m_pStringList->first();s;s = m_pStringList->next())
	{
		if(!s->isEmpty())
		{
			tmp.sprintf("S%d",idx);
			c.writeEntry(tmp.ptr(),*s);
			idx++;
		}
	}
}

//=============== KviInputEditor ==============//

static int g_iInputFontCharWidth[256];
static bool g_bInputFontMetricsDirty = true;


KviInputEditor::KviInputEditor(TQWidget * par,KviWindow *wnd,KviUserListView * view)
:TQFrame(par,"input")
{
	m_pIconMenu            = 0;
	m_pInputParent         = par;
	m_iMaxBufferSize       = KVI_INPUT_MAX_BUFFER_SIZE;
	m_iCursorPosition      = 0;                             //Index of the char AFTER the cursor
	m_iFirstVisibleChar    = 0;                             //Index of the first visible character
	m_iSelectionBegin      = -1;                            //Index of the first char in the selection
	m_iSelectionEnd        = -1;                            //Index of the last char in the selection
	m_bIMComposing         = false;                         //Whether the input method is active (composing).
	// for input method support
	m_iIMStart             = 0;                             //Index of the start of the preedit string.
	m_iIMLength            = 0;                             //Length of the preedit string.
	m_iIMSelectionBegin    = 0;                             //Index of the start of the selection in preedit string.
	m_iIMSelectionLength   = 0;                             //Length of the selection in preedit string.

	m_bCursorOn            = false;                         //Cursor state
	m_iCursorTimer         = 0;                             //Timer that iverts the cursor state
	m_iDragTimer           = 0;                             //Timer for drag selection updates
	m_iLastCursorXPosition = KVI_INPUT_MARGIN;              //Calculated in paintEvent
	m_iSelectionAnchorChar = -1;                            //Character clicked at the beginning of the selection process
	m_iCurHistoryIdx       = -1;                            //No data in the history
	m_bUpdatesEnabled      = true;
	m_pKviWindow           = wnd;
	m_pUserListView        = view;
	m_pHistory             = new KviPointerList<TQString>;
	m_pHistory->setAutoDelete(true);
	m_bReadOnly = FALSE;
	
	setInputMethodEnabled(true);

#ifdef COMPILE_USE_QT4
	setAutoFillBackground(false);
	setFocusPolicy(TQ_StrongFocus);
#else
	setBackgroundMode(TQt::NoBackground);
	setFocusPolicy(TQ_StrongFocus);
#endif
	setAcceptDrops(true);
	setFrameStyle( LineEditPanel );
	setFrameShadow( Plain );
	
	m_pIconMenu = new KviTalPopupMenu();
	connect(m_pIconMenu,TQT_SIGNAL(activated(int)),this,TQT_SLOT(iconPopupActivated(int)));

#ifdef COMPILE_USE_QT4
	setCursor(TQt::IBeamCursor);
#else
	setCursor(IbeamCursor);
#endif
}

KviInputEditor::~KviInputEditor()
{
	if(g_pLastFontMetrics) delete g_pLastFontMetrics;
	g_pLastFontMetrics = 0;
	if(m_pIconMenu)delete m_pIconMenu;
	delete m_pHistory;
	if(m_iCursorTimer)killTimer(m_iCursorTimer);
	killDragTimer();
}

void KviInputEditor::recalcFontMetrics(TQFontMetrics * pFm)
{
	TQFontMetrics fm(KVI_OPTION_FONT(KviOption_fontInput));
	unsigned short i;
	for(i=1;i<32;i++)
	{
		TQChar c = getSubstituteChar(i);
		g_iInputFontCharWidth[i] = fm.width(c);
		if(c != TQChar(i))g_iInputFontCharWidth[i] += 4;
	}
	for(i=32;i<256;i++)
	{
		g_iInputFontCharWidth[i] = fm.width(TQChar(i));
	}
	g_bInputFontMetricsDirty = false;
}

void KviInputEditor::applyOptions()
{
	g_bInputFontMetricsDirty = true;
	update();
}

void KviInputEditor::dragEnterEvent(TQDragEnterEvent *e)
{
	if(KviUriDrag::canDecode(e))
	{
		e->accept(true);
// FIXME: #warning "FIX THIS COMMENTED STUFF"
/*
		m_pKviWindow->m_pFrm->m_pStatusBar->tempText(__tr("Drop the file to /PARSE it"),5000);
*/
	} else e->accept(false);
}

void KviInputEditor::dropEvent(TQDropEvent *e)
{
	TQStringList list;
	if(KviUriDrag::decodeLocalFiles(e,list))
	{
		//debug("Local files decoded");
		if(!list.isEmpty())
		{
			//debug("List not empty");
			TQStringList::ConstIterator it = list.begin(); //kewl ! :)
    		for( ; it != list.end(); ++it )
			{
				TQString tmp = *it; //wow :)
#ifndef COMPILE_ON_WINDOWS
				if(tmp.length() > 0)
				{
					if(tmp[0] != TQChar('/'))tmp.prepend("/"); //HACK HACK HACK for TQt bug (?!?)
				}
#endif
				tmp.prepend("/PARSE \"");
				tmp.append("\"");
				if(m_pKviWindow)
					KviKvsScript::run(tmp,m_pKviWindow);
			}
		}
	}
}

int  KviInputEditor::heightHint() const
{
	return sizeHint().height();
}

TQSize KviInputEditor::sizeHint() const
{
	//grabbed from qlineedit.cpp
	constPolish();
	TQFontMetrics fm(KVI_OPTION_FONT(KviOption_fontInput));
	int h = TQMAX(fm.lineSpacing(), 14) + 2*2; /* innerMargin */
	int w = fm.width( 'x' ) * 17; // "some"
	int m = frameWidth() * 2;
#ifdef COMPILE_USE_QT4
	TQStyleOption opt;
	opt.initFrom(this);
	return (style()->sizeFromContents(TQStyle::CT_LineEdit,&opt,
				     TQSize( w + m, h + m ).
				     expandedTo(TQApplication::globalStrut()),this));
#else
	return (style().tqsizeFromContents(TQStyle::CT_LineEdit, this,
				     TQSize( w + m, h + m ).
				     expandedTo(TQApplication::globalStrut())));
#endif
}

#define KVI_INPUT_DEF_BACK 100
#define KVI_INPUT_DEF_FORE 101

#ifdef COMPILE_USE_QT4
void KviInputEditor::paintEvent(TQPaintEvent *e)
{
	TQPainter p(this);
	SET_ANTI_ALIASING(p);
	drawFrame(&p);
	drawContents(&p);
}
#endif

void KviInputEditor::drawContents(TQPainter *p)
{
	if(!isVisible())return;

	TQRect rect = contentsRect();
	int widgetWidth       = rect.width();
	int widgetHeight      = rect.height();

	KviDoubleBuffer doublebuffer(widgetWidth,widgetHeight);
	TQPixmap * pDoubleBufferPixmap = doublebuffer.pixmap();

	TQPainter pa(pDoubleBufferPixmap);
	SET_ANTI_ALIASING(pa);

	pa.setFont(KVI_OPTION_FONT(KviOption_fontInput));

	TQFontMetrics fm(pa.fontMetrics());
	
	if(!g_pLastFontMetrics) 
		g_pLastFontMetrics = new TQFontMetrics(pa.fontMetrics());
	
	if(g_bInputFontMetricsDirty)
		recalcFontMetrics(&fm);


#ifdef COMPILE_PSEUDO_TRANSPARENCY
	if(g_pShadedChildGlobalDesktopBackground)
	{
		TQPoint pnt = mapToGlobal(rect.topLeft());
		pa.drawTiledPixmap(0,0,widgetWidth,widgetHeight,*g_pShadedChildGlobalDesktopBackground,pnt.x(),pnt.y());
	} else {
#endif
		TQPixmap *pix=KVI_OPTION_PIXMAP(KviOption_pixmapInputBackground).pixmap();
		
		pa.fillRect(0,0,widgetWidth,widgetHeight,KVI_OPTION_COLOR(KviOption_colorInputBackground));
		if(pix)
			KviPixmapUtils::drawPixmapWithPainter(&pa,pix,KVI_OPTION_UINT(KviOption_uintInputPixmapAlign),rect,widgetWidth,widgetHeight);
#ifdef COMPILE_PSEUDO_TRANSPARENCY
	}
#endif


	int curXPos      = KVI_INPUT_MARGIN;
	int maxXPos      = widgetWidth-2*KVI_INPUT_MARGIN;
	m_iCurBack       = KVI_INPUT_DEF_BACK; //transparent
	m_iCurFore       = KVI_INPUT_DEF_FORE; //normal fore color
	m_bCurBold       = false;
	m_bCurUnderline  = false;

	int bottom       = widgetHeight-(widgetHeight-fm.height())/2;
	int textBaseline = fm.ascent()+(widgetHeight-fm.height())/2;
	int top          = (widgetHeight-fm.height())/2;
	
	runUpToTheFirstVisibleChar();

	int charIdx      = m_iFirstVisibleChar;

	pa.setClipRect(0,0,widgetWidth,widgetHeight);

	//Control the selection state
	if((m_iSelectionEnd < m_iSelectionBegin) || (m_iSelectionEnd == -1) || (m_iSelectionBegin == -1))
	{
		m_iSelectionEnd = -1;
		m_iSelectionBegin = -1;
	}

	if((m_iSelectionBegin != -1) && (m_iSelectionEnd >= m_iFirstVisibleChar))
	{
		int iSelStart = m_iSelectionBegin;

    // TODO Refactor: write a function to combine this with the code determining iIMStart and iIMSelectionStart
		if(iSelStart < m_iFirstVisibleChar)iSelStart = m_iFirstVisibleChar;
		int xLeft = xPositionFromCharIndex(fm,iSelStart,TRUE);
		int xRight = xPositionFromCharIndex(fm,m_iSelectionEnd + 1,TRUE);

//		pa.setRasterOp(TQt::NotROP);
		pa.fillRect(xLeft,frameWidth(),xRight - xLeft,widgetWidth,KVI_OPTION_COLOR(KviOption_colorInputSelectionBackground));
//		pa.setRasterOp(TQt::CopyROP);
	}

	// When m_bIMComposing is true, the text between m_iIMStart and m_iIMStart+m_iIMLength should be highlighted to show that this is the active
	// preedit area for the input method, and the text outside cannot be edited while
	// composing. Maybe this can be implemented similarly as painting the selection?
	// Also notice that inside the preedit, there can also be a selection, given by
	// m_iSelectionBegin and m_iSelectionLength, and the widget needs to highlight that
	// while in IM composition mode
	if(m_bIMComposing && m_iIMLength > 0)
	{
		// TODO Write a function to combine IM selection drawing code. maybe the preedit area too.
		int iIMSelectionStart = m_iIMSelectionBegin;
		if(iIMSelectionStart < m_iFirstVisibleChar) iIMSelectionStart = m_iFirstVisibleChar;
		int xIMSelectionLeft = xPositionFromCharIndex(fm,iIMSelectionStart,TRUE);
		int xIMSelectionRight = xPositionFromCharIndex(fm,iIMSelectionStart + m_iIMSelectionLength,TRUE);
//		pa.setRasterOp(TQt::NotROP);
		pa.fillRect(xIMSelectionLeft,0,xIMSelectionRight - xIMSelectionLeft, widgetWidth,KVI_OPTION_COLOR(KviOption_colorInputSelectionBackground));
//		pa.setRasterOp(TQt::CopyROP);
 
		// highlight the IM selection
		int iIMStart = m_iIMStart;
		if(m_iIMStart < m_iFirstVisibleChar) m_iIMStart = m_iFirstVisibleChar;
		int xIMLeft = xPositionFromCharIndex(fm,iIMStart,TRUE);
		int xIMRight = xPositionFromCharIndex(fm,iIMStart + m_iIMLength,TRUE);

		// underline the IM preedit
		// Maybe should be put in drawTextBlock, similar to drawing underlined text
		pa.drawLine(xIMLeft, bottom, xIMRight, bottom);
	}

	pa.setClipping(false);

	while((charIdx < ((int)(m_szTextBuffer.length()))) && (curXPos < maxXPos))
	{
		extractNextBlock(charIdx,fm,curXPos,maxXPos);

		if(m_bControlBlock)
		{
			pa.setPen(KVI_OPTION_COLOR(KviOption_colorInputControl));

			TQString s = getSubstituteChar(m_szTextBuffer[charIdx].unicode());

			// the block width is 4 pixels more than the actual character

			pa.drawText(curXPos + 2,textBaseline,s,1);

			pa.drawRect(curXPos,top,m_iBlockWidth-1,bottom);
		} else {
			if(m_iSelectionBegin!=-1)
			{
				int iBlockEnd=charIdx+m_iBlockLen;
				//block is selected (maybe partially)
				if( iBlockEnd>m_iSelectionBegin && charIdx<=m_iSelectionEnd )
				{
					int iSubStart,iSubLen;
					//in common it consists of 3 parts: unselected-selected-unselected
					//some of thst parts can be empty (for example block is fully selected)
					
					//first part start is always equal to the block start
					iSubStart=charIdx;
					iSubLen = m_iSelectionBegin>charIdx ? m_iSelectionBegin-charIdx : 0;
					
				
					if(iSubLen)
					{
						drawTextBlock(&pa,fm,curXPos,textBaseline,iSubStart,iSubLen,FALSE);
						curXPos += m_iBlockWidth;
						m_iBlockWidth=0;
					}
					
					//second one
					iSubStart+=iSubLen;
					iSubLen=m_iSelectionEnd<iBlockEnd ? m_iSelectionEnd-iSubStart+1 : iBlockEnd-iSubStart;
					
					
					if(iSubLen)
					{
						drawTextBlock(&pa,fm,curXPos,textBaseline,iSubStart,iSubLen,TRUE);
						curXPos += m_iBlockWidth;
						m_iBlockWidth=0;
					}
					
					if( m_iSelectionEnd<(iBlockEnd-1))
					{
						iSubStart+=iSubLen;
						iSubLen=iBlockEnd-iSubStart;
						drawTextBlock(&pa,fm,curXPos,textBaseline,iSubStart,iSubLen,FALSE);
					}
				} else {
					drawTextBlock(&pa,fm,curXPos,textBaseline,charIdx,m_iBlockLen);
				}
			} else {
				drawTextBlock(&pa,fm,curXPos,textBaseline,charIdx,m_iBlockLen);
			}
		}

		curXPos += m_iBlockWidth;
		charIdx += m_iBlockLen;
	}
	
	//Now the cursor

	m_iLastCursorXPosition = KVI_INPUT_MARGIN;
	m_iBlockLen = m_iFirstVisibleChar;

	while(m_iBlockLen < m_iCursorPosition)
	{
		TQChar c = m_szTextBuffer.at(m_iBlockLen);
#ifdef COMPILE_USE_QT4
		m_iLastCursorXPosition+= c.unicode() < 32 ? fm.width(getSubstituteChar(c.unicode())) + 3 : fm.width(c);
#else
		m_iLastCursorXPosition+= (c.unicode() < 256) ? g_iInputFontCharWidth[c.unicode()] : fm.width(c);
#endif
		m_iBlockLen++;
	}

	//m_iLastCursorXPosition = cur1XPos;

	if(m_bCursorOn)
	{
		pa.setPen(KVI_OPTION_COLOR(KviOption_colorInputCursor));
		pa.drawLine(m_iLastCursorXPosition,0,m_iLastCursorXPosition,widgetHeight);
	} else {
		pa.setPen(KVI_OPTION_COLOR(KviOption_colorInputForeground));
	}

#ifdef COMPILE_USE_QT4
	// The other version of drawPixmap seems to be buggy
	p->drawPixmap(rect.x(),rect.y(),rect.width(),rect.height(),*pDoubleBufferPixmap,0,0,widgetWidth,widgetHeight);
#else
	p->drawPixmap(rect.x(),rect.y(),*pDoubleBufferPixmap,0,0,widgetWidth,widgetHeight);
#endif
}

void KviInputEditor::drawTextBlock(TQPainter * pa,TQFontMetrics & fm,int curXPos,int textBaseline,int charIdx,int len,bool bSelected)
{
	TQString tmp = m_szTextBuffer.mid(charIdx,len);
	m_iBlockWidth = fm.width(tmp);
	
	TQRect rect = contentsRect();
	int widgetHeight      = rect.height();
	
	if(m_iCurFore == KVI_INPUT_DEF_FORE)
	{
		pa->setPen( bSelected ? KVI_OPTION_COLOR(KviOption_colorInputSelectionForeground) : KVI_OPTION_COLOR(KviOption_colorInputForeground));
	} else {
		if(((unsigned char)m_iCurFore) > 16)
		{
			pa->setPen(KVI_OPTION_COLOR(KviOption_colorInputBackground));
		} else {
			pa->setPen(KVI_OPTION_MIRCCOLOR((unsigned char)m_iCurFore));
		}
	}

	if(m_iCurBack != KVI_INPUT_DEF_BACK)
	{
		if(((unsigned char)m_iCurBack) > 16)
		{
			pa->fillRect(curXPos,(widgetHeight-fm.height())/2,m_iBlockWidth,fm.height(),KVI_OPTION_COLOR(KviOption_colorInputForeground));
		} else {
			pa->fillRect(curXPos,(widgetHeight-fm.height())/2,m_iBlockWidth,fm.height(),KVI_OPTION_MIRCCOLOR((unsigned char)m_iCurBack));
		}
	}

	pa->drawText(curXPos,textBaseline,tmp);

	if(m_bCurBold)pa->drawText(curXPos+1,textBaseline,tmp);
	if(m_bCurUnderline)
	{
		pa->drawLine(curXPos,textBaseline + fm.descent(),curXPos+m_iBlockWidth,textBaseline + fm.descent());
	}
	
}

TQChar KviInputEditor::getSubstituteChar(unsigned short control_code)
{
	switch(control_code)
	{
		case KVI_TEXT_COLOR:
			return TQChar('K');
			break;
		case KVI_TEXT_BOLD:
			return TQChar('B');
			break;
		case KVI_TEXT_RESET:
			return TQChar('O');
			break;
		case KVI_TEXT_REVERSE:
			return TQChar('R');
			break;
		case KVI_TEXT_UNDERLINE:
			return TQChar('U');
			break;
		case KVI_TEXT_CRYPTESCAPE:
			return TQChar('P');
			break;
		case KVI_TEXT_ICON:
			return TQChar('I');
			break;
		default:
			return TQChar(control_code);
			break;
	}
}

void KviInputEditor::extractNextBlock(int idx,TQFontMetrics & fm,int curXPos,int maxXPos)
{
	m_iBlockLen = 0;
	m_iBlockWidth = 0;

	TQChar c = m_szTextBuffer[idx];

	if((c.unicode() > 32) ||
		((c != TQChar(KVI_TEXT_COLOR)) &&
		(c != TQChar(KVI_TEXT_BOLD)) && (c != TQChar(KVI_TEXT_UNDERLINE)) &&
		(c != TQChar(KVI_TEXT_RESET)) && (c != TQChar(KVI_TEXT_REVERSE)) &&
		(c != TQChar(KVI_TEXT_CRYPTESCAPE)) && (c != TQChar(KVI_TEXT_ICON))))
	{
		m_bControlBlock = false;
		//Not a control code...run..
		while((idx < ((int)(m_szTextBuffer.length()))) && (curXPos < maxXPos))
		{
			c = m_szTextBuffer[idx];
			if((c.unicode() > 32) ||
				((c != TQChar(KVI_TEXT_COLOR)) && (c != TQChar(KVI_TEXT_BOLD)) &&
				(c != TQChar(KVI_TEXT_UNDERLINE)) && (c != TQChar(KVI_TEXT_RESET)) &&
				(c != TQChar(KVI_TEXT_REVERSE)) && (c != TQChar(KVI_TEXT_CRYPTESCAPE)) &&
				(c != TQChar(KVI_TEXT_ICON))))
			{
				m_iBlockLen++;
#ifdef COMPILE_USE_QT4
				int xxx = c.unicode() < 32 ? fm.width(getSubstituteChar(c.unicode())) + 3 : fm.width(c);;
#else
				int xxx = (c.unicode() < 256 ? g_iInputFontCharWidth[c.unicode()] : fm.width(c));
#endif
				m_iBlockWidth +=xxx;
				curXPos       +=xxx;
				idx++;
			} else break;
		}
		return;
	} else {
		m_bControlBlock = true;
		m_iBlockLen = 1;
		m_iBlockWidth = g_iInputFontCharWidth[c.unicode()];
		//Control code
		switch(c.unicode())
		{
			case KVI_TEXT_BOLD:
				m_bCurBold = ! m_bCurBold;
				break;
			case KVI_TEXT_UNDERLINE:
				m_bCurUnderline = ! m_bCurUnderline;
				break;
			case KVI_TEXT_RESET:
				m_iCurFore = KVI_INPUT_DEF_FORE;
				m_iCurBack = KVI_INPUT_DEF_BACK;
				m_bCurBold = false;
				m_bCurUnderline = false;
				break;
			case KVI_TEXT_REVERSE:
			{
				char auxClr = m_iCurFore;
				m_iCurFore  = m_iCurBack;
				m_iCurBack  = auxClr;
			}
			break;
			case KVI_TEXT_CRYPTESCAPE:
			case KVI_TEXT_ICON:
				// makes a single block
				break;
			case KVI_TEXT_COLOR:
			{
				idx++;
				if(idx >= ((int)(m_szTextBuffer.length())))return;
				unsigned char fore;
				unsigned char back;
				idx = getUnicodeColorBytes(m_szTextBuffer,idx,&fore,&back);
				if(fore != KVI_NOCHANGE)
				{
					m_iCurFore = fore;
					if(back != KVI_NOCHANGE)m_iCurBack = back;
				} else {
					// ONLY a CTRL+K
					m_iCurBack = KVI_INPUT_DEF_BACK;
					m_iCurFore = KVI_INPUT_DEF_FORE;
				}
			}
			break;
			default:
				debug("Ops..");
				exit(0);
			break;
		}
	}
}

void KviInputEditor::runUpToTheFirstVisibleChar()
{
	register int idx = 0;
	while(idx < m_iFirstVisibleChar)
	{
		unsigned short c = m_szTextBuffer[idx].unicode();
		if(c < 32)
		{
			switch(c)
			{
				case KVI_TEXT_BOLD:
					m_bCurBold = ! m_bCurBold;
					break;
				case KVI_TEXT_UNDERLINE:
					m_bCurUnderline = ! m_bCurUnderline;
					break;
				case KVI_TEXT_RESET:
					m_iCurFore = KVI_INPUT_DEF_FORE;
					m_iCurBack = KVI_INPUT_DEF_BACK;
					m_bCurBold = false;
					m_bCurUnderline = false;
					break;
				case KVI_TEXT_REVERSE:
				{
					char auxClr = m_iCurFore;
					m_iCurFore  = m_iCurBack;
					m_iCurBack  = auxClr;
				}
				break;
				case KVI_TEXT_COLOR:
				{
					idx++;
					if(idx >= ((int)(m_szTextBuffer.length())))return;
					unsigned char fore;
					unsigned char back;
					idx = getUnicodeColorBytes(m_szTextBuffer,idx,&fore,&back);
					idx--;
					if(fore != KVI_NOCHANGE)m_iCurFore = fore;
					else m_iCurFore = KVI_INPUT_DEF_FORE;
					if(back != KVI_NOCHANGE)m_iCurBack = back;
					else m_iCurBack = KVI_INPUT_DEF_BACK;
				}
				break;
				case 0:
					debug("KviInputEditor::Encountered invisible end of the string!");
					exit(0);
				break;
			}
		}
		idx++;
	}
}


void KviInputEditor::mousePressEvent(TQMouseEvent *e)
{
	if(e->button() & Qt::LeftButton)
	{
		m_iCursorPosition = charIndexFromXPosition(e->pos().x());
		//move the cursor to
		int anchorX =  xPositionFromCharIndex(m_iCursorPosition);
		if(anchorX > (width()-frameWidth()))m_iFirstVisibleChar++;
		m_iSelectionAnchorChar = m_iCursorPosition;
		selectOneChar(-1);
		//grabMouse(TQCursor(crossCursor));
		repaintWithCursorOn();
		killDragTimer();
		m_iDragTimer = startTimer(KVI_INPUT_DRAG_TIMEOUT);

	} else if(e->button() & Qt::RightButton)
	{
        int type = g_pActiveWindow->type();

		//Popup menu
		g_pInputPopup->clear();
		
		TQString szClip;

		TQClipboard * c = TQApplication::clipboard();
		if(c)
		{
			szClip = c->text(TQClipboard::Clipboard);
			
#ifdef COMPILE_USE_QT4
			int occ = szClip.count(TQChar('\n'));
#else
			int occ = szClip.contains(TQChar('\n'));
#endif
	
			if(!szClip.isEmpty())
			{
				if(szClip.length() > 60)
				{
					szClip.truncate(60);
					szClip.append("...");
				}
				szClip.replace(TQChar('&'),"&amp;");
				szClip.replace(TQChar('<'),"&lt;");
				szClip.replace(TQChar('>'),"&gt;");
				szClip.replace(TQChar('\n'),"<br>");
	
				TQString label = "<center><b>";
				label += __tr2qs("Clipboard");
				label += ":</b><br>";
				label += szClip;
				label += "<br><b>";
	
				TQString num;
				num.setNum(occ);
	
				label += num;
				label += TQChar(' ');
				label += (occ == 1) ? __tr2qs("line break") : __tr2qs("line breaks");
				label += "</b></center>";
	
				TQLabel * l = new TQLabel(label,g_pInputPopup);
				l->setFrameStyle(TQFrame::Raised | TQFrame::StyledPanel);
				l->setMargin(5);
				// FIXME: This does NOT work under TQt 4.x (they seem to consider it as bad UI design)
#ifndef COMPILE_USE_QT4
				g_pInputPopup->insertItem(l);
#else
				delete l;
#endif
			}
		}
		
		int id = g_pInputPopup->insertItem(__tr2qs("Cu&t") + ACCEL_KEY(X),this,TQT_SLOT(cut()));
		g_pInputPopup->setItemEnabled(id,hasSelection());
		id = g_pInputPopup->insertItem(__tr2qs("&Copy") + ACCEL_KEY(C),this,TQT_SLOT(copyToClipboard()));
		g_pInputPopup->setItemEnabled(id,hasSelection());
		id = g_pInputPopup->insertItem(__tr2qs("&Paste") + ACCEL_KEY(V),this,TQT_SLOT(pasteClipboardWithConfirmation()));
		g_pInputPopup->setItemEnabled(id,!szClip.isEmpty() && !m_bReadOnly);
		id = g_pInputPopup->insertItem(__tr2qs("Paste (Slowly)"),this,TQT_SLOT(pasteSlow()));
		if ((type == KVI_WINDOW_TYPE_CHANNEL) || (type == KVI_WINDOW_TYPE_QUERY) || (type == KVI_WINDOW_TYPE_DCCCHAT))
			g_pInputPopup->setItemEnabled(id,!szClip.isEmpty() && !m_bReadOnly);
		else 
			g_pInputPopup->setItemEnabled(id,false);
		id = g_pInputPopup->insertItem(__tr2qs("Paste &File") + ACCEL_KEY(F),this,TQT_SLOT(pasteFile()));
		if ((type != KVI_WINDOW_TYPE_CHANNEL) && (type != KVI_WINDOW_TYPE_QUERY) && (type != KVI_WINDOW_TYPE_DCCCHAT))
			g_pInputPopup->setItemEnabled(id,false);
		else
			g_pInputPopup->setItemEnabled(id,!m_bReadOnly);
		if(m_bSpSlowFlag ==true)
		{
			id = g_pInputPopup->insertItem(__tr2qs("Stop Paste"),this,TQT_SLOT(stopPasteSlow())); /*G&N 2005*/
		}
		id = g_pInputPopup->insertItem(__tr2qs("Clear"),this,TQT_SLOT(clear()));
		g_pInputPopup->setItemEnabled(id,!m_szTextBuffer.isEmpty() && !m_bReadOnly);
		g_pInputPopup->insertSeparator();
		id = g_pInputPopup->insertItem(__tr2qs("Select All"),this,TQT_SLOT(selectAll()));
		g_pInputPopup->setItemEnabled(id,(!m_szTextBuffer.isEmpty()));
		
		
		g_pInputPopup->insertSeparator();
		m_pIconMenu->clear();
		
		KviPointerHashTable<TQString,KviTextIcon> * d = g_pTextIconManager->textIconDict();
		KviPointerHashTableIterator<TQString,KviTextIcon> it(*d);
		TQStringList strList;
		while(KviTextIcon * i = it.current())
		{
			strList.append(it.currentKey());
			++it;
		}
		strList.sort();
		KviTextIcon * icon;
		TQPixmap *pix;
		
		for(TQStringList::Iterator iter = strList.begin(); iter != strList.end(); ++iter)
		{
			icon=g_pTextIconManager->lookupTextIcon(*iter);
			if(icon)
			{
				pix = icon->pixmap();
				if(pix) m_pIconMenu->insertItem(*pix,*iter);
			}
		}
		
		g_pInputPopup->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_BIGGRIN)),__tr2qs("Insert Icon"),m_pIconMenu);
		g_pInputPopup->popup(mapToGlobal(e->pos()));
	} else {
		pasteSelectionWithConfirmation();
	}
}
void KviInputEditor::iconPopupActivated(int id)
{
	if(!m_bReadOnly)
	{
		TQString text = m_pIconMenu->text(id);
		if(!text.isEmpty())
		{
			text.prepend(KVI_TEXT_ICON);
			text.append(' ');
			insertText(text);
		}
	}
}

bool KviInputEditor::hasSelection()
{
	return ((m_iSelectionBegin != -1)&&(m_iSelectionEnd != -1));
}

void KviInputEditor::copyToClipboard()
{
	if(!hasSelection())return;
	TQClipboard * c = TQApplication::clipboard();
	if(!c)return;
	TQString szTxt = m_szTextBuffer.mid(m_iSelectionBegin,(m_iSelectionEnd-m_iSelectionBegin)+1);
	c->setText(szTxt,TQClipboard::Clipboard);
	repaintWithCursorOn();
}

void KviInputEditor::copyToSelection(bool bDonNotCopyToClipboard)
{
	if(!hasSelection())return;
	TQClipboard * c = TQApplication::clipboard();
	if(!c)return;
	TQString szTxt = m_szTextBuffer.mid(m_iSelectionBegin,(m_iSelectionEnd-m_iSelectionBegin)+1);
	if(c->supportsSelection())
		c->setText(szTxt,TQClipboard::Selection);
	else if(!bDonNotCopyToClipboard)
		c->setText(szTxt,TQClipboard::Clipboard);
	repaintWithCursorOn();
}


void KviInputEditor::moveCursorTo(int idx,bool bRepaint)
{
	if(idx < 0)idx = 0;
	if(idx > ((int)(m_szTextBuffer.length())))idx = m_szTextBuffer.length();
	if(idx > m_iCursorPosition)
	{
		while(m_iCursorPosition < idx)
		{
			moveRightFirstVisibleCharToShowCursor();
			m_iCursorPosition++;
		}
	} else {
		m_iCursorPosition = idx;
		if(m_iFirstVisibleChar > m_iCursorPosition)m_iFirstVisibleChar = m_iCursorPosition;
	}
	if(bRepaint)repaintWithCursorOn();
}

void KviInputEditor::removeSelected()
{
	if(!hasSelection())return;
	m_szTextBuffer.remove(m_iSelectionBegin,(m_iSelectionEnd-m_iSelectionBegin)+1);
	moveCursorTo(m_iSelectionBegin,false);
	selectOneChar(-1);
	repaintWithCursorOn();
}

void KviInputEditor::cut()
{
	if(!hasSelection())return;
	TQClipboard * c = TQApplication::clipboard();
	if(!c)return;
	c->setText(m_szTextBuffer.mid(m_iSelectionBegin,(m_iSelectionEnd-m_iSelectionBegin)+1),TQClipboard::Clipboard);
	m_szTextBuffer.remove(m_iSelectionBegin,(m_iSelectionEnd-m_iSelectionBegin)+1);
	moveCursorTo(m_iSelectionBegin,false);
	selectOneChar(-1);
	repaintWithCursorOn();
}

void KviInputEditor::insertText(const TQString &text)
{
	TQString szText = text; // crop away constness
	if(szText.isEmpty())return;

	//szText.replaceAll('\t'," "); //Do not paste tabs

	//szText.replace(TQRegExp("\t")," "); // do not paste tabs

	m_bUpdatesEnabled = false;
	removeSelected();
	m_bUpdatesEnabled = true;

	if(szText.find('\n') == -1)
	{
		m_szTextBuffer.insert(m_iCursorPosition,szText);
		m_szTextBuffer.truncate(m_iMaxBufferSize);
		moveCursorTo(m_iCursorPosition + szText.length());
	} else {
		//Multiline paste...do not execute commands here
		TQString szBlock;
		while(!szText.isEmpty())
		{
			int idx = szText.find('\n');
			if(idx != -1)
			{
				szBlock = szText.left(idx);
				//else szBlock = TQChar(KVI_TEXT_RESET);
				szText.remove(0,idx+1);
			} else {
				szBlock = szText;
				szText  = "";
			}

			m_szTextBuffer.insert(m_iCursorPosition,szBlock);
			m_szTextBuffer.truncate(m_iMaxBufferSize);

			int pos = 0;
			while((pos < ((int)(m_szTextBuffer.length()))) && (m_szTextBuffer[pos] < 33))pos++;
			if((pos < ((int)(m_szTextBuffer.length()))) && (m_szTextBuffer[pos] == TQChar('/')))m_szTextBuffer.insert(pos,"\\");

			returnPressed(idx != -1);
		}
	}
}

// Replace (length) characters in the buffer from (start) with (text), returns
// the length of the text inserted (different from text.length() only if the 
// buffer was truncated.
int KviInputEditor::replaceSegment(int start, int length, const TQString &text)
{
	m_szTextBuffer.remove(start, length);
	m_szTextBuffer.insert(start, text);
	m_szTextBuffer.truncate(m_iMaxBufferSize);
	repaintWithCursorOn();

	int iInsertedLength = text.length();
	int iMaxInsertedLength = m_iMaxBufferSize - start;
	if(iInsertedLength > iMaxInsertedLength) return iMaxInsertedLength;
	return iInsertedLength;
}

void KviInputEditor::pasteClipboardWithConfirmation()
{
	TQClipboard * c = TQApplication::clipboard();
	if(!c)return;
	TQString szText = c->text(TQClipboard::Clipboard);

	if(szText.contains(TQChar('\n')) > 0)
	{
		if(m_pInputParent->inherits("KviInput"))
			((KviInput*)(m_pInputParent))->multiLinePaste(szText);
	} else {
		insertText(szText);
	}
}

void KviInputEditor::pasteSelectionWithConfirmation()
{
	TQClipboard * c = TQApplication::clipboard();
	if(!c)return;
	TQString szText = c->text(c->supportsSelection() ? TQClipboard::Selection : TQClipboard::Clipboard);

	if(szText.contains(TQChar('\n')) > 0)
	{
		if(m_pInputParent->inherits("KviInput"))
			((KviInput*)(m_pInputParent))->multiLinePaste(szText);
	} else {
		insertText(szText);
	}
}

void KviInputEditor::pasteSlow()
{
	KviKvsScript::run("spaste.clipboard",g_pActiveWindow);
	m_bSpSlowFlag = true;
}

void KviInputEditor::stopPasteSlow()
{
	KviKvsScript::run("spaste.stop",g_pActiveWindow);
	m_bSpSlowFlag = false;
}

void KviInputEditor::pasteFile()
{
	TQString stmp = TQFileDialog::getOpenFileName("","",this,"Paste File", "Choose a file" );
	if(stmp!="")
	{
		TQString stmp1 = "spaste.file " + stmp ;
		KviKvsScript::run(stmp1,g_pActiveWindow);
		m_bSpSlowFlag = true;
	}
}

void KviInputEditor::selectAll()
{
	if(m_szTextBuffer.length() > 0)
	{
		m_iSelectionBegin = 0;
		m_iSelectionEnd = m_szTextBuffer.length()-1;
	}
	end();
}

void KviInputEditor::clear()
{
	m_szTextBuffer = "";
	selectOneChar(-1);
	home();
}

void KviInputEditor::setText(const TQString text)
{
	m_szTextBuffer = text;
	m_szTextBuffer.truncate(m_iMaxBufferSize);
	selectOneChar(-1);
	end();
}

void KviInputEditor::mouseReleaseEvent(TQMouseEvent *)
{
	if(m_iDragTimer)
	{
		m_iSelectionAnchorChar =-1;
		//releaseMouse();
		killDragTimer();
	}
	if(hasSelection())
		copyToSelection();
}

void KviInputEditor::killDragTimer()
{
	if(m_iDragTimer)
	{
		killTimer(m_iDragTimer);
		m_iDragTimer = 0;
	}
}

void KviInputEditor::timerEvent(TQTimerEvent *e)
{
	if(e->timerId() == m_iCursorTimer)
	{
		if(!hasFocus() || !isVisibleToTLW())
		{
			killTimer(m_iCursorTimer);
			m_iCursorTimer = 0;
			m_bCursorOn = false;
		} else m_bCursorOn = ! m_bCursorOn;
		update();
	} else {
		//Drag timer
		handleDragSelection();
	}
}

void KviInputEditor::handleDragSelection()
{
	if(m_iSelectionAnchorChar == -1)return;

	TQPoint pnt = mapFromGlobal(TQCursor::pos());


	if(pnt.x() <= 0)
	{
		//Left side dragging
		if(m_iFirstVisibleChar > 0)m_iFirstVisibleChar--;
		m_iCursorPosition = m_iFirstVisibleChar;
	} else if(pnt.x() >= width())
	{
		//Right side dragging...add a single character to the selection on the right
		if(m_iCursorPosition < ((int)(m_szTextBuffer.length())))
		{
			moveRightFirstVisibleCharToShowCursor();
			m_iCursorPosition++;
		} //else at the end of the selection...don't move anything
	} else {
		//Inside the window...
		m_iCursorPosition = charIndexFromXPosition(pnt.x());
	}
	if(m_iCursorPosition == m_iSelectionAnchorChar)selectOneChar(-1);
	else {
		if(m_iCursorPosition > m_iSelectionAnchorChar)
		{
			m_iSelectionBegin = m_iSelectionAnchorChar;
				m_iSelectionEnd   = m_iCursorPosition-1;
		} else {
			m_iSelectionBegin = m_iCursorPosition;
			m_iSelectionEnd   = m_iSelectionAnchorChar-1;
		}
	}
	repaintWithCursorOn();
}

void KviInputEditor::returnPressed(bool bRepaint)
{
	if (!m_szTextBuffer.isEmpty() /* && (!m_pHistory->current() || m_szTextBuffer.compare(*(m_pHistory->current())))*/)
	{
		if(m_pInputParent->inherits("KviInput"))
			g_pInputHistory->add(new TQString(m_szTextBuffer));

		m_pHistory->insert(0,new TQString(m_szTextBuffer));
	}

	__range_valid(KVI_INPUT_MAX_LOCAL_HISTORY_ENTRIES > 1); //ABSOLUTELY NEEDED, if not, pHist will be destroyed...
	if(m_pHistory->count() > KVI_INPUT_MAX_LOCAL_HISTORY_ENTRIES)m_pHistory->removeLast();

	m_iCurHistoryIdx = -1;

	// FIXME: ALL THIS STUFF SHOULD BE CONVERTED TO TQString
	/*
	if(m_pInputParent->inherits("KviInput"))
	{
		TQString szBuffer(m_szTextBuffer);
		m_szTextBuffer="";
		selectOneChar(-1);
		m_iCursorPosition = 0;
		m_iFirstVisibleChar = 0;
		if(bRepaint)repaintWithCursorOn();
		KviUserInput::parse(szBuffer,m_pKviWindow);
	} else {
	*/
	emit enterPressed();
	/*
		return;
	}
	*/
}

void KviInputEditor::focusInEvent(TQFocusEvent *)
{
	if(m_iCursorTimer==0)
	{
		m_iCursorTimer = startTimer(KVI_INPUT_BLINK_TIME);
		m_bCursorOn = true;
		update();
	}
	// XIM handling...
#ifndef COMPILE_USE_QT4
	// THIS SEEMS TO BE GONE IN TQt4.x ? (even if the documentation states that it *should* be there)
	setMicroFocusHint(1,1,width() - 2,height() - 2,true,0);
#endif
}

void KviInputEditor::focusOutEvent(TQFocusEvent *)
{
	if(m_iCursorTimer)killTimer(m_iCursorTimer);
	m_iCursorTimer = 0;
	m_bCursorOn = false;
	update();
}


void KviInputEditor::internalCursorRight(bool bShift)
{
	if(m_iCursorPosition >= ((int)(m_szTextBuffer.length())))return;
	moveRightFirstVisibleCharToShowCursor();
	//Grow the selection if needed
	if(bShift)
	{
		if((m_iSelectionBegin > -1)&&(m_iSelectionEnd > -1))
		{
			if(m_iSelectionEnd == m_iCursorPosition-1)m_iSelectionEnd++;
			else if(m_iSelectionBegin == m_iCursorPosition)m_iSelectionBegin++;
			else selectOneChar(m_iCursorPosition);
		} else selectOneChar(m_iCursorPosition);
	} else selectOneChar(-1);
	m_iCursorPosition++;
}

void KviInputEditor::internalCursorLeft(bool bShift)
{
	if(m_iCursorPosition <= 0)return;

	if(bShift)
	{
		if((m_iSelectionBegin > -1)&&(m_iSelectionEnd > -1))
		{
			if(m_iSelectionBegin == m_iCursorPosition)m_iSelectionBegin--;
			else if(m_iSelectionEnd == m_iCursorPosition-1)m_iSelectionEnd--;
			else selectOneChar(m_iCursorPosition - 1);
		} else selectOneChar(m_iCursorPosition - 1);
	} else selectOneChar(-1);

	m_iCursorPosition--;
	if(m_iFirstVisibleChar > m_iCursorPosition)m_iFirstVisibleChar--;
}

// remember the text before and after the cursor at this point, and put them
// before and after the text inserted by IM in imEndEvent.
//    hagabaka
void KviInputEditor::imStartEvent(TQIMEvent *e)
{
	removeSelected();
	m_iIMStart = m_iIMSelectionBegin = m_iCursorPosition;
	m_iIMLength = 0;
	m_bIMComposing = true;
	e->accept();
}

// Whenever the IM's preedit changes, update the visuals and internal data. refer to <http://doc.trolltech.com/3.3/qimevent.html> */
//    hagabaka
void KviInputEditor::imComposeEvent(TQIMEvent *e)
{
	// replace the old pre-edit string with e->text()
	m_bUpdatesEnabled = false;
#ifdef COMPILE_USE_QT4
	// TQt 4.x ??????????
	m_iIMLength = replaceSegment(m_iIMStart, m_iIMLength, e->commitString());

	// update selection inside the pre-edit
	m_iIMSelectionBegin = m_iIMStart + e->replacementStart();
	m_iIMSelectionLength = e->replacementLength();
	moveCursorTo(m_iIMSelectionBegin);

#else
	m_iIMLength = replaceSegment(m_iIMStart, m_iIMLength, e->text());

	// update selection inside the pre-edit
	m_iIMSelectionBegin = m_iIMStart + e->cursorPos();
	m_iIMSelectionLength = e->selectionLength();
	moveCursorTo(m_iIMSelectionBegin);
#endif


	// repaint
	m_bUpdatesEnabled = true;
	repaintWithCursorOn();
	e->accept();
}

// Input method is done; put its resulting text to where the preedit area was
//    hagabaka
void KviInputEditor::imEndEvent(TQIMEvent *e)
{
	// replace the preedit area with the IM result text
	m_bUpdatesEnabled = false;
#ifdef COMPILE_USE_QT4
	// TQt 4.x ??????????
	m_iIMLength = replaceSegment(m_iIMStart, m_iIMLength, e->commitString());
#else
	m_iIMLength = replaceSegment(m_iIMStart, m_iIMLength, e->text());
#endif

	// move cursor to after the IM result text
	moveCursorTo(m_iIMStart + m_iIMLength);

	// repaint
	m_bUpdatesEnabled = true;
	repaintWithCursorOn();

	// reset data
	m_bIMComposing = false;
	e->accept();
}

// FIXME According to <http://www.kde.gr.jp/~asaki/how-to-support-input-method.html>, if the XIM
//  style used is OverTheTop, code needs to be added in keyPressEvent handler */
//    hagabaka
void KviInputEditor::keyPressEvent(TQKeyEvent *e)
{
	// disable the keyPress handling when IM is in composition.
	if(m_bIMComposing)
	{
		e->ignore();
		return;
	}
	// completion thingies

	if(!m_bReadOnly)
	{
		if((e->key() == TQt::Key_Tab) || (e->key() == TQt::Key_BackTab))
		{
			completion(e->state() & TQt::ShiftButton);
			return;
		} else {
			m_bLastCompletionFinished=1;
		}
	}

	
	if(e->key() == TQt::Key_Escape)
	{
		emit escapePressed();
		return;
	}

	if((e->state() & TQt::AltButton) || (e->state() & TQt::ControlButton))
	{
		switch(e->key())
		{
			case TQt::Key_Backspace:
				if(m_pInputParent->inherits("KviInput"))
				{
					((KviInput*)(m_pInputParent))->multiLinePaste(m_szTextBuffer);
					clear();
					return;
				}
				break;
		}
	}

//Make CtrlKey and CommandKey ("Apple") behave equally on MacOSX.
//This way typical X11 and Apple shortcuts can be used simultanously within the input line.
#ifndef Q_OS_MACX
	if(e->state() & TQt::ControlButton)
#else
	if((e->state() & TQt::ControlButton) || (e->state() & TQt::MetaButton))
#endif
	{
		switch(e->key())
		{
			case TQt::Key_Right:
				if(m_iCursorPosition < ((int)(m_szTextBuffer.length())))
				{
					// skip whitespace
					while(m_iCursorPosition < ((int)(m_szTextBuffer.length())))
					{
						if(!m_szTextBuffer.at(m_iCursorPosition).isSpace())break;
						internalCursorRight(e->state() & TQt::ShiftButton);
					}
					// skip nonwhitespace
					while(m_iCursorPosition < ((int)(m_szTextBuffer.length())))
					{
						if(m_szTextBuffer.at(m_iCursorPosition).isSpace())break;
						internalCursorRight(e->state() & TQt::ShiftButton);
					}
					repaintWithCursorOn();
				}
			break;
			case TQt::Key_Left:
				if(m_iCursorPosition > 0)
				{
					// skip whitespace
					while(m_iCursorPosition > 0)
					{
						if(!m_szTextBuffer.at(m_iCursorPosition - 1).isSpace())break;
						internalCursorLeft(e->state() & TQt::ShiftButton);
					}
					// skip nonwhitespace
					while(m_iCursorPosition > 0)
					{
						if(m_szTextBuffer.at(m_iCursorPosition - 1).isSpace())break;
						internalCursorLeft(e->state() & TQt::ShiftButton);
					}
					repaintWithCursorOn();
				}
			break;
			case TQt::Key_K:
			{
				if(!m_bReadOnly)
				{
					insertChar(KVI_TEXT_COLOR);
					int xPos = xPositionFromCharIndex(m_iCursorPosition);
					if(xPos > 24)xPos-=24;
					if(!g_pColorWindow)g_pColorWindow = new KviColorWindow();
					if(xPos+g_pColorWindow->width() > width())xPos = width()-(g_pColorWindow->width()+2);
					g_pColorWindow->move(mapToGlobal(TQPoint(xPos,-35)));
					g_pColorWindow->popup(this);
				}
			}
			break;
			case TQt::Key_B:
				if(!m_bReadOnly) insertChar(KVI_TEXT_BOLD);
			break;
			case TQt::Key_O:
				if(!m_bReadOnly) insertChar(KVI_TEXT_RESET);
			break;
			case TQt::Key_U:
				if(!m_bReadOnly) insertChar(KVI_TEXT_UNDERLINE);
			break;
			case TQt::Key_R:
				if(!m_bReadOnly) insertChar(KVI_TEXT_REVERSE);
			break;
			case TQt::Key_P:
				if(!m_bReadOnly) insertChar(KVI_TEXT_CRYPTESCAPE); // DO NOT CRYPT THIS STUFF
			break;
			case TQt::Key_I:
			{
				if(!m_bReadOnly)
				{
					insertChar(KVI_TEXT_ICON); // THE NEXT WORD IS AN ICON NAME
					int xPos = xPositionFromCharIndex(m_iCursorPosition);
					if(xPos > 24)xPos-=24;
					if(!g_pTextIconWindow)g_pTextIconWindow = new KviTextIconWindow();
					if(xPos+g_pTextIconWindow->width() > width())xPos = width()-(g_pTextIconWindow->width()+2);
					g_pTextIconWindow->move(mapToGlobal(TQPoint(xPos,-KVI_TEXTICON_WIN_HEIGHT)));
					g_pTextIconWindow->popup(this);
				}
			}
			break;
			case TQt::Key_C:
				copyToClipboard();
			break;
			case TQt::Key_X:
				if(!m_bReadOnly) cut();
			break;
			case TQt::Key_V:
				if(!m_bReadOnly) pasteClipboardWithConfirmation();
			break;
			//case TQt::Key_Backspace:
			case TQt::Key_W:
				if(m_iCursorPosition > 0 && !m_bReadOnly && !hasSelection())
				{
					// skip whitespace
					while(m_iCursorPosition > 0)
					{
						if(!m_szTextBuffer.at(m_iCursorPosition - 1).isSpace())break;
						m_szTextBuffer.remove(m_iCursorPosition-1,1);
						m_iCursorPosition--;
						if(m_iFirstVisibleChar > m_iCursorPosition)m_iFirstVisibleChar--;
					}
					// skip nonwhitespace
					while(m_iCursorPosition > 0)
					{
						if(m_szTextBuffer.at(m_iCursorPosition - 1).isSpace())break;
						m_szTextBuffer.remove(m_iCursorPosition-1,1);
						m_iCursorPosition--;
						if(m_iFirstVisibleChar > m_iCursorPosition)m_iFirstVisibleChar--;
					}
					repaintWithCursorOn();
				}
			break;
			case TQt::Key_PageUp:
				if(KVI_OPTION_BOOL(KviOption_boolDisableInputHistory)) break;
				if(m_pInputParent->inherits("KviInput"))
					((KviInput*)(m_pInputParent))->historyButtonClicked();
			break;
			case TQt::Key_F:
				if(m_pKviWindow)
					if(m_pKviWindow->view())m_pKviWindow->view()->toggleToolWidget();
			break;
			case TQt::Key_A:
				m_iSelectionBegin=0;
				m_iSelectionEnd=m_szTextBuffer.length()-1;
				m_iCursorPosition=m_szTextBuffer.length();
				repaintWithCursorOn();
			break;
			case TQt::Key_Return:
			case TQt::Key_Enter:
				if(m_pInputParent->inherits("KviInput"))
				{
					TQString szBuffer(m_szTextBuffer);
					m_szTextBuffer="";
					selectOneChar(-1);
					m_iCursorPosition = 0;
					m_iFirstVisibleChar = 0;
					repaintWithCursorOn();
					KviUserInput::parseNonCommand(szBuffer,m_pKviWindow);
					if (!szBuffer.isEmpty())
					{
						g_pInputHistory->add(new TQString(szBuffer));
						m_pHistory->insert(0,new TQString(szBuffer));
					}
				
					__range_valid(KVI_INPUT_MAX_LOCAL_HISTORY_ENTRIES > 1); //ABSOLUTELY NEEDED, if not, pHist will be destroyed...
					if(m_pHistory->count() > KVI_INPUT_MAX_LOCAL_HISTORY_ENTRIES)m_pHistory->removeLast();
				
					m_iCurHistoryIdx = -1;
				}
				break;	
			default:
				if(!m_bReadOnly) insertText(e->text());
			break;
		}
		return;
	}

	if((e->state() & TQt::AltButton) && (e->state() & TQt::Keypad))
	{
		// TQt::Key_Meta seems to substitute TQt::Key_Alt on some keyboards
		if((e->key() == TQt::Key_Alt) || (e->key() == TQt::Key_Meta))
		{
			m_szAltKeyCode = "";
			return;
		} else if((e->ascii() >= '0') && (e->ascii() <= '9'))
		{
			m_szAltKeyCode += e->ascii();
			return;
		}

		//debug("%c",e->ascii());
		if(!m_bReadOnly) {
			insertText(e->text());
		}
		return;
	}

	if(e->state() & TQt::ShiftButton)
	{
		switch(e->key())
		{
			case TQt::Key_Insert:
				if(!m_bReadOnly) pasteClipboardWithConfirmation();
				return;
			break;
			case TQt::Key_PageUp:
				if(m_pKviWindow)
					if(m_pKviWindow->view())m_pKviWindow->view()->prevLine();
				return;
			break;
			case TQt::Key_PageDown:
				if(m_pKviWindow)
					if(m_pKviWindow->view())m_pKviWindow->view()->nextLine();
				return;
			break;
		}
	}

	switch(e->key())
	{
		case TQt::Key_Right:
			if(m_iCursorPosition < ((int)(m_szTextBuffer.length())))
			{
				internalCursorRight(e->state() & TQt::ShiftButton);
				repaintWithCursorOn();
			}
			break;
		case TQt::Key_Left:
			if(m_iCursorPosition > 0)
			{
				internalCursorLeft(e->state() & TQt::ShiftButton);
				repaintWithCursorOn();
			}
			break;
		case TQt::Key_Backspace:
			if(!m_bReadOnly)
			{
				if(hasSelection() && (m_iSelectionEnd >= m_iCursorPosition-1) && (m_iSelectionBegin <= m_iCursorPosition))
				{
					//remove the selection
					m_szTextBuffer.remove(m_iSelectionBegin,(m_iSelectionEnd-m_iSelectionBegin)+1);
					m_iCursorPosition = m_iSelectionBegin;
					if(m_iFirstVisibleChar > m_iCursorPosition)m_iFirstVisibleChar = m_iCursorPosition;
				} else if(m_iCursorPosition > 0) {
					m_iCursorPosition--;
					m_szTextBuffer.remove(m_iCursorPosition,1);
					if(m_iFirstVisibleChar > m_iCursorPosition)m_iFirstVisibleChar--;
				}
				selectOneChar(-1);
				repaintWithCursorOn();
			}
			break;
		case TQt::Key_Delete:
			if(!m_bReadOnly)
			{
				if(hasSelection()) removeSelected();
				else if(m_iCursorPosition < (int)m_szTextBuffer.length())
				{
					m_szTextBuffer.remove(m_iCursorPosition,1);
					selectOneChar(-1);
					repaintWithCursorOn();
				}
			}
			break;
		case TQt::Key_Home:
			if(m_iCursorPosition > 0)
			{
				if(e->state() & TQt::ShiftButton)
				{
					if((m_iSelectionBegin == -1)&&(m_iSelectionEnd == -1))m_iSelectionEnd = m_iCursorPosition - 1;
					m_iSelectionBegin = 0;
				} else {
					selectOneChar(-1);
				}
				home();
			}
			break;
		case TQt::Key_End://we should call it even the cursor is at the end for deselecting
			if(e->state() & TQt::ShiftButton)
			{
				if((m_iSelectionBegin == -1)&&(m_iSelectionEnd == -1))m_iSelectionBegin = m_iCursorPosition;
				m_iSelectionEnd = m_szTextBuffer.length()-1;
			} else {
				selectOneChar(-1);
			}
			end();
			break;
		case TQt::Key_Up:
			if(!m_bReadOnly)
			{
				if(m_pHistory->count() > 0)
				{
					if(m_iCurHistoryIdx < 0)
					{
						m_szSaveTextBuffer = m_szTextBuffer;
						m_szTextBuffer = *(m_pHistory->at(0));
						m_iCurHistoryIdx = 0;
					} else if(m_iCurHistoryIdx >= (int)(m_pHistory->count()-1))
					{
						m_szTextBuffer=m_szSaveTextBuffer;
						m_iCurHistoryIdx = -1;
					} else {
						m_iCurHistoryIdx++;
						m_szTextBuffer = *(m_pHistory->at(m_iCurHistoryIdx));
					}
					selectOneChar(-1);
					if(KVI_OPTION_BOOL(KviOption_boolInputHistoryCursorAtEnd))end();
					else home();
				}
			}
			break;
		case TQt::Key_Down:
			if(!m_bReadOnly)
			{
				if(m_pHistory->count() > 0)
				{
					if(m_iCurHistoryIdx < 0)
					{
						m_szSaveTextBuffer = m_szTextBuffer;
						m_szTextBuffer = *(m_pHistory->at(m_pHistory->count()-1));
						m_iCurHistoryIdx =m_pHistory->count()-1;
					} else if(m_iCurHistoryIdx == 0)
					{
						m_szTextBuffer=m_szSaveTextBuffer;
						m_iCurHistoryIdx = -1;
					} else {
						m_iCurHistoryIdx--;
						m_szTextBuffer = *(m_pHistory->at(m_iCurHistoryIdx));
					}
					selectOneChar(-1);
					if(KVI_OPTION_BOOL(KviOption_boolInputHistoryCursorAtEnd))end();
					else home();
				}
			}
			break;
		case TQt::Key_PageUp:
			if(m_pKviWindow)
				if(m_pKviWindow->view())m_pKviWindow->view()->prevPage();
		break;
		case TQt::Key_PageDown:
			if(m_pKviWindow)
				if(m_pKviWindow->view())m_pKviWindow->view()->nextPage();
		break;
		case TQt::Key_Return:
		case TQt::Key_Enter:
			returnPressed();
			break;
		case TQt::Key_Alt:
		case TQt::Key_Meta:
			m_szAltKeyCode = "";
			break;
		default:
			if(!e->text().isEmpty() && !m_bReadOnly)
				insertText(e->text());
		break;
	}
}

void KviInputEditor::keyReleaseEvent(TQKeyEvent *e)
{
	if((e->key() == TQt::Key_Alt) || (e->key() == TQt::Key_Meta))
	{
		if(m_szAltKeyCode.hasData())
		{
			bool bOk;
			unsigned short ch = m_szAltKeyCode.toUShort(&bOk);
			if(bOk && ch != 0)
			{
				//debug("INSERTING CHAR %d",ch);
				insertChar(TQChar(ch));
				e->accept();
			}
		}
		m_szAltKeyCode = "";
	}
	e->ignore();
}

void KviInputEditor::getWordBeforeCursor(TQString &buffer,bool * bIsFirstWordInLine)
{
	if(m_szTextBuffer.isEmpty() || m_iCursorPosition <= 0)
	{
		buffer = "";
		return;
	}

	buffer = m_szTextBuffer.left(m_iCursorPosition);

	int idx = buffer.findRev(' ');
	int idx2 = buffer.findRev(','); // This is for comma separated lists...
	int idx3 = buffer.findRev('(');
	int idx4 = buffer.findRev('"');
	if(idx2 > idx)idx = idx2;
	if(idx3 > idx)idx = idx3;
	if(idx4 > idx)idx = idx4;
	*bIsFirstWordInLine = false;
	if(idx > -1)buffer.remove(0,idx+1);
	else *bIsFirstWordInLine = true;
}

void KviInputEditor::completion(bool bShift)
{
	// FIXME: Spaces in directory completion can mess everything completely
	//        On windows the KVI_PATH_SEPARATOR_CHARacters are breaking everything...
	//        Well.... :D

	TQString word;
	TQString match;

	bool bFirstWordInLine;
	getWordBeforeCursor(word,&bFirstWordInLine);
	if(word.isEmpty())
	{
		if(m_szLastCompletedNick.isEmpty())return; // nothing to complete
		else {
			// this is standard nick completion continued
			standardNickCompletion(bShift,word,bFirstWordInLine);
			repaintWithCursorOn();
			return;
		}
	}
	KviPointerList<TQString> tmp;
	tmp.setAutoDelete(true);

	bool bIsCommand = false;
	bool bIsDir = false;
	bool bIsNick = false;

	unsigned short uc = word[0].unicode();

	if(uc == '/')
	{
		if(bFirstWordInLine)
		{
			// command completion
			word.remove(0,1);
			if(word.isEmpty())return;
			KviKvsKernel::instance()->completeCommand(word,&tmp);
			bIsCommand = true;
		} else {
			// directory completion attempt
			g_pApp->completeDirectory(word,&tmp);
			bIsDir = true;
		}
	} else if(uc == '$')
	{
		// function/identifer completion
		word.remove(0,1);
		if(word.isEmpty())return;
		KviKvsKernel::instance()->completeFunction(word,&tmp);
	} else if(uc == '#' || uc == '&' || uc == '!')
	{
		if(m_pKviWindow)
		{
			if( (word.length()==1) && (m_pKviWindow->windowName()[0].unicode()==uc))
			{
				match=m_pKviWindow->windowName();
				match.append(" ");
				replaceWordBeforeCursor(word,match,false);
				repaintWithCursorOn();
				return;
			} else {
				if(m_pKviWindow->console())
					m_pKviWindow->console()->completeChannel(word,&tmp);
			}
		}

	//FIXME: Complete also on irc:// starting strings, not only irc.?
	} else if(KviTQString::equalCIN(word,"irc.",4))
	{
		// irc server name
		if(m_pKviWindow)
			if(m_pKviWindow->console())
				m_pKviWindow->console()->completeServer(word,&tmp);
	} else {
		// empty word will end up here
		if(m_pUserListView)
		{
			if(KVI_OPTION_BOOL(KviOption_boolBashLikeNickCompletion))
			{
				m_pUserListView->completeNickBashLike(word,&tmp,bShift);
				bIsNick = true;
			} else {
				standardNickCompletion(bShift,word,bFirstWordInLine);
				repaintWithCursorOn();
				return;
			}
		}
	}

	// Lookup the longest exact match

	if(tmp.count() > 0)
	{
		if(tmp.count() == 1)
		{
			match = *(tmp.first());
			if(bIsCommand)match.append(' ');
			else if(bIsNick)
			{
				if(!KVI_OPTION_STRING(KviOption_stringNickCompletionPostfix).isEmpty())
				{
					if(bFirstWordInLine || (!KVI_OPTION_BOOL(KviOption_boolUseNickCompletionPostfixForFirstWordOnly)))
						match.append(KVI_OPTION_STRING(KviOption_stringNickCompletionPostfix));
				}
			}
		} else {
			TQString all;
			TQString * s = tmp.first();
			match = *s;
			int wLen = word.length();
			for(;s;s = tmp.next())
			{
				if(s->length() < match.length())
					match.remove(s->length(),match.length() - s->length());
				// All the matches here have length >= word.len()!!!
				const TQChar * b1 = KviTQString::nullTerminatedArray(*s) + wLen;
				const TQChar * b2 = KviTQString::nullTerminatedArray(match) + wLen;
				const TQChar * c1 = b1;
				const TQChar * c2 = b2;
				if(bIsDir)while(c1->unicode() && (c1->unicode() == c2->unicode()))c1++,c2++;
				else while(c1->unicode() && (c1->lower().unicode() == c2->lower().unicode()))c1++,c2++;
				int len = wLen + (c1 - b1);
				if(len < ((int)(match.length())))match.remove(len,match.length() - len);
				if(!all.isEmpty())all.append(", ");
				all.append(*s);
			}
			if(m_pKviWindow)
				m_pKviWindow->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("%d matches: %Q"),tmp.count(),&all);
		}
	} else 
		if(m_pKviWindow)
			m_pKviWindow->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,__tr2qs("No matches"));

	if(!match.isEmpty())
	{
		//if(!bIsDir && !bIsNick)match = match.lower(); <-- why? It is nice to have
		//						 $module.someFunctionName instad 
		//						 of unreadable $module.somefunctionfame
		replaceWordBeforeCursor(word,match,false);
	}

	repaintWithCursorOn();
}

void KviInputEditor::replaceWordBeforeCursor(const TQString &word,const TQString &replacement,bool bRepaint)
{
	selectOneChar(-1);
	m_iCursorPosition -= word.length();
	m_szTextBuffer.remove(m_iCursorPosition,word.length());
	m_szTextBuffer.insert(m_iCursorPosition,replacement);
	m_szTextBuffer.truncate(m_iMaxBufferSize);
	moveCursorTo(m_iCursorPosition + replacement.length());
	if(bRepaint)repaintWithCursorOn();
}

void KviInputEditor::standardNickCompletion(bool bAddMask,TQString &word,bool bFirstWordInLine)
{
	// FIXME: this could be really simplified...
	if(!m_pUserListView)return;
	selectOneChar(-1);

	TQString buffer;
	if(m_szLastCompletedNick.isEmpty())
	{
		// New completion session: we NEED sth to complete
		if(word.isEmpty())return;
		if(m_pUserListView->completeNickStandard(word,m_szLastCompletedNick,buffer,bAddMask))
		{
			// completed: save the buffer
			m_szLastCompletionBuffer          = m_szTextBuffer;
			m_iLastCompletionCursorPosition   = m_iCursorPosition;
			m_iLastCompletionCursorXPosition  = m_iLastCursorXPosition;
			m_iLastCompletionFirstVisibleChar = m_iFirstVisibleChar;
			m_szLastCompletedNick             = buffer;
			if(!KVI_OPTION_STRING(KviOption_stringNickCompletionPostfix).isEmpty())
			{
				if(bFirstWordInLine || (!KVI_OPTION_BOOL(KviOption_boolUseNickCompletionPostfixForFirstWordOnly)))
					buffer.append(KVI_OPTION_STRING(KviOption_stringNickCompletionPostfix));
			}
			replaceWordBeforeCursor(word,buffer,false);
			m_bLastCompletionFinished=0;
			// REPAINT CALLED FROM OUTSIDE!
		} // else no match at all
	} else  if(!m_bLastCompletionFinished) {
		// Old session
		// swap the buffers
		m_szTextBuffer                        = m_szLastCompletionBuffer;
		m_iCursorPosition                     = m_iLastCompletionCursorPosition;
		m_iLastCursorXPosition                = m_iLastCompletionCursorXPosition;
		m_iFirstVisibleChar                   = m_iLastCompletionFirstVisibleChar;
		// re-extract
		//word = m_szTextBuffer.left(m_iCursorPosition);

		getWordBeforeCursor(word,&bFirstWordInLine);
		if(word.isEmpty())return;
		if(m_pUserListView->completeNickStandard(word,m_szLastCompletedNick,buffer,bAddMask))
		{
			// completed
			m_szLastCompletedNick             = buffer;
			if(!KVI_OPTION_STRING(KviOption_stringNickCompletionPostfix).isEmpty())
			{
				if(bFirstWordInLine || (!KVI_OPTION_BOOL(KviOption_boolUseNickCompletionPostfixForFirstWordOnly)))
					buffer.append(KVI_OPTION_STRING(KviOption_stringNickCompletionPostfix));
			}
			replaceWordBeforeCursor(word,buffer,false);
			m_bLastCompletionFinished=0;
			// REPAINT CALLED FROM OUTSIDE!
		} else {
			m_bLastCompletionFinished=1;
			m_szLastCompletedNick = "";
		}
	} else {
		// Old session finished
		// re-extract
		//word = m_szTextBuffer.left(m_iCursorPosition);
		//getWordBeforeCursor(word,&bFirstWordInLine);
		if(word.isEmpty())return;
		if(m_pUserListView->completeNickStandard(word,"",buffer,bAddMask))
		{
			// completed
			m_szLastCompletionBuffer          = m_szTextBuffer;
			m_iLastCompletionCursorPosition   = m_iCursorPosition;
			m_iLastCompletionCursorXPosition  = m_iLastCursorXPosition;
			m_iLastCompletionFirstVisibleChar = m_iFirstVisibleChar;
			m_szLastCompletedNick             = buffer;
			if(!KVI_OPTION_STRING(KviOption_stringNickCompletionPostfix).isEmpty())
			{
				if(bFirstWordInLine || (!KVI_OPTION_BOOL(KviOption_boolUseNickCompletionPostfixForFirstWordOnly)))
					buffer.append(KVI_OPTION_STRING(KviOption_stringNickCompletionPostfix));
			}
			replaceWordBeforeCursor(word,buffer,false);
			m_bLastCompletionFinished=0;
			// REPAINT CALLED FROM OUTSIDE!
		} else {
			m_bLastCompletionFinished=1;
			m_szLastCompletedNick = "";
		}
	}
}


//Funky helpers

void KviInputEditor::end()
{
	m_iLastCursorXPosition = frameWidth();
	m_iCursorPosition = 0;
	m_iFirstVisibleChar = 0;
	while(m_iCursorPosition < ((int)(m_szTextBuffer.length())))
	{
		moveRightFirstVisibleCharToShowCursor();
		m_iCursorPosition++;
	}
	repaintWithCursorOn();
}

void KviInputEditor::home()
{
	m_iFirstVisibleChar = 0;
	m_iCursorPosition   = 0;
	repaintWithCursorOn();
}

void KviInputEditor::insertChar(TQChar c)
{
	if(m_szTextBuffer.length() >= m_iMaxBufferSize)return;

	// Kill the selection
	if((m_iSelectionBegin > -1) || (m_iSelectionEnd > -1))
	{
		if((m_iCursorPosition >= m_iSelectionBegin) && (m_iCursorPosition <= m_iSelectionEnd))
		{
			m_bUpdatesEnabled = false;
			removeSelected();
			m_bUpdatesEnabled = true;
		}
	}
	selectOneChar(-1);
	m_szTextBuffer.insert(m_iCursorPosition,c);
	moveRightFirstVisibleCharToShowCursor();
	m_iCursorPosition++;
	repaintWithCursorOn();
}

void KviInputEditor::moveRightFirstVisibleCharToShowCursor()
{
	// :)
	TQFontMetrics fm(KVI_OPTION_FONT(KviOption_fontInput));

	TQChar c = m_szTextBuffer.at(m_iCursorPosition);

#ifdef COMPILE_USE_QT4
	m_iLastCursorXPosition += c.unicode() < 32 ? fm.width(getSubstituteChar(c.unicode())) + 3 : fm.width(c);;
#else
	m_iLastCursorXPosition += (c.unicode() < 256) ? g_iInputFontCharWidth[c.unicode()] : fm.width(c);
#endif
	while(m_iLastCursorXPosition >= contentsRect().width()-2*KVI_INPUT_MARGIN)
	{
		c = m_szTextBuffer.at(m_iFirstVisibleChar);
#ifdef COMPILE_USE_QT4
		m_iLastCursorXPosition -= c.unicode() < 32 ? fm.width(getSubstituteChar(c.unicode())) + 3 : fm.width(c);;
#else
		m_iLastCursorXPosition -= (c.unicode() < 256) ? g_iInputFontCharWidth[c.unicode()] : fm.width(c);
#endif
		m_iFirstVisibleChar++;
	}
}

void KviInputEditor::repaintWithCursorOn()
{
	// :)
	if(m_bUpdatesEnabled)
	{
		m_bCursorOn = true;
		update();
	}
}

void KviInputEditor::selectOneChar(int pos)
{
	m_iSelectionBegin = pos;
	m_iSelectionEnd   = pos;
}

int KviInputEditor::charIndexFromXPosition(int xPos)
{
	int curXPos = frameWidth()+KVI_INPUT_MARGIN;
	int curChar = m_iFirstVisibleChar;
	int bufLen  = m_szTextBuffer.length();

	TQFontMetrics fm(KVI_OPTION_FONT(KviOption_fontInput));
	while(curChar < bufLen)
	{
		TQChar c = m_szTextBuffer.at(curChar);
#ifdef COMPILE_USE_QT4
		int widthCh = c.unicode() < 32 ? fm.width(getSubstituteChar(c.unicode())) + 3 : fm.width(c);;
#else
		int widthCh = (c.unicode() < 256) ? g_iInputFontCharWidth[c.unicode()] : fm.width(c);
#endif
		if(xPos < (curXPos+(widthCh/2)))return curChar;
		else if(xPos < (curXPos+widthCh))return (curChar+1);
		{
			curXPos+=widthCh;
			curChar++;
		}
	}
	return curChar;
}

int  KviInputEditor::xPositionFromCharIndex(TQFontMetrics& fm,int chIdx,bool bContentsCoords)
{
	// FIXME: this could use fm.width(m_szTextBuffer,chIdx)
	int curXPos = bContentsCoords ? KVI_INPUT_MARGIN : frameWidth()+KVI_INPUT_MARGIN;
	int curChar = m_iFirstVisibleChar;
	while(curChar < chIdx)
	{
		TQChar c = m_szTextBuffer.at(curChar);
#ifdef COMPILE_USE_QT4
		curXPos += c.unicode() < 32 ? fm.width(getSubstituteChar(c.unicode())) + 3 : fm.width(c);;
#else
		curXPos += (c.unicode() < 256) ? g_iInputFontCharWidth[c.unicode()] : fm.width(c);
#endif
		curChar++;
	}
	return curXPos;
}

int KviInputEditor::xPositionFromCharIndex(int chIdx,bool bContentsCoords)
{
	// FIXME: this could use fm.width(m_szTextBuffer,chIdx)
	int curXPos = bContentsCoords ? KVI_INPUT_MARGIN : frameWidth()+KVI_INPUT_MARGIN;
	int curChar = m_iFirstVisibleChar;
	//debug("%i",g_pLastFontMetrics);
	if(!g_pLastFontMetrics) g_pLastFontMetrics = new TQFontMetrics(KVI_OPTION_FONT(KviOption_fontInput));
	while(curChar < chIdx)
	{
		TQChar c = m_szTextBuffer.at(curChar);
#ifdef COMPILE_USE_QT4
		curXPos += c.unicode() < 32 ? g_pLastFontMetrics->width(getSubstituteChar(c.unicode())) + 3 : g_pLastFontMetrics->width(c);
#else
		curXPos += (c.unicode() < 256) ? g_iInputFontCharWidth[c.unicode()] : g_pLastFontMetrics->width(c);
#endif
		curChar++;
	}
	return curXPos;
}

/*
	@doc: texticons
	@type:
		generic
	@title:
		The KVIrc TextIcons extension
	@short:
		The KVIrc TextIcons extension
	@body:
		Starting from version 3.0.0 KVIrc supports the TextIcon extension
		to the standard IRC protocol. It is a mean for sending text enriched
		of small images without sending the images themselves.[br]
		The idea is quite simple: the IRC client (and it's user) associates
		some small images to text strings (called icon tokens) and the strings are sent
		in place of the images preceeded by a special escape character.[br]
		The choosen escape character is 29 (hex 0x1d) which corresponds
		to the ASCII group separator.[br]
		So for example if a client has the association of the icon token "rose" with a small
		icon containing a red rose flower then KVIrc could send the string
		"&lt;0x1d&gt;rose" in the message stream to ask the remote parties to
		display such an icon. If the remote parties don't have this association
		then they will simply strip the control code and display the string "rose",
		(eventually showing it in some enchanced way).[br]
		The icon tokens can't contain spaces
		so the receiving clients stop the extraction of the icon strings
		when a space, an icon escape or the message termination is encountered.
		[br]
		&lt;icon escape&gt; := character 0x1d (ASCII group separator)[br]
		&lt;icon token&gt; := any character with the exception of 0x1d, CR,LF and SPACE.[br]
		[br]
		Please note that this is a KVIrc extension and the remote clients
		that don't support this feature will not display the icon (and will
		eventually show the 0x1d character in the data stream).[br]
		If you like this feature please either convince the remote users
		to try KVIrc or tell them to write to their client developers asking
		for this simple feature to be implemented.[br]
*/


/*
	@doc: commandline
	@title:
		The Commandline Input Features
	@type:
		generic
	@short:
		Commandline input features
	@body:
		[big]Principles of operation[/big]
		[p]
		The idea is simple: anything that starts with a slash (/) character
		is interpreted as a command. Anything else is plain text that is
		sent to the target of the window (channel, query, dcc chat etc..).
		[/p]
		[big]The two operating modes[/big]
		[p]
		The commandline input has two operating modes: the "user friendly mode" and
		the "kvs mode". In the user friendly mode all the parameters of the commands
		are interpreted exactly like you type them. There is no special interpretation
		of $,%,-,( and ; characters. This allows you to type "/me is happy ;)", for example.
		In the kvs mode the full parameter interpretation is enabled and the commands
		work just like in any other script editor. This means that anything that
		starts with a $ is a function call, anything that starts with a % is a variable,
		the dash characters after command names are interpreted as switches and ; is the
		command separator. This in turn does NOT allow you to type "/me is happy ;)"
		because ; is the command separator and ) will be interpreted as the beginning
		of the next command. In KVS mode you obviously have to escape the ; character
		by typing "/me is happy \;)". The user friendly mode is good for everyday chatting
		and for novice users while the KVS mode is for experts that know that minimum about
		scripting languages. Please note that in the user-friendly mode you're not allowed
		to type multiple commands at once :).
		[/p]
		[big]Default Key Bindings:[/big][br]
		Ctrl+B: Inserts the 'bold' mIRC text control character<br>
		Ctrl+K: Inserts the 'color' mIRC text control character<br>
		Ctrl+R: Inserts the 'reverse' mIRC text control character<br>
		Ctrl+U: Inserts the 'underline' mIRC text control character<br>
		Ctrl+O: Inserts the 'reset' mIRC text control character<br>
		Ctrl+P: Inserts the 'non-crypt' (plain text) KVIrc control character used to disable encryption of the current text line<br>
		Ctrl+C: Copies the selected text to clipboard<br>
		Ctrl+X: Cuts the selected text<br>
		Ctrl+V: Pastes the clipboard contents (same as middle mouse click)<br>
		Ctrl+I: Inserts the 'icon' control code and pops up the icon list box<br>
		Ctrl+A: Select all<br>
		CursorUp: Moves backward in the command history<br>
		CursorDown: Moves forward in the command history<br>
		CursorRight: Moves the cursor to the right<br>
		CursorLeft: Moves the cursor to the left :)<br>
		Shift+CursorLeft: Moves the selection to the left<br>
		Shift+RightCursor: Moves the selection to the right<br>
		Ctrl+CursorLeft: Moves the cursor one word left<br>
		Ctrl+CursorRight: Moves the cursor one word right<br>
		Ctrl+Shift+CursorLeft: Moves the selection one word left<br>
		Ctrl+Shift+CursorRight: Moves the selection one word right<br>
		Tab: Nickname, function/command, or filename completion (see below)<br>
		Shift+Tab: Hostmask or function/command completion (see below)<br>
		Alt+&lt;numeric_sequence&gt;: Inserts the character by ASCII/Unicode code<br>
		<example>
		Alt+32: Inserts ASCII/Unicode character 32: ' ' (a space)
		Alt+00032: Same as above :)
		Alt+13: Inserts the Carriage Return (CR) control character
		Alt+77: Inserts ASCII/Unicode character 77: 'M'
		Alt+23566: Inserts Unicode character 23566 (an ideogram)
		</example>
		Also look at the <a href="shortcuts.kvihelp">global shortcuts</a> reference.<br>
		If you drop a file on this widget, a <a href="parse.kvihelp">/PARSE &lt;filename&gt;</a> will be executed.<br>
		You can enable word substitution in the preferences dialog.<br>
		For example, if you choose to substitute "afaik" with "As far as I know",<br>
		when you will type "afaik" somewhere in the command line, and then
		press Space or Return, that word will be replaced with "As far as I know".<br>
		Experiment with it :)<br>
		The Tab key activates the completion of the current word.<br>
		If a word is prefixed with a '/', it is treated as a command to be completed,
		if it begins with '$', it is treated as a function or identifier to be completed,
		otherwise it is treated as a nickname or filename to be completed.<br>
		<example>
			/ec&lt;Tab&gt; will produce /echo&lt;space&gt
			/echo $loca&lt;Tab&gt; will produce /echo $localhost
		</example>
		Multiple matches are listed in the view window and the word is completed
		to the common part of all the matches.<br>
		<example>
			$sel&lt;Tab;&gt; will find multiple matches and produce $selected
		</example>
		Experiment with that too :)
*/



KviInput::KviInput(KviWindow *par,KviUserListView * view)
: TQWidget(par,"input")
{
	TQBoxLayout* pLayout=new TQHBoxLayout(this);
	pLayout->setAutoAdd(true);
	pLayout->setDirection(TQBoxLayout::RightToLeft);

	pLayout->setMargin(0);
	pLayout->setSpacing(0);

	m_pWindow = par;
	m_pMultiLineEditor = 0;
	
	m_pHideToolsButton = new KviStyledToolButton(this,"hide_container_button");
	
	m_pHideToolsButton->setUsesBigPixmap(false);
	m_pHideToolsButton->setFixedWidth(10);

	if(g_pIconManager->getBigIcon("kvi_horizontal_left.png"))
		m_pHideToolsButton->setPixmap(*(g_pIconManager->getBigIcon("kvi_horizontal_left.png")));
	
	connect(m_pHideToolsButton,TQT_SIGNAL(clicked()),this,TQT_SLOT(toggleToolButtons()));
	
	m_pButtonContainer=new KviTalHBox(this);
	m_pButtonContainer->setSpacing(0);

#ifdef COMPILE_USE_QT4
	m_pButtonContainer->setSizePolicy(TQSizePolicy(TQSizePolicy::Minimum,TQSizePolicy::Preferred));
//	if(m_pButtonContainer->layout())
//		m_pButtonContainer->layout()->setSizeConstraint(TQLayout::SetMinimumSize);
#endif

	m_pHistoryButton = new KviStyledToolButton(m_pButtonContainer,"historybutton");
	m_pHistoryButton->setUsesBigPixmap(false);
	//m_pHistoryButton->setUpdatesEnabled(TRUE); ???
	TQIconSet is1;
	if(!KVI_OPTION_BOOL(KviOption_boolDisableInputHistory))//G&N mar 2005
	{
		is1.setPixmap(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_TIME)),TQIconSet::Small);
		m_pHistoryButton->setIconSet(is1);
		KviTalToolTip::add(m_pHistoryButton,__tr2qs("Show History<br>&lt;Ctrl+PageUp&gt;"));
		connect(m_pHistoryButton,TQT_SIGNAL(clicked()),this,TQT_SLOT(historyButtonClicked()));
	}
	else
	{
		is1.setPixmap(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_QUITSPLIT)),TQIconSet::Small);
		m_pHistoryButton->setIconSet(is1);
		KviTalToolTip::add(m_pHistoryButton,__tr2qs("Input History Disabled"));
	}

	m_pIconButton = new KviStyledToolButton(m_pButtonContainer,"iconbutton");
	m_pIconButton->setUsesBigPixmap(false);
	TQIconSet is3;
	is3.setPixmap(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_BIGGRIN)),TQIconSet::Small);
	m_pIconButton->setIconSet(is3);
	KviTalToolTip::add(m_pIconButton,__tr2qs("Show Icons Popup<br>&lt;Ctrl+I&gt;<br>See also /help texticons"));

	connect(m_pIconButton,TQT_SIGNAL(clicked()),this,TQT_SLOT(iconButtonClicked()));


	m_pCommandlineModeButton = new KviStyledToolButton(m_pButtonContainer,"commandlinemodebutton");
	m_pCommandlineModeButton->setUsesBigPixmap(false);
	m_pCommandlineModeButton->setToggleButton(true);
	TQIconSet is0;
	is0.setPixmap(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SAYSMILE)),TQIconSet::Small,TQIconSet::Normal,TQIconSet::On);
	is0.setPixmap(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SAYKVS)),TQIconSet::Small,TQIconSet::Normal,TQIconSet::Off);
	m_pCommandlineModeButton->setIconSet(is0);
	KviTalToolTip::add(m_pCommandlineModeButton,__tr2qs("User friendly commandline mode<br>See also /help commandline"));
	if(KVI_OPTION_BOOL(KviOption_boolCommandlineInUserFriendlyModeByDefault))
		m_pCommandlineModeButton->setOn(true);


	m_pMultiEditorButton = new KviStyledToolButton(m_pButtonContainer,"multieditorbutton");
	m_pMultiEditorButton->setToggleButton(true);
	m_pMultiEditorButton->setUsesBigPixmap(false);
	TQIconSet is2;
	is2.setPixmap(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_TERMINAL)),TQIconSet::Small,TQIconSet::Normal,TQIconSet::On);
	is2.setPixmap(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_TERMINAL)),TQIconSet::Small,TQIconSet::Normal,TQIconSet::Off);
	m_pMultiEditorButton->setIconSet(is2);
	TQString szTip = __tr2qs("Multi-line Editor<br>&lt;Alt+Backspace&gt;");
	szTip += " - &lt;Ctrl+Backspace&gt;";
	KviTalToolTip::add(m_pMultiEditorButton,szTip);

	connect(m_pMultiEditorButton,TQT_SIGNAL(toggled(bool)),this,TQT_SLOT(multilineEditorButtonToggled(bool)));
	
	m_pInputEditor = new KviInputEditor(this,par,view);
	connect(m_pInputEditor,TQT_SIGNAL(enterPressed()),this,TQT_SLOT(inputEditorEnterPressed()));
#ifdef COMPILE_USE_QT4
	m_pInputEditor->setSizePolicy(TQSizePolicy(TQSizePolicy::Expanding,TQSizePolicy::Ignored));
#else
	m_pInputEditor->setSizePolicy(TQSizePolicy(TQSizePolicy::Ignored,TQSizePolicy::Ignored));
#endif
	

#ifdef COMPILE_USE_QT4
	m_pMultiEditorButton->setAutoRaise(true);
	m_pCommandlineModeButton->setAutoRaise(true);
	m_pIconButton->setAutoRaise(true);
	m_pHistoryButton->setAutoRaise(true);
	m_pHideToolsButton->setAutoRaise(true);
#endif

	pLayout->setStretchFactor(m_pInputEditor,100000);
	pLayout->setStretchFactor(m_pButtonContainer,0);
	pLayout->setStretchFactor(m_pHideToolsButton,0);
}

KviInput::~KviInput()
{
	if(m_pMultiLineEditor)KviScriptEditor::destroyInstance(m_pMultiLineEditor);
}

bool KviInput::isButtonsHidden()
{
	return m_pButtonContainer->isHidden();
}

void KviInput::setButtonsHidden(bool bHidden)
{
	if(!m_pHideToolsButton || !m_pButtonContainer) return;
	if(bHidden==m_pButtonContainer->isHidden()) return;
	m_pButtonContainer->setHidden(bHidden);
	TQPixmap* pix= bHidden ? 
		g_pIconManager->getBigIcon("kvi_horizontal_right.png") :
		g_pIconManager->getBigIcon("kvi_horizontal_left.png");
	if(pix)
		m_pHideToolsButton->setPixmap(*pix);
}

void KviInput::toggleToolButtons()
{
	setButtonsHidden(!isButtonsHidden());
}

void KviInput::inputEditorEnterPressed()
{
	TQString szText = m_pInputEditor->text();
	KviUserInput::parse(szText,m_pWindow,TQString(),m_pCommandlineModeButton->isOn());
	m_pInputEditor->setText("");
}

void KviInput::keyPressEvent(TQKeyEvent *e)
{
	//debug("KviInput::keyPressEvent(key:%d,state:%d,text:%s)",e->key(),e->state(),e->text().isEmpty() ? "empty" : e->text().utf8().data());

	if((e->state() & TQt::ControlButton) || (e->state() & TQt::AltButton) || (e->state() & TQt::MetaButton))
	{
		switch(e->key())
		{
			case TQt::Key_Backspace:
				//if(m_pMultiLineEditor)
				multilineEditorButtonToggled(!m_pMultiLineEditor);
			break;
		}
	}

	if(e->state() & TQt::ControlButton)
	{
		switch(e->key())
		{
			case TQt::Key_Enter:
			case TQt::Key_Return:
			{
				if(m_pMultiLineEditor)
				{
					TQString szText;
					m_pMultiLineEditor->getText(szText);
					if(szText.isEmpty())return;
					if(KVI_OPTION_BOOL(KviOption_boolWarnAboutPastingMultipleLines))
					{
						if(szText.length() > 256)
						{
							if(szText[0] != '/')
							{
#ifdef COMPILE_USE_QT4
								int nLines = szText.count('\n') + 1;
#else
								int nLines = szText.contains('\n') + 1;
#endif
								if(nLines > 15)
								{
									int nRet = TQMessageBox::question(
										this,
										__tr2qs("Confirm Multiline Message"),
										__tr2qs("You're about to send a message with %1 lines of text.<br><br>" \
												"There is nothing wrong with it, this warning is<br>" \
												"here to prevent you from accidentally sending<br>" \
												"a really large message just because you didn't edit it<br>" \
												"properly after pasting text from the clipboard.<br><br>" \
												"Do you want the message to be sent?").arg(nLines),
										__tr2qs("Yes, always"),
										__tr2qs("Yes"),
										__tr2qs("No"),
										1,2);
									switch(nRet)
									{
										case 0:
											KVI_OPTION_BOOL(KviOption_boolWarnAboutPastingMultipleLines) = false;
										break;
										case 2:
											return;
										break;
										default: // also case 1
										break;
									}
								}
							}
						}
					}
					KviUserInput::parse(szText,m_pWindow,TQString(),m_pCommandlineModeButton->isOn());
					m_pMultiLineEditor->setText("");
				}
			}
			break;
			case TQt::Key_PageUp:
				historyButtonClicked();
			break;
		}
	}
}

void KviInput::multiLinePaste(const TQString &text)
{
	if(!m_pMultiLineEditor)multilineEditorButtonToggled(true);
	m_pMultiLineEditor->setText(text);
}

void KviInput::multilineEditorButtonToggled(bool bOn)
{
	if(m_pMultiLineEditor)
	{
		if(bOn)return;
		KviScriptEditor::destroyInstance(m_pMultiLineEditor);
		m_pMultiLineEditor = 0;
		m_pInputEditor->show();
		m_pWindow->childrenTreeChanged(0);
		m_pInputEditor->setFocus();
		m_pMultiEditorButton->setOn(false);
	} else {
		if(!bOn)return;
		m_pMultiLineEditor = KviScriptEditor::createInstance(this);
		TQString szText = __tr2qs("<Ctrl+Return>; submits, <Alt+Backspace>; hides this editor");
		// compatibility entry to avoid breaking translation just before a release... :)
		szText.replace("Alt+Backspace","Ctrl+Backspace");
		m_pMultiLineEditor->setFindText(szText);
		m_pMultiLineEditor->setFindLineeditReadOnly(true);
		m_pInputEditor->hide();
		m_pMultiLineEditor->show();
		m_pWindow->childrenTreeChanged(m_pMultiLineEditor);
		m_pMultiLineEditor->setFocus();
		m_pMultiEditorButton->setOn(true);
	}
}

void KviInput::iconButtonClicked()
{
	if(!g_pTextIconWindow)g_pTextIconWindow = new KviTextIconWindow();
	TQPoint pnt = m_pIconButton->mapToGlobal(TQPoint(m_pIconButton->width(),0));
	g_pTextIconWindow->move(pnt.x()-g_pTextIconWindow->width(),pnt.y() - g_pTextIconWindow->height());
	g_pTextIconWindow->popup(this,true);
}

void KviInput::historyButtonClicked()
{
	if(!g_pHistoryWindow)g_pHistoryWindow = new KviHistoryWindow();

	TQPoint pnt = mapToGlobal(TQPoint(0,0));

	g_pHistoryWindow->setGeometry(pnt.x(),pnt.y() - KVI_HISTORY_WIN_HEIGHT,width(),KVI_HISTORY_WIN_HEIGHT);
	g_pHistoryWindow->popup(this);
}

#define BUTTON_WIDTH 20

/*void KviInput::resizeEvent(TQResizeEvent *e)
{
	//m_pButtonContainer
	m_pInputEditor->setGeometry(0,0,m_pButtonContainer->isVisible() ? width() - (BUTTON_WIDTH * 4)-10 : width() - 10,height());
	if(m_pMultiLineEditor)m_pMultiLineEditor->setGeometry(0,0,m_pButtonContainer->isVisible() ? width() - (BUTTON_WIDTH * 4)-10 : width() - 10,height());
	if(m_pButtonContainer->isVisible()) m_pButtonContainer->setGeometry(width() - (BUTTON_WIDTH * 4)-10,0,BUTTON_WIDTH*4,height());
		
	m_pHideToolsButton->setGeometry(width() - 10,0,10,height());
	
	TQWidget::resizeEvent(e);
}*/

void KviInput::setFocus()
{
	// redirect setFocus() to the right children
	if(m_pMultiLineEditor)m_pMultiLineEditor->setFocus();
	else m_pInputEditor->setFocus();
}

void KviInput::focusInEvent(TQFocusEvent * e)
{
	// if we get a focus in event , redirect the focus to the children
	if(m_pMultiLineEditor)m_pMultiLineEditor->setFocus();
	else m_pInputEditor->setFocus();
}


int KviInput::heightHint() const
{
	return m_pMultiLineEditor ? 120 : m_pInputEditor->heightHint();
}

void KviInput::setText(const TQString &text)
{
	// FIXME: Latin1 -> TQString ?
	if(m_pMultiLineEditor)m_pMultiLineEditor->setText(text);
	else m_pInputEditor->setText(text);
}

void KviInput::insertChar(char c)
{
	m_pInputEditor->insertChar(c);
}

void KviInput::insertText(const TQString& text)
{
	m_pInputEditor->insertText(text);
}

void KviInput::applyOptions()
{
	if(g_pLastFontMetrics) delete g_pLastFontMetrics;
	g_pLastFontMetrics = 0;

	if(KVI_OPTION_BOOL(KviOption_boolDisableInputHistory))//G&N mar 2005
	{
		TQIconSet is1;
		is1.setPixmap(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_QUITSPLIT)),TQIconSet::Small);
		m_pHistoryButton->setIconSet(is1);
		KviTalToolTip::add(m_pHistoryButton,__tr2qs("Input History Disabled"));
		m_pHistoryButton->disconnect(TQT_SIGNAL(clicked()));
	}

	if(!KVI_OPTION_BOOL(KviOption_boolDisableInputHistory))
	{
		TQIconSet is1;
		is1.setPixmap(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_TIME)),TQIconSet::Small);
		m_pHistoryButton->setIconSet(is1);
		KviTalToolTip::add(m_pHistoryButton,__tr2qs("Show History<br>&lt;Ctrl+PageUp&gt;"));
		connect(m_pHistoryButton,TQT_SIGNAL(clicked()),this,TQT_SLOT(historyButtonClicked()));
	}

	m_pInputEditor->applyOptions();
}

void KviInput::setFocusProxy(TQWidget *)
{
	/* do nothing */
}

//const TQString & KviInput::text()
TQString KviInput::text()
{
	TQString szText;
	if(m_pMultiLineEditor)
		m_pMultiLineEditor->getText(szText);
	else
		szText=m_pInputEditor->text();
	return szText; 
}

#include "kvi_input.moc"