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