File: XGServerEvent.m

package info (click to toggle)
gnustep-back 0.14.0-2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 3,416 kB
  • ctags: 1,025
  • sloc: objc: 35,429; ansic: 6,048; makefile: 212; sh: 116
file content (2356 lines) | stat: -rw-r--r-- 72,500 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
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
/*
   XGServerEvent - Window/Event code for X11 backends.

   Copyright (C) 1998,1999 Free Software Foundation, Inc.

   Written by:  Adam Fedor <fedor@boulder.colorado.edu>
   Date: Nov 1998
   
   This file is part of the GNU Objective C User Interface Library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; see the file COPYING.LIB.
   If not, see <http://www.gnu.org/licenses/> or write to the 
   Free Software Foundation, 51 Franklin Street, Fifth Floor, 
*/

#include "config.h"

#include <AppKit/AppKitExceptions.h>
#include <AppKit/NSApplication.h>
#include <AppKit/NSGraphics.h>
#include <AppKit/NSMenu.h>
#include <AppKit/NSPasteboard.h>
#include <AppKit/NSWindow.h>
#include <Foundation/NSException.h>
#include <Foundation/NSArray.h>
#include <Foundation/NSDictionary.h>
#include <Foundation/NSData.h>
#include <Foundation/NSNotification.h>
#include <Foundation/NSValue.h>
#include <Foundation/NSString.h>
#include <Foundation/NSUserDefaults.h>
#include <Foundation/NSRunLoop.h>
#include <Foundation/NSDebug.h>

#include "x11/XGServerWindow.h"
#include "x11/XGInputServer.h"
#include "x11/XGDragView.h"
#include "x11/XGGeneric.h"
#include "x11/xdnd.h"

#ifdef HAVE_WRASTER_H
#include "wraster.h"
#else
#include "x11/wraster.h"
#endif

#include "math.h"
#include <X11/keysym.h>
#include <X11/Xproto.h>

#if LIB_FOUNDATION_LIBRARY
# include <Foundation/NSPosixFileDescriptor.h>
#elif defined(NeXT_PDO)
# include <Foundation/NSFileHandle.h>
# include <Foundation/NSNotification.h>
#endif

#define	cWin	((gswindow_device_t*)generic.cachedWindow)

extern Atom     WM_STATE;

// NumLock's mask (it depends on the keyboard mapping)
static unsigned int _num_lock_mask;
// Modifier state
static char _control_pressed = 0;
static char _command_pressed = 0;
static char _alt_pressed = 0;
static char _help_pressed = 0;
/*
Keys used for the modifiers (you may set them with user preferences).
Note that the first and second key sym for a modifier must be different.
Otherwise, the _*_pressed tracking will be confused.
*/
static KeySym _control_keysyms[2];
static KeySym _command_keysyms[2];
static KeySym _alt_keysyms[2];
static KeySym _help_keysyms[2];

static BOOL _is_keyboard_initialized = NO;
static BOOL _mod_ignore_shift = NO;

void __objc_xgcontextevent_linking (void)
{
}

static SEL    procSel = 0;
static void (*procEvent)(id, SEL, XEvent*) = 0;

#ifdef XSHM
@interface NSGraphicsContext (SharedMemory)
-(void) gotShmCompletion: (Drawable)d;
@end
#endif

@interface XGServer (Private)
- (void) receivedEvent: (void*)data
                  type: (RunLoopEventType)type
                 extra: (void*)extra
               forMode: (NSString*)mode;
- (void) setupRunLoopInputSourcesForMode: (NSString*)mode; 
- (NSDate*) timedOutEvent: (void*)data
                     type: (RunLoopEventType)type
                  forMode: (NSString*)mode;
- (int) XGErrorHandler: (Display*)display : (XErrorEvent*)err;
- (void) processEvent: (XEvent *) event;
- (NSEvent *)_handleTakeFocusAtom: (XEvent)xEvent 
		       forContext: (NSGraphicsContext *)gcontext;
@end


int
XGErrorHandler(Display *display, XErrorEvent *err)
{
  XGServer	*ctxt = (XGServer*)GSCurrentServer();

  return [ctxt XGErrorHandler: display : err];
}

static NSEvent*process_key_event (XEvent* xEvent, XGServer* ctxt, 
  NSEventType eventType, NSMutableArray *event_queue);

static unichar process_char (KeySym keysym, unsigned *eventModifierFlags);

static unsigned process_modifier_flags(unsigned int state);

static void initialize_keyboard (void);

static void set_up_num_lock (void);

// checks whether a GNUstep modifier (key_sym) is pressed when we're only able
// to check whether X keycodes are pressed in xEvent->xkeymap;
static int check_modifier (XEvent *xEvent, KeySym key_sym)
{
    char *key_vector;
    int by,bi;
    int key_code = XKeysymToKeycode(xEvent->xkeymap.display, key_sym);

    by = key_code / 8;
    bi = key_code % 8;
    key_vector = xEvent->xkeymap.key_vector;
    return (key_vector[by] & (1 << bi));
}

@interface XGServer (WindowOps)
- (void) styleoffsets: (float *) l : (float *) r : (float *) t : (float *) b
                     : (unsigned int) style : (Window) win;
- (NSRect) _XWinRectToOSWinRect: (NSRect)r for: (void*)windowNumber;
@end

@implementation XGServer (EventOps)

- (int) XGErrorHandler: (Display*)display : (XErrorEvent*)err
{
  int length = 1024;
  char buffer[length+1];

  /*
   * Ignore attempts to set input focus to unmapped window, except for noting
   * if the most recent request failed (mark the request serial number to 0)
   * in which case we should repeat the request when the window becomes
   * mapped again.
   */
  if (err->error_code == BadMatch && err->request_code == X_SetInputFocus)
    {
      if (err->serial == generic.focusRequestNumber)
	{
	  generic.focusRequestNumber = 0;
	}
      return 0;
    }

  XGetErrorText(display, err->error_code, buffer, length);
  if (err->type == 0
      && GSDebugSet(@"XSynchronize") == NO)
    {
      NSLog(@"X-Windows error - %s\n\
          on display: %s\n\
    		type: %d\n\
       serial number: %d\n\
	request code: %d\n",
	buffer,
    	XDisplayName(DisplayString(display)),
	err->type, err->serial, err->request_code);
      return 0;
    }
  [NSException raise: NSWindowServerCommunicationException
    format: @"X-Windows error - %s\n\
          on display: %s\n\
    		type: %d\n\
       serial number: %d\n\
	request code: %d\n",
	buffer,
    	XDisplayName(DisplayString(display)),
	err->type, err->serial, err->request_code];
  return 0;
}

- (void) setupRunLoopInputSourcesForMode: (NSString*)mode
{
  int		xEventQueueFd = XConnectionNumber(dpy);
  NSRunLoop	*currentRunLoop = [NSRunLoop currentRunLoop];

#if defined(LIB_FOUNDATION_LIBRARY)
  {
    id fileDescriptor = [[[NSPosixFileDescriptor alloc]
	initWithFileDescriptor: xEventQueueFd]
	autorelease];

    // Invoke limitDateForMode: to setup the current
    // mode of the run loop (the doc says that this
    // method and acceptInputForMode: beforeDate: are
    // the only ones that setup the current mode).

    [currentRunLoop limitDateForMode: mode];

    [fileDescriptor setDelegate: self];
    [fileDescriptor monitorFileActivity: NSPosixReadableActivity];
  }
#elif defined(NeXT_PDO)
  {
    id fileDescriptor = [[[NSFileHandle alloc]
	initWithFileDescriptor: xEventQueueFd]
	autorelease];

    [[NSNotificationCenter defaultCenter] addObserver: self
	selector: @selector(activityOnFileHandle:)
	name: NSFileHandleDataAvailableNotification
	object: fileDescriptor];
    [fileDescriptor waitForDataInBackgroundAndNotifyForModes:
	[NSArray arrayWithObject: mode]];
  }
#else
  [currentRunLoop addEvent: (void*)(gsaddr)xEventQueueFd
		      type: ET_RDESC
		   watcher: (id<RunLoopEvents>)self
		   forMode: mode];
#endif
  if (procSel == 0)
    {
      procSel = @selector(processEvent:);
      procEvent = (void (*)(id, SEL, XEvent*))
	[self methodForSelector: procSel];
    }
}

#if LIB_FOUNDATION_LIBRARY
- (void) activity: (NSPosixFileActivities)activity
		posixFileDescriptor: (NSPosixFileDescriptor*)fileDescriptor
{
  [self receivedEvent: 0 type: 0 extra: 0 forMode: nil];
}
#elif defined(NeXT_PDO)
- (void) activityOnFileHandle: (NSNotification*)notification
{
  id fileDescriptor = [notification object];
  id runLoopMode = [[NSRunLoop currentRunLoop] currentMode];

  [fileDescriptor waitForDataInBackgroundAndNotifyForModes:
	[NSArray arrayWithObject: runLoopMode]];
  [self receivedEvent: 0 type: 0 extra: 0 forMode: nil];
}
#endif

- (void) receivedEvent: (void*)data
                  type: (RunLoopEventType)type
                 extra: (void*)extra
               forMode: (NSString*)mode
{
  XEvent		xEvent;

  // loop and grab all of the events from the X queue
  while (XPending(dpy) > 0)
    {
      XNextEvent(dpy, &xEvent);

#ifdef USE_XIM
      if (XFilterEvent(&xEvent, None)) 
	{
	  NSDebugLLog(@"NSKeyEvent", @"Event filtered (by XIM?)\n");
	  continue;
	}
#endif

      (*procEvent)(self, procSel, &xEvent);
    }
}

/*
 */
- (NSPoint) _XPointToOSPoint: (NSPoint)x for: (void*)window
{
  gswindow_device_t	*win = (gswindow_device_t*)window;
  unsigned int		style = win->win_attrs.window_style;
  NSPoint	o;
  float	t, b, l, r;

  [self styleoffsets: &l : &r : &t : &b : style : win->ident];
  o.x = x.x + l;
  o.y = NSHeight(win->xframe) - x.y + b;

  NSDebugLLog(@"Frame", @"X2OP %d, %x, %@, %@", win->number, style,
    NSStringFromPoint(x), NSStringFromPoint(o));
  return o;
}


