summaryrefslogtreecommitdiffstats
path: root/extensions/nsplugin/src/qnp.cpp
blob: 492da1808c2b534bfbae69361d56becdc869d1f9 (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
/****************************************************************************
**
** Implementation of TQt extension classes for Netscape Plugin support.
**
** Created : 970601
**
** Copyright (C) 1992-2008 Trolltech ASA.  All rights reserved.
**
** This file is part of the TQt GUI Toolkit.
**
** This file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the files LICENSE.GPL2
** and LICENSE.GPL3 included in the packaging of this file.
** Alternatively you may (at your option) use any later version
** of the GNU General Public License if such license has been
** publicly approved by Trolltech ASA (or its successors, if any)
** and the KDE Free TQt Foundation.
**
** Please review the following information to ensure GNU General
** Public Licensing requirements will be met:
** http://trolltech.com/products/qt/licenses/licensing/opensource/.
** If you are unsure which license is appropriate for your use, please
** review the following information:
** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
** or contact the sales department at sales@trolltech.com.
**
** This file may be used under the terms of the Q Public License as
** defined by Trolltech ASA and appearing in the file LICENSE.TQPL
** included in the packaging of this file.  Licensees holding valid TQt
** Commercial licenses may use this file in accordance with the TQt
** Commercial License Agreement provided with the Software.
**
** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted
** herein.
**
**********************************************************************/


// Remaining Q_WS_X11 considerations:
//   - What if !piApp upon NPP_NewStream?  Are we safe?
//      - Yes, but users need to know of this:  that no GUI can be
//         done until after setWindow is called.
//   - Use NPN_GetValue in Communicator4.0 to get the display earlier!
//   - For ClientMessage events, trap them, and if they are not for us,
//	untrap them and retransmit them and set a timer to retrap them
//	after N seconds.

// Remaining Q_WS_WIN considerations:
//   - we need to activateZeroTimers() at some time.
//   - we need to call winEventFilter on events
//   - timers:
//    if ( msg.message == WM_TIMER ) {            // timer message received
//        activateTimer( msg.wParam );
//        return TRUE;
//    }
//    if ( msg.message == WM_KEYDOWN || msg.message == WM_KEYUP ) {
//        if ( translateKeyCode(msg.wParam) == 0 ) {
//            TranslateMessage( &msg );           // translate to WM_CHAR
//            return TRUE;
//        }
//    }
//   - qWinProcessConfigRequests?

// Remaining general stuff:
//   - Provide the "reason" parameter to streamDestroyed

// TQt stuff
#include <ntqapplication.h>
#include <ntqeventloop.h>
#include <ntqwidget.h>
#include <ntqobjectlist.h>
#include <ntqcursor.h>
#include <ntqprinter.h>
#include <ntqfile.h>
#include <ntqpainter.h>

#include "ntqnp.h"

#include <stdlib.h>		// Must be here for Borland C++
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <limits.h>

#ifdef Q_WS_X11
#include <X11/Intrinsic.h>

class TQNPXtPrivate;

class TQNPXt : public TQEventLoop
{
public:
    TQNPXt( const char *applicationClass, XtAppContext context = NULL, XrmOptionDescRec *options = 0, int numOptions = 0);
    ~TQNPXt();

    XtAppContext applicationContext() const;

    void registerSocketNotifier( TQSocketNotifier * );
    void unregisterSocketNotifier( TQSocketNotifier * );

    static void registerWidget( TQWidget* );
    static void unregisterWidget( TQWidget* );
    static bool redeliverEvent( XEvent *event );
    static XEvent* lastEvent();

protected:
    bool processEvents( ProcessEventsFlags flags );

private:
    void appStartingUp();
    void appClosingDown();
    TQNPXtPrivate *d;

};

#define	 GC GC_QQQ
#endif

extern "C" {
//
// Netscape plugin API
//
#ifdef Q_WS_WIN
#ifndef _WINDOWS
#define _WINDOWS
#endif
#endif
#ifdef Q_WS_X11
#define XP_UNIX
#endif


// This is to allow mingw support on windows without altering the sun header files
#if defined(Q_CC_GNU) && defined(Q_WS_WIN) && !defined(_MSC_VER)
#define _MSC_VER 1
#include "npapi.h"
#undef _MSC_VER
#else
#include "npapi.h"
#endif

#ifdef Q_WS_X11
#undef XP_UNIX
#include "npunix.c"
#endif

//
// Stuff for the NPP_SetWindow function:
//
#ifdef Q_WS_X11
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/IntrinsicP.h> // for XtCreateWindow
#include <X11/Shell.h>
#include <X11/StringDefs.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
//#include <dlfcn.h>
#endif
#ifdef Q_WS_WIN
#include <windows.h>
#endif
}

#ifdef Q_WS_WIN
#include "npwin.cpp"
#endif

static TQEventLoop* event_loop = 0;
static TQApplication* application = 0;

struct _NPInstance
{
    uint16            fMode;

#ifdef Q_WS_WIN
    HWND            window;
#endif

    NPP npp;

#ifdef Q_WS_X11
    Window window;
    Display *display;
#endif

    uint32 x, y;
    uint32 width, height;

    TQNPWidget* widget;
    TQNPInstance* instance;

    int16 argc;
    TQString *argn;
    TQString *argv;
};



// The single global plugin
static TQNPlugin *qNP=0;
static int instance_count=0;

// Temporary parameter passed `around the side' of calls to user functions
static _NPInstance* next_pi=0;

// To avoid looping when browser OR plugin can delete streams
static int qnps_no_call_back = 0;

#ifdef Q_WS_WIN
// defined in qapplication_win.cpp
Q_EXPORT extern bool qt_win_use_simple_timers;
Q_EXPORT void qWinProcessConfigRequests();
static HHOOK hhook = 0;

LRESULT CALLBACK FilterProc( int nCode, WPARAM wParam, LPARAM lParam )
{
    if ( tqApp ) {
	tqApp->sendPostedEvents();
	tqApp->eventLoop()->activateSocketNotifiers();
	qWinProcessConfigRequests();
    }

    return CallNextHookEx( hhook, nCode, wParam, lParam );
}

#endif

#ifdef Q_WS_X11
static int (*original_x_errhandler)( Display *dpy, XErrorEvent * ) = 0;
static int dummy_x_errhandler( Display *, XErrorEvent * )
{
    return 0;
}
#endif

/******************************************************************************
 * Plug-in Calls - these are called by Netscape
 *****************************************************************************/


// Instance state information about the plugin.

#ifdef Q_WS_X11

extern "C" char*
NPP_GetMIMEDescription(void)
{
    if (!qNP) qNP = TQNPlugin::create();
    return (char*)qNP->getMIMEDescription();
}



extern "C" NPError
NPP_GetValue(void * /*future*/, NPPVariable variable, void *value)
{
    if (!qNP) qNP = TQNPlugin::create();
    NPError err = NPERR_NO_ERROR;
    if (variable == NPPVpluginNameString)
	*((const char **)value) = qNP->getPluginNameString();
    else if (variable == NPPVpluginDescriptionString)
	*((const char **)value) = qNP->getPluginDescriptionString();
    else
	err = NPERR_GENERIC_ERROR;

    return err;
}

#endif

/*
** NPP_Initialize is called when your DLL is being loaded to do any
** DLL-specific initialization.
*/
extern "C" NPError
NPP_Initialize(void)
{
#ifdef Q_WS_WIN
    qt_win_use_simple_timers = TRUE;
    // Nothing more - we do it in DLLMain
#endif

    if (!qNP) qNP = TQNPlugin::create();
    return NPERR_NO_ERROR;
}

static jref plugin_java_class = 0;

/*
** NPP_GetJavaClass is called during initialization to ask your plugin
** what its associated Java class is. If you don't have one, just return
** NULL. Otherwise, use the javah-generated "use_" function to both
** initialize your class and return it. If you can't find your class, an
** error will be signalled by "use_" and will cause the Navigator to
** complain to the user.
*/
extern "C" jref
NPP_GetJavaClass(void)
{
    if (!qNP) qNP = TQNPlugin::create();
    plugin_java_class = (jref)qNP->getJavaClass();
    return plugin_java_class;
}

/*
** NPP_Shutdown is called when your DLL is being unloaded to do any
** DLL-specific shut-down. You should be a good citizen and declare that
** you're not using your java class any more. This allows java to unload
** it, freeing up memory.
*/
extern "C" void
NPP_Shutdown(void)
{
    if (qNP) {
	if (plugin_java_class)
	    qNP->unuseJavaClass();
	delete qNP;
	qNP = 0;
    }

#ifdef Q_WS_X11
    if ( original_x_errhandler )
    	XSetErrorHandler( original_x_errhandler );
#endif
    if ( tqApp) {
#ifdef Q_WS_WIN32
	if ( hhook )
	    UnhookWindowsHookEx( hhook );
	hhook = 0;
#endif
	delete application;
	delete event_loop;
    }

}


struct NS_Private {
    uchar* a;
    uchar* b;
};

/*
** NPP_New is called when your plugin is instantiated (i.e. when an EMBED
** tag appears on a page).
*/
extern "C" NPError
NPP_New(NPMIMEType /*pluginType*/,
    NPP instance,
    uint16 mode,
    int16 argc,
    char* argn[],
    char* argv[],
    NPSavedData* /*saved*/)
{
    NPError result = NPERR_NO_ERROR;
    _NPInstance* This;

    if (instance == NULL)
	return NPERR_INVALID_INSTANCE_ERROR;

    instance->pdata = new _NPInstance;

    This = (_NPInstance*) instance->pdata;

    if (This == NULL)
	return NPERR_OUT_OF_MEMORY_ERROR;

    This->npp = instance;

    /* mode is NP_EMBED, NP_FULL, or NP_BACKGROUND (see npapi.h) */
    This->fMode = mode;

    This->window = 0;
    This->widget = 0;

    This->argc = argc;
    This->argn = new TQString[argc+1];
    This->argv = new TQString[argc+1];
    for (int i=0; i<This->argc; i++) {
	This->argn[i] = argn[i];
	This->argv[i] = argv[i];
    }

    // Everything is set up - we can let TQNPInstance be created now.
    next_pi = This;
    qNP->newInstance();
    instance_count++;

    return result;
}

extern "C" NPError
NPP_Destroy(NPP instance, NPSavedData** /*save*/)
{
    _NPInstance* This;

    if (instance == NULL)
	return NPERR_INVALID_INSTANCE_ERROR;

    This = (_NPInstance*) instance->pdata;

    if (This != NULL) {
	delete This->widget;
	delete This->instance;
	delete [] This->argn;
	delete [] This->argv;

	delete This;
	instance->pdata = NULL;

	instance_count--;
    }

    return NPERR_NO_ERROR;
}

extern "C" NPError
NPP_SetWindow(NPP instance, NPWindow* window)
{
    if (!qNP) qNP = TQNPlugin::create();
    NPError result = NPERR_NO_ERROR;
    _NPInstance* This;

    if (instance == NULL)
	return NPERR_INVALID_INSTANCE_ERROR;

    This = (_NPInstance*) instance->pdata;


    // take a shortcut if all that was changed is the geometry
    if ( This->widget && window
#ifdef Q_WS_X11
	 && This->window == (Window) window->window
#endif
#ifdef Q_WS_WIN
	 && This->window == (HWND) window->window
#endif
	) {
	This->x = window->x;
	This->y = window->y;
	This->width = window->width;
	This->height = window->height;
	This->widget->resize( This->width, This->height );
	return result;
    }

    delete This->widget;

    if ( !window )
	return result;

#ifdef Q_WS_X11
    This->window = (Window) window->window;
    This->display =
	((NPSetWindowCallbackStruct *)window->ws_info)->display;
#endif
#ifdef Q_WS_WIN
    This->window = (HWND) window->window;
#endif

    This->x = window->x;
    This->y = window->y;
    This->width = window->width;
    This->height = window->height;


    if (!tqApp) {
#ifdef Q_WS_X11
	// We are the first TQt-based plugin to arrive
	event_loop = new TQNPXt( "qnp", XtDisplayToApplicationContext(This->display) );
	application = new TQApplication(This->display);
#endif
#ifdef Q_WS_WIN
	static int argc=0;
	static char **argv={ 0 };
	application = new TQApplication( argc, argv );
#ifdef UNICODE
	if ( qWinVersion() & TQt::WV_NT_based )
	    hhook = SetWindowsHookExW( WH_GETMESSAGE, FilterProc, 0, GetCurrentThreadId() );
	else
#endif
	    hhook = SetWindowsHookExA( WH_GETMESSAGE, FilterProc, 0, GetCurrentThreadId() );
#endif
    }

#ifdef Q_WS_X11
    if ( !original_x_errhandler )
    	original_x_errhandler = XSetErrorHandler( dummy_x_errhandler );
#endif

    // New widget on this new window.
    next_pi = This;
    /* This->widget = */ // (happens sooner - in TQNPWidget constructor)
    This->instance->newWindow();

    if ( !This->widget )
	return result;

#ifdef Q_WS_X11
    This->widget->resize( This->width, This->height );
    XReparentWindow( This->widget->x11Display(), This->widget->winId(), This->window, 0, 0 );
    XSync( This->widget->x11Display(), False );
#endif
#ifdef Q_WS_WIN
    LONG oldLong = GetWindowLong(This->window, GWL_STYLE);
    ::SetWindowLong(This->window, GWL_STYLE, oldLong | WS_CLIPCHILDREN | WS_CLIPSIBLINGS);
    ::SetWindowLong( This->widget->winId(), GWL_STYLE, WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS );
    ::SetParent( This->widget->winId(), This->window );
    This->widget->raise();
    This->widget->setGeometry( 0, 0, This->width, This->height );
#endif
    This->widget->show();
    return result;
}


extern "C" NPError
NPP_NewStream(NPP instance,
	  NPMIMEType type,
	  NPStream *stream,
	  NPBool seekable,
	  uint16 *stype)
{
    _NPInstance* This;

    if (instance == NULL)
	return NPERR_INVALID_INSTANCE_ERROR;

    This = (_NPInstance*) instance->pdata;

    if ( This ) {
	TQNPStream* qnps = new TQNPStream(This->instance,type,stream,seekable);
	stream->pdata = qnps;
	TQNPInstance::StreamMode sm = (TQNPInstance::StreamMode)*stype;
	if (!This->instance->newStreamCreated(qnps, sm)) {
	    return NPERR_GENERIC_ERROR;
	}
	*stype = sm;
    }

    return NPERR_NO_ERROR;
}


int32 STREAMBUFSIZE = 0X0FFFFFFF; /* If we are reading from a file in NPAsFile
				   * mode so we can take any size stream in our
				   * write call (since we ignore it) */

extern "C" int32
NPP_WriteReady(NPP instance, NPStream *stream)
{
    _NPInstance* This;
    if (instance != NULL) {
	This = (_NPInstance*) instance->pdata;
    } else {
	// Yikes, that's unusual!
	return 0;
    }

    if (This) {
	return This->instance->writeReady((TQNPStream*)stream->pdata);
    }

    /* Number of bytes ready to accept in NPP_Write() */
    return STREAMBUFSIZE;
}


extern "C" int32
NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer)
{
    if (instance != NULL)
    {
	_NPInstance* This = (_NPInstance*) instance->pdata;

	if (This) {
	    return This->instance->write((TQNPStream*)stream->pdata,
		offset, len, buffer);
	}
    }

    return len;        /* The number of bytes accepted */
}


