Welcome to mirror list, hosted at ThFree Co, Russian Federation.

GHOST_SystemX11.cpp « intern « ghost « intern - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 9b6d48c5993a5c826baccfb972e5e2a9a7d45cc7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
/*
 * ***** BEGIN GPL LICENSE BLOCK *****
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
 * All rights reserved.
 *
 * The Original Code is: all of this file.
 *
 * Contributor(s): none yet.
 *
 * Part of this code has been taken from Qt, under LGPL license
 * Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
 *
 * ***** END GPL LICENSE BLOCK *****
 */

/** \file ghost/intern/GHOST_SystemX11.cpp
 *  \ingroup GHOST
 */

#include "GHOST_SystemX11.h"
#include "GHOST_WindowX11.h"
#include "GHOST_WindowManager.h"
#include "GHOST_TimerManager.h"
#include "GHOST_EventCursor.h"
#include "GHOST_EventKey.h"
#include "GHOST_EventButton.h"
#include "GHOST_EventWheel.h"
#include "GHOST_DisplayManagerX11.h"
#include "GHOST_EventDragnDrop.h"
#ifdef WITH_INPUT_NDOF
#  include "GHOST_NDOFManagerX11.h"
#endif

#ifdef WITH_XDND
#  include "GHOST_DropTargetX11.h"
#endif

#include "GHOST_Debug.h"

#include <X11/Xatom.h>
#include <X11/keysym.h>
#include <X11/XKBlib.h> /* allow detectable autorepeate */
#include <X11/Xutil.h>

#ifdef WITH_XF86KEYSYM
#include <X11/XF86keysym.h>
#endif

/* For timing */
#include <sys/time.h>
#include <unistd.h>

#include <iostream>
#include <vector>
#include <stdio.h> /* for fprintf only */
#include <cstdlib> /* for exit */

/* for debugging - so we can breakpoint X11 errors */
// #define USE_X11_ERROR_HANDLERS

/* see [#34039] Fix Alt key glitch on Unity desktop */
#define USE_UNITY_WORKAROUND

static GHOST_TKey convertXKey(KeySym key);

/* these are for copy and select copy */
static char *txt_cut_buffer = NULL;
static char *txt_select_buffer = NULL;

using namespace std;

GHOST_SystemX11::
GHOST_SystemX11(
    ) :
	GHOST_System(),
	m_start_time(0)
{
	m_display = XOpenDisplay(NULL);
	
	if (!m_display) {
		std::cerr << "Unable to open a display" << std::endl;
		abort(); /* was return before, but this would just mean it will crash later */
	}

#ifdef USE_X11_ERROR_HANDLERS
	(void) XSetErrorHandler(GHOST_X11_ApplicationErrorHandler);
	(void) XSetIOErrorHandler(GHOST_X11_ApplicationIOErrorHandler);
#endif

#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
	/* note -- don't open connection to XIM server here, because the locale
	 * has to be set before opening the connection but setlocale() has not
	 * been called yet.  the connection will be opened after entering
	 * the event loop. */
	m_xim = NULL;
#endif

#define GHOST_INTERN_ATOM_IF_EXISTS(atom) { m_atom.atom = XInternAtom(m_display, #atom , True);  } (void)0
#define GHOST_INTERN_ATOM(atom)           { m_atom.atom = XInternAtom(m_display, #atom , False); } (void)0

	GHOST_INTERN_ATOM_IF_EXISTS(WM_DELETE_WINDOW);
	GHOST_INTERN_ATOM(WM_PROTOCOLS);
	GHOST_INTERN_ATOM(WM_TAKE_FOCUS);
	GHOST_INTERN_ATOM(WM_STATE);
	GHOST_INTERN_ATOM(WM_CHANGE_STATE);
	GHOST_INTERN_ATOM(_NET_WM_STATE);
	GHOST_INTERN_ATOM(_NET_WM_STATE_MAXIMIZED_HORZ);
	GHOST_INTERN_ATOM(_NET_WM_STATE_MAXIMIZED_VERT);

	GHOST_INTERN_ATOM(_NET_WM_STATE_FULLSCREEN);
	GHOST_INTERN_ATOM(_MOTIF_WM_HINTS);
	GHOST_INTERN_ATOM(TARGETS);
	GHOST_INTERN_ATOM(STRING);
	GHOST_INTERN_ATOM(COMPOUND_TEXT);
	GHOST_INTERN_ATOM(TEXT);
	GHOST_INTERN_ATOM(CLIPBOARD);
	GHOST_INTERN_ATOM(PRIMARY);
	GHOST_INTERN_ATOM(XCLIP_OUT);
	GHOST_INTERN_ATOM(INCR);
	GHOST_INTERN_ATOM(UTF8_STRING);
#ifdef WITH_X11_XINPUT
	m_atom.TABLET = XInternAtom(m_display, XI_TABLET, False);
#endif

#undef GHOST_INTERN_ATOM_IF_EXISTS
#undef GHOST_INTERN_ATOM

	m_last_warp = 0;

	/* compute the initial time */
	timeval tv;
	if (gettimeofday(&tv, NULL) == -1) {
		GHOST_ASSERT(false, "Could not instantiate timer!");
	}
	
	/* Taking care not to overflow the tv.tv_sec * 1000 */
	m_start_time = GHOST_TUns64(tv.tv_sec) * 1000 + tv.tv_usec / 1000;
	
	
	/* use detectable autorepeate, mac and windows also do this */
	int use_xkb;
	int xkb_opcode, xkb_event, xkb_error;
	int xkb_major = XkbMajorVersion, xkb_minor = XkbMinorVersion;
	
	use_xkb = XkbQueryExtension(m_display, &xkb_opcode, &xkb_event, &xkb_error, &xkb_major, &xkb_minor);
	if (use_xkb) {
		XkbSetDetectableAutoRepeat(m_display, true, NULL);
	}
	
#ifdef WITH_X11_XINPUT
	/* initialize incase X11 fails to load */
	memset(&m_xtablet, 0, sizeof(m_xtablet));

	initXInputDevices();
#endif
}

GHOST_SystemX11::
~GHOST_SystemX11()
{
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
	if (m_xim) {
		XCloseIM(m_xim);
	}
#endif

#ifdef WITH_X11_XINPUT
	/* close tablet devices */
	if (m_xtablet.StylusDevice)
		XCloseDevice(m_display, m_xtablet.StylusDevice);
	
	if (m_xtablet.EraserDevice)
		XCloseDevice(m_display, m_xtablet.EraserDevice);
#endif /* WITH_X11_XINPUT */

	XCloseDisplay(m_display);
}


GHOST_TSuccess
GHOST_SystemX11::
init()
{
	GHOST_TSuccess success = GHOST_System::init();

	if (success) {
#ifdef WITH_INPUT_NDOF
		m_ndofManager = new GHOST_NDOFManagerX11(*this);
#endif
		m_displayManager = new GHOST_DisplayManagerX11(this);

		if (m_displayManager) {
			return GHOST_kSuccess;
		}
	}

	return GHOST_kFailure;
}

GHOST_TUns64
GHOST_SystemX11::
getMilliSeconds() const
{
	timeval tv;
	if (gettimeofday(&tv, NULL) == -1) {
		GHOST_ASSERT(false, "Could not compute time!");
	}

	/* Taking care not to overflow the tv.tv_sec * 1000 */
	return GHOST_TUns64(tv.tv_sec) * 1000 + tv.tv_usec / 1000 - m_start_time;
}
	
GHOST_TUns8
GHOST_SystemX11::
getNumDisplays() const
{
	return GHOST_TUns8(1);
}

/**
 * Returns the dimensions of the main display on this system.
 * \return The dimension of the main display.
 */
void
GHOST_SystemX11::
getMainDisplayDimensions(
		GHOST_TUns32& width,
		GHOST_TUns32& height) const
{
	if (m_display) {
		/* note, for this to work as documented,
		 * we would need to use Xinerama check r54370 for code that did thia,
		 * we've since removed since its not worth the extra dep - campbell */
		getAllDisplayDimensions(width, height);
	}
}


/**
 * Returns the dimensions of the main display on this system.
 * \return The dimension of the main display.
 */
void
GHOST_SystemX11::
getAllDisplayDimensions(
		GHOST_TUns32& width,
		GHOST_TUns32& height) const
{
	if (m_display) {
		width  = DisplayWidth(m_display, DefaultScreen(m_display));
		height = DisplayHeight(m_display, DefaultScreen(m_display));
	}
}

