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