extern "C" NPError
NPP_DestroyStream(NPP instance, NPStream *stream, NPError reason)
{
    _NPInstance* This;

    if (instance == NULL)
	return NPERR_INVALID_INSTANCE_ERROR;

    if (!qnps_no_call_back) {
	This = (_NPInstance*) instance->pdata;

	TQNPStream* qnps = (TQNPStream*)stream->pdata;
	if ( qnps )
	    switch (reason) {
		case NPRES_DONE:
		    qnps->setComplete(TRUE);
		    break;
		case NPRES_USER_BREAK:
		    break;
		case NPRES_NETWORK_ERR:
		    qnps->setOkay(FALSE);
		    break;
	    }

	if (This) {
	    // Give the instance a chance to do something
	    This->instance->streamDestroyed(qnps);
	}

	qnps_no_call_back++;
	delete qnps;
	qnps_no_call_back--;
    }

    return NPERR_NO_ERROR;
}


extern "C" void
NPP_StreamAsFile(NPP instance, NPStream *stream, const char* fname)
{
    _NPInstance* This;

    if (instance == NULL) return;

    This = (_NPInstance*) instance->pdata;

    if ( This ) {
	TQNPStream* qnps = (TQNPStream*)stream->pdata;
	This->instance->streamAsFile(qnps, fname);
    }
}

