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