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