typedef struct
{
    int32    type;
    FILE*    fp;
} NPPrintCallbackStruct;

#ifdef Q_WS_X11

class TQNPPrinter : public TQPrinter {
    TQFile file;
public:
    TQNPPrinter(FILE* fp)
    {
	file.open(IO_WriteOnly, fp);
	TQPDevCmdParam param;
	param.device = &file;
	cmd(PdcSetdev, 0, &param);
    }
    void end()
    {
	TQPDevCmdParam param;
	param.device = 0;
	cmd(PdcSetdev, 0, &param);
    }
};
#endif

extern "C" void
NPP_Print(NPP instance, NPPrint* printInfo)
{
    if(printInfo == NULL)
	return;

    if (instance != NULL) {
	_NPInstance* This = (_NPInstance*) instance->pdata;

	if (printInfo->mode == NP_FULL) {
	    printInfo->print.fullPrint.pluginPrinted =
		This->instance->printFullPage();
	} else if (printInfo->mode == NP_EMBED) {
#ifdef Q_WS_X11
	    void* platformPrint =
		printInfo->print.embedPrint.platformPrint;
	    FILE* outfile = ((NPPrintCallbackStruct*)platformPrint)->fp;
	    if (ftell(outfile)) {
// 		NPWindow* w =
// 		    &(printInfo->print.embedPrint.window);
		TQNPPrinter prn(outfile);
		TQPainter painter(&prn);
		// #### config viewport with w->{x,y,width,height}
		This->instance->print(&painter);
		prn.end();
	    } else {
		// Why does the browser make spurious NPP_Print calls?
	    }
#endif
#ifdef Q_WS_WIN
	    NPWindow* printWindow =
		&(printInfo->print.embedPrint.window);
	    void* platformPrint =
		printInfo->print.embedPrint.platformPrint;
	    // #### Nothing yet.
#endif
	}
    }
}

extern "C" void
NPP_URLNotify(NPP instance,
	      const char* url,
	      NPReason reason,
	      void* notifyData)
{
    if (instance != NULL) {
	TQNPInstance::Reason r;
	switch (reason) {
	case NPRES_DONE:
	    r = TQNPInstance::ReasonDone;
	    break;
	case NPRES_USER_BREAK:
	    r = TQNPInstance::ReasonBreak;
	    break;
	case NPRES_NETWORK_ERR:
	    r = TQNPInstance::ReasonError;
	    break;
	default:
	    r = TQNPInstance::ReasonUnknown;
	    break;
	}
	_NPInstance* This = (_NPInstance*) instance->pdata;
	This->instance->notifyURL(url, r, notifyData);
    }
}



#ifdef Q_WS_WIN

BOOL   WINAPI   DllMain (HANDLE hInst,
			ULONG ul_reason_for_call,
			LPVOID lpReserved)
{
    return TRUE;
}

#endif



/*!
    \class TQNPWidget ntqnp.h
    \brief The TQNPWidget class provides a TQWidget that is a web browser plugin window.

    \extension Netscape Plugin

    Derive from TQNPWidget to create a widget that can be used as a
    web browser plugin window, or create one and add child widgets.
    Instances of TQNPWidget may only be created when
    TQNPInstance::newWindow() is called by the browser.

    A common way to develop a plugin widget is to develop it as a
    stand-alone application window, then make it a \e child of a
    plugin widget to use it as a browser plugin. The technique is:

\code
class MyPluginWindow : public TQNPWidget
{
    TQWidget* child;
public:
    MyPluginWindow()
    {
	// Some widget that is normally used as a top-level widget
	child = new MyIndependentlyDevelopedWidget();

	// Use the background color of the web page
	child->setBackgroundColor( backgroundColor() );

	// Fill the plugin widget
	child->setGeometry( 0, 0, width(), height() );
    }

    void resizeEvent(TQResizeEvent*)
    {
	// Fill the plugin widget
	child->resize(size());
    }
};
\endcode

    The default implementation is an empty window.
*/

