d69f8f67934bc530f2ede72b70ce8ddb9f41d840
[sdk] / ecere / src / gui / drivers / XInterface.ec
1 namespace gui::drivers;
2
3 import "instance"
4 #if !defined(ECERE_VANILLA) && !defined(ECERE_NO3D) && !defined(ECERE_NOGL)
5 import "OpenGLDisplayDriver"
6 #endif
7
8 #if (defined(__unix__) || defined(__APPLE__)) && !defined(ECERE_MINIGLX)
9
10 #undef __BLOCKS__
11 default:
12 #define uint _uint
13 #define property _property
14 #define new _new
15 #define class _class
16
17 #ifdef __linux__
18 #include <linux/joystick.h>
19 #endif
20 #include <sys/param.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <sys/select.h>
24
25 //#include <stdio.h>
26 //#include <stdlib.h>
27 //#include <string.h>
28
29 #define Window    X11Window
30 #define Cursor    X11Cursor
31 #define Font      X11Font
32 #define Display   X11Display
33 #define Time      X11Time
34 #define KeyCode   X11KeyCode
35 #define Picture   X11Picture
36
37 #include <X11/Xatom.h>
38 #include <X11/Xlib.h>
39 #include <X11/Xresource.h>
40 #include <X11/Xutil.h>
41 #include <X11/XKBlib.h>
42 #include <X11/keysym.h>
43 #include <fcntl.h>
44 #if !defined(ECERE_NO3D) && !defined(ECERE_NOGL)
45 #include <GL/glx.h>
46 #endif
47 #include <X11/extensions/Xrender.h>
48 #include <X11/extensions/XShm.h>
49
50 #undef Picture
51 #undef Window
52 #undef Cursor
53 #undef Font
54 #undef Display
55 #undef Time
56 #undef KeyCode
57 #undef uint
58
59 #undef new
60 #undef property
61 #undef class
62 private:
63
64 import "Interface"
65 import "XDisplayDriver"
66
67 // These are the events we care about
68 #define EVENT_MASK StructureNotifyMask | \
69       ButtonPressMask | ButtonReleaseMask | PointerMotionMask | \
70       KeyPressMask | KeyReleaseMask | ExposureMask | FocusChangeMask | \
71       PropertyChangeMask
72
73 void * xGlobalDisplay;
74 static XIM im;
75 // static XIC ic;
76 static XContext windowContext;
77 static Window lastActive;
78
79 static char * clipBoardData;
80
81 static Thread /* xThread, */ timerThread;
82 static bool xTerminate;
83 static Semaphore xSemaphore { };
84 static Mutex xMutex { };
85 static bool fullScreenMode;
86 static int desktopX = 0, desktopY = 0, desktopW = 0, desktopH = 0;
87 X11Window confineWindow;
88 static X11Cursor nullCursor;
89 static X11Window capturedWindow = None;
90 static Window restrictedWindow = null;
91 static bool gotAnXEvent = false;
92 static XEvent xEvent;
93 static int joystickFD[4];
94 static X11Window activeWindow;
95
96 static enum AtomIdents
97 {
98    clipboard, multiple, targets, utf8_string, wm_delete_window, wm_hints, wm_name, wm_protocols, wm_state, wm_take_focus, wm_transient_for,
99    _motif_wm_hints,
100    _net_active_window, _net_current_desktop, _net_number_of_desktops, _net_wm_icon, _net_wm_name, _net_wm_pid,
101    _net_wm_state, _net_wm_state_demands_attention, _net_wm_state_hidden, _net_wm_user_time, _net_wm_window_type,
102    _net_wm_window_type_desktop, _net_wm_window_type_dialog, _net_wm_window_type_dock, _net_wm_window_type_dropdown_menu,
103    _net_wm_window_type_menu, _net_wm_window_type_normal, _net_wm_window_type_popup_menu, _net_wm_window_type_splash,
104    _net_wm_window_type_toolbar, _net_wm_window_type_utility, _net_workarea, _net_frame_extents, _net_request_frame_extents,
105    _net_wm_state_maximized_vert, _net_wm_state_maximized_horz, _net_wm_state_modal, app_selection
106 };
107
108 static Atom atoms[AtomIdents];
109
110 static const char *atomNames[AtomIdents] = {
111    "CLIPBOARD", //clipboard
112    "MULTIPLE", //multiple
113    "TARGETS", //targets
114    "UTF8_STRING", //utf8_string
115    "WM_DELETE_WINDOW", //wm_delete_window
116    "WM_HINTS", //wm_hints
117    "WM_NAME", //wm_name
118    "WM_PROTOCOLS", //wm_protocols
119    "WM_STATE", //wm_state
120    "WM_TAKE_FOCUS", //wm_take_focus
121    "WM_TRANSIENT_FOR", //wm_transient_for
122    "_MOTIF_WM_HINTS", //_motif_wm_hints
123    "_NET_ACTIVE_WINDOW", //_net_active_window
124    "_NET_CURRENT_DESKTOP", //_net_current_desktop
125    "_NET_NUMBER_OF_DESKTOPS", //_net_number_of_desktops
126    "_NET_WM_ICON", //_net_wm_icon
127    "_NET_WM_NAME", //_net_wm_name
128    "_NET_WM_PID", //_net_wm_pid
129    "_NET_WM_STATE", //_net_wm_state
130    "_NET_WM_STATE_DEMANDS_ATTENTION", //_net_wm_state_demands_attention
131    "_NET_WM_STATE_HIDDEN", //_net_wm_state_hidden
132    "_NET_WM_USER_TIME", //_net_wm_user_time
133    "_NET_WM_WINDOW_TYPE", //_net_wm_window_type
134    "_NET_WM_WINDOW_TYPE_DESKTOP", //_net_wm_window_type_desktop
135    "_NET_WM_WINDOW_TYPE_DIALOG", //_net_wm_window_type_dialog
136    "_NET_WM_WINDOW_TYPE_DOCK", //_net_wm_window_type_dock
137    "_NET_WM_WINDOW_TYPE_DROPDOWN_MENU", //_net_wm_window_type_dropdown_menu
138    "_NET_WM_WINDOW_TYPE_MENU", //_net_wm_window_type_menu
139    "_NET_WM_WINDOW_TYPE_NORMAL", //_net_wm_window_type_normal
140    "_NET_WM_WINDOW_TYPE_POPUP_MENU", //_net_wm_window_type_popup_menu
141    "_NET_WM_WINDOW_TYPE_SPLASH", //_net_wm_window_type_splash
142    "_NET_WM_WINDOW_TYPE_TOOLBAR", //_net_wm_window_type_toolbar
143    "_NET_WM_WINDOW_TYPE_UTILITY", //_net_wm_window_type_utility
144    "_NET_WORKAREA",  //_net_workarea
145    "_NET_FRAME_EXTENTS", // _net_frame_extents
146    "_NET_REQUEST_FRAME_EXTENTS", // _net_request_frame_extents
147    "_NET_WM_STATE_MAXIMIZED_VERT", // _net_wm_state_maximized_vert
148    "_NET_WM_STATE_MAXIMIZED_HORZ", // _net_wm_state_maximized_horz
149    "_NET_WM_STATE_MODAL", // _net_wm_state_modal
150    "APP_SELECTION"
151 };
152 /*
153 _NET_WM_STATE_STICKY, ATOM
154 _NET_WM_STATE_MAXIMIZED_VERT, ATOM
155 _NET_WM_STATE_MAXIMIZED_HORZ, ATOM
156 _NET_WM_STATE_SHADED, ATOM
157 _NET_WM_STATE_SKIP_TASKBAR, ATOM
158 _NET_WM_STATE_SKIP_PAGER, ATOM
159 _NET_WM_STATE_HIDDEN, ATOM
160 _NET_WM_STATE_FULLSCREEN, ATOM
161 _NET_WM_STATE_ABOVE, ATOM
162 _NET_WM_STATE_BELOW, ATOM
163 _NET_WM_STATE_DEMANDS_ATTENTION, ATOM
164 */
165
166 static bool autoRepeatDetectable;
167 static bool setICPosition;
168 int xSystemDepth;
169 PixelFormat xSystemPixelFormat;
170 Visual * xSystemVisual;
171 bool xSharedMemory;
172
173 static Time timeStamp;
174
175 class XWindowData : struct
176 {
177 public:
178    XVisualInfo * visual;
179    XIC ic;
180    bool laterFocus;
181    // Decorations Size
182    Box decor;
183    bool gotFrameExtents;
184 };
185
186 bool XGetBorderWidths(Window window, Box box)
187 {
188    XWindowData windowData = window.windowData;
189    if(windowData)
190    {
191       if(window.state == maximized)
192          box = { 0, 0, 0, 0 };
193       else
194          box = windowData.decor;
195       return true;
196    }
197    return false;
198 }
199
200 static Visual * FindFullColorVisual(X11Display *dpy, int * depth)
201 {
202    XVisualInfo vinfo;
203    XVisualInfo *vinfo_ret;
204    int numitems;
205   
206    vinfo._class = TrueColor;
207    vinfo_ret = XGetVisualInfo(dpy, VisualClassMask, &vinfo, &numitems);
208    if(numitems)
209    {
210       int maxdepth = 0;
211       while(numitems > 0)
212       {
213          if(vinfo_ret[numitems-1].depth > maxdepth)
214             maxdepth = vinfo_ret[numitems-1].depth;
215          numitems--;
216       }
217       XFree((void *) vinfo_ret);
218       if(maxdepth >= 16)
219       {
220          if(XMatchVisualInfo(dpy, DefaultScreen(dpy), maxdepth, TrueColor, &vinfo))
221          {
222             *depth = maxdepth;
223             return vinfo.visual;
224          }
225       }
226    } 
227    return null;
228 }
229
230 static void RepositionDesktop(bool updateChildren)
231 {
232    int x = 0, y = 0;
233    int w, h;
234    Screen * x_screen = XDefaultScreenOfDisplay(xGlobalDisplay);
235    X11Window x_root;
236    int current = 0;   
237    char *data = null;
238    int format;
239    unsigned long len, fill;
240    Atom type;
241    static double lastTime = 0, time;
242
243    time = GetTime();
244    if(desktopW && desktopH && time - lastTime < 1.5) return;
245    lastTime = time;
246
247    w = XDisplayWidth(xGlobalDisplay, DefaultScreen(xGlobalDisplay));
248    h = XDisplayHeight(xGlobalDisplay, DefaultScreen(xGlobalDisplay));
249    x_root = XRootWindowOfScreen(x_screen);
250    
251    if(atoms[_net_number_of_desktops] != None)
252    {
253       if(XGetWindowProperty(xGlobalDisplay, x_root, atoms[_net_number_of_desktops], 0, 1, False,
254                             XA_CARDINAL, &type, &format, &len, &fill,
255                             &data) != Success)
256       {
257          printf("cant get xa desktops property\n");
258       }
259       
260       if(data)
261       {
262          int desktops = 0;
263          desktops = (int)*(long *)data;
264
265          //printf("_NET_NUMBER_OF_DESKTOPS is %d\n", desktops);
266
267          XFree(data);
268          data = null;
269       }
270    }
271    
272    if(atoms[_net_current_desktop] != None)
273    {   
274       if(XGetWindowProperty(xGlobalDisplay, x_root, atoms[_net_current_desktop], 0, 1, False,
275                             XA_CARDINAL, &type, &format, &len, &fill,
276                             &data) != Success)
277       {
278          printf("cant get xa current property\n");
279       }
280       
281       if(data)
282       {
283          current = (int)*(long *)data;
284          XFree(data);
285          data = null;
286
287          //printf("_NET_CURRENT_DESKTOP is %d\n", current);
288       }
289    }   
290    if(atoms[_net_workarea] != None)
291    {
292       long *workareas;
293
294       if(XGetWindowProperty(xGlobalDisplay, x_root, atoms[_net_workarea], 0, (4 * 32),
295                             False, AnyPropertyType, &type, &format, &len,
296                             &fill, &data) != Success)
297       {
298          //printf("warning\n");
299       }
300       
301       /*
302       if(type == None || format == 0)
303          printf("warning\n");
304
305       if(fill)
306          printf("warning\n");
307       
308       if(len % 4)
309          printf("warning\n");
310       */
311   
312       if(data)
313       {
314          workareas = (long *)data;
315      
316          x = (int)workareas[current * 4];
317          y = (int)workareas[current * 4 + 1];
318          w = (int)workareas[current * 4 + 2];
319          h = (int)workareas[current * 4 + 3];
320
321          //printf("_NET_WORKAREA is x = %d, y = %d, w = %d, h = %d\n", x, y, w, h);
322          XFree(data);
323          data = null;
324       }
325       //   printf("Work Area width: %d, height %d\n", w, h);
326    }
327
328    if(desktopX != x || desktopY != y || desktopW != w || desktopH != h)
329    {
330       guiApp.SetDesktopPosition(x, y, w, h, updateChildren);
331       desktopX = x;
332       desktopY = y;
333       desktopW = w;
334       desktopH = h;
335    }
336 }
337
338 /****************************************************************************
339    /// PRIVATE UTILITY FUNCTIONS /////////////
340 ****************************************************************************/
341 // --- Keyboard Input ---
342 #define KEYCODE_HOME    0x59
343 #define KEYCODE_UP      0x5A
344 #define KEYCODE_PGUP    0x5B
345 #define KEYCODE_LEFT    0x5C
346 #define KEYCODE_RIGHT   0x5E
347 #define KEYCODE_END     0x5F
348 #define KEYCODE_DOWN    0x60
349 #define KEYCODE_PGDWN   0x61
350 #define KEYCODE_INS     0x62
351 #define KEYCODE_DEL     0x63
352 #define KEYCODE_SLASH   0x68
353
354 default:
355 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit;
356 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyUp;
357 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyDown;
358 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit;
359 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMouseMove;
360 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftDoubleClick;
361 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonDown;
362 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonUp;
363 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleDoubleClick;
364 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonDown;
365 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonUp;
366 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightDoubleClick;
367 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonDown;
368 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonUp;
369 private:
370
371 static bool ProcessKeyMessage(Window window, uint keyCode, int release, XKeyEvent * event)
372 {
373    bool result = true;
374    Key code;
375    unichar ch = 0;
376    KeySym keysym = NoSymbol;
377    Status status;
378    int buflength = 0;
379    static long bufsize = 16;
380    static char *buf = NULL;
381    XWindowData windowData = window.windowData;
382    Key key = 0;
383
384    if(window.destroyed) return result;
385
386    // Logf("Got 0x%x (%d)\n", keyCode, key);
387
388    // Translate the key code
389    /*
390    key = key - 8;
391    //Logf("Got 0x%x (%d)\n", key, key);
392    
393    switch(key)
394    {
395       case KEYCODE_HOME: key = home; break;
396       case KEYCODE_UP: key = up; break;
397       case KEYCODE_PGUP: key = pageUp; break;
398       case KEYCODE_LEFT: key = left; break;
399       case KEYCODE_RIGHT: key = right; break;
400       case KEYCODE_END: key = end; break;
401       case KEYCODE_DOWN: key = down; break;
402       case KEYCODE_PGDWN: key = pageDown; break;
403       case KEYCODE_INS: key = insert; break;
404       case KEYCODE_DEL: key = del; break;
405       case KEYCODE_SLASH: key = keyPadSlash; break;
406    }
407   
408    ch = (byte)Interface::TranslateKey(key, event->state & ShiftMask);
409    */
410 /*
411    if(release)
412       Logf("Key up:   %3d (%2x)\n", key, key);
413    else
414       Logf("Key down: %3d (%2x)\n", key, key);
415 */
416
417    if(!buf)
418       buf = malloc((uint)bufsize);
419    if(windowData && windowData.ic)
420    { 
421       buflength = XmbLookupString(windowData.ic, event, buf, (int)bufsize, &keysym, &status);
422       if (status == XBufferOverflow)
423       {
424          buf = realloc(buf, (uint)(bufsize = buflength));
425          buflength = XmbLookupString(windowData.ic, event, buf, (int)bufsize, &keysym, &status);
426       }
427       if(status != XLookupKeySym && status != XLookupBoth && release == 1)
428          keysym = XLookupKeysym(event, 0);
429    }
430    else
431    {
432       keysym = XLookupKeysym(event, 0);
433    }
434
435    // printf("Got keysym %d (%x)\n", keysym, keysym);
436    if(keysym != NoSymbol) //status == XLookupKeySym || status == XLookupBoth)
437    {
438       switch(keysym)
439       {
440          case XK_BackSpace:   key = backSpace; break;
441          case XK_ISO_Left_Tab: key = tab; break;
442          case XK_Tab:         key = tab; break;
443          // case XK_Linefeed:
444          // case XK_Clear:
445          case XK_Return:      key = enter; break;
446          case XK_Pause:       key = pauseBreak; break;
447          case XK_Scroll_Lock: key = scrollLock; break;
448          case XK_Sys_Req:     key = printScreen; break;
449          case XK_Escape:      key = escape; break;
450          case XK_Delete:      key = del; break;
451
452          case XK_Home:        key = home; break;
453          case XK_Left:        key = left; break;
454          case XK_Up:          key = up; break;
455          case XK_Right:       key = right; break;
456          case XK_Down:        key = down; break;
457          // case XK_Prior:
458          case XK_Page_Up:     key = pageUp; break;
459          // case XK_Next:
460          case XK_Page_Down:   key = pageDown; break;
461          case XK_End:         key = end; break;
462          // case XK_Begin:
463
464          // case XK_Select:
465          // case XK_Print: 
466          // case XK_Execute:
467          case XK_Insert:      key = insert; break;
468          // case XK_Undo:
469          // case XK_Redo:
470          // case XK_Menu:
471          // case XK_Find:
472          // case XK_Cancel:
473 #ifdef __APPLE__
474          case XK_Help:     key = insert; break;
475 #endif
476          case XK_Break:    key = Key { pauseBreak, ctrl = true }; break;
477 #ifdef __APPLE__
478          case XK_Mode_switch: key = leftAlt; break;
479 #endif
480          // case XK_script_switch:
481          case XK_Num_Lock:    key = numLock; break;
482
483          // case XK_KP_Space: 
484          // case XK_KP_Tab:
485          case XK_KP_Enter:    key = keyPadEnter; break;
486          // case XK_KP_F1:
487          // case XK_KP_F2:
488          // case XK_KP_F3:
489          // case XK_KP_F4:
490          case XK_KP_Home:     key = keyPadHome; break;
491          case XK_KP_Left:     key = keyPadLeft; break;
492          case XK_KP_Up:       key = keyPadUp; break;
493          case XK_KP_Right:    key = keyPadRight; break;
494          case XK_KP_Down:     key = keyPadDown; break;
495          // case XK_KP_Prior:
496          case XK_KP_Page_Up:  key = keyPadPageUp; break;
497          // case XK_KP_Next:
498          case XK_KP_Page_Down:key = keyPadPageDown; break;
499          case XK_KP_End:      key = keyPadEnd; break;
500          // case XK_KP_Begin:
501          case XK_KP_Insert:   key = keyPadInsert; break;
502          case XK_KP_Delete:   key = keyPadDelete; break;
503          // case XK_KP_Equal:
504          case XK_KP_Multiply: key = keyPadStar; break;
505          case XK_KP_Add:      key = keyPadPlus; break;
506          case XK_KP_Separator:key = keyPadDelete; break;
507          case XK_KP_Subtract: key = keyPadMinus; break;
508          // case XK_KP_Decimal: 
509          case XK_KP_Divide:   key = keyPadSlash; break;
510
511          case XK_KP_0:  key = keyPad0; break;
512          case XK_KP_1:  key = keyPad1; break;
513          case XK_KP_2:  key = keyPad2; break;
514          case XK_KP_3:  key = keyPad3; break;
515          case XK_KP_4:  key = keyPad4; break;
516          case XK_KP_5:  key = keyPad5; break;
517          case XK_KP_6:  key = keyPad6; break;
518          case XK_KP_7:  key = keyPad7; break;
519          case XK_KP_8:  key = keyPad8; break;
520          case XK_KP_9:  key = keyPad9; break;
521
522          case XK_F1: key = f1; break;
523          case XK_F2: key = f2; break;
524          case XK_F3: key = f3; break;
525          case XK_F4: key = f4; break;
526          case XK_F5: key = f5; break;
527          case XK_F6: key = f6; break;
528          case XK_F7: key = f7; break;
529          case XK_F8: key = f8; break;
530          case XK_F9: key = f9; break;
531          case XK_F10: key = f10; break;
532          case XK_F11: key = f11; break;
533          //case XK_L1:
534          case XK_F12: key = f12; break;
535          /*
536          case XK_L2:
537          case XK_F13:
538          case XK_L3:
539          case XK_F14:
540          case XK_L4:
541          case XK_F15:
542          case XK_L5:
543          case XK_F16:
544          case XK_L6:
545          case XK_F17:
546          case XK_L7:
547          case XK_F18:
548          case XK_L8:
549          case XK_F19:
550          case XK_L9:
551          case XK_F20:
552          case XK_L10:
553          case XK_F21:
554          case XK_R1:
555          case XK_F22:
556          case XK_R2:
557          case XK_F23:
558          case XK_R3:
559          case XK_F24:
560          case XK_R4:
561          case XK_F25:
562          case XK_R5:
563          case XK_F26:
564          case XK_R6:
565          case XK_F27:
566          case XK_R7:
567          case XK_F28:
568          case XK_R8:
569          case XK_F29:
570          case XK_R9:
571          case XK_F30:
572          case XK_R10:
573          case XK_F31:
574          case XK_R11:
575          case XK_F32:
576          case XK_R12:
577          case XK_F33:
578          case XK_R13:
579          case XK_F34:
580          case XK_R14:
581          case XK_F35:
582          case XK_R15:
583          */
584          case XK_Shift_L: key = leftShift; break;
585          case XK_Shift_R: key = rightShift; break;
586          case XK_Control_L: key = leftControl; break;
587          case XK_Control_R: key = rightControl; break;
588          case XK_Caps_Lock: key = capsLock; break;
589          // case XK_Shift_Lock: 
590          // case XK_Meta_L:
591          // case XK_Meta_R:
592          case XK_Alt_L: key = leftAlt; break;
593          case XK_Alt_R: key = rightAlt; break;
594          // case XK_Super_L:
595          // case XK_Super_R:
596          // case XK_Hyper_L:
597          // case XK_Hyper_R:
598
599          case XK_space: key = space; break;
600          case XK_exclam: key = bang; break;
601          case XK_quotedbl: key = doubleQuote; break;
602          case XK_numbersign: key = pound; break;
603          case XK_dollar: key = dollar; break;
604          case XK_percent: key = percent; break;
605          case XK_ampersand: key = ampersand; break;
606          case XK_apostrophe: key = quote; break;
607          // case XK_quoteright: key = quote; break;
608          case XK_parenleft: key = leftParanthesis; break;
609          case XK_parenright: key = rightParanthesis; break;
610          case XK_asterisk: key = star; break;
611          case XK_plus: key = plus; break;
612          case XK_comma: key = comma; break;
613          case XK_minus: key = minus; break;
614          case XK_period: key = period; break;
615          case XK_slash: key = slash; break;
616          case XK_0: key = k0; break;
617          case XK_1: key = k1; break;
618          case XK_2: key = k2; break;
619          case XK_3: key = k3; break;
620          case XK_4: key = k4; break;
621          case XK_5: key = k5; break;
622          case XK_6: key = k6; break;
623          case XK_7: key = k7; break;
624          case XK_8: key = k8; break;
625          case XK_9: key = k9; break;
626          case XK_colon: key = colon; break;
627          case XK_semicolon: key = semicolon; break;
628          case XK_less: key = smallerThan; break;
629          case XK_equal: key = equal; break;
630          case XK_greater: key = greaterThan; break;
631          case XK_question: key = questionMark; break;
632          case XK_at: key = ampersand; break;
633          case XK_A: key = a; break;
634          case XK_B: key = b; break;
635          case XK_C: key = c; break;
636          case XK_D: key = d; break;
637          case XK_E: key = e; break;
638          case XK_F: key = f; break;
639          case XK_G: key = g; break;
640          case XK_H: key = h; break;
641          case XK_I: key = i; break;
642          case XK_J: key = j; break;
643          case XK_K: key = k; break;
644          case XK_L: key = l; break;
645          case XK_M: key = m; break;
646          case XK_N: key = n; break;
647          case XK_O: key = o; break;
648          case XK_P: key = p; break;
649          case XK_Q: key = q; break;
650          case XK_R: key = r; break;
651          case XK_S: key = s; break;
652          case XK_T: key = t; break;
653          case XK_U: key = u; break;
654          case XK_V: key = v; break;
655          case XK_W: key = w; break;
656          case XK_X: key = x; break;
657          case XK_Y: key = y; break;
658          case XK_Z: key = z; break;
659          case XK_bracketleft: key = leftBracket; break;
660          case XK_backslash: key = backSlash; break;
661          case XK_bracketright: key = rightBracket; break;
662          case XK_asciicircum: key = circumflex; break;
663          case XK_underscore: key = underscore; break;
664          // case XK_grave: key = backQuote; break;
665          case XK_quoteleft: key = backQuote; break;
666          case XK_a: key = a; break;
667          case XK_b: key = b; break;
668          case XK_c: key = c; break;
669          case XK_d: key = d; break;
670          case XK_e: key = e; break;
671          case XK_f: key = f; break;
672          case XK_g: key = g; break;
673          case XK_h: key = h; break;
674          case XK_i: key = i; break;
675          case XK_j: key = j; break;
676          case XK_k: key = k; break;
677          case XK_l: key = l; break;
678          case XK_m: key = m; break;
679          case XK_n: key = n; break;
680          case XK_o: key = o; break;
681          case XK_p: key = p; break;
682          case XK_q: key = q; break;
683          case XK_r: key = r; break;
684          case XK_s: key = s; break;
685          case XK_t: key = t; break;
686          case XK_u: key = u; break;
687          case XK_v: key = v; break;
688          case XK_w: key = w; break;
689          case XK_x: key = x; break;
690          case XK_y: key = y; break;
691          case XK_z: key = z; break;
692          case XK_braceleft: key = leftBracket; break;
693          case XK_bar: key = pipe; break;
694          case XK_braceright: key = rightBracket; break;
695          case XK_asciitilde: key = tilde; break;
696       }
697    }
698    if(!windowData.ic)
699    {
700       ch = (byte)Interface::TranslateKey(key, event->state & ShiftMask);
701       // 127 is delete, we don't treat that as a character (Use (SmartKey)key == del)
702       if(ch == 128 || ch == 127) ch = 0;
703    }
704    code = key;
705    if(keysym == XK_ISO_Left_Tab)
706       code.shift = true;
707    if(key != leftShift && key != rightShift && event->state & ShiftMask)
708       code.shift = true;
709    if(key != leftControl && key != rightControl && event->state & ControlMask)
710       code.ctrl = true;
711    if(key != leftAlt && key != rightAlt && event->state & Mod1Mask)
712       code.alt = true;
713
714 #ifdef __APPLE__
715    if(key != leftAlt && key != rightAlt && event->state & (1<<13))
716    {
717       code.alt = true;
718       /*buflength = 0;
719       ch = 0;*/
720    } 
721 #endif
722
723    // Logf("Key Message: %s, keysym: 0x%x, key: %d state: %d, ch: %c\n", release ? ((release == 2) ? "REPEAT" : "KeyRelease") : "KeyPress", keysym, key, event->state, (byte)ch);
724
725    incref window;
726    if(release == 1)
727    {
728       int numBytes;
729       if(windowData && windowData.ic) ch = buflength ? UTF8GetChar(buf, &numBytes) : 0;
730       if(ch == 127) ch = 0;
731       // printf("Release! %d %d %d\n", keysym, code, ch);
732       result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyUp, code, ch);
733    }
734    else
735    {
736       int c;
737       if(release == 0)
738       {
739          if(windowData.ic && buflength)
740          {
741             for(c = 0; c<buflength;)
742             {
743                int numBytes;
744                ch = UTF8GetChar(buf + c, &numBytes);
745                if(ch == 127) ch = 0;
746                result = window.KeyMessage((c == 0) ? 
747                   __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyDown : __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit,
748                   (c == 0) ? code : 0, ch);
749                c += numBytes;
750                if(!numBytes) c = buflength;
751             }
752          }
753          else
754             result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyDown, code, ch);
755       }
756       else if(key<128)
757       {
758          if(buflength && windowData.ic)
759             for(c = 0; c<buflength;)
760             {
761                int numBytes;
762                ch = UTF8GetChar(buf + c, &numBytes);
763                if(ch == 127) ch = 0;
764                result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit, code, ch);
765                c += numBytes;
766                if(!numBytes) c = buflength;
767             }
768          else
769             result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit, code, ch);
770       } 
771    }
772    delete window;
773             
774    return result;
775 }
776 /*
777 static uint E_CALL XEventThread(void * data)
778 {
779    for(;;)
780    {
781       XEvent e;
782       xSemaphore.Wait();
783       if(xTerminate) break;
784       if(!gotAnXEvent)
785       {
786          XPeekEvent(xGlobalDisplay, &e);
787          gotAnXEvent = true;
788          guiApp.SignalEvent();
789       }
790    }
791    return 0;
792 }
793 */
794
795 static Bool EventChecker(void *display, XEvent *event, char * data)
796 {
797    return (!data || (event->type == (int) data)) && event->type != NoExpose && event->type != GraphicsExpose;
798 }
799
800 static Bool ConfigureNotifyChecker(void *display, XConfigureEvent *event, char * data)
801 {
802    return ((!data || (event->window == (X11Window) data)) && event->type == ConfigureNotify;
803 }
804
805 static uint timerDelay = MAXINT;
806 #define RESOLUTION   (18.2 * 100)
807 static uint XTimerThread(Thread thread)
808 {
809    int s = ConnectionNumber(xGlobalDisplay);
810    /*
811    Time lastTime, thisTime;
812    lastTime = GetTime();
813    */
814    for(;;)
815    {
816       //int result;
817       //bool waitSemaphore = false;
818       fd_set readSet, writeSet, exceptSet;
819       struct timeval tv = { (timerDelay == MAXINT) ? 0 : (timerDelay / 1000000), (timerDelay == MAXINT) ? (int)(1000000 / 18.2) : (timerDelay % 1000000) };
820       
821       if(xTerminate) break;
822       FD_ZERO(&readSet);
823       FD_ZERO(&writeSet);
824       FD_ZERO(&exceptSet);
825       FD_SET(s, &readSet);
826       FD_SET(s, &exceptSet);
827       xMutex.Wait();
828       if(select(s + 1, &readSet, null, null, &tv))
829       {
830          if(FD_ISSET(s, &readSet))
831             gotAnXEvent = true;
832       }
833       xMutex.Release();
834       guiApp.SignalEvent();  
835       xSemaphore.Wait();
836
837 #if 0
838       XEvent e;
839       Sleep(1.0 / RESOLUTION);
840       thisTime = GetTime();
841       if(xTerminate) break;
842       if(thisTime - lastTime > (1.0 / 18.2))
843       {
844          guiApp.SignalEvent();
845          lastTime = thisTime;
846       }
847       else
848       {
849          xMutex.Wait();
850          if(!gotAnXEvent)
851          {
852             XLockDisplay(xGlobalDisplay);
853             if(XCheckIfEvent(xGlobalDisplay, &xEvent, EventChecker, null))
854             {
855                gotAnXEvent = true;
856                guiApp.SignalEvent();
857             }
858             XUnlockDisplay(xGlobalDisplay);
859          }
860          xMutex.Release();
861       }
862 #endif
863    }
864    return 0;
865 }
866
867 static int MyXErrorHandler(X11Display * display, XErrorEvent * event)
868 {
869    char buffer[1024];
870    if(xGlobalDisplay)
871       XGetErrorText(xGlobalDisplay, event->error_code, buffer, sizeof(buffer));
872    Logf("X Error: %s\n", buffer);
873    return 0;
874 }
875
876 static int MyXIOErrorHandler(X11Display * display)
877 {
878    Log("X IO Error\n");
879    return 0;
880 }
881
882 // Motif Hints (to get rid of the decorations)
883 #define MWM_HINTS_FUNCTIONS   (1L << 0)
884 #define MWM_HINTS_DECORATIONS (1L << 1)
885 #define MWM_HINTS_INPUT_MODE  (1L << 2)
886 #define MWM_HINTS_STATUS      (1L << 3)
887
888 #define MWM_DECOR_ALL         (1L << 0)
889 #define MWM_DECOR_BORDER      (1L << 1)
890 #define MWM_DECOR_RESIZEH     (1L << 2)
891 #define MWM_DECOR_TITLE       (1L << 3)
892 #define MWM_DECOR_MENU        (1L << 4)
893 #define MWM_DECOR_MINIMIZE    (1L << 5)
894 #define MWM_DECOR_MAXIMIZE    (1L << 6)
895
896 #define MWM_FUNC_ALL (1L << 0)
897 #define MWM_FUNC_RESIZE (1L << 1)
898 #define MWM_FUNC_MOVE (1L << 2)
899 #define MWM_FUNC_MINIMIZE (1L << 3)
900 #define MWM_FUNC_MAXIMIZE (1L << 4)
901 #define MWM_FUNC_CLOSE (1L << 5)
902
903 struct MWM_Hints
904 {
905   unsigned long flags;
906   unsigned long functions;
907   unsigned long decorations;
908   long inputMode;
909   unsigned long status;
910 };
911
912 static void WaitForViewableWindow(Window window)
913 {
914    //int attempts = 0;
915    //Logf("Wait for viewable %s\n", window.name);
916    XFlush(xGlobalDisplay);
917    //while(attempts++ < 40) 
918    while(true)
919    {
920       XWindowAttributes attributes = { 0 };
921       int result;
922       if(!XGetWindowAttributes(xGlobalDisplay, (X11Window)window.windowHandle, &attributes))
923          break;
924       if(attributes.map_state == IsViewable)
925          break;
926       else
927          Sleep(1.0 / RESOLUTION);
928    }
929 }
930
931 /****************************************************************************
932    /// DRIVER IMPLEMENTATION /////////////
933 ****************************************************************************/
934
935 /*static */class HiResTimer : Thread
936 {
937    bool terminate;
938    uint delay;
939    
940    void Stop()
941    {
942       if(started)
943       {
944          terminate = true;
945          Wait();
946       }
947    }
948    
949    uint Main()
950    {
951       while(!terminate)
952       {
953          //usleep(delay);
954          // Sleep(delay / 1000000.0);
955          struct timeval tv = { delay / 1000000, delay % 1000000 };
956          select(0,null,null,null, &tv);
957          guiApp.SignalEvent();
958       }
959       return 0;
960    }
961 };
962
963 static HiResTimer hiResTimer { };
964
965 default:
966
967 #include <sys/ipc.h>
968 #include <sys/shm.h>
969 #include <signal.h>
970 #include <locale.h>
971
972
973 private:
974
975 #ifndef SHM_STAT
976 #define SHM_STAT  13
977 #define SHM_INFO  14
978 #endif
979
980 static int terminatePid;
981
982 static void SigIntHandler(int value)
983 {
984    // printf("SigHandler %d\n", getpid());
985    if(!terminatePid || terminatePid == getpid())
986    {
987       terminateX++;
988       terminatePid = getpid();
989       // printf("terminateX now equals %d\n", terminateX);
990       if(guiApp && guiApp.semaphore)
991          guiApp.semaphore.Release();
992    }
993    /*
994    struct shmid_ds info;
995         int maxid = shmctl (0, SHM_INFO, &info);
996    int pid = getpgrp();
997    int thisPid = getpid();
998    //if(thisPid == pid)
999    /-*
1000    {
1001       if(maxid >= 0)
1002       {
1003          int id;
1004               for(id = 0; id <= maxid; id++)
1005          {
1006                  struct shmid_ds shmseg;
1007             int shmid;
1008                       if((shmid = shmctl(id, SHM_STAT, &shmseg)) >= 0)
1009             {
1010                if(shmseg.shm_cpid == pid || shmseg.shm_cpid == thisPid)
1011                {
1012                   printf("%d (%d) belongs to us (%d)\n", shmid, id, shmseg.shm_cpid);
1013                   shmctl(shmid, IPC_RMID, 0);
1014                }
1015             }
1016          }
1017       }
1018       exit(0);
1019    }
1020    */
1021    /*else if(guiApp.desktop)
1022       guiApp.desktop.Destroy(0);*/
1023 }
1024
1025 class XInterface : Interface
1026 {
1027    class_property(name) = "X";
1028
1029    // --- User Interface System ---
1030    bool Initialize()
1031    {
1032       setlocale(LC_ALL, "en_US.UTF-8");
1033       XInitThreads();
1034       XSupportsLocale();
1035       XSetLocaleModifiers("");
1036       XSetErrorHandler(MyXErrorHandler);
1037       XSetIOErrorHandler(MyXIOErrorHandler);
1038 #ifndef __APPLE__
1039       signal(SIGINT, SigIntHandler);
1040 #endif
1041       xTerminate = false;
1042       xGlobalDisplay = XOpenDisplay(null);
1043
1044         joystickFD[0] = open("/dev/js0", O_RDONLY);
1045       joystickFD[1] = open("/dev/js1", O_RDONLY);
1046       joystickFD[2] = open("/dev/js2", O_RDONLY);
1047       joystickFD[3] = open("/dev/js3", O_RDONLY);
1048     
1049       if(xGlobalDisplay)
1050       {
1051          XWindowAttributes attributes = { 0 };
1052          XGetWindowAttributes(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), &attributes);
1053          xSystemDepth = attributes.depth;
1054          xSystemVisual = attributes.visual;
1055          switch(xSystemDepth)
1056          {
1057             case 32: case 24: xSystemPixelFormat = pixelFormat888; break;
1058             case 16:
1059             case 15:
1060             {
1061                XVisualInfo vinfo;
1062                XVisualInfo *vinfo_ret;
1063                int numitems = 0;
1064               
1065                vinfo.visualid = XVisualIDFromVisual(xSystemVisual);
1066                vinfo_ret = XGetVisualInfo(xGlobalDisplay, VisualIDMask, &vinfo, &numitems);
1067                if(numitems)
1068                {
1069                   xSystemPixelFormat = (vinfo_ret->green_mask == 0x3E0) ? pixelFormat555 : pixelFormat565;
1070                   /*
1071                   if(GetXRenderFormat(xSystemPixelFormat, 0))
1072                   {
1073                      // printf("Got X Render format %d\n", xSystemPixelFormat);
1074                      break;
1075                   }
1076                   else
1077                      printf("No X Format?\n");
1078                   xSystemPixelFormat = (xSystemPixelFormat == pixelFormat555) ? pixelFormat565 : pixelFormat555;
1079                   vinfo = *vinfo_ret;
1080                   // vinfo._class = DirectColor;
1081                   vinfo.visualid = 0;
1082                   vinfo.bits_per_rgb = 5;
1083                   vinfo.depth = xSystemDepth;
1084                   vinfo.green_mask = (xSystemPixelFormat == pixelFormat555) ? 0x3E0 : 0x7E0;
1085                   vinfo.red_mask   = (xSystemPixelFormat == pixelFormat555) ? 0x7C00 : 0xF800;
1086                   XFree((void *) vinfo_ret);
1087                   if(XMatchVisualInfo(xGlobalDisplay, DefaultScreen(xGlobalDisplay), vinfo.depth, vinfo._class, &vinfo))
1088                   //vinfo_ret = XGetVisualInfo(xGlobalDisplay, VisualDepthMask|VisualRedMaskMask|VisualGreenMaskMask|VisualBlueMaskMask, &vinfo, &numitems);
1089                   //if(vinfo_ret)
1090                   {
1091                      //vinfo = *vinfo_ret;
1092                      if(GetXRenderFormat(xSystemPixelFormat, 0))
1093                      {
1094                         // printf("Got X Render format %d (second try)\n", xSystemPixelFormat);
1095                         // printf("red mask: %x, green mask: %x, blue mask: %x\n", vinfo.red_mask,vinfo.green_mask, vinfo.blue_mask);
1096                      }
1097                      xSystemVisual = vinfo.visual;
1098                   }
1099                   else
1100                      printf("Could not get a 555 visual\n");
1101                   */
1102                } 
1103                break;
1104             }
1105          }
1106          // printf("Got a depth of %d\n", xSystemDepth);
1107
1108          {  
1109             int major, minor, pixmaps;
1110             xSharedMemory = XShmQueryExtension(xGlobalDisplay) && XShmQueryVersion(xGlobalDisplay, &major, &minor, &pixmaps) && pixmaps;
1111          }  
1112
1113          // printf("Opening IM\n");
1114          im = XOpenIM(xGlobalDisplay, null, null, null);
1115          // if(im)
1116          {
1117             XColor fore = { 0 }, back = { 0 };
1118             Pixmap pixmap = XCreatePixmap(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), 1, 1, 1);
1119             Pixmap mask = XCreatePixmap(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), 1, 1, 1);
1120             XSetWindowAttributes attributes = { 0 };
1121
1122             XkbSetDetectableAutoRepeat(xGlobalDisplay, True, &autoRepeatDetectable);
1123
1124             XInternAtoms(xGlobalDisplay, (char**)atomNames, AtomIdents::enumSize, False, atoms);
1125             
1126             {
1127                Atom protocols[2] = { atoms[wm_delete_window], atoms[wm_take_focus] };
1128
1129                XSetWMProtocols(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), protocols, 2);
1130             }
1131
1132             /*
1133             if(atoms[_net_workarea] == None)
1134                printf("Warning: _NET_WORKAREA extension not supported\n");
1135             */
1136
1137             attributes.override_redirect = True;
1138             if(!windowContext)
1139             {
1140                windowContext = XUniqueContext();
1141             }
1142
1143             nullCursor = XCreatePixmapCursor(xGlobalDisplay, pixmap, mask, &fore, &back, 0, 0);
1144             confineWindow = XCreateWindow(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay),
1145                0,0,1,1,0, CopyFromParent, InputOnly, xSystemVisual /*CopyFromParent*/, CWOverrideRedirect, &attributes);
1146
1147
1148             // IM initialization
1149             {
1150                /*ic = XCreateIC(im, XNInputStyle,
1151                   XIMPreeditNothing | XIMStatusNothing,
1152                   // XIMPreeditNone | XIMStatusNone | XIMPreeditPosition | XIMStatusArea | XIMPreeditArea | XIMStatusArea | XIMPreeditNothing | XIMStatusNothing,
1153                   XNClientWindow, confineWindow, XNFocusWindow, confineWindow, 0);
1154                   */
1155
1156                /*
1157                XIMStyles *IMcando;
1158                XIMStyle  clientCanDo; 
1159                XIMStyle  styleWeWillUse = null;
1160                int i;
1161                XVaNestedList arglist;
1162                unsigned long imEventMask;
1163
1164                XGetImValues(im, XNQueryInputStyle, &IMcando, null);
1165                XSetICFocus(ic);
1166                clientCanDo =
1167                   XIMPreeditNone | XIMStatusNone |
1168                   XIMPreeditPosition | XIMStatusArea |
1169                   XIMPreeditArea | XIMStatusArea |
1170                   XIMPreeditNothing | XIMStatusNothing;
1171                
1172                for(i=0; i<IMcando->count_styles; i++)
1173                {
1174                    XIMStyle tmpStyle;
1175                    tmpStyle = IMcando->support_styles[i];
1176                    if ( ((tmpStyle & clientCanDo) == tmpStyle) && prefer(tmpStyle, styleWeWillUse) )
1177                      styleWeWillUse = tmpStyle;
1178                }
1179                if(styleWeWillUse = null)
1180                    exit_with_error();
1181                XFree(IMcando);
1182
1183                arglist = XVaCreateNestedList(0, XNFontSet, fontset,
1184                                           XNForeground,
1185                                           WhitePixel(xGlobalDisplay, screen),
1186                                           XNBackground,
1187                                           BlackPixel(xGlobalDisplay, screen),
1188                                           NULL);
1189                ic = XCreateIC(im, XNInputStyle, styleWeWillUse,
1190                              XNClientWindow, window, XNFocusWindow, window,
1191                              XNStatusAttributes, arglist,
1192                              XNPreeditAttributes, arglist, NULL);
1193                XFree(arglist);
1194                if (ic == null)
1195                    exit_with_error();
1196
1197                XGetWindowAttributes(xGlobalDisplay, win, &winAtts);
1198                XGetICValues(ic, XNFilterEvents, &imEventMask, null);
1199                imEventMask |= winAtts.your_event_mask;
1200                XSelectInput(xGlobalDisplay, window, imEventMask);
1201                XSetICFocus(ic);
1202                */
1203             }
1204             
1205             xMutex.Wait();
1206             timerThread = Thread { };
1207             incref timerThread;
1208             timerThread.Main = XTimerThread;
1209             timerThread.Create();
1210
1211             return true;
1212          }   
1213       }
1214       return false;
1215    }
1216
1217    void Terminate()
1218    {
1219       XEvent e = { 0 };
1220       xTerminate = true;
1221
1222       // WHY WAS THIS COMMENTED HERE?
1223       // Probably because it was causing crashes, the proper fix should now be in DestroyRootWindow
1224       delete lastActive;
1225
1226       xMutex.Release();
1227       xSemaphore.Release();
1228
1229       timerThread.Wait();
1230       delete timerThread;
1231       hiResTimer.Stop();
1232
1233       //XPutBackEvent(xGlobalDisplay, &e);
1234       // xThread.Wait();
1235       // delete xThread;
1236
1237       /*if(windowData && windowData.ic)
1238       {
1239          XDestroyIC(windowData.ic);
1240          windowData.ic = null;
1241       }*/
1242       if(im)
1243       {
1244          XCloseIM(im);
1245          im = null;
1246       }
1247       XCloseDisplay(xGlobalDisplay);
1248       xGlobalDisplay = null;
1249
1250       if(joystickFD[0] != -1) close(joystickFD[0]);
1251       if(joystickFD[1] != -1) close(joystickFD[1]);
1252       if(joystickFD[2] != -1) close(joystickFD[2]);
1253       if(joystickFD[3] != -1) close(joystickFD[3]);
1254    }
1255
1256    #define DBLCLICK_DELAY  300   // 0.3 second
1257    #define DBLCLICK_DELTA  1
1258
1259    bool ProcessInput(bool processAll)
1260    {
1261       bool eventAvailable = false;
1262       XEvent e;
1263
1264       if(!fullScreenMode) RepositionDesktop(true);
1265       //xMutex.Wait();
1266 //*      XLockDisplay(xGlobalDisplay);
1267       while(!xTerminate && (/*gotAnXEvent || */XCheckIfEvent(xGlobalDisplay, &e, EventChecker, null)))
1268       {
1269          Window window = null;
1270          XAnyEvent * thisEvent = (XAnyEvent *)&e;
1271          // printf("Got an event: %d\n", thisEvent->type);
1272
1273          //if(gotAnXEvent) { thisEvent = (XAnyEvent *)&xEvent; gotAnXEvent = false; }
1274
1275          if(im && XFilterEvent((union _XEvent *)thisEvent, None))
1276             continue;
1277          eventAvailable = true;
1278          XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1279          if(window)
1280          {
1281             XWindowData windowData = window.windowData;
1282             static uint lastKeyCode = 0;
1283             switch(thisEvent->type)
1284             {
1285                case KeyPress:
1286                {
1287                   XKeyEvent * event = (XKeyEvent *) thisEvent;
1288                   //*XUnlockDisplay(xGlobalDisplay);
1289                   ProcessKeyMessage(window, event->keycode, (event->keycode == lastKeyCode) ? 2 : 0, event);
1290                   //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1291                   lastKeyCode = event->keycode;
1292                   break;
1293                }
1294                case KeyRelease:
1295                {
1296                   XKeyEvent * event = (XKeyEvent *) thisEvent;
1297                   XEvent nextEvent;
1298                   lastKeyCode = 0;
1299                   if(!autoRepeatDetectable && XCheckIfEvent(xGlobalDisplay, (XEvent *)&nextEvent, EventChecker, (void *)KeyPress))
1300                   {
1301                      if(im && XFilterEvent(&nextEvent, None))
1302                         break;
1303
1304                      if(((XKeyEvent *)&nextEvent)->keycode == event->keycode)
1305                      {
1306                         //*XUnlockDisplay(xGlobalDisplay);
1307                         ProcessKeyMessage(window, event->keycode, 2, event);
1308                      }
1309                      else
1310                      {
1311                         //*XUnlockDisplay(xGlobalDisplay);
1312                         // printf("Keycode not the same :(\n");
1313                         ProcessKeyMessage(window, event->keycode, 1, event);
1314                         ProcessKeyMessage(window, ((XKeyEvent *)&nextEvent)->keycode, 0, (XKeyEvent *)&nextEvent);
1315                      }
1316                   }
1317                   else
1318                   {
1319                      //*XUnlockDisplay(xGlobalDisplay);
1320                      // printf("No KeyPress ahead\n");
1321                      ProcessKeyMessage(window, event->keycode, 1, event);
1322                   }
1323                   //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1324                   break;
1325                }
1326                case ButtonPress:
1327                {
1328                   XButtonEvent * event = (XButtonEvent *) thisEvent;
1329
1330                   static double lastTime[3];
1331                   static Window lastWindow[3];
1332                   static Point lastPos[3];
1333
1334                   Modifiers keyFlags = 0;
1335                   bool doubleClick;
1336                   uint button, buttonDouble, whichButton;
1337                   uint buttonMask;
1338                   int x = event->x_root, y = event->y_root;
1339
1340                   if(event->button == Button1)
1341                   {
1342                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonDown;
1343                      buttonDouble = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftDoubleClick;
1344                      whichButton = 0;
1345                      buttonMask = Button1Mask;
1346                      keyFlags.left = true;
1347                   }
1348                   else if(event->button == Button3)
1349                   {
1350                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonDown;
1351                      buttonDouble = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightDoubleClick;
1352                      whichButton = 2;
1353                      buttonMask = Button3Mask;
1354                      keyFlags.right = true;
1355                   }
1356                   else
1357                   {
1358                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonDown;
1359                      buttonDouble = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleDoubleClick;
1360                      whichButton = 1;
1361                      buttonMask = Button2Mask;
1362                      keyFlags.middle = true;
1363                   }
1364                   if(event->state & buttonMask)
1365                      break;
1366
1367                   doubleClick = event->time - lastTime[whichButton] < DBLCLICK_DELAY &&
1368                      window == lastWindow[whichButton] &&
1369                      Abs(event->x_root - lastPos[whichButton].x) < DBLCLICK_DELTA &&
1370                      Abs(event->y_root - lastPos[whichButton].y) < DBLCLICK_DELTA;
1371                   lastTime[whichButton] = doubleClick ? 0 : event->time;
1372                   lastWindow[whichButton] = window;
1373                   lastPos[whichButton].x = event->x_root;
1374                   lastPos[whichButton].y = event->y_root;
1375
1376                   if(event->state & ShiftMask)     keyFlags.shift = true;
1377                   if(event->state & ControlMask)   keyFlags.ctrl = true;
1378                   if(event->state & Mod1Mask)      keyFlags.alt = true;
1379                   if(event->state & Button1Mask)   keyFlags.left = true;
1380                   if(event->state & Button2Mask)   keyFlags.middle = true;
1381                   if(event->state & Button3Mask)   keyFlags.right = true;
1382                   //*XUnlockDisplay(xGlobalDisplay);
1383
1384                   incref window;
1385                   if(event->button == Button4 || event->button == Button5)
1386                   {
1387                      window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit, (event->button == Button4) ? wheelUp : wheelDown, 0);
1388                   }
1389                   else
1390                   {
1391                      if(doubleClick)
1392                      {
1393                         if(!window.MouseMessage(buttonDouble, x, y, &keyFlags, false, true))
1394                         {
1395                            //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1396                            delete window;
1397                            break;
1398                         }
1399                      }
1400                      window.MouseMessage(button, x, y, &keyFlags, false, /*doubleClick? false : */true);
1401                   }
1402                   //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1403                   delete window;
1404                   break;
1405                }
1406                case ButtonRelease:
1407                {
1408                   Modifiers keyFlags = 0;
1409                   XButtonEvent * event = (XButtonEvent *) thisEvent;
1410                   uint button;
1411                   uint buttonMask;
1412                   int x = event->x_root, y = event->y_root;
1413                   if(event->button == Button1)
1414                   {
1415                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonUp;
1416                      buttonMask = Button1Mask;
1417                   }
1418                   else if(event->button == Button3)
1419                   {
1420                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonUp;
1421                      buttonMask = Button3Mask;
1422                   }
1423                   else
1424                   {
1425                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonUp;
1426                      buttonMask = Button2Mask;
1427                   }
1428                   if(!(event->state & buttonMask)) break;
1429                   if(event->state & ShiftMask)     keyFlags.shift = true;
1430                   if(event->state & ControlMask)   keyFlags.ctrl = true;
1431                   if(event->state & Mod1Mask)      keyFlags.alt = true;
1432                   if(event->state & Button1Mask)   keyFlags.left = true;
1433                   if(event->state & Button2Mask)   keyFlags.middle = true;
1434                   if(event->state & Button3Mask)   keyFlags.right = true;
1435                   if(guiApp.windowCaptured && guiApp.windowCaptured != window)
1436                   {
1437                      // X hasn't noticed the capture yet, so fix it!
1438                      x += window.absPosition.x;
1439                      y += window.absPosition.y;
1440                      window = guiApp.windowCaptured.rootWindow;
1441                      x -= window.absPosition.x;
1442                      y -= window.absPosition.y;
1443                   }
1444                   //*XUnlockDisplay(xGlobalDisplay);
1445                   incref window;
1446                   window.MouseMessage(button, x, y, &keyFlags, false, false);
1447                   delete window;
1448                   //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1449                   break;
1450                }
1451                case MotionNotify:
1452                { 
1453                   static uint lastTime = 0;
1454                   XMotionEvent * event = (XMotionEvent *) thisEvent;
1455                   while(XCheckIfEvent(xGlobalDisplay, (XEvent *)thisEvent, EventChecker, (void *)MotionNotify));
1456                   // if(event->time - lastTime > 15)
1457                   {
1458                      Modifiers keyFlags = 0;
1459                      // int x = event->x_root, y = event->y_root;
1460
1461                      if(event->state & ShiftMask)     keyFlags.shift = true;
1462                      if(event->state & ControlMask)   keyFlags.ctrl = true;
1463                      if(event->state & Mod1Mask)      keyFlags.alt = true;
1464                      if(event->state & Button1Mask)   keyFlags.left = true;
1465                      if(event->state & Button2Mask)   keyFlags.middle = true;
1466                      if(event->state & Button3Mask)   keyFlags.right = true;
1467                      //*XUnlockDisplay(xGlobalDisplay);
1468                      incref window;
1469                      window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMouseMove,
1470                         event->x_root, event->y_root, &keyFlags, false, false);
1471                      delete window;
1472                      //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1473                      lastTime = (uint)event->time;
1474                   }
1475                   break;
1476                }
1477                case Expose:
1478                {
1479                   XExposeEvent * event = (XExposeEvent *) thisEvent;
1480                   Box box;
1481                   box.left = event->x - window.clientStart.x;
1482                   box.top = event->y - window.clientStart.y;
1483                   box.right = box.left + event->width - 1;
1484                   box.bottom = box.top + event->height - 1;
1485                   window.Update(box);
1486                   box.left   += window.clientStart.x;
1487                   box.top    += window.clientStart.y;
1488                   box.right  += window.clientStart.x;
1489                   box.bottom += window.clientStart.y;
1490                   window.UpdateDirty(box);
1491                   break;
1492                }
1493                case SelectionRequest:
1494                {
1495                     XSelectionRequestEvent *req = (XSelectionRequestEvent *) thisEvent;
1496                     XEvent respond;
1497                          if(req->target == atoms[targets] && clipBoardData)
1498                   {
1499                      Atom * supportedTargets = new Atom[4];
1500                      supportedTargets[0] = atoms[targets];
1501                      supportedTargets[1] = atoms[multiple];
1502                      supportedTargets[2] = XA_STRING;
1503                      supportedTargets[3] = atoms[utf8_string];
1504                      XChangeProperty(xGlobalDisplay,req->requestor, req->_property,
1505                                          XA_ATOM,32,PropModeReplace, (byte *) supportedTargets, 4*sizeof(Atom));
1506                      respond.xselection._property = req->_property;
1507                      delete supportedTargets;
1508                   }
1509                   else if((req->target == XA_STRING || req->target == atoms[utf8_string]) && clipBoardData)
1510                          {
1511                      Atom _property = (req->_property == None) ? req->target : req->_property;
1512                                  XChangeProperty(xGlobalDisplay,req->requestor, _property,
1513                                          req->target/*req->_property*/,8,PropModeReplace, (byte *) clipBoardData, strlen(clipBoardData));
1514                                  respond.xselection._property = _property;
1515                          }
1516                   else
1517                                  respond.xselection._property = None;
1518                          
1519                   respond.xselection.type = SelectionNotify;
1520                          respond.xselection.display = req->display;
1521                          respond.xselection.requestor = req->requestor;
1522                          respond.xselection.selection =req->selection;
1523                          respond.xselection.target = req->target;
1524                          respond.xselection.time = CurrentTime;
1525                          XSendEvent(xGlobalDisplay, req->requestor,0,0,&respond);
1526                   break;
1527                }
1528                case SelectionClear:
1529                {
1530                   delete clipBoardData;
1531                   break;
1532                }
1533                case FocusIn:
1534                {
1535                   if(activeWindow != (X11Window)window.windowHandle)
1536                   {
1537                      XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1538                      Window modalRoot = window.FindModal();
1539                      XWindowData windowData;
1540
1541                      activeWindow = (X11Window)window.windowHandle;
1542
1543                      if(window.parent && window == window.parent.activeChild) break;
1544                      incref window;
1545                      //if(window.creationActivation == activate)
1546                      {
1547                         if(modalRoot)
1548                            modalRoot.ExternalActivate(true, true, window, null); // lastActive);
1549                         else
1550                            window.ExternalActivate(true, true, window, null); // lastActive);
1551                      }
1552                      windowData = modalRoot ? modalRoot.windowData : window.windowData;
1553                      if(windowData && windowData.ic)
1554                      {
1555                         // XSetICValues(ic, XNClientWindow, window.windowHandle, XNFocusWindow, window.windowHandle, 0);
1556                         XSetICFocus(windowData.ic);
1557                      }
1558                      //delete lastActive;
1559                      //lastActive = window;
1560                      //incref lastActive;
1561                      delete window;
1562                   }
1563                   break;
1564                }
1565                case FocusOut:
1566                {
1567 #ifdef _DEBUG
1568                   //printf("Processing a FocusOut Event for %s (%x)\n", window._class.name, window);
1569 #endif
1570
1571                   if(XCheckTypedWindowEvent(xGlobalDisplay, thisEvent->window, FocusIn, (XEvent *)thisEvent))
1572                   {
1573                      break;
1574                   }
1575                   if(thisEvent->window == activeWindow)
1576                      activeWindow = (X11Window)null;
1577 #if 0
1578                   if(XCheckTypedEvent(xGlobalDisplay, FocusIn, (XEvent *)thisEvent))
1579                   {
1580                      if(XCheckTypedWindowEvent(xGlobalDisplay, thisEvent->window, FocusOut, (XEvent *)thisEvent))
1581                      {
1582                         XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1583                         
1584                         XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1585                         if(window)
1586                         {
1587                            Window windowCopy = window;
1588                            XWindowData windowData;
1589                            if(windowCopy == windowCopy.parent.activeChild) break;
1590                            incref windowCopy;
1591                            windowCopy.ExternalActivate(true, true,  windowCopy, lastActive);
1592
1593                            windowData = windowCopy.windowData;
1594                            if(windowData && windowData.ic)
1595                               XSetICFocus(windowData.ic);
1596
1597                            delete lastActive;
1598                            lastActive = windowCopy;
1599                            incref lastActive;
1600                            delete windowCopy;
1601                         }
1602
1603                         // XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1604                         if(window)
1605                         {
1606                            if(window != window.parent.activeChild) break;
1607                            incref window;
1608                            window.ExternalActivate(false, true,  window, lastActive);
1609                            delete window;
1610                         }
1611                      }
1612                      else
1613                      {
1614                         XWindowData windowData;
1615                         XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1616                         
1617                         if(window)
1618                         {
1619                            XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1620                            Window modalRoot = window.FindModal();
1621
1622                            incref window;
1623                            if(modalRoot)
1624                            {
1625                               modalRoot.ExternalActivate(true, true, window, lastActive);
1626                            }
1627                            else
1628                            {
1629                               window.ExternalActivate(true, true, window, lastActive);
1630                            }
1631                            windowData = modalRoot ? modalRoot.windowData : window.windowData;
1632                            if(windowData && windowData.ic)
1633                               XSetICFocus(windowData.ic);
1634
1635                            delete lastActive;
1636                            lastActive = window;
1637                            incref lastActive;
1638                            delete window;
1639                         }
1640                      }
1641                   }
1642                   else
1643 #endif
1644                   {
1645                      XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1646                      if(window != window.parent.activeChild && window != guiApp.interimWindow) break;
1647                      incref window;
1648
1649 #ifdef _DEBUG
1650                      //printf("Deactivating %s\n", window._class.name);
1651 #endif
1652
1653                      if(!window.ExternalActivate(false, true, window, null /*lastActive*/))
1654                      {
1655                         XCheckTypedEvent(xGlobalDisplay, /*thisEvent->window, */ButtonPress, (XEvent *)thisEvent);
1656                      }
1657                      
1658                      //delete lastActive;
1659                      /*
1660                      lastActive = window;
1661                      incref lastActive;
1662                      */
1663                      delete window;
1664                   }
1665                   break;
1666                }
1667                case ConfigureNotify:
1668                {
1669                   XConfigureEvent * event = (XConfigureEvent *) thisEvent;
1670                   while(XCheckIfEvent(xGlobalDisplay, (XEvent *)thisEvent, (void *)ConfigureNotifyChecker, (void *)window.windowHandle));
1671                   //if(event->x - desktopX != window.position.x || event->y - desktopY != window.position.y || event->width != window.size.w || event->height != window.size.h)
1672
1673                   // TODO: Support _NET_REQUEST_FRAME_EXTENTS message / _NET_FRAME_EXTENTS property for decoration size awareness
1674                   if(window.nativeDecorations)
1675                   {
1676                      int format;
1677                      unsigned long len, fill;
1678                      Atom type;
1679                      char * data = null;
1680                      if(XGetWindowProperty(xGlobalDisplay, (X11Window)window.systemHandle, atoms[_net_wm_state], 0, 32, False,
1681                             XA_ATOM, &type, &format, &len, &fill, &data) == Success)
1682                      {
1683                         bool maxVert = false, maxHorz = false, isMinimized = false;
1684                         Atom * hints = (Atom *)data;
1685                         int c;
1686                         for(c = 0; c < len && hints[c]; c++)
1687                         {
1688                            if(hints[c] == atoms[_net_wm_state_maximized_vert])
1689                               maxVert = true;
1690                            else if(hints[c] == atoms[_net_wm_state_maximized_horz])
1691                               maxHorz = true;
1692                            else if(hints[c] == atoms[_net_wm_state_hidden])
1693                               isMinimized = true;
1694                         }
1695                         XFree(data);
1696
1697                         if(maxVert && maxHorz)
1698                         {
1699                            if(window.state != maximized)
1700                               *&window.state = maximized;
1701                         }
1702                         else if(isMinimized)
1703                         {
1704                            if(window.state != minimized)
1705                               *&window.state = minimized;
1706                         }
1707                         else if(window.state != normal)
1708                            *&window.state = normal;
1709                      }
1710                   }
1711                   {
1712                      int x = event->x;
1713                      int y = event->y;
1714                      int w = event->width, h = event->height;
1715
1716                      //if(event->send_event)
1717                      {
1718                         X11Window rootChild;
1719                         int rootX, rootY;
1720                         XTranslateCoordinates(xGlobalDisplay, event->window,
1721                            RootWindow(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 0, 0, 
1722                            &rootX, &rootY, &rootChild);
1723                         x = rootX;
1724                         y = rootY;
1725                      }
1726
1727                      x -= desktopX;
1728                      y -= desktopY;
1729
1730                      if(window.nativeDecorations && window.state != maximized)
1731                      {
1732                         x -= windowData.decor.left;
1733                         y -= windowData.decor.top;
1734                         w += windowData.decor.left + windowData.decor.right;
1735                         h += windowData.decor.top + windowData.decor.bottom;
1736                         /*
1737                         x -= window.clientStart.x;
1738                         y -= window.clientStart.y - (window.hasMenuBar ? skinMenuHeight : 0);
1739                         w += window.size.w - window.clientSize.w;
1740                         h += window.size.h - window.clientSize.h;
1741                         */
1742                      }
1743                      window.Position(x, y, w, h, true, true, true, true, false, false);
1744                   }
1745                   break;
1746                }
1747                case ClientMessage:
1748                {
1749                   XClientMessageEvent * event = (XClientMessageEvent *) thisEvent;
1750
1751                   if(event->data.l[0] == atoms[wm_delete_window])
1752                   {
1753                      window.Destroy(0);
1754                   }
1755
1756                   if(event->data.l[0] == atoms[wm_take_focus])
1757                   {
1758                      Window modalRoot;
1759                      XWindowData windowData;
1760                      bool laterFocus;
1761                      activeWindow = (X11Window)window.windowHandle;
1762
1763                      timeStamp = (int)event->data.l[1];
1764                      
1765                      windowData = window.windowData;
1766                      laterFocus = windowData.laterFocus;
1767                      windowData.laterFocus = true;
1768
1769 #ifdef _DEBUG
1770                      //printf("Processing a ClientMessage WM_TAKE_FOCUS Event for %s (%x)\n", window._class.name, window);
1771 #endif
1772                      if(guiApp.interimWindow && guiApp.interimWindow.created && window != guiApp.interimWindow) break; //window == window.parent.activeChild) break;
1773                      // if(window == window.parent.activeChild) break;
1774                      incref window;
1775    
1776                      {
1777                         XEvent checkEvent;
1778                         //XFlush(xGlobalDisplay);
1779                         while(XCheckTypedEvent(xGlobalDisplay, FocusOut, &checkEvent))
1780                         {
1781                            XFocusChangeEvent *event = (XFocusChangeEvent *) &checkEvent;
1782                            Window window;
1783                            XFindContext(xGlobalDisplay, event->window, windowContext, (XPointer *) &window);
1784                            if(window != window.parent.activeChild) break;
1785                            incref window;
1786
1787       #ifdef _DEBUG
1788                            //printf("Found a FocusOut ahead, deactivating %s (%d)\n", window._class.name, window);
1789       #endif
1790
1791                            if(!window.ExternalActivate(false, true, window, null /*lastActive*/))
1792                            {
1793                               XCheckTypedEvent(xGlobalDisplay, /*thisEvent->window, */ButtonPress, (XEvent *)thisEvent);
1794                            }
1795                            delete lastActive;
1796                            delete window;
1797                         }
1798                      }
1799
1800                      modalRoot = window.FindModal();
1801                      windowData = modalRoot ? modalRoot.windowData : window.windowData;
1802                      if(windowData)
1803                      {
1804                         if(laterFocus || (modalRoot ? modalRoot : window).creationActivation == activate)
1805                         {
1806                            if(modalRoot)
1807                            {
1808                               XRaiseWindow(xGlobalDisplay, (X11Window)modalRoot.windowHandle);
1809                               WaitForViewableWindow(modalRoot);
1810                               if(atoms[_net_active_window])
1811                               {
1812                                  XClientMessageEvent event = { 0 };
1813                                  event.type = ClientMessage;
1814                                  event.message_type = atoms[_net_active_window];
1815                                  event.display = xGlobalDisplay;
1816                                  event.serial = 0;
1817                                  event.window = (X11Window)modalRoot.windowHandle;
1818                                  event.send_event = 1;
1819                                  event.format = 32;
1820                                  event.data.l[0] = 0;
1821                                  /*
1822                                  event.data.l[0] = 1;
1823                                  event.data.l[1] = atoms[_net_wm_user_time];
1824                                  event.data.l[2] = activeWindow; //guiApp.desktop.activeChild.windowHandle;
1825                                  */
1826 #ifdef _DEBUG
1827                                  //printf("(ClientMessage - %s) Setting _NET_ACTIVE_WINDOW for %s (%x)\n", window._class.name, modalRoot._class.name, modalRoot);
1828 #endif
1829
1830                                  XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
1831                                  XSetInputFocus(xGlobalDisplay, (X11Window)modalRoot.windowHandle, RevertToPointerRoot, (uint)timeStamp);
1832
1833                                  //XFlush(xGlobalDisplay);
1834                                  //printf("Done.\n");
1835                               }
1836                            }
1837                            else
1838                            {
1839                               XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToPointerRoot, (uint)timeStamp);
1840                               window.ExternalActivate(true, true, window, null); // lastActive); 
1841                               if(windowData && windowData.ic)
1842                               {
1843                                  // XSetICValues(ic, XNClientWindow, window.windowHandle, XNFocusWindow, window.windowHandle, 0);
1844                                  //XSetICFocus(windowData.ic);
1845                               }
1846                            }
1847                         }
1848                         windowData.laterFocus = true;
1849                         delete lastActive;
1850                         lastActive = window;
1851                         incref lastActive;
1852                      }
1853                      delete window;
1854                   }
1855                   break;
1856                }
1857                case PropertyNotify:
1858                {
1859                   XWindowData windowData = window.windowData;
1860                   XPropertyEvent * event = (XPropertyEvent *) thisEvent;
1861                   if(event->atom == atoms[_net_frame_extents] &&
1862                     event->state == PropertyNewValue && windowData)
1863                   {
1864                      int format;
1865                      unsigned long len, fill;
1866                      Atom type;
1867                      char * data = null;
1868
1869                      if(XGetWindowProperty(xGlobalDisplay, (X11Window)window.windowHandle,
1870                         atoms[_net_frame_extents], 0, 4,
1871                          False, XA_CARDINAL, &type, &format, &len,
1872                          &fill, &data) == Success && data)
1873                      {
1874                         long *extents = (long *)data;
1875                         bool change = extents[0] != windowData.decor.left ||
1876                                       extents[1] != windowData.decor.right ||
1877                                       extents[2] != windowData.decor.top ||
1878                                       extents[3] != windowData.decor.bottom;
1879
1880                         bool hadFrameExtents = windowData.gotFrameExtents;
1881                         Box oldDecor = windowData.decor;
1882                         if(!hadFrameExtents || extents[0] || extents[1] || extents[2] || extents[3])
1883                         {
1884                            windowData.decor =
1885                            {
1886                               left = (int)extents[0], right  = (int)extents[1],
1887                               top  = (int)extents[2], bottom = (int)extents[3]
1888                            };
1889                            windowData.gotFrameExtents = true;
1890                            if(change && ((Window)window).clientSize.w > 0)
1891                            {
1892                               int x = window.position.x, y = window.position.y, w = window.size.w, h = window.size.h;
1893                               if(!hadFrameExtents && window.state != maximized)
1894                               {
1895                                  window.ComputeAnchors(
1896                                     window.normalAnchor,
1897                                     window.normalSizeAnchor,
1898                                     &x, &y, &w, &h);
1899                               }
1900                               else
1901                               {
1902                                  x += windowData.decor.left - oldDecor.left;
1903                                  y += windowData.decor.top - oldDecor.top;
1904
1905                                  w += windowData.decor.left - oldDecor.left + windowData.decor.right - oldDecor.right;
1906                                  h += windowData.decor.top - oldDecor.top   + windowData.decor.bottom - oldDecor.bottom;
1907                               }
1908
1909                               if(window.state != maximized)
1910                               {
1911                                  window.Position(x, y, w, h, true, true, true, true, false, !hadFrameExtents && window.state != maximized);
1912                                  UpdateRootWindow(window);
1913                               }
1914                            }
1915                         }
1916                         XFree(data);
1917                      }
1918                      else
1919                         windowData.gotFrameExtents = true; // Unsupported?
1920                   }
1921                   break;
1922                }
1923             }
1924             if(!processAll) break;
1925          }
1926       }
1927       //*if(xGlobalDisplay) XUnlockDisplay(xGlobalDisplay);
1928       //xMutex.Release();
1929       if(!eventAvailable)
1930          return false;
1931       return true;
1932    }
1933
1934    void Wait()
1935    {
1936       gotAnXEvent = false;
1937       xMutex.Release();
1938       xSemaphore.Release();
1939       guiApp.WaitEvent();
1940       xMutex.Wait();
1941    }
1942
1943    void Lock(Window window)
1944    {
1945       //*XLockDisplay(xGlobalDisplay);
1946    }
1947
1948    void Unlock(Window window)
1949    {
1950       //*XUnlockDisplay(xGlobalDisplay);
1951    }
1952
1953    char ** GraphicsDrivers(int * numDrivers)
1954    {
1955       static char *graphicsDrivers[] = { "X", "OpenGL" };
1956       *numDrivers = sizeof(graphicsDrivers) / sizeof(char *);
1957       return (char **)graphicsDrivers;
1958    }
1959
1960    void GetCurrentMode(bool * fullScreen, int * resolution, int * colorDepth, int * refreshRate)
1961    {
1962       *fullScreen = fullScreenMode;
1963    }
1964
1965    void EnsureFullScreen(bool *fullScreen)
1966    {
1967
1968    }
1969
1970    bool ScreenMode(bool fullScreen, int resolution, int colorDepth, int refreshRate, bool * textMode)
1971    {
1972       bool result = true;
1973
1974       fullScreenMode = fullScreen;
1975
1976       if(fullScreen)
1977       {
1978
1979       }
1980       else
1981       {
1982          static bool firstTime = true;
1983          firstTime = false;
1984          desktopX = desktopY = desktopW = desktopH = 0;
1985
1986          RepositionDesktop(false);
1987       }
1988       return result;
1989    }
1990
1991    // --- Window Creation ---
1992    void * CreateRootWindow(Window window)
1993    {
1994       X11Window windowHandle;
1995       XSetWindowAttributes attributes = { 0 };
1996       XVisualInfo * visualInfo = null;
1997       int depth;
1998       Visual * visual;
1999       XIC ic = null;
2000       unsigned long mask = EVENT_MASK;
2001
2002       attributes.override_redirect = window.interim ? True : False;
2003       attributes.event_mask = EVENT_MASK;
2004       //printf("%s\n", guiApp.defaultDisplayDriver);
2005 #if !defined(ECERE_VANILLA) && !defined(ECERE_NO3D) && !defined(ECERE_NOGL)
2006       if(window.dispDriver == class(OpenGLDisplayDriver) || !strcmp(guiApp.defaultDisplayDriver, "OpenGL"))
2007       {
2008          int samples;
2009          bool alpha = true;
2010          for(samples = 4;; samples /= 2)
2011          {
2012             bool found = false;
2013             int attrib[30] =
2014             {
2015                GLX_RENDER_TYPE, GLX_RGBA_BIT,
2016                GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
2017                GLX_DOUBLEBUFFER, True,
2018                GLX_DEPTH_SIZE, 1,
2019                GLX_RED_SIZE, 1,
2020                GLX_GREEN_SIZE, 1,
2021                GLX_BLUE_SIZE, 1
2022             };
2023             int numAttribs = 14;
2024             
2025             GLXFBConfig *fbconfigs = null, fbconfig;
2026             int numfbconfigs;
2027             int i;
2028             //printf("Samples = %d, alpha = %d\n", samples, alpha);
2029             if(alpha)
2030             {
2031                attrib[numAttribs++] = GLX_ALPHA_SIZE;
2032                attrib[numAttribs++] = 1;
2033             }
2034             if(samples)
2035             {
2036                attrib[numAttribs++] = GLX_SAMPLE_BUFFERS_ARB;
2037                attrib[numAttribs++] = GL_TRUE;
2038                attrib[numAttribs++] = GLX_SAMPLES_ARB;
2039                attrib[numAttribs++] = samples;
2040             }
2041             attrib[numAttribs] = None;
2042
2043             // visualInfo = glXChooseVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib);
2044
2045             //printf("Trying %d samples...\n", samples);
2046             fbconfigs = glXChooseFBConfig(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib, &numfbconfigs);
2047             if(fbconfigs)
2048             {
2049                for (i = 0; i < numfbconfigs; i++)
2050                {
2051                   XRenderPictFormat * format;
2052                   visualInfo = glXGetVisualFromFBConfig(xGlobalDisplay, fbconfigs[i]);
2053                   if (!visualInfo) continue;
2054                   if(window.alphaBlend)
2055                   {
2056                      format = XRenderFindVisualFormat(xGlobalDisplay, visualInfo->visual);
2057                      if (!format) { XFree(visualInfo); continue; }
2058                      if(format->direct.alphaMask > 0)
2059                      {
2060                         //printf("Found what we're looking for (alphaBlend)\n");
2061                         fbconfig = fbconfigs[i];
2062                         found = true;
2063                         break;
2064                      }
2065                   }
2066                   else
2067                   {
2068                      //printf("Found what we're looking for\n");
2069                      found = true;
2070                      break;
2071                   }
2072                }
2073                if (i == numfbconfigs)
2074                {
2075                   fbconfig = fbconfigs[0];
2076                   visualInfo = glXGetVisualFromFBConfig(xGlobalDisplay, fbconfig);
2077                }
2078             }
2079             if(fbconfigs)
2080                XFree(fbconfigs);
2081             if(found || (!samples && !alpha))
2082             {
2083                //printf("Stopping now\n");
2084                break;
2085             }
2086             else
2087                XFree(visualInfo);
2088             if(samples == 1) samples = 0;
2089             else if(!samples) alpha = false;
2090          }
2091       }
2092       if(!visualInfo)
2093       {
2094          int attrList[] = 
2095          {
2096             GLX_USE_GL, GLX_DEPTH_SIZE, 1,
2097             GLX_RGBA, 
2098             GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
2099             GLX_DOUBLEBUFFER, 
2100             None
2101          };
2102          visualInfo = glXChooseVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrList);
2103       }
2104 #endif
2105       depth = visualInfo ? visualInfo->depth : (window.alphaBlend ? 32 : xSystemDepth);
2106       visual = visualInfo ? visualInfo->visual : (window.alphaBlend ? FindFullColorVisual (xGlobalDisplay, &depth) : xSystemVisual);
2107       // printf("visual: %d, depth: %d\n", visual, depth);
2108
2109       if(visual)
2110       {
2111          attributes.colormap = XCreateColormap(xGlobalDisplay, XRootWindow(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), visual, AllocNone);
2112          attributes.border_pixel = 0;
2113       }
2114       else
2115          return null;
2116
2117       if(fullScreenMode)
2118       {
2119          windowHandle = XCreateWindow(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay),
2120             0,0,guiApp.desktop.size.w,guiApp.desktop.size.h,0, depth, InputOutput, visual ? visual : CopyFromParent, 
2121             CWEventMask | (visual ? (CWColormap | CWBorderPixel) : 0)/*| CWOverrideRedirect*/, &attributes);
2122       }
2123       /*
2124          Unsupported for now...
2125       else if(window.systemParent)
2126       {
2127
2128       }
2129       */
2130       else
2131       {
2132          if(window.windowHandle)
2133             windowHandle = (X11Window)window.windowHandle;
2134          else
2135          {
2136             X11Window parentWindow = (X11Window)null;
2137
2138             if(window.master.rootWindow && window.master.rootWindow != guiApp.desktop && (window._isModal || window.style.interim))
2139             {
2140                Window master = window.master;
2141                Window rootWindow = master.rootWindow;
2142
2143                parentWindow = rootWindow.is3D ? (X11Window)rootWindow.parent.windowHandle : (X11Window)rootWindow.windowHandle;
2144
2145                // parentWindow = window.master.rootWindow.is3D ? window.master.rootWindow.parent.windowHandle : window.master.rootWindow.windowHandle;
2146             }
2147             if(window.style.showInTaskBar)
2148                parentWindow = (X11Window)null;
2149
2150             windowHandle = XCreateWindow(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), 
2151                0,0,1,1,0, depth, InputOutput, visual ? visual : CopyFromParent, 
2152                CWEventMask | CWOverrideRedirect | (visual ? (CWColormap | CWBorderPixel) : 0), &attributes);
2153
2154             if(parentWindow && (window.interim || window.isModal))
2155             {
2156                //printf("Setting WM_TRANSIENT_FOR of %s to %s\n", window._class.name, window.master.rootWindow._class.name);
2157                XSetTransientForHint(xGlobalDisplay, windowHandle, parentWindow);
2158                //XFlush(xGlobalDisplay);
2159                //printf("Done.\n");
2160                //XChangeProperty(xGlobalDisplay, windowHandle, atoms[wm_transient_for], XA_WINDOW, 32, PropModeReplace, (unsigned char*)&parentWindow, 1);
2161                if(window.isModal)
2162                {
2163                   Atom hints[1] = { atoms[_net_wm_state_modal] };
2164                   XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_state], XA_ATOM, 32, PropModeReplace, (unsigned char*)&hints, 1);
2165                }
2166             }
2167
2168             {
2169                Atom hints[2] =
2170                {
2171                   parentWindow ? atoms[_net_wm_window_type_menu] : atoms[_net_wm_window_type_normal],
2172                   parentWindow ? atoms[_net_wm_window_type_popup_menu] : 0
2173                };
2174 #if defined(__APPLE__) || defined(__FreeBSD__)
2175                // Don't set this on non-interim windows for OS X...
2176                if(parentWindow && window.interim)
2177 #endif
2178
2179                   XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_window_type], XA_ATOM, 32,
2180                      PropModeReplace, (unsigned char*)&hints, parentWindow ? 2 : 1);
2181                {
2182                   XWMHints xwmHints;
2183                   xwmHints.flags = InputHint;
2184                   xwmHints.input = 0;
2185                   XSetWMHints(xGlobalDisplay, windowHandle, &xwmHints);
2186                }
2187                {
2188                   Atom protocols[2] = { atoms[wm_delete_window], atoms[wm_take_focus] };
2189                   XSetWMProtocols(xGlobalDisplay, windowHandle, protocols, 2);
2190                }
2191             }
2192          }
2193       }
2194
2195       if(!ic && im)
2196       {
2197          char fontString[1024] = "--helvetica-*-r-*-*-*-120-*-*-*-*-*-*,-misc-fixed-*-r-*-*-*-130-*-*-*-*-*-*";
2198          XPoint cursor_location = { 0, 0 };
2199          char **missing_charsets;
2200          int num_missing_charsets = 0;
2201          char *default_string;
2202          XFontSet fontset;
2203          XRectangle area = { 0, 0,  400, 400 };         
2204          XVaNestedList argList;
2205
2206          // sprintf(fontString, "-*-%s-*-r-*-*-*-%d-*-*-*-*-*-*", "Helvetica" /*window.font.faceName*/, (int)(window.font.size * 20));
2207          fontset = XCreateFontSet(xGlobalDisplay, fontString, &missing_charsets, &num_missing_charsets, &default_string);
2208          argList = XVaCreateNestedList(0,
2209                                        XNSpotLocation, &cursor_location, 
2210                                        //XNArea, &area,
2211                                        XNFontSet, fontset,/*
2212                                        XNForeground,
2213                                        WhitePixel(xGlobalDisplay, DefaultScreen(xGlobalDisplay)),
2214                                        XNBackground,
2215                                        BlackPixel(xGlobalDisplay, DefaultScreen(xGlobalDisplay)),*/
2216                                        NULL);
2217          ic = XCreateIC(im, XNInputStyle,
2218             XIMStatusNothing | XIMPreeditPosition,
2219             XNPreeditAttributes, argList,
2220             XNClientWindow, windowHandle, XNFocusWindow, windowHandle, NULL);
2221          XFree(argList);
2222          // Should we free the fontset or not?
2223          // XFreeFontSet(xGlobalDisplay, fontset);
2224          if(ic)
2225             setICPosition = true;
2226          else
2227             ic = XCreateIC(im, XNInputStyle, XIMStatusNothing | XIMPreeditNothing, XNClientWindow, windowHandle, XNFocusWindow, windowHandle, null);
2228       }
2229       if(ic)
2230       {
2231               XGetICValues(ic, XNFilterEvents, &mask, NULL);
2232               mask |= EVENT_MASK;
2233       }
2234       /*
2235       XSelectInput(xGlobalDisplay, windowHandle, mask);
2236
2237       if(capturedWindow == None && !restrictedWindow)
2238       {
2239          XGrabPointer(xGlobalDisplay, (X11Window)windowHandle, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2240             GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
2241          XUngrabPointer(xGlobalDisplay, CurrentTime);
2242       }
2243       */
2244
2245       {
2246          if ( atoms[_motif_wm_hints] != None ) 
2247          {
2248             MWM_Hints hints
2249             {
2250                (window.nativeDecorations ? 0 : MWM_HINTS_DECORATIONS)|MWM_HINTS_FUNCTIONS,
2251                (window.hasClose ? MWM_FUNC_CLOSE : 0) |
2252                (window.hasMaximize ? MWM_FUNC_MAXIMIZE : 0) |
2253                (window.hasMinimize ? MWM_FUNC_MINIMIZE : 0) |
2254                ((window.moveable || ((BorderBits)window.borderStyle).fixed) ? MWM_FUNC_MOVE : 0) |
2255                (((BorderBits)window.borderStyle).sizable ? MWM_FUNC_RESIZE : 0),
2256                 0, 0, 0
2257             };
2258             XChangeProperty(xGlobalDisplay, windowHandle, atoms[_motif_wm_hints], atoms[_motif_wm_hints], 32,
2259                PropModeReplace, (unsigned char*)&hints, 5);
2260          }
2261          if(atoms[_net_wm_pid] != None)
2262          {
2263             int pid = getpid();
2264             // printf("Setting _NET_WM_PID to %d\n", pid); 
2265             XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_pid], XA_CARDINAL, 32,
2266                PropModeReplace, (unsigned char*)&pid, 1);            
2267          }
2268       }
2269       
2270       /*
2271       {
2272          Atom protocolsAtom = XInternAtom(xGlobalDisplay, "WM_PROTOCOLS", False);
2273          if ( protocolsAtom != None ) 
2274          {
2275             MWM_Hints hints = { MWM_HINTS_DECORATIONS|MWM_HINTS_FUNCTIONS, 0, 0, 0, 0 };
2276             XChangeProperty(xGlobalDisplay, windowHandle, atoms[_motif_wm_hints], atoms[_motif_wm_hints], 32,
2277                PropModeReplace, (unsigned char*)&hints, sizeof(hints)/4);
2278          }
2279       }*/
2280       // XFlush(xGlobalDisplay);
2281       window.windowData = XWindowData { visualInfo, ic };
2282       
2283       XSaveContext(xGlobalDisplay, windowHandle, windowContext, (XPointer)window);
2284
2285       XSelectInput(xGlobalDisplay, windowHandle, mask);
2286
2287       if(capturedWindow == None && !restrictedWindow)
2288       {
2289          XGrabPointer(xGlobalDisplay, (X11Window)windowHandle, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2290             GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
2291          XUngrabPointer(xGlobalDisplay, CurrentTime);
2292       }
2293
2294       if(window.nativeDecorations)
2295       {
2296          // Maximize / Restore the window
2297          XClientMessageEvent event = { 0 };
2298          event.type = ClientMessage;
2299          event.message_type = atoms[_net_request_frame_extents];
2300          event.display = xGlobalDisplay;
2301          event.serial = 0;
2302          event.window = (X11Window)windowHandle;
2303          event.send_event = 1;
2304          window.windowHandle = (void *)windowHandle;
2305          event.format = 32;
2306          XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false,
2307             SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
2308       }
2309       return (void *)windowHandle;
2310    }
2311
2312    void DestroyRootWindow(Window window)
2313    {
2314       XEvent event;
2315
2316       XDeleteContext(xGlobalDisplay, (XID)window, windowContext); 
2317       XSaveContext(xGlobalDisplay, (X11Window)window.windowHandle, windowContext, null);
2318       XDestroyWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2319       XSync(xGlobalDisplay, 0);
2320       while(XCheckWindowEvent(xGlobalDisplay, (X11Window)window.windowHandle, 0xFFFFFFFF, &event));
2321       window.windowHandle = null;
2322       if(window.windowData)
2323       {
2324          XWindowData windowData = window.windowData;
2325          XFree(windowData.visual);
2326          if(windowData && windowData.ic)
2327             XDestroyIC(windowData.ic);
2328          delete windowData;
2329          // printf("Setting windowData for %s to null\n", window._class.name);
2330          window.windowData = null;
2331       }
2332       if(lastActive == window)
2333          delete lastActive;
2334    }
2335
2336    // -- Window manipulation ---
2337
2338    void SetRootWindowCaption(Window window, char * name)
2339    {
2340       if(window.windowHandle)
2341       {
2342          XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[_net_wm_name],
2343             atoms[utf8_string], 8, PropModeReplace, (byte *)name, name ? strlen(name) : 0);
2344          XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[wm_name],
2345             atoms[utf8_string], 8, PropModeReplace, (byte *)name, name ? strlen(name) : 0);
2346       }   
2347    }
2348
2349    void PositionRootWindow(Window window, int x, int y, int w, int h, bool move, bool resize)
2350    {
2351       //Logf("Position root window %s\n", window.name);
2352       if(window.windowHandle && (!window.parent || !window.parent.display))
2353       {
2354          bool visible = window.visible;
2355          if(window.visible && window.created)
2356             XMapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2357          if(window.state == minimized) return;
2358
2359          if(window.nativeDecorations)
2360          {
2361             XWindowData windowData = window.windowData;
2362
2363             // Was commenting this out was part of #700/#795 fix, but this causes jumping of e.g. About box after getting frame extents PropertyNotify
2364
2365                // && window.state != maximized -- required for Cinnamon on Mint 14/15
2366             if(!windowData.gotFrameExtents && window.state != maximized) return;
2367
2368             x -= windowData.decor.left;
2369             y -= windowData.decor.top;
2370
2371             w -= windowData.decor.left + windowData.decor.right;
2372             h -= windowData.decor.top + windowData.decor.bottom;
2373
2374             // Tweak for first unmaximize on Unity on Ubuntu 11.10
2375             if(window.state == maximized && (desktopX + w > desktopW || desktopY + h > desktopH))
2376             {
2377                w -= 40;
2378                h -= 40;
2379             }
2380          }
2381
2382          x += desktopX;
2383          y += desktopY;
2384
2385          if(move && resize)
2386             XMoveResizeWindow(xGlobalDisplay, (X11Window)window.windowHandle, x, y, w, h);
2387          else if(move)
2388             XMoveWindow(xGlobalDisplay, (X11Window)window.windowHandle, x, y);
2389          else if(resize)
2390             XResizeWindow(xGlobalDisplay, (X11Window)window.windowHandle, w, h);
2391 #if defined(__APPLE__)
2392 //         if(window.created && !visible)
2393   //          XUnmapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2394 #endif
2395       }
2396    }
2397
2398    void OrderRootWindow(Window window, bool topMost)
2399    {
2400
2401    }
2402
2403    void SetRootWindowColor(Window window)
2404    {
2405
2406    }
2407
2408    void OffsetWindow(Window window, int * x, int * y)
2409    {
2410
2411    }
2412
2413    void UpdateRootWindow(Window window)
2414    {
2415       if(!window.parent || !window.parent.display)
2416       {
2417          if(window.visible)
2418          {
2419             Box box = window.box;
2420             box.left -= window.clientStart.x;
2421             box.top -= window.clientStart.y;
2422             box.right -= window.clientStart.x;
2423             box.bottom -= window.clientStart.y;
2424             // Logf("Update root window %s\n", window.name);
2425             window.Update(null);
2426             box.left   += window.clientStart.x;
2427             box.top    += window.clientStart.y;
2428             box.right  += window.clientStart.x;
2429             box.bottom += window.clientStart.y;
2430             window.UpdateDirty(box);
2431          }
2432       }
2433    }
2434
2435
2436    void SetRootWindowState(Window window, WindowState state, bool visible)
2437    {
2438       if(!window.parent || !window.parent.display)
2439       {
2440          //Logf("Set root window state %d %s\n", state, window.name);
2441          if(visible)
2442          {
2443             XMapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2444             WaitForViewableWindow(window);
2445             if(window.creationActivation == activate && state != minimized)
2446                ActivateRootWindow(window);
2447             
2448             if(state == minimized)
2449             {
2450                uint iconic = IconicState;
2451                /*
2452                XChangeProperty(xGlobalDisplay, window.windowHandle, atoms[_net_wm_state], XA_ATOM, 32,
2453                   PropModeReplace, (unsigned char*)&atoms[_net_wm_state_hidden], 1);
2454                */
2455                /*
2456                XChangeProperty(xGlobalDisplay, window.windowHandle, atoms[wm_state], XA_CARDINAL, 32,
2457                   PropModeReplace, &iconic, 1);
2458                */
2459                
2460                /*
2461                XClientMessageEvent event = { 0 };
2462                event.type = ClientMessage;
2463                event.message_type = atoms[_net_wm_state];
2464                event.display = xGlobalDisplay;
2465                event.serial = 0;
2466                event.window = window.windowHandle;
2467                event.send_event = 1;
2468                event.format = 32;
2469                event.data.l[0] = 2; // 1;
2470                event.data.l[1] = atoms[_net_wm_state_hidden];
2471                XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, &event);
2472                */
2473                /*
2474                XClientMessageEvent event = { 0 };
2475                event.type = ClientMessage;
2476                event.message_type = atoms[wm_state];
2477                event.display = xGlobalDisplay;
2478                event.window = window.windowHandle;
2479                event.send_event = 1;
2480                event.format = 32;
2481                event.data.l[0] = IconicState;
2482                XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, &event);
2483                */
2484
2485                // printf("Attempting to minimize %s\n", window._class.name);
2486                XIconifyWindow(xGlobalDisplay, (X11Window)window.windowHandle, DefaultScreen(xGlobalDisplay));
2487             }
2488             else
2489             {
2490                if(!window.nativeDecorations || (!((XWindowData)window.windowData).gotFrameExtents && window.state == maximized)) //((XWindowData)window.windowData).gotFrameExtents && (!window.nativeDecorations || window.state == state))
2491                {
2492                   int x = window.position.x;
2493                   int y = window.position.y;
2494                   int w = window.size.w;
2495                   int h = window.size.h;
2496
2497                   if(window.nativeDecorations)
2498                   {
2499                      XWindowData windowData = window.windowData;
2500                      x -= windowData.decor.left;
2501                      y -= windowData.decor.top;
2502
2503                      w -= windowData.decor.left + windowData.decor.right;
2504                      h -= windowData.decor.top + windowData.decor.bottom;
2505                   }
2506                   x += desktopX;
2507                   y += desktopY;
2508
2509                   // With native decorations, we do it the first time
2510                   // or the WM (Gnome) is sticking it to the top/right!
2511                   XMoveResizeWindow(xGlobalDisplay, 
2512                      (X11Window)window.windowHandle,
2513                      x, y, w, h);
2514                   UpdateRootWindow(window);
2515                }
2516                if(window.nativeDecorations)
2517                {
2518                   // Maximize / Restore the window
2519                   XClientMessageEvent event = { 0 };
2520                   event.type = ClientMessage;
2521                   event.message_type = atoms[_net_wm_state];
2522                   event.display = xGlobalDisplay;
2523                   event.serial = 0;
2524                   event.window = (X11Window)window.windowHandle;
2525                   event.send_event = 1;
2526                   event.format = 32;
2527                   event.data.l[0] = (state == maximized) ? 1 : 0;
2528                   event.data.l[1] = atoms[_net_wm_state_maximized_vert];
2529                   event.data.l[2] = atoms[_net_wm_state_maximized_horz];
2530                   XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false,
2531                      SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
2532                }
2533             }
2534          }
2535          else
2536             XUnmapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2537          //XFlush(xGlobalDisplay);
2538       }
2539    }
2540
2541    void FlashRootWindow(Window window)
2542    {
2543       XClientMessageEvent event = { 0 };
2544       // printf("Attempting to flash root window\n");
2545       event.type = ClientMessage;
2546       event.message_type = atoms[_net_wm_state];
2547       event.display = xGlobalDisplay;
2548       event.serial = 0;
2549       event.window = (X11Window)window.windowHandle;
2550       event.send_event = 1;
2551       event.format = 32;
2552       event.data.l[0] = 1;
2553       event.data.l[1] = atoms[_net_wm_state_demands_attention];
2554       XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
2555    }
2556
2557    void ActivateRootWindow(Window window)
2558    {
2559       if(!window.parent || !window.parent.display)
2560       {
2561          if(!window.style.hidden && window.created)
2562          {
2563             //printf("Activate root window %s\n", window._class.name);
2564             XRaiseWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2565             XMapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2566             WaitForViewableWindow(window);
2567             if(atoms[_net_active_window])
2568             {
2569                XClientMessageEvent event = { 0 };
2570                event.type = ClientMessage;
2571                event.message_type = atoms[_net_active_window];
2572                event.display = xGlobalDisplay;
2573                event.serial = 0;
2574                event.window = (X11Window)window.windowHandle;
2575                event.send_event = 1;
2576                event.format = 32;
2577                event.data.l[0] = 0;
2578                
2579                //event.data.l[0] = 2;
2580                //event.data.l[1] = timeStamp;
2581                
2582
2583                //event.data.l[1] = atoms[_net_wm_user_time];
2584                //event.data.l[2] = activeWindow; //guiApp.desktop.activeChild.windowHandle;
2585                
2586 #ifdef _DEBUG
2587                //printf("(ActivateRootWindow) Setting _NET_ACTIVE_WINDOW for %s (%x)\n", window._class.name, window);
2588 #endif
2589                
2590                XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
2591 //#if defined(__APPLE__)
2592                XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToPointerRoot, CurrentTime);
2593 //#endif
2594             }
2595             else
2596                XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToPointerRoot, CurrentTime);
2597          }
2598       }
2599    }
2600
2601    // --- Mouse-based window movement ---
2602
2603    void StartMoving(Window window, int x, int y, bool fromKeyBoard)
2604    {
2605
2606    }
2607
2608    void StopMoving(Window window)
2609    {
2610
2611    }
2612
2613    // -- Mouse manipulation ---
2614
2615    void GetMousePosition(int *x, int *y)
2616    {
2617       X11Window rootWindow, childWindow;
2618       int mx, my;
2619       unsigned int state;
2620       ((GuiApplication)__thisModule.application).Lock();
2621       //XLockDisplay(xGlobalDisplay);
2622       XQueryPointer(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), &childWindow, 
2623          &rootWindow, x, y, &mx, &my, &state);
2624       //XUnlockDisplay(xGlobalDisplay);
2625       ((GuiApplication)__thisModule.application).Unlock();
2626    }
2627
2628    void SetMousePosition(int x, int y)
2629    {
2630
2631    }
2632
2633    void SetMouseRange(Window window, Box box)
2634    {
2635       ((GuiApplication)__thisModule.application).Lock();
2636       //XLockDisplay(xGlobalDisplay);
2637       if(box && box.left > 0 && box.top > 0 && 
2638          box.right < guiApp.desktop.clientSize.w - 1 && box.bottom < guiApp.desktop.clientSize.h - 1)
2639       {
2640          if(!window.parent || !window.parent.display)
2641          {
2642             XMoveResizeWindow(xGlobalDisplay, confineWindow, box.left + desktopX, box.top + desktopY, 
2643                box.right - box.left + 1, box.bottom - box.top + 1);
2644       
2645             if(!restrictedWindow)
2646                XMapWindow(xGlobalDisplay, confineWindow);
2647
2648             XGrabPointer(xGlobalDisplay, (X11Window) window.rootWindow.windowHandle, False,
2649                ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2650                GrabModeAsync, confineWindow, fullScreenMode ? nullCursor : None, CurrentTime);
2651
2652             restrictedWindow = window;
2653          }
2654       }
2655       else if(restrictedWindow)
2656       {
2657          if(capturedWindow != None)
2658          {
2659             XGrabPointer(xGlobalDisplay, (X11Window)capturedWindow,
2660                False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2661                GrabModeAsync, None, fullScreenMode ? nullCursor : None, CurrentTime);
2662          }
2663          else
2664             XUngrabPointer(xGlobalDisplay, CurrentTime);
2665          
2666          if(restrictedWindow)
2667             XUnmapWindow(xGlobalDisplay, confineWindow);
2668
2669          restrictedWindow = null;
2670       }
2671       //XUnlockDisplay(xGlobalDisplay);
2672       ((GuiApplication)__thisModule.application).Unlock();
2673    }
2674
2675    void SetMouseCapture(Window window)
2676    {
2677       //*XLockDisplay(xGlobalDisplay);
2678       if(window)
2679       {
2680          if(!window.parent || !window.parent.display)
2681          {
2682             XGrabPointer(xGlobalDisplay, (X11Window)window.windowHandle,
2683                False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2684                GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
2685
2686             capturedWindow = (X11Window) window.windowHandle;
2687          }
2688       }
2689       else if(capturedWindow != None)
2690       {
2691          if(restrictedWindow)
2692             XGrabPointer(xGlobalDisplay, (X11Window) restrictedWindow.rootWindow.windowHandle, False, 
2693                ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2694                GrabModeAsync, confineWindow, fullScreenMode ? nullCursor : None, CurrentTime);
2695          else
2696             XUngrabPointer(xGlobalDisplay, CurrentTime);
2697          capturedWindow = None;
2698       }
2699       //*XUnlockDisplay(xGlobalDisplay);
2700    }
2701
2702    // -- Mouse cursor ---
2703
2704    void SetMouseCursor(int cursor)
2705    {
2706       //*XLockDisplay(xGlobalDisplay);
2707       if(cursor == -1)
2708       {
2709          XDefineCursor(xGlobalDisplay, (X11Window) guiApp.desktop.windowHandle, nullCursor);
2710       }
2711       //*XUnlockDisplay(xGlobalDisplay);
2712    }
2713
2714    // --- Caret ---
2715
2716    void SetCaret(int x, int y, int size)
2717    {
2718       Window caretOwner = guiApp.caretOwner;
2719       Window window = caretOwner ? caretOwner.rootWindow : null;
2720       if(window && window.windowData && setICPosition)
2721       {
2722          XWindowData windowData = window.windowData;
2723          if(windowData && windowData.ic)
2724          {
2725             XPoint cursor_location =
2726             {
2727                (short)(caretOwner.caretPos.x - caretOwner.scroll.x + caretOwner.absPosition.x - window.absPosition.x),
2728                (short)(caretOwner.caretPos.y - caretOwner.scroll.y + caretOwner.absPosition.y - window.absPosition.y)
2729             };
2730             XVaNestedList argList = XVaCreateNestedList(0, XNSpotLocation, &cursor_location, NULL);
2731             XSetICValues(windowData.ic, XNPreeditAttributes, argList, 0);
2732          }
2733       }
2734    }  
2735
2736    void ClearClipboard()
2737    {
2738       //*XLockDisplay(xGlobalDisplay);
2739       if(clipBoardData)
2740       {
2741          delete clipBoardData;
2742         XSetSelectionOwner(xGlobalDisplay, atoms[clipboard], None, CurrentTime);
2743       }
2744       //*XUnlockDisplay(xGlobalDisplay);
2745    }
2746
2747    bool AllocateClipboard(ClipBoard clipBoard, uint size)
2748    {
2749       bool result = false;
2750       if((clipBoard.text = new0 byte[size]))
2751          result = true;   
2752       return result;
2753    }
2754
2755    bool SaveClipboard(ClipBoard clipBoard)
2756    {
2757       bool result = false;
2758       //*XLockDisplay(xGlobalDisplay);
2759       if(clipBoard.text)
2760       {
2761          Window rootWindow = guiApp.desktop;
2762          if(!fullScreenMode) 
2763          {
2764             for(rootWindow = rootWindow.children.first; 
2765                rootWindow && !rootWindow.windowHandle; 
2766                rootWindow = rootWindow.next);
2767          }
2768          if(clipBoardData)
2769             delete clipBoardData;
2770          else if(rootWindow)
2771            XSetSelectionOwner(xGlobalDisplay, atoms[clipboard], 
2772                (X11Window) rootWindow.windowHandle, CurrentTime);
2773          clipBoardData = clipBoard.text;
2774          clipBoard.text = null;
2775          result = true;
2776       }
2777       //*XUnlockDisplay(xGlobalDisplay);
2778       return result;
2779    }
2780
2781    bool LoadClipboard(ClipBoard clipBoard)
2782    {
2783       bool result = false;
2784
2785       //*XLockDisplay(xGlobalDisplay);
2786       // The data is inside this client...
2787       if(clipBoardData)
2788       {
2789          clipBoard.text = new char[strlen(clipBoardData)+1];
2790          strcpy(clipBoard.text, clipBoardData);
2791          result = true;
2792       }
2793       // The data is with another client...
2794       else
2795       {
2796          Window rootWindow = guiApp.desktop;
2797          if(!fullScreenMode)
2798          {
2799             for(rootWindow = rootWindow.children.first; 
2800                rootWindow && !rootWindow.windowHandle; 
2801                rootWindow = rootWindow.next);
2802          }
2803          if(rootWindow)
2804          {
2805             Atom selAtom = atoms[clipboard];
2806             X11Window owner = XGetSelectionOwner(xGlobalDisplay, selAtom);
2807             if(owner != None)
2808             {
2809                Atom atom;
2810                for(atom = atoms[utf8_string]; atom; atom = ((atom == atoms[utf8_string]) ? XA_STRING : 0))
2811                {
2812                   XEvent e;
2813                   XConvertSelection(xGlobalDisplay, selAtom, atom, atoms[app_selection] /*None*/, (X11Window) rootWindow.windowHandle, CurrentTime);
2814                   XIfEvent(xGlobalDisplay, (XEvent *) &e, EventChecker, (void *)SelectionNotify);
2815                   if(e.type == SelectionNotify)
2816                   {
2817                      XSelectionEvent * selection = (XSelectionEvent *) &e;
2818                      //printf("Got a SelectionNotify with %d (%s)\n", selection->_property, XGetAtomName(xGlobalDisplay, selection->_property));
2819                      byte *data = null;
2820                      unsigned long len, size = 0, dummy;
2821                      Atom type;
2822                      int format;
2823                      XGetWindowProperty(xGlobalDisplay, (X11Window) rootWindow.windowHandle, selection->_property ? selection->_property : atom, 0, 0, False, AnyPropertyType, &type, &format, &len, &size, &data);
2824                      if(data)
2825                      {
2826                         XFree(data);
2827                         data = null;
2828                      }
2829                      if(size > 0)
2830                      {
2831                         if(XGetWindowProperty(xGlobalDisplay, (X11Window) rootWindow.windowHandle, selection->_property ? selection->_property : atom, 0, size, False,
2832                               AnyPropertyType, &type,&format,&len, &dummy, &data) == Success)
2833                         {
2834                            clipBoard.text = new char[size+1];
2835                            strncpy(clipBoard.text, data, size);
2836                            clipBoard.text[size] = '\0';
2837                            XFree(data);
2838                            result = true;
2839                            break;
2840                         }
2841                      }
2842                   }
2843                }
2844             }
2845          }
2846       }
2847       //*XUnlockDisplay(xGlobalDisplay);
2848       return result;
2849    }
2850
2851    void UnloadClipboard(ClipBoard clipBoard)
2852    {
2853       delete clipBoard.text;
2854    }
2855
2856    // --- State based input ---
2857
2858    bool AcquireInput(Window window, bool state)
2859    {
2860       return false;
2861    }
2862
2863    bool GetMouseState(MouseButtons * buttons, int * x, int * y)
2864    {
2865       bool result = false;
2866       if(x) *x = 0;
2867       if(y) *y = 0;
2868       return result;
2869    }
2870
2871    bool GetJoystickState(int device, Joystick joystick)
2872    {
2873       bool result = false;
2874    #if defined(__linux__)   
2875       if(joystick && device < 4)
2876       {
2877          struct JS_DATA_TYPE js = { 0 };
2878          memset(joystick, 0, sizeof(Joystick));
2879          if(joystickFD[device] && read(joystickFD[device], &js, JS_RETURN) == JS_RETURN)
2880          {
2881             joystick.buttons = js.buttons;
2882             joystick.x = js.x - 128;
2883             joystick.y = js.y - 128;
2884             result = true;
2885          }
2886       }
2887    #endif   
2888       return result;
2889    }
2890
2891    bool GetKeyState(Key key)
2892    {
2893       int keyState = 0;
2894       return keyState;
2895    }
2896
2897    void SetTimerResolution(uint hertz)
2898    {
2899       timerDelay = hertz ? (1000000 / hertz) : MAXINT;
2900       /*
2901       hiResTimer.Stop();
2902       if(hertz)
2903       {
2904          hiResTimer.delay = 1000000 / hertz;
2905          hiResTimer.Create();
2906       }
2907       */
2908    }  
2909
2910    bool SetIcon(Window window, BitmapResource resource)
2911    {
2912       if(resource)
2913       {
2914          Bitmap bitmap { };
2915          if(bitmap.Load(resource.fileName, null, null))
2916          {
2917             unsigned long * icon = new unsigned long[2 + bitmap.width * bitmap.height];
2918             bitmap.Convert(null, pixelFormat888, null);
2919             icon[0] = bitmap.width;
2920             icon[1] = bitmap.height;
2921             if(sizeof(long) != sizeof(uint32))
2922             {
2923                int c;
2924                for(c = 0; c < bitmap.width * bitmap.height; c++)
2925                   icon[c+2] = ((uint32 *)bitmap.picture)[c];
2926             }
2927             else
2928                memcpy(icon + 2, bitmap.picture, bitmap.width * bitmap.height * sizeof(uint32));
2929             XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[_net_wm_icon],
2930                           XA_CARDINAL,32,PropModeReplace, (byte *)icon, 2+bitmap.width*bitmap.height);
2931            delete icon;
2932          }
2933          delete bitmap;
2934       }
2935       return true;
2936    }
2937 }
2938
2939 default dllexport void * __attribute__((stdcall)) IS_XGetDisplay()
2940 {
2941    return xGlobalDisplay;
2942 }
2943
2944 default dllexport void * __attribute__((stdcall)) IS_XGetWindow(Window window)
2945 {
2946    return window.windowHandle ? window.windowHandle : window.rootWindow.windowHandle;
2947 }
2948
2949 #endif