/**
 * Create a new window.
 * The new window is added to the list of windows managed.
 * Never explicitly delete the window, use disposeWindow() instead.
 * \param	title	The name of the window (displayed in the title bar of the window if the OS supports it).
 * \param	left	The coordinate of the left edge of the window.
 * \param	top		The coordinate of the top edge of the window.
 * \param	width	The width the window.
 * \param	height	The height the window.
 * \param	state	The state of the window when opened.
 * \param	type	The type of drawing context installed in this window.
 * \param	stereoVisual	Stereo visual for quad buffered stereo.
 * \param	exclusive	Use to show the window ontop and ignore others
 *						(used fullscreen).
 * \param	numOfAASamples	Number of samples used for AA (zero if no AA)
 * \param	parentWindow    Parent (embedder) window
 * \return	The new window (or 0 if creation failed).
 */
GHOST_IWindow *
GHOST_SystemX11::
createWindow(
		const STR_String& title,
		GHOST_TInt32 left,
		GHOST_TInt32 top,
		GHOST_TUns32 width,
		GHOST_TUns32 height,
		GHOST_TWindowState state,
		GHOST_TDrawingContextType type,
		const bool stereoVisual,
		const bool exclusive,
		const GHOST_TUns16 numOfAASamples,
		const GHOST_TEmbedderWindowID parentWindow)
{
	GHOST_WindowX11 *window = 0;
	
	if (!m_display) return 0;
	

	

	window = new GHOST_WindowX11(this, m_display, title,
	                             left, top, width, height,
	                             state, parentWindow, type,
	                             stereoVisual, exclusive,
	                             numOfAASamples);

	if (window) {
		/* Both are now handle in GHOST_WindowX11.cpp
		 * Focus and Delete atoms. */

		if (window->getValid()) {
			/* Store the pointer to the window */
			m_windowManager->addWindow(window);
			m_windowManager->setActiveWindow(window);
			pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window) );
		}
		else {
			delete window;
			window = 0;
		}
	}
	return window;
}

#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
static void destroyIMCallback(XIM xim, XPointer ptr, XPointer data)
{
	GHOST_PRINT("XIM server died\n");

	if (ptr)
		*(XIM *)ptr = NULL;
}

bool GHOST_SystemX11::openX11_IM()
{
	if (!m_display)
		return false;

	/* set locale modifiers such as "@im=ibus" specified by XMODIFIERS */
	XSetLocaleModifiers("");

	m_xim = XOpenIM(m_display, NULL, (char *)GHOST_X11_RES_NAME, (char *)GHOST_X11_RES_CLASS);
	if (!m_xim)
		return false;

	XIMCallback destroy;
	destroy.callback = (XIMProc)destroyIMCallback;
	destroy.client_data = (XPointer)&m_xim;
	XSetIMValues(m_xim, XNDestroyCallback, &destroy, NULL);
	return true;
}
#endif

GHOST_WindowX11 *
GHOST_SystemX11::
findGhostWindow(
		Window xwind) const
{
	
	if (xwind == 0) return NULL;

	/* It is not entirely safe to do this as the backptr may point
	 * to a window that has recently been removed.
	 * We should always check the window manager's list of windows
	 * and only process events on these windows. */

	vector<GHOST_IWindow *> & win_vec = m_windowManager->getWindows();

	vector<GHOST_IWindow *>::iterator win_it = win_vec.begin();
	vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end();
	
	for (; win_it != win_end; ++win_it) {
		GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
		if (window->getXWindow() == xwind) {
			return window;
		}
	}
	return NULL;
	
}

static void SleepTillEvent(Display *display, GHOST_TInt64 maxSleep)
{
	int fd = ConnectionNumber(display);
	fd_set fds;
	
	FD_ZERO(&fds);
	FD_SET(fd, &fds);

	if (maxSleep == -1) {
		select(fd + 1, &fds, NULL, NULL, NULL);
	}
	else {
		timeval tv;

		tv.tv_sec = maxSleep / 1000;
		tv.tv_usec = (maxSleep - tv.tv_sec * 1000) * 1000;
	
		select(fd + 1, &fds, NULL, NULL, &tv);
	}
}

/* This function borrowed from Qt's X11 support
 * qclipboard_x11.cpp
 *  */
struct init_timestamp_data {
	Time timestamp;
};

static Bool init_timestamp_scanner(Display *, XEvent *event, XPointer arg)
{
	init_timestamp_data *data =
	    reinterpret_cast<init_timestamp_data *>(arg);
	switch (event->type)
	{
		case ButtonPress:
		case ButtonRelease:
			data->timestamp = event->xbutton.time;
			break;
		case MotionNotify:
			data->timestamp = event->xmotion.time;
			break;
		case KeyPress:
		case KeyRelease:
			data->timestamp = event->xkey.time;
			break;
		case PropertyNotify:
			data->timestamp = event->xproperty.time;
			break;
		case EnterNotify:
		case LeaveNotify:
			data->timestamp = event->xcrossing.time;
			break;
		case SelectionClear:
			data->timestamp = event->xselectionclear.time;
			break;
		default:
			break;
	}

	return false;
}

Time
GHOST_SystemX11::
lastEventTime(Time default_time) {
	init_timestamp_data data;
	data.timestamp = default_time;
	XEvent ev;
	XCheckIfEvent(m_display, &ev, &init_timestamp_scanner, (XPointer) & data);

	return data.timestamp;
}

bool
GHOST_SystemX11::
processEvents(
		bool waitForEvent)
{
	/* Get all the current events -- translate them into
	 * ghost events and call base class pushEvent() method. */
	
	bool anyProcessed = false;
	
	do {
		GHOST_TimerManager *timerMgr = getTimerManager();
		
		if (waitForEvent && m_dirty_windows.empty() && !XPending(m_display)) {
			GHOST_TUns64 next = timerMgr->nextFireTime();
			
			if (next == GHOST_kFireTimeNever) {
				SleepTillEvent(m_display, -1);
			}
			else {
				GHOST_TInt64 maxSleep = next - getMilliSeconds();

				if (maxSleep >= 0)
					SleepTillEvent(m_display, next - getMilliSeconds());
			}
		}
		
		if (timerMgr->fireTimers(getMilliSeconds())) {
			anyProcessed = true;
		}
		
		while (XPending(m_display)) {
			XEvent xevent;
			XNextEvent(m_display, &xevent);

#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
			/* open connection to XIM server and create input context (XIC)
			 * when receiving the first FocusIn or KeyPress event after startup,
			 * or recover XIM and XIC when the XIM server has been restarted */
			if (xevent.type == FocusIn || xevent.type == KeyPress) {
				if (!m_xim && openX11_IM()) {
					GHOST_PRINT("Connected to XIM server\n");
				}

				if (m_xim) {
					GHOST_WindowX11 * window = findGhostWindow(xevent.xany.window);
					if (window && !window->getX11_XIC() && window->createX11_XIC()) {
						GHOST_PRINT("XIM input context created\n");
						if (xevent.type == KeyPress)
							/* we can assume the window has input focus
							 * here, because key events are received only
							 * when the window is focused. */
							XSetICFocus(window->getX11_XIC());
					}
				}
			}

			/* dispatch event to XIM server */
			if ((XFilterEvent(&xevent, (Window)NULL) == True) && (xevent.type != KeyRelease)) {
				/* do nothing now, the event is consumed by XIM.
				 * however, KeyRelease event should be processed
				 * here, otherwise modifiers remain activated.   */
				continue;
			}
#endif

			processEvent(&xevent);
			anyProcessed = true;


#ifdef USE_UNITY_WORKAROUND
			/* note: processEvent() can't include this code because
			 * KeymapNotify event have no valid window information. */

			/* the X server generates KeymapNotify event immediately after
			 * every EnterNotify and FocusIn event.  we handle this event
			 * to correct modifier states. */
			if (xevent.type == FocusIn) {
				/* use previous event's window, because KeymapNotify event
				 * has no window information. */
				GHOST_WindowX11 *window = findGhostWindow(xevent.xany.window);
				if (window && XPending(m_display) >= 2) {
					XNextEvent(m_display, &xevent);

					if (xevent.type == KeymapNotify) {
						XEvent xev_next;

						/* check if KeyPress or KeyRelease event was generated
						 * in order to confirm the window is active. */
						XPeekEvent(m_display, &xev_next);

						if (xev_next.type == KeyPress || xev_next.type == KeyRelease) {
							/* XK_Hyper_L/R currently unused */
							const static KeySym modifiers[8] = {XK_Shift_L, XK_Shift_R,
							                                    XK_Control_L, XK_Control_R,
							                                    XK_Alt_L, XK_Alt_R,
							                                    XK_Super_L, XK_Super_R};

							for (int i = 0; i < (sizeof(modifiers) / sizeof(*modifiers)); i++) {
								KeyCode kc = XKeysymToKeycode(m_display, modifiers[i]);
								if (((xevent.xkeymap.key_vector[kc >> 3] >> (kc & 7)) & 1) != 0) {
									pushEvent(new GHOST_EventKey(
									              getMilliSeconds(),
									              GHOST_kEventKeyDown,
									              window,
									              convertXKey(modifiers[i]),
									              '\0',
									              NULL));
								}
							}
						}
					}
				}
			}
#endif  /* USE_UNITY_WORKAROUND */

		}
		
		if (generateWindowExposeEvents()) {
			anyProcessed = true;
		}

#ifdef WITH_INPUT_NDOF
		if (static_cast<GHOST_NDOFManagerX11 *>(m_ndofManager)->processEvents()) {
			anyProcessed = true;
		}
#endif
		
	} while (waitForEvent && !anyProcessed);
	
	return anyProcessed;
}