/*!
    Creates a TQNPWidget.
*/
TQNPWidget::TQNPWidget() :
     pi(next_pi)
{
    if (!next_pi) {
	tqFatal("TQNPWidget must only be created within call to newWindow");
    }
    next_pi->widget = this;
    next_pi = 0;

#ifdef Q_WS_WIN
    clearWFlags( WStyle_NormalBorder | WStyle_Title | WStyle_MinMax | WStyle_SysMenu );
    topData()->ftop = 0;
    topData()->fright = 0;
    topData()->fleft = 0;
    topData()->fbottom = 0;
#endif
}

/*!
    Destroys the window. This will be called by the plugin binding
    code when the window is no longer required. The web browser will
    delete windows when they leave the page. The bindings will change
    the TQWidget::winId() of the window when the window is resized, but
    this should not affect normal widget behavior.
*/
TQNPWidget::~TQNPWidget()
{
#ifdef Q_WS_X11
    destroy( FALSE, FALSE ); // X has destroyed all windows
#endif
}


/*!\internal */
void TQNPWidget::enterEvent(TQEvent*)
{
    enterInstance();
}

/*!\internal */
void TQNPWidget:: leaveEvent(TQEvent*)
{
    if ( !TQApplication::activePopupWidget() )
	leaveInstance();
}

/*!
    Called when the mouse enters the plugin window. Does nothing by
    default.
*/
void TQNPWidget::enterInstance()
{
}

/*!
    Called when the mouse leaves the plugin window. Does nothing by
    default.
*/
void TQNPWidget::leaveInstance()
{
}

/*!
    Returns the instance for which this widget is the plugin window.
*/
TQNPInstance* TQNPWidget::instance()
{
    return pi->instance;
}





/*!
    \class TQNPInstance ntqnp.h
    \brief The TQNPInstance class provides a TQObject that is a web browser plugin.

    \extension Netscape Plugin

    Deriving from TQNPInstance creates an object that represents a
    single \c{<EMBED>} tag in an HTML document.

    The TQNPInstance is responsible for creating an appropriate
    TQNPWidget window if required (not all plugins have windows), and
    for interacting with the input/output facilities intrinsic to
    plugins.

    Note that there is \e{absolutely no guarantee} regarding the order
    in which functions are called. Sometimes the browser will call
    newWindow() first, at other times, newStreamCreated() will be
    called first (assuming the \c{<EMBED>} tag has a SRC parameter).

    \e{None of TQt's GUI functionality} may be used until after the
    first call to newWindow(). This includes any use of TQPaintDevice
    (i.e. TQPixmap, TQWidget, and all subclasses), TQApplication, anything
    related to TQPainter (TQBrush, etc.), fonts, TQMovie, TQToolTip, etc.
    Useful classes which specifically \e can be used are TQImage,
    TQFile, and TQBuffer.

    This restriction can easily be accommodated by structuring your
    plugin so that the task of the TQNPInstance is to gather data,
    while the task of the TQNPWidget is to provide a graphical
    interface to that data.
*/

/*!
    \enum TQNPInstance::InstanceMode

    This enum type provides TQt-style names for three #defines in
    \c npapi.h:

    \value Embed - corresponds to NP_EMBED
    \value Full - corresponds to NP_FULL
    \value Background - corresponds to NP_BACKGROUND

*/

/*!
    \enum TQNPInstance::Reason

    \value ReasonDone
    \value ReasonBreak
    \value ReasonError
    \value ReasonUnknown
*/

/*!
    \enum TQNPInstance::StreamMode

    \value Normal
    \value Seek
    \value AsFile
    \value AsFileOnly
*/

/*!
    Creates a TQNPInstance.

    Can only be called from within a derived class created within
    TQNPlugin::newInstance().
*/
TQNPInstance::TQNPInstance() :
    pi(next_pi)
{
    if (!next_pi) {
	tqFatal("TQNPInstance must only be created within call to newInstance");
    }
    next_pi->instance = this;
    next_pi = 0;
}

/*!
    Called when the plugin instance is about to be deleted.
*/
TQNPInstance::~TQNPInstance()
{
}

/*!
    Called at most once, at some time after the TQNPInstance is
    created. If the plugin requires a window, this function should
    return a derived class of TQNPWidget that provides the required
    interface.
*/
TQNPWidget* TQNPInstance::newWindow()
{
    // No window by default
    next_pi = 0;
    return 0;
}

/*!
    Returns the plugin window created by newWindow(), if any.
*/
TQNPWidget* TQNPInstance::widget()
{
    return pi->widget;
}

/*!
    \fn bool TQNPInstance::newStreamCreated(TQNPStream*, StreamMode& smode)

    This function is called when a new stream has been created. The
    instance should return TRUE if it accepts the processing of the
    stream. If the instance requires the stream as a file, it should
    set \a smode to \c AsFileOnly, in which case the data will be
    delivered some time later to the streamAsFile() function.
    Otherwise, the data will be delivered in chunks to the write()
    function, which must consume at least as much data as returned
    by the most recent call to writeReady().

    Note that the \c AsFileOnly method is not supported by Netscape
    2.0 and MSIE 3.0.

    The default implementation accepts any stream.
*/
bool TQNPInstance::newStreamCreated(TQNPStream*, StreamMode&)
{
    return TRUE;
}

/*!
    Called when a stream is delivered as a single file called \a fname
    rather than as chunks. This may be simpler for a plugin to deal
    with, but precludes any incremental behavior.

    Note that the \c AsFileOnly method is not supported by Netscape
    2.0 and MSIE 3.0.

    \sa newStreamCreated(), newStream()
*/
void TQNPInstance::streamAsFile(TQNPStream*, const char* fname)
{
}

/*!
    Called when a stream is destroyed. At this point, the stream may
    be complete() and okay(). If it is not okay(), then an error has
    occurred. If it is okay(), but not complete(), then the user has
    cancelled the transmission; do not give an error message in this
    case.
*/
void TQNPInstance::streamDestroyed(TQNPStream*)
{
}

/*!
    Returns the minimum amount of data the instance is willing to
    receive from the given stream.

    The default returns a very large value.
*/
int TQNPInstance::writeReady(TQNPStream*)
{
    // Yes, we can handle any amount of data at once.
    return 0X0FFFFFFF;
}

/*!
    \fn int TQNPInstance::write(TQNPStream*, int offset, int len, void* buffer)

    Called when incoming data is available for processing by the
    instance. The instance \e must consume at least the amount that it
    returned in the most recent call to writeReady(), but it may
    consume up to the amount given by \a len. \a buffer is the data
    available for consumption. The \a offset argument is merely an
    informational value indicating the total amount of data that has
    been consumed in prior calls.

    This function should return the amount of data actually consumed.
*/
int TQNPInstance::write(TQNPStream*, int, int len, void*)
{
    // Yes, we processed it all... into the bit bucket.
    return len;
}

