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