~hikiko/nux/arb-srgba-shader

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


#include "GLResource.h"
#include "GpuDevice.h"
#include "GLDeviceObjects.h"
#include "GLResourceManager.h"

#include "GLTextureResourceManager.h"
#include "GLVertexResourceManager.h"
#include "GraphicsEngine.h"
#include "GLWindowManager.h"
#include "Events.h"

#include "GraphicsDisplay.h"

#include <X11/extensions/shape.h>

namespace nux
{
  int GraphicsDisplay::double_click_time_delay = 400; // milliseconds

  GraphicsDisplay::GraphicsDisplay()
    : m_X11Display(NULL)
    , m_X11Screen(0)
    , m_ParentWindow(0)
    , m_GLCtx(0)
#ifndef NUX_OPENGLES_20    
    , glx_window_(0)
#endif
    , m_NumVideoModes(0)
    , m_BorderPixel(0)
    , _x11_major(0)
    , _x11_minor(0)
    , _glx_major(0)
    , _glx_minor(0)
    , _has_glx_13(false)
    , m_X11RepeatKey(true)
    , m_ViewportSize(Size(0,0))
    , m_WindowSize(Size(0,0))
    , m_WindowPosition(Point(0,0)) 
    , m_Fullscreen(false)
    , m_ScreenBitDepth(32)
    , m_GfxInterfaceCreated(false)
    , m_BestMode(-1)
    , m_CreatedFromForeignWindow(false)
    , last_click_time_(0)
    , double_click_counter_(0)
    , m_num_device_modes(0)
    , m_pEvent(NULL)
    , _last_dnd_position(Point(0, 0)) //DND
    , m_PauseGraphicsRendering(false)
    , m_FrameTime(0) 
    , m_DeviceFactory(0)
    , m_GraphicsContext(0)
    , m_Style(WINDOWSTYLE_NORMAL)
    , _drag_display(NULL)
    , _drag_drop_timestamp(0)
    , _dnd_source_data(NULL)
    , _dnd_source_window(0)
    , _global_pointer_grab_data(0)
    , _global_pointer_grab_active(false)
    , _global_pointer_grab_callback(0)
    , _global_keyboard_grab_data(0)
    , _global_keyboard_grab_active(false)
    , _global_keyboard_grab_callback(0)
    , _dnd_is_drag_source(false)
    , _dnd_source_target_accepts_drop(false)
    , _dnd_source_grab_active(false)
    , _dnd_source_drop_sent(false)
  {
    inlSetThreadLocalStorage(_TLS_GraphicsDisplay, this);

    m_X11LastEvent.type = -1;

    m_pEvent = new Event();

    _dnd_source_funcs.get_drag_image = 0;
    _dnd_source_funcs.get_drag_types = 0;
    _dnd_source_funcs.get_data_for_type = 0;
    _dnd_source_funcs.drag_finished = 0;
  }

  GraphicsDisplay::~GraphicsDisplay()
  {
    NUX_SAFE_DELETE( m_GraphicsContext );
    NUX_SAFE_DELETE( m_DeviceFactory );

    if (m_CreatedFromForeignWindow == false)
    {
      DestroyOpenGLWindow();
    }
    
    NUX_SAFE_DELETE( m_pEvent );
    inlSetThreadLocalStorage(_TLS_GraphicsDisplay, 0);
  }

  NString GraphicsDisplay::FindResourceLocation(const char *ResourceFileName, bool ErrorOnFail)
  {
    NString path = m_ResourcePathLocation.GetFile(ResourceFileName);

    if (path == "" && ErrorOnFail)
    {
      nuxCriticalMsg("[GraphicsDisplay::FindResourceLocation] Failed to locate resource file: %s.", ResourceFileName);
      return NString("");
    }

    return path;
  }

  NString GraphicsDisplay::FindUITextureLocation(const char *ResourceFileName, bool ErrorOnFail)
  {
    FilePath searchpath;
    searchpath.AddSearchPath(m_UITextureSearchPath);
    NString path = searchpath.GetFile(ResourceFileName);

    if ((path == "") && ErrorOnFail)
    {
      nuxCriticalMsg("[GraphicsDisplay::FindResourceLocation] Failed to locate ui texture file: %s.", ResourceFileName);
      return NString("");
    }

    return path;
  }

  NString GraphicsDisplay::FindShaderLocation(const char *ResourceFileName, bool ErrorOnFail)
  {
    FilePath searchpath;
    searchpath.AddSearchPath(m_ShaderSearchPath);
    NString path = searchpath.GetFile(ResourceFileName);

    if ((path == "") && ErrorOnFail)
    {
      nuxCriticalMsg("[GraphicsDisplay::FindResourceLocation] Failed to locate shader file: %s.", ResourceFileName);
      return NString("");
    }

    return path;
  }

  NString GraphicsDisplay::FindFontLocation(const char *ResourceFileName, bool ErrorOnFail)
  {
    FilePath searchpath;
    searchpath.AddSearchPath(m_FontSearchPath);
    NString path = searchpath.GetFile(ResourceFileName);

    if ((path == "") && ErrorOnFail)
    {
      nuxCriticalMsg("[GraphicsDisplay::FindResourceLocation] Failed to locate font file file: %s.", ResourceFileName);
      return NString("");
    }

    return path;
  }



  bool GraphicsDisplay::IsGfxInterfaceCreated()
  {
    return m_GfxInterfaceCreated;
  }