#ifdef WITH_X11_XINPUT
/* set currently using tablet mode (stylus or eraser) depending on device ID */
static void setTabletMode(GHOST_SystemX11 *system, GHOST_WindowX11 *window, XID deviceid)
{
	if (deviceid == system->GetXTablet().StylusID)
		window->GetTabletData()->Active = GHOST_kTabletModeStylus;
	else if (deviceid == system->GetXTablet().EraserID)
		window->GetTabletData()->Active = GHOST_kTabletModeEraser;
}
#endif /* WITH_X11_XINPUT */

#ifdef WITH_X11_XINPUT
static bool checkTabletProximity(Display *display, XDevice *device)
{
	/* we could have true/false/not-found return value, but for now false is OK */

	/* see: state.c from xinput, to get more data out of the device */
	XDeviceState *state;

	if (device == NULL) {
		return false;
	}

	state = XQueryDeviceState(display, device);

	if (state) {
		XInputClass *cls = state->data;
		// printf("%d class%s :\n", state->num_classes,
		//       (state->num_classes > 1) ? "es" : "");
		for (int loop = 0; loop < state->num_classes; loop++) {
			switch (cls->c_class) {
				case ValuatorClass:
					XValuatorState *val_state = (XValuatorState *)cls;
					// printf("ValuatorClass Mode=%s Proximity=%s\n",
					//        val_state->mode & 1 ? "Absolute" : "Relative",
					//        val_state->mode & 2 ? "Out" : "In");

					if ((val_state->mode & 2) == 0) {
						XFreeDeviceState(state);
						return true;
					}
					break;
			}
			cls = (XInputClass *) ((char *)cls + cls->length);
		}
		XFreeDeviceState(state);
	}
	return false;
}
#endif /* WITH_X11_XINPUT */