- (void) processEvent: (XEvent *) event
{
  static int		clickCount = 1;
  static unsigned int	eventFlags;
  NSEvent		*e = nil;
  XEvent		xEvent;
  static NSPoint	eventLocation;
  NSWindow              *nswin;
  Window		xWin;
  NSEventType		eventType;
  NSGraphicsContext     *gcontext;
  float                 deltaX;
  float                 deltaY;

  gcontext = GSCurrentContext();
  xEvent = *event;

  switch (xEvent.type)
    {
	// mouse button events
      case ButtonPress:
	NSDebugLLog(@"NSEvent", @"%d ButtonPress: \
		xEvent.xbutton.time %u timeOfLastClick %u \n",
		    xEvent.xbutton.window, xEvent.xbutton.time,
		    generic.lastClick);
	/*
	 * hardwired test for a double click
	 *
	 * For multiple clicks, the clicks must remain in the same
	 * region of the same window and must occur in a limited time.
	 *
	 * default time of 300 should be user set;
	 * perhaps the movement of 3 should also be a preference?
	 */
	{
	  BOOL	incrementCount = YES;

#define	CLICK_TIME	300
#define	CLICK_MOVE	3
	  if (xEvent.xbutton.time
	    >= (unsigned long)(generic.lastClick + CLICK_TIME))
	    incrementCount = NO;
	  else if (generic.lastClickWindow != xEvent.xbutton.window)
	    incrementCount = NO;
	  else if ((generic.lastClickX - xEvent.xbutton.x) > CLICK_MOVE)
	    incrementCount = NO;
	  else if ((generic.lastClickX - xEvent.xbutton.x) < -CLICK_MOVE)
	    incrementCount = NO;
	  else if ((generic.lastClickY - xEvent.xbutton.y) > CLICK_MOVE)
	    incrementCount = NO;
	  else if ((generic.lastClickY - xEvent.xbutton.y) < -CLICK_MOVE)
	    incrementCount = NO;

	  if (incrementCount == YES)
	    {
	      clickCount++;
	    }
	  else
	    {
	      /*
	       * Not a multiple-click, so we must set the stored
	       * location of the click to the new values and
	       * reset the counter.
	       */
	      clickCount = 1;
	      generic.lastClickWindow = xEvent.xbutton.window;
	      generic.lastClickX = xEvent.xbutton.x;
	      generic.lastClickY = xEvent.xbutton.y;
	    }
	}
	generic.lastClick = xEvent.xbutton.time;
	[self setLastTime: generic.lastClick];
	deltaY = 0.0;

	if (xEvent.xbutton.button == generic.lMouse)
	  eventType = NSLeftMouseDown;
	else if (xEvent.xbutton.button == generic.rMouse
	  && generic.rMouse != 0)
	  eventType = NSRightMouseDown;
	else if (xEvent.xbutton.button == generic.mMouse
	  && generic.mMouse != 0)
	  eventType = NSOtherMouseDown;
	else if (xEvent.xbutton.button == generic.upMouse
	  && generic.upMouse != 0)
	  {
	    deltaY = 1.;
	    eventType = NSScrollWheel;
	  }
	else if (xEvent.xbutton.button == generic.downMouse
	  && generic.downMouse != 0)
	  {
	    deltaY = -1.;
	    eventType = NSScrollWheel;
	  }
	else
	  {
	    break;		/* Unknown button */
	  }

	eventFlags = process_modifier_flags(xEvent.xbutton.state);
	// if pointer is grabbed use grab window
	xWin = (grabWindow == 0) ? xEvent.xbutton.window : grabWindow;
	if (cWin == 0 || xWin != cWin->ident)
	  generic.cachedWindow = [XGServer _windowForXWindow: xWin];
	if (cWin == 0)
	  break;
	eventLocation.x = xEvent.xbutton.x;
	eventLocation.y = xEvent.xbutton.y;
	eventLocation = [self _XPointToOSPoint: eventLocation
					   for: cWin];

	if (generic.flags.useWindowMakerIcons == 1)
	  {
	    /*
	     * We must hand over control of our icon/miniwindow
	     * to Window Maker.
		 */
	    if ((cWin->win_attrs.window_style
	      & (NSMiniWindowMask | NSIconWindowMask)) != 0
	      && eventType == NSLeftMouseDown && clickCount == 1)
	      {
          if (cWin->parent == None)
            break;
          xEvent.xbutton.window = cWin->parent;
          XUngrabPointer(dpy, CurrentTime);
          XSendEvent(dpy, cWin->parent, True,
                     ButtonPressMask, &xEvent);
          XFlush(dpy);
          break;
	      }
	  }

	// create NSEvent
	e = [NSEvent mouseEventWithType: eventType
		     location: eventLocation
		     modifierFlags: eventFlags
         timestamp: (NSTimeInterval)generic.lastClick / 1000.0
		     windowNumber: cWin->number
		     context: gcontext
		     eventNumber: xEvent.xbutton.serial
		     clickCount: clickCount
		     pressure: 1.0
		     buttonNumber: 0 /* FIXME */
		     deltaX: 0.
		     deltaY: deltaY
		     deltaZ: 0.];
	break;

      case ButtonRelease:
	NSDebugLLog(@"NSEvent", @"%d ButtonRelease\n",
		    xEvent.xbutton.window);
	[self setLastTime: xEvent.xbutton.time];
	if (xEvent.xbutton.button == generic.lMouse)
	  eventType = NSLeftMouseUp;
	else if (xEvent.xbutton.button == generic.rMouse
	  && generic.rMouse != 0)
	  eventType = NSRightMouseUp;
	else if (xEvent.xbutton.button == generic.mMouse
	  && generic.mMouse != 0)
	  eventType = NSOtherMouseUp;
	else
	  {
	    // we ignore release of scrollUp or scrollDown
	    break;		/* Unknown button */
	  }

	eventFlags = process_modifier_flags(xEvent.xbutton.state);
	// if pointer is grabbed use grab window
	xWin = (grabWindow == 0) ? xEvent.xbutton.window : grabWindow;
	if (cWin == 0 || xWin != cWin->ident)
	  generic.cachedWindow = [XGServer _windowForXWindow: xWin];
	if (cWin == 0)
	  break;
	eventLocation.x = xEvent.xbutton.x;
	eventLocation.y = xEvent.xbutton.y;
	eventLocation = [self _XPointToOSPoint: eventLocation
					   for: cWin];

	e = [NSEvent mouseEventWithType: eventType
		     location: eventLocation
		     modifierFlags: eventFlags
		     timestamp: (NSTimeInterval)generic.lastTime / 1000.0
		     windowNumber: cWin->number
		     context: gcontext
		     eventNumber: xEvent.xbutton.serial
		     clickCount: clickCount
		     pressure: 1.0
		     buttonNumber: 0	/* FIXMME */
		     deltaX: 0.0
		     deltaY: 0.0
		     deltaZ: 0.0];
	break;

      case CirculateNotify:
	NSDebugLLog(@"NSEvent", @"%d CirculateNotify\n",
		    xEvent.xcirculate.window);
	break;

      case CirculateRequest:
	NSDebugLLog(@"NSEvent", @"%d CirculateRequest\n",
		    xEvent.xcirculaterequest.window);
	break;

      case ClientMessage:
	{
	  NSTimeInterval time;
	  DndClass dnd = xdnd ();
	      
	  NSDebugLLog(@"NSEvent", @"%d ClientMessage\n",
		      xEvent.xclient.window);
	  if (cWin == 0 || xEvent.xclient.window != cWin->ident)
	    {
	      generic.cachedWindow
		= [XGServer _windowForXWindow: xEvent.xclient.window];
	    }
	  if (cWin == 0)
	    break;
	  if (xEvent.xclient.message_type == generic.protocols_atom)
	    {
	      [self setLastTime: (Time)xEvent.xclient.data.l[1]];
	      NSDebugLLog(@"NSEvent", @"WM Protocol - %s\n",
			  XGetAtomName(dpy, xEvent.xclient.data.l[0]));

	      if ((Atom)xEvent.xclient.data.l[0] == generic.delete_win_atom)
		{
		  /*
		   * WM is asking us to close a window
		   */
		  eventLocation = NSMakePoint(0,0);
		  e = [NSEvent otherEventWithType: NSAppKitDefined
			       location: eventLocation
			       modifierFlags: 0
			       timestamp: 0
			       windowNumber: cWin->number
			       context: gcontext
			       subtype: GSAppKitWindowClose
			       data1: 0
			       data2: 0];
		}
	      else if ((Atom)xEvent.xclient.data.l[0]
		== generic.miniaturize_atom)
		{
		  eventLocation = NSMakePoint(0,0);
		  e = [NSEvent otherEventWithType: NSAppKitDefined
			       location: eventLocation
			       modifierFlags: 0
			       timestamp: 0
			       windowNumber: cWin->number
			       context: gcontext
			       subtype: GSAppKitWindowMiniaturize
			       data1: 0
			       data2: 0];
		}
	      else if ((Atom)xEvent.xclient.data.l[0]
		== generic.take_focus_atom)
		{
		  e = [self _handleTakeFocusAtom: xEvent 
				      forContext: gcontext];
		}
	      else if ((Atom)xEvent.xclient.data.l[0]
		== generic.net_wm_ping_atom)
		{
		  xEvent.xclient.window = RootWindow(dpy, cWin->screen);
		  XSendEvent(dpy, xEvent.xclient.window, False, 
		    (SubstructureRedirectMask | SubstructureNotifyMask), 
		    &xEvent);
		}
	    }
	  else if (xEvent.xclient.message_type == dnd.XdndEnter)
	    {
	      Window source;

	      NSDebugLLog(@"NSDragging", @"  XdndEnter message\n");
	      source = XDND_ENTER_SOURCE_WIN(&xEvent);
	      eventLocation = NSMakePoint(0,0);
	      e = [NSEvent otherEventWithType: NSAppKitDefined
			   location: eventLocation
			   modifierFlags: 0
			   timestamp: 0
			   windowNumber: cWin->number
			   context: gcontext
			   subtype: GSAppKitDraggingEnter
			   data1: source
			   data2: 0];
	      /* If this is a non-local drag, set the dragInfo */
	      if ([XGServer _windowForXWindow: source] == NULL)
		{
		  [[XGDragView sharedDragView] setupDragInfoFromXEvent:
						 &xEvent];
		}
	    }
	  else if (xEvent.xclient.message_type == dnd.XdndPosition)
	    {
	      Window		source;
	      Atom		action;
	      NSDragOperation	operation;
	      int root_x, root_y;
	      Window root_child;

	      NSDebugLLog(@"NSDragging", @"  XdndPosition message\n");
	      source = XDND_POSITION_SOURCE_WIN(&xEvent);
	      /*
		Work around a bug/feature in WindowMaker that does not
		send ConfigureNotify events for app icons.
	      */
	      XTranslateCoordinates(dpy, xEvent.xclient.window,
				    RootWindow(dpy, cWin->screen),
				    0, 0,
				    &root_x, &root_y,
				    &root_child);
	      cWin->xframe.origin.x = root_x;
	      cWin->xframe.origin.y = root_y;

	      eventLocation.x = XDND_POSITION_ROOT_X(&xEvent) - 
		NSMinX(cWin->xframe);
	      eventLocation.y = XDND_POSITION_ROOT_Y(&xEvent) - 
		NSMinY(cWin->xframe);
	      eventLocation = [self _XPointToOSPoint: eventLocation
						 for: cWin];
	      time = XDND_POSITION_TIME(&xEvent);
	      action = XDND_POSITION_ACTION(&xEvent);
	      operation = GSDragOperationForAction(action);
	      e = [NSEvent otherEventWithType: NSAppKitDefined
			   location: eventLocation
			   modifierFlags: 0
			   timestamp: time / 1000.0
			   windowNumber: cWin->number
			   context: gcontext
			   subtype: GSAppKitDraggingUpdate
			   data1: source
			   data2: operation];
	      /* If this is a non-local drag, update the dragInfo */
	      if ([XGServer _windowForXWindow: source] == NULL)
		{
		  [[XGDragView sharedDragView] updateDragInfoFromEvent:
						 e];
		}
	    }
	  else if (xEvent.xclient.message_type == dnd.XdndStatus)
	    {
	      Window		target;
	      Atom		action;
	      NSDragOperation	operation;

	      NSDebugLLog(@"NSDragging", @"  XdndStatus message\n");
	      target = XDND_STATUS_TARGET_WIN(&xEvent);
	      eventLocation = NSMakePoint(0, 0);
	      if (XDND_STATUS_WILL_ACCEPT (&xEvent))
		{
		  action = XDND_STATUS_ACTION(&xEvent);
		}
	      else
		{
		  action = NSDragOperationNone;
		}
		  
	      operation = GSDragOperationForAction(action);
	      e = [NSEvent otherEventWithType: NSAppKitDefined
			   location: eventLocation
			   modifierFlags: 0
			   timestamp: 0
			   windowNumber: cWin->number
			   context: gcontext
			   subtype: GSAppKitDraggingStatus
			   data1: target
			   data2: operation];
	    }
	  else if (xEvent.xclient.message_type == dnd.XdndLeave)
	    {
	      Window	source;

	      NSDebugLLog(@"NSDragging", @"  XdndLeave message\n");
	      source = XDND_LEAVE_SOURCE_WIN(&xEvent);
	      eventLocation = NSMakePoint(0, 0);
	      e = [NSEvent otherEventWithType: NSAppKitDefined
			   location: eventLocation
			   modifierFlags: 0
			   timestamp: 0
			   windowNumber: cWin->number
			   context: gcontext
			   subtype: GSAppKitDraggingExit
			   data1: 0
			   data2: 0];
	      /* If this is a non-local drag, reset the dragInfo */
	      if ([XGServer _windowForXWindow: source] == NULL)
		{
		  [[XGDragView sharedDragView] resetDragInfo];
		}
	    }
	  else if (xEvent.xclient.message_type == dnd.XdndDrop)
	    {
	      Window	source;

	      NSDebugLLog(@"NSDragging", @"  XdndDrop message\n");
	      source = XDND_DROP_SOURCE_WIN(&xEvent);
	      eventLocation = NSMakePoint(0, 0);
	      time = XDND_DROP_TIME(&xEvent);
	      e = [NSEvent otherEventWithType: NSAppKitDefined
			   location: eventLocation
			   modifierFlags: 0
			   timestamp: time / 1000.0
			   windowNumber: cWin->number
			   context: gcontext
			   subtype: GSAppKitDraggingDrop
			   data1: source
			   data2: 0];
	    }
	  else if (xEvent.xclient.message_type == dnd.XdndFinished)
	    {
	      Window	target;

	      NSDebugLLog(@"NSDragging", @"  XdndFinished message\n");
	      target = XDND_FINISHED_TARGET_WIN(&xEvent);
	      eventLocation = NSMakePoint(0, 0);
	      e = [NSEvent otherEventWithType: NSAppKitDefined
			   location: eventLocation
			   modifierFlags: 0
			   timestamp: 0
			   windowNumber: cWin->number
			   context: gcontext
			   subtype: GSAppKitDraggingFinished
			   data1: target
			   data2: 0];
	    }
	}
	break;

      case ColormapNotify:
	// colormap attribute
	NSDebugLLog(@"NSEvent", @"%d ColormapNotify\n",
		    xEvent.xcolormap.window);
	break;

	    // the window has been resized, change the width and height
	    // and update the window so the changes get displayed
      case ConfigureNotify:
	NSDebugLLog(@"NSEvent", @"%d ConfigureNotify "
		    @"x:%d y:%d w:%d h:%d b:%d %c", xEvent.xconfigure.window,
		    xEvent.xconfigure.x, xEvent.xconfigure.y,
		    xEvent.xconfigure.width, xEvent.xconfigure.height,
		    xEvent.xconfigure.border_width,
		    xEvent.xconfigure.send_event ? 'T' : 'F');
	if (cWin == 0 || xEvent.xconfigure.window != cWin->ident)
	  {
	    generic.cachedWindow
	      = [XGServer _windowForXWindow:xEvent.xconfigure.window];
	  }

	if (cWin != 0)
	  {
	    NSRect	   r, x, n, h;
	    NSTimeInterval ts = (NSTimeInterval)generic.lastMotion;

	    r = cWin->xframe;

	    x = NSMakeRect(xEvent.xconfigure.x,
			   xEvent.xconfigure.y,
			   xEvent.xconfigure.width,
			   xEvent.xconfigure.height);

	    /*
	    According to the ICCCM, coordinates in synthetic events
	    (ie. non-zero send_event) are in root space, while coordinates
	    in real events are in the parent window's space. The parent
	    window might be some window manager window, so we can't
	    directly use those coordinates.

	    Thus, if the event is real, we use XTranslateCoordinates to
	    get the root space coordinates.
	    */
	    if (xEvent.xconfigure.send_event == 0)
	      {
		int root_x, root_y;
		Window root_child;
		XTranslateCoordinates(dpy, xEvent.xconfigure.window,
				      RootWindow(dpy, cWin->screen),
				      0, 0,
				      &root_x, &root_y,
				      &root_child);
		x.origin.x = root_x;
		x.origin.y = root_y;
	      }

	    cWin->xframe = x;
	    n = [self _XFrameToOSFrame: x for: cWin];
	    NSDebugLLog(@"Moving",
			@"Update win %d:\n   original:%@\n   new:%@",
			cWin->number, NSStringFromRect(r), 
			NSStringFromRect(x));
	    /*
	     * Set size hints info to be up to date with new size.
	     */
	    h = [self _XFrameToXHints: x for: cWin];
	    cWin->siz_hints.width = h.size.width;
	    cWin->siz_hints.height = h.size.height;

	    /*
	    We only update the position hints if we're on the screen.
	    Otherwise, the window manager might not have added decorations
	    (if any) to the window yet. Since we compensate for decorations
	    when we set the position, this will confuse us and we'll end
	    up compensating twice, which makes windows drift.
	    */
	    if (cWin->map_state == IsViewable)
	      {
		cWin->siz_hints.x = h.origin.x;
		cWin->siz_hints.y = h.origin.y;
	      }

	    /*
	     * create GNUstep event(s)
	     */
	    if (!NSEqualSizes(r.size, x.size))
	      {
		/* Resize events move the origin. There's no good
		   place to pass this info back, so we put it in
		   the event location field */
		e = [NSEvent otherEventWithType: NSAppKitDefined
			     location: n.origin
			     modifierFlags: eventFlags
			     timestamp: ts / 1000.0
			     windowNumber: cWin->number
			     context: gcontext
			     subtype: GSAppKitWindowResized
			     data1: n.size.width
			     data2: n.size.height];
	      }
	    if (!NSEqualPoints(r.origin, x.origin))
	      {
		if (e != nil)
		  {
		    [event_queue addObject: e];
		  }
		e = [NSEvent otherEventWithType: NSAppKitDefined
			     location: eventLocation
			     modifierFlags: eventFlags
			     timestamp: ts / 1000.0
			     windowNumber: cWin->number
			     context: gcontext
			     subtype: GSAppKitWindowMoved
			     data1: n.origin.x
			     data2: n.origin.y];
	      }
	  }
	break;

	    // same as ConfigureNotify but we get this event
	    // before the change has actually occurred
      case ConfigureRequest:
	NSDebugLLog(@"NSEvent", @"%d ConfigureRequest\n",
		    xEvent.xconfigurerequest.window);
	break;

	    // a window has been created
      case CreateNotify:
	NSDebugLLog(@"NSEvent", @"%d CreateNotify\n",
		    xEvent.xcreatewindow.window);
	break;

	    // a window has been destroyed
      case DestroyNotify:
	NSDebugLLog(@"NSEvent", @"%d DestroyNotify\n",
		    xEvent.xdestroywindow.window);
	break;

	    // when the pointer enters a window
      case EnterNotify:
	NSDebugLLog(@"NSEvent", @"%d EnterNotify\n",
		    xEvent.xcrossing.window);
	break;
	      
	    // when the pointer leaves a window
      case LeaveNotify:
	NSDebugLLog(@"NSEvent", @"%d LeaveNotify\n",
		    xEvent.xcrossing.window);
	if (cWin == 0 || xEvent.xcrossing.window != cWin->ident)
	  {
	    generic.cachedWindow
	      = [XGServer _windowForXWindow: xEvent.xcrossing.window];
	  }
	if (cWin == 0)
	  break;
	eventLocation = NSMakePoint(-1,-1);
	e = [NSEvent otherEventWithType: NSAppKitDefined
		     location: eventLocation
		     modifierFlags: 0
		     timestamp: 0
		     windowNumber: cWin->number
		     context: gcontext
		     subtype: GSAppKitWindowLeave
		     data1: 0
		     data2: 0];
	break;

	    // the visibility of a window has changed
      case VisibilityNotify:
	NSDebugLLog(@"NSEvent", @"%d VisibilityNotify %d\n", 
		    xEvent.xvisibility.window, xEvent.xvisibility.state);
	if (cWin == 0 || xEvent.xvisibility.window != cWin->ident)
	  {
	    generic.cachedWindow
	      = [XGServer _windowForXWindow:xEvent.xvisibility.window];
	  }
	if (cWin != 0)
	  cWin->visibility = xEvent.xvisibility.state;
	break;

	// a portion of the window has become visible and
	// we must redisplay it
      case Expose:
	NSDebugLLog(@"NSEvent", @"%d Expose\n",
		    xEvent.xexpose.window);
	{
	  if (cWin == 0 || xEvent.xexpose.window != cWin->ident)
	    {
	      generic.cachedWindow
		= [XGServer _windowForXWindow:xEvent.xexpose.window];
	    }
	  if (cWin != 0)
	    {
	      XRectangle rectangle;

	      rectangle.x = xEvent.xexpose.x;
	      rectangle.y = xEvent.xexpose.y;
	      rectangle.width = xEvent.xexpose.width;
	      rectangle.height = xEvent.xexpose.height;
	      NSDebugLLog(@"NSEvent", @"Expose frame %d %d %d %d\n",
			  rectangle.x, rectangle.y,
			  rectangle.width, rectangle.height);
#if 1
	      [self _addExposedRectangle: rectangle : cWin->number];

	      if (xEvent.xexpose.count == 0)
		[self _processExposedRectangles: cWin->number];
#else
	      {
	        NSRect		rect;
		NSTimeInterval	ts = (NSTimeInterval)generic.lastMotion;

		rect = [self _XWinRectToOSWinRect: NSMakeRect(
		  rectangle.x, rectangle.y, rectangle.width, rectangle.height)
		  for: cWin];
		e = [NSEvent otherEventWithType: NSAppKitDefined
		  location: rect.origin
		  modifierFlags: eventFlags
		  timestamp: ts / 1000.0
		  windowNumber: cWin->number
		  context: gcontext
		  subtype: GSAppKitRegionExposed
		  data1: rect.size.width
		  data2: rect.size.height];
	      }

#endif
	    }
	  break;
	}

      // keyboard focus entered a window
      case FocusIn:
        NSDebugLLog(@"NSEvent", @"%d FocusIn\n",
                    xEvent.xfocus.window);
        if (cWin == 0 || xEvent.xfocus.window != cWin->ident)
          {
            generic.cachedWindow
                = [XGServer _windowForXWindow:xEvent.xfocus.window];
          }
        if (cWin == 0)
          break;
        NSDebugLLog(@"Focus", @"%d got focus on %d\n",
                    xEvent.xfocus.window, cWin->number);
        // Store this for debugging, may not be the real focus window
        generic.currentFocusWindow = cWin->number;
        if (xEvent.xfocus.serial == generic.focusRequestNumber)
          {
            /*
             * This is a response to our own request - so we mark the
             * request as complete.
             */
            generic.desiredFocusWindow = 0;
            generic.focusRequestNumber = 0;
          }
        break;
        
	    // keyboard focus left a window
      case FocusOut:
        {
          Window	fw;
          int		rev;
          
          /*
           * See where the focus has moved to -
           * If it has gone to 'none' or 'PointerRoot' then 
           * it's not one of ours.
           * If it has gone to our root window - use the icon window.
           * If it has gone to a window - we see if it is one of ours.
           */
          XGetInputFocus(xEvent.xfocus.display, &fw, &rev);
          NSDebugLLog(@"NSEvent", @"%d FocusOut\n",
                      xEvent.xfocus.window);
          if (fw != None && fw != PointerRoot)
            {
              generic.cachedWindow = [XGServer _windowForXWindow: fw];
              if (cWin == 0)
                {
                  generic.cachedWindow = [XGServer _windowForXParent: fw];
                }
              if (cWin == 0)
                {
                  nswin = nil;
                }
              else
                {
                  nswin = GSWindowWithNumber(cWin->number);
                }
            }
          else
            {
              nswin = nil;
            }
          NSDebugLLog(@"Focus", @"Focus went to %d (xwin %d)\n", 
                      (nswin != nil) ? cWin->number : 0, fw);

          // Focus went to a window not in this application.
          if (nswin == nil)
            {
              [NSApp deactivate];
            }

          // Clean up old focus request
          generic.cachedWindow
              = [XGServer _windowForXWindow: xEvent.xfocus.window];
          NSDebugLLog(@"Focus", @"%d lost focus on %d\n",
                      xEvent.xfocus.window, (cWin) ? cWin->number : 0);
          generic.currentFocusWindow = 0;
          if (cWin && generic.desiredFocusWindow == cWin->number)
            {
              /* Request not valid anymore since we lost focus */
              generic.focusRequestNumber = 0;
            }
        }
        break;

      case GraphicsExpose:
        NSDebugLLog(@"NSEvent", @"%d GraphicsExpose\n",
                    xEvent.xexpose.window);
        break;

      case NoExpose:
        NSDebugLLog(@"NSEvent", @"NoExpose\n");
        break;

      // window is moved because of a change in the size of its parent
      case GravityNotify:
        NSDebugLLog(@"NSEvent", @"%d GravityNotify\n",
                    xEvent.xgravity.window);
        break;

	    // a key has been pressed
      case KeyPress:
        NSDebugLLog(@"NSEvent", @"%d KeyPress\n",
                    xEvent.xkey.window);
        [self setLastTime: xEvent.xkey.time];
        e = process_key_event (&xEvent, self, NSKeyDown, event_queue);
        break;

	    // a key has been released
      case KeyRelease:
        NSDebugLLog(@"NSEvent", @"%d KeyRelease\n",
                    xEvent.xkey.window);
        [self setLastTime: xEvent.xkey.time];
        e = process_key_event (&xEvent, self, NSKeyUp, event_queue);
        break;

	    // reports the state of the keyboard when pointer or
	    // focus enters a window
      case KeymapNotify:
	{
	  if (_is_keyboard_initialized == NO)
	    initialize_keyboard ();

	  NSDebugLLog(@"NSEvent", @"%d KeymapNotify\n",
		      xEvent.xkeymap.window);

	  // Check if control is pressed
	  _control_pressed = 0;
	  if ((_control_keysyms[0] != NoSymbol)
	      && check_modifier (&xEvent, _control_keysyms[0]))
	    {
	      _control_pressed |= 1;
	    }
	  if ((_control_keysyms[1] != NoSymbol)
	      && check_modifier (&xEvent, _control_keysyms[1]))
	    {
	      _control_pressed |= 2;
	    }

	  // Check if command is pressed
	  _command_pressed = 0;
	  if ((_command_keysyms[0] != NoSymbol)
	      && check_modifier (&xEvent, _command_keysyms[0]))
	    {
	      _command_pressed |= 1;
	    }
	  if ((_command_keysyms[1] != NoSymbol)
	      && check_modifier (&xEvent, _command_keysyms[1]))
	    {
	      _command_pressed |= 2;
	    }

	  // Check if alt is pressed
	  _alt_pressed = 0;
	  if ((_alt_keysyms[0] != NoSymbol)
	      && check_modifier (&xEvent, _alt_keysyms[0]))
	    {
	      _alt_pressed |= 1;
	    }
	  if ((_alt_keysyms[1] != NoSymbol)
	      && check_modifier (&xEvent, _alt_keysyms[1]))
	    {
	      _alt_pressed |= 2;
	    }

	  // Check if help is pressed
	  _help_pressed = 0;
	  if ((_help_keysyms[0] != NoSymbol)
	      && check_modifier (&xEvent, _help_keysyms[0]))
	    {
	      _help_pressed |= 1;
	    }
	  if ((_help_keysyms[1] != NoSymbol)
	      && check_modifier (&xEvent, _help_keysyms[1]))
	    {
	      _help_pressed |= 2;
	    }
	}
	break;

	    // when a window changes state from ummapped to
	    // mapped or vice versa
      case MapNotify:
        NSDebugLLog(@"NSEvent", @"%d MapNotify\n",
                    xEvent.xmap.window);
        if (cWin == 0 || xEvent.xmap.window != cWin->ident)
          {
            generic.cachedWindow
                = [XGServer _windowForXWindow:xEvent.xmap.window];
          }
        if (cWin != 0)
          {
            cWin->map_state = IsViewable;
            /*
             * if the window that was just mapped wants the input
             * focus, re-do the request.
             */
            if (generic.desiredFocusWindow == cWin->number
                && generic.focusRequestNumber == 0)
              {
                NSDebugLLog(@"Focus", @"Refocusing %d on map notify", 
                            cWin->number);
                [self setinputfocus: cWin->number];
              }
            /*
             * Make sure that the newly mapped window displays.
             */
            nswin = GSWindowWithNumber(cWin->number);
            [nswin update];
          }
        break;

	    // Window is no longer visible.
      case UnmapNotify:
	NSDebugLLog(@"NSEvent", @"%d UnmapNotify\n",
		    xEvent.xunmap.window);
	if (cWin == 0 || xEvent.xunmap.window != cWin->ident)
	  {
	    generic.cachedWindow
	      = [XGServer _windowForXWindow:xEvent.xunmap.window];
	  }
	if (cWin != 0)
	  {
	    cWin->map_state = IsUnmapped;
	    cWin->visibility = -1;
	  }
	break;

	    // like MapNotify but occurs before the request is carried out
      case MapRequest:
	NSDebugLLog(@"NSEvent", @"%d MapRequest\n",
		    xEvent.xmaprequest.window);
	break;

	    // keyboard or mouse mapping has been changed by another client
      case MappingNotify:
	NSDebugLLog(@"NSEvent", @"%d MappingNotify\n",
		    xEvent.xmapping.window);
	if ((xEvent.xmapping.request == MappingModifier) 
	    || (xEvent.xmapping.request == MappingKeyboard))
	  {
	    XRefreshKeyboardMapping (&xEvent.xmapping);
	    set_up_num_lock ();
	  }
	break;

      case MotionNotify:
	NSDebugLLog(@"NSMotionEvent", @"%d MotionNotify - %d %d\n",
		    xEvent.xmotion.window, xEvent.xmotion.x, xEvent.xmotion.y);
	{
	  unsigned int	state;

	  /*
	   * Compress motion events to avoid flooding.
	   */
	  while (XPending(xEvent.xmotion.display))
	    {
	      XEvent	peek;

	      XPeekEvent(xEvent.xmotion.display, &peek);
	      if (peek.type == MotionNotify
		  && xEvent.xmotion.window == peek.xmotion.window
		  && xEvent.xmotion.subwindow == peek.xmotion.subwindow)
		{
		  XNextEvent(xEvent.xmotion.display, &xEvent);
		}
	      else
		{
		  break;
		}
	    }

	  generic.lastMotion = xEvent.xmotion.time;
	  [self setLastTime: generic.lastMotion];
	  state = xEvent.xmotion.state;
	  if (state & generic.lMouseMask)
	    {
	      eventType = NSLeftMouseDragged;
	    }
	  else if (state & generic.rMouseMask)
	    {
	      eventType = NSRightMouseDragged;
	    }
	  else if (state & generic.mMouseMask)
	    {
	      eventType = NSOtherMouseDragged;
	    }
	  else
	    {
	      eventType = NSMouseMoved;
	    }

	  eventFlags = process_modifier_flags(state);
	  // if pointer is grabbed use grab window instead
	  xWin = (grabWindow == 0)
	    ? xEvent.xmotion.window : grabWindow;
	  if (cWin == 0 || xWin != cWin->ident)
	    generic.cachedWindow = [XGServer _windowForXWindow: xWin];
	  if (cWin == 0)
	    break;

	  deltaX = - eventLocation.x;
	  deltaY = - eventLocation.y;
	  eventLocation = NSMakePoint(xEvent.xmotion.x, xEvent.xmotion.y);
	  eventLocation = [self _XPointToOSPoint: eventLocation
					     for: cWin];
	  deltaX += eventLocation.x;
	  deltaY += eventLocation.y;

	  e = [NSEvent mouseEventWithType: eventType
		       location: eventLocation
		       modifierFlags: eventFlags
		       timestamp: (NSTimeInterval)generic.lastTime / 1000.0
		       windowNumber: cWin->number
		       context: gcontext
		       eventNumber: xEvent.xbutton.serial
		       clickCount: clickCount
		       pressure: 1.0
		       buttonNumber: 0 /* FIXME */
		       deltaX: deltaX
		       deltaY: deltaY
		       deltaZ: 0];
	  break;
	}

	// a window property has changed or been deleted
      case PropertyNotify:
	NSDebugLLog(@"NSEvent", @"%d PropertyNotify - '%s'\n",
		    xEvent.xproperty.window,
		    XGetAtomName(dpy, xEvent.xproperty.atom));
	break;

	    // a client successfully reparents a window
      case ReparentNotify:
	NSDebugLLog(@"NSEvent", @"%d ReparentNotify - offset %d %d\n",
		    xEvent.xreparent.window, xEvent.xreparent.x,
		    xEvent.xreparent.y);
	if (cWin == 0 || xEvent.xreparent.window != cWin->ident)
	  {
	    generic.cachedWindow
	      = [XGServer _windowForXWindow:xEvent.xreparent.window];
	  }
	if (cWin != 0)
	  {
	    cWin->parent = xEvent.xreparent.parent;
	  }

	if (cWin != 0 && xEvent.xreparent.parent != cWin->root
	  && (xEvent.xreparent.x != 0 || xEvent.xreparent.y != 0))
	  {
	    Window		parent = xEvent.xreparent.parent;
	    XWindowAttributes	wattr;
	    float		l;
	    float		r;
	    float		t;
	    float		b;
	    Offsets		*o;

	    /* Get the WM offset info which we hope is the same
	     * for all parented windows with the same style.
	     * The coordinates in the event are insufficient to determine
	     * the offsets as the new parent window may have a border,
	     * so we must get the attributes of that window and use them
	     * to determine our offsets.
	     */
	    XGetWindowAttributes(dpy, parent, &wattr);
	    NSDebugLLog(@"NSEvent", @"Parent border,width,height %d,%d,%d\n",
	      wattr.border_width, wattr.width, wattr.height);
	    l = xEvent.xreparent.x + wattr.border_width;
	    t = xEvent.xreparent.y + wattr.border_width;

	    /* Find total parent size and subtract window size and
	     * top-left-corner offset to determine bottom-right-corner
	     * offset.
	     */
	    r = wattr.width + wattr.border_width * 2;
	    r -= (cWin->xframe.size.width + l);
	    b = wattr.height + wattr.border_width * 2;
	    b -= (cWin->xframe.size.height + t);

	    // Some window manager e.g. KDE2 put in multiple windows,
	    // so we have to find the right parent, closest to root
	    /* FIXME: This section of code has caused problems with
	       certain users. An X error occurs in XQueryTree and
	       later a seg fault in XFree. It's 'commented' out for
	       now unless you set the default 'GSDoubleParentWindows'
	    */
	    if (generic.flags.doubleParentWindow)
	      {
		Window	new_parent = parent;

		r = wattr.width + wattr.border_width * 2;
		b = wattr.height + wattr.border_width * 2;
		while (new_parent && (new_parent != cWin->root))
		  {
		    Window root;
		    Window *children;
		    unsigned int nchildren;

		    parent = new_parent;
		    NSLog(@"QueryTree window is %d (root %d cwin root %d)", 
			  parent, root, cWin->root);
		    if (!XQueryTree(dpy, parent, &root, &new_parent, 
		      &children, &nchildren))
		      {
			new_parent = None;
			if (children)
			  {
			    NSLog(@"Bad pointer from failed X call?");
			    children = 0;
			  }
		      }
		    if (children)
		      {
			XFree(children);
		      }
		    if (new_parent && new_parent != cWin->root)
		      {
			XWindowAttributes	pattr;

			XGetWindowAttributes(dpy, parent, &pattr);
			l += pattr.x + pattr.border_width;
			t += pattr.y + pattr.border_width;
			r = pattr.width + pattr.border_width * 2;
			b = pattr.height + pattr.border_width * 2;
		      }
		  } /* while */
		r -= (cWin->xframe.size.width + l);
		b -= (cWin->xframe.size.height + t);
	      } /* generic.flags.doubleParentWindow */

	    o = generic.offsets + (cWin->win_attrs.window_style & 15);
	    if (o->known == NO)
	      {
	        o->l = l;
	        o->r = r;
	        o->t = t;
	        o->b = b;
		o->known = YES;
		/* FIXME: if offsets have changed, from previously guessed
		 * versions, we should go through window list and fix up
		 * hints.
		 */
	      }
	    else
	      {
	        BOOL	changed = NO;

	        if (l != o->l)
		  {
		    NSLog(@"Ignore left offset change from %d to %d",
		      (int)o->l, (int)l);
		    changed = YES;
		  }
	        if (r != o->r)
		  {
		    NSLog(@"Ignore right offset change from %d to %d",
		      (int)o->r, (int)r);
		    changed = YES;
		  }
	        if (t != o->t)
		  {
		    NSLog(@"Ignore top offset change from %d to %d",
		      (int)o->t, (int)t);
		    changed = YES;
		  }
	        if (b != o->b)
		  {
		    NSLog(@"Ignore bottom offset change from %d to %d",
		      (int)o->b, (int)b);
		    changed = YES;
		  }
		if (changed == YES)
		  {
		    NSLog(@"Reparent was with offset %d %d\n",
		      xEvent.xreparent.x, xEvent.xreparent.y);
		    NSLog(@"Parent border,width,height %d,%d,%d\n",
		      wattr.border_width, wattr.width, wattr.height);
		  }
	      }

	  }
	break;

	    // another client attempts to change the size of a window
      case ResizeRequest:
        NSDebugLLog(@"NSEvent", @"%d ResizeRequest\n",
                    xEvent.xresizerequest.window);
        break;

	    // events dealing with the selection
      case SelectionClear:
        NSDebugLLog(@"NSEvent", @"%d SelectionClear\n",
                    xEvent.xselectionclear.window);
        break;

      case SelectionNotify:
        NSDebugLLog(@"NSEvent", @"%d SelectionNotify\n",
                    xEvent.xselection.requestor);
        break;

      case SelectionRequest:
        NSDebugLLog(@"NSEvent", @"%d SelectionRequest\n",
                    xEvent.xselectionrequest.requestor);
        {
          NSPasteboard *pb = [NSPasteboard pasteboardWithName: NSDragPboard];
          NSArray *types = [pb types];
          NSData *data = nil;
          Atom xType = xEvent.xselectionrequest.target;
          static Atom XG_UTF8_STRING = None;
          static Atom XG_TEXT = None;

          if (XG_UTF8_STRING == None)
            {
              XG_UTF8_STRING = XInternAtom(dpy, "UTF8_STRING", False);
              XG_TEXT = XInternAtom(dpy, "TEXT", False);
            }

          if (((xType == XG_UTF8_STRING) || 
               (xType == XA_STRING) || 
               (xType == XG_TEXT)) &&
              [types containsObject: NSStringPboardType])
            {
              NSString *s = [pb stringForType: NSStringPboardType];

              if (xType == XG_UTF8_STRING)
                {
                  data = [s dataUsingEncoding: NSUTF8StringEncoding];
                }
              else if ((xType == XA_STRING) || (xType == XG_TEXT))
                {
                  data = [s dataUsingEncoding: NSISOLatin1StringEncoding];
                }
            }
          // FIXME: Add support for more types. See: xpbs.m

          if (data != nil)
            {
              DndClass dnd = xdnd();

              // Send the data to the other process
              xdnd_selection_send(&dnd, &xEvent.xselectionrequest, 
                                  (unsigned char *)[data bytes], [data length]);	
            }
        }
        break;

	    // We shouldn't get here unless we forgot to trap an event above
      default:
#ifdef XSHM
	if (xEvent.type == XShmGetEventBase(dpy)+ShmCompletion
	    && [gcontext respondsToSelector: @selector(gotShmCompletion:)])
	  {
	    [gcontext gotShmCompletion: 
			((XShmCompletionEvent *)&xEvent)->drawable];
	    break;
	  }
#endif
	NSLog(@"Received an untrapped event\n");
	break;
    }
  if (e)
    {
      [event_queue addObject: e];
    }
  e = nil;
}