  static Bool WaitForNotify( Display *dpy, XEvent *event, XPointer arg )
  {
    return(event->type == MapNotify) && (event->xmap.window == (Window) arg);
  }

// TODO: change windowWidth, windowHeight, to window_size;
  static NCriticalSection CreateOpenGLWindow_CriticalSection;
  bool GraphicsDisplay::CreateOpenGLWindow(const char *WindowTitle,
                                         unsigned int WindowWidth,
                                         unsigned int WindowHeight,
                                         WindowStyle Style,
                                         const GraphicsDisplay *Parent,
                                         bool FullscreenFlag,
                                         bool create_rendering_data)
  {
    int xinerama_event, xinerama_error;
    int xinerama_major, xinerama_minor;
    NScopeLock Scope(&CreateOpenGLWindow_CriticalSection);

    m_GfxInterfaceCreated = false;

    // FIXME : put at the end
    Size new_size(WindowWidth, WindowHeight);
    m_ViewportSize = new_size;
    m_WindowSize = new_size;
    // end of fixme

    m_Fullscreen = FullscreenFlag;  // Set The Global Fullscreen Flag
    m_BestMode = -1;                // assume -1 if the mode is not fullscreen

    // Open The display.
    m_X11Display = XOpenDisplay(0);

    if (m_X11Display == 0)
    {
      nuxDebugMsg("[GraphicsDisplay::CreateOpenGLWindow] XOpenDisplay has failed. The window cannot be created.");
      return false;
    }

    m_X11Screen = DefaultScreen(m_X11Display);
    XF86VidModeQueryVersion(m_X11Display, &_x11_major, &_x11_minor);
    XineramaQueryVersion(m_X11Display, &xinerama_major, &xinerama_minor);
    XineramaQueryExtension(m_X11Display, &xinerama_event, &xinerama_error);

    XF86VidModeGetAllModeLines(m_X11Display, m_X11Screen, &m_NumVideoModes, &m_X11VideoModes);
    m_X11OriginalVideoMode = *m_X11VideoModes[0];

    if (m_Fullscreen)               // Attempt Fullscreen Mode?
    {
      // check if resolution is supported
      bool mode_supported = false;

      for (int num_modes = 0 ; num_modes < m_NumVideoModes; num_modes++)
      {
        if ((m_X11VideoModes[num_modes]->hdisplay == m_ViewportSize.width )
          && (m_X11VideoModes[num_modes]->vdisplay == m_ViewportSize.height ))
        {
          mode_supported = true;
          m_BestMode = num_modes;
          break;
        }
      }

      if (mode_supported == false)
      {
        m_Fullscreen = false;
      }
    }

#ifndef NUX_OPENGLES_20
    // Check support for GLX
    int dummy0, dummy1;
    if (!glXQueryExtension(m_X11Display, &dummy0, &dummy1))
    {
      nuxCriticalMsg("[GraphicsDisplay::CreateOpenGLWindow] GLX is not supported.");
      return false;
    }

    // Check GLX version
    glXQueryVersion(m_X11Display, &_glx_major, &_glx_minor);

    // FBConfigs support added in GLX version 1.3
    if (((_glx_major == 1) && (_glx_minor < 3)) || (_glx_major < 1))
    {
      _has_glx_13 = false;
    }
    else
    {
      _has_glx_13 = true;
    }

    _has_glx_13 = false; // force old way. this is temporary...
 
    if (_has_glx_13 == false)
    {
      // Find an OpenGL capable visual.
      static int g_DoubleBufferVisual[] =
      {
        GLX_RGBA,
        GLX_DOUBLEBUFFER,
        GLX_RED_SIZE,       8,
        GLX_GREEN_SIZE,     8,
        GLX_BLUE_SIZE,      8,
        GLX_ALPHA_SIZE,     8,
        GLX_DEPTH_SIZE,     24,
        GLX_STENCIL_SIZE,   8,
        None
      };

      m_X11VisualInfo = glXChooseVisual(m_X11Display, m_X11Screen, g_DoubleBufferVisual);

      if (m_X11VisualInfo == NULL)
      {
        nuxDebugMsg("[GraphicsDisplay::CreateOpenGLWindow] Cannot get appropriate visual.");
        return false;
      }

      // Create OpenGL Context.
      m_GLCtx = glXCreateContext(m_X11Display, m_X11VisualInfo, 0, GL_TRUE);

      m_X11Colormap = XCreateColormap(m_X11Display,
                                       RootWindow(m_X11Display, m_X11VisualInfo->screen),
                                       m_X11VisualInfo->visual,
                                       AllocNone);
    }
    else
    {
        int DoubleBufferAttributes[] =
        {
          //GLX_X_RENDERABLE, True,
          GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
          GLX_RENDER_TYPE,   GLX_RGBA_BIT,
          GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
          GLX_DOUBLEBUFFER,  True,
          GLX_RED_SIZE,      8,     /* the maximum number of bits per component    */
          GLX_GREEN_SIZE,    8, 
          GLX_BLUE_SIZE,     8,
          GLX_ALPHA_SIZE,    8,
          GLX_DEPTH_SIZE,    24,
          GLX_STENCIL_SIZE,  8,
          None
        };

        GLXFBConfig *fbconfigs = NULL;
        int         fbcount;

        #define GET_PROC(proc_type, proc_name, check)       \
        do                                                  \
        {                                                   \
          proc_name = (proc_type) glXGetProcAddress((const GLubyte *) #proc_name); \
        } while (0)

        /* initialize GLX 1.3 function pointers */
        GET_PROC(PFNGLXGETFBCONFIGSPROC,              glXGetFBConfigs, false);
        GET_PROC(PFNGLXGETFBCONFIGATTRIBPROC,         glXGetFBConfigAttrib, false);
        GET_PROC(PFNGLXGETVISUALFROMFBCONFIGPROC,     glXGetVisualFromFBConfig, false);
        GET_PROC(PFNGLXCREATEWINDOWPROC,              glXCreateWindow, false);
        GET_PROC(PFNGLXDESTROYWINDOWPROC,             glXDestroyWindow, false);
        GET_PROC(PFNGLXCREATEPIXMAPPROC,              glXCreatePixmap, false);
        GET_PROC(PFNGLXDESTROYPIXMAPPROC,             glXDestroyPixmap, false);
        GET_PROC(PFNGLXCREATEPBUFFERPROC,             glXCreatePbuffer, false);
        GET_PROC(PFNGLXDESTROYPBUFFERPROC,            glXDestroyPbuffer, false);
        GET_PROC(PFNGLXCREATENEWCONTEXTPROC,          glXCreateNewContext, false);
        GET_PROC(PFNGLXMAKECONTEXTCURRENTPROC,        glXMakeContextCurrent, false);
        GET_PROC(PFNGLXCHOOSEFBCONFIGPROC,            glXChooseFBConfig, false);
        
        /* GLX_SGIX_pbuffer */
        GET_PROC(PFNGLXCREATEGLXPBUFFERSGIXPROC,      glXCreateGLXPbufferSGIX, false);
        GET_PROC(PFNGLXDESTROYGLXPBUFFERSGIXPROC,     glXDestroyGLXPbufferSGIX, false);
        #undef GET_PROC


        // Request a double buffer configuration
        fbconfigs = glXChooseFBConfig(m_X11Display, DefaultScreen(m_X11Display), DoubleBufferAttributes, &fbcount);

        if (fbconfigs == NULL)
        {
          nuxCriticalMsg("[GraphicsDisplay::CreateOpenGLWindow] glXChooseFBConfig cannot get a supported configuration.");
          return false;
        }

        // Select best multi-sample config.
        if ((_glx_major >= 1) && (_glx_minor >= 4))
        {
          int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999;
          for (int i = 0; i < fbcount; i++)
          {
            XVisualInfo *vi = glXGetVisualFromFBConfig(m_X11Display, fbconfigs[i]);
            if (vi)
            {
              int sample_buf, samples;
              glXGetFBConfigAttrib(m_X11Display, fbconfigs[i], GLX_SAMPLE_BUFFERS, &sample_buf);
              glXGetFBConfigAttrib(m_X11Display, fbconfigs[i], GLX_SAMPLES       , &samples);

              //nuxDebugMsg("Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d SAMPLES = %d\n", i, vi->visualid, sample_buf, samples);

              if (((best_fbc < 0) || sample_buf) && (samples > best_num_samp))
              {
                best_fbc = i;
                best_num_samp = samples; 
              }

              if ((worst_fbc < 0) || (!sample_buf) || (samples < worst_num_samp))
              {
                worst_fbc = i;
                worst_num_samp = samples;
              }
            }
            XFree(vi);
          }

          nuxAssertMsg(best_fbc >= 0, "[GraphicsDisplay::CreateOpenGLWindow] Invalid frame buffer config.");

          _fb_config = fbconfigs[best_fbc];
        }
        else
        {
          // Choose the first one
          _fb_config = fbconfigs[0];
        }

        XFree(fbconfigs);

        m_X11VisualInfo = glXGetVisualFromFBConfig(m_X11Display, _fb_config);

        m_X11Colormap = XCreateColormap(m_X11Display, RootWindow(m_X11Display, m_X11VisualInfo->screen),
          m_X11VisualInfo->visual,
          AllocNone);
    }
#else
    EGLDisplay dpy = eglGetDisplay((EGLNativeDisplayType)m_X11Display);
    if (dpy == EGL_NO_DISPLAY)
    {
      nuxDebugMsg("[GraphicsDisplay::CreateOpenGLWindow] Cannot get EGL display.");
      return false;
    }
    EGLint            major, minor;
    if (!eglInitialize(dpy, &major, &minor))
    {
      nuxDebugMsg("[GraphicsDisplay::CreateOpenGLWindow] Cannot initialize EGL.");
      return false;
    }

    eglBindAPI(EGL_OPENGL_ES_API);

    const EGLint config_attribs[] =
    {
      EGL_SURFACE_TYPE,         EGL_WINDOW_BIT,
      EGL_RED_SIZE,             1,
      EGL_GREEN_SIZE,           1,
      EGL_BLUE_SIZE,            1,
      EGL_ALPHA_SIZE,           1,
      EGL_DEPTH_SIZE,           1,
      EGL_RENDERABLE_TYPE,      EGL_OPENGL_ES2_BIT,
      EGL_CONFIG_CAVEAT,        EGL_NONE,
      EGL_NONE,
    };
    EGLConfig         configs[1024];
    EGLint            count;
    if (!eglChooseConfig(dpy, config_attribs, configs, 1024, &count))
    {
      nuxDebugMsg("[GraphicsDisplay::CreateOpenGLWindow] Cannot get EGL config.");
      return false;
    }

    EGLConfig config = configs[0];
    EGLint visualid = 0;
    if (!eglGetConfigAttrib(dpy, config, EGL_NATIVE_VISUAL_ID, &visualid))
    {
      nuxDebugMsg("[GraphicsDisplay::CreateOpenGLWindow] Cannot get native visual ID from EGL config.");
      return false;
    }

    XVisualInfo       visual_info = {0};
    visual_info.visualid = visualid;
    m_X11VisualInfo = XGetVisualInfo(m_X11Display, VisualIDMask, &visual_info, &count);
    if (!m_X11VisualInfo)
    {
      nuxCriticalMsg("[GraphicsDisplay::CreateOpenGLWindow] Cannot get appropriate visual.");
      return false;
    }

    m_X11Colormap = XCreateColormap(m_X11Display,
                                     RootWindow(m_X11Display, m_X11VisualInfo->screen),
                                     m_X11VisualInfo->visual,
                                     AllocNone);
#endif

    m_X11Attr.background_pixmap = 0;
    m_X11Attr.border_pixel      = 0;
    m_X11Attr.colormap          = m_X11Colormap;
    m_X11Attr.override_redirect = m_Fullscreen;
    m_X11Attr.event_mask =
      // Mouse
      /*Button1MotionMask |
      Button2MotionMask |
      Button3MotionMask |
      Button4MotionMask |
      Button5MotionMask |
      ButtonMotionMask |*/
      ButtonPressMask |
      ButtonReleaseMask |
      // Mouse motion
      //-OwnerGrabButtonMask |
      //PointerMotionHintMask |
      PointerMotionMask |
      // Keyboard
      //--KeymapStateMask |
      KeyPressMask    |
      KeyReleaseMask  |
      // Window enter/exit
      LeaveWindowMask |
      EnterWindowMask |
      // Exposure Focus
      ExposureMask |
      FocusChangeMask |
      // Structure notify
      //--ResizeRedirectMask |
      StructureNotifyMask;// |
    //--SubstructureNotifyMask |
    //--SubstructureRedirectMask |
    // Visibility
    //--VisibilityChangeMask |
    // Property
    //--PropertyChangeMask |
    // Colormap
    //--ColormapChangeMask |
    // No event
    //--NoEventMask;


    if (m_Fullscreen)
    {
      XF86VidModeSwitchToMode(m_X11Display, m_X11Screen, m_X11VideoModes[m_BestMode]);
      XF86VidModeSetViewPort(m_X11Display, m_X11Screen, 0, 0);
      //Width = m_X11VideoModes[m_BestMode]->hdisplay;
      //Height = m_X11VideoModes[m_BestMode]->vdisplay;
      XFree(m_X11VideoModes);

      /* create a fullscreen window */

      m_X11Window = XCreateWindow(m_X11Display,
                                   RootWindow(m_X11Display, m_X11VisualInfo->screen),
                                   0, 0,                           // X, Y
                                   m_WindowSize.width, m_WindowSize.height,
                                   0,                              // Border
                                   m_X11VisualInfo->depth,         // Depth
                                   InputOutput,                    // Class
                                   m_X11VisualInfo->visual,        // Visual
                                   CWBorderPixel |
                                   CWColormap |
                                   CWEventMask |
                                   CWOverrideRedirect,
                                   &m_X11Attr);

      XWarpPointer(m_X11Display, None, m_X11Window, 0, 0, 0, 0, 0, 0);
      //XMapRaised(m_X11Display, m_X11Window);
      XGrabKeyboard(m_X11Display, m_X11Window, True,
                     GrabModeAsync,
                     GrabModeAsync,
                     CurrentTime);
      XGrabPointer(m_X11Display, m_X11Window, True,
                    ButtonPressMask,
                    GrabModeAsync, GrabModeAsync, m_X11Window, None, CurrentTime);
    }
    else
    {
      m_X11Window = XCreateWindow(m_X11Display,
                                   RootWindow(m_X11Display, m_X11VisualInfo->screen),
                                   0, 0,
                                   m_WindowSize.width, m_WindowSize.height,
                                   0,
                                   m_X11VisualInfo->depth,
                                   InputOutput,
                                   m_X11VisualInfo->visual,
                                   CWBorderPixel |
                                   CWColormap |
                                   CWEventMask |
                                   CWOverrideRedirect,
                                   &m_X11Attr);

      /* only set window title and handle wm_delete_events if in windowed mode */
      m_WMDeleteWindow = XInternAtom(m_X11Display, "WM_DELETE_WINDOW", True);
      XSetWMProtocols(m_X11Display, m_X11Window, &m_WMDeleteWindow, 1);

      XSetStandardProperties(m_X11Display, m_X11Window, WindowTitle, WindowTitle, None, NULL, 0, NULL);
      //XMapRaised(m_X11Display, m_X11Window);
    }

#ifndef NUX_OPENGLES_20
    if (_has_glx_13)
    {
      XFree(m_X11VisualInfo);
      m_X11VisualInfo = 0;

      /* Create a GLX context for OpenGL rendering */
      m_GLCtx = glXCreateNewContext(m_X11Display, _fb_config, GLX_RGBA_TYPE, NULL, True);

      if (m_GLCtx == 0)
      {
        nuxDebugMsg("[GraphicsDisplay::CreateOpenGLWindow] m_GLCtx is null");
      }

      /* Create a GLX window to associate the frame buffer configuration
      ** with the created X window */
      glx_window_ = glXCreateWindow(m_X11Display, _fb_config, m_X11Window, NULL);

      // Map the window to the screen, and wait for it to appear */
      XMapWindow(m_X11Display, m_X11Window);
      XEvent event;
      XIfEvent(m_X11Display, &event, WaitForNotify, (XPointer) m_X11Window);

      /* Bind the GLX context to the Window */
      glXMakeContextCurrent(m_X11Display, glx_window_, glx_window_, m_GLCtx);
    }
#else
    m_GLSurface = eglCreateWindowSurface(dpy, config, (EGLNativeWindowType)m_X11Window, 0);
    if (!m_GLSurface)
    {
      nuxCriticalMsg("[GraphicsDisplay::CreateOpenGLWindow] Failed to create surface.");
      return false;
    }

    const EGLint context_attribs[] =
    {
      EGL_CONTEXT_CLIENT_VERSION, 2,
      EGL_NONE
    };
    m_GLCtx = eglCreateContext(dpy, config, EGL_NO_CONTEXT, context_attribs);
    if (m_GLCtx == EGL_NO_CONTEXT)
    {
      nuxCriticalMsg("[GraphicsDisplay::CreateOpenGLWindow] Failed to create EGL context.");
      return false;
    }
#endif

    MakeGLContextCurrent();

    m_GfxInterfaceCreated = true;

    m_DeviceFactory = new GpuDevice(m_ViewportSize.width, m_ViewportSize.height, BITFMT_R8G8B8A8,
        m_X11Display,
        m_X11Window,
        _has_glx_13,
        _fb_config,
        m_GLCtx,
        1, 0, false);

    m_GraphicsContext = new GraphicsEngine(*this);

    //EnableVSyncSwapControl();
    //DisableVSyncSwapControl();
        
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    SwapBuffer();
    
       
    InitGlobalGrabWindow();

    return TRUE;
  }

#ifdef NUX_OPENGLES_20
  bool GraphicsDisplay::CreateFromOpenGLWindow(Display *X11Display, Window X11Window, EGLContext OpenGLContext)
#else
  bool GraphicsDisplay::CreateFromOpenGLWindow(Display *X11Display, Window X11Window, GLXContext OpenGLContext)
#endif
  {
    // Do not make the opengl context current
    // Do not swap the framebuffer
    // Do not clear the depth or color buffer
    // Do not enable/disbale VSync

    m_X11Display = X11Display;
    m_X11Window = X11Window;
    m_GLCtx = OpenGLContext;

    m_X11Screen = DefaultScreen(m_X11Display);

    Window root_return;
    int x_return, y_return;
    unsigned int width_return, height_return;
    unsigned int border_width_return;
    unsigned int depth_return;

    XGetGeometry(X11Display, X11Window, &root_return, &x_return, &y_return, &width_return, &height_return, &border_width_return, &depth_return);
    m_WindowSize = Size(width_return, height_return);
    m_WindowPosition = Point(x_return, y_return);

    m_ViewportSize = Size(width_return, height_return);

    m_GfxInterfaceCreated = true;

    // m_DeviceFactory = new GpuDevice(m_ViewportSize.GetWidth(), m_ViewportSize.GetHeight(), BITFMT_R8G8B8A8);
    m_DeviceFactory = new GpuDevice(m_ViewportSize.width, m_ViewportSize.height, BITFMT_R8G8B8A8,
        m_X11Display,
        m_X11Window,
        false,
        _fb_config,
        m_GLCtx,
        1, 0, false);
    m_GraphicsContext = new GraphicsEngine(*this);

    InitGlobalGrabWindow();

    m_CreatedFromForeignWindow = true;

    return true;
  }

  GraphicsEngine* GraphicsDisplay::GetGraphicsEngine() const
  {
    return m_GraphicsContext;
  }

  GpuDevice* GraphicsDisplay::GetGpuDevice() const
  {
    return m_DeviceFactory;
  }

  int GraphicsDisplay::GetGlXMajor() const
  {
    return _glx_major;
  }

  int GraphicsDisplay::GetGlXMinor() const
  {
    return _glx_minor;
  }

  bool GraphicsDisplay::HasFrameBufferSupport()
  {
    return m_DeviceFactory->GetGpuInfo().Support_EXT_Framebuffer_Object();
  }

// TODO(thumper): Size const& GraphicsDisplay::GetWindowSize();
  void GraphicsDisplay::GetWindowSize(int &w, int &h)
  {
    w = m_WindowSize.width;
    h = m_WindowSize.height;
  }

  void GraphicsDisplay::GetDesktopSize(int &w, int &h)
  {
    Window root;
    int x, y;
    unsigned int width, height, depth, border_width;
    bool ret = XGetGeometry(m_X11Display, RootWindow(m_X11Display, m_X11Screen),
                             &root,
                             &x, &y,
                             &width, &height, &border_width, &depth);

    if (ret == false)
    {
      nuxAssert("[GetDesktopSize] Failed to get the desktop size");
      w = 0;
      h = 0;
    }
  }

  void GraphicsDisplay::SetWindowSize(int width, int height)
  {
    nuxDebugMsg("[GraphicsDisplay::SetWindowSize] Setting window size to %dx%d", width, height);
    // Resize window client area
    XResizeWindow(m_X11Display, m_X11Window, width, height);
    XFlush(m_X11Display);
  }

  void GraphicsDisplay::SetWindowPosition(int x, int y)
  {
    nuxDebugMsg("[GraphicsDisplay::SetWindowPosition] Setting window position to %dx%d", x, y);
    // Resize window client area
    XMoveWindow(m_X11Display, m_X11Window, x, y);
    XFlush(m_X11Display);
  }

  int GraphicsDisplay::GetWindowWidth()
  {
    return m_WindowSize.width;
  }

  int GraphicsDisplay::GetWindowHeight()
  {
    return m_WindowSize.height;
  }

  void GraphicsDisplay::SetViewPort(int x, int y, int width, int height)
  {
    if (IsGfxInterfaceCreated())
    {
      //do not rely on m_ViewportSize: glViewport can be called directly
      m_ViewportSize = Size(width, height);
      m_GraphicsContext->SetViewport(x, y, width, height);
      m_GraphicsContext->SetScissor(0, 0, width, height);
    }
  }

  void GraphicsDisplay::ResetWindowSize()
  {
    Window root_return;
    int x_return, y_return;
    unsigned int width_return, height_return;
    unsigned int border_width_return;
    unsigned int depth_return;

    XGetGeometry(m_X11Display,
      m_X11Window,
      &root_return,
      &x_return,
      &y_return,
      &width_return,
      &height_return,
      &border_width_return,
      &depth_return);

    m_WindowSize = Size(width_return, height_return);
    m_WindowPosition = Point(x_return, y_return);
  }

  Point GraphicsDisplay::GetMouseScreenCoord()
  {
    Window root_return;
    Window child_return;
    int root_x_return;
    int root_y_return;
    int win_x_return;
    int win_y_return;
    unsigned int mask_return;


    XQueryPointer(m_X11Display,
                   RootWindow(m_X11Display, m_X11Screen),
                   &root_return,
                   &child_return,
                   &root_x_return,
                   &root_y_return,
                   &win_x_return,
                   &win_y_return,
                   &mask_return);
    XFlush(m_X11Display);

    return Point(root_x_return, root_y_return);
  }

  Point GraphicsDisplay::GetMouseWindowCoord()
  {
    Window root_return;
    Window child_return;
    int root_x_return;
    int root_y_return;
    int win_x_return;
    int win_y_return;
    unsigned int mask_return;

    XQueryPointer(m_X11Display,
                   RootWindow(m_X11Display, m_X11Screen),
                   &root_return,
                   &child_return,
                   &root_x_return,
                   &root_y_return,
                   &win_x_return,
                   &win_y_return,
                   &mask_return);
    XFlush(m_X11Display);

    return Point(win_x_return, win_y_return);
  }

  Point GraphicsDisplay::GetWindowCoord()
  {
    XWindowAttributes attrib;
    int status = XGetWindowAttributes(m_X11Display, m_X11Window, &attrib);

    if (status == 0)
    {
      nuxAssert("[GraphicsDisplay::GetWindowCoord] Failed to get the window attributes.");
      return Point(0, 0);
    }

    return Point(attrib.x, attrib.y);
  }

  Rect GraphicsDisplay::GetWindowGeometry()
  {
    return Rect(m_WindowPosition.x, m_WindowPosition.y, m_WindowSize.width, m_WindowSize.height);
  }

  Rect GraphicsDisplay::GetNCWindowGeometry()
  {
    return Rect(m_WindowPosition.x, m_WindowPosition.y, m_WindowSize.width, m_WindowSize.height);
  }

  void GraphicsDisplay::MakeGLContextCurrent()
  {
#ifndef NUX_OPENGLES_20
    if (_has_glx_13)
    {
      nuxDebugMsg("Has glx 1.3");
      if (!glXMakeContextCurrent(m_X11Display, glx_window_, glx_window_, m_GLCtx))
      {
        nuxDebugMsg("Destroy");
        DestroyOpenGLWindow();
      }
    }
    else if (!glXMakeCurrent(m_X11Display, m_X11Window, m_GLCtx))
    {
      DestroyOpenGLWindow();
    }
#else
    EGLDisplay dpy = eglGetDisplay((EGLNativeDisplayType)m_X11Display);

    if (!eglMakeCurrent(dpy, m_GLSurface, m_GLSurface, m_GLCtx))
    {
      DestroyOpenGLWindow();
    }
#endif
  }

  void GraphicsDisplay::SwapBuffer(bool glswap)
  {
    // There are a lot of mouse motion events coming from X11. The system processes one event at a time and sleeps
    // if necessary to cap the frame rate to 60 frames per seconds. But while the thread sleeping, there are accumulated
    // motion events waiting to be processed. This creates an increasing backlog of motion events. It translate into a slow
    // motion of elements that moves in response to the mouse.
    // Solution: if the the current event is a motion event, changes are, it is followed many more motion events.
    // In this case, don't sleep the thread... Swap the framebuffer to see the result of the current single motion event.
    // It maybe worth investigating how to properly balance event processing and drawing in order to keep the
    // frame rate and the responsiveness at acceptable levels.
    // As a consequence, when the mouse is moving, the frame rate goes beyond 60fps.

    /*bool bsleep = true;
    if (XPending(m_X11Display) > 0)
    {
        XEvent xevent;
        XPeekEvent(m_X11Display, &xevent);
        if (xevent.type == MotionNotify)
        {
            //nuxDebugMsg("[GraphicsDisplay::SwapBuffer]: MotionNotify event.");
            bsleep = false;
        }
    }*/

    if (IsPauseThreadGraphicsRendering())
      return;

    if (glswap)
    {
#ifndef NUX_OPENGLES_20
      if (_has_glx_13)
        glXSwapBuffers(m_X11Display, glx_window_);
      else
        glXSwapBuffers(m_X11Display, m_X11Window);
#else
      eglSwapBuffers(eglGetDisplay((EGLNativeDisplayType)m_X11Display), m_GLSurface);
#endif
    }

    m_FrameTime = m_Timer.PassedMilliseconds();
  }

  void GraphicsDisplay::DestroyOpenGLWindow()
  {
    if (m_GfxInterfaceCreated == true)
    {
      if (m_GLCtx == 0)
      {
        nuxDebugMsg("[GraphicsDisplay::DestroyOpenGLWindow] m_GLCtx is null");
      }

      if (m_GLCtx)
      {
#ifndef NUX_OPENGLES_20

        // Release the current context
        if (_has_glx_13)
        {
          if (!glXMakeContextCurrent(m_X11Display, None, None, NULL))
          {
            nuxAssert("[GraphicsDisplay::DestroyOpenGLWindow] glXMakeContextCurrent failed.");
          }
        }
        else
        {
          if (!glXMakeCurrent(m_X11Display, None, NULL))
          {
            nuxAssert("[GraphicsDisplay::DestroyOpenGLWindow] glXMakeCurrent failed.");
          }
        }

        glXDestroyContext(m_X11Display, m_GLCtx);

        if (_has_glx_13)
        {
          glXDestroyWindow(m_X11Display, glx_window_);
        }
#else
        EGLDisplay dpy = eglGetDisplay((EGLNativeDisplayType)m_X11Display);

        if (!eglMakeCurrent(dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT))
        {
          nuxAssert("[GraphicsDisplay::DestroyOpenGLWindow] eglMakeCurrent failed.");
        }

        eglDestroyContext(dpy, m_GLCtx);
        eglDestroySurface(dpy, m_GLSurface);
        eglTerminate(dpy);
        eglReleaseThread();
#endif
        m_GLCtx = NULL;
      }

      /* switch back to original desktop resolution if we were in fs */
      if (m_Fullscreen)
      {
        XF86VidModeSwitchToMode(m_X11Display, m_X11Screen, &m_X11OriginalVideoMode);
        XF86VidModeSetViewPort(m_X11Display, m_X11Screen, 0, 0);
      }

      XDestroyWindow(m_X11Display, m_X11Window);
      XFreeColormap(m_X11Display, m_X11Colormap);
      XCloseDisplay(m_X11Display);
    }

    m_GfxInterfaceCreated = false;
  }

  int GraphicsDisplay::MouseMove(XEvent xevent, Event *m_pEvent)
  {
    // Erase mouse event and mouse doubleclick events. Keep the mouse states.
    unsigned int _mouse_state = m_pEvent->mouse_state & 0x0F000000;

    m_pEvent->type = NUX_MOUSE_MOVE;

    if (xevent.type == MotionNotify)
    {
      _mouse_state |= (xevent.xmotion.state & Button1Mask) ? NUX_STATE_BUTTON1_DOWN : 0;
      _mouse_state |= (xevent.xmotion.state & Button2Mask) ? NUX_STATE_BUTTON2_DOWN : 0;
      _mouse_state |= (xevent.xmotion.state & Button3Mask) ? NUX_STATE_BUTTON3_DOWN : 0;
    }
    else if (xevent.type == LeaveNotify || xevent.type == EnterNotify)
    {
      _mouse_state |= (xevent.xcrossing.state & Button1Mask) ? NUX_STATE_BUTTON1_DOWN : 0;
      _mouse_state |= (xevent.xcrossing.state & Button2Mask) ? NUX_STATE_BUTTON2_DOWN : 0;
      _mouse_state |= (xevent.xcrossing.state & Button3Mask) ? NUX_STATE_BUTTON3_DOWN : 0;
    }
    m_pEvent->mouse_state = _mouse_state;

    return 0;
  }

  int GraphicsDisplay::MousePress(XEvent xevent, Event *m_pEvent)
  {
    // Erase mouse event and mouse double-click events. Keep the mouse states.
    ulong _mouse_state = m_pEvent->mouse_state & 0x0F000000;

    bool double_click = false;
    Time current_time = xevent.xbutton.time;
    if ((double_click_counter_ == 1) && ((int)current_time - (int)last_click_time_ < double_click_time_delay))
    {
      double_click = true;
      double_click_counter_ = 0;
    }
    else
    {
      double_click_counter_ = 1;
    }

    // State of the button before the event
    _mouse_state |= (xevent.xbutton.state & Button1Mask) ? NUX_STATE_BUTTON1_DOWN : 0;
    _mouse_state |= (xevent.xbutton.state & Button2Mask) ? NUX_STATE_BUTTON2_DOWN : 0;
    _mouse_state |= (xevent.xbutton.state & Button3Mask) ? NUX_STATE_BUTTON3_DOWN : 0;

    if (xevent.xbutton.type == ButtonPress)
    {
      if (xevent.xbutton.button == Button1)
      {
        if (double_click)
          m_pEvent->type = NUX_MOUSE_DOUBLECLICK;
        else
          m_pEvent->type = NUX_MOUSE_PRESSED;

        _mouse_state |= NUX_EVENT_BUTTON1_DOWN;
        _mouse_state |= NUX_STATE_BUTTON1_DOWN;
      }

      if (xevent.xbutton.button == Button2)
      {
        if (double_click)
          m_pEvent->type = NUX_MOUSE_DOUBLECLICK;
        else
          m_pEvent->type = NUX_MOUSE_PRESSED;

        _mouse_state |= NUX_EVENT_BUTTON2_DOWN;
        _mouse_state |= NUX_STATE_BUTTON2_DOWN;
      }

      if (xevent.xbutton.button == Button3)
      {
        if (double_click)
          m_pEvent->type = NUX_MOUSE_DOUBLECLICK;
        else
          m_pEvent->type = NUX_MOUSE_PRESSED;

        _mouse_state |= NUX_EVENT_BUTTON3_DOWN;
        _mouse_state |= NUX_STATE_BUTTON3_DOWN;
      }

      if (xevent.xbutton.button == Button4)
      {
        _mouse_state |= NUX_EVENT_MOUSEWHEEL;
        m_pEvent->type = NUX_MOUSE_WHEEL;
        m_pEvent->wheel_delta = NUX_MOUSEWHEEL_DELTA;
        return 1;
      }

      if (xevent.xbutton.button == Button5)
      {
        _mouse_state |= NUX_EVENT_MOUSEWHEEL;
        m_pEvent->type = NUX_MOUSE_WHEEL;
        m_pEvent->wheel_delta = -NUX_MOUSEWHEEL_DELTA;
        return 1;
      }

      if (xevent.xbutton.button == 6)
      {
        _mouse_state |= NUX_EVENT_MOUSEWHEEL;
        m_pEvent->type = NUX_MOUSE_WHEEL;
        m_pEvent->wheel_delta = NUX_MOUSEWHEEL_DELTA;
        return 1;
      }

      if (xevent.xbutton.button == 7)
      {
        _mouse_state |= NUX_EVENT_MOUSEWHEEL;
        m_pEvent->type = NUX_MOUSE_WHEEL;
        m_pEvent->wheel_delta = -NUX_MOUSEWHEEL_DELTA;
        return 1;
      }
    }

    m_pEvent->mouse_state = _mouse_state;

    return 0;
  }

  int GraphicsDisplay::MouseRelease(XEvent xevent, Event *m_pEvent)
  {
    // Erase mouse event and mouse double-click events. Keep the mouse states.
    ulong _mouse_state = m_pEvent->mouse_state & 0x0F000000;

    // State of the button before the event
    _mouse_state |= (xevent.xbutton.state & Button1Mask) ? NUX_STATE_BUTTON1_DOWN : 0;
    _mouse_state |= (xevent.xbutton.state & Button2Mask) ? NUX_STATE_BUTTON2_DOWN : 0;
    _mouse_state |= (xevent.xbutton.state & Button3Mask) ? NUX_STATE_BUTTON3_DOWN : 0;

    if (xevent.xbutton.type == ButtonRelease)
    {
      if (xevent.xbutton.button == Button1)
      {
        m_pEvent->type = NUX_MOUSE_RELEASED;
        _mouse_state |= NUX_EVENT_BUTTON1_UP;
        _mouse_state &= ~NUX_STATE_BUTTON1_DOWN;
      }

      if (xevent.xbutton.button == Button2)
      {
        m_pEvent->type = NUX_MOUSE_RELEASED;
        _mouse_state |= NUX_EVENT_BUTTON2_UP;
        _mouse_state &= ~NUX_STATE_BUTTON2_DOWN;
      }

      if (xevent.xbutton.button == Button3)
      {
        m_pEvent->type = NUX_MOUSE_RELEASED;
        _mouse_state |= NUX_EVENT_BUTTON3_UP;
        _mouse_state &= ~NUX_STATE_BUTTON3_DOWN;
      }
    }

    m_pEvent->mouse_state = _mouse_state;
    last_click_time_ = xevent.xbutton.time;

    return 0;
  }

  unsigned int GetModifierKeyState(unsigned int modifier_key_state)
  {
    unsigned int state = 0;

    // For CapsLock, we don't want to know if the key is pressed Down or Up.
    // We really want to know the state of the the CapsLock: on(keyboard light is on) or off?
    if (modifier_key_state & LockMask)
    {
      state |= KEY_MODIFIER_CAPS_LOCK;
    }

    if (modifier_key_state & ControlMask)
    {
      state |= KEY_MODIFIER_CTRL;
    }

    if (modifier_key_state & ShiftMask)
    {
      state |= KEY_MODIFIER_SHIFT;
    }

    if (modifier_key_state & Mod1Mask)
    {
      state |= KEY_MODIFIER_ALT;
    }

    if (modifier_key_state & Mod2Mask)
    {
      state |= KEY_MODIFIER_NUMLOCK;
    }

    // todo(jaytaoko): find out which key enable mod3mask
    // if (modifier_key_state & Mod3Mask)
    // {

    // }

    if (modifier_key_state & Mod4Mask)
    {
      state |= KEY_MODIFIER_SUPER;
    }

    // todo(jaytaoko): find out which key enable mod5mask
    // if (modifier_key_state & Mod5Mask)
    // {

    // }

    return state;
  }

  bool GraphicsDisplay::GetSystemEvent(Event *evt)
  {
    m_pEvent->Reset();
    // Erase mouse event and mouse doubleclick states. Keep the mouse states.
    m_pEvent->mouse_state &= 0x0F000000;

    bool got_event;

    // Process event matching this window
    XEvent xevent;

    if (XPending(m_X11Display))
    {
      bool bProcessEvent = true;
      XNextEvent(m_X11Display, &xevent);

      if (!_event_filters.empty())
      {
        for (auto filter : _event_filters)
        {
          bool result = filter.filter(xevent, filter.data);
          if (result)
          {
            memcpy(evt, m_pEvent, sizeof(Event));
            return true;
          }
        }
      }
      // Detect auto repeat keys. X11 sends a combination of KeyRelease/KeyPress(at the same time) when a key auto repeats.
      // Here, we make sure we process only the keyRelease when the key is effectively released.
      if ((xevent.type == KeyPress) || (xevent.type == KeyRelease))
      {
        if (xevent.xkey.keycode < 256)
        {
          // Detect if a key is repeated
          char Keys[32];
          // The XQueryKeymap function returns a bit vector for the logical state of the keyboard, where each bit set
          // to 1 indicates that the corresponding key is currently pressed down. The vector is represented as 32 bytes.
          // Byte N(from 0) contains the bits for keys 8N to 8N + 7 with the least significant bit in the byte representing
          // key 8N.
          // Note that the logical state of a device(as seen by client applications) may lag the physical state if device
          // event processing is frozen.

          XQueryKeymap(m_X11Display, Keys);

          if (Keys[xevent.xkey.keycode >> 3] & (1 << (xevent.xkey.keycode % 8)))
          {
            // KeyRelease event + KeyDown = discard repeated event
            if (xevent.type == KeyRelease)
            {
              m_X11LastEvent = xevent;
              bProcessEvent = false;
            }

            // KeyPress event + key repeat disabled + matching KeyRelease event = discard repeated event
            if ((xevent.type == KeyPress) && (!m_X11RepeatKey) &&
                 (m_X11LastEvent.xkey.keycode == xevent.xkey.keycode) &&
                 (m_X11LastEvent.xkey.time == xevent.xkey.time))
            {
              bProcessEvent = false;;
            }
          }
        }
      }

      if (xevent.type == MotionNotify)
      {
        while (XCheckTypedEvent(m_X11Display, MotionNotify, &xevent));
      }

      if (bProcessEvent)
        ProcessXEvent(xevent, false);

      memcpy(evt, m_pEvent, sizeof(Event));

      got_event = true;
    }
    else
    {
      memcpy(evt, m_pEvent, sizeof(Event));
      got_event = false;
    }

    return got_event;
  }
  
#if defined(NUX_OS_LINUX)
  void GraphicsDisplay::InjectXEvent(Event *evt, XEvent xevent)
  {
    m_pEvent->Reset();
    // Erase mouse event and mouse doubleclick states. Keep the mouse states.
    m_pEvent->mouse_state &= 0x0F000000;
    
    // We could do some checks here to make sure the xevent is really what it pretends to be.
    ProcessXEvent(xevent, false);
    memcpy(evt, m_pEvent, sizeof(Event));
  }

  void GraphicsDisplay::AddEventFilter(EventFilterArg arg)
  {
    _event_filters.push_back(arg);
  }

  void GraphicsDisplay::RemoveEventFilter(void *owner)
  {
    std::list<EventFilterArg>::iterator it;
    for (it = _event_filters.begin(); it != _event_filters.end(); ++it)
    {
      if ((*it).data == owner)
      {
        _event_filters.erase(it);
        break;
      }
    }
  }
#endif

  void GraphicsDisplay::ProcessForeignX11Event(XEvent *xevent, Event *nux_event)
  {
    m_pEvent->Reset();
    // Erase mouse event and mouse doubleclick states. Keep the mouse states.
    m_pEvent->mouse_state &= 0x0F000000;

    // Process event matching this window
    if (true /*(NUX_REINTERPRET_CAST(XAnyEvent*, xevent))->window == m_X11Window*/)
    {
      bool bProcessEvent = true;
      // Detect auto repeat keys. X11 sends a combination of KeyRelease/KeyPress(at the same time) when a key auto repeats.
      // Here, we make sure we process only the keyRelease when the key is effectively released.
      if ((xevent->type == KeyPress) || (xevent->type == KeyRelease))
      {
        if (xevent->xkey.keycode < 256)
        {
          // Detect if a key is repeated
          char Keys[32];
          // The XQueryKeymap function returns a bit vector for the logical state of the keyboard, where each bit set
          // to 1 indicates that the corresponding key is currently pressed down. The vector is represented as 32 bytes.
          // Byte N(from 0) contains the bits for keys 8N to 8N + 7 with the least significant bit in the byte representing
          // key 8N.
          // Note that the logical state of a device(as seen by client applications) may lag the physical state if device
          // event processing is frozen.

          XQueryKeymap(xevent->xany.display, Keys);

          if (Keys[xevent->xkey.keycode >> 3] & (1 << (xevent->xkey.keycode % 8)))
          {
            // KeyRelease event + KeyDown = discard repeated event
            if (xevent->type == KeyRelease)
            {
              m_X11LastEvent = *xevent;
              bProcessEvent = false;
            }

            // KeyPress event + key repeat disabled + matching KeyRelease event = discard repeated event
            if ((xevent->type == KeyPress) && (!m_X11RepeatKey) &&
                 (m_X11LastEvent.xkey.keycode == xevent->xkey.keycode) &&
                 (m_X11LastEvent.xkey.time == xevent->xkey.time))
            {
              bProcessEvent = false;;
            }
          }
        }
      }

      if (xevent->type == MotionNotify)
      {
        while (XCheckTypedEvent(m_X11Display, MotionNotify, xevent));
      }

      if (bProcessEvent)
        ProcessXEvent(*xevent, true);

      memcpy(nux_event, m_pEvent, sizeof(Event));
    }
    else
    {
      memcpy(nux_event, m_pEvent, sizeof(Event));
    }
  }

  Event &GraphicsDisplay::GetCurrentEvent()
  {
    return *m_pEvent;
  }

  bool GraphicsDisplay::HasXPendingEvent() const
  {
    return XPending(m_X11Display) ? true : false;
  }
  
  void GraphicsDisplay::RecalcXYPosition(int x_root, int y_root, int &x_recalc, int &y_recalc)
  {
    int main_window_x = m_WindowPosition.x;
    int main_window_y = m_WindowPosition.y;
  
    x_recalc = x_root - main_window_x;
    y_recalc = y_root - main_window_y;
  }

  void GraphicsDisplay::RecalcXYPosition(Window TheMainWindow, XEvent xevent, int &x_recalc, int &y_recalc)
  {
    x_recalc = y_recalc = 0;
    int main_window_x = m_WindowPosition.x;
    int main_window_y = m_WindowPosition.y;
    bool same = (TheMainWindow == xevent.xany.window);
    
    switch(xevent.type)
    {
      case ButtonPress:
      case ButtonRelease:
      {
        if (same)
        {
          x_recalc = xevent.xbutton.x;
          y_recalc = xevent.xbutton.y;
        }
        else
        {
          x_recalc = xevent.xbutton.x_root - main_window_x;
          y_recalc = xevent.xbutton.y_root - main_window_y;
        }
        break;
      }

      case MotionNotify:
      {
        if (same)
        {
          x_recalc = xevent.xmotion.x;
          y_recalc = xevent.xmotion.y;
        }
        else
        {
          x_recalc = xevent.xmotion.x_root - main_window_x;
          y_recalc = xevent.xmotion.y_root - main_window_y;
        }
        break;
      }

      case LeaveNotify:
      case EnterNotify:
      {
        if (same)
        {
          x_recalc = xevent.xcrossing.x;
          y_recalc = xevent.xcrossing.y;
        }
        else
        {
          x_recalc = xevent.xcrossing.x_root - main_window_x;
          y_recalc = xevent.xcrossing.y_root - main_window_y;
        }
        break;
      }
    }
  }

  void GraphicsDisplay::ProcessXEvent(XEvent xevent, bool foreign)
  {
    int x_recalc = 0;
    int y_recalc = 0;

    RecalcXYPosition(m_X11Window, xevent, x_recalc, y_recalc);
    
    bool local_from_server = !foreign;
    foreign = foreign || xevent.xany.window != m_X11Window;

    m_pEvent->type = NUX_NO_EVENT;
    m_pEvent->x11_window = xevent.xany.window;

    switch(xevent.type)
    {
      case DestroyNotify:
      {
        if (foreign)
          break;
          
        m_pEvent->type = NUX_DESTROY_WINDOW;
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: DestroyNotify event.");
        break;
      }

      case Expose:
      {
        if (foreign)
          break;
        
        m_pEvent->type = NUX_WINDOW_DIRTY;
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: Expose event.");
        break;
      }


      case ConfigureNotify:
      {
        if (foreign)
          break;
        
        m_pEvent->type = NUX_SIZE_CONFIGURATION;
        m_pEvent->width =  xevent.xconfigure.width;
        m_pEvent->height = xevent.xconfigure.height;
        m_WindowSize = Size(xevent.xconfigure.width, xevent.xconfigure.height);

        int x, y;
        Window child_return;

        XTranslateCoordinates(m_X11Display, m_X11Window, RootWindow(m_X11Display, 0), 0, 0, &x, &y, &child_return);
        m_WindowPosition = Point(x, y);

        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: ConfigureNotify event. %d %d", x, y);
        break;
      }

      case FocusIn:
      {
        if (!local_from_server)
          break;
          
        m_pEvent->type = NUX_WINDOW_ENTER_FOCUS;
        m_pEvent->mouse_state = 0;

        m_pEvent->dx = 0;
        m_pEvent->dy = 0;
        m_pEvent->virtual_code = 0;
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: FocusIn event.");
        break;
      }

      case FocusOut:
      {
        if (!local_from_server)
          break;
          
        m_pEvent->type = NUX_WINDOW_EXIT_FOCUS;
        m_pEvent->mouse_state = 0;

        m_pEvent->dx = 0;
        m_pEvent->dy = 0;
        m_pEvent->virtual_code = 0;
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: FocusOut event.");
        break;
      }

      case KeyPress:
      {
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: KeyPress event.");
        KeyCode keycode = xevent.xkey.keycode;
        KeySym keysym = NoSymbol;
        keysym = XKeycodeToKeysym(xevent.xany.display, keycode, 0);

        m_pEvent->key_modifiers = GetModifierKeyState(xevent.xkey.state);
        m_pEvent->key_repeat_count = 0;
        m_pEvent->x11_keysym = keysym;
        m_pEvent->x11_keycode = xevent.xkey.keycode;
        m_pEvent->type = NUX_KEYDOWN;
        m_pEvent->x11_timestamp = xevent.xkey.time;
        m_pEvent->x11_key_state = xevent.xkey.state;

        char buffer[NUX_EVENT_TEXT_BUFFER_SIZE];
        Memset(m_pEvent->text, 0, NUX_EVENT_TEXT_BUFFER_SIZE);

        bool skip = false;
        if ((keysym == NUX_VK_BACKSPACE) ||
            (keysym == NUX_VK_DELETE) ||
            (keysym == NUX_VK_ESCAPE))
        {
          //temporary fix for TextEntry widget: filter some keys
         skip = true; 
        }
        
        int num_char_stored = XLookupString(&xevent.xkey, buffer, NUX_EVENT_TEXT_BUFFER_SIZE, (KeySym*) &m_pEvent->x11_keysym, NULL);
        if (num_char_stored && (!skip))
        {
          Memcpy(m_pEvent->text, buffer, num_char_stored);
        }

        break;
      }

      case KeyRelease:
      {
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: KeyRelease event.");
        KeyCode keycode = xevent.xkey.keycode;
        KeySym keysym = NoSymbol;
        keysym = XKeycodeToKeysym(xevent.xany.display, keycode, 0);

        m_pEvent->key_modifiers = GetModifierKeyState(xevent.xkey.state);
        m_pEvent->key_repeat_count = 0;
        m_pEvent->x11_keysym = keysym;
        m_pEvent->x11_keycode = xevent.xkey.keycode;
        m_pEvent->type = NUX_KEYUP;
        m_pEvent->x11_timestamp = xevent.xkey.time;
        m_pEvent->x11_key_state = xevent.xkey.state;
        break;
      }

      case ButtonPress:
      {
        if (_dnd_is_drag_source)
        {
          HandleDndDragSourceEvent(xevent);
          break;
        }
        
        m_pEvent->x = x_recalc;
        m_pEvent->y = y_recalc;
        m_pEvent->x_root = 0;
        m_pEvent->y_root = 0;
        m_pEvent->key_modifiers = GetModifierKeyState(xevent.xkey.state);
        MousePress(xevent, m_pEvent);
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: ButtonPress event.");
        break;
      }

      case ButtonRelease:
      {
        if (_dnd_is_drag_source)
        {
          HandleDndDragSourceEvent(xevent);
          // fall through on purpose
        }
      
        m_pEvent->x = x_recalc;
        m_pEvent->y = y_recalc;
        m_pEvent->x_root = 0;
        m_pEvent->y_root = 0;
        m_pEvent->key_modifiers = GetModifierKeyState(xevent.xkey.state);
        MouseRelease(xevent, m_pEvent);
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: ButtonRelease event.");
        break;
      }

      case MotionNotify:
      {
        if (_dnd_is_drag_source)
        {
          HandleDndDragSourceEvent(xevent);
          break;
        }
      
        m_pEvent->x = x_recalc;
        m_pEvent->y = y_recalc;
        m_pEvent->x_root = 0;
        m_pEvent->y_root = 0;
        m_pEvent->key_modifiers = GetModifierKeyState(xevent.xkey.state);
        MouseMove(xevent, m_pEvent);
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: MotionNotify event.");
        break;
      }

      // Note: there is no WM_MOUSEENTER. WM_MOUSEENTER is equivalent to WM_MOUSEMOVE after a WM_MOUSELEAVE.
      case LeaveNotify:
      {
        if (xevent.xcrossing.mode != NotifyNormal || !local_from_server)
          break;
          
        m_pEvent->x = -1;
        m_pEvent->y = -1;
        m_pEvent->x_root = 0;
        m_pEvent->y_root = 0;
        m_pEvent->key_modifiers = GetModifierKeyState(xevent.xkey.state);
        m_pEvent->type = NUX_WINDOW_MOUSELEAVE;
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: LeaveNotify event.");
        break;
      }

      case EnterNotify:
      {
        if (xevent.xcrossing.mode != NotifyNormal || !local_from_server)
          break;
          
        m_pEvent->x = x_recalc;
        m_pEvent->y = y_recalc;
        m_pEvent->x_root = 0;
        m_pEvent->y_root = 0;
        m_pEvent->key_modifiers = GetModifierKeyState(xevent.xkey.state);
        MouseMove(xevent, m_pEvent);
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: EnterNotify event.");
        break;
      }
      
      case SelectionRequest:
      {
        if (xevent.xselectionrequest.selection == XInternAtom(xevent.xany.display, "XdndSelection", false))
           HandleDndSelectionRequest(xevent);
        break;
      }
      
      case MapNotify:
      {
        if (xevent.xmap.window == _dnd_source_window)
        {
          DrawDndSourceWindow();
        } 
        else
        {
          //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: MapNotify event.");
          m_pEvent->type = NUX_WINDOW_MAP;
        }
        
        break;
      }

      case UnmapNotify:
      {
        //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: UnmapNotify event.");
        m_pEvent->type = NUX_WINDOW_UNMAP;
        break;
      }

      case ClientMessage:
      {
        //if(foreign)
        //  break;

        if ((xevent.xclient.format == 32) && ((xevent.xclient.data.l[0]) == static_cast<long> (m_WMDeleteWindow)))
        {
          m_pEvent->type = NUX_TERMINATE_APP;
          //nuxDebugMsg("[GraphicsDisplay::ProcessXEvents]: ClientMessage event: Close Application.");
        }
        
        if (xevent.xclient.message_type == XInternAtom(xevent.xany.display, "XdndPosition", false))
        {
          HandleXDndPosition(xevent, m_pEvent);
        }
        else if (xevent.xclient.message_type == XInternAtom(xevent.xany.display, "XdndEnter", false))
        {
          HandleXDndEnter(xevent);
          m_pEvent->type = NUX_DND_ENTER_WINDOW;
        }
        else if (xevent.xclient.message_type == XInternAtom(xevent.xany.display, "XdndStatus", false))
        {
          HandleXDndStatus(xevent);
          m_pEvent->type = NUX_NO_EVENT;
        }
        else if (xevent.xclient.message_type == XInternAtom(xevent.xany.display, "XdndLeave", false))
        {
          HandleXDndLeave(xevent);
          m_pEvent->type = NUX_DND_LEAVE_WINDOW;
        }
        else if (xevent.xclient.message_type == XInternAtom(xevent.xany.display, "XdndDrop", false))
        {
          HandleXDndDrop(xevent, m_pEvent);
        }
        else if (xevent.xclient.message_type == XInternAtom(xevent.xany.display, "XdndFinished", false))
        {
          HandleXDndFinished(xevent);
          m_pEvent->type = NUX_NO_EVENT;
        }
        
        break;
      }
    }
  }
  
  void GraphicsDisplay::HandleDndSelectionRequest(XEvent xevent)
  {
    XEvent result;
    
    if (!_dnd_source_funcs.get_data_for_type)
      return;

    result.xselection.type = SelectionNotify;
    result.xselection.display = xevent.xany.display;
    result.xselection.requestor = xevent.xselectionrequest.requestor;
    result.xselection.selection = xevent.xselectionrequest.selection;
    result.xselection.target = xevent.xselectionrequest.target;
    result.xselection.property = xevent.xselectionrequest.property;
    result.xselection.time = xevent.xselectionrequest.time;

    int format, size;
    char *type = XGetAtomName(xevent.xany.display, xevent.xselectionrequest.target);
    const unsigned char *data = (const unsigned char *) (*(_dnd_source_funcs.get_data_for_type)) (type, &size, &format, _dnd_source_data);
    
    XFree(type);
    
    XChangeProperty(xevent.xany.display,  
                     xevent.xselectionrequest.requestor, 
                     xevent.xselectionrequest.property,
                     xevent.xselectionrequest.target, 
                     format, 
                     PropModeReplace, 
                     data,
                     size);
    XSendEvent(xevent.xany.display, xevent.xselectionrequest.requestor, False, 0, &result);
  }
  
  gboolean
  GraphicsDisplay::OnDragEndTimeout(gpointer data)
  {
    static_cast<GraphicsDisplay*> (data)->EndDndDrag(DNDACTION_NONE);
    
    return false;
  }
  
  void GraphicsDisplay::HandleDndDragSourceEvent(XEvent xevent)
  {
    if (_dnd_source_drop_sent)
      return;

    switch(xevent.type)
    {
      case ButtonPress:
        break;

      case ButtonRelease:
      
        if (!_dnd_source_target_window || !_dnd_source_target_accepts_drop)
        {
          SetDndSourceTargetWindow(None);
          EndDndDrag(DNDACTION_NONE);
        }
        else
        {
          SendDndSourceDrop(_dnd_source_target_window, xevent.xbutton.time);
          _dnd_source_drop_sent = true;

          UngrabPointer(this);
          _dnd_source_grab_active = false;

          g_timeout_add(1000, &GraphicsDisplay::OnDragEndTimeout, this);
        }
        break;

      case MotionNotify:
        Window target = GetDndTargetWindowForPos(xevent.xmotion.x_root, xevent.xmotion.y_root);
        
        if (_dnd_source_window)
        {
          Window rw;
          int x, y;
          unsigned int w, h, b, d;
          XGetGeometry(GetX11Display(), _dnd_source_window, &rw, &x, &y, &w, &h, &b, &d);
          XMoveWindow(GetX11Display(), _dnd_source_window, xevent.xmotion.x_root - (w / 2), xevent.xmotion.y_root - (h / 2));
        }
        
        if (target != _dnd_source_target_window)
          SetDndSourceTargetWindow(target);
        
        if (_dnd_source_target_window)
          SendDndSourcePosition(_dnd_source_target_window, xevent.xmotion.x_root, xevent.xmotion.y_root, xevent.xmotion.time);
        
        break;
    }
  }
  
  void GraphicsDisplay::SendDndSourceDrop(Window target, Time time)
  {
    XClientMessageEvent drop_message;
    drop_message.window = target;
    drop_message.format = 32;
    drop_message.type = ClientMessage;

    drop_message.message_type = XInternAtom(GetX11Display(), "XdndDrop", false);
    drop_message.data.l[0] = _dnd_source_window;
    drop_message.data.l[1] = 0;
    drop_message.data.l[2] = time;
    
    XSendEvent(GetX11Display(), target, False, NoEventMask, (XEvent *) &drop_message);
  }
  
  void GraphicsDisplay::SendDndSourcePosition(Window target, int x, int y, Time time)
  {
    XClientMessageEvent position_message;
    position_message.window = target;
    position_message.format = 32;
    position_message.type = ClientMessage;

    position_message.message_type = XInternAtom(GetX11Display(), "XdndPosition", false);
    position_message.data.l[0] = _dnd_source_window;
    position_message.data.l[1] = 0;
    position_message.data.l[2] = (x << 16) + y;
    position_message.data.l[3] = time;
    position_message.data.l[4] = XInternAtom(GetX11Display(), "XdndActionCopy", false); //fixme
    
    XSendEvent(GetX11Display(), target, False, NoEventMask, (XEvent *) &position_message);
  }
  
  void GraphicsDisplay::SendDndSourceEnter(Window target)
  {
    XClientMessageEvent enter_message;
    enter_message.window = target;
    enter_message.format = 32;
    enter_message.type = ClientMessage;

    enter_message.message_type = XInternAtom(GetX11Display(), "XdndEnter", false);
    enter_message.data.l[0] = _dnd_source_window;
    enter_message.data.l[1] = (((unsigned long) xdnd_version) << 24) + 1; // mark that we have set the atom list
    enter_message.data.l[2] = None; // fixme, these should contain the first 3 atoms
    enter_message.data.l[3] = None;
    enter_message.data.l[4] = None;
    
    XSendEvent(GetX11Display(), target, False, NoEventMask, (XEvent *) &enter_message);
  }
  
  void GraphicsDisplay::SendDndSourceLeave(Window target)
  {
    XClientMessageEvent leave_message;
    leave_message.window = target;
    leave_message.format = 32;
    leave_message.type = ClientMessage;

    leave_message.message_type = XInternAtom(GetX11Display(), "XdndLeave", false);
    leave_message.data.l[0] = _dnd_source_window;
    leave_message.data.l[1] = 0; // flags
    
    XSendEvent(GetX11Display(), target, False, NoEventMask, (XEvent *) &leave_message);
  }
  
  void GraphicsDisplay::SetDndSourceTargetWindow(Window target)
  {
    if (target == _dnd_source_target_window || !_dnd_source_grab_active)
      return;
    
    if (_dnd_source_target_window)
      SendDndSourceLeave(_dnd_source_target_window);
    
    if (target)
      SendDndSourceEnter(target);
    
    _dnd_source_target_accepts_drop = false;
    _dnd_source_target_window = target;
  }
  
  // This function hilariously inefficient
  Window GraphicsDisplay::GetDndTargetWindowForPos(int pos_x, int pos_y)
  {
    Window result = 0;
    
    Window root_window = DefaultRootWindow(GetX11Display());
    
    int cur_x, cur_y;
    XTranslateCoordinates(GetX11Display(), root_window, root_window, pos_x, pos_y, &cur_x, &cur_y, &result);
    
    if (!result)
      return result;
      
    Window src = root_window;
    while (true)
    {
      // translate into result space
      Window child;
      int new_x, new_y;
      XTranslateCoordinates(GetX11Display(), src, result, cur_x, cur_y, &new_x, &new_y, &child);
      
      cur_x = new_x;
      cur_y = new_y;
    
      // Check if our current window is XdndAware
      Atom type = 0;
      int format;
      unsigned long n, a;
      unsigned char *data = 0;
      if (XGetWindowProperty(GetX11Display(), result, XInternAtom(GetX11Display(), "XdndAware", false), 0, 1, False,
                             XA_ATOM, &type, &format, &n, &a, &data) == Success) 
      {
        if (data)
        {
          long dnd_version = 0;
          dnd_version = ((Atom *)data)[0];

          if (dnd_version < 5)
            result = 0; // dont have v5? go away until I implement this :)

          XFree(data);
          break; // result is the winner
        }
      }
      
      // Find child window if any and ignore translation
      XTranslateCoordinates(GetX11Display(), result, result, cur_x, cur_y, &new_x, &new_y, &child);
      
      // there is no child window, stop
      if (!child)
      {
        result = 0;
        break;
      }
      
      src = result;
      result = child;
    }
    
    return result;
  }
  
  void GraphicsDisplay::EndDndDrag(DndAction action)
  {
    Display *display = GetX11Display();
    
    if (_dnd_source_funcs.drag_finished)
      (*(_dnd_source_funcs.drag_finished)) (action, _dnd_source_data);
    _dnd_is_drag_source = false;
    
    if (_dnd_source_window)
      XDestroyWindow(display, _dnd_source_window);
    _dnd_source_window = 0;
    
    GrabDndSelection(display, None, CurrentTime);
    UngrabPointer(this);
    _dnd_source_grab_active = false;
    
    _dnd_source_funcs.get_drag_image = 0;
    _dnd_source_funcs.get_drag_types = 0;
    _dnd_source_funcs.get_data_for_type = 0;
    _dnd_source_funcs.drag_finished = 0;
    
    _dnd_source_data = 0;
  }
  
  void GraphicsDisplay::DrawDndSourceWindow()
  {
    if (!_dnd_source_funcs.get_drag_image || !_dnd_source_data || !_dnd_source_window)
      return;
    
    Display *display = GetX11Display();
    NBitmapData *data = (*(_dnd_source_funcs.get_drag_image)) (_dnd_source_data);
    XImage *image;
    
    image = XGetImage(display, _dnd_source_window, 0, 0, data->GetWidth(), data->GetHeight(), AllPlanes, ZPixmap);
    GC gc = XCreateGC(display, _dnd_source_window, 0, NULL);
    
    BitmapFormat format = data->GetFormat();
    
    /* draw some shit */
    if (data->IsTextureData())
    {
      ImageSurface surface = data->GetSurface(0);
      
      int x, y;
      for (y = 0; y < data->GetHeight(); y++)
      {
        for (x = 0; x < data->GetWidth(); x++)
        {
          long pixel = (long) surface.Read(x, y);
	  long a;
	  
	  if (format  == BITFMT_R8G8B8)
	    a = 255;
	  else
	    a = ((pixel >> 24) & 0xff);
          long r = (((pixel >> 16) & 0xff) * a) / 255;
          long g = (((pixel >> 8)  & 0xff) * a) / 255;
          long b = (((pixel >> 0)  & 0xff) * a) / 255;
          
          long result_pixel = (a << 24) | (b << 16) | (g << 8) | (r << 0);
          
          XPutPixel(image, x, y, result_pixel);
        }
      }
    }
    
    /* upload */
    XPutImage(display, _dnd_source_window, gc, image, 0, 0, 0, 0, data->GetWidth(), data->GetHeight());
    
    XDestroyImage(image);
  }
  
  void GraphicsDisplay::StartDndDrag(const DndSourceFuncs &funcs, void *user_data)
  {
    Display *display = GetX11Display();
    
    if (!display || !GrabPointer(NULL, this, true))
    {
      if (funcs.drag_finished)
        (*(funcs.drag_finished)) (DNDACTION_NONE, user_data);
      return;
    }
  
    _dnd_source_funcs = funcs;
    _dnd_source_data = user_data;
    _dnd_source_grab_active = true;
    _dnd_source_drop_sent = false;
    
    int width = 100, height = 100;
    if (_dnd_source_funcs.get_drag_image)
    {
      NBitmapData *data = (*(_dnd_source_funcs.get_drag_image)) (_dnd_source_data);
      width = data->GetWidth();
      height = data->GetHeight();
      
      delete data;
    }
    
    Window root = DefaultRootWindow(display);
    XVisualInfo vinfo;
    if (!XMatchVisualInfo(display, XDefaultScreen(display), 32, TrueColor, &vinfo))
    {
      printf("Could not match visual info\n");
      EndDndDrag(DNDACTION_NONE);
      return;
    }
    
    XSetWindowAttributes attribs;
    attribs.override_redirect = true;
    attribs.background_pixel = 0;
    attribs.border_pixel = 0;
    attribs.colormap = XCreateColormap(display, root, vinfo.visual, AllocNone);
    
    unsigned long attrib_mask = CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWColormap;
    // make a window which will serve two purposes:
    // First this window will be used to display feedback to the user
    // Second this window will grab and own the XdndSelection Selection
    _dnd_source_window = XCreateWindow(display, 
                                        root, 
                                        -1000, -1000, 
                                        width, height, 
                                        0,
                                        vinfo.depth,
                                        InputOutput,
                                        vinfo.visual, 
                                        attrib_mask,
                                        &attribs);
                                        
    XSelectInput(display, _dnd_source_window, StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | PointerMotionMask);
    XMapRaised(display, _dnd_source_window);
    
    Atom atom_type[1];
    atom_type[0] = XInternAtom(display, "_NET_WM_WINDOW_TYPE_DND", false);
    XChangeProperty(display, _dnd_source_window, XInternAtom(display, "_NET_WM_WINDOW_TYPE", false), 
                     XA_ATOM, 32, PropModeReplace, (unsigned char*) atom_type, 1);

    Atom data[32];
    int     i = 0;
    data[i++] = XInternAtom(display, "_NET_WM_STATE_STICKY", false);
    data[i++] = XInternAtom(display, "_NET_WM_STATE_SKIP_TASKBAR", false);
    data[i++] = XInternAtom(display, "_NET_WM_STATE_SKIP_PAGER", false);
    data[i++] = XInternAtom(display, "_NET_WM_STATE_ABOVE", false);

    XChangeProperty(display, _dnd_source_window, XInternAtom(display, "_NET_WM_STATE", 0),
                 XA_ATOM, 32, PropModeReplace,
                 (unsigned char *) data, i);

    Region region = XCreateRegion();
    if (region)
    {
      XShapeCombineRegion(display, _dnd_source_window, ShapeInput, 0, 0, region, ShapeSet);
      XDestroyRegion(region);
    }
    
    XFlush(display);
    
    _dnd_is_drag_source = true;
    _dnd_source_target_window = 0;
    
    
    std::list<const char *> types = _dnd_source_funcs.get_drag_types(_dnd_source_data);
    std::list<const char *>::iterator it;
    
    Atom type_atoms[types.size()];
    
    i = 0;
    for (it = types.begin(); it != types.end(); ++it)
    {
      type_atoms[i] = XInternAtom(display, *it, false);
      i++;
    }
    
    XChangeProperty(display, _dnd_source_window, XInternAtom(display, "XdndTypeList", false),
                    XA_ATOM, 32, PropModeReplace, (unsigned char *)type_atoms, i);
    
    GrabDndSelection(display, _dnd_source_window, CurrentTime);
  }
  
  bool GraphicsDisplay::GrabDndSelection(Display *display, Window window, Time time)
  {
    XSetSelectionOwner(GetX11Display(), XInternAtom(display, "XdndSelection", false), window, time);
    Window owner = XGetSelectionOwner(display, XInternAtom(display, "XdndSelection", false));
    return owner == window;
  }
  
  void GraphicsDisplay::SendDndStatus(bool accept, DndAction action, Rect region)
  {
    if (!_drag_window || !_drag_display || !_drag_source)
      return;
  
    Atom a;
    switch(action)
    {
      case DNDACTION_MOVE:
        a = XInternAtom(_drag_display, "XdndActionMove", false);
        break;
      case DNDACTION_COPY:
        a = XInternAtom(_drag_display, "XdndActionCopy", false);
        break;
      case DNDACTION_PRIVATE:
        a = XInternAtom(_drag_display, "XdndActionPrivate", false);
        break;
      case DNDACTION_LINK:
        a = XInternAtom(_drag_display, "XdndActionLink", false);
        break;
      case DNDACTION_ASK:
        a = XInternAtom(_drag_display, "XdndActionAsk", false);
        break;
      default:
        a = None;
        break;
    }
    SendXDndStatus(_drag_display, _drag_window, _drag_source, accept, a, region);
  }
  
  void GraphicsDisplay::SendDndFinished(bool accepted, DndAction performed_action)
  {
    if (!_drag_window || !_drag_display || !_drag_source)
      return;
    
    Atom a;
    switch(performed_action)
    {
      case DNDACTION_MOVE:
        a = XInternAtom(_drag_display, "XdndActionMove", false);
        break;
      case DNDACTION_COPY:
        a = XInternAtom(_drag_display, "XdndActionCopy", false);
        break;
      case DNDACTION_PRIVATE:
        a = XInternAtom(_drag_display, "XdndActionPrivate", false);
        break;
      case DNDACTION_LINK:
        a = XInternAtom(_drag_display, "XdndActionLink", false);
        break;
      case DNDACTION_ASK:
        a = XInternAtom(_drag_display, "XdndActionAsk", false);
        break;
      default:
        a = None;
        break;
    }
    SendXDndFinished(_drag_display, _drag_window, _drag_source, accepted, a);
  }
  
  std::list<char *> GraphicsDisplay::GetDndMimeTypes()
  {
    std::list<char *> result;
    
    if (!_drag_display)
      return result;
    
    Atom a;
    int i;
    for (i = 0; i <= _xdnd_max_type; i++)
    {
      a = _xdnd_types[i];
      
      if (!a)
        break;
      
      char *name = XGetAtomName(_drag_display, a);
      result.push_back(g_strdup(name));
      XFree(name);
    }
    return result;
  }
  
  char * GraphicsDisplay::GetDndData(char *property)
  {
    if (_dnd_is_drag_source)
    {
      int size, format;
      return g_strdup((*(_dnd_source_funcs.get_data_for_type)) (property, &size, &format, _dnd_source_data));
    }
    else
    {
      Atom a = XInternAtom(_drag_display, property, false);
      return GetXDndData(_drag_display, _drag_window, a, _drag_drop_timestamp);
    }
  }
  
  void GraphicsDisplay::SendXDndStatus(Display *display, Window source, Window target, bool accept, Atom action, Rect box)
  {
    XClientMessageEvent response;
    response.window = target;
    response.format = 32;
    response.type = ClientMessage;

    response.message_type = XInternAtom(display, "XdndStatus", false);
    response.data.l[0] = source;
    response.data.l[1] = 0; // flags
    response.data.l[2] = (box.x << 16) | box.y; // x, y
    response.data.l[3] = (box.width << 16) | box.height; // w, h
    
    if (accept)
    {
      response.data.l[4] = action;
      response.data.l[1] |= 1 << 0;
    }
    else
    {
      response.data.l[4] = None;
    }
    
    XSendEvent(display, target, False, NoEventMask, (XEvent *) &response);
  }
  
  void GraphicsDisplay::HandleXDndPosition(XEvent event, Event* nux_event)
  {
    const unsigned long *l = (const unsigned long *)event.xclient.data.l;
  
    int x = (l[2] & 0xffff0000) >> 16;
    int y = l[2] & 0x0000ffff;
    
    int x_recalc = 0;
    int y_recalc = 0;

    RecalcXYPosition(x, y, x_recalc, y_recalc);

    nux_event->type = NUX_DND_MOVE;
    nux_event->x = x_recalc;
    nux_event->y = y_recalc;

    // Store the last DND position;
    _last_dnd_position = Point(x_recalc, y_recalc);
  }
  
  void GraphicsDisplay::HandleXDndEnter(XEvent event)
  {
    const long *l = event.xclient.data.l;
    int version = (int)(((unsigned long)(l[1])) >> 24);
    
    if (version > xdnd_version)
      return;
    
    _drag_source = l[0];
    _drag_window = event.xany.window;
    _drag_display = event.xany.display;
    
    int j = 0;
    if (l[1] & 1) 
    {
      unsigned char *retval = 0;
      unsigned long n, a;
      int f;
      Atom type = None;

      XGetWindowProperty(_drag_display, _drag_source, XInternAtom(_drag_display, "XdndTypeList", false), 0,
                         _xdnd_max_type, False, XA_ATOM, &type, &f, &n, &a, &retval);

      if (retval) 
      {
        Atom *data = (Atom *)retval;
        for (; j < _xdnd_max_type && j < (int)n; j++)
          _xdnd_types[j] = data[j];
        
        XFree((uchar*)data);
      }
    } 
    else 
    {
      // xdnd supports up to 3 types without using XdndTypelist
      int i;
      for (i = 2; i < 5; i++) 
        _xdnd_types[j++] = l[i];
    }
    
    _xdnd_types[j] = 0;
  }
  
  void GraphicsDisplay::HandleXDndStatus(XEvent event)
  {
    const unsigned long *l = (const unsigned long *)event.xclient.data.l;
    
    // should protect against stray messages
    if (l[1] & 1)
      _dnd_source_target_accepts_drop = true;
    else
      _dnd_source_target_accepts_drop = false;
  }
  
  void GraphicsDisplay::HandleXDndLeave(XEvent event)
  {
    // reset the key things
    _xdnd_types[0] = 0;
    _drag_source = 0;
    _drag_window = 0;
    _drag_drop_timestamp = 0;
  }
  
  bool GraphicsDisplay::GetXDndSelectionEvent(Display *display, Window target, Atom property, long time, XEvent *result, int attempts)
  {
    // request the selection
    XConvertSelection(display,
                       XInternAtom(display, "XdndSelection", false),
                       property,
                       XInternAtom(display, "XdndSelection", false),
                       target,
                       time);
    XFlush(display);
    
    int i;
    for (i = 0; i < attempts; i++)
    {
      if (XCheckTypedWindowEvent(display, target, SelectionNotify, result))
      {
        return true;
      }
      
      XFlush(display);
      
      struct timeval usleep_tv;
      usleep_tv.tv_sec = 0;
      usleep_tv.tv_usec = 50000;
      select(0, 0, 0, 0, &usleep_tv);
    }
    
    return false;
  }
  
  void GraphicsDisplay::SendXDndFinished(Display *display, Window source, Window target, bool result, Atom action)
  {
    XClientMessageEvent response;
    response.window = target;
    response.format = 32;
    response.type = ClientMessage;

    response.message_type = XInternAtom(display, "XdndFinished", false);
    response.data.l[0] = source;
    response.data.l[1] = result ? 1 : 0; // flags
    response.data.l[2] = action; // action
    
    XSendEvent(display, target, False, NoEventMask, (XEvent *) &response);
  }
  
  char * GraphicsDisplay::GetXDndData(Display *display, Window requestor, Atom property, long time)
  {
    char *result = 0;
    XEvent xevent;
    if (GetXDndSelectionEvent(display, requestor, property, time, &xevent, 50))
    {
      unsigned char *buffer = NULL;
      Atom type;

      unsigned long  bytes_left; // bytes_after
      unsigned long  length;     // nitems
      int   format;
      
      if (XGetWindowProperty(display, 
                             requestor, 
                             XInternAtom(display, "XdndSelection", false), 
                             0, 
                             10000,
                             False,
                             AnyPropertyType, 
                             &type, 
                             &format, 
                             &length, 
                             &bytes_left, 
                             &buffer) == Success)
      {
        result = g_strdup((char *) buffer);
        XFree(buffer);
      }
    }
    
    return result;
  }
  
  void GraphicsDisplay::HandleXDndDrop(XEvent event, Event *nux_event)
  {
    const long *l = event.xclient.data.l;
    _drag_drop_timestamp = l[2];
    
    nux_event->type = NUX_DND_DROP;

    // The drop does not provide(x, y) coordinates of the location of the drop. Use the last DND position.
    nux_event->x = _last_dnd_position.x;
    nux_event->y = _last_dnd_position.y;
  }
  
  void GraphicsDisplay::HandleXDndFinished(XEvent event)
  {
    const unsigned long *l = (const unsigned long *)event.xclient.data.l;
    
    if (l[0] != _dnd_source_target_window)
      return;
    
    bool accepted = l[1] & 1;
    DndAction result = DNDACTION_NONE;

    if (accepted)
    {
      if (l[2] == XInternAtom(GetX11Display(), "XdndActionCopy", false))
        result = DNDACTION_COPY;
      else if (l[2] == XInternAtom(GetX11Display(), "XdndActionAsk", false))
        result = DNDACTION_ASK;
      else if (l[2] == XInternAtom(GetX11Display(), "XdndActionLink", false))
        result = DNDACTION_LINK;
      else if (l[2] == XInternAtom(GetX11Display(), "XdndActionMove", false))
        result = DNDACTION_MOVE;
      else if (l[2] == XInternAtom(GetX11Display(), "XdndActionPrivate", false))
        result = DNDACTION_PRIVATE;  
    }
    
    EndDndDrag(result);
  }
  
  void GraphicsDisplay::InitGlobalGrabWindow()
  {
    Display *display = GetX11Display();

    XSetWindowAttributes attribs;
    attribs.override_redirect = True;
    _global_grab_window = XCreateWindow(display,
                                         DefaultRootWindow(display),
                                         -100, -100,                     // X, Y
                                         1, 1,                           // Width, Height
                                         0,                              // Border
                                         0,                              // Depth
                                         InputOnly,                      // Class
                                         CopyFromParent,                 // Visual
                                         CWOverrideRedirect,
                                         &attribs);
    
    XSelectInput(display, _global_grab_window, StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | ButtonMotionMask | PointerMotionMask);
    XMapRaised(display, _global_grab_window);
    
    Atom atom_type[1];
    atom_type[0] = XInternAtom(display, "_NET_WM_WINDOW_TYPE_UTILITY", false);
    XChangeProperty(display, _global_grab_window, XInternAtom(display, "_NET_WM_WINDOW_TYPE", false), 
                     XA_ATOM, 32, PropModeReplace, (unsigned char*) atom_type, 1);

    Atom data[32];
    int     i = 0;
    data[i++] = XInternAtom(display, "_NET_WM_STATE_STICKY", false);
    data[i++] = XInternAtom(display, "_NET_WM_STATE_SKIP_TASKBAR", false);
    data[i++] = XInternAtom(display, "_NET_WM_STATE_SKIP_PAGER", false);
    data[i++] = XInternAtom(display, "_NET_WM_STATE_ABOVE", false);

    XChangeProperty(display, _global_grab_window, XInternAtom(display, "_NET_WM_STATE", 0),
                 XA_ATOM, 32, PropModeReplace,
                 (unsigned char *) data, i);
  }

  bool GraphicsDisplay::GrabPointer(GrabReleaseCallback callback, void *data, bool replace_existing)
  {
    if (_global_pointer_grab_active)
    {
      if (!replace_existing || _dnd_source_grab_active) // prevent grabbing over DND grabs
        return false;
      
      if (_global_pointer_grab_callback)
        (*_global_pointer_grab_callback) (true, _global_pointer_grab_data);
    }
    
    if (!_global_pointer_grab_active)
    {
      int result = XGrabPointer(GetX11Display(), 
                                _global_grab_window, 
                                True, 
                                   ButtonPressMask | 
                                   ButtonReleaseMask | 
                                   PointerMotionMask | 
                                   ButtonMotionMask , 
                                GrabModeAsync,
                                GrabModeAsync, 
                                None,
                                None, 
                                CurrentTime);
                                      
      if (result == GrabSuccess)
        _global_pointer_grab_active = true;
    }
    
    if (_global_pointer_grab_active)
    {
      _global_pointer_grab_callback = callback;
      _global_pointer_grab_data = data;
    }
    
    return _global_pointer_grab_active;
  }
  
  bool GraphicsDisplay::UngrabPointer(void *data)
  {
    if (data != _global_pointer_grab_data || !_global_pointer_grab_active)
      return false;
    
    _global_pointer_grab_active = false;
    XUngrabPointer(GetX11Display(), CurrentTime);
    
    if (_global_pointer_grab_callback)
      (*_global_pointer_grab_callback) (false, data);
    
    _global_pointer_grab_data = false;
    _global_pointer_grab_callback = 0;
    
    return true;
  }
  
  bool GraphicsDisplay::PointerIsGrabbed()
  {
    return _global_pointer_grab_active;  
  }

  bool GraphicsDisplay::GrabKeyboard(GrabReleaseCallback callback, void *data, bool replace_existing)
  {
    if (_global_keyboard_grab_active)
    {
      if (!replace_existing)
        return false; // fail case
      
      if (_global_keyboard_grab_callback)
        (*_global_keyboard_grab_callback) (true, _global_keyboard_grab_data);
    }
    
    if (!_global_keyboard_grab_active)
    {
      int result = XGrabKeyboard(GetX11Display(), 
                                _global_grab_window, 
                                True, 
                                GrabModeAsync,
                                GrabModeAsync, 
                                CurrentTime);
                                      
      if (result == GrabSuccess)
        _global_keyboard_grab_active = true;
    }
    
    if (_global_keyboard_grab_active)
    {
      _global_keyboard_grab_callback = callback;
      _global_keyboard_grab_data = data;
    }
    
    return _global_keyboard_grab_active;
  }
  
  bool GraphicsDisplay::UngrabKeyboard(void *data)
  {
    if (data != _global_keyboard_grab_data || !_global_keyboard_grab_active)
      return false;
    
    _global_keyboard_grab_active = false;
    XUngrabKeyboard(GetX11Display(), CurrentTime);
    
    if (_global_keyboard_grab_callback)
      (*_global_keyboard_grab_callback) (false, data);
    
    _global_keyboard_grab_data = false;
    _global_keyboard_grab_callback = 0;
    
    return true;
  }
  
  bool GraphicsDisplay::KeyboardIsGrabbed()
  {
    return _global_keyboard_grab_active;  
  }

  void GraphicsDisplay::ShowWindow()
  {
    XMapRaised(m_X11Display, m_X11Window);
  }

  void GraphicsDisplay::HideWindow()
  {
    XUnmapWindow(m_X11Display, m_X11Window);
  }

  bool GraphicsDisplay::IsWindowVisible()
  {
    XWindowAttributes window_attributes_return;
    XGetWindowAttributes(m_X11Display, m_X11Window, &window_attributes_return);

    if (window_attributes_return.map_state == IsViewable)
    {
      return true;
    }
    return false;
  }

  void GraphicsDisplay::EnterMaximizeWindow()
  {

  }

  void GraphicsDisplay::ExitMaximizeWindow()
  {

  }

  void GraphicsDisplay::SetWindowTitle(const char *Title)
  {
    XStoreName(m_X11Display, m_X11Window, TCHAR_TO_ANSI(Title));
  }

  bool GraphicsDisplay::HasVSyncSwapControl() const
  {
    return GetGpuDevice()->GetGpuInfo().Support_EXT_Swap_Control();
  }

  void GraphicsDisplay::EnableVSyncSwapControl()
  {
#ifndef NUX_OPENGLES_20
    if (GetGpuDevice()->GetGpuInfo().Support_EXT_Swap_Control())
    {
      GLXDrawable drawable = glXGetCurrentDrawable();
      glXSwapIntervalEXT(m_X11Display, drawable, 1);
    }
#endif
  }

  void GraphicsDisplay::DisableVSyncSwapControl()
  {
#ifndef NUX_OPENGLES_20
    if (GetGpuDevice()->GetGpuInfo().Support_EXT_Swap_Control())
    {
      GLXDrawable drawable = glXGetCurrentDrawable();
      if (drawable != None)
      {
        glXSwapIntervalEXT(m_X11Display, drawable, 0);
      }
    }
#endif
  }

  float GraphicsDisplay::GetFrameTime() const
  {
    return m_FrameTime;
  }

  void GraphicsDisplay::ResetFrameTime()
  {
    m_Timer.Reset();
  }

  void GraphicsDisplay::PauseThreadGraphicsRendering()
  {
    m_PauseGraphicsRendering = true;
    MakeGLContextCurrent();
  }

  bool GraphicsDisplay::IsPauseThreadGraphicsRendering() const
  {
    return m_PauseGraphicsRendering;
  }

}