/*!
    Requests that the \a url be retrieved and sent to the named \a
    window. See Netscape's JavaScript documentation for an explanation
    of window names.
*/
void TQNPInstance::getURL(const char* url, const char* window)
{
    NPN_GetURL( pi->npp, url, window );
}

/*!
    \preliminary

    This function is \e{not tested}.

    It is an interface to the NPN_PostURL function of the Netscape
    Plugin API.

    Passes \a url, \a window, \a buf, \a len, and \a file to
    NPN_PostURL.
*/
void TQNPInstance::postURL(const char* url, const char* window,
	     uint len, const char* buf, bool file)
{
    NPN_PostURL( pi->npp, url, window, len, buf, file );
}

/*!
    Requests that the given \a url be retrieved and sent to
    the named \a window. See Netscape's JavaScript documentation for
    an explanation of window names. Passes the arguments including \a
    data to NPN_GetURLNotify.

    \sa
    \link http://developer.netscape.com/docs/manuals/communicator/plugin/refpgur.htm#npngeturlnotify
    Netscape: NPN_GetURLNotify method\endlink
*/
void TQNPInstance::getURLNotify(const char* url, const char* window, void*data)
{
#ifdef Q_WS_WIN // Only on Windows?
    NPN_GetURLNotify( pi->npp, url, window, data );
#else
    Q_UNUSED( url );
    Q_UNUSED( window );
    Q_UNUSED( data );
#endif
}

/*!
    \preliminary

    This function is \e{not tested}.

    It is an encapsulation of the NPP_Print function of the Netscape
    Plugin API.
*/
bool TQNPInstance::printFullPage()
{
    return FALSE;
}

/*!
    \preliminary

    This function is \e{not tested}.

    Print the instance embedded in a page.

    It is an encapsulation of the NPP_Print function of the Netscape
    Plugin API.
*/
void TQNPInstance::print(TQPainter*)
{
    // ### default could redirected-print the window.
}

/*!
    Returns the number of arguments to the instance. Note that you
    should not normally rely on the ordering of arguments, and
    note that the SGML specification does not permit multiple
    arguments with the same name.

    \sa arg(), argn()
*/
int TQNPInstance::argc() const
{
    return pi->argc;
}

/*!
    Returns the name of the \a{i}-th argument.

    \sa argc(), argv()
*/
const char* TQNPInstance::argn(int i) const
{
    return pi->argn[i];
}

/*!
    \preliminary

    This function is \e{not tested}.

    Called whenever a \a url is notified after a call to
    NPN_GetURLNotify with \a notifyData. The reason is given in \a r.

    It is an encapsulation of the NPP_URLNotify function of the
    Netscape Plugin API.

    See also:
    \link http://developer.netscape.com/docs/manuals/communicator/plugin/refpgur.htm#nppurlnotify
    Netscape: NPP_URLNotify method\endlink
*/
void TQNPInstance::notifyURL(const char*, Reason, void*)
{
}

/*!
    Returns the value of the \a{i}-th argument.

    \as argc(), arg()
*/
const char* TQNPInstance::argv(int i) const
{
    return pi->argv[i];
}

/*!
    Returns the mode of the plugin.
*/
TQNPInstance::InstanceMode TQNPInstance::mode() const
{
    return (TQNPInstance::InstanceMode)pi->fMode;
}

/*!
    Returns the value of the named arguments, or 0 if no argument
    called \a name appears in the \c{<EMBED>} tag of this instance.
    If the argument appears, but has no value assigned, the empty
    string is returned. In summary:

    \table
    \header \i Tag \i Result
    \row \i \c{<EMBED ...>} \i arg("FOO") == 0
    \row \i \c{<EMBED FOO ...>} \i arg("FOO") == ""
    \row \i \c{<EMBED FOO=BAR ...>} \i arg("FOO") == "BAR"
    \endtable
*/
const char* TQNPInstance::arg(const char* name) const
{
    for (int i=0; i<pi->argc; i++) {
	// SGML: names are case insensitive
	if ( tqstricmp( name, pi->argn[i] ) == 0 ) {
	    if (pi->argv[i].isEmpty())
		return "";
	    else
		return pi->argv[i];
	}
    }
    return 0;
}

/*!
    Returns the user agent (browser name) containing this instance.
*/
const char* TQNPInstance::userAgent() const
{
    return NPN_UserAgent(pi->npp);
}

/*!
    \preliminary

    This function is \e{not tested}.

    Requests the creation of a new data stream \e from the plugin.
    The MIME type and window are passed in \a mimetype and \a window.
    \a as_file holds the \c AsFileOnly flag. It is an interface to the
    NPN_NewStream function of the Netscape Plugin API.
*/
TQNPStream* TQNPInstance::newStream(const char* mimetype, const char* window,
    bool as_file)
{
    NPStream* s=0;
    NPError err = NPN_NewStream(pi->npp, (char*)mimetype, window, &s);
    if (err != NPERR_NO_ERROR) return 0;
    return s ? new TQNPStream(this, mimetype, s, as_file) : 0;
}

/*!
    Sets the status message in the browser containing this instance to
    \a msg.
*/
void TQNPInstance::status(const char* msg)
{
    NPN_Status(pi->npp, msg);
}


/*!
    Returns the Java object associated with the plugin instance, an
    object of the \link TQNPlugin::getJavaClass() plugin's Java
    class\endlink, or 0 if the plug-in does not have a Java class,
    Java is disabled, or an error occurred.

    The return value is actually a \c{jref} we use \c{void*} so as to
    avoid burdening plugins which do not require Java.

    \sa TQNPlugin::getJavaClass(), TQNPlugin::getJavaEnv(), getJavaPeer()
*/
void* TQNPInstance::getJavaPeer() const
{
    return NPN_GetJavaPeer(pi->npp);
}


/*!
    \class TQNPStream ntqnp.h
    \brief The TQNPStream class provides a stream of data provided to a TQNPInstance by the browser.

    \extension Netscape Plugin

    Note that this is neither a TQTextStream nor a TQDataStream.

    \sa TQNPInstance::write(), TQNPInstance::newStreamCreated()
*/

/*!
    Creates a stream. Plugins should not call this; they should call
    TQNPInstance::newStream() if they need a stream.

    Takes a TQNPInstance \a in, MIME type \a mt, a pointer to an
    _NPStream \a st and a seekable flag \a se.
*/
TQNPStream::TQNPStream(TQNPInstance* in,const char* mt, _NPStream* st, bool se) :
    inst(in),
    stream(st),
    mtype(mt),
    seek(se)
{
    isokay = TRUE;
    iscomplete = FALSE;
}

/*!
    Destroys the stream.
*/
TQNPStream::~TQNPStream()
{
    if (!qnps_no_call_back) {
	qnps_no_call_back++;
	NPN_DestroyStream(inst->pi->npp, stream, NPRES_USER_BREAK);
	qnps_no_call_back--;
    }
}

/*!
    \fn TQNPInstance* TQNPStream::instance()

    Returns the TQNPInstance for which this stream was created.
*/

/*!
    Returns the URL from which the stream was created.
*/
const char* TQNPStream::url() const
{
    return stream->url;
}