/*
 * WM is asking us to take the keyboard focus
 */
- (NSEvent *)_handleTakeFocusAtom: (XEvent)xEvent 
                       forContext: (NSGraphicsContext *)gcontext
{
  int key_num;
  NSWindow *key_win;
  NSEvent *e = nil;
  key_win = [NSApp keyWindow];
  key_num = [key_win windowNumber];
  NSDebugLLog(@"Focus", @"take focus:%d (current=%d key=%d)",
	      cWin->number, generic.currentFocusWindow, key_num);

  /* Sometimes window managers lose the setinputfocus on the key window
   * e.g. when ordering out a window with focus then ordering in the key window.   
   * it might search for a window until one accepts its take focus request.
   */
  if (key_num == cWin->number)
    cWin->ignore_take_focus = NO;
  
  /* Invalidate the previous request. It's possible the app lost focus
     before this request was fufilled and we are being focused again,
     or ??? */
  {
    generic.focusRequestNumber = 0;
    generic.desiredFocusWindow = 0;
  }
  /* We'd like to send this event directly to the front-end to handle,
     but the front-end polls events so slowly compared the speed at
     which X events could potentially come that we could easily get
     out of sync, particularly when there are a lot of window
     events */
  if ([NSApp isHidden])
    {
      /* This often occurs when hidding an app, since a bunch of
	 windows get hidden at once, and the WM is searching for a
	 window to take focus after each one gets hidden. */
      NSDebugLLog(@"Focus", @"WM take focus while hiding");
    }
  else if (cWin->ignore_take_focus == YES)
    {
      NSDebugLLog(@"Focus", @"Ignoring window focus request");
      cWin->ignore_take_focus = NO;
    }
  else if (cWin->number == key_num)
    {
      NSDebugLLog(@"Focus", @"Reasserting key window");
      [GSServerForWindow(key_win) setinputfocus: key_num];
    }
  else if (key_num 
	   && cWin->number == [[[NSApp mainMenu] window] windowNumber])
    {
      /* This might occur when the window manager just wants someone
	 to become key, so it tells the main menu (typically the first
	 menu in the list), but since we already have a window that
	 was key before, use that instead */
      NSDebugLLog(@"Focus", @"Key window is already %d", key_num);
      [GSServerForWindow(key_win) setinputfocus: key_num];
    }
  else
    {
      NSPoint eventLocation;
      /*
       * Here the app asked for this (if key_win==nil) or there was a
       * click on the title bar or some other reason (window mapped,
       * etc). We don't necessarily want to forward the event for the
       * last reason but we just have to deal with that since we can
       * never be sure if it's necessary.
       */
      eventLocation = NSMakePoint(0,0);
      e = [NSEvent otherEventWithType:NSAppKitDefined
		   location: eventLocation
		   modifierFlags: 0
		   timestamp: 0
		   windowNumber: cWin->number
		   context: gcontext
		   subtype: GSAppKitWindowFocusIn
		   data1: 0
		   data2: 0];
    }
  return e;
}


