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