void
GHOST_SystemX11::processEvent(XEvent *xe)
{
	GHOST_WindowX11 *window = findGhostWindow(xe->xany.window);
	GHOST_Event *g_event = NULL;

	if (!window) {
		return;
	}

#ifdef WITH_X11_XINPUT
	/* Proximity-Out Events are not reliable, if the tablet is active - check on each event
	 * this adds a little overhead but only while the tablet is in use.
	 * in the futire we could have a ghost call window->CheckTabletProximity()
	 * but for now enough parts of the code are checking 'Active'
	 * - campbell */
	if (window->GetTabletData()->Active != GHOST_kTabletModeNone) {
		if (checkTabletProximity(xe->xany.display, m_xtablet.StylusDevice) == false &&
		    checkTabletProximity(xe->xany.display, m_xtablet.EraserDevice) == false)
		{
			// printf("proximity disable\n");
			window->GetTabletData()->Active = GHOST_kTabletModeNone;
		}
	}
#endif /* WITH_X11_XINPUT */

	switch (xe->type) {
		case Expose:
		{
			XExposeEvent & xee = xe->xexpose;

			if (xee.count == 0) {
				/* Only generate a single expose event
				 * per read of the event queue. */

				g_event = new
				          GHOST_Event(
				    getMilliSeconds(),
				    GHOST_kEventWindowUpdate,
				    window
				    );
			}
			break;
		}

		case MotionNotify:
		{
			XMotionEvent &xme = xe->xmotion;

#ifdef WITH_X11_XINPUT
			bool is_tablet = window->GetTabletData()->Active != GHOST_kTabletModeNone;
#else
			bool is_tablet = false;
#endif

			if (is_tablet == false && window->getCursorGrabModeIsWarp()) {
				GHOST_TInt32 x_new = xme.x_root;
				GHOST_TInt32 y_new = xme.y_root;
				GHOST_TInt32 x_accum, y_accum;
				GHOST_Rect bounds;

				/* fallback to window bounds */
				if (window->getCursorGrabBounds(bounds) == GHOST_kFailure)
					window->getClientBounds(bounds);

				/* could also clamp to screen bounds
				 * wrap with a window outside the view will fail atm  */
				bounds.wrapPoint(x_new, y_new, 8); /* offset of one incase blender is at screen bounds */
				window->getCursorGrabAccum(x_accum, y_accum);

				if (x_new != xme.x_root || y_new != xme.y_root) {
					if (xme.time > m_last_warp) {
						/* when wrapping we don't need to add an event because the
						 * setCursorPosition call will cause a new event after */
						setCursorPosition(x_new, y_new); /* wrap */
						window->setCursorGrabAccum(x_accum + (xme.x_root - x_new), y_accum + (xme.y_root - y_new));
						m_last_warp = lastEventTime(xme.time);
					}
					else {
						setCursorPosition(x_new, y_new); /* wrap but don't accumulate */
					}
				}
				else {
					g_event = new
					          GHOST_EventCursor(
					    getMilliSeconds(),
					    GHOST_kEventCursorMove,
					    window,
					    xme.x_root + x_accum,
					    xme.y_root + y_accum
					    );
				}
			}
			else {
				g_event = new
				          GHOST_EventCursor(
				    getMilliSeconds(),
				    GHOST_kEventCursorMove,
				    window,
				    xme.x_root,
				    xme.y_root
				    );
			}
			break;
		}

		case KeyPress:
		case KeyRelease:
		{
			XKeyEvent *xke = &(xe->xkey);
			KeySym key_sym;
			char ascii;
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
			/* utf8_array[] is initial buffer used for Xutf8LookupString().
			 * if the length of the utf8 string exceeds this array, allocate
			 * another memory area and call Xutf8LookupString() again.
			 * the last 5 bytes are used to avoid segfault that might happen
			 * at the end of this buffer when the constructor of GHOST_EventKey
			 * reads 6 bytes regardless of the effective data length. */
			char utf8_array[16 * 6 + 5]; /* 16 utf8 characters */
			char *utf8_buf = utf8_array;
			int len = 1; /* at least one null character will be stored */
#else
			char *utf8_buf = NULL;
#endif
			
			GHOST_TKey gkey;

			/* In keyboards like latin ones,
			 * numbers needs a 'Shift' to be accessed but key_sym
			 * is unmodified (or anyone swapping the keys with xmodmap).
			 *
			 * Here we look at the 'Shifted' version of the key.
			 * If it is a number, then we take it instead of the normal key.
			 *
			 * The modified key is sent in the 'ascii's variable anyway.
			 */
			if ((xke->keycode >= 10 && xke->keycode < 20) &&
			    ((key_sym = XLookupKeysym(xke, ShiftMask)) >= XK_0) && (key_sym <= XK_9))
			{
				/* pass (keep shift'ed key_sym) */
			}
			else {
				/* regular case */
				key_sym = XLookupKeysym(xke, 0);
			}

			gkey = convertXKey(key_sym);

			GHOST_TEventType type = (xke->type == KeyPress) ? 
			                        GHOST_kEventKeyDown : GHOST_kEventKeyUp;
			
			if (!XLookupString(xke, &ascii, 1, NULL, NULL)) {
				ascii = '\0';
			}
			
#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
			/* getting unicode on key-up events gives XLookupNone status */
			XIC xic = window->getX11_XIC();
			if (xic && xke->type == KeyPress) {
				Status status;

				/* use utf8 because its not locale depentant, from xorg docs */
				if (!(len = Xutf8LookupString(xic, xke, utf8_buf, sizeof(utf8_array) - 5, &key_sym, &status))) {
					utf8_buf[0] = '\0';
				}

				if (status == XBufferOverflow) {
					utf8_buf = (char *) malloc(len + 5);
					len = Xutf8LookupString(xic, xke, utf8_buf, len, &key_sym, &status);
				}

				if ((status == XLookupChars || status == XLookupBoth)) {
					if ((unsigned char)utf8_buf[0] >= 32) { /* not an ascii control character */
						/* do nothing for now, this is valid utf8 */
					}
					else {
						utf8_buf[0] = '\0';
					}
				}
				else if (status == XLookupKeySym) {
					/* this key doesn't have a text representation, it is a command
					 * key of some sort */;
				}
				else {
					printf("Bad keycode lookup. Keysym 0x%x Status: %s\n",
					       (unsigned int) key_sym,
					       (status == XLookupNone ? "XLookupNone" :
					        status == XLookupKeySym ? "XLookupKeySym" :
					        "Unknown status"));

					printf("'%.*s' %p %p\n", len, utf8_buf, xic, m_xim);
				}
			}
			else {
				utf8_buf[0] = '\0';
			}
#endif

			g_event = new
			          GHOST_EventKey(
			    getMilliSeconds(),
			    type,
			    window,
			    gkey,
			    ascii,
			    utf8_buf
			    );

#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
			/* when using IM for some languages such as Japanese,
			 * one event inserts multiple utf8 characters */
			if (xic && xke->type == KeyPress) {
				unsigned char c;
				int i = 0;
				while (1) {
					/* search character boundary */
					if ((unsigned char)utf8_buf[i++] > 0x7f) {
						for (; i < len; ++i) {
							c = utf8_buf[i];
							if (c < 0x80 || c > 0xbf) break;
						}
					}

					if (i >= len) break;

					/* enqueue previous character */
					pushEvent(g_event);

					g_event = new
					          GHOST_EventKey(
					    getMilliSeconds(),
					    type,
					    window,
					    gkey,
					    '\0',
					    &utf8_buf[i]
					    );
				}
			}

			if (utf8_buf != utf8_array)
				free(utf8_buf);
#endif
			
			break;
		}

		case ButtonPress:
		case ButtonRelease:
		{
			XButtonEvent & xbe = xe->xbutton;
			GHOST_TButtonMask gbmask = GHOST_kButtonMaskLeft;
			GHOST_TEventType type = (xbe.type == ButtonPress) ? 
			                        GHOST_kEventButtonDown : GHOST_kEventButtonUp;

			/* process wheel mouse events and break, only pass on press events */
			if (xbe.button == Button4) {
				if (xbe.type == ButtonPress)
					g_event = new GHOST_EventWheel(getMilliSeconds(), window, 1);
				break;
			}
			else if (xbe.button == Button5) {
				if (xbe.type == ButtonPress)
					g_event = new GHOST_EventWheel(getMilliSeconds(), window, -1);
				break;
			}
			
			/* process rest of normal mouse buttons */
			if (xbe.button == Button1)
				gbmask = GHOST_kButtonMaskLeft;
			else if (xbe.button == Button2)
				gbmask = GHOST_kButtonMaskMiddle;
			else if (xbe.button == Button3)
				gbmask = GHOST_kButtonMaskRight;
			/* It seems events 6 and 7 are for horizontal scrolling.
			 * you can re-order button mapping like this... (swaps 6,7 with 8,9)
			 *   xmodmap -e "pointer = 1 2 3 4 5 8 9 6 7"
			 */
			else if (xbe.button == 6)
				gbmask = GHOST_kButtonMaskButton6;
			else if (xbe.button == 7)
				gbmask = GHOST_kButtonMaskButton7;
			else if (xbe.button == 8)
				gbmask = GHOST_kButtonMaskButton4;
			else if (xbe.button == 9)
				gbmask = GHOST_kButtonMaskButton5;
			else
				break;

			g_event = new
			          GHOST_EventButton(
			    getMilliSeconds(),
			    type,
			    window,
			    gbmask
			    );
			break;
		}
			
		/* change of size, border, layer etc. */
		case ConfigureNotify:
		{
			/* XConfigureEvent & xce = xe->xconfigure; */

			g_event = new 
			          GHOST_Event(
			    getMilliSeconds(),
			    GHOST_kEventWindowSize,
			    window
			    );
			break;
		}

		case FocusIn:
		case FocusOut:
		{
			XFocusChangeEvent &xfe = xe->xfocus;

			/* TODO: make sure this is the correct place for activate/deactivate */
			// printf("X: focus %s for window %d\n", xfe.type == FocusIn ? "in" : "out", (int) xfe.window);
		
			/* May have to look at the type of event and filter some out. */

			GHOST_TEventType gtype = (xfe.type == FocusIn) ? 
			                         GHOST_kEventWindowActivate : GHOST_kEventWindowDeactivate;

#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
			XIC xic = window->getX11_XIC();
			if (xic) {
				if (xe->type == FocusIn)
					XSetICFocus(xic);
				else
					XUnsetICFocus(xic);
			}
#endif

			g_event = new 
			          GHOST_Event(
			    getMilliSeconds(),
			    gtype,
			    window
			    );
			break;

		}
		case ClientMessage:
		{
			XClientMessageEvent & xcme = xe->xclient;

			if (((Atom)xcme.data.l[0]) == m_atom.WM_DELETE_WINDOW) {
				g_event = new 
				          GHOST_Event(
				    getMilliSeconds(),
				    GHOST_kEventWindowClose,
				    window
				    );
			}
			else if (((Atom)xcme.data.l[0]) == m_atom.WM_TAKE_FOCUS) {
				XWindowAttributes attr;
				Window fwin;
				int revert_to;

				/* as ICCCM say, we need reply this event
				 * with a SetInputFocus, the data[1] have
				 * the valid timestamp (send by the wm).
				 *
				 * Some WM send this event before the
				 * window is really mapped (for example
				 * change from virtual desktop), so we need
				 * to be sure that our windows is mapped
				 * or this call fail and close blender.
				 */
				if (XGetWindowAttributes(m_display, xcme.window, &attr) == True) {
					if (XGetInputFocus(m_display, &fwin, &revert_to) == True) {
						if (attr.map_state == IsViewable) {
							if (fwin != xcme.window)
								XSetInputFocus(m_display, xcme.window, RevertToParent, xcme.data.l[1]);
						}
					}
				}
			}
			else {
#ifdef WITH_XDND
				/* try to handle drag event (if there's no such events, GHOST_HandleClientMessage will return zero) */
				if (window->getDropTarget()->GHOST_HandleClientMessage(xe) == false) {
					/* Unknown client message, ignore */
				}
#else
				/* Unknown client message, ignore */
#endif
			}

			break;
		}
		
		case DestroyNotify:
			::exit(-1);
		/* We're not interested in the following things.(yet...) */
		case NoExpose:
		case GraphicsExpose:
			break;
		
		case EnterNotify:
		case LeaveNotify:
		{
			/* XCrossingEvents pointer leave enter window.
			 * also do cursor move here, MotionNotify only
			 * happens when motion starts & ends inside window.
			 * we only do moves when the crossing mode is 'normal'
			 * (really crossing between windows) since some windowmanagers
			 * also send grab/ungrab crossings for mousewheel events.
			 */
			XCrossingEvent &xce = xe->xcrossing;
			if (xce.mode == NotifyNormal) {
				g_event = new 
				          GHOST_EventCursor(
				    getMilliSeconds(),
				    GHOST_kEventCursorMove,
				    window,
				    xce.x_root,
				    xce.y_root
				    );
			}

			// printf("X: %s window %d\n", xce.type == EnterNotify ? "entering" : "leaving", (int) xce.window);

			if (xce.type == EnterNotify)
				m_windowManager->setActiveWindow(window);
			else
				m_windowManager->setWindowInactive(window);

			break;
		}
		case MapNotify:
			/*
			 * From ICCCM:
			 * [ Clients can select for StructureNotify on their
			 *   top-level windows to track transition between
			 *   Normal and Iconic states. Receipt of a MapNotify
			 *   event will indicate a transition to the Normal
			 *   state, and receipt of an UnmapNotify event will
			 *   indicate a transition to the Iconic state. ]
			 */
			if (window->m_post_init == True) {
				/*
				 * Now we are sure that the window is
				 * mapped, so only need change the state.
				 */
				window->setState(window->m_post_state);
				window->m_post_init = False;
			}
			break;
		case UnmapNotify:
			break;
		case MappingNotify:
		case ReparentNotify:
			break;
		case SelectionRequest:
		{
			XEvent nxe;
			Atom target, utf8_string, string, compound_text, c_string;
			XSelectionRequestEvent *xse = &xe->xselectionrequest;
			
			target = XInternAtom(m_display, "TARGETS", False);
			utf8_string = XInternAtom(m_display, "UTF8_STRING", False);
			string = XInternAtom(m_display, "STRING", False);
			compound_text = XInternAtom(m_display, "COMPOUND_TEXT", False);
			c_string = XInternAtom(m_display, "C_STRING", False);
			
			/* support obsolete clients */
			if (xse->property == None) {
				xse->property = xse->target;
			}
			
			nxe.xselection.type = SelectionNotify;
			nxe.xselection.requestor = xse->requestor;
			nxe.xselection.property = xse->property;
			nxe.xselection.display = xse->display;
			nxe.xselection.selection = xse->selection;
			nxe.xselection.target = xse->target;
			nxe.xselection.time = xse->time;
			
			/* Check to see if the requestor is asking for String */
			if (xse->target == utf8_string ||
			    xse->target == string ||
			    xse->target == compound_text ||
			    xse->target == c_string)
			{
				if (xse->selection == XInternAtom(m_display, "PRIMARY", False)) {
					XChangeProperty(m_display, xse->requestor, xse->property, xse->target, 8, PropModeReplace,
					                (unsigned char *)txt_select_buffer, strlen(txt_select_buffer));
				}
				else if (xse->selection == XInternAtom(m_display, "CLIPBOARD", False)) {
					XChangeProperty(m_display, xse->requestor, xse->property, xse->target, 8, PropModeReplace,
					                (unsigned char *)txt_cut_buffer, strlen(txt_cut_buffer));
				}
			}
			else if (xse->target == target) {
				Atom alist[5];
				alist[0] = target;
				alist[1] = utf8_string;
				alist[2] = string;
				alist[3] = compound_text;
				alist[4] = c_string;
				XChangeProperty(m_display, xse->requestor, xse->property, xse->target, 32, PropModeReplace,
				                (unsigned char *)alist, 5);
				XFlush(m_display);
			}
			else {
				/* Change property to None because we do not support anything but STRING */
				nxe.xselection.property = None;
			}
			
			/* Send the event to the client 0 0 == False, SelectionNotify */
			XSendEvent(m_display, xse->requestor, 0, 0, &nxe);
			XFlush(m_display);
			break;
		}
		
		default:
		{
#ifdef WITH_X11_XINPUT
			if (xe->type == m_xtablet.MotionEvent) {
				XDeviceMotionEvent *data = (XDeviceMotionEvent *)xe;
				const unsigned char axis_first = data->first_axis;
				const unsigned char axes_end = axis_first + data->axes_count;  /* after the last */
				int axis_value;

				/* stroke might begin without leading ProxyIn event,
				 * this happens when window is opened when stylus is already hovering
				 * around tablet surface */
				setTabletMode(this, window, data->deviceid);

				/* Note: This event might be generated with incomplete dataset (don't exactly know why, looks like in
				 *       some cases, if the value does not change, it is not included in subsequent XDeviceMotionEvent
				 *       events). So we have to check which values this event actually contains!
				 */

#define AXIS_VALUE_GET(axis, val)  ((axis_first <= axis && axes_end > axis) && ((void)(val = data->axis_data[axis]), true))

				if (AXIS_VALUE_GET(2, axis_value)) {
					window->GetTabletData()->Pressure = axis_value / ((float)m_xtablet.PressureLevels);
				}

				/* the (short) cast and the & 0xffff is bizarre and unexplained anywhere,
				 * but I got garbage data without it. Found it in the xidump.c source --matt
				 *
				 * The '& 0xffff' just truncates the value to its two lowest bytes, this probably means
				 * some drivers do not properly set the whole int value? Since we convert to float afterward,
				 * I don't think we need to cast to short here, but do not have a device to check this. --mont29
				 */
				if (AXIS_VALUE_GET(3, axis_value)) {
					window->GetTabletData()->Xtilt = (short)(axis_value & 0xffff) /
					                                 ((float)m_xtablet.XtiltLevels);
				}
				if (AXIS_VALUE_GET(4, axis_value)) {
					window->GetTabletData()->Ytilt = (short)(axis_value & 0xffff) /
					                                 ((float)m_xtablet.YtiltLevels);
				}

#undef AXIS_VALUE_GET

			}
			else if (xe->type == m_xtablet.ProxInEvent) {
				XProximityNotifyEvent *data = (XProximityNotifyEvent *)xe;

				setTabletMode(this, window, data->deviceid);
			}
			else if (xe->type == m_xtablet.ProxOutEvent) {
				window->GetTabletData()->Active = GHOST_kTabletModeNone;
			}
#endif // WITH_X11_XINPUT
			break;
		}
	}

	if (g_event) {
		pushEvent(g_event);
	}
}

