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