// Return the key_sym corresponding to the user defaults string given,
// or fallback if no default is registered.
static KeySym
key_sym_from_defaults (Display *display, NSUserDefaults *defaults,
                       NSString *keyDefaultKey, KeySym fallback)
{
  NSString *keyDefaultName;
  KeySym key_sym;

  keyDefaultName = [defaults stringForKey: keyDefaultKey];
  if (keyDefaultName == nil)
    return fallback;

  key_sym = XStringToKeysym ([keyDefaultName cString]);
#if 0
  if (key_sym == NoSymbol && [keyDefaultName intValue] > 0)
    {
      key_sym = [keyDefaultName intValue];
    }
#endif
  if (key_sym == NoSymbol)
    {
      // This is not necessarily an error.
      // If you want on purpose to disable a key, 
      // set its default to 'NoSymbol'.
      NSLog (@"KeySym %@ not found; disabling %@", keyDefaultName,
                                                   keyDefaultKey);
    }

  return key_sym;
}

// This function should be called before any keyboard event is dealed with.
static void
initialize_keyboard (void)
{
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  Display *display = [XGServer currentXDisplay];

  // Below must be stored and checked as keysyms, not keycodes, since
  // more than one keycode may be mapped t the same keysym
  // Initialize Control
  _control_keysyms[0] = key_sym_from_defaults(display, defaults,
                                              @"GSFirstControlKey",
                                              XK_Control_L);

  _control_keysyms[1] = key_sym_from_defaults(display, defaults,
                                              @"GSSecondControlKey",
                                              XK_Control_R);

  if (_control_keysyms[0] == _control_keysyms[1])
    _control_keysyms[1] = NoSymbol;

  // Initialize Command
  _command_keysyms[0] = key_sym_from_defaults(display, defaults,
                                              @"GSFirstCommandKey",
                                              XK_Alt_L);

  _command_keysyms[1] = key_sym_from_defaults(display, defaults,
                                              @"GSSecondCommandKey",
                                              NoSymbol);

  if (_command_keysyms[0] == _command_keysyms[1])
    _command_keysyms[1] = NoSymbol;

  // Initialize Alt
  _alt_keysyms[0] = key_sym_from_defaults(display, defaults,
                                          @"GSFirstAlternateKey",
                                          XK_Alt_R);
  if (XKeysymToKeycode(display, _alt_keysyms[0]) == 0)
    _alt_keysyms[0] = XK_Mode_switch;

  _alt_keysyms[1] = key_sym_from_defaults(display, defaults,
                                          @"GSSecondAlternateKey",
                                          NoSymbol);

  if (_alt_keysyms[0] == _alt_keysyms[1])
    _alt_keysyms[1] = NoSymbol;

  // Initialize Help
  _help_keysyms[0] = key_sym_from_defaults(display, defaults,
                                          @"GSFirstHelpKey",
                                          XK_Help);
  if (XKeysymToKeycode(display, _help_keysyms[0]) == 0)
    _help_keysyms[0] = NoSymbol;

  _help_keysyms[1] = key_sym_from_defaults(display, defaults,
                                          @"GSSecondHelpKey",
                                          XK_Super_L);

  if (_help_keysyms[0] == _help_keysyms[1])
    _help_keysyms[1] = NoSymbol;

  
  set_up_num_lock ();
  _mod_ignore_shift = [defaults boolForKey: @"GSModifiersAreKeys"];
  
  _is_keyboard_initialized = YES;
}