GHOST_TSuccess
GHOST_SystemX11::
getModifierKeys(
		GHOST_ModifierKeys& keys) const
{

	/* analyse the masks retuned from XQueryPointer. */

	memset((void *)m_keyboard_vector, 0, sizeof(m_keyboard_vector));

	XQueryKeymap(m_display, (char *)m_keyboard_vector);

	/* now translate key symobols into keycodes and
	 * test with vector. */

	const static KeyCode shift_l = XKeysymToKeycode(m_display, XK_Shift_L);
	const static KeyCode shift_r = XKeysymToKeycode(m_display, XK_Shift_R);
	const static KeyCode control_l = XKeysymToKeycode(m_display, XK_Control_L);
	const static KeyCode control_r = XKeysymToKeycode(m_display, XK_Control_R);
	const static KeyCode alt_l = XKeysymToKeycode(m_display, XK_Alt_L);
	const static KeyCode alt_r = XKeysymToKeycode(m_display, XK_Alt_R);
	const static KeyCode super_l = XKeysymToKeycode(m_display, XK_Super_L);
	const static KeyCode super_r = XKeysymToKeycode(m_display, XK_Super_R);

	/* shift */
	keys.set(GHOST_kModifierKeyLeftShift, ((m_keyboard_vector[shift_l >> 3] >> (shift_l & 7)) & 1) != 0);
	keys.set(GHOST_kModifierKeyRightShift, ((m_keyboard_vector[shift_r >> 3] >> (shift_r & 7)) & 1) != 0);
	/* control */
	keys.set(GHOST_kModifierKeyLeftControl, ((m_keyboard_vector[control_l >> 3] >> (control_l & 7)) & 1) != 0);
	keys.set(GHOST_kModifierKeyRightControl, ((m_keyboard_vector[control_r >> 3] >> (control_r & 7)) & 1) != 0);
	/* alt */
	keys.set(GHOST_kModifierKeyLeftAlt, ((m_keyboard_vector[alt_l >> 3] >> (alt_l & 7)) & 1) != 0);
	keys.set(GHOST_kModifierKeyRightAlt, ((m_keyboard_vector[alt_r >> 3] >> (alt_r & 7)) & 1) != 0);
	/* super (windows) - only one GHOST-kModifierKeyOS, so mapping to either */
	keys.set(GHOST_kModifierKeyOS, ( ((m_keyboard_vector[super_l >> 3] >> (super_l & 7)) & 1) ||
	                                 ((m_keyboard_vector[super_r >> 3] >> (super_r & 7)) & 1) ) != 0);

	return GHOST_kSuccess;
}

GHOST_TSuccess
GHOST_SystemX11::
getButtons(
		GHOST_Buttons& buttons) const
{
	Window root_return, child_return;
	int rx, ry, wx, wy;
	unsigned int mask_return;

	if (XQueryPointer(m_display,
	                  RootWindow(m_display, DefaultScreen(m_display)),
	                  &root_return,
	                  &child_return,
	                  &rx, &ry,
	                  &wx, &wy,
	                  &mask_return) == True)
	{
		buttons.set(GHOST_kButtonMaskLeft,   (mask_return & Button1Mask) != 0);
		buttons.set(GHOST_kButtonMaskMiddle, (mask_return & Button2Mask) != 0);
		buttons.set(GHOST_kButtonMaskRight,  (mask_return & Button3Mask) != 0);
	}
	else {
		return GHOST_kFailure;
	}	

	return GHOST_kSuccess;
}


GHOST_TSuccess
GHOST_SystemX11::
getCursorPosition(
		GHOST_TInt32& x,
		GHOST_TInt32& y) const
{

	Window root_return, child_return;
	int rx, ry, wx, wy;
	unsigned int mask_return;

	if (XQueryPointer(
	        m_display,
	        RootWindow(m_display, DefaultScreen(m_display)),
	        &root_return,
	        &child_return,
	        &rx, &ry,
	        &wx, &wy,
	        &mask_return
	        ) == False) {
		return GHOST_kFailure;
	}
	else {
		x = rx;
		y = ry;
	}	
	return GHOST_kSuccess;
}


GHOST_TSuccess
GHOST_SystemX11::
setCursorPosition(
		GHOST_TInt32 x,
		GHOST_TInt32 y
        ) {

	/* This is a brute force move in screen coordinates
	 * XWarpPointer does relative moves so first determine the
	 * current pointer position. */

	int cx, cy;
	if (getCursorPosition(cx, cy) == GHOST_kFailure) {
		return GHOST_kFailure;
	}

	int relx = x - cx;
	int rely = y - cy;

	XWarpPointer(m_display, None, None, 0, 0, 0, 0, relx, rely);
	XSync(m_display, 0); /* Sync to process all requests */
	
	return GHOST_kSuccess;
}


void
GHOST_SystemX11::
addDirtyWindow(
		GHOST_WindowX11 *bad_wind)
{
	GHOST_ASSERT((bad_wind != NULL), "addDirtyWindow() NULL ptr trapped (window)");
	
	m_dirty_windows.push_back(bad_wind);
}


bool
GHOST_SystemX11::
generateWindowExposeEvents()
{
	vector<GHOST_WindowX11 *>::iterator w_start = m_dirty_windows.begin();
	vector<GHOST_WindowX11 *>::const_iterator w_end = m_dirty_windows.end();
	bool anyProcessed = false;
	
	for (; w_start != w_end; ++w_start) {
		GHOST_Event *g_event = new
		                       GHOST_Event(
		    getMilliSeconds(),
		    GHOST_kEventWindowUpdate,
		    *w_start
		    );

		(*w_start)->validate();
		
		if (g_event) {
			pushEvent(g_event);
			anyProcessed = true;
		}
	}

	m_dirty_windows.clear();
	return anyProcessed;
}

