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