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