#define GXMAP(k, x, y) case x: k = y; break

static GHOST_TKey
convertXKey(KeySym key)
{
	GHOST_TKey type;

	if ((key >= XK_A) && (key <= XK_Z)) {
		type = GHOST_TKey(key - XK_A + int(GHOST_kKeyA));
	}
	else if ((key >= XK_a) && (key <= XK_z)) {
		type = GHOST_TKey(key - XK_a + int(GHOST_kKeyA));
	}
	else if ((key >= XK_0) && (key <= XK_9)) {
		type = GHOST_TKey(key - XK_0 + int(GHOST_kKey0));
	}
	else if ((key >= XK_F1) && (key <= XK_F24)) {
		type = GHOST_TKey(key - XK_F1 + int(GHOST_kKeyF1));
#if defined(__sun) || defined(__sun__) 
		/* This is a bit of a hack, but it looks like sun
		 * Used F11 and friends for its special keys Stop,again etc..
		 * So this little patch enables F11 and F12 to work as expected
		 * following link has documentation on it:
		 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4734408
		 * also from /usr/include/X11/Sunkeysym.h
		 * #define SunXK_F36               0x1005FF10      // Labeled F11
		 * #define SunXK_F37               0x1005FF11      // Labeled F12
		 *
		 *      mein@cs.umn.edu
		 */
		
	}
	else if (key == 268828432) {
		type = GHOST_kKeyF11;
	}
	else if (key == 268828433) {
		type = GHOST_kKeyF12;
#endif
	}
	else {
		switch (key) {
			GXMAP(type, XK_BackSpace,    GHOST_kKeyBackSpace);
			GXMAP(type, XK_Tab,          GHOST_kKeyTab);
			GXMAP(type, XK_Return,       GHOST_kKeyEnter);
			GXMAP(type, XK_Escape,       GHOST_kKeyEsc);
			GXMAP(type, XK_space,        GHOST_kKeySpace);

			GXMAP(type, XK_Linefeed,     GHOST_kKeyLinefeed);
			GXMAP(type, XK_semicolon,    GHOST_kKeySemicolon);
			GXMAP(type, XK_period,       GHOST_kKeyPeriod);
			GXMAP(type, XK_comma,        GHOST_kKeyComma);
			GXMAP(type, XK_quoteright,   GHOST_kKeyQuote);
			GXMAP(type, XK_quoteleft,    GHOST_kKeyAccentGrave);
			GXMAP(type, XK_minus,        GHOST_kKeyMinus);
			GXMAP(type, XK_slash,        GHOST_kKeySlash);
			GXMAP(type, XK_backslash,    GHOST_kKeyBackslash);
			GXMAP(type, XK_equal,        GHOST_kKeyEqual);
			GXMAP(type, XK_bracketleft,  GHOST_kKeyLeftBracket);
			GXMAP(type, XK_bracketright, GHOST_kKeyRightBracket);
			GXMAP(type, XK_Pause,        GHOST_kKeyPause);

			GXMAP(type, XK_Shift_L,      GHOST_kKeyLeftShift);
			GXMAP(type, XK_Shift_R,      GHOST_kKeyRightShift);
			GXMAP(type, XK_Control_L,    GHOST_kKeyLeftControl);
			GXMAP(type, XK_Control_R,    GHOST_kKeyRightControl);
			GXMAP(type, XK_Alt_L,        GHOST_kKeyLeftAlt);
			GXMAP(type, XK_Alt_R,        GHOST_kKeyRightAlt);
			GXMAP(type, XK_Super_L,      GHOST_kKeyOS);
			GXMAP(type, XK_Super_R,      GHOST_kKeyOS);

			GXMAP(type, XK_Insert,       GHOST_kKeyInsert);
			GXMAP(type, XK_Delete,       GHOST_kKeyDelete);
			GXMAP(type, XK_Home,         GHOST_kKeyHome);
			GXMAP(type, XK_End,          GHOST_kKeyEnd);
			GXMAP(type, XK_Page_Up,      GHOST_kKeyUpPage);
			GXMAP(type, XK_Page_Down,    GHOST_kKeyDownPage);

			GXMAP(type, XK_Left,         GHOST_kKeyLeftArrow);
			GXMAP(type, XK_Right,        GHOST_kKeyRightArrow);
			GXMAP(type, XK_Up,           GHOST_kKeyUpArrow);
			GXMAP(type, XK_Down,         GHOST_kKeyDownArrow);

			GXMAP(type, XK_Caps_Lock,    GHOST_kKeyCapsLock);
			GXMAP(type, XK_Scroll_Lock,  GHOST_kKeyScrollLock);
			GXMAP(type, XK_Num_Lock,     GHOST_kKeyNumLock);

			/* keypad events */

			GXMAP(type, XK_KP_0,         GHOST_kKeyNumpad0);
			GXMAP(type, XK_KP_1,         GHOST_kKeyNumpad1);
			GXMAP(type, XK_KP_2,         GHOST_kKeyNumpad2);
			GXMAP(type, XK_KP_3,         GHOST_kKeyNumpad3);
			GXMAP(type, XK_KP_4,         GHOST_kKeyNumpad4);
			GXMAP(type, XK_KP_5,         GHOST_kKeyNumpad5);
			GXMAP(type, XK_KP_6,         GHOST_kKeyNumpad6);
			GXMAP(type, XK_KP_7,         GHOST_kKeyNumpad7);
			GXMAP(type, XK_KP_8,         GHOST_kKeyNumpad8);
			GXMAP(type, XK_KP_9,         GHOST_kKeyNumpad9);
			GXMAP(type, XK_KP_Decimal,   GHOST_kKeyNumpadPeriod);

			GXMAP(type, XK_KP_Insert,    GHOST_kKeyNumpad0);
			GXMAP(type, XK_KP_End,       GHOST_kKeyNumpad1);
			GXMAP(type, XK_KP_Down,      GHOST_kKeyNumpad2);
			GXMAP(type, XK_KP_Page_Down, GHOST_kKeyNumpad3);
			GXMAP(type, XK_KP_Left,      GHOST_kKeyNumpad4);
			GXMAP(type, XK_KP_Begin,     GHOST_kKeyNumpad5);
			GXMAP(type, XK_KP_Right,     GHOST_kKeyNumpad6);
			GXMAP(type, XK_KP_Home,      GHOST_kKeyNumpad7);
			GXMAP(type, XK_KP_Up,        GHOST_kKeyNumpad8);
			GXMAP(type, XK_KP_Page_Up,   GHOST_kKeyNumpad9);
			GXMAP(type, XK_KP_Delete,    GHOST_kKeyNumpadPeriod);

			GXMAP(type, XK_KP_Enter,     GHOST_kKeyNumpadEnter);
			GXMAP(type, XK_KP_Add,       GHOST_kKeyNumpadPlus);
			GXMAP(type, XK_KP_Subtract,  GHOST_kKeyNumpadMinus);
			GXMAP(type, XK_KP_Multiply,  GHOST_kKeyNumpadAsterisk);
			GXMAP(type, XK_KP_Divide,    GHOST_kKeyNumpadSlash);

			/* Media keys in some keyboards and laptops with XFree86/Xorg */
#ifdef WITH_XF86KEYSYM
			GXMAP(type, XF86XK_AudioPlay,    GHOST_kKeyMediaPlay);
			GXMAP(type, XF86XK_AudioStop,    GHOST_kKeyMediaStop);
			GXMAP(type, XF86XK_AudioPrev,    GHOST_kKeyMediaFirst);
			GXMAP(type, XF86XK_AudioRewind,  GHOST_kKeyMediaFirst);
			GXMAP(type, XF86XK_AudioNext,    GHOST_kKeyMediaLast);
#ifdef XF86XK_AudioForward /* Debian lenny's XF86keysym.h has no XF86XK_AudioForward define */
			GXMAP(type, XF86XK_AudioForward, GHOST_kKeyMediaLast);
#endif
#endif

			/* some extra sun cruft (NICE KEYBOARD!) */
#ifdef __sun__
			GXMAP(type, 0xffde,          GHOST_kKeyNumpad1);
			GXMAP(type, 0xffe0,          GHOST_kKeyNumpad3);
			GXMAP(type, 0xffdc,          GHOST_kKeyNumpad5);
			GXMAP(type, 0xffd8,          GHOST_kKeyNumpad7);
			GXMAP(type, 0xffda,          GHOST_kKeyNumpad9);

			GXMAP(type, 0xffd6,          GHOST_kKeyNumpadSlash);
			GXMAP(type, 0xffd7,          GHOST_kKeyNumpadAsterisk);
#endif

			default:
				type = GHOST_kKeyUnknown;
				break;
		}
	}

	return type;
}

