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