static void
set_up_num_lock (void)
{
  XModifierKeymap *modifier_map;
  int i, j;
  unsigned int modifier_masks[8] = 
  {
    ShiftMask, LockMask, ControlMask, Mod1Mask, 
    Mod2Mask, Mod3Mask, Mod4Mask, Mod5Mask
  };
  Display *display = [XGServer currentXDisplay];
  KeyCode _num_lock_keycode;
  
  // Get NumLock keycode
  _num_lock_keycode = XKeysymToKeycode (display, XK_Num_Lock);
  if (_num_lock_keycode == 0)
    {
      // Weird.  There is no NumLock in this keyboard.
      _num_lock_mask = 0; 
      return;
    }

  // Get the current modifier mapping
  modifier_map = XGetModifierMapping (display);
  
  // Scan the modifiers for NumLock
  for (j = 0; j < 8; j++)
    for (i = 0; i < (modifier_map->max_keypermod); i++)
      {
	if ((modifier_map->modifiermap)[i + j*modifier_map->max_keypermod] 
	  == _num_lock_keycode)
	  {
	    _num_lock_mask = modifier_masks[j];
	    XFreeModifiermap (modifier_map);
	    return;
	  }
      }
  // Weird.  NumLock is not among the modifiers
  _num_lock_mask = 0;
  XFreeModifiermap (modifier_map);
  return;
}