#undef GXMAP

/* from xclip.c xcout() v0.11 */

#define XCLIB_XCOUT_NONE            0 /* no context */
#define XCLIB_XCOUT_SENTCONVSEL     1 /* sent a request */
#define XCLIB_XCOUT_INCR            2 /* in an incr loop */
#define XCLIB_XCOUT_FALLBACK        3 /* STRING failed, need fallback to UTF8 */
#define XCLIB_XCOUT_FALLBACK_UTF8   4 /* UTF8 failed, move to compouned */
#define XCLIB_XCOUT_FALLBACK_COMP   5 /* compouned failed, move to text. */
#define XCLIB_XCOUT_FALLBACK_TEXT   6

/* Retrieves the contents of a selections. */
void GHOST_SystemX11::getClipboard_xcout(const XEvent *evt,
		Atom sel, Atom target, unsigned char **txt,
		unsigned long *len, unsigned int *context) const
{
	Atom pty_type;
	int pty_format;
	unsigned char *buffer;
	unsigned long pty_size, pty_items;
	unsigned char *ltxt = *txt;

	vector<GHOST_IWindow *> & win_vec = m_windowManager->getWindows();
	vector<GHOST_IWindow *>::iterator win_it = win_vec.begin();
	GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
	Window win = window->getXWindow();

	switch (*context) {
		/* There is no context, do an XConvertSelection() */
		case XCLIB_XCOUT_NONE:
			/* Initialise return length to 0 */
			if (*len > 0) {
				free(*txt);
				*len = 0;
			}

			/* Send a selection request */
			XConvertSelection(m_display, sel, target, m_atom.XCLIP_OUT, win, CurrentTime);
			*context = XCLIB_XCOUT_SENTCONVSEL;
			return;

		case XCLIB_XCOUT_SENTCONVSEL:
			if (evt->type != SelectionNotify)
				return;

			if (target == m_atom.UTF8_STRING && evt->xselection.property == None) {
				*context = XCLIB_XCOUT_FALLBACK_UTF8;
				return;
			}
			else if (target == m_atom.COMPOUND_TEXT && evt->xselection.property == None) {
				*context = XCLIB_XCOUT_FALLBACK_COMP;
				return;
			}
			else if (target == m_atom.TEXT && evt->xselection.property == None) {
				*context = XCLIB_XCOUT_FALLBACK_TEXT;
				return;
			}

			/* find the size and format of the data in property */
			XGetWindowProperty(m_display, win, m_atom.XCLIP_OUT, 0, 0, False,
			                   AnyPropertyType, &pty_type, &pty_format,
			                   &pty_items, &pty_size, &buffer);
			XFree(buffer);

			if (pty_type == m_atom.INCR) {
				/* start INCR mechanism by deleting property */
				XDeleteProperty(m_display, win, m_atom.XCLIP_OUT);
				XFlush(m_display);
				*context = XCLIB_XCOUT_INCR;
				return;
			}

			/* if it's not incr, and not format == 8, then there's
			 * nothing in the selection (that xclip understands, anyway) */

			if (pty_format != 8) {
				*context = XCLIB_XCOUT_NONE;
				return;
			}

			// not using INCR mechanism, just read the property
			XGetWindowProperty(m_display, win, m_atom.XCLIP_OUT, 0, (long) pty_size,
			                   False, AnyPropertyType, &pty_type,
			                   &pty_format, &pty_items, &pty_size, &buffer);

			/* finished with property, delete it */
			XDeleteProperty(m_display, win, m_atom.XCLIP_OUT);

			/* copy the buffer to the pointer for returned data */
			ltxt = (unsigned char *) malloc(pty_items);
			memcpy(ltxt, buffer, pty_items);

			/* set the length of the returned data */
			*len = pty_items;
			*txt = ltxt;

			/* free the buffer */
			XFree(buffer);

			*context = XCLIB_XCOUT_NONE;

			/* complete contents of selection fetched, return 1 */
			return;

		case XCLIB_XCOUT_INCR:
			/* To use the INCR method, we basically delete the
			 * property with the selection in it, wait for an
			 * event indicating that the property has been created,
			 * then read it, delete it, etc. */

			/* make sure that the event is relevant */
			if (evt->type != PropertyNotify)
				return;

			/* skip unless the property has a new value */
			if (evt->xproperty.state != PropertyNewValue)
				return;

			/* check size and format of the property */
			XGetWindowProperty(m_display, win, m_atom.XCLIP_OUT, 0, 0, False,
			                   AnyPropertyType, &pty_type, &pty_format,
			                   &pty_items, &pty_size, &buffer);

			if (pty_format != 8) {
				/* property does not contain text, delete it
				 * to tell the other X client that we have read
				 * it and to send the next property */
				XFree(buffer);
				XDeleteProperty(m_display, win, m_atom.XCLIP_OUT);
				return;
			}

			if (pty_size == 0) {
				/* no more data, exit from loop */
				XFree(buffer);
				XDeleteProperty(m_display, win, m_atom.XCLIP_OUT);
				*context = XCLIB_XCOUT_NONE;

				/* this means that an INCR transfer is now
				 * complete, return 1 */
				return;
			}

			XFree(buffer);

			/* if we have come this far, the property contains
			 * text, we know the size. */
			XGetWindowProperty(m_display, win, m_atom.XCLIP_OUT, 0, (long) pty_size,
			                   False, AnyPropertyType, &pty_type, &pty_format,
			                   &pty_items, &pty_size, &buffer);

			/* allocate memory to accommodate data in *txt */
			if (*len == 0) {
				*len = pty_items;
				ltxt = (unsigned char *) malloc(*len);
			}
			else {
				*len += pty_items;
				ltxt = (unsigned char *) realloc(ltxt, *len);
			}

			/* add data to ltxt */
			memcpy(&ltxt[*len - pty_items], buffer, pty_items);

			*txt = ltxt;
			XFree(buffer);

			/* delete property to get the next item */
			XDeleteProperty(m_display, win, m_atom.XCLIP_OUT);
			XFlush(m_display);
			return;
	}
	return;
}

GHOST_TUns8 *GHOST_SystemX11::getClipboard(bool selection) const
{
	Atom sseln;
	Atom target = m_atom.UTF8_STRING;
	Window owner;

	/* from xclip.c doOut() v0.11 */
	unsigned char *sel_buf;
	unsigned long sel_len = 0;
	XEvent evt;
	unsigned int context = XCLIB_XCOUT_NONE;

	if (selection == True)
		sseln = m_atom.PRIMARY;
	else
		sseln = m_atom.CLIPBOARD;

	vector<GHOST_IWindow *> & win_vec = m_windowManager->getWindows();
	vector<GHOST_IWindow *>::iterator win_it = win_vec.begin();
	GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
	Window win = window->getXWindow();

	/* check if we are the owner. */
	owner = XGetSelectionOwner(m_display, sseln);
	if (owner == win) {
		if (sseln == m_atom.CLIPBOARD) {
			sel_buf = (unsigned char *)malloc(strlen(txt_cut_buffer) + 1);
			strcpy((char *)sel_buf, txt_cut_buffer);
			return sel_buf;
		}
		else {
			sel_buf = (unsigned char *)malloc(strlen(txt_select_buffer) + 1);
			strcpy((char *)sel_buf, txt_select_buffer);
			return sel_buf;
		}
	}
	else if (owner == None)
		return(NULL);

	while (1) {
		/* only get an event if xcout() is doing something */
		if (context != XCLIB_XCOUT_NONE)
			XNextEvent(m_display, &evt);

		/* fetch the selection, or part of it */
		getClipboard_xcout(&evt, sseln, target, &sel_buf, &sel_len, &context);

		/* fallback is needed. set XA_STRING to target and restart the loop. */
		if (context == XCLIB_XCOUT_FALLBACK) {
			context = XCLIB_XCOUT_NONE;
			target = m_atom.STRING;
			continue;
		}
		else if (context == XCLIB_XCOUT_FALLBACK_UTF8) {
			/* utf8 fail, move to compouned text. */
			context = XCLIB_XCOUT_NONE;
			target = m_atom.COMPOUND_TEXT;
			continue;
		}
		else if (context == XCLIB_XCOUT_FALLBACK_COMP) {
			/* compouned text fail, move to text. */
			context = XCLIB_XCOUT_NONE;
			target = m_atom.TEXT;
			continue;
		}
		else if (context == XCLIB_XCOUT_FALLBACK_TEXT) {
			/* text fail, nothing else to try, break. */
			context = XCLIB_XCOUT_NONE;
		}

		/* only continue if xcout() is doing something */
		if (context == XCLIB_XCOUT_NONE)
			break;
	}

	if (sel_len) {
		/* only print the buffer out, and free it, if it's not
		 * empty
		 */
		unsigned char *tmp_data = (unsigned char *) malloc(sel_len + 1);
		memcpy((char *)tmp_data, (char *)sel_buf, sel_len);
		tmp_data[sel_len] = '\0';
		
		if (sseln == m_atom.STRING)
			XFree(sel_buf);
		else
			free(sel_buf);
		
		return tmp_data;
	}
	return(NULL);
}

