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