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