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