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