static BOOL
keysym_is_X_modifier (KeySym keysym)
{
  switch (keysym)
    {
    case XK_Num_Lock: 
    case XK_Shift_L:    
    case XK_Shift_R:    
    case XK_Caps_Lock:  
    case XK_Shift_Lock: 
      return YES;

    default:
      return NO;
    }
}

static NSEvent*
process_key_event (XEvent* xEvent, XGServer* context, NSEventType eventType,
  NSMutableArray *event_queue)
{
  NSString	*keys, *ukeys;
  KeySym	keysym;
  NSPoint	eventLocation;
  unsigned short keyCode;
  unsigned int	eventFlags;
  unichar       unicode;
  NSEvent	*event = nil;
  NSEventType   originalType;
  gswindow_device_t *window;
  int		control_key = 0;
  int		command_key = 0;
  int		alt_key = 0;
  int		help_key = 0;
  KeySym	modKeysym;  // process modifier independently of shift, etc.
  
  if (_is_keyboard_initialized == NO)
    initialize_keyboard ();

  /* Process location */
  window = [XGServer _windowWithTag: [[NSApp keyWindow] windowNumber]];
  if (window != 0)
    {
      eventLocation.x = xEvent->xbutton.x;
      eventLocation.y = xEvent->xbutton.y;
      eventLocation = [context _XPointToOSPoint: eventLocation
					    for: window];
    }
    
  /* Process characters */
  keys = [context->inputServer lookupStringForEvent: (XKeyEvent *)xEvent
		 window: window
		 keysym: &keysym];

  /* Process keycode */
  keyCode = ((XKeyEvent *)xEvent)->keycode;
  //ximKeyCode = XKeysymToKeycode([XGServer currentXDisplay],keysym);

  /* Process NSFlagsChanged events.  We can't use a switch because we
     are not comparing to constants. Make sure keySym is not NoSymbol since
     XIM events can potentially return this. */
  /* Possibly ignore shift/other modifier state in determining KeySym to
     work around correct but undesired behavior with shifted modifiers.
     See Back defaults documentation for "GSModifiersAreKeys". */
  modKeysym = (_mod_ignore_shift == YES) ?
      XLookupKeysym((XKeyEvent *)xEvent, 0) : keysym;
  if (modKeysym != NoSymbol)
    {
      if (modKeysym == _control_keysyms[0]) 
	{
	  control_key = 1;
	}
      else if (modKeysym == _control_keysyms[1])
	{
	  control_key = 2;
	}
      else if (modKeysym == _command_keysyms[0]) 
	{
	  command_key = 1;
	}
      else if (modKeysym == _command_keysyms[1]) 
	{
	  command_key = 2;
	}
      else if (modKeysym == _alt_keysyms[0]) 
	{
	  alt_key = 1;
	}
      else if (modKeysym == _alt_keysyms[1]) 
	{
	  alt_key = 2;
	}
      else if (modKeysym == _help_keysyms[0]) 
	{
	  help_key = 1;
	}
      else if (modKeysym == _help_keysyms[1]) 
	{
	  help_key = 2;
	}
    }

  originalType = eventType;
  if (control_key || command_key || alt_key || help_key)
    {
      eventType = NSFlagsChanged;
      if (xEvent->xkey.type == KeyPress)
	{
	  if (control_key)
	    _control_pressed |= control_key;
	  if (command_key)
	    _command_pressed |= command_key;
	  if (alt_key)
	    _alt_pressed |= alt_key;
	  if (help_key)
	    _help_pressed |= help_key;
	}
      else if (xEvent->xkey.type == KeyRelease)
	{
	  if (control_key)
	    _control_pressed &= ~control_key;
	  if (command_key)
	    _command_pressed &= ~command_key;
	  if (alt_key)
	    _alt_pressed &= ~alt_key;
	  if (help_key)
	    _help_pressed &= ~help_key;
	}
    }

  /* Process modifiers */
  eventFlags = process_modifier_flags (xEvent->xkey.state);

  /* Add NSNumericPadKeyMask if the key is in the KeyPad */
  if (IsKeypadKey (keysym))
    eventFlags = eventFlags | NSNumericPadKeyMask;

  NSDebugLLog (@"NSKeyEvent", @"keysym=%d, keyCode=%d flags=%d (state=%d)",
	      keysym, keyCode, eventFlags, ((XKeyEvent *)xEvent)->state);
  
  /* Add NSFunctionKeyMask if the key is a function or a misc function key */
  /* We prefer not to do this and do it manually in process_char
     because X's idea of what is a function key seems to be different
     from OPENSTEP's one */
  /* if (IsFunctionKey (keysym) || IsMiscFunctionKey (keysym))
       eventFlags = eventFlags | NSFunctionKeyMask; */

  /* First, check to see if the key event if a Shift, NumLock or
     CapsLock or ShiftLock keypress/keyrelease.  If it is, then use a
     NSFlagsChanged event type.  This will generate a NSFlagsChanged
     event each time you press/release a shift key, even if the flags
     haven't actually changed.  I don't see this as a problem - if we
     didn't, the shift keypress/keyrelease event would never be
     notified to the application.

     NB - to know if shift was pressed, we need to check the X keysym
     - it doesn't work to compare the X modifier flags of this
     keypress X event with the ones of the previous one, because when
     you press Shift, the X shift keypress event has the *same* X
     modifiers flags as the X keypress event before it - only
     keypresses coming *after* the shift keypress will get a different
     X modifier mask.  */
  if (keysym_is_X_modifier (keysym))
    {
      eventType = NSFlagsChanged;
    }

  if (help_key)
    {
      unicode = NSHelpFunctionKey;
      keys = [NSString stringWithCharacters: &unicode  length: 1];
      if (originalType == NSKeyDown)
        {
	  event = [NSEvent keyEventWithType: NSKeyDown
		   location: eventLocation
		   modifierFlags: eventFlags
		   timestamp: (NSTimeInterval)xEvent->xkey.time / 1000.0
		   windowNumber: window->number
		   context: GSCurrentContext()
		   characters: keys
		   charactersIgnoringModifiers: keys
		   isARepeat: NO
		   keyCode: keyCode];
	  [event_queue addObject: event];
	  event = [NSEvent keyEventWithType: NSFlagsChanged
		   location: eventLocation
		   modifierFlags: eventFlags
		   timestamp: (NSTimeInterval)xEvent->xkey.time / 1000.0
		   windowNumber: window->number
		   context: GSCurrentContext()
		   characters: keys
		   charactersIgnoringModifiers: keys
		   isARepeat: NO
		   keyCode: keyCode];
	  return event;
	}
      else
        {
	  event = [NSEvent keyEventWithType: NSFlagsChanged
		   location: eventLocation
		   modifierFlags: eventFlags
		   timestamp: (NSTimeInterval)xEvent->xkey.time / 1000.0
		   windowNumber: window->number
		   context: GSCurrentContext()
		   characters: keys
		   charactersIgnoringModifiers: keys
		   isARepeat: NO
		   keyCode: keyCode];
	  [event_queue addObject: event];
	  event = [NSEvent keyEventWithType: NSKeyUp
		   location: eventLocation
		   modifierFlags: eventFlags
		   timestamp: (NSTimeInterval)xEvent->xkey.time / 1000.0
		   windowNumber: window->number
		   context: GSCurrentContext()
		   characters: keys
		   charactersIgnoringModifiers: keys
		   isARepeat: NO
		   keyCode: keyCode];
	  return event;
	}
    }
  else
    {
      /* Now we get the unicode character for the pressed key using our
       * internal table.
       */
      unicode = process_char (keysym, &eventFlags);

      /* If that didn't work, we use what X gave us */
      if (unicode != 0)
	{
	  keys = [NSString stringWithCharacters: &unicode  length: 1];
	}

      // Now the same ignoring modifiers, except Shift, ShiftLock, NumLock.
      xEvent->xkey.state = (xEvent->xkey.state & (ShiftMask | LockMask 
						  | _num_lock_mask));
      ukeys = [context->inputServer lookupStringForEvent: (XKeyEvent *)xEvent
		      window: window
		      keysym: &keysym];
      unicode = process_char (keysym, &eventFlags);
      if (unicode != 0)
	{
	  ukeys = [NSString stringWithCharacters: &unicode  length: 1];
	}

      event = [NSEvent keyEventWithType: eventType
		   location: eventLocation
		   modifierFlags: eventFlags
		   timestamp: (NSTimeInterval)xEvent->xkey.time / 1000.0
		   windowNumber: window->number
		   context: GSCurrentContext()
		   characters: keys
		   charactersIgnoringModifiers: ukeys
		   isARepeat: NO /* isARepeat can't be supported with X */
		   keyCode: keyCode];

      return event;
    }
}

