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