/*!
    Returns the length of the stream in bytes. The function might
    return 0 for streams of unknown length.
*/
uint TQNPStream::end() const
{
    return stream->end;
}

/*!
    Returns the time when the source of the stream was last modified.
*/
uint TQNPStream::lastModified() const
{
    return stream->lastmodified;
}

/*!
    Returns the MIME type of the stream.
*/
const char* TQNPStream::type() const
{
    return mtype;
}

/*!
    Returns TRUE if the stream is seekable; otherwise returns FALSE.
*/
bool TQNPStream::seekable() const
{
    return seek;
}

/*!
  \internal
*/
void TQNPStream::setOkay(bool y)
{
    isokay = y;
}

/*!
  \internal
*/
void TQNPStream::setComplete(bool y)
{
    iscomplete = y;
}

/*!
    Returns TRUE if no errors have occurred on the stream; otherwise
    returns FALSE.
*/
bool TQNPStream::okay() const
{
    return isokay;
}

/*!
    Returns TRUE if the stream has received all the data from the
    source; otherwise returns FALSE.
*/
bool TQNPStream::complete() const
{
    return iscomplete;
}

/*!
    Requests the section of the stream, of \a length bytes from \a
    offset, be sent to the TQNPInstance::write() function of the
    instance() of this stream.
*/
void TQNPStream::requestRead(int offset, uint length)
{
    NPByteRange range;
    range.offset = offset;
    range.length = length;
    range.next = 0; // ### Only one supported at this time
    NPN_RequestRead(stream, &range);
}

/*!
    Writes \a len bytes from \a buffer \e to the stream.
*/
int TQNPStream::write( int len, void* buffer )
{
    return NPN_Write(inst->pi->npp, stream, len, buffer);
}



/******************************************************************************
 * The plugin itself - only one ever exists, created by TQNPlugin::create()
 *****************************************************************************/


/*!
    \class TQNPlugin ntqnp.h
    \brief The TQNPlugin class provides the main factory for plugin objects.

    \extension Netscape Plugin

    This class is the heart of the plugin. One instance of this object
    is created when the plugin is \e first needed, by calling
    TQNPlugin::create(), which must be implemented in your plugin code
    to return some derived class of TQNPlugin. The one TQNPlugin object
    creates all TQNPInstance instances for a web browser running in a
    single process.

    Additionally, if TQt is linked to the plugin as a dynamic library,
    only one instance of TQApplication will exist \e{across all plugins
    that have been made with TQt}. So, your plugin should tread lightly
    on global settings. Do not, for example, use
    TQApplication::setFont() - that will change the font in every
    widget of every TQt-based plugin currently loaded!
*/

/*!
    \fn TQNPlugin* TQNPlugin::create()

    This function must be implemented by your plugin code. It should return a
    derived class of TQNPlugin.
*/

/*!
    Returns the plugin most recently returned by TQNPlugin::create().
*/
TQNPlugin* TQNPlugin::actual()
{
    return qNP;
}

/*!
    Creates a TQNPlugin. This may only be used by the constructor
    of the class, derived from TQNPlugin, that is returned by your
    plugin's implementation of the TQNPlugin::create() function.
*/
TQNPlugin::TQNPlugin()
{
    // Encourage linker to include stuff.
    static void* a;
    a = (void*)NP_Initialize;
    a = (void*)NP_Shutdown;
}

/*!
    Destroys the TQNPlugin. This is called by the plugin binding code
    just before the plugin is about to be unloaded from memory. If
    newWindow() has been called, a TQApplication will still exist at
    this time, but will be deleted shortly after, just before the plugin
    is deleted.
*/
TQNPlugin::~TQNPlugin()
{
}

/*!
    Populates \e *\a plugin_major and \e *\a plugin_minor with the
    version of the plugin API and populates \e *\a browser_major and
    \e *\a browser_minor with the version of the web browser.
*/
void TQNPlugin::getVersionInfo(int& plugin_major, int& plugin_minor,
	     int& browser_major, int& browser_minor)
{
    NPN_Version(&plugin_major, &plugin_minor, &browser_major, &browser_minor);
}

/*!
    \fn TQNPInstance* TQNPlugin::newInstance()

    Override this function to return an appropriate derived class of
    TQNPInstance.
*/

/*!
    \fn const char* TQNPlugin::getMIMEDescription() const

    Override this function to return the MIME description of the data formats
    supported by your plugin. The format of this string is shown by
    the following example:

\code
    const char* getMIMEDescription() const
    {
	return "image/x-png:png:PNG Image;"
	       "image/png:png:PNG Image;"
	       "image/x-portable-bitmap:pbm:PBM Image;"
	       "image/x-portable-graymap:pgm:PGM Image;"
	       "image/x-portable-pixmap:ppm:PPM Image;"
	       "image/bmp:bmp:BMP Image;"
	       "image/x-ms-bmp:bmp:BMP Image;"
	       "image/x-xpixmap:xpm:XPM Image;"
	       "image/xpm:xpm:XPM Image";
    }
\endcode
*/

/*!
    \fn const char* TQNPlugin::getPluginNameString() const

    Returns a pointer to the plain-text name of the plugin.
*/

/*!
    \fn const char* TQNPlugin::getPluginDescriptionString() const

    Returns a pointer to the plain-text description of the plugin.
*/

/*!
    Override this function to return a reference to the Java class that represents
    the plugin. The default returns 0, indicating no class.

    If you override this class, you must also override
    TQNPlugin::unuseJavaClass().

    The return value is actually a \c{jref}; we use \c{void*} so as to
    avoid burdening plugins which do not require Java.

    \sa getJavaEnv(), TQNPInstance::getJavaPeer()
*/
void* TQNPlugin::getJavaClass()
{
    return NULL;
}

/*!
    This function is called when the plugin is shutting down. The
    function should \e unuse the Java class returned earlier by
    getJavaClass().
*/
void TQNPlugin::unuseJavaClass()
{
    tqFatal("TQNPlugin::unuseJavaClass() must be overridden along with getJavaClass()");
}

/*!
    Returns a pointer to the Java execution environment, or 0 if
    either Java is disabled or an error occurred.

    The return value is actually a \c{JRIEnv*}; we use \c{void*} so as
    to avoid burdening plugins which do not require Java.

    \sa getJavaClass(), TQNPInstance::getJavaPeer()
*/
void* TQNPlugin::getJavaEnv() const
{
    return NPN_GetJavaEnv();
}

#ifdef Q_WS_X11

#include <ntqapplication.h>
#include <ntqwidgetintdict.h>

// resolve the conflict between X11's FocusIn and TQEvent::FocusIn
const int XFocusOut = FocusOut;
const int XFocusIn = FocusIn;
#undef FocusOut
#undef FocusIn

const int XKeyPress = KeyPress;
const int XKeyRelease = KeyRelease;
#undef KeyPress
#undef KeyRelease