static unichar 
process_char (KeySym keysym, unsigned *eventModifierFlags)
{
  switch (keysym)
    {
      /* NB: Whatever is explicitly put in this conversion table takes
	 precedence over what is returned by XLookupString.  Not sure
	 this is a good idea for latin-1 character input. */
    case XK_Return:       return NSCarriageReturnCharacter;
    case XK_KP_Enter:     return NSEnterCharacter;
    case XK_Linefeed:     return NSFormFeedCharacter;
    case XK_Tab:          return NSTabCharacter;
#ifdef XK_XKB_KEYS
    case XK_ISO_Left_Tab: return NSTabCharacter;
#endif
      /* FIXME: The following line ? */
    case XK_Escape:       return 0x1b;
    case XK_BackSpace:    return NSBackspaceKey;

      /* The following keys need to be reported as function keys */
#define XGPS_FUNCTIONKEY \
*eventModifierFlags = *eventModifierFlags | NSFunctionKeyMask;

    case XK_F1:           XGPS_FUNCTIONKEY return NSF1FunctionKey;
    case XK_F2:           XGPS_FUNCTIONKEY return NSF2FunctionKey;
    case XK_F3:           XGPS_FUNCTIONKEY return NSF3FunctionKey;
    case XK_F4:           XGPS_FUNCTIONKEY return NSF4FunctionKey;
    case XK_F5:           XGPS_FUNCTIONKEY return NSF5FunctionKey;
    case XK_F6:           XGPS_FUNCTIONKEY return NSF6FunctionKey;
    case XK_F7:           XGPS_FUNCTIONKEY return NSF7FunctionKey;
    case XK_F8:           XGPS_FUNCTIONKEY return NSF8FunctionKey;
    case XK_F9:           XGPS_FUNCTIONKEY return NSF9FunctionKey;
    case XK_F10:          XGPS_FUNCTIONKEY return NSF10FunctionKey;
    case XK_F11:          XGPS_FUNCTIONKEY return NSF11FunctionKey;
    case XK_F12:          XGPS_FUNCTIONKEY return NSF12FunctionKey;
    case XK_F13:          XGPS_FUNCTIONKEY return NSF13FunctionKey;
    case XK_F14:          XGPS_FUNCTIONKEY return NSF14FunctionKey;
    case XK_F15:          XGPS_FUNCTIONKEY return NSF15FunctionKey;
    case XK_F16:          XGPS_FUNCTIONKEY return NSF16FunctionKey;
    case XK_F17:          XGPS_FUNCTIONKEY return NSF17FunctionKey;
    case XK_F18:          XGPS_FUNCTIONKEY return NSF18FunctionKey;
    case XK_F19:          XGPS_FUNCTIONKEY return NSF19FunctionKey;
    case XK_F20:          XGPS_FUNCTIONKEY return NSF20FunctionKey;
    case XK_F21:          XGPS_FUNCTIONKEY return NSF21FunctionKey;
    case XK_F22:          XGPS_FUNCTIONKEY return NSF22FunctionKey;
    case XK_F23:          XGPS_FUNCTIONKEY return NSF23FunctionKey;
    case XK_F24:          XGPS_FUNCTIONKEY return NSF24FunctionKey;
    case XK_F25:          XGPS_FUNCTIONKEY return NSF25FunctionKey;
    case XK_F26:          XGPS_FUNCTIONKEY return NSF26FunctionKey;
    case XK_F27:          XGPS_FUNCTIONKEY return NSF27FunctionKey;
    case XK_F28:          XGPS_FUNCTIONKEY return NSF28FunctionKey;
    case XK_F29:          XGPS_FUNCTIONKEY return NSF29FunctionKey;
    case XK_F30:          XGPS_FUNCTIONKEY return NSF30FunctionKey;
    case XK_F31:          XGPS_FUNCTIONKEY return NSF31FunctionKey;
    case XK_F32:          XGPS_FUNCTIONKEY return NSF32FunctionKey;
    case XK_F33:          XGPS_FUNCTIONKEY return NSF33FunctionKey;
    case XK_F34:          XGPS_FUNCTIONKEY return NSF34FunctionKey;
    case XK_F35:          XGPS_FUNCTIONKEY return NSF35FunctionKey;
    case XK_Delete:       XGPS_FUNCTIONKEY return NSDeleteFunctionKey;
    case XK_Home:         XGPS_FUNCTIONKEY return NSHomeFunctionKey;  
    case XK_Left:         XGPS_FUNCTIONKEY return NSLeftArrowFunctionKey;
    case XK_Right:        XGPS_FUNCTIONKEY return NSRightArrowFunctionKey;
    case XK_Up:           XGPS_FUNCTIONKEY return NSUpArrowFunctionKey;  
    case XK_Down:         XGPS_FUNCTIONKEY return NSDownArrowFunctionKey;
//  case XK_Prior:        XGPS_FUNCTIONKEY return NSPrevFunctionKey;
//  case XK_Next:         XGPS_FUNCTIONKEY return NSNextFunctionKey;
    case XK_End:          XGPS_FUNCTIONKEY return NSEndFunctionKey; 
    case XK_Begin:        XGPS_FUNCTIONKEY return NSBeginFunctionKey;
    case XK_Select:       XGPS_FUNCTIONKEY return NSSelectFunctionKey;
    case XK_Print:        XGPS_FUNCTIONKEY return NSPrintFunctionKey;  
    case XK_Execute:      XGPS_FUNCTIONKEY return NSExecuteFunctionKey;
    case XK_Insert:       XGPS_FUNCTIONKEY return NSInsertFunctionKey; 
    case XK_Undo:         XGPS_FUNCTIONKEY return NSUndoFunctionKey;
    case XK_Redo:         XGPS_FUNCTIONKEY return NSRedoFunctionKey;
    case XK_Menu:         XGPS_FUNCTIONKEY return NSMenuFunctionKey;
    case XK_Find:         XGPS_FUNCTIONKEY return NSFindFunctionKey;
    case XK_Help:         XGPS_FUNCTIONKEY return NSHelpFunctionKey;
    case XK_Break:        XGPS_FUNCTIONKEY return NSBreakFunctionKey;
    case XK_Mode_switch:  XGPS_FUNCTIONKEY return NSModeSwitchFunctionKey;
    case XK_Scroll_Lock:  XGPS_FUNCTIONKEY return NSScrollLockFunctionKey;
    case XK_Pause:        XGPS_FUNCTIONKEY return NSPauseFunctionKey;
    case XK_Clear:        XGPS_FUNCTIONKEY return NSClearDisplayFunctionKey;
#ifndef NeXT
    case XK_Page_Up:      XGPS_FUNCTIONKEY return NSPageUpFunctionKey;
    case XK_Page_Down:    XGPS_FUNCTIONKEY return NSPageDownFunctionKey;
    case XK_Sys_Req:      XGPS_FUNCTIONKEY return NSSysReqFunctionKey;  
#endif
    case XK_KP_F1:        XGPS_FUNCTIONKEY return NSF1FunctionKey;
    case XK_KP_F2:        XGPS_FUNCTIONKEY return NSF2FunctionKey;
    case XK_KP_F3:        XGPS_FUNCTIONKEY return NSF3FunctionKey;
    case XK_KP_F4:        XGPS_FUNCTIONKEY return NSF4FunctionKey;
#ifndef NeXT
    case XK_KP_Home:      XGPS_FUNCTIONKEY return NSHomeFunctionKey;
    case XK_KP_Left:      XGPS_FUNCTIONKEY return NSLeftArrowFunctionKey;
    case XK_KP_Up:        XGPS_FUNCTIONKEY return NSUpArrowFunctionKey;  
    case XK_KP_Right:     XGPS_FUNCTIONKEY return NSRightArrowFunctionKey;
    case XK_KP_Down:      XGPS_FUNCTIONKEY return NSDownArrowFunctionKey; 
//  case XK_KP_Prior:     return NSPrevFunctionKey;      
    case XK_KP_Page_Up:   XGPS_FUNCTIONKEY return NSPageUpFunctionKey;    
//  case XK_KP_Next:      return NSNextFunctionKey;      
    case XK_KP_Page_Down: XGPS_FUNCTIONKEY return NSPageDownFunctionKey;  
    case XK_KP_End:       XGPS_FUNCTIONKEY return NSEndFunctionKey;       
    case XK_KP_Begin:     XGPS_FUNCTIONKEY return NSBeginFunctionKey;     
    case XK_KP_Insert:    XGPS_FUNCTIONKEY return NSInsertFunctionKey;    
    case XK_KP_Delete:    XGPS_FUNCTIONKEY return NSDeleteFunctionKey;    
#endif
#undef XGPS_FUNCTIONKEY
    default:              return 0;
    }
}