void GHOST_SystemX11::putClipboard(GHOST_TInt8 *buffer, bool selection) const
{
	Window m_window, owner;

	vector<GHOST_IWindow *> & win_vec = m_windowManager->getWindows();
	vector<GHOST_IWindow *>::iterator win_it = win_vec.begin();
	GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
	m_window = window->getXWindow();

	if (buffer) {
		if (selection == False) {
			XSetSelectionOwner(m_display, m_atom.CLIPBOARD, m_window, CurrentTime);
			owner = XGetSelectionOwner(m_display, m_atom.CLIPBOARD);
			if (txt_cut_buffer)
				free((void *)txt_cut_buffer);

			txt_cut_buffer = (char *) malloc(strlen(buffer) + 1);
			strcpy(txt_cut_buffer, buffer);
		}
		else {
			XSetSelectionOwner(m_display, m_atom.PRIMARY, m_window, CurrentTime);
			owner = XGetSelectionOwner(m_display, m_atom.PRIMARY);
			if (txt_select_buffer)
				free((void *)txt_select_buffer);

			txt_select_buffer = (char *) malloc(strlen(buffer) + 1);
			strcpy(txt_select_buffer, buffer);
		}

		if (owner != m_window)
			fprintf(stderr, "failed to own primary\n");
	}
}

#ifdef WITH_XDND
GHOST_TSuccess GHOST_SystemX11::pushDragDropEvent(GHOST_TEventType eventType, 
		GHOST_TDragnDropTypes draggedObjectType,
		GHOST_IWindow *window,
		int mouseX, int mouseY,
		void *data)
{
	GHOST_SystemX11 *system = ((GHOST_SystemX11 *)getSystem());
	return system->pushEvent(new GHOST_EventDragnDrop(system->getMilliSeconds(),
	                                                  eventType,
	                                                  draggedObjectType,
	                                                  window, mouseX, mouseY, data)
	                         );
}
#endif

#ifdef WITH_X11_XINPUT
/* 
 * Dummy function to get around IO Handler exiting if device invalid
 * Basically it will not crash blender now if you have a X device that
 * is configured but not plugged in.
 */
int GHOST_X11_ApplicationErrorHandler(Display *display, XErrorEvent *theEvent)
{
	fprintf(stderr, "Ignoring Xlib error: error code %d request code %d\n",
	        theEvent->error_code, theEvent->request_code);

	/* No exit! - but keep lint happy */
	return 0;
}

int GHOST_X11_ApplicationIOErrorHandler(Display *display)
{
	fprintf(stderr, "Ignoring Xlib error: error IO\n");

	/* No exit! - but keep lint happy */
	return 0;
}

/* These C functions are copied from Wine 1.1.13's wintab.c */
#define BOOL int
#define TRUE 1
#define FALSE 0

static bool match_token(const char *haystack, const char *needle)
{
	const char *p, *q;
	for (p = haystack; *p; )
	{
		while (*p && isspace(*p))
			p++;
		if (!*p)
			break;

		for (q = needle; *q && *p && tolower(*p) == tolower(*q); q++)
			p++;
		if (!*q && (isspace(*p) || !*p))
			return TRUE;

		while (*p && !isspace(*p))
			p++;
	}
	return FALSE;
}


/* Determining if an X device is a Tablet style device is an imperfect science.
 * We rely on common conventions around device names as well as the type reported
 * by Wacom tablets.  This code will likely need to be expanded for alternate tablet types
 *
 * Wintab refers to any device that interacts with the tablet as a cursor,
 * (stylus, eraser, tablet mouse, airbrush, etc)
 * this is not to be confused with wacom x11 configuration "cursor" device.
 * Wacoms x11 config "cursor" refers to its device slot (which we mirror with
 * our gSysCursors) for puck like devices (tablet mice essentially).
 */
#if 0 // unused
static BOOL is_tablet_cursor(const char *name, const char *type)
{
	int i;
	static const char *tablet_cursor_whitelist[] = {
		"wacom",
		"wizardpen",
		"acecad",
		"tablet",
		"cursor",
		"stylus",
		"eraser",
		"pad",
		NULL
	};

	for (i = 0; tablet_cursor_whitelist[i] != NULL; i++) {
		if (name && match_token(name, tablet_cursor_whitelist[i]))
			return TRUE;
		if (type && match_token(type, tablet_cursor_whitelist[i]))
			return TRUE;
	}
	return FALSE;
}
#endif
static BOOL is_stylus(const char *name, const char *type)
{
	int i;
	static const char *tablet_stylus_whitelist[] = {
		"stylus",
		"wizardpen",
		"acecad",
		NULL
	};

	for (i = 0; tablet_stylus_whitelist[i] != NULL; i++) {
		if (name && match_token(name, tablet_stylus_whitelist[i]))
			return TRUE;
		if (type && match_token(type, tablet_stylus_whitelist[i]))
			return TRUE;
	}

	return FALSE;
}

static BOOL is_eraser(const char *name, const char *type)
{
	if (name && match_token(name, "eraser"))
		return TRUE;
	if (type && match_token(type, "eraser"))
		return TRUE;
	return FALSE;
}
#undef BOOL
#undef TRUE
#undef FALSE
/* end code copied from wine */

void GHOST_SystemX11::initXInputDevices()
{
	static XErrorHandler   old_handler = (XErrorHandler) 0;
	static XIOErrorHandler old_handler_io = (XIOErrorHandler) 0;

	XExtensionVersion *version = XGetExtensionVersion(m_display, INAME);

	if (version && (version != (XExtensionVersion *)NoSuchExtension)) {
		if (version->present) {
			int device_count;
			XDeviceInfo *device_info = XListInputDevices(m_display, &device_count);
			m_xtablet.StylusDevice = NULL;
			m_xtablet.EraserDevice = NULL;

			/* Install our error handler to override Xlib's termination behavior */
			old_handler = XSetErrorHandler(GHOST_X11_ApplicationErrorHandler);
			old_handler_io = XSetIOErrorHandler(GHOST_X11_ApplicationIOErrorHandler);

			for (int i = 0; i < device_count; ++i) {
				char *device_type = device_info[i].type ? XGetAtomName(m_display, device_info[i].type) : NULL;
				
//				printf("Tablet type:'%s', name:'%s', index:%d\n", device_type, device_info[i].name, i);


				if ((m_xtablet.StylusDevice == NULL) &&
				    (is_stylus(device_info[i].name, device_type) || (device_info[i].type == m_atom.TABLET)))
				{
//					printf("\tfound stylus\n");
					m_xtablet.StylusID = device_info[i].id;
					m_xtablet.StylusDevice = XOpenDevice(m_display, m_xtablet.StylusID);

					if (m_xtablet.StylusDevice != NULL) {
						/* Find how many pressure levels tablet has */
						XAnyClassPtr ici = device_info[i].inputclassinfo;
						for (int j = 0; j < m_xtablet.StylusDevice->num_classes; ++j) {
							if (ici->c_class == ValuatorClass) {
//								printf("\t\tfound ValuatorClass\n");
								XValuatorInfo *xvi = (XValuatorInfo *)ici;
								m_xtablet.PressureLevels = xvi->axes[2].max_value;

								if (xvi->num_axes > 3) {
									/* this is assuming that the tablet has the same tilt resolution in both
									 * positive and negative directions. It would be rather weird if it didn't.. */
									m_xtablet.XtiltLevels = xvi->axes[3].max_value;
									m_xtablet.YtiltLevels = xvi->axes[4].max_value;
								}
								else {
									m_xtablet.XtiltLevels = 0;
									m_xtablet.YtiltLevels = 0;
								}

								break;
							}
						
							ici = (XAnyClassPtr)(((char *)ici) + ici->length);
						}
					}
					else {
						m_xtablet.StylusID = 0;
					}
				}
				else if ((m_xtablet.EraserDevice == NULL) &&
				         (is_eraser(device_info[i].name, device_type)))
				{
//					printf("\tfound eraser\n");
					m_xtablet.EraserID = device_info[i].id;
					m_xtablet.EraserDevice = XOpenDevice(m_display, m_xtablet.EraserID);
					if (m_xtablet.EraserDevice == NULL) m_xtablet.EraserID = 0;
				}

				if (device_type) {
					XFree((void *)device_type);
				}
			}

			/* Restore handler */
			(void) XSetErrorHandler(old_handler);
			(void) XSetIOErrorHandler(old_handler_io);

			XFreeDeviceList(device_info);
		}
		XFree(version);
	}
}

#endif /* WITH_X11_XINPUT */