Boolean qnpxt_event_dispatcher( XEvent *event );
static void qnpxt_keep_alive();
void qnpxt_timeout_handler( XtPointer, XtIntervalId * );

class TQNPXtPrivate
{
public:
    TQNPXtPrivate();

    void hookMeUp();
    void unhook();

    XtAppContext appContext, ownContext;
    TQMemArray<XtEventDispatchProc> dispatchers;
    TQWidgetIntDict mapper;

    TQIntDict<TQSocketNotifier> socknotDict;
    uint pending_socknots;
    bool activate_timers;
    int timerid;

    // arguments for Xt display initialization
    const char* applicationClass;
    XrmOptionDescRec* options;
    int numOptions;
};
static TQNPXtPrivate *static_d = 0;
static XEvent* last_xevent = 0;


bool TQNPXt::redeliverEvent( XEvent *event )
{
    // redeliver the event to Xt, NOT through TQt
    if ( static_d->dispatchers[ event->type ]( event ) ) {
	// tqDebug( "Xt: redelivered event" );
	return TRUE;
    }
    return FALSE;
};


XEvent* TQNPXt::lastEvent()
{
    return last_xevent;
}


TQNPXtPrivate::TQNPXtPrivate()
    : appContext(NULL), ownContext(NULL),
      pending_socknots(0), activate_timers(FALSE), timerid(-1)
{
}

void TQNPXtPrivate::hookMeUp()
{
    // worker to plug TQt into Xt (event dispatchers)
    // and Xt into TQt (TQNPXtEventLoop)

    // ### TODO extensions?
    dispatchers.resize( LASTEvent );
    dispatchers.fill( 0 );
    int et;
    for ( et = 2; et < LASTEvent; et++ )
	dispatchers[ et ] =
	    XtSetEventDispatcher( TQPaintDevice::x11AppDisplay(),
				  et, ::qnpxt_event_dispatcher );
}

void TQNPXtPrivate::unhook()
{
    // unhook TQt from Xt (event dispatchers)
    // unhook Xt from TQt? (TQNPXtEventLoop)

    // ### TODO extensions?
    int et;
    for ( et = 2; et < LASTEvent; et++ )
	(void) XtSetEventDispatcher( TQPaintDevice::x11AppDisplay(),
				     et, dispatchers[ et ] );
    dispatchers.resize( 0 );

    /*
      We cannot destroy the app context here because it closes the X
      display, something TQApplication does as well a bit later.
      if ( ownContext )
          XtDestroyApplicationContext( ownContext );
     */
    appContext = ownContext = 0;
}

extern bool tqt_try_modal( TQWidget *, XEvent * ); // defined in qapplication_x11.cpp
Boolean qnpxt_event_dispatcher( XEvent *event )
{
    static bool grabbed = FALSE;

    TQApplication::sendPostedEvents();

    TQWidgetIntDict *mapper = &static_d->mapper;
    TQWidget* qnpxt = mapper->find( event->xany.window );
    if ( !qnpxt && TQWidget::find( event->xany.window) == 0 ) {
	// event is not for TQt, try Xt
	Widget w = XtWindowToWidget( TQPaintDevice::x11AppDisplay(),
				     event->xany.window );
	while ( w && ! ( qnpxt = mapper->find( XtWindow( w ) ) ) ) {
	    if ( XtIsShell( w ) ) {
		break;
	    }
	    w = XtParent( w );
	}

 	if ( qnpxt && ( event->type == XKeyPress ||
			 event->type == XKeyRelease ) )  {
	    // remap key events to keep accelerators working
 	    event->xany.window = qnpxt->winId();
 	}

	if ( w ) {
	    if ( !grabbed && ( event->type        == XFocusIn &&
			       event->xfocus.mode == NotifyGrab ) ) {
		// tqDebug( "Xt: grab started" );
		grabbed = TRUE;
	    } else if ( grabbed && ( event->type        == XFocusOut &&
				     event->xfocus.mode == NotifyUngrab ) ) {
		// tqDebug( "Xt: grab ended" );
		grabbed = FALSE;
	    }
	}
    }

    /*
      If the mouse has been grabbed for a window that we don't know
      about, we shouldn't deliver any pointer events, since this will
      intercept the event that ends the mouse grab that Xt/Motif
      started.
    */
    bool do_deliver = TRUE;
    if ( grabbed && ( event->type == ButtonPress   ||
		      event->type == ButtonRelease ||
		      event->type == MotionNotify  ||
		      event->type == EnterNotify   ||
		      event->type == LeaveNotify ) )
	do_deliver = FALSE;

    last_xevent = event;
    bool delivered = do_deliver && ( tqApp->x11ProcessEvent( event ) != -1 );
    last_xevent = 0;
    if ( qnpxt ) {
	switch ( event->type ) {
	case EnterNotify:
	case LeaveNotify:
	    event->xcrossing.focus = False;
	    delivered = FALSE;
	    break;
	case XKeyPress:
	case XKeyRelease:
	    delivered = TRUE;
	    break;
	case XFocusIn:
	case XFocusOut:
	    delivered = FALSE;
	    break;
	default:
	    delivered = FALSE;
	    break;
	}
    }

    qnpxt_keep_alive();

    if ( delivered ) {
	// tqDebug( "TQt: delivered event" );
	return True;
    }

    // discard user input events when we have an active popup widget
    if ( TQApplication::activePopupWidget() ) {
	switch ( event->type ) {
	case ButtonPress:			// disallow mouse/key events
	case ButtonRelease:
	case MotionNotify:
	case XKeyPress:
	case XKeyRelease:
	case EnterNotify:
	case LeaveNotify:
	case ClientMessage:
	    // tqDebug( "TQt: active popup - discarding event" );
	    return True;

	default:
	    break;
	}
    }

    if ( TQApplication::activeModalWidget() ) {
	if ( qnpxt ) {
	    // send event through TQt modality handling...
	    if ( !tqt_try_modal( qnpxt, event ) ) {
		// tqDebug( "TQt: active modal widget discarded event" );
		return True;
	    }
	} else if ( !grabbed ) {
	    // we could have a pure Xt shell as a child of the active
	    // modal widget
	    TQWidget *qw = 0;
	    Widget xw = XtWindowToWidget( TQPaintDevice::x11AppDisplay(),
					  event->xany.window );
	    while ( xw && !( qw = mapper->find( XtWindow( xw ) ) ) )
		xw = XtParent( xw );

	    while ( qw && qw != TQApplication::activeModalWidget() )
		qw = qw->parentWidget();

	    if ( !qw ) {
		// event is destined for an Xt widget, but since TQt has an
		// active modal widget, we stop here...
		switch ( event->type ) {
		case ButtonPress:			// disallow mouse/key events
		case ButtonRelease:
		case MotionNotify:
		case XKeyPress:
		case XKeyRelease:
		case EnterNotify:
		case LeaveNotify:
		case ClientMessage:
		    // tqDebug( "TQt: active modal widget discarded unknown event" );
		    return True;
		default:
		    break;
		}
	    }
	}
    }

    if ( static_d->dispatchers[ event->type ]( event ) ) {
	// tqDebug( "Xt: delivered event" );
	// Xt handled the event.
	return True;
    }

    return False;
}