// process_modifier_flags() determines which modifier keys (Command, Control,
// Shift,  and so forth) were held down while the event occured.
static unsigned int
process_modifier_flags(unsigned int state)
{
  unsigned int eventModifierFlags = 0;

  if (state & ShiftMask)
    eventModifierFlags = eventModifierFlags | NSShiftKeyMask;

  if (state & LockMask)
    eventModifierFlags = eventModifierFlags | NSAlphaShiftKeyMask;

  if (_control_pressed != 0)
    eventModifierFlags = eventModifierFlags | NSControlKeyMask;

  if (_command_pressed != 0)
    eventModifierFlags = eventModifierFlags | NSCommandKeyMask;

  if (_alt_pressed != 0)
    eventModifierFlags = eventModifierFlags | NSAlternateKeyMask;
  
  if (_help_pressed != 0)
    eventModifierFlags = eventModifierFlags | NSHelpKeyMask;
  
  // Other modifiers ignored for now. 

  return eventModifierFlags;
}


- (NSDate*) timedOutEvent: (void*)data
                     type: (RunLoopEventType)type
                  forMode: (NSString*)mode
{
  return nil;
}

/* Drag and Drop */
- (id <NSDraggingInfo>)dragInfo
{
  return [XGDragView sharedDragView];
}

@end

@implementation XGServer (XSync)
- (BOOL) xSyncMap: (void*)windowHandle
{
  gswindow_device_t	*window = (gswindow_device_t*)windowHandle;

  /*
   * if the window is not mapped, make sure we have sent all requests to the
   * X-server, it may be that our mapping request was buffered.
   */
  if (window->map_state != IsViewable)
    {
      XSync(dpy, False);
      [self receivedEvent: 0 type: 0 extra: 0 forMode: nil];
    }
  /*
   * If the window is still not mapped, it may be that the window-manager
   * intercepted our mapping request, and hasn't dealt with it yet.
   * Listen for input for up to a second, in the hope of getting the mapping.
   */
  if (window->map_state != IsViewable)
    {
      NSDate	*d = [NSDate dateWithTimeIntervalSinceNow: 1.0];
      NSRunLoop	*l = [NSRunLoop currentRunLoop];
      NSString	*m = [l currentMode];

      while (window->map_state != IsViewable && [d timeIntervalSinceNow] > 0)
        {
	  [l runMode: m beforeDate: d];
	}
    }
  if (window->map_state != IsViewable)
    {
      NSLog(@"Window still not mapped a second after mapping request made");
      return NO;
    }
  return YES;
}
@end

@implementation XGServer (X11Ops)

/*
 * Return mouse location in base coords ignoring the event loop
 */
- (NSPoint) mouselocation
{
  return [self mouseLocationOnScreen: defScreen window: NULL];
}

- (NSPoint) mouseLocationOnScreen: (int)screen window: (int *)win
{
  Window	rootWin;
  Window	childWin;
  int		currentX;
  int		currentY;
  int		winX;
  int		winY;
  unsigned	mask;
  BOOL		ok;
  NSPoint       p;
  int           height;
  int           screen_number;
  
  screen_number = (screen >= 0) ? screen : defScreen;
  ok = XQueryPointer (dpy, [self xDisplayRootWindowForScreen: screen_number],
    &rootWin, &childWin, &currentX, &currentY, &winX, &winY, &mask);
  p = NSMakePoint(-1,-1);
  if (ok == False)
    {
      /* Mouse not on the specified screen_number */
      XWindowAttributes attribs;
      ok = XGetWindowAttributes(dpy, rootWin, &attribs);
      if (ok == False)
	{
	  return p;
	}
      screen_number = XScreenNumberOfScreen(attribs.screen);
      if (screen >= 0 && screen != screen_number)
	{
	  /* Mouse not on the requred screen, return an invalid point */
	  return p;
	}
      height = attribs.height;
    }
  else
    height = DisplayHeight(dpy, screen_number);
  p = NSMakePoint(currentX, height - currentY);
  if (win)
    {
      gswindow_device_t *w = 0;
      w = [XGServer _windowForXWindow: childWin];
      if (w == NULL)
	w = [XGServer _windowForXParent: childWin];
      if (w)
	*win = w->number;
      else
	*win = 0;
    }
  return p;
}

- (NSEvent*) getEventMatchingMask: (unsigned)mask
		       beforeDate: (NSDate*)limit
			   inMode: (NSString*)mode
			  dequeue: (BOOL)flag
{
  [self receivedEvent: 0 type: 0 extra: 0 forMode: nil];
  return [super getEventMatchingMask: mask
			  beforeDate: limit
			      inMode: mode
			     dequeue: flag];
}

- (void) discardEventsMatchingMask: (unsigned)mask
		       beforeEvent: (NSEvent*)limit
{
  [self receivedEvent: 0 type: 0 extra: 0 forMode: nil];
  [super discardEventsMatchingMask: mask
		       beforeEvent: limit];
}

@end

@implementation XGServer (TimeKeeping)
// Sync time with X server every 10 seconds
#define MAX_TIME_DIFF 10
// Regard an X time stamp as valid for half a second
#define OUT_DATE_TIME_DIFF 0.5

- (void) setLastTime: (Time)last
{
  if (generic.lastTimeStamp == 0 
      || generic.baseXServerTime + MAX_TIME_DIFF * 1000 < last)
    {
      // We have not sync'ed with the clock for at least
      // MAX_TIME_DIFF seconds ... so we do it now.
      generic.lastTimeStamp = [NSDate timeIntervalSinceReferenceDate];
      generic.baseXServerTime = last;
    }
  else
    {
      // Optimisation to compute the new time stamp instead.
      generic.lastTimeStamp += (last - generic.lastTime) / 1000.0;
    }

  generic.lastTime = last;
}

- (Time) lastTime
{
  // In the case of activation via DO the lastTime is outdated and cannot be used.
  if (generic.lastTimeStamp == 0 
      || ((generic.lastTimeStamp + OUT_DATE_TIME_DIFF)
          < [NSDate timeIntervalSinceReferenceDate]))
    {
      return CurrentTime;
    }
  else
    {
      return generic.lastTime;
    }
}

@end