File: pmshell.c

package info (click to toggle)
links2 2.7-1%2Bdeb7u1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 17,720 kB
  • sloc: ansic: 121,532; sh: 2,333; cpp: 571; makefile: 115; awk: 47; perl: 34
file content (2265 lines) | stat: -rw-r--r-- 57,405 bytes parent folder | download
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
/* pmshell.c
 * PMShell graphics driver
 * (c) 2002 Mikulas Patocka
 * This file is a part of the Links program, released under GPL.
 */

#include "cfg.h"

#if 0
#define debug_call(x) printf x; fflush(stdout);
#else
#define debug_call(x)
#endif

#ifdef GRDRV_PMSHELL

#include "links.h"

extern struct graphics_driver pmshell_driver;

#ifdef OS2

#define INCL_DOS
#define INCL_DOSERRORS
#define INCL_GPI
#define INCL_WIN
#include <os2.h>

#include <sys/builtin.h>
#include <sys/fmutex.h>

#define PM_SPAWN_SUBPROC

extern PPIB os2_pib;

static ULONG pm_hidden_frame = 0;
static ULONG pm_frame = (FCF_TITLEBAR | FCF_SYSMENU | FCF_SIZEBORDER | FCF_MINMAX | FCF_SHELLPOSITION | FCF_TASKLIST | FCF_NOBYTEALIGN);

static HAB hab_disp;
static HAB hab;
static HMQ hmq;
static HDC hdc_mem;
static HPS hps_mem;
static HWND hwnd_hidden;
static HPS hps_hidden;
static HPOINTER icon;

static _fmutex pm_mutex;

static int pm_lock_init(void)
{
	return _fmutex_create(&pm_mutex, 0);
}

static void pm_lock_close(void)
{
	_fmutex_checked_close(&pm_mutex);
}

static inline void pm_lock(void)
{
	_fmutex_request(&pm_mutex, _FMR_IGNINT);
}

static inline void pm_unlock(void)
{
	_fmutex_release(&pm_mutex);
}

static HEV pm_sem;
static ULONG pm_event_dummy;

static int pm_event_init(void)
{
	return DosCreateEventSem(NULL, &pm_sem, 0, 0);
}

static void pm_event_close(void)
{
	APIRET r;
	r = DosCloseEventSem(pm_sem);
	if (r && r != ERROR_SEM_BUSY)
		fatal_exit("DoscloseEventSem failed: %ld", (long)r);
}

static inline void pm_event_wait(void)
{
	APIRET r;
	wait_again:
	r = DosWaitEventSem(pm_sem, SEM_INDEFINITE_WAIT);
	if (r == ERROR_INTERRUPT)
		goto wait_again;
	if (r)
		fatal_exit("DosWaitEventSem failed: %ld", (long)r);
	if ((r = DosResetEventSem(pm_sem, &pm_event_dummy)))
		fatal_exit("DosResetEventSem failed: %ld", (long)r);
}

static inline void pm_event_signal(void)
{
	APIRET r;
	if ((r = DosPostEventSem(pm_sem)))
		fatal_exit("DosPostEventSem failed: %ld", (long)r);
}

static inline void SetCapture(HWND hwnd)
{
	WinSetCapture(HWND_DESKTOP, hwnd);
}

static inline void ReleaseCapture(void)
{
	WinSetCapture(HWND_DESKTOP, NULLHANDLE);
}

#endif

#ifdef WIN32

/*#define UNICODE*/
/*#define NO_STRICT*/

#include <windows.h>
#ifdef HAVE_WINDOWSX_H
#include <windowsx.h>
#endif
#include <pthread.h>

static HMODULE module_handle;
static pthread_t pthread_handle;
static int unicode_title_supported;
static int unicode_supported;
static ATOM window_class_atom;
static HDC screen_dc;
static HWND hwnd_hidden;
static HICON icon_big;
static HICON icon_small;

#define RECTL		RECT
#define xLeft		left
#define xRight		right
#define yTop		top
#define yBottom		bottom

#define WM_BUTTON1DOWN		WM_LBUTTONDOWN
#define WM_BUTTON1DBLCLK	WM_LBUTTONDBLCLK
#define WM_BUTTON2DOWN		WM_RBUTTONDOWN
#define WM_BUTTON2DBLCLK	WM_RBUTTONDBLCLK
#define WM_BUTTON3DOWN		WM_MBUTTONDOWN
#define WM_BUTTON3DBLCLK	WM_MBUTTONDBLCLK

#define WM_BUTTON1UP		WM_LBUTTONUP
#define WM_BUTTON2UP		WM_RBUTTONUP
#define WM_BUTTON3UP		WM_MBUTTONUP

#ifndef WM_XBUTTONDOWN
#define WM_XBUTTONDOWN		0x20b
#endif
#ifndef WM_XBUTTONDBLCLK
#define WM_XBUTTONDBLCLK	0x20d
#endif
#ifndef WM_XBUTTONUP
#define WM_XBUTTONUP		0x20c
#endif
#ifndef XBUTTON1
#define XBUTTON1		0x0001
#endif
#ifndef XBUTTON2
#define XBUTTON2		0x0002
#endif
#ifndef GET_X_LPARAM
#define GET_X_LPARAM(lp) 	((short)LOWORD(lp))
#endif
#ifndef GET_Y_LPARAM
#define GET_Y_LPARAM(lp) 	((short)HIWORD(lp))
#endif

static HANDLE winapi_semaphore;

static int pm_lock_init(void)
{
	winapi_semaphore = CreateSemaphoreA(NULL, 1, 1, NULL);
	return !winapi_semaphore;
}

static void pm_lock_close(void)
{
	if (!CloseHandle(winapi_semaphore)) 
		fatal_exit("CloseHandle failed");
}

static inline void pm_lock(void)
{
	if (WaitForSingleObject(winapi_semaphore, INFINITE) == WAIT_FAILED)
		fatal_exit("WaitForSingleObject failed");
}

static inline void pm_unlock(void)
{
	if (!ReleaseSemaphore(winapi_semaphore, 1, NULL))
		fatal_exit("ReleaseSemaphore failed");
}

static HANDLE winapi_event;

static int pm_event_init(void)
{
	winapi_event = CreateEventA(NULL, FALSE, FALSE, NULL);
	return !winapi_event;
}

static void pm_event_close(void)
{
	if (!CloseHandle(winapi_event)) 
		fatal_exit("CloseHandle failed");
}

static inline void pm_event_wait(void)
{
	if (WaitForSingleObject(winapi_event, INFINITE) == WAIT_FAILED)
		fatal_exit("WaitForSingleObject failed");
}

static inline void pm_event_signal(void)
{
	if (!SetEvent(winapi_event))
		fatal_exit("SetEvent failed");
}

#endif

static BITMAPINFO *pm_bitmapinfo;
static int icon_set;

#define pm_class_name	"links"
#define pm_class_name_l	L"links"

#define E_KEY		1
#define E_MOUSE		2
#define E_REDRAW	3
#define E_RESIZE	4

struct pm_event {
	struct pm_event *next;
	struct pm_event *prev;
	int type;
	int x1, y1, x2, y2;
};

struct pm_window {
	struct pm_window *next;
	struct pm_window *prev;
	int x, y;
	unsigned char in;
	unsigned char minimized;
	struct pm_window *nxt;
	struct pm_window **prv;
#ifdef OS2
	HPS ps;
	HWND h;
#endif
#ifdef WIN32
	HDC dc;
	HPEN pen_cache;
	HBRUSH brush_cache;
	int pen_cache_color;
	int brush_cache_color;
#endif
	HWND hc;
	struct graphics_device *dev;
	int button;
	unsigned long lastpos;
	struct list_head queue;
};

#define WIN_HASH	64

#ifdef OS2
static int HASH_VALUE(HWND hw)
{
	return hw & (WIN_HASH - 1);
}
#endif
#ifdef WIN32
static int HASH_VALUE(HWND hw)
{
	return (unsigned long)hw & (WIN_HASH - 1);
}
#endif

static struct pm_window *pm_windows[WIN_HASH];

static void pm_hash_window(struct pm_window *win)
{
	int pos = HASH_VALUE(win->hc);
	win->prv = &pm_windows[pos];
	if ((win->nxt = pm_windows[pos])) pm_windows[pos]->prv = &win->nxt;
	pm_windows[pos] = win;
}

static void pm_unhash_window(struct pm_window *win)
{
	if (win->nxt) win->nxt->prv = win->prv;
	*win->prv = win->nxt;
}

static inline struct pm_window *pm_lookup_window(HWND h)
{
	struct pm_window *win;
	for (win = pm_windows[HASH_VALUE(h)]; win && win->hc != h; win = win->nxt) ;
	return win;
}

#define pm_win(dev) ((struct pm_window *)dev->driver_data)

static int pm_pipe[2];

static unsigned char *pm_status;

static int pm_cp;

static struct list_head pm_event_windows = { &pm_event_windows, &pm_event_windows };

static void pm_send_event(struct pm_window *win, int t, int x1, int y1, int x2, int y2)
{
	/* must be called with pm_lock */
	struct pm_event *ev;
	if ((ev = malloc(sizeof(struct pm_event)))) {
		ev->type = t;
		ev->x1 = x1, ev->y1 = y1;
		ev->x2 = x2, ev->y2 = y2;
		if (!win->in) {
			if (list_empty(pm_event_windows)) {
				int wr;
				EINTRLOOP(wr, write(pm_pipe[1], "x", 1));
			}
			add_to_list(pm_event_windows, win);
			win->in = 1;
		}
		add_to_list(win->queue, ev);
	}
}

static void pm_send_mouse_event(struct pm_window *win, int x1, int y1, int b)
{
	if (!list_empty(win->queue)) {
		struct pm_event *last = win->queue.next;
		if (last->type == E_MOUSE && last->x2 == b) {
			last->x1 = x1;
			last->y1 = y1;
			return;
		}
	}
	pm_send_event(win, E_MOUSE, x1, y1, b, 0);
}

static void pm_cancel_event(struct pm_window *win, int t, struct pm_event **pev)
{
	struct pm_event *ev;
	if (pev) *pev = NULL;
	foreachback(ev, win->queue) if (ev->type == t) {
		if (pev) *pev = ev;
		else {
			del_from_list(ev);
			free(ev);
		}
		return;
	}
}

