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