TQNPXt::TQNPXt( const char *applicationClass, XtAppContext context,
		XrmOptionDescRec *options , int numOptions)
{
#if defined(QT_CHECK_STATE)
    if ( static_d )
	tqWarning( "TQNPXt: should only have one TQNPXt instance!" );
#endif

    d = static_d = new TQNPXtPrivate;
    XtToolkitInitialize();
    if ( context )
	d->appContext = context;
    else
	d->ownContext = d->appContext = XtCreateApplicationContext();

    d->applicationClass = applicationClass;
    d->options = options;
    d->numOptions = numOptions;
}


TQNPXt::~TQNPXt()
{
    delete d;
    static_d = 0;
}

XtAppContext TQNPXt::applicationContext() const
{
    return d->appContext;
}


void TQNPXt::appStartingUp()
{
    /*
      TQApplication could be using a Display from an outside source, so
      we should only initialize the display if the current application
      context does not contain the TQApplication display
    */

    bool display_found = FALSE;
    Display **displays;
    Cardinal x, count;
    XtGetDisplays( d->appContext, &displays, &count );
    for ( x = 0; x < count && ! display_found; ++x ) {
	if ( displays[x] == TQPaintDevice::x11AppDisplay() )
	    display_found = TRUE;
    }
    if ( displays )
	XtFree( (char *) displays );

    if ( ! display_found ) {
	int argc = tqApp->argc();
	XtDisplayInitialize( d->appContext,
			     TQPaintDevice::x11AppDisplay(),
			     tqApp->name(),
			     d->applicationClass,
			     d->options,
			     d->numOptions,
			     &argc,
			     tqApp->argv() );
    }

    d->hookMeUp();

    // start a zero-timer to get the timer keep-alive working
    d->timerid = XtAppAddTimeOut( d->appContext, 0, qnpxt_timeout_handler, 0 );
}

void TQNPXt::appClosingDown()
{
    if ( d->timerid != -1 )
	XtRemoveTimeOut( d->timerid );
    d->timerid = -1;

    d->unhook();
}


void TQNPXt::registerWidget( TQWidget* w )
{
    if ( !static_d )
	return;
    static_d->mapper.insert( w->winId(), w );
}


void TQNPXt::unregisterWidget( TQWidget* w )
{
    if ( !static_d )
	return;
    static_d->mapper.remove( w->winId() );
}


void qnpxt_socknot_handler( XtPointer pointer, int *, XtInputId *id )
{
    TQNPXt *eventloop = (TQNPXt *) pointer;
    TQSocketNotifier *socknot = static_d->socknotDict.find( *id );
    if ( ! socknot ) // this shouldn't happen
	return;
    eventloop->setSocketNotifierPending( socknot );
    if ( ++static_d->pending_socknots > static_d->socknotDict.count() ) {
	/*
	  We have too many pending socket notifiers.  Since Xt prefers
	  socket notifiers over X events, we should go ahead and
	  activate all our pending socket notifiers so that the event
	  loop doesn't freeze up because of this.
	*/
	eventloop->activateSocketNotifiers();
	static_d->pending_socknots = 0;
    }
}

void TQNPXt::registerSocketNotifier( TQSocketNotifier *notifier )
{
    XtInputMask mask;
    switch ( notifier->type() ) {
    case TQSocketNotifier::Read:
	mask = XtInputReadMask;
	break;

    case TQSocketNotifier::Write:
	mask = XtInputWriteMask;
	break;

    case TQSocketNotifier::Exception:
	mask = XtInputExceptMask;
	break;

    default:
	tqWarning( "TQNPXtEventLoop: socket notifier has invalid type" );
	return;
    }

    XtInputId id = XtAppAddInput( d->appContext,
				  notifier->socket(), (XtPointer) mask,
				  qnpxt_socknot_handler, this );
    d->socknotDict.insert( id, notifier );

    TQEventLoop::registerSocketNotifier( notifier );
}

void TQNPXt::unregisterSocketNotifier( TQSocketNotifier *notifier )
{
    TQIntDictIterator<TQSocketNotifier> it( d->socknotDict );
    while ( it.current() && notifier != it.current() )
	++it;
    if ( ! it.current() ) {
	// this shouldn't happen
	tqWarning( "TQNPXtEventLoop: failed to unregister socket notifier" );
	return;
    }

    XtRemoveInput( it.currentKey() );
    d->socknotDict.remove( it.currentKey() );

    TQEventLoop::unregisterSocketNotifier( notifier );
}

static void qnpxt_keep_alive() {
    // make sure we fire off TQt's timers
    int ttw = TQApplication::eventLoop()->timeToWait();
    if ( static_d->timerid != -1 )
	XtRemoveTimeOut( static_d->timerid );
    static_d->timerid = -1;
    if ( ttw != -1 ) {
	static_d->timerid =
	    XtAppAddTimeOut( static_d->appContext, ttw, qnpxt_timeout_handler, 0 );
    }
}

void qnpxt_timeout_handler( XtPointer, XtIntervalId * )
{
    static_d->timerid = -1;

    if ( ! TQApplication::eventLoop()->loopLevel() ) {
	/*
	  when the TQt eventloop is not running, make sure that TQt
	  timers still work with an Xt keep-alive timer
	*/
	TQApplication::eventLoop()->activateTimers();
	static_d->activate_timers = FALSE;

	qnpxt_keep_alive();
    } else {
	static_d->activate_timers = TRUE;
    }
}

bool TQNPXt::processEvents( ProcessEventsFlags flags )
{
    // TQt uses posted events to do lots of delayed operations, like
    // repaints... these need to be delivered before we go to sleep
    TQApplication::sendPostedEvents();

    bool canWait = ( flags & WaitForMore );

    qnpxt_keep_alive();

    // get the pending event mask from Xt and process the next event
    XtInputMask pendingmask = XtAppPending( d->appContext );
    XtInputMask mask = pendingmask;
    if ( pendingmask & XtIMTimer ) {
	mask &= ~XtIMTimer;
	// zero timers will starve the Xt X event dispatcher... so
	// process something *instead* of a timer first...
	if ( mask != 0 )
	    XtAppProcessEvent( d->appContext, mask );
	// and process a timer afterwards
	mask = pendingmask & XtIMTimer;
    }

    if ( canWait )
	XtAppProcessEvent( d->appContext, XtIMAll );
    else
	XtAppProcessEvent( d->appContext, mask );

    int nevents = 0;
    if ( ! ( flags & ExcludeSocketNotifiers ) ) {
	nevents += activateSocketNotifiers();
	d->pending_socknots = 0;
    }

    if ( d->activate_timers ) {
	nevents += activateTimers();
    }
    d->activate_timers = FALSE;

    return ( canWait || ( pendingmask != 0 ) || nevents > 0 );
}


#endif // Q_WS_X11