static void pm_resize(struct pm_window *win, RECTL *r)
{
	struct pm_event *ev;
	win->x = r->xRight;
	win->y = r->yTop;
	pm_cancel_event(win, E_REDRAW, NULL);
	pm_cancel_event(win, E_RESIZE, &ev);
	if (ev) {
		ev->x2 = r->xRight;
		ev->y2 = r->yTop;
	} else pm_send_event(win, E_RESIZE, 0, 0, r->xRight, r->yTop);
}

static void pm_redraw(struct pm_window *win, RECTL *r)
{
	struct pm_event *ev;
	pm_cancel_event(win, E_RESIZE, &ev);
	if (ev) return;
	pm_cancel_event(win, E_REDRAW, &ev);
	if (ev) {
		if (r->xLeft < ev->x1) ev->x1 = r->xLeft;
		if (r->xRight > ev->x2) ev->x2 = r->xRight;
		if (win->y - r->yTop < ev->y1) ev->y1 = win->y - r->yTop;
		if (win->y - r->yBottom > ev->y2) ev->y2 = win->y - r->yBottom;
		return;
	}
	pm_send_event(win, E_REDRAW, r->xLeft, win->y - r->yTop, r->xRight, win->y - r->yBottom);
}

#ifdef OS2

#define N_VK	0x42

static struct os2_key pm_vk_table[N_VK] = {
	{0, 0}, {0, 0}, {0, 0}, {0, 0}, {KBD_CTRL_C, 0}, {KBD_BS, 0}, {KBD_TAB, 0}, {KBD_TAB, KBD_SHIFT},
	{KBD_ENTER, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {KBD_ESC, 0},
	{' ', 0}, {KBD_PAGE_UP, 0}, {KBD_PAGE_DOWN, 0}, {KBD_END, 0}, {KBD_HOME, 0}, {KBD_LEFT, 0}, {KBD_UP, 0}, {KBD_RIGHT, 0},
	{KBD_DOWN, 0}, {0, 0}, {KBD_INS, 0}, {KBD_DEL, 0}, {0, 0}, {0, 0}, {KBD_ENTER, 0}, {0, 0},
	{KBD_F1, 0}, {KBD_F2, 0}, {KBD_F3, 0}, {KBD_F4, 0}, {KBD_F5, 0}, {KBD_F6, 0}, {KBD_F7, 0}, {KBD_F8, 0},
	{KBD_F9, 0}, {KBD_F10, 0}, {KBD_F11, 0}, {KBD_F12, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
	{0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
	{0, 0}, {KBD_DEL, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0},
	{0, 0}, {0, 0}
};

#endif

static int win_x(struct pm_window *win)
{
#ifdef OS2
	int x = (short)(win->lastpos & 0xffff);
#endif
#ifdef WIN32
	int x = GET_X_LPARAM(win->lastpos);
#endif
	if (x < 0) x = -1;
	if (x > win->x) x = win->x;
	return x;
}

static int win_y(struct pm_window *win)
{
#ifdef OS2
	int y = (short)(win->y - (win->lastpos >> 16));
#endif
#ifdef WIN32
	int y = GET_Y_LPARAM(win->lastpos);
#endif
	if (y < 0) y = -1;
	if (y > win->y) y = win->y;
	return y;
}

static void pm_user_msg(unsigned long msg, void *mp1, void *mp2);

#ifdef OS2
static MRESULT EXPENTRY pm_window_proc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
#define mouse_pos	((unsigned)mp1)
#endif
#ifdef WIN32
static LRESULT CALLBACK pm_window_proc(HWND hwnd, UINT msg, WPARAM mp1, LPARAM mp2)
#define mouse_pos	((unsigned long)mp2)
#endif
{
#ifdef OS2
	int k_usch;
	int scancode;
#endif
	int flags;
	long k_usvk;
	long k_fsflags;
	long key;
	struct pm_window *win;
	RECTL wr, ur;
	/*fprintf(stderr, "%08x %08x %08x\n", (int)msg, (int)mp1, (int)mp2);*/
	if (hwnd == hwnd_hidden) {
		pm_user_msg(msg, (void *)mp1, (void *)mp2);
	} else switch (msg) {
		case WM_PAINT:
			pm_lock();
#ifdef OS2
			WinQueryUpdateRect(hwnd, &ur);
			if (!WinQueryWindowRect(hwnd, &wr)) {
				memset(&wr, 0, sizeof wr);
			}
			WinValidateRect(hwnd, &ur, FALSE);
#endif
#ifdef WIN32
			GetUpdateRect(hwnd, &ur, FALSE);
			if (!GetClientRect(hwnd, &wr)) {
				memset(&wr, 0, sizeof wr);
			}
			wr.yTop = wr.yBottom;
			wr.yBottom = 0;
			if (!ValidateRect(hwnd, &ur))
				fatal_exit("ValidateRect failed");
#endif
			if (!(win = pm_lookup_window(hwnd))) {
				pm_unlock();
				return 0;
			}
			if (win->minimized) {
				pm_unlock();
				break;
			}
#ifdef WIN32
			ur.yTop = win->y - ur.yTop;
			ur.yBottom = win->y - ur.yBottom;
#endif
			if (wr.xRight != win->x || wr.yTop != win->y) {
#if 0
				if (WinQueryWindowRect(win->h, &wr)) {
					pm_default_window_width = wr.xRight;
					pm_default_window_height = wr.yTop;
				}
#endif
				pm_resize(win, &wr);
			} else {
				pm_redraw(win, &ur);
			}
			pm_unlock();
			return 0;
#ifdef OS2
		case WM_MINMAXFRAME:
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) {
				pm_unlock();
				return 0;
			}
			if (((SWP *)mp1)->fl & (SWP_HIDE | SWP_MINIMIZE))
				win->minimized = 1;
			else
				win->minimized = 0;
			pm_unlock();
			break;
#endif
		case WM_CLOSE:
		case WM_QUIT:
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) {
				pm_unlock();
				return 0;
			}
			pm_send_event(win, E_KEY, KBD_CTRL_C, 0, 0, 0);
			pm_unlock();
			return 0;
		case WM_CHAR:
#ifdef WIN32
		case WM_SYSCHAR:
		case WM_KEYDOWN:
		case WM_SYSKEYDOWN:
#endif
#ifdef OS2
			k_fsflags = (int)mp1;
			scancode = ((unsigned long)mp1 >> 24) & 0xff;
			k_usch = (int)mp2 & 0xffff;
			k_usvk = ((int)mp2 >> 16) & 0xffff;

			/*
			 * F1 keydown is lost for unknown reason --- so catch
			 * keyup instead.
			 */
			if ((k_fsflags & (KC_VIRTUALKEY | KC_CHAR)) == KC_VIRTUALKEY && k_usvk == 0x20)
				k_fsflags ^= KC_KEYUP;

			if (k_fsflags & (KC_KEYUP | KC_DEADKEY | KC_INVALIDCOMP))
				return 0;

			flags = (k_fsflags & KC_SHIFT ? KBD_SHIFT : 0) | (k_fsflags & KC_CTRL ? KBD_CTRL : 0) | (k_fsflags & KC_ALT ? KBD_ALT : 0);
			if (k_fsflags & KC_ALT && ((scancode >= 0x47 && scancode <= 0x49) || (scancode >= 0x4b && scancode <= 0x4d) || (scancode >= 0x4f && scancode <= 0x52))) return 0;
			if ((k_fsflags & (KC_VIRTUALKEY | KC_CHAR)) == KC_VIRTUALKEY) {
				if (k_usvk < N_VK && (key = pm_vk_table[k_usvk].x)) {
					flags |= pm_vk_table[k_usvk].y;
					if (key == KBD_CTRL_C) flags &= ~KBD_CTRL;
					goto s;
				}
			}
			if (k_usch & 0xff) {
				key = k_usch & 0xff;
				if (!(flags & KBD_CTRL)) {
					if (key == 0x0d) key = KBD_ENTER;
					if (key == 0x08) key = KBD_BS;
					if (key == 0x09) key = KBD_TAB;
					if (key == 0x1b) key = KBD_ESC;
				}
				if (key >= 0 && key < ' ') key += '@', flags |= KBD_CTRL;
			} else key = os2xtd[k_usch >> 8].x, flags |= os2xtd[k_usch >> 8].y;
			if ((key & 0xdf) == 'C' && (flags & KBD_CTRL)) key = KBD_CTRL_C, flags &= ~KBD_CTRL;
			s:
			if (!key) return 0;
			/*if (key >= 0) flags &= ~KBD_SHIFT;*/
			if (key >= 0x80 && pm_cp) {
				if ((key = cp2u(key, pm_cp)) < 0) return 0;
			}
#endif
#ifdef WIN32
			k_fsflags = (long)mp2;
			flags = 0;
			if (k_fsflags & (1 << 29))
				flags |= KBD_ALT;
			if (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN) {
				/*fprintf(stderr, "vk: %lx %lx\n", (long)mp1, (long)mp2);*/
				k_usvk = (long)mp1;
				switch (k_usvk) {
					case VK_CANCEL: key = KBD_CTRL_C; break;
					case VK_PRIOR: key = KBD_PAGE_UP; break;
					case VK_NEXT: key = KBD_PAGE_DOWN; break;
					case VK_END: key = KBD_END; break;
					case VK_HOME: key = KBD_HOME; break;
					case VK_LEFT: key = KBD_LEFT; break;
					case VK_RIGHT: key = KBD_RIGHT; break;
					case VK_DOWN: key = KBD_DOWN; break;
					case VK_UP: key = KBD_UP; break;
					case VK_INSERT: key = KBD_INS; break;
					case VK_DELETE: key = KBD_DEL; break;
					case VK_HELP: key = KBD_F1; break;
					case VK_F1: key = KBD_F1; break;
					case VK_F2: key = KBD_F2; break;
					case VK_F3: key = KBD_F3; break;
					case VK_F4: key = KBD_F4; break;
					case VK_F5: key = KBD_F5; break;
					case VK_F6: key = KBD_F6; break;
					case VK_F7: key = KBD_F7; break;
					case VK_F8: key = KBD_F8; break;
					case VK_F9: key = KBD_F9; break;
					case VK_F10: key = KBD_F10; break;
					case VK_F11: key = KBD_F11; break;
					case VK_F12: key = KBD_F12; break;
					default: return 0;
				}
			} else {
				/*fprintf(stderr, "ch: %lx %lx\n", (long)mp1, (long)mp2);*/
				key = (long)mp1;
				if (key <= 0) return 0;
				if (key > 0 && key < 0x20) {
					if (key == 3) key = KBD_CTRL_C;
					else if (key == 8) key = KBD_BS;
					else if (key == 9) key = KBD_TAB;
					else if (key == 10) key = KBD_ENTER;
					else if (key == 13) key = KBD_ENTER;
					else if (key == 27) key = KBD_ESC;
					else if (key == 127) key = KBD_BS;
					else {
						key += 'A' - 1;
						flags |= KBD_CTRL;
					}
				} else if (!unicode_supported) {
					key = cp2u(key, pm_cp);
				}
			}
#endif
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) {
				pm_unlock();
				return 0;
			}
			pm_send_event(win, E_KEY, key, flags, 0, 0);
			pm_unlock();
			return 0;
		case WM_BUTTON1DOWN:
		case WM_BUTTON1DBLCLK:
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			win->button |= 1 << B_LEFT;
			win->lastpos = mouse_pos;
			pm_send_event(win, E_MOUSE, win_x(win), win_y(win), B_DOWN | B_LEFT, 0);
			pm_unlock();
			SetCapture(hwnd);
			break;
		case WM_BUTTON2DOWN:
		case WM_BUTTON2DBLCLK:
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			win->button |= 1 << B_RIGHT;
			win->lastpos = mouse_pos;
			pm_send_event(win, E_MOUSE, win_x(win), win_y(win), B_DOWN | B_RIGHT, 0);
			pm_unlock();
			SetCapture(hwnd);
			break;
		case WM_BUTTON3DOWN:
		case WM_BUTTON3DBLCLK:
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			win->button |= 1 << B_MIDDLE;
			win->lastpos = mouse_pos;
			pm_send_event(win, E_MOUSE, win_x(win), win_y(win), B_DOWN | B_MIDDLE, 0);
			pm_unlock();
			SetCapture(hwnd);
			break;
		case WM_BUTTON1UP:
#ifdef OS2
		case WM_BUTTON1MOTIONEND:
#endif
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			if (msg == WM_BUTTON1UP) win->lastpos = mouse_pos;
			if (win->button & (1 << B_LEFT)) pm_send_event(win, E_MOUSE, win_x(win), win_y(win), B_UP | B_LEFT, 0);
			win->button &= ~(1 << B_LEFT);
			pm_unlock();
			if (!win->button) ReleaseCapture();
			break;
		case WM_BUTTON2UP:
#ifdef OS2
		case WM_BUTTON2MOTIONEND:
#endif
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			if (msg == WM_BUTTON2UP) win->lastpos = mouse_pos;
			if (win->button & (1 << B_RIGHT)) pm_send_event(win, E_MOUSE, win_x(win), win_y(win), B_UP | B_RIGHT, 0);
			win->button &= ~(1 << B_RIGHT);
			pm_unlock();
			if (!win->button) ReleaseCapture();
			break;
		case WM_BUTTON3UP:
#ifdef OS2
		case WM_BUTTON3MOTIONEND:
#endif
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			if (msg == WM_BUTTON3UP) win->lastpos = mouse_pos;
			if (win->button & (1 << B_MIDDLE)) pm_send_event(win, E_MOUSE, win_x(win), win_y(win), B_UP | B_MIDDLE, 0);
			win->button &= ~(1 << B_MIDDLE);
			pm_unlock();
			if (!win->button) ReleaseCapture();
			break;
#ifdef WIN32
		case WM_XBUTTONDOWN:
		case WM_XBUTTONDBLCLK:
			if (HIWORD(mp1) == XBUTTON1)
				flags = B_FOURTH;
			else if (HIWORD(mp1) == XBUTTON2)
				flags = B_FIFTH;
			else break;
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			win->button |= 1 << flags;
			win->lastpos = mouse_pos;
			pm_send_event(win, E_MOUSE, win_x(win), win_y(win), B_DOWN | flags, 0);
			pm_unlock();
			SetCapture(hwnd);
			break;
		case WM_XBUTTONUP:
			if (HIWORD(mp1) == XBUTTON1)
				flags = B_FOURTH;
			else if (HIWORD(mp1) == XBUTTON2)
				flags = B_FIFTH;
			else break;
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			win->lastpos = mouse_pos;
			if (win->button & flags) pm_send_event(win, E_MOUSE, win_x(win), win_y(win), B_UP | flags, 0);
			win->button &= ~(1 << flags);
			pm_unlock();
			if (!win->button) ReleaseCapture();
			break;
#endif
		case WM_MOUSEMOVE:
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
#ifdef OS2
			if (win->button && WinQueryCapture(HWND_DESKTOP) != hwnd) {
				for (flags = B_LEFT; flags <= B_SIXTH; flags++)
					if (win->button & (1 << flags))
						pm_send_event(win, E_MOUSE, win_x(win), win_y(win), B_UP | flags, 0);
				win->button = 0;
			}
#endif
			if (win->lastpos == mouse_pos) { pm_unlock(); break; }
			win->lastpos = mouse_pos;
			pm_send_mouse_event(win, win_x(win), win_y(win),
				(win->button ? B_DRAG : B_MOVE) |
				(win->button & (1 << B_LEFT) ? B_LEFT :
				win->button & (1 << B_MIDDLE) ? B_MIDDLE :
				win->button & (1 << B_RIGHT) ? B_RIGHT :
				win->button & (1 << B_FOURTH) ? B_FOURTH :
				win->button & (1 << B_FIFTH) ? B_FIFTH :
				win->button & (1 << B_SIXTH) ? B_SIXTH :
				0));
			pm_unlock();
			break;
#ifdef WIN32
		case WM_CAPTURECHANGED:
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			if ((HWND)mp2 == win->hc) { pm_unlock(); break; }
			for (flags = B_LEFT; flags <= B_SIXTH; flags++)
				if (win->button & (1 << flags))
					pm_send_event(win, E_MOUSE, win_x(win), win_y(win), B_UP | flags, 0);
			win->button = 0;
			pm_unlock();
			break;
#endif
#ifdef OS2
		case WM_VSCROLL:
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			if ((unsigned long)mp2 == SB_LINEUP << 16 || (unsigned long)mp2 == SB_LINEDOWN << 16) pm_send_event(win, E_MOUSE, win_x(win), win_y(win), ((unsigned long)mp2 == SB_LINEUP << 16 ? B_WHEELUP1 : B_WHEELDOWN1) | B_MOVE, 0);
			pm_unlock();
			break;
		case WM_HSCROLL:
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			if ((unsigned long)mp2 == SB_LINELEFT << 16 || (unsigned long)mp2 == SB_LINERIGHT << 16) pm_send_event(win, E_MOUSE, win_x(win), win_y(win), ((unsigned long)mp2 == SB_LINELEFT << 16 ? B_WHEELLEFT1 : B_WHEELRIGHT1) | B_MOVE, 0);
			pm_unlock();
			break;
#endif
#ifdef WIN32
		case WM_MOUSEWHEEL:
			flags = HIWORD(mp1);
			if (!flags) break;
			pm_lock();
			if (!(win = pm_lookup_window(hwnd))) { pm_unlock(); break; }
			pm_send_event(win, E_MOUSE, win_x(win), win_y(win), flags > 0 && flags < 0x8000 ? B_WHEELUP : B_WHEELDOWN, 0);
			pm_unlock();
			break;
#endif
	}
#ifdef OS2
	return WinDefWindowProc(hwnd, msg, mp1, mp2);
#endif
#ifdef WIN32
	if (!unicode_supported)
		return DefWindowProcA(hwnd, msg, mp1, mp2);
	else
		return DefWindowProcW(hwnd, msg, mp1, mp2);
#endif
}

static int pm_thread_shutdown;

#define MSG_CREATE_WINDOW	(WM_USER + 0)
#define MSG_DELETE_WINDOW	(WM_USER + 1)
#define MSG_SET_WINDOW_TITLE	(WM_USER + 2)
#define MSG_SHUTDOWN_THREAD	(WM_USER + 3)

static void pm_user_msg(unsigned long msg, void *mp1, void *mp2)
{
	struct pm_window *win;
	switch (msg) {
		case MSG_CREATE_WINDOW:
			win = mp1;
#ifdef OS2
			win->h = WinCreateStdWindow(HWND_DESKTOP, 0, &pm_frame, pm_class_name, "Links", 0, 0, 0, &win->hc);
			if (win->h != NULLHANDLE) {
				if (icon != NULLHANDLE) WinSendMsg(win->h, WM_SETICON, (void *)icon, 0);
				if (!WinSetWindowPos(win->h, HWND_TOP, 0, 0, 0, 0, SWP_ACTIVATE | SWP_SHOW | SWP_ZORDER))
					error("WinSetWindowPos failed");
			}
#endif
#ifdef WIN32
			if (unicode_supported) {
				win->hc = CreateWindowExW(WS_EX_APPWINDOW | WS_EX_LEFT, (void *)(unsigned long)window_class_atom, L"Links", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, module_handle, NULL);
			} else {
				win->hc = CreateWindowExA(WS_EX_APPWINDOW | WS_EX_LEFT, (void *)(unsigned long)window_class_atom, "Links", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, module_handle, NULL);
			}
			if (win->hc != NULL) {
				if (unicode_supported) {
					if (icon_big != NULL) SendMessageW(win->hc, WM_SETICON, ICON_BIG, (LPARAM)icon_big);
					if (icon_small != NULL) SendMessageW(win->hc, WM_SETICON, ICON_SMALL, (LPARAM)icon_small);
				} else {
					if (icon_big != NULL) SendMessageA(win->hc, WM_SETICON, ICON_BIG, (LPARAM)icon_big);
					if (icon_small != NULL) SendMessageA(win->hc, WM_SETICON, ICON_SMALL, (LPARAM)icon_small);
				}
				ShowWindow(win->hc, SW_SHOW);
			}
#endif
			pm_lock();
			pm_event_signal();
			break;
		case MSG_DELETE_WINDOW:
			win = mp1;
#ifdef OS2
			if (!WinDestroyWindow(win->h))
				fatal_exit("WinDestroyWindow failed");
#endif
#ifdef WIN32
			if (!DestroyWindow(win->hc))
				fatal_exit("DestroyWindow failed");
#endif
			pm_lock();
			pm_event_signal();
			break;
		case MSG_SET_WINDOW_TITLE:
			win = mp1;
#ifdef OS2
			WinSetWindowText(win->h, mp2);
#endif
#ifdef WIN32
			if (unicode_supported && unicode_title_supported)
				SetWindowTextW(win->hc, mp2);
			else
				SetWindowTextA(win->hc, mp2);
#endif
			pm_lock();
			pm_event_signal();
			break;
		case MSG_SHUTDOWN_THREAD:
			pm_thread_shutdown = 1;
			break;
	}
}

static void pm_send_msg(int msg, void *param, void *param2)
{
#ifdef OS2
	while (!WinPostMsg(hwnd_hidden, msg, (MPARAM)param, (MPARAM)param2)) {
		sleep(1);
	}
#endif
#ifdef WIN32
	BOOL r;
	if (!GdiFlush())
		{/*error("GdiFlush failed")*/}
	retry:
	if (!unicode_supported)
		r = PostMessageA(hwnd_hidden, msg, (unsigned long)param, (unsigned long)param2);
	else
		r = PostMessageW(hwnd_hidden, msg, (unsigned long)param, (unsigned long)param2);
	if (!r) {
		DWORD err = GetLastError();
		if (err == ERROR_NOT_ENOUGH_QUOTA) {
			sleep(1);
			goto retry;
		}
		fatal_exit("PostMessage failed: %x", (unsigned)GetLastError());
	}
#endif
	pm_event_wait();
#ifdef WIN32
	if (msg == MSG_SHUTDOWN_THREAD) {
		if (pthread_join(pthread_handle, NULL))
			fatal_exit("pthread_join failed");
	}
#endif
}

static void pm_dispatcher(void *p)
{
#ifdef OS2
	QMSG msg;
	HWND hwnd_hidden_h;
#endif
#ifdef WIN32
	MSG msg;
	HCURSOR hcursor;
	WNDCLASSEXW class_w;
	WNDCLASSEXA class_a;
#endif
	pm_status = NULL;
#ifdef OS2
	/*DosSetPriority(PRTYS_THREAD, PRTYC_FOREGROUNDSERVER, 1, 0);*/
	DosSetPriority(PRTYS_THREAD, PRTYC_NOCHANGE, 1, 0);
	if ((hab_disp = WinInitialize(0)) == NULLHANDLE) {
		pm_status = cast_uchar "WinInitialize failed in pm thread.\n";
		goto os2_fail0;
	}
	if ((hmq = WinCreateMsgQueue(hab_disp, 0)) == NULLHANDLE) {
		ERRORID e = WinGetLastError(hab_disp);
		if ((e & 0xffff) == PMERR_NOT_IN_A_PM_SESSION) pm_status = cast_uchar "Not in a pmshell session.\n";
		else pm_status = cast_uchar "WinCreateMsgQueue failed in pm thread.\n";
		goto os2_fail1;
	}
	if ((pm_cp = WinQueryCp(hmq))) {
		unsigned char a[12];
		snprint(a, 12, pm_cp);
		if ((pm_cp = get_cp_index(a)) < 0 || pm_cp == utf8_table) pm_cp = 0;
	}
	/*{
		ULONG cp_list[100];
		int n, i;
		debug("WinQueryCp: %d", WinQueryCp(hmq));
		n = WinQueryCpList(hab_disp, 100, cp_list);
		debug("%d", n);
		for (i = 0; i < n; i++) fprintf(stderr, "%d, ", cp_list[i]);
	}*/
	if (WinRegisterClass(hab_disp, pm_class_name, pm_window_proc, CS_SIZEREDRAW, 0) == FALSE) {
		pm_status = cast_uchar "WinRegisterClass failed for.\n";
		goto os2_fail2;
	}
	if ((hwnd_hidden_h = WinCreateStdWindow(HWND_DESKTOP, 0, &pm_hidden_frame, pm_class_name, NULL, 0, 0, 0, &hwnd_hidden)) == NULLHANDLE) {
		pm_status = cast_uchar "Could not create hidden window.\n";
		goto os2_fail3;
	}
	if ((hps_hidden = WinGetPS(hwnd_hidden)) == NULLHANDLE) {
		pm_status = cast_uchar "Could not get hidden window ps.\n";
		goto os2_fail4;
	}
	GpiCreateLogColorTable(hps_hidden, 0, LCOLF_RGB, 0, 0, NULL);
#endif
#ifdef WIN32
	pm_cp = get_windows_cp(0);

	hcursor = LoadCursorA(0, (void *)IDC_ARROW);

	memset(&class_w, 0, sizeof class_w);
	class_w.cbSize = sizeof class_w;
	class_w.style = CS_HREDRAW | CS_VREDRAW;
	class_w.lpfnWndProc = pm_window_proc;
	class_w.hInstance = module_handle;
	class_w.hCursor = hcursor;
	class_w.lpszClassName = pm_class_name_l;
	window_class_atom = RegisterClassExW(&class_w);
	if (window_class_atom) {
		OSVERSIONINFO v;
		unicode_supported = 1;
		unicode_title_supported = 0;
		v.dwOSVersionInfoSize = sizeof v;
		if (is_winnt() && GetVersionEx(&v) && v.dwMajorVersion >= 5)
			unicode_title_supported = 1;
	} else {
		unicode_supported = 0;
		unicode_title_supported = 0;
		memset(&class_a, 0, sizeof class_a);
		class_a.cbSize = sizeof class_a;
		class_a.style = CS_HREDRAW | CS_VREDRAW;
		class_a.lpfnWndProc = pm_window_proc;
		class_a.hInstance = module_handle;
		class_a.hCursor = hcursor;
		class_a.lpszClassName = pm_class_name;
		window_class_atom = RegisterClassExA(&class_a);
	}
	if (!window_class_atom) {
		pm_status = cast_uchar "Unable to register window class.\n";
		goto win32_fail;
	}
	if (unicode_supported) {
		hwnd_hidden = CreateWindowExW(WS_EX_LEFT, (void *)(unsigned long)window_class_atom, L"Links", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, module_handle, NULL);
	} else {
		hwnd_hidden = CreateWindowExA(WS_EX_LEFT, (void *)(unsigned long)window_class_atom, "Links", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, module_handle, NULL);
	}
	if (!hwnd_hidden) {
		pm_status = cast_uchar "Could not create hidden window.\n";
		goto win32_fail;
	}
	if (!unicode_supported)
		PeekMessageA(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
	else
		PeekMessageW(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
#endif
	pm_event_signal();
	while (!pm_thread_shutdown) {
#ifdef OS2
		WinGetMsg(hab_disp, &msg, 0L, 0, 0);
		WinDispatchMsg(hab_disp, &msg);
#endif
#ifdef WIN32
		if (!unicode_supported)
			GetMessageA(&msg, NULL, 0, 0);
		else
			GetMessageW(&msg, NULL, 0, 0);
		TranslateMessage(&msg);
		if (!unicode_supported)
			DispatchMessageA(&msg);
		else
			DispatchMessageW(&msg);
#endif
	}

#ifdef OS2
		if (!WinReleasePS(hps_hidden))
			error("WinReleasePS failed");
	os2_fail4:
		if (!WinDestroyWindow(hwnd_hidden_h))
			error("WinDestroyWindow failed");
	os2_fail3:
	os2_fail2:
		if (!WinDestroyMsgQueue(hmq))
			error("WinDestroyMsgQueue failed");
	os2_fail1:
		if (!WinTerminate(hab_disp))
			error("WinTerminate failed");
		if (!WinTerminate(hab_disp))
			error("WinTerminate failed");
	os2_fail0:
#endif
#ifdef WIN32
	if (!DestroyWindow(hwnd_hidden))
		error("DestroyWindow failed");
	win32_fail:
#endif
	pm_event_signal();
	return;
}

#ifdef WIN32
static void *pm_dispatcher_win32(void *p)
{
	pm_dispatcher(NULL);
	return NULL;
}
#endif

static void pm_pipe_error(void *p)
{
	error("exception on pm pipe");
	set_handlers(pm_pipe[0], NULL, NULL, NULL, NULL);
}

static void pm_handler(void *p)
{
	unsigned char c;
	struct pm_window *win = NULL;
	struct pm_event *ev = NULL;
	pm_lock();
	if (!list_empty(pm_event_windows)) {
		win = pm_event_windows.prev;
		if (!list_empty(win->queue)) {
			ev = win->queue.prev;
			del_from_list(ev);
		}
		if (list_empty(win->queue)) {
			del_from_list(win);
			win->in = 0;
		}
	}
	if (list_empty(pm_event_windows)) {
		int rd;
		EINTRLOOP(rd, read(pm_pipe[0], &c, 1));
		if (rd != 1) pm_pipe_error(NULL);
	}
	pm_unlock();
	if (!ev) return;
	switch (ev->type) {
		struct rect r;
		case E_KEY:
			if (win->dev->keyboard_handler)
				win->dev->keyboard_handler(win->dev, ev->x1, ev->y1);
			break;
		case E_MOUSE:
			if (win->dev->mouse_handler)
				win->dev->mouse_handler(win->dev, ev->x1, ev->y1, ev->x2);
			break;
		case E_REDRAW:
			if (win->dev->redraw_handler) {
				r.x1 = ev->x1; r.y1 = ev->y1;
				r.x2 = ev->x2; r.y2 = ev->y2;
				win->dev->redraw_handler(win->dev, &r);
			}
			break;
		case E_RESIZE:
			win->dev->size.x2 = ev->x2;
			win->dev->size.y2 = ev->y2;
			if (win->dev->resize_handler) {
				win->dev->resize_handler(win->dev);
			}
	}
	free(ev);
}

#ifdef OS2

#define PM_FLUSH()	do { } while (0)
#define PM_UNFLUSH()	do { } while (0)

#endif

#ifdef WIN32

static unsigned char flush_in_progress = 0;

static void pm_do_flush(void *ignore)
{
	flush_in_progress = 0;
	if (!GdiFlush())
		{/*error("GdiFlush failed")*/}
}

static inline void PM_FLUSH(void)
{
	if (!flush_in_progress) {
		register_bottom_half(pm_do_flush, NULL);
		flush_in_progress = 1;
	}
}

#define PM_UNFLUSH()	unregister_bottom_half(pm_do_flush, NULL)

#endif

static int pm_bitmap_count = 0;

static unsigned char *pm_get_driver_param(void)
{
	return NULL;
}

#ifdef PM_SPAWN_SUBPROC

static int pm_sin, pm_sout, pm_serr, pm_ip[2], pm_op[2], pm_ep[2];
static int pm_cons_ok = 0;

static void pm_setup_console(void)
{
	int rs;
	if (pm_cons_ok) goto fail9;
	EINTRLOOP(pm_sin, dup(0));
	if (pm_sin < 0) goto fail;
	EINTRLOOP(pm_sout, dup(1));
	if (pm_sout < 0) goto fail1;
	EINTRLOOP(pm_serr, dup(2));
	if (pm_serr < 0) goto fail2;
	if (c_pipe(pm_ip)) goto fail3;
	if (c_pipe(pm_op)) goto fail4;
	if (c_pipe(pm_ep)) goto fail5;
	EINTRLOOP(rs, dup2(pm_ip[0], 0));
	if (rs != 0) goto fail6;
	EINTRLOOP(rs, dup2(pm_op[1], 1));
	if (rs != 1) goto fail7;
	EINTRLOOP(rs, dup2(pm_ep[1], 2));
	if (rs != 2) goto fail8;
	EINTRLOOP(rs, close(pm_ip[0]));
	EINTRLOOP(rs, close(pm_op[1]));
	EINTRLOOP(rs, close(pm_ep[1]));
	pm_cons_ok = 1;
	return;
fail9:
	EINTRLOOP(rs, dup2(pm_serr, 2));
fail8:
	EINTRLOOP(rs, dup2(pm_sout, 1));
fail7:
	EINTRLOOP(rs, dup2(pm_sin, 0));
fail6:
	EINTRLOOP(rs, close(pm_ep[0]));
	EINTRLOOP(rs, close(pm_ep[1]));
fail5:
	EINTRLOOP(rs, close(pm_op[0]));
	EINTRLOOP(rs, close(pm_op[1]));
fail4:
	EINTRLOOP(rs, close(pm_ip[0]));
	EINTRLOOP(rs, close(pm_ip[1]));
fail3:
	EINTRLOOP(rs, close(pm_serr));
fail2:
	EINTRLOOP(rs, close(pm_sout));
fail1:
	EINTRLOOP(rs, close(pm_sin));
fail:	pm_cons_ok = 0;
}

static int pm_do_console_step(int slp)
{
#define CONS_BUF 20
	int did_something = 0;
	unsigned char buffer[CONS_BUF];
	fd_set s;
	struct timeval tv = { 0, 0 };
	int rs;
	int m = pm_op[0] > pm_ep[0] ? pm_op[0] : pm_ep[0];
	int r, w;
	if (pm_sin > m) m = pm_sin;
	m++;
	if (!pm_cons_ok) return -1;
	FD_ZERO(&s);
	/*FD_SET(pm_sin, &s);*/
	if (m > (int)FD_SETSIZE) {
		fatal_exit("too big handle %d", m - 1);
	}
	FD_SET(pm_op[0], &s);
	FD_SET(pm_ep[0], &s);
	EINTRLOOP(rs, select(m, &s, NULL, NULL, slp ? NULL : &tv));
	if (rs <= 0) return -1;
#define SEL_CHK(ih, oh)							\
	if (FD_ISSET(ih, &s)) {						\
		EINTRLOOP(r, read(ih, buffer, CONS_BUF));		\
		if (r <= 0) return -1;					\
		do {							\
			if ((w = hard_write(oh, buffer, r)) <= 0) return -1;\
			did_something = 1;				\
			r -= w;						\
		} while (r > 0);					\
	}

	block_signals(0, 0);
	/*SEL_CHK(pm_sin, pm_ip[1]);*/
	SEL_CHK(pm_op[0], pm_sout);
	SEL_CHK(pm_ep[0], pm_serr);
	unblock_signals();
	return did_something;
#undef SEL_CHK
}

static void pm_do_console(void)
{
	while (pm_do_console_step(1) >= 0)
		;
}

static void pm_sigcld(void *p)
{
	int st;
	pid_t w;
	EINTRLOOP(w, wait(&st));
	while (pm_do_console_step(0) > 0)
		;
	if (w > 0 && WIFEXITED(st)) exit(WEXITSTATUS(st));
	else exit(RET_FATAL);
}

static unsigned char *pm_spawn_subproc(void)
{
	unsigned char **arg;
	int rs;
	pid_t pm_child_pid;

	if ((unsigned)g_argc > MAXINT / sizeof(unsigned char *) - 1) overalloc();
	arg = mem_alloc((g_argc + 1) * sizeof(unsigned char *));
	memcpy(arg, g_argv, g_argc * sizeof(unsigned char *));
	arg[g_argc] = NULL;
	pm_child_pid = -1;
	install_signal_handler(SIGCHLD, pm_sigcld, NULL, 1);
	pm_setup_console();
	pm_child_pid = spawnvp(P_PM, path_to_exe, (char **)arg);
	mem_free(arg);
	if (pm_child_pid < 0) {
		set_sigcld();
		pm_setup_console();
		return cast_uchar "Unable to spawn subprocess.\n";
	}
	pm_do_console();
	pm_setup_console();
	while (1)
		EINTRLOOP(rs, select(1, NULL, NULL, NULL, NULL));

	return cast_uchar "Not reached.\n";
}

#endif

static unsigned char *pm_init_driver(unsigned char *param, unsigned char *display)
{
	unsigned char *s;
	int rs;

#ifdef OS2
	if (os2_pib) {
		if (os2_pib->pib_ultype != 3 &&
		    os2_pib->pib_ultype != 4) {
#ifdef PM_SPAWN_SUBPROC
			s = pm_spawn_subproc();
			goto r0;
#else
			os2_pib->pib_ultype = 3;
#endif
		}
	}

	if ((hab = WinInitialize(0)) == 0) {
		s = cast_uchar "WinInitialize failed.\n";
		goto r0;
	}
#endif
#ifdef WIN32
	module_handle = GetModuleHandleA(NULL);
	if (!module_handle) {
		s = cast_uchar "Unable to get module handle.\n";
		goto r0;
	}
#endif
	if (pm_event_init()) {
		s = cast_uchar "Could not create event semaphore.\n";
		goto r1;
	}
	if (c_pipe(pm_pipe)) {
		s = cast_uchar "Could not create pipe.\n";
		goto r2;
	}
	EINTRLOOP(rs, fcntl(pm_pipe[1], F_SETFL, O_NONBLOCK));
	memset(pm_windows, 0, sizeof(struct pm_window *) * WIN_HASH);
	if (pm_lock_init()) {
		s = cast_uchar "Could not create mutext.\n";
		goto r3;
	}
	pm_thread_shutdown = 0;
#ifdef OS2
	if (_beginthread(pm_dispatcher, NULL, 65536, NULL) == -1) {
		s = cast_uchar "Could not start thread.\n";
		goto r4;
	}
#endif
#ifdef WIN32
	if (pthread_create(&pthread_handle, NULL, pm_dispatcher_win32, NULL)) {
		s = cast_uchar "Could not start thread.\n";
		goto r4;
	}
#endif
	pm_event_wait();
	if (pm_status) {
		s = pm_status;
		goto r4;
	}
#ifdef OS2
	pmshell_driver.depth = 0xc3;

	pm_bitmapinfo = mem_calloc(sizeof(BITMAPINFOHEADER));
	pm_bitmapinfo->cbFix = sizeof(BITMAPINFOHEADER);
	pm_bitmapinfo->cPlanes = 1;
	pm_bitmapinfo->cBitCount = 24;

	{
		SIZEL sizl = { 0, 0 };
		PSZ data[4] = { "DISPLAY", NULL, NULL, NULL };
		hdc_mem = DevOpenDC(hab, OD_MEMORY, "*", 4L, (PDEVOPENDATA)data, NULLHANDLE);
		if (!hdc_mem) {
			s = cast_uchar "Unable to create memory device context.\n";
			goto r5;
		}
		hps_mem = GpiCreatePS(hab, hdc_mem, &sizl, GPIA_ASSOC | PU_PELS | GPIT_MICRO);
		if (!hps_mem) {
			s = cast_uchar "Unable to create memory presentation space.\n";
			goto r6;
		}
	}

	icon = WinLoadPointer(HWND_DESKTOP, 0, 1);
#endif
#ifdef WIN32
	{
		int bpp;

		screen_dc = GetDC(NULL);
		if (!screen_dc) {
			s = cast_uchar "Unable to get screen device context.\n";
			goto r5;
		}
		bpp = GetDeviceCaps(screen_dc, BITSPIXEL);

		if (bpp < 24)
			pmshell_driver.depth = 0x7a;
		else
			pmshell_driver.depth = 0xc3;

		pm_bitmapinfo = mem_calloc(sizeof(BITMAPINFO));
		pm_bitmapinfo->bmiHeader.biSize = sizeof(pm_bitmapinfo->bmiHeader);
		pm_bitmapinfo->bmiHeader.biPlanes = 1;
		pm_bitmapinfo->bmiHeader.biBitCount = bpp < 24 ? 16 : 24;
		pm_bitmapinfo->bmiHeader.biCompression = BI_RGB;
	}

	icon_big = LoadImage(module_handle, MAKEINTRESOURCE(1), IMAGE_ICON, 32, 32, LR_DEFAULTCOLOR);
	icon_small = LoadImage(module_handle, MAKEINTRESOURCE(1), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
#endif
	icon_set = 0;
	set_handlers(pm_pipe[0], pm_handler, NULL, pm_pipe_error, NULL);

	return NULL;

#ifdef OS2
	r6:
	if (DevCloseDC(hdc_mem) == DEV_ERROR)
		error("DevCloseDC failed");
#endif
	r5:
	mem_free(pm_bitmapinfo);
	pm_send_msg(MSG_SHUTDOWN_THREAD, NULL, NULL);
	r4:
	pm_lock_close();
	r3:
	EINTRLOOP(rs, close(pm_pipe[0]));
	EINTRLOOP(rs, close(pm_pipe[1]));
	r2:
	pm_event_close();
	r1:
	PM_UNFLUSH();
#ifdef OS2
	if (!WinTerminate(hab))
		error("WinTerminate failed");
#endif
	r0:
	return stracpy(s);
}

static void pm_shutdown_driver(void)
{
	int rs;
	pm_send_msg(MSG_SHUTDOWN_THREAD, NULL, NULL);
#ifdef OS2
	if (icon != NULLHANDLE)
		if (!WinDestroyPointer(icon))
			error("WinDestroyPointer failed");
	if (!GpiDestroyPS(hps_mem))
		error("GpiDestroyPS failed");
	if (DevCloseDC(hdc_mem) == DEV_ERROR)
		error("DevCloseDC failed");
#endif
#ifdef WIN32
	if (icon_small != NULL)
		if (!DestroyIcon(icon_small))
			error("DestroIcon failed");
	if (icon_big != NULL)
		if (!DestroyIcon(icon_big))
			error("DestroIcon failed");
	if (!ReleaseDC(NULL, screen_dc))
		error("ReleaseDC failed");
#endif
	mem_free(pm_bitmapinfo);
	pm_lock_close();
	set_handlers(pm_pipe[0], NULL, NULL, NULL, NULL);
	EINTRLOOP(rs, close(pm_pipe[0]));
	EINTRLOOP(rs, close(pm_pipe[1]));
	pm_event_close();
	PM_UNFLUSH();
#ifdef OS2
	if (!WinTerminate(hab))
		error("WinTerminate failed");
#endif
	if (pm_bitmap_count) internal("pm_shutdown_driver: %d bitmaps leaked", pm_bitmap_count);
}

#ifdef OS2

static HPOINTER pmshell_create_icon(void)
{
	unsigned char *icon_data, *icon_data_2;
	int icon_w, icon_h, icon_skip;
	int size;
	int i, j;
	HBITMAP hbm;
	HPOINTER hicon;
	const int border = 4;

	get_links_icon(&icon_data, &icon_w, &icon_h, &icon_skip, 4);
	size = icon_h * icon_skip;
	icon_data_2 = mem_alloc(size * 2);
	for (i = 0; i < icon_h; i++)
		memcpy(icon_data_2 + i * icon_skip, icon_data + (icon_h - 1 - i) * icon_skip, icon_skip);
	free(icon_data);
	for (i = 0; i < size; i++) {
		icon_data_2[i + size] = 0;
	}
#define set_trans(x, y) memset(icon_data_2 + ((y) + icon_h) * icon_skip + (x) * (pmshell_driver.depth & 7), 0xff, pmshell_driver.depth & 7);
	for (j = 0; j < border; j++) for (i = 0; i < icon_w; i++) set_trans(i, j);
	for (j = icon_h - border; j < icon_h; j++) for (i = 0; i < icon_w; i++) set_trans(i, j);
	for (j = 0; j < icon_h; j++) for (i = 0; i < border; i++) set_trans(i, j);
	for (j = 0; j < icon_h; j++) for (i = icon_w - border; i < icon_w; i++) set_trans(i, j);
#undef set_trans
	pm_bitmapinfo->cx = icon_w;
	pm_bitmapinfo->cy = icon_h * 2;
	hbm = GpiCreateBitmap(hps_hidden, (PBITMAPINFOHEADER2)pm_bitmapinfo, CBM_INIT, icon_data_2, (PBITMAPINFO2)pm_bitmapinfo);
	mem_free(icon_data_2);
	if (hbm == GPI_ERROR)
		return NULLHANDLE;
	hicon = WinCreatePointer(HWND_DESKTOP, hbm, FALSE, 0, 0);
	if (!hicon)
		error("WinCreatePointer failed");
	if (!GpiDeleteBitmap(hbm))
		error("GpiDeleteBitmap failed");
	return hicon;
}

#endif

#ifdef WIN32

static HICON win32_create_icon(int x, int y)
{
	unsigned char *icon_data, *zero_data;
	int icon_w, icon_h, icon_skip;
	int left, right, top, bottom;
	int i, j;
	HBITMAP hbm_icon;
	HBITMAP hbm_mask;
	ICONINFO ic;
	HICON hicon = NULL;
	HDC memory_dc;
	HGDIOBJ prev_obj;

	get_links_icon(&icon_data, &icon_w, &icon_h, &icon_skip, 4);
	zero_data = mem_calloc(icon_h * icon_skip);

	memory_dc = CreateCompatibleDC(NULL);
	if (!memory_dc) {
		error("CreateCompatibleDC failed");
		goto ret1;
	}

	hbm_icon = CreateCompatibleBitmap(screen_dc, x, y);
	if (!hbm_icon) {
		error("CreateBitmap failed");
		goto ret2;
	}
	prev_obj = SelectObject(memory_dc, hbm_icon);
	if (!prev_obj) {
		error("SelectObject failed");
		goto ret3;
	}
	pm_bitmapinfo->bmiHeader.biWidth = icon_w;
	pm_bitmapinfo->bmiHeader.biHeight = -icon_h;
	if (!StretchDIBits(memory_dc, 0, 0, x, y, 0, 0, icon_w, icon_h, icon_data, pm_bitmapinfo, DIB_RGB_COLORS, SRCCOPY)) {
		error("StretchDIBits failed");
		prev_obj = SelectObject(memory_dc, prev_obj);
		if (!prev_obj) {
			error("SelectObject failed");
			goto ret3;
		}
		goto ret3;
	}
	prev_obj = SelectObject(memory_dc, prev_obj);
	if (!prev_obj) {
		error("SelectObject failed");
		goto ret3;
	}
	hbm_mask = CreateBitmap(x, y, 1, 1, zero_data);
	if (!hbm_mask) {
		error("CreateCompatibleBitmap failed");
		goto ret3;
	}
	prev_obj = SelectObject(memory_dc, hbm_mask);
	if (!prev_obj) {
		error("SelectObject failed");
		goto ret4;
	}
	if (x == 16 && y == 16) {
		top = bottom = left = right = 1;
		if (is_winnt())
			top = 2;
	} else if (x == 32 && y == 32) {
		top = bottom = left = right = 3;
	} else {
		top = bottom = left = right = 0;
	}
	for (j = 0; j < top; j++) for (i = 0; i < x; i++) SetPixel(memory_dc, i, j, 0xffffff);
	for (j = y - bottom; j < y; j++) for (i = 0; i < x; i++) SetPixel(memory_dc, i, j, 0xffffff);
	for (j = 0; j < y; j++) for (i = 0; i < left; i++) SetPixel(memory_dc, i, j, 0xffffff);
	for (j = 0; j < y; j++) for (i = x - left; i < x; i++) SetPixel(memory_dc, i, j, 0xffffff);
	prev_obj = SelectObject(memory_dc, prev_obj);
	if (!prev_obj) {
		error("SelectObject failed");
		goto ret4;
	}
	memset(&ic, 0, sizeof ic);
	ic.fIcon = TRUE;
	ic.hbmMask = hbm_mask;
	ic.hbmColor = hbm_icon;
	hicon = CreateIconIndirect(&ic);
	if (!hicon)
		error("CreateIconIndirect failed");

ret4:
	if (!DeleteBitmap(hbm_mask))
		error("DeleteBitmap failed");
ret3:
	if (!DeleteBitmap(hbm_icon))
		error("DeleteBitmap failed");
ret2:
	if (!DeleteDC(memory_dc))
		error("DeleteDC failed");
ret1:
	free(icon_data);
	mem_free(zero_data);
	return hicon;
	return NULL;
}

#endif

static struct graphics_device *pm_init_device(void)
{
	RECTL wr;
	struct graphics_device *dev;
	struct pm_window *win;

	if (!icon_set) {
#ifdef OS2
		if (icon == NULLHANDLE) icon = pmshell_create_icon();
#endif
#ifdef WIN32
		if (!icon_big) icon_big = win32_create_icon(32, 32);
		if (!icon_small) icon_small = win32_create_icon(16, 16);
#endif
	}
	icon_set = 1;

	win = mem_alloc(sizeof(struct pm_window));
	win->lastpos = -1L;
	win->button = 0;
	init_list(win->queue);
	win->in = 0;
	win->minimized = 0;
	pm_send_msg(MSG_CREATE_WINDOW, win, NULL);
#ifdef OS2
	if (win->h == NULLHANDLE) {
		goto r1;
	}
	if ((win->ps = WinGetPS(win->hc)) == NULLHANDLE) {
		goto r2;
	}
#endif
#ifdef WIN32
	win->pen_cache = NULL;
	win->pen_cache_color = -1;
	win->brush_cache = NULL;
	win->brush_cache_color = -1;
	if (win->hc == NULL) {
		goto r1;
	}
	if ((win->dc = GetDC(win->hc)) == NULL) {
		goto r2;
	}
#endif
	dev = mem_calloc(sizeof(struct graphics_device));
	dev->driver_data = win;
	win->dev = dev;
#ifdef OS2
	if (!WinQueryWindowRect(win->hc, &wr)) {
		memset(&wr, 0, sizeof wr);
	}
#endif
#ifdef WIN32
	if (!GetClientRect(win->hc, &wr)) {
		memset(&wr, 0, sizeof wr);
	}
	wr.yTop = wr.yBottom;
#endif
	win->x = dev->size.x2 = wr.xRight;
	win->y = dev->size.y2 = wr.yTop;
	dev->clip.x1 = dev->clip.y1 = 0;
	dev->clip.x2 = dev->size.x2;
	dev->clip.y2 = dev->size.y2;
#ifdef OS2
	GpiCreateLogColorTable(win->ps, 0, LCOLF_RGB, 0, 0, NULL);
#endif
	pm_hash_window(win);
	pm_unlock();
	return dev;

	r2:	pm_unlock();
		pm_send_msg(MSG_DELETE_WINDOW, win, NULL);
	r1:	if (win->in) del_from_list(win);
		pm_unlock();
		mem_free(win);
	return NULL;
}

static void pm_shutdown_device(struct graphics_device *dev)
{
	struct pm_window *win = pm_win(dev);
#ifdef OS2
	if (!WinReleasePS(win->ps))
		error("WinReleasePS failed");
#endif
#ifdef WIN32
	if (!GdiFlush())
		{/*error("GdiFlush failed")*/}
	if (!ReleaseDC(win->hc, win->dc))
		error("ReleaseDC failed");
#endif
	pm_send_msg(MSG_DELETE_WINDOW, win, NULL);
#ifdef WIN32
	if (win->pen_cache)
		if (!DeleteObject(win->pen_cache))
			error("DeleteObject failed for pen cache");
	if (win->brush_cache)
		if (!DeleteObject(win->brush_cache))
			error("DeleteObject failed for brush cache");
#endif
	pm_unhash_window(win);
	if (win->in) del_from_list(win);
	pm_unlock();
	while (!list_empty(win->queue)) {
		struct pm_event *ev = win->queue.next;
		del_from_list(ev);
		free(ev);
	}
	mem_free(win);
	mem_free(dev);
}

#define MAX_TITLE_SIZE	512

static void pm_set_window_title(struct graphics_device *dev, unsigned char *title)
{
	unsigned char *text;
#if defined(WIN32)
	if (unicode_supported && unicode_title_supported) {
		int l = 0;
		text = init_str();
		while (*title && l < MAX_TITLE_SIZE * 2) {
			unsigned u;
			GET_UTF_8(title, u);
			if (u > 0 && u <= 0xffff) {
				add_chr_to_str(&text, &l, u & 0xff);
				add_chr_to_str(&text, &l, u >> 8);
			}
		}
		add_chr_to_str(&text, &l, 0);
	} else
#endif
	{
		struct conv_table *ct = get_translation_table(utf8_table, pm_cp);
		text = convert_string(ct, title, strlen(cast_const_char title), NULL);
		clr_white(text);
		if (strlen(cast_const_char text) > MAX_TITLE_SIZE) text[MAX_TITLE_SIZE] = 0;
	}

	pm_send_msg(MSG_SET_WINDOW_TITLE, pm_win(dev), text);
	pm_unlock();
	/*SendMessage(pm_win(dev)->hc, WM_SETTEXT, NULL, text);*/
	mem_free(text);
}

static int pm_get_empty_bitmap(struct bitmap *bmp)
{
	debug_call(("get_empty_bitmap (%dx%d)\n", bmp->x, bmp->y));
	if ((unsigned)bmp->x > (unsigned)MAXINT / (pmshell_driver.depth & 7) - 4) {
		over:
		bmp->data = NULL;
		bmp->flags = NULL;
		return -1;
	}
	bmp->skip = (bmp->x * (pmshell_driver.depth & 7) + 3) & ~3;
	if (bmp->skip && (unsigned)bmp->skip * (unsigned)bmp->y / (unsigned)bmp->skip != (unsigned)bmp->y) goto over;
	if ((unsigned)bmp->skip * (unsigned)bmp->y > MAXINT) goto over;
	bmp->data = mem_alloc_mayfail(bmp->skip * bmp->y);
	if (!bmp->data) goto over;
	bmp->data = (unsigned char *)bmp->data + bmp->skip * (bmp->y - 1);
	bmp->skip = -bmp->skip;
	debug_call(("done\n"));
	return 0;
}

static void pm_register_bitmap(struct bitmap *bmp)
{
#ifdef OS2
	HBITMAP hbm;
	unsigned char *pointer;
#endif
	debug_call(("register_bitmap (%dx%d)\n", bmp->x, bmp->y));
	pm_bitmap_count++;
#ifdef OS2
	if (!bmp->data) {
		bmp->flags = (void *)GPI_ERROR;
		return;
	}
	pointer = (unsigned char *)bmp->data + bmp->skip * (bmp->y - 1);
	pm_bitmapinfo->cx = bmp->x;
	pm_bitmapinfo->cy = bmp->y;
again:
	hbm = GpiCreateBitmap(hps_hidden, (PBITMAPINFOHEADER2)pm_bitmapinfo, CBM_INIT, pointer, (PBITMAPINFO2)pm_bitmapinfo);
	if (hbm == GPI_ERROR) {
		if (out_of_memory(MF_GPI, NULL, 0))
			goto again;
	}
	mem_free(pointer);
	bmp->flags = (void *)hbm;
	debug_call(("done\n"));
#endif
}

static void *pm_prepare_strip(struct bitmap *bmp, int top, int lines)
{
#ifdef OS2
	if (bmp->flags == (void *)GPI_ERROR) {
		over:
		bmp->data = NULL;
		return NULL;
	}
	if (-bmp->skip && (unsigned)-bmp->skip * (unsigned)lines / (unsigned)-bmp->skip != (unsigned)lines) goto over;
	if ((unsigned)-bmp->skip * (unsigned)lines > MAXINT) goto over;
	bmp->data = mem_alloc(-bmp->skip * lines);
	if (!bmp->data) goto over;
	return (unsigned char *)bmp->data - bmp->skip * (lines - 1);
#endif
#ifdef WIN32
	return ((unsigned char *)bmp->data) + bmp->skip * top;
#endif
}

static void pm_commit_strip(struct bitmap *bmp, int top, int lines)
{
#ifdef OS2
	LONG r;
	HBITMAP old;
	HBITMAP new = (HBITMAP)bmp->flags;
	if (new == GPI_ERROR || !bmp->data)
		return;
	old = GpiSetBitmap(hps_mem, new);
	if (old == HBM_ERROR)
		goto ret;
	pm_bitmapinfo->cx = bmp->x;
	pm_bitmapinfo->cy = bmp->y;
again:
	r = GpiSetBitmapBits(hps_mem, bmp->y - top - lines, lines, bmp->data, (PBITMAPINFO2)pm_bitmapinfo);
	if (r == GPI_ALTERROR) {
		if (out_of_memory(MF_GPI, NULL, 0))
			goto again;
	}
	GpiSetBitmap(hps_mem, old);
	ret:
	mem_free(bmp->data);
#endif
}

static void pm_unregister_bitmap(struct bitmap *bmp)
{
	debug_call(("unregister_bitmap (%dx%d)\n", bmp->x, bmp->y));
	pm_bitmap_count--;
#ifdef OS2
	if ((HBITMAP)bmp->flags != GPI_ERROR)
		if (!GpiDeleteBitmap((HBITMAP)bmp->flags))
			error("GpiDeleteBitmap failed");
#endif
#ifdef WIN32
	mem_free((unsigned char *)bmp->data + bmp->skip * (bmp->y - 1));
#endif
	debug_call(("done\n"));
}

static void pm_draw_bitmap(struct graphics_device *dev, struct bitmap *bmp, int x, int y)
{
	POINTL p;
	RECTL r;
	debug_call(("draw_bitmap (%dx%d -> %x,%x)\n", bmp->x, bmp->y, x, y));
#ifdef OS2
	if ((HBITMAP)bmp->flags == GPI_ERROR)
		return;
#endif
	r.xLeft = x < dev->clip.x1 ? dev->clip.x1 - x : 0;
	r.xRight = x + bmp->x > dev->clip.x2 ? dev->clip.x2 - x : bmp->x;
	r.yTop = bmp->y - (y < dev->clip.y1 ? dev->clip.y1 - y : 0);
	r.yBottom = y + bmp->y > dev->clip.y2 ? bmp->y - dev->clip.y2 + y : 0;
	if (r.xLeft >= r.xRight || r.yTop <= r.yBottom)
		return;
	p.x = x + r.xLeft;
	p.y = pm_win(dev)->y - y - bmp->y + r.yBottom;
#ifdef OS2
	WinDrawBitmap(pm_win(dev)->ps, (HBITMAP)bmp->flags, &r, &p, 0, 1, DBM_NORMAL);
#endif
#ifdef WIN32
	pm_bitmapinfo->bmiHeader.biWidth = bmp->x;
	pm_bitmapinfo->bmiHeader.biHeight = r.yTop - r.yBottom;
	SetDIBitsToDevice(pm_win(dev)->dc, p.x, pm_win(dev)->y - p.y - (r.yTop - r.yBottom), r.xRight - r.xLeft, r.yTop - r.yBottom, r.xLeft, 0, 0, r.yTop - r.yBottom, (unsigned char *)bmp->data + bmp->skip * (bmp->y - 1 - r.yBottom), pm_bitmapinfo, DIB_RGB_COLORS);
#endif
	PM_FLUSH();
	debug_call(("done\n"));
}

static long pm_get_color(int rgb)
{
#ifdef OS2
	return rgb & 0xffffff;
#endif
#ifdef WIN32
	COLORREF c, d;
	c = ((rgb & 0xff) << 16) | (rgb & 0xff00) | ((rgb & 0xff0000) >> 16);
	d = GetNearestColor(screen_dc, c);
	if (d == CLR_INVALID) return c;
	return d;
#endif
}

#ifdef WIN32

static int win32_select_brush(struct pm_window *win, int color)
{
	HBRUSH hbrush;
	if (color == win->brush_cache_color)
		return 0;
	hbrush = CreateSolidBrush(color);
	if (!hbrush) {
		error("CreateSolidBrush failed");
		return -1;
	}
	if (win->brush_cache != NULL)
		if (!DeleteObject(win->brush_cache))
			error("DeleteObject failed for previous brush");
	win->brush_cache = hbrush;
	win->brush_cache_color = color;
	return 0;
}

static int win32_select_pen(struct pm_window *win, int color)
{
	HPEN hpen;
	HGDIOBJ orig;
	if (color == win->pen_cache_color)
		return 0;
	hpen = CreatePen(PS_SOLID, 0, color);
	if (!hpen) {
		error("CreatePen failed");
		return -1;
	}
	orig = SelectObject(win->dc, hpen);
	if (!orig) {
		error("SelectObject failed for pen");
		if (!DeleteObject(hpen))
			error("DeleteObject failed for pen");
		return -1;
	}
	if (!DeleteObject(orig))
		error("DeleteObject failed for previous pen");
	win->pen_cache = hpen;
	win->pen_cache_color = color;
	return 0;
}

#endif

static void pm_fill_area(struct graphics_device *dev, int x1, int y1, int x2, int y2, long color)
{
	RECTL r;
	debug_call(("fill_area (%d,%d)->(%d,%d)\n", x1, y1, x2, y2));
	if (x1 < dev->clip.x1) x1 = dev->clip.x1;
	if (x2 > dev->clip.x2) x2 = dev->clip.x2;
	if (y1 < dev->clip.y1) y1 = dev->clip.y1;
	if (y2 > dev->clip.y2) y2 = dev->clip.y2;
	if (x1 >= x2 || y1 >= y2) return;
	r.xLeft = x1;
	r.yBottom = y2;
	r.xRight = x2;
	r.yTop = y1;
#ifdef OS2
	r.yBottom = pm_win(dev)->y - r.yBottom;
	r.yTop = pm_win(dev)->y - r.yTop;
	WinFillRect(pm_win(dev)->ps, &r, color);
#endif
#ifdef WIN32
	if (win32_select_brush(pm_win(dev), color))
		return;
	if (!FillRect(pm_win(dev)->dc, &r, pm_win(dev)->brush_cache))
		error("FillRect failed");
#endif
	PM_FLUSH();
	debug_call(("done\n"));
}

static void pm_draw_hline(struct graphics_device *dev, int x1, int y, int x2, long color)
{
#ifdef OS2
	HPS ps = pm_win(dev)->ps;
	POINTL p;
#endif
	debug_call(("draw_hline (%d,%d)->(%d)\n", x1, y, x2));
	if (y < dev->clip.y1) return;
	if (y >= dev->clip.y2) return;
	if (x1 < dev->clip.x1) x1 = dev->clip.x1;
	if (x2 > dev->clip.x2) x2 = dev->clip.x2;
	if (x1 >= x2) return;
#ifdef OS2
	GpiSetColor(ps, color);
	p.x = x1;
	p.y = pm_win(dev)->y - y - 1;
	GpiMove(ps, &p);
	p.x = x2 - 1;
	GpiLine(ps, &p);
#endif
#ifdef WIN32
	if (win32_select_pen(pm_win(dev), color))
		return;
	if (!MoveToEx(pm_win(dev)->dc, x1, y, NULL)) {
		error("MoveToEx failed");
	} else if (!LineTo(pm_win(dev)->dc, x2, y)) {
		error("LineTo failed");
	}
#endif
	PM_FLUSH();
	debug_call(("done\n"));
}

static void pm_draw_vline(struct graphics_device *dev, int x, int y1, int y2, long color)
{
#ifdef OS2
	HPS ps = pm_win(dev)->ps;
	POINTL p;
#endif
	debug_call(("draw_vline (%d,%d)->(%d)\n", x, y1, y2));
	if (x < dev->clip.x1) return;
	if (x >= dev->clip.x2) return;
	if (y1 < dev->clip.y1) y1 = dev->clip.y1;
	if (y2 > dev->clip.y2) y2 = dev->clip.y2;
	if (y1 >= y2) return;
#ifdef OS2
	GpiSetColor(ps, color);
	p.x = x;
	p.y = pm_win(dev)->y - y1 - 1;
	GpiMove(ps, &p);
	p.y = pm_win(dev)->y - y2;
	GpiLine(ps, &p);
#endif
#ifdef WIN32
	if (win32_select_pen(pm_win(dev), color))
		return;
	if (!MoveToEx(pm_win(dev)->dc, x, y1, NULL)) {
		error("MoveToEx failed");
	} else if (!LineTo(pm_win(dev)->dc, x, y2)) {
		error("LineTo failed");
	}
#endif
	PM_FLUSH();
	debug_call(("done\n"));
}

static void pm_hscroll_redraws(struct pm_window *win, struct rect *r, int dir)
{
	struct pm_event *e;
	pm_cancel_event(win, E_REDRAW, &e);
	if (!e) return;
	if (dir > 0) {
		if (e->x2 > r->x1 && e->x2 < r->x2) {
			e->x2 += dir;
			if (e->x2 > r->x2) e->x2 = r->x2;
		}
	} else if (dir < 0) {
		if (e->x1 > r->x1 && e->x1 < r->x2) {
			e->x1 += dir;
			if (e->x1 < r->x1) e->x1 = r->x1;
		}
	}
}

static int pm_hscroll(struct graphics_device *dev, struct rect_set **ignore, int sc)
{
	RECTL r;

	debug_call(("hscroll (%d)\n", sc));
	ignore = NULL;
	r.xLeft = dev->clip.x1;
	r.yBottom = dev->clip.y2;
	r.xRight = dev->clip.x2;
	r.yTop = dev->clip.y1;
	pm_lock();
#ifdef OS2
	r.yBottom = pm_win(dev)->y - r.yBottom;
	r.yTop = pm_win(dev)->y - r.yTop;
	WinScrollWindow(pm_win(dev)->hc, sc, 0, &r, &r, NULLHANDLE, NULL, SW_INVALIDATERGN);
#endif
#ifdef WIN32
	if (ScrollWindowEx(pm_win(dev)->hc, sc, 0, &r, &r, NULL, NULL, SW_INVALIDATE) == ERROR)
		error("ScrollWindowEx failed");
#endif
	pm_hscroll_redraws(pm_win(dev), &dev->clip, sc);
	pm_unlock();
	PM_FLUSH();
	debug_call(("done\n"));
	return 0;
}

static void pm_vscroll_redraws(struct pm_window *win, struct rect *r, int dir)
{
	struct pm_event *e;
	pm_cancel_event(win, E_REDRAW, &e);
	if (!e) return;
	if (dir > 0) {
		if (e->y2 > r->y1 && e->y2 < r->y2) {
			e->y2 += dir;
			if (e->y2 > r->y2) e->y2 = r->y2;
		}
	} else if (dir < 0) {
		if (e->y1 > r->y1 && e->y1 < r->y2) {
			e->y1 += dir;
			if (e->y1 < r->y1) e->y1 = r->y1;
		}
	}
}

static int pm_vscroll(struct graphics_device *dev, struct rect_set **ignore, int sc)
{
	RECTL r;

	debug_call(("vscroll (%d)\n", sc));
	ignore = NULL;
	r.xLeft = dev->clip.x1;
	r.yBottom = dev->clip.y2;
	r.xRight = dev->clip.x2;
	r.yTop = dev->clip.y1;
	pm_lock();
#ifdef OS2
	r.yBottom = pm_win(dev)->y - r.yBottom;
	r.yTop = pm_win(dev)->y - r.yTop;
	WinScrollWindow(pm_win(dev)->hc, 0, -sc, &r, &r, NULLHANDLE, NULL, SW_INVALIDATERGN);
#endif
#ifdef WIN32
	if (ScrollWindowEx(pm_win(dev)->hc, 0, sc, &r, &r, NULL, NULL, SW_INVALIDATE) == ERROR)
		error("ScrollWindowEx failed");
#endif
	pm_vscroll_redraws(pm_win(dev), &dev->clip, sc);
	pm_unlock();
	PM_FLUSH();
	debug_call(("done\n"));
	return 0;
}

static void pm_set_clip_area(struct graphics_device *dev, struct rect *rr)
{
	debug_call(("set_clip_area (%d,%d)x(%d,%d)\n", rr->x1, rr->y1, rr->x2, rr->y2));
	memcpy(&dev->clip, rr, sizeof(struct rect));
	if (dev->clip.x1 >= dev->clip.x2 || dev->clip.y1 >= dev->clip.y2) dev->clip.x1 = dev->clip.x2 = dev->clip.y1 = dev->clip.y2 = 0;
	debug_call(("done\n"));
}

struct graphics_driver pmshell_driver = {
#ifdef OS2
	cast_uchar "pmshell",
#endif
#ifdef WIN32
	cast_uchar "windows",
#endif
	pm_init_driver,
	pm_init_device,
	pm_shutdown_device,
	pm_shutdown_driver,
	pm_get_driver_param,
	pm_get_empty_bitmap,
	pm_register_bitmap,
	pm_prepare_strip,
	pm_commit_strip,
	pm_unregister_bitmap,
	pm_draw_bitmap,
	pm_get_color,
	pm_fill_area,
	pm_draw_hline,
	pm_draw_vline,
	pm_hscroll,
	pm_vscroll,
	pm_set_clip_area,
	dummy_block,
	dummy_unblock,
	pm_set_window_title,
	NULL, /* exec */
	NULL, /* set_clipboard_text */
	NULL, /* get_clipboard_text */
	0,			/* depth */
	0, 0,			/* x, y */
	0,			/* flags */
	0,			/* codepage */
	NULL,			/* shell */
};

#ifdef _UWIN

int main(int argc, char **argv);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nShow)
{
	int i, neednew, quote, clen;
	int argc = 1;
	unsigned char **argv;
	if (!(argv = malloc(2 * sizeof(unsigned char *)))) alloc_err: fatal_exit("can't allocate commandline");
	if (!(argv[0] = cast_uchar strdup("links"))) goto alloc_err;
	argv[1] = NULL;
	neednew = 1;
	quote = 0;
	clen = 0;
	for (i = 0; lpCmdLine[i]; i++) {
		unsigned c = lpCmdLine[i];
		if (c == ' ' && !quote) {
			neednew = 1;
			continue;
		}
		if (c == '"') {
			quote ^= 1;
			continue;
		}
		if (c == '\\' && lpCmdLine[i + 1]) {
			c = lpCmdLine[++i];
		}
		if (neednew) {
			if (!(argv = realloc(argv, (argc + 2) * sizeof(unsigned char *)))) goto alloc_err;
			if (!(argv[argc] = malloc(1))) goto alloc_err;
			argv[argc + 1] = NULL;
			argc++;
			neednew = 0;
			clen = 0;
		}
		if (!(argv[argc - 1] = realloc(argv[argc - 1], clen + 1))) goto alloc_err;
		argv[argc - 1][clen] = c;
		argv[argc - 1][clen + 1] = 0;
		clen++;
	}
	/*debug("cmdline: -%s-", lpCmdLine);*/
	return main(argc, (char **)argv);
}

#endif

#endif