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