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