ecere/gui/drivers/XInterface: Setting more WM_NORMAL_HINTS to avoid jumping windows...
[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 #ifdef _DEBUG
899    Logf("X Error: %s\n", buffer);
900 #endif
901    return 0;
902 }
903
904 static int MyXIOErrorHandler(X11Display * display)
905 {
906    Log("X IO Error\n");
907    return 0;
908 }
909
910 // Motif Hints (to get rid of the decorations)
911 #define MWM_HINTS_FUNCTIONS   (1L << 0)
912 #define MWM_HINTS_DECORATIONS (1L << 1)
913 #define MWM_HINTS_INPUT_MODE  (1L << 2)
914 #define MWM_HINTS_STATUS      (1L << 3)
915
916 #define MWM_DECOR_ALL         (1L << 0)
917 #define MWM_DECOR_BORDER      (1L << 1)
918 #define MWM_DECOR_RESIZEH     (1L << 2)
919 #define MWM_DECOR_TITLE       (1L << 3)
920 #define MWM_DECOR_MENU        (1L << 4)
921 #define MWM_DECOR_MINIMIZE    (1L << 5)
922 #define MWM_DECOR_MAXIMIZE    (1L << 6)
923
924 #define MWM_FUNC_ALL (1L << 0)
925 #define MWM_FUNC_RESIZE (1L << 1)
926 #define MWM_FUNC_MOVE (1L << 2)
927 #define MWM_FUNC_MINIMIZE (1L << 3)
928 #define MWM_FUNC_MAXIMIZE (1L << 4)
929 #define MWM_FUNC_CLOSE (1L << 5)
930
931 struct MWM_Hints
932 {
933   unsigned long flags;
934   unsigned long functions;
935   unsigned long decorations;
936   long inputMode;
937   unsigned long status;
938 };
939
940 static void WaitForViewableWindow(Window window)
941 {
942    //int attempts = 0;
943    //Logf("Wait for viewable %s\n", window.name);
944    XFlush(xGlobalDisplay);
945    //while(attempts++ < 40)
946    while(true)
947    {
948       XWindowAttributes attributes = { 0 };
949       int result;
950       if(!XGetWindowAttributes(xGlobalDisplay, (X11Window)window.windowHandle, &attributes))
951          break;
952       if(attributes.map_state == IsViewable)
953          break;
954       else
955          Sleep(1.0 / RESOLUTION);
956    }
957 }
958
959 /****************************************************************************
960    /// DRIVER IMPLEMENTATION /////////////
961 ****************************************************************************/
962
963 /*static */class HiResTimer : Thread
964 {
965    bool terminate;
966    uint delay;
967
968    void Stop()
969    {
970       if(started)
971       {
972          terminate = true;
973          Wait();
974       }
975    }
976
977    uint Main()
978    {
979       while(!terminate)
980       {
981          //usleep(delay);
982          // Sleep(delay / 1000000.0);
983          struct timeval tv = { delay / 1000000, delay % 1000000 };
984          select(0,null,null,null, &tv);
985          guiApp.SignalEvent();
986       }
987       return 0;
988    }
989 };
990
991 static HiResTimer hiResTimer { };
992
993 default:
994
995 #include <sys/ipc.h>
996 #include <sys/shm.h>
997 #include <signal.h>
998 #include <locale.h>
999
1000
1001 private:
1002
1003 #ifndef SHM_STAT
1004 #define SHM_STAT  13
1005 #define SHM_INFO  14
1006 #endif
1007
1008 static int terminatePid;
1009
1010 static void SigIntHandler(int value)
1011 {
1012    // printf("SigHandler %d\n", getpid());
1013    if(!terminatePid || terminatePid == getpid())
1014    {
1015       terminateX++;
1016       terminatePid = getpid();
1017       // printf("terminateX now equals %d\n", terminateX);
1018       if(guiApp && guiApp.semaphore)
1019          guiApp.semaphore.Release();
1020    }
1021    /*
1022    struct shmid_ds info;
1023         int maxid = shmctl (0, SHM_INFO, &info);
1024    int pid = getpgrp();
1025    int thisPid = getpid();
1026    //if(thisPid == pid)
1027    /-*
1028    {
1029       if(maxid >= 0)
1030       {
1031          int id;
1032               for(id = 0; id <= maxid; id++)
1033          {
1034                  struct shmid_ds shmseg;
1035             int shmid;
1036                       if((shmid = shmctl(id, SHM_STAT, &shmseg)) >= 0)
1037             {
1038                if(shmseg.shm_cpid == pid || shmseg.shm_cpid == thisPid)
1039                {
1040                   printf("%d (%d) belongs to us (%d)\n", shmid, id, shmseg.shm_cpid);
1041                   shmctl(shmid, IPC_RMID, 0);
1042                }
1043             }
1044          }
1045       }
1046       exit(0);
1047    }
1048    */
1049    /*else if(guiApp.desktop)
1050       guiApp.desktop.Destroy(0);*/
1051 }
1052
1053 class XInterface : Interface
1054 {
1055    class_property(name) = "X";
1056
1057    // --- User Interface System ---
1058    bool Initialize()
1059    {
1060       setlocale(LC_ALL, "en_US.UTF-8");
1061       XInitThreads();
1062       XSupportsLocale();
1063       XSetLocaleModifiers("");
1064       XSetErrorHandler(MyXErrorHandler);
1065       XSetIOErrorHandler(MyXIOErrorHandler);
1066 #ifndef __APPLE__
1067       signal(SIGINT, SigIntHandler);
1068 #endif
1069       xTerminate = false;
1070       xGlobalDisplay = XOpenDisplay(null);
1071       frameExtentSupported = unknown;
1072
1073         joystickFD[0] = open("/dev/js0", O_RDONLY);
1074       joystickFD[1] = open("/dev/js1", O_RDONLY);
1075       joystickFD[2] = open("/dev/js2", O_RDONLY);
1076       joystickFD[3] = open("/dev/js3", O_RDONLY);
1077
1078       systemCursors[iBeam]    = XCreateFontCursor(xGlobalDisplay, XC_xterm);
1079       systemCursors[cross]    = XCreateFontCursor(xGlobalDisplay, XC_tcross);
1080       systemCursors[moving]   = XCreateFontCursor(xGlobalDisplay, XC_fleur);
1081       systemCursors[sizeNESW] = XCreateFontCursor(xGlobalDisplay, XC_bottom_left_corner);
1082       systemCursors[sizeNS]   = XCreateFontCursor(xGlobalDisplay, XC_sb_v_double_arrow);
1083       systemCursors[sizeNWSE] = XCreateFontCursor(xGlobalDisplay, XC_bottom_right_corner);
1084       systemCursors[sizeWE]   = XCreateFontCursor(xGlobalDisplay, XC_sb_h_double_arrow);
1085       systemCursors[hand]     = XCreateFontCursor(xGlobalDisplay, XC_hand2);
1086       systemCursors[arrow]    = XCreateFontCursor(xGlobalDisplay, XC_left_ptr);
1087
1088       if(xGlobalDisplay)
1089       {
1090          XWindowAttributes attributes = { 0 };
1091          XGetWindowAttributes(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), &attributes);
1092          xSystemDepth = attributes.depth;
1093          xSystemVisual = attributes.visual;
1094          switch(xSystemDepth)
1095          {
1096             case 32: case 24: xSystemPixelFormat = pixelFormat888; break;
1097             case 16:
1098             case 15:
1099             {
1100                XVisualInfo vinfo;
1101                XVisualInfo *vinfo_ret;
1102                int numitems = 0;
1103
1104                vinfo.visualid = XVisualIDFromVisual(xSystemVisual);
1105                vinfo_ret = XGetVisualInfo(xGlobalDisplay, VisualIDMask, &vinfo, &numitems);
1106                if(numitems)
1107                {
1108                   xSystemPixelFormat = (vinfo_ret->green_mask == 0x3E0) ? pixelFormat555 : pixelFormat565;
1109                   /*
1110                   if(GetXRenderFormat(xSystemPixelFormat, 0))
1111                   {
1112                      // printf("Got X Render format %d\n", xSystemPixelFormat);
1113                      break;
1114                   }
1115                   else
1116                      printf("No X Format?\n");
1117                   xSystemPixelFormat = (xSystemPixelFormat == pixelFormat555) ? pixelFormat565 : pixelFormat555;
1118                   vinfo = *vinfo_ret;
1119                   // vinfo._class = DirectColor;
1120                   vinfo.visualid = 0;
1121                   vinfo.bits_per_rgb = 5;
1122                   vinfo.depth = xSystemDepth;
1123                   vinfo.green_mask = (xSystemPixelFormat == pixelFormat555) ? 0x3E0 : 0x7E0;
1124                   vinfo.red_mask   = (xSystemPixelFormat == pixelFormat555) ? 0x7C00 : 0xF800;
1125                   XFree((void *) vinfo_ret);
1126                   if(XMatchVisualInfo(xGlobalDisplay, DefaultScreen(xGlobalDisplay), vinfo.depth, vinfo._class, &vinfo))
1127                   //vinfo_ret = XGetVisualInfo(xGlobalDisplay, VisualDepthMask|VisualRedMaskMask|VisualGreenMaskMask|VisualBlueMaskMask, &vinfo, &numitems);
1128                   //if(vinfo_ret)
1129                   {
1130                      //vinfo = *vinfo_ret;
1131                      if(GetXRenderFormat(xSystemPixelFormat, 0))
1132                      {
1133                         // printf("Got X Render format %d (second try)\n", xSystemPixelFormat);
1134                         // printf("red mask: %x, green mask: %x, blue mask: %x\n", vinfo.red_mask,vinfo.green_mask, vinfo.blue_mask);
1135                      }
1136                      xSystemVisual = vinfo.visual;
1137                   }
1138                   else
1139                      printf("Could not get a 555 visual\n");
1140                   */
1141                }
1142                break;
1143             }
1144          }
1145          // printf("Got a depth of %d\n", xSystemDepth);
1146
1147          {
1148             int major, minor, pixmaps;
1149             xSharedMemory = XShmQueryExtension(xGlobalDisplay) && XShmQueryVersion(xGlobalDisplay, &major, &minor, &pixmaps) && pixmaps;
1150          }
1151
1152          // printf("Opening IM\n");
1153          im = XOpenIM(xGlobalDisplay, null, null, null);
1154          // if(im)
1155          {
1156             XColor fore = { 0 }, back = { 0 };
1157             Pixmap pixmap = XCreatePixmap(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), 1, 1, 1);
1158             Pixmap mask = XCreatePixmap(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), 1, 1, 1);
1159             XSetWindowAttributes attributes = { 0 };
1160
1161             XkbSetDetectableAutoRepeat(xGlobalDisplay, True, &autoRepeatDetectable);
1162
1163             XInternAtoms(xGlobalDisplay, (char**)atomNames, AtomIdents::enumSize, False, atoms);
1164
1165             // Check which atoms are supported by the WM
1166             {
1167                int format;
1168                unsigned long count, fill;
1169                Atom type;
1170                Atom * data;
1171
1172                if(XGetWindowProperty(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), atoms[_net_supported],
1173                   0, 10000, False, XA_ATOM, &type, &format, &count, &fill, (void *)&data) == Success)
1174                {
1175                   int i;
1176                   for (i = 0; i < count; i++)
1177                   {
1178                      AtomIdents j;
1179                      for(j = 0; j < AtomIdents::enumSize; j++)
1180                      {
1181                         if(atoms[j] == data[i])
1182                         {
1183                            atomsSupported[j] = true;
1184                            break;
1185                         }
1186                      }
1187                   }
1188                   XFree(data);
1189                }
1190             }
1191
1192             {
1193                Atom protocols[2] = { atoms[wm_delete_window], atoms[wm_take_focus] };
1194
1195                XSetWMProtocols(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), protocols, 2);
1196             }
1197
1198             /*
1199             if(atomsSupported[_net_workarea])
1200                printf("Warning: _NET_WORKAREA extension not supported\n");
1201             */
1202
1203             attributes.override_redirect = True;
1204             if(!windowContext)
1205             {
1206                windowContext = XUniqueContext();
1207             }
1208
1209             nullCursor = XCreatePixmapCursor(xGlobalDisplay, pixmap, mask, &fore, &back, 0, 0);
1210             confineWindow = XCreateWindow(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay),
1211                0,0,1,1,0, CopyFromParent, InputOnly, xSystemVisual /*CopyFromParent*/, CWOverrideRedirect, &attributes);
1212
1213
1214             // IM initialization
1215             {
1216                /*ic = XCreateIC(im, XNInputStyle,
1217                   XIMPreeditNothing | XIMStatusNothing,
1218                   // XIMPreeditNone | XIMStatusNone | XIMPreeditPosition | XIMStatusArea | XIMPreeditArea | XIMStatusArea | XIMPreeditNothing | XIMStatusNothing,
1219                   XNClientWindow, confineWindow, XNFocusWindow, confineWindow, 0);
1220                   */
1221
1222                /*
1223                XIMStyles *IMcando;
1224                XIMStyle  clientCanDo;
1225                XIMStyle  styleWeWillUse = null;
1226                int i;
1227                XVaNestedList arglist;
1228                unsigned long imEventMask;
1229
1230                XGetImValues(im, XNQueryInputStyle, &IMcando, null);
1231                XSetICFocus(ic);
1232                clientCanDo =
1233                   XIMPreeditNone | XIMStatusNone |
1234                   XIMPreeditPosition | XIMStatusArea |
1235                   XIMPreeditArea | XIMStatusArea |
1236                   XIMPreeditNothing | XIMStatusNothing;
1237
1238                for(i=0; i<IMcando->count_styles; i++)
1239                {
1240                    XIMStyle tmpStyle;
1241                    tmpStyle = IMcando->support_styles[i];
1242                    if ( ((tmpStyle & clientCanDo) == tmpStyle) && prefer(tmpStyle, styleWeWillUse) )
1243                      styleWeWillUse = tmpStyle;
1244                }
1245                if(styleWeWillUse = null)
1246                    exit_with_error();
1247                XFree(IMcando);
1248
1249                arglist = XVaCreateNestedList(0, XNFontSet, fontset,
1250                                           XNForeground,
1251                                           WhitePixel(xGlobalDisplay, screen),
1252                                           XNBackground,
1253                                           BlackPixel(xGlobalDisplay, screen),
1254                                           NULL);
1255                ic = XCreateIC(im, XNInputStyle, styleWeWillUse,
1256                              XNClientWindow, window, XNFocusWindow, window,
1257                              XNStatusAttributes, arglist,
1258                              XNPreeditAttributes, arglist, NULL);
1259                XFree(arglist);
1260                if (ic == null)
1261                    exit_with_error();
1262
1263                XGetWindowAttributes(xGlobalDisplay, win, &winAtts);
1264                XGetICValues(ic, XNFilterEvents, &imEventMask, null);
1265                imEventMask |= winAtts.your_event_mask;
1266                XSelectInput(xGlobalDisplay, window, imEventMask);
1267                XSetICFocus(ic);
1268                */
1269             }
1270
1271             xMutex.Wait();
1272             timerThread = Thread { };
1273             incref timerThread;
1274             timerThread.Main = XTimerThread;
1275             timerThread.Create();
1276
1277             return true;
1278          }
1279       }
1280       return false;
1281    }
1282
1283    void Terminate()
1284    {
1285       XEvent e = { 0 };
1286       xTerminate = true;
1287
1288       // WHY WAS THIS COMMENTED HERE?
1289       // Probably because it was causing crashes, the proper fix should now be in DestroyRootWindow
1290       delete lastActive;
1291
1292       xMutex.Release();
1293       xSemaphore.Release();
1294
1295       timerThread.Wait();
1296       delete timerThread;
1297       hiResTimer.Stop();
1298
1299       XFreeCursor(xGlobalDisplay, systemCursors[iBeam]);
1300       XFreeCursor(xGlobalDisplay, systemCursors[cross]);
1301       XFreeCursor(xGlobalDisplay, systemCursors[moving]);
1302       XFreeCursor(xGlobalDisplay, systemCursors[sizeNESW]);
1303       XFreeCursor(xGlobalDisplay, systemCursors[sizeNS]);
1304       XFreeCursor(xGlobalDisplay, systemCursors[sizeNWSE]);
1305       XFreeCursor(xGlobalDisplay, systemCursors[sizeWE]);
1306       XFreeCursor(xGlobalDisplay, systemCursors[hand]);
1307       XFreeCursor(xGlobalDisplay, systemCursors[arrow]);
1308
1309       //XPutBackEvent(xGlobalDisplay, &e);
1310       // xThread.Wait();
1311       // delete xThread;
1312
1313       /*if(windowData && windowData.ic)
1314       {
1315          XDestroyIC(windowData.ic);
1316          windowData.ic = null;
1317       }*/
1318       if(im)
1319       {
1320          XCloseIM(im);
1321          im = null;
1322       }
1323       XCloseDisplay(xGlobalDisplay);
1324       xGlobalDisplay = null;
1325
1326       if(joystickFD[0] != -1) close(joystickFD[0]);
1327       if(joystickFD[1] != -1) close(joystickFD[1]);
1328       if(joystickFD[2] != -1) close(joystickFD[2]);
1329       if(joystickFD[3] != -1) close(joystickFD[3]);
1330    }
1331
1332    #define DBLCLICK_DELAY  300   // 0.3 second
1333    #define DBLCLICK_DELTA  1
1334
1335    bool ProcessInput(bool processAll)
1336    {
1337       bool eventAvailable = false;
1338       XEvent e;
1339
1340       if(!fullScreenMode) RepositionDesktop(true);
1341       //xMutex.Wait();
1342 //*      XLockDisplay(xGlobalDisplay);
1343       while(!xTerminate && (/*gotAnXEvent || */XCheckIfEvent(xGlobalDisplay, &e, EventChecker, null)))
1344       {
1345          Window window = null;
1346          XAnyEvent * thisEvent = (XAnyEvent *)&e;
1347          // printf("Got an event: %d\n", thisEvent->type);
1348
1349          //if(gotAnXEvent) { thisEvent = (XAnyEvent *)&xEvent; gotAnXEvent = false; }
1350
1351          if(im && XFilterEvent((union _XEvent *)thisEvent, None))
1352             continue;
1353          eventAvailable = true;
1354          XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1355          if(window)
1356          {
1357             XWindowData windowData = window.windowData;
1358             static uint lastKeyCode = 0;
1359             switch(thisEvent->type)
1360             {
1361                case KeyPress:
1362                {
1363                   XKeyEvent * event = (XKeyEvent *) thisEvent;
1364                   //*XUnlockDisplay(xGlobalDisplay);
1365                   ProcessKeyMessage(window, event->keycode, (event->keycode == lastKeyCode) ? 2 : 0, event);
1366                   //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1367                   lastKeyCode = event->keycode;
1368                   break;
1369                }
1370                case KeyRelease:
1371                {
1372                   XKeyEvent * event = (XKeyEvent *) thisEvent;
1373                   XEvent nextEvent;
1374                   lastKeyCode = 0;
1375                   if(!autoRepeatDetectable && XCheckIfEvent(xGlobalDisplay, (XEvent *)&nextEvent, EventChecker, (void *)KeyPress))
1376                   {
1377                      if(im && XFilterEvent(&nextEvent, None))
1378                         break;
1379
1380                      if(((XKeyEvent *)&nextEvent)->keycode == event->keycode)
1381                      {
1382                         //*XUnlockDisplay(xGlobalDisplay);
1383                         ProcessKeyMessage(window, event->keycode, 2, event);
1384                      }
1385                      else
1386                      {
1387                         //*XUnlockDisplay(xGlobalDisplay);
1388                         // printf("Keycode not the same :(\n");
1389                         ProcessKeyMessage(window, event->keycode, 1, event);
1390                         ProcessKeyMessage(window, ((XKeyEvent *)&nextEvent)->keycode, 0, (XKeyEvent *)&nextEvent);
1391                      }
1392                   }
1393                   else
1394                   {
1395                      //*XUnlockDisplay(xGlobalDisplay);
1396                      // printf("No KeyPress ahead\n");
1397                      ProcessKeyMessage(window, event->keycode, 1, event);
1398                   }
1399                   //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1400                   break;
1401                }
1402                case ButtonPress:
1403                {
1404                   XButtonEvent * event = (XButtonEvent *) thisEvent;
1405
1406                   static double lastTime[3];
1407                   static Window lastWindow[3];
1408                   static Point lastPos[3];
1409
1410                   Modifiers keyFlags = 0;
1411                   bool doubleClick;
1412                   uint button, buttonDouble, whichButton;
1413                   uint buttonMask;
1414                   int x = event->x_root, y = event->y_root;
1415
1416                   if(event->button == Button1)
1417                   {
1418                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonDown;
1419                      buttonDouble = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftDoubleClick;
1420                      whichButton = 0;
1421                      buttonMask = Button1Mask;
1422                      keyFlags.left = true;
1423                   }
1424                   else if(event->button == Button3)
1425                   {
1426                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonDown;
1427                      buttonDouble = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightDoubleClick;
1428                      whichButton = 2;
1429                      buttonMask = Button3Mask;
1430                      keyFlags.right = true;
1431                   }
1432                   else
1433                   {
1434                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonDown;
1435                      buttonDouble = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleDoubleClick;
1436                      whichButton = 1;
1437                      buttonMask = Button2Mask;
1438                      keyFlags.middle = true;
1439                   }
1440                   if(event->state & buttonMask)
1441                      break;
1442
1443                   doubleClick = event->time - lastTime[whichButton] < DBLCLICK_DELAY &&
1444                      window == lastWindow[whichButton] &&
1445                      Abs(event->x_root - lastPos[whichButton].x) < DBLCLICK_DELTA &&
1446                      Abs(event->y_root - lastPos[whichButton].y) < DBLCLICK_DELTA;
1447                   lastTime[whichButton] = doubleClick ? 0 : event->time;
1448                   lastWindow[whichButton] = window;
1449                   lastPos[whichButton].x = event->x_root;
1450                   lastPos[whichButton].y = event->y_root;
1451
1452                   if(event->state & ShiftMask)     keyFlags.shift = true;
1453                   if(event->state & ControlMask)   keyFlags.ctrl = true;
1454                   if(event->state & Mod1Mask)      keyFlags.alt = true;
1455                   if(event->state & Button1Mask)   keyFlags.left = true;
1456                   if(event->state & Button2Mask)   keyFlags.middle = true;
1457                   if(event->state & Button3Mask)   keyFlags.right = true;
1458                   //*XUnlockDisplay(xGlobalDisplay);
1459
1460                   incref window;
1461                   if(event->button == Button4 || event->button == Button5)
1462                   {
1463                      window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit, (event->button == Button4) ? wheelUp : wheelDown, 0);
1464                   }
1465                   else
1466                   {
1467                      if(doubleClick)
1468                      {
1469                         if(!window.MouseMessage(buttonDouble, x, y, &keyFlags, false, true))
1470                         {
1471                            //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1472                            delete window;
1473                            break;
1474                         }
1475                      }
1476                      window.MouseMessage(button, x, y, &keyFlags, false, /*doubleClick? false : */true);
1477                   }
1478                   //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1479                   delete window;
1480                   break;
1481                }
1482                case ButtonRelease:
1483                {
1484                   Modifiers keyFlags = 0;
1485                   XButtonEvent * event = (XButtonEvent *) thisEvent;
1486                   uint button;
1487                   uint buttonMask;
1488                   int x = event->x_root, y = event->y_root;
1489                   if(event->button == Button1)
1490                   {
1491                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonUp;
1492                      buttonMask = Button1Mask;
1493                   }
1494                   else if(event->button == Button3)
1495                   {
1496                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonUp;
1497                      buttonMask = Button3Mask;
1498                   }
1499                   else
1500                   {
1501                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonUp;
1502                      buttonMask = Button2Mask;
1503                   }
1504                   if(!(event->state & buttonMask)) break;
1505                   if(event->state & ShiftMask)     keyFlags.shift = true;
1506                   if(event->state & ControlMask)   keyFlags.ctrl = true;
1507                   if(event->state & Mod1Mask)      keyFlags.alt = true;
1508                   if(event->state & Button1Mask)   keyFlags.left = true;
1509                   if(event->state & Button2Mask)   keyFlags.middle = true;
1510                   if(event->state & Button3Mask)   keyFlags.right = true;
1511                   if(guiApp.windowCaptured && guiApp.windowCaptured != window)
1512                   {
1513                      // X hasn't noticed the capture yet, so fix it!
1514                      x += window.absPosition.x;
1515                      y += window.absPosition.y;
1516                      window = guiApp.windowCaptured.rootWindow;
1517                      x -= window.absPosition.x;
1518                      y -= window.absPosition.y;
1519                   }
1520                   //*XUnlockDisplay(xGlobalDisplay);
1521                   incref window;
1522                   window.MouseMessage(button, x, y, &keyFlags, false, false);
1523                   delete window;
1524                   //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1525                   break;
1526                }
1527                case MotionNotify:
1528                {
1529                   static uint lastTime = 0;
1530                   XMotionEvent * event = (XMotionEvent *) thisEvent;
1531                   while(XCheckIfEvent(xGlobalDisplay, (XEvent *)thisEvent, EventChecker, (void *)MotionNotify));
1532                   // if(event->time - lastTime > 15)
1533                   {
1534                      Modifiers keyFlags = 0;
1535                      // int x = event->x_root, y = event->y_root;
1536
1537                      if(event->state & ShiftMask)     keyFlags.shift = true;
1538                      if(event->state & ControlMask)   keyFlags.ctrl = true;
1539                      if(event->state & Mod1Mask)      keyFlags.alt = true;
1540                      if(event->state & Button1Mask)   keyFlags.left = true;
1541                      if(event->state & Button2Mask)   keyFlags.middle = true;
1542                      if(event->state & Button3Mask)   keyFlags.right = true;
1543                      //*XUnlockDisplay(xGlobalDisplay);
1544                      incref window;
1545                      window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMouseMove,
1546                         event->x_root, event->y_root, &keyFlags, false, false);
1547                      delete window;
1548                      //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1549                      lastTime = (uint)event->time;
1550                   }
1551                   break;
1552                }
1553                case Expose:
1554                {
1555                   XExposeEvent * event = (XExposeEvent *) thisEvent;
1556                   Box box;
1557                   box.left = event->x - window.clientStart.x;
1558                   box.top = event->y - window.clientStart.y;
1559                   box.right = box.left + event->width - 1;
1560                   box.bottom = box.top + event->height - 1;
1561                   window.Update(box);
1562                   box.left   += window.clientStart.x;
1563                   box.top    += window.clientStart.y;
1564                   box.right  += window.clientStart.x;
1565                   box.bottom += window.clientStart.y;
1566                   window.UpdateDirty(box);
1567                   break;
1568                }
1569                case SelectionRequest:
1570                {
1571                     XSelectionRequestEvent *req = (XSelectionRequestEvent *) thisEvent;
1572                     XEvent respond;
1573                          if(req->target == atoms[targets] && clipBoardData)
1574                   {
1575                      Atom * supportedTargets = new Atom[4];
1576                      supportedTargets[0] = atoms[targets];
1577                      supportedTargets[1] = atoms[multiple];
1578                      supportedTargets[2] = XA_STRING;
1579                      supportedTargets[3] = atoms[utf8_string];
1580                      XChangeProperty(xGlobalDisplay,req->requestor, req->_property,
1581                                          XA_ATOM,32,PropModeReplace, (byte *) supportedTargets, 4*sizeof(Atom));
1582                      respond.xselection._property = req->_property;
1583                      delete supportedTargets;
1584                   }
1585                   else if((req->target == XA_STRING || req->target == atoms[utf8_string]) && clipBoardData)
1586                          {
1587                      Atom _property = (req->_property == None) ? req->target : req->_property;
1588                                  XChangeProperty(xGlobalDisplay,req->requestor, _property,
1589                                          req->target/*req->_property*/,8,PropModeReplace, (byte *) clipBoardData, strlen(clipBoardData));
1590                                  respond.xselection._property = _property;
1591                          }
1592                   else
1593                                  respond.xselection._property = None;
1594
1595                   respond.xselection.type = SelectionNotify;
1596                          respond.xselection.display = req->display;
1597                          respond.xselection.requestor = req->requestor;
1598                          respond.xselection.selection =req->selection;
1599                          respond.xselection.target = req->target;
1600                          respond.xselection.time = CurrentTime;
1601                          XSendEvent(xGlobalDisplay, req->requestor,0,0,&respond);
1602                   break;
1603                }
1604                case SelectionClear:
1605                {
1606                   delete clipBoardData;
1607                   break;
1608                }
1609                case FocusIn:
1610                {
1611                   if(activeWindow != (X11Window)window.windowHandle)
1612                   {
1613                      XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1614                      Window modalRoot = window.FindModal();
1615                      XWindowData windowData;
1616
1617                      activeWindow = (X11Window)window.windowHandle;
1618
1619                      if(window.parent && window == window.parent.activeChild) break;
1620                      incref window;
1621                      //if(window.creationActivation == activate)
1622                      {
1623                         if(modalRoot)
1624                            modalRoot.ExternalActivate(true, true, window, null); // lastActive);
1625                         else
1626                            window.ExternalActivate(true, true, window, null); // lastActive);
1627                      }
1628                      windowData = modalRoot ? modalRoot.windowData : window.windowData;
1629                      if(windowData && windowData.ic)
1630                      {
1631                         // XSetICValues(ic, XNClientWindow, window.windowHandle, XNFocusWindow, window.windowHandle, 0);
1632                         XSetICFocus(windowData.ic);
1633                      }
1634                      //delete lastActive;
1635                      //lastActive = window;
1636                      //incref lastActive;
1637                      delete window;
1638                   }
1639                   break;
1640                }
1641                case FocusOut:
1642                {
1643 #ifdef _DEBUG
1644                   //printf("Processing a FocusOut Event for %s (%x)\n", window._class.name, window);
1645 #endif
1646
1647                   if(XCheckTypedWindowEvent(xGlobalDisplay, thisEvent->window, FocusIn, (XEvent *)thisEvent))
1648                   {
1649                      break;
1650                   }
1651                   if(thisEvent->window == activeWindow)
1652                      activeWindow = (X11Window)null;
1653 #if 0
1654                   if(XCheckTypedEvent(xGlobalDisplay, FocusIn, (XEvent *)thisEvent))
1655                   {
1656                      if(XCheckTypedWindowEvent(xGlobalDisplay, thisEvent->window, FocusOut, (XEvent *)thisEvent))
1657                      {
1658                         XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1659
1660                         XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1661                         if(window)
1662                         {
1663                            Window windowCopy = window;
1664                            XWindowData windowData;
1665                            if(windowCopy == windowCopy.parent.activeChild) break;
1666                            incref windowCopy;
1667                            windowCopy.ExternalActivate(true, true,  windowCopy, lastActive);
1668
1669                            windowData = windowCopy.windowData;
1670                            if(windowData && windowData.ic)
1671                               XSetICFocus(windowData.ic);
1672
1673                            delete lastActive;
1674                            lastActive = windowCopy;
1675                            incref lastActive;
1676                            delete windowCopy;
1677                         }
1678
1679                         // XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1680                         if(window)
1681                         {
1682                            if(window != window.parent.activeChild) break;
1683                            incref window;
1684                            window.ExternalActivate(false, true,  window, lastActive);
1685                            delete window;
1686                         }
1687                      }
1688                      else
1689                      {
1690                         XWindowData windowData;
1691                         XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1692
1693                         if(window)
1694                         {
1695                            XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1696                            Window modalRoot = window.FindModal();
1697
1698                            incref window;
1699                            if(modalRoot)
1700                            {
1701                               modalRoot.ExternalActivate(true, true, window, lastActive);
1702                            }
1703                            else
1704                            {
1705                               window.ExternalActivate(true, true, window, lastActive);
1706                            }
1707                            windowData = modalRoot ? modalRoot.windowData : window.windowData;
1708                            if(windowData && windowData.ic)
1709                               XSetICFocus(windowData.ic);
1710
1711                            delete lastActive;
1712                            lastActive = window;
1713                            incref lastActive;
1714                            delete window;
1715                         }
1716                      }
1717                   }
1718                   else
1719 #endif
1720                   {
1721                      XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1722                      if(window != window.parent.activeChild && window != guiApp.interimWindow) break;
1723                      incref window;
1724
1725 #ifdef _DEBUG
1726                      //printf("Deactivating %s\n", window._class.name);
1727 #endif
1728
1729                      if(!window.ExternalActivate(false, true, window, null /*lastActive*/))
1730                      {
1731                         XCheckTypedEvent(xGlobalDisplay, /*thisEvent->window, */ButtonPress, (XEvent *)thisEvent);
1732                      }
1733
1734                      //delete lastActive;
1735                      /*
1736                      lastActive = window;
1737                      incref lastActive;
1738                      */
1739                      delete window;
1740                   }
1741                   break;
1742                }
1743                case ConfigureNotify:
1744                {
1745                   XConfigureEvent * event = (XConfigureEvent *) thisEvent;
1746                   while(XCheckIfEvent(xGlobalDisplay, (XEvent *)thisEvent, (void *)ConfigureNotifyChecker, (void *)window.windowHandle));
1747                   //if(event->x - desktopX != window.position.x || event->y - desktopY != window.position.y || event->width != window.size.w || event->height != window.size.h)
1748
1749                   // TODO: Support _NET_REQUEST_FRAME_EXTENTS message / _NET_FRAME_EXTENTS property for decoration size awareness
1750                   if(window.nativeDecorations)
1751                   {
1752                      int format;
1753                      unsigned long len, fill;
1754                      Atom type;
1755                      char * data = null;
1756                      if(XGetWindowProperty(xGlobalDisplay, (X11Window)window.systemHandle, atoms[_net_wm_state], 0, 32, False,
1757                             XA_ATOM, &type, &format, &len, &fill, &data) == Success)
1758                      {
1759                         bool maxVert = false, maxHorz = false, isMinimized = false;
1760                         Atom * hints = (Atom *)data;
1761                         int c;
1762                         for(c = 0; c < len && hints[c]; c++)
1763                         {
1764                            if(hints[c] == atoms[_net_wm_state_maximized_vert])
1765                               maxVert = true;
1766                            else if(hints[c] == atoms[_net_wm_state_maximized_horz])
1767                               maxHorz = true;
1768                            else if(hints[c] == atoms[_net_wm_state_hidden])
1769                               isMinimized = true;
1770                         }
1771                         XFree(data);
1772
1773                         if(maxVert && maxHorz)
1774                         {
1775                            if(window.state != maximized)
1776                               *&window.state = maximized;
1777                         }
1778                         else if(isMinimized)
1779                         {
1780                            if(window.state != minimized)
1781                               *&window.state = minimized;
1782                         }
1783                         else if(window.state != normal)
1784                            *&window.state = normal;
1785                      }
1786                   }
1787                   {
1788                      int x = event->x;
1789                      int y = event->y;
1790                      int w = event->width, h = event->height;
1791
1792                      //if(event->send_event)
1793                      {
1794                         X11Window rootChild;
1795                         int rootX, rootY;
1796                         XTranslateCoordinates(xGlobalDisplay, event->window,
1797                            RootWindow(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 0, 0,
1798                            &rootX, &rootY, &rootChild);
1799                         x = rootX;
1800                         y = rootY;
1801                      }
1802
1803                      x -= desktopX;
1804                      y -= desktopY;
1805
1806                      if(window.nativeDecorations && window.state != maximized)
1807                      {
1808                         x -= windowData.decor.left;
1809                         y -= windowData.decor.top;
1810                         w += windowData.decor.left + windowData.decor.right;
1811                         h += windowData.decor.top + windowData.decor.bottom;
1812                         /*
1813                         x -= window.clientStart.x;
1814                         y -= window.clientStart.y - (window.hasMenuBar ? skinMenuHeight : 0);
1815                         w += window.size.w - window.clientSize.w;
1816                         h += window.size.h - window.clientSize.h;
1817                         */
1818                      }
1819                      window.Position(x, y, w, h, true, true, true, true, false, false);
1820                   }
1821                   break;
1822                }
1823                case ClientMessage:
1824                {
1825                   XClientMessageEvent * event = (XClientMessageEvent *) thisEvent;
1826
1827                   if(event->data.l[0] == atoms[wm_delete_window])
1828                   {
1829                      window.Destroy(0);
1830                   }
1831
1832                   if(event->data.l[0] == atoms[wm_take_focus])
1833                   {
1834                      Window modalRoot;
1835                      XWindowData windowData;
1836                      bool laterFocus;
1837                      activeWindow = (X11Window)window.windowHandle;
1838
1839                      timeStamp = (int)event->data.l[1];
1840
1841                      windowData = window.windowData;
1842                      laterFocus = windowData.laterFocus;
1843                      windowData.laterFocus = true;
1844
1845 #ifdef _DEBUG
1846                      //printf("Processing a ClientMessage WM_TAKE_FOCUS Event for %s (%x)\n", window._class.name, window);
1847 #endif
1848                      if(guiApp.interimWindow && guiApp.interimWindow.created && window != guiApp.interimWindow) break; //window == window.parent.activeChild) break;
1849                      // if(window == window.parent.activeChild) break;
1850                      incref window;
1851
1852                      {
1853                         XEvent checkEvent;
1854                         //XFlush(xGlobalDisplay);
1855                         while(XCheckTypedEvent(xGlobalDisplay, FocusOut, &checkEvent))
1856                         {
1857                            XFocusChangeEvent *event = (XFocusChangeEvent *) &checkEvent;
1858                            Window window;
1859                            XFindContext(xGlobalDisplay, event->window, windowContext, (XPointer *) &window);
1860                            if(window != window.parent.activeChild) break;
1861                            incref window;
1862
1863       #ifdef _DEBUG
1864                            //printf("Found a FocusOut ahead, deactivating %s (%d)\n", window._class.name, window);
1865       #endif
1866
1867                            if(!window.ExternalActivate(false, true, window, null /*lastActive*/))
1868                            {
1869                               XCheckTypedEvent(xGlobalDisplay, /*thisEvent->window, */ButtonPress, (XEvent *)thisEvent);
1870                            }
1871                            delete lastActive;
1872                            delete window;
1873                         }
1874                      }
1875
1876                      modalRoot = window.FindModal();
1877                      windowData = modalRoot ? modalRoot.windowData : window.windowData;
1878                      if(windowData)
1879                      {
1880                         if(laterFocus || (modalRoot ? modalRoot : window).creationActivation == activate)
1881                         {
1882                            if(modalRoot)
1883                            {
1884                               XRaiseWindow(xGlobalDisplay, (X11Window)modalRoot.windowHandle);
1885                               WaitForViewableWindow(modalRoot);
1886                               if(atomsSupported[_net_active_window])
1887                               {
1888                                  XClientMessageEvent event = { 0 };
1889                                  event.type = ClientMessage;
1890                                  event.message_type = atoms[_net_active_window];
1891                                  event.display = xGlobalDisplay;
1892                                  event.serial = 0;
1893                                  event.window = (X11Window)modalRoot.windowHandle;
1894                                  event.send_event = 1;
1895                                  event.format = 32;
1896                                  event.data.l[0] = 0;
1897                                  /*
1898                                  event.data.l[0] = 1;
1899                                  event.data.l[1] = atoms[_net_wm_user_time];
1900                                  event.data.l[2] = activeWindow; //guiApp.desktop.activeChild.windowHandle;
1901                                  */
1902 #ifdef _DEBUG
1903                                  //printf("(ClientMessage - %s) Setting _NET_ACTIVE_WINDOW for %s (%x)\n", window._class.name, modalRoot._class.name, modalRoot);
1904 #endif
1905
1906                                  XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
1907                                  XSetInputFocus(xGlobalDisplay, (X11Window)modalRoot.windowHandle, RevertToPointerRoot, (uint)timeStamp);
1908
1909                                  //XFlush(xGlobalDisplay);
1910                                  //printf("Done.\n");
1911                               }
1912                            }
1913                            else
1914                            {
1915                               XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToPointerRoot, (uint)timeStamp);
1916                               window.ExternalActivate(true, true, window, null); // lastActive);
1917                               if(windowData && windowData.ic)
1918                               {
1919                                  // XSetICValues(ic, XNClientWindow, window.windowHandle, XNFocusWindow, window.windowHandle, 0);
1920                                  //XSetICFocus(windowData.ic);
1921                               }
1922                            }
1923                         }
1924                         windowData.laterFocus = true;
1925                         delete lastActive;
1926                         lastActive = window;
1927                         incref lastActive;
1928                      }
1929                      delete window;
1930                   }
1931                   break;
1932                }
1933                case PropertyNotify:
1934                {
1935                   XWindowData windowData = window.windowData;
1936                   XPropertyEvent * event = (XPropertyEvent *) thisEvent;
1937                   if(event->atom == atoms[_net_frame_extents] &&
1938                     event->state == PropertyNewValue && windowData)
1939                   {
1940                      int format;
1941                      unsigned long len, fill;
1942                      Atom type;
1943                      char * data = null;
1944
1945                      if(XGetWindowProperty(xGlobalDisplay, (X11Window)window.windowHandle,
1946                         atoms[_net_frame_extents], 0, 4,
1947                          False, XA_CARDINAL, &type, &format, &len,
1948                          &fill, &data) == Success && data)
1949                      {
1950                         long *extents = (long *)data;
1951                         bool change = extents[0] != windowData.decor.left ||
1952                                       extents[1] != windowData.decor.right ||
1953                                       extents[2] != windowData.decor.top ||
1954                                       extents[3] != windowData.decor.bottom;
1955
1956                         bool hadFrameExtents = windowData.gotFrameExtents;
1957                         Box oldDecor = windowData.decor;
1958
1959                         frameExtentSupported = working;
1960                         frameExtentWindow = 0;
1961                         frameExtentRequest = 0;
1962
1963                         if(!hadFrameExtents || extents[0] || extents[1] || extents[2] || extents[3])
1964                         {
1965                            windowData.decor =
1966                            {
1967                               left = (int)extents[0], right  = (int)extents[1],
1968                               top  = (int)extents[2], bottom = (int)extents[3]
1969                            };
1970                            windowData.gotFrameExtents = true;
1971                            if(change && ((Window)window).clientSize.w > 0)
1972                            {
1973                               int x = window.position.x, y = window.position.y, w = window.size.w, h = window.size.h;
1974                               if(!hadFrameExtents && window.state != maximized)
1975                               {
1976                                  window.ComputeAnchors(
1977                                     window.normalAnchor,
1978                                     window.normalSizeAnchor,
1979                                     &x, &y, &w, &h);
1980                               }
1981                               else
1982                               {
1983                                  x += windowData.decor.left - oldDecor.left;
1984                                  y += windowData.decor.top - oldDecor.top;
1985
1986                                  w += windowData.decor.left - oldDecor.left + windowData.decor.right - oldDecor.right;
1987                                  h += windowData.decor.top - oldDecor.top   + windowData.decor.bottom - oldDecor.bottom;
1988                               }
1989
1990                               if(window.state != maximized)
1991                               {
1992                                  window.Position(x, y, w, h, true, true, true, true, false, !hadFrameExtents && window.state != maximized);
1993                                  UpdateRootWindow(window);
1994                               }
1995                            }
1996                         }
1997                         XFree(data);
1998                      }
1999                      else
2000                         windowData.gotFrameExtents = true; // Unsupported?
2001                   }
2002                   break;
2003                }
2004             }
2005             if(!processAll) break;
2006          }
2007       }
2008       //*if(xGlobalDisplay) XUnlockDisplay(xGlobalDisplay);
2009       //xMutex.Release();
2010       if(!eventAvailable)
2011          return false;
2012       return true;
2013    }
2014
2015    void Wait()
2016    {
2017       gotAnXEvent = false;
2018       xMutex.Release();
2019       xSemaphore.Release();
2020       guiApp.WaitEvent();
2021       xMutex.Wait();
2022    }
2023
2024    void Lock(Window window)
2025    {
2026       //*XLockDisplay(xGlobalDisplay);
2027    }
2028
2029    void Unlock(Window window)
2030    {
2031       //*XUnlockDisplay(xGlobalDisplay);
2032    }
2033
2034    char ** GraphicsDrivers(int * numDrivers)
2035    {
2036       static char *graphicsDrivers[] = { "X", "OpenGL" };
2037       *numDrivers = sizeof(graphicsDrivers) / sizeof(char *);
2038       return (char **)graphicsDrivers;
2039    }
2040
2041    void GetCurrentMode(bool * fullScreen, int * resolution, int * colorDepth, int * refreshRate)
2042    {
2043       *fullScreen = fullScreenMode;
2044    }
2045
2046    void EnsureFullScreen(bool *fullScreen)
2047    {
2048
2049    }
2050
2051    bool ScreenMode(bool fullScreen, int resolution, int colorDepth, int refreshRate, bool * textMode)
2052    {
2053       bool result = true;
2054
2055       fullScreenMode = fullScreen;
2056
2057       if(fullScreen)
2058       {
2059
2060       }
2061       else
2062       {
2063          static bool firstTime = true;
2064          firstTime = false;
2065          desktopX = desktopY = desktopW = desktopH = 0;
2066
2067          RepositionDesktop(false);
2068       }
2069       return result;
2070    }
2071
2072    // --- Window Creation ---
2073    void * CreateRootWindow(Window window)
2074    {
2075       X11Window windowHandle;
2076       XSetWindowAttributes attributes = { 0 };
2077       XVisualInfo * visualInfo = null;
2078       int depth;
2079       Visual * visual;
2080       XIC ic = null;
2081       unsigned long mask = EVENT_MASK;
2082
2083       // Old WM (e.g. TWM), use built-in decorations
2084       if(!atomsSupported[_net_wm_state])
2085          window.nativeDecorations = false;
2086       attributes.override_redirect = (window.interim || (!atomsSupported[_net_wm_state] && !window.nativeDecorations)) ? True : False;
2087       attributes.event_mask = EVENT_MASK;
2088       //printf("%s\n", guiApp.defaultDisplayDriver);
2089 #if !defined(ECERE_VANILLA) && !defined(ECERE_NO3D) && !defined(ECERE_NOGL)
2090       if(window.dispDriver == class(OpenGLDisplayDriver) || !strcmp(guiApp.defaultDisplayDriver, "OpenGL"))
2091       {
2092          int samples;
2093          bool alpha = true;
2094          for(samples = 4;; samples /= 2)
2095          {
2096             bool found = false;
2097             int attrib[30] =
2098             {
2099                GLX_RENDER_TYPE, GLX_RGBA_BIT,
2100                GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
2101                GLX_DOUBLEBUFFER, True,
2102                GLX_DEPTH_SIZE, 1,
2103                GLX_RED_SIZE, 1,
2104                GLX_GREEN_SIZE, 1,
2105                GLX_BLUE_SIZE, 1
2106             };
2107             int numAttribs = 14;
2108
2109             GLXFBConfig *fbconfigs = null, fbconfig;
2110             int numfbconfigs;
2111             int i;
2112             //printf("Samples = %d, alpha = %d\n", samples, alpha);
2113             if(alpha)
2114             {
2115                attrib[numAttribs++] = GLX_ALPHA_SIZE;
2116                attrib[numAttribs++] = 1;
2117             }
2118             if(samples)
2119             {
2120                attrib[numAttribs++] = GLX_SAMPLE_BUFFERS_ARB;
2121                attrib[numAttribs++] = GL_TRUE;
2122                attrib[numAttribs++] = GLX_SAMPLES_ARB;
2123                attrib[numAttribs++] = samples;
2124             }
2125             attrib[numAttribs] = None;
2126
2127             // visualInfo = glXChooseVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib);
2128
2129             //printf("Trying %d samples...\n", samples);
2130             fbconfigs = glXChooseFBConfig(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib, &numfbconfigs);
2131             if(fbconfigs)
2132             {
2133                for (i = 0; i < numfbconfigs; i++)
2134                {
2135                   XRenderPictFormat * format;
2136                   visualInfo = glXGetVisualFromFBConfig(xGlobalDisplay, fbconfigs[i]);
2137                   if (!visualInfo) continue;
2138                   if(window.alphaBlend)
2139                   {
2140                      format = XRenderFindVisualFormat(xGlobalDisplay, visualInfo->visual);
2141                      if (!format) { XFree(visualInfo); continue; }
2142                      if(format->direct.alphaMask > 0)
2143                      {
2144                         //printf("Found what we're looking for (alphaBlend)\n");
2145                         fbconfig = fbconfigs[i];
2146                         found = true;
2147                         break;
2148                      }
2149                   }
2150                   else
2151                   {
2152                      //printf("Found what we're looking for\n");
2153                      found = true;
2154                      break;
2155                   }
2156                }
2157                if (i == numfbconfigs)
2158                {
2159                   fbconfig = fbconfigs[0];
2160                   visualInfo = glXGetVisualFromFBConfig(xGlobalDisplay, fbconfig);
2161                }
2162             }
2163             if(fbconfigs)
2164                XFree(fbconfigs);
2165             if(found || (!samples && !alpha))
2166             {
2167                //printf("Stopping now\n");
2168                break;
2169             }
2170             else
2171                XFree(visualInfo);
2172             if(samples == 1) samples = 0;
2173             else if(!samples) alpha = false;
2174          }
2175       }
2176       if(!visualInfo)
2177       {
2178          int attrList[] =
2179          {
2180             GLX_USE_GL, GLX_DEPTH_SIZE, 1,
2181             GLX_RGBA,
2182             GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
2183             GLX_DOUBLEBUFFER,
2184             None
2185          };
2186          visualInfo = glXChooseVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrList);
2187       }
2188 #endif
2189       depth = visualInfo ? visualInfo->depth : (window.alphaBlend ? 32 : xSystemDepth);
2190       visual = visualInfo ? visualInfo->visual : (window.alphaBlend ? FindFullColorVisual (xGlobalDisplay, &depth) : xSystemVisual);
2191       // printf("visual: %d, depth: %d\n", visual, depth);
2192
2193       if(visual)
2194       {
2195          attributes.colormap = XCreateColormap(xGlobalDisplay, XRootWindow(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), visual, AllocNone);
2196          attributes.border_pixel = 0;
2197       }
2198       else
2199          return null;
2200
2201       if(fullScreenMode)
2202       {
2203          windowHandle = XCreateWindow(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay),
2204             0,0,guiApp.desktop.size.w,guiApp.desktop.size.h,0, depth, InputOutput, visual ? visual : CopyFromParent,
2205             CWEventMask | (visual ? (CWColormap | CWBorderPixel) : 0)/*| CWOverrideRedirect*/, &attributes);
2206       }
2207       /*
2208          Unsupported for now...
2209       else if(window.systemParent)
2210       {
2211
2212       }
2213       */
2214       else
2215       {
2216          if(window.windowHandle)
2217             windowHandle = (X11Window)window.windowHandle;
2218          else
2219          {
2220             X11Window parentWindow = (X11Window)null;
2221             int x = window.position.x, y = window.position.y;
2222             int w = window.state == normal ? Max(1, window.size.w) : Max(1, window.normalSizeAnchor.size.w);
2223             int h = window.state == normal ? Max(1, window.size.h) : Max(1, window.normalSizeAnchor.size.h);
2224
2225             if(window.master.rootWindow && window.master.rootWindow != guiApp.desktop && (window._isModal || window.style.interim))
2226             {
2227                Window master = window.master;
2228                Window rootWindow = master.rootWindow;
2229
2230                parentWindow = rootWindow.is3D ? (X11Window)rootWindow.parent.windowHandle : (X11Window)rootWindow.windowHandle;
2231
2232                // parentWindow = window.master.rootWindow.is3D ? window.master.rootWindow.parent.windowHandle : window.master.rootWindow.windowHandle;
2233             }
2234             if(window.style.showInTaskBar)
2235                parentWindow = (X11Window)null;
2236
2237             windowHandle = XCreateWindow(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay),
2238                x, y, w, h,
2239                0, depth, InputOutput, visual ? visual : CopyFromParent,
2240                CWEventMask | CWOverrideRedirect | (visual ? (CWColormap | CWBorderPixel) : 0), &attributes);
2241
2242             if(parentWindow && (window.interim || window.isModal))
2243             {
2244                //printf("Setting WM_TRANSIENT_FOR of %s to %s\n", window._class.name, window.master.rootWindow._class.name);
2245                XSetTransientForHint(xGlobalDisplay, windowHandle, parentWindow);
2246                //XFlush(xGlobalDisplay);
2247                //printf("Done.\n");
2248                //XChangeProperty(xGlobalDisplay, windowHandle, atoms[wm_transient_for], XA_WINDOW, 32, PropModeReplace, (unsigned char*)&parentWindow, 1);
2249                if(window.isModal)
2250                {
2251                   Atom hints[1] = { atoms[_net_wm_state_modal] };
2252                   XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_state], XA_ATOM, 32, PropModeReplace, (unsigned char*)&hints, 1);
2253                }
2254             }
2255
2256             {
2257                Atom hints[2] =
2258                {
2259                   parentWindow ? atoms[_net_wm_window_type_menu] : atoms[_net_wm_window_type_normal],
2260                   parentWindow ? atoms[_net_wm_window_type_popup_menu] : 0
2261                };
2262 #if defined(__APPLE__) || defined(__FreeBSD__)
2263                // Don't set this on non-interim windows for OS X...
2264                if(parentWindow && window.interim)
2265 #endif
2266
2267                   XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_window_type], XA_ATOM, 32,
2268                      PropModeReplace, (unsigned char*)&hints, parentWindow ? 2 : 1);
2269                {
2270                   XWMHints xwmHints;
2271                   xwmHints.flags = InputHint;
2272                   xwmHints.input = 0;
2273                   XSetWMHints(xGlobalDisplay, windowHandle, &xwmHints);
2274                }
2275                {
2276                   Atom protocols[2] = { atoms[wm_delete_window], atoms[wm_take_focus] };
2277                   XSetWMProtocols(xGlobalDisplay, windowHandle, protocols, 2);
2278                }
2279
2280                // Set Normal hints for minimum/maximum size
2281                if(true) //window.minSize.w || window.minSize.h || window.maxSize.w < MAXINT || window.maxSize.h < MAXINT)
2282                {
2283                   XSizeHints hints = { 0 };
2284                   MinMaxValue mw, mh;
2285                   window.SetWindowMinimum(&mw, &mh);
2286                   if(window.minSize.w || window.minSize.h)
2287                   {
2288                      hints.min_width = Max(window.minSize.w, mw);
2289                      hints.min_height = Max(window.minSize.h, mh);
2290                      hints.flags |= PMinSize;
2291                   }
2292                   if(window.maxSize.w < MAXINT || window.minSize.h < MAXINT)
2293                   {
2294                      hints.max_width = window.maxSize.w;
2295                      hints.max_height = window.maxSize.h;
2296                      hints.flags |= PMaxSize;
2297                   }
2298                   hints.x = x;
2299                   hints.y = y;
2300                   hints.flags |= PPosition;
2301
2302                   hints.width = w;
2303                   hints.height = h;
2304                   hints.flags |= PSize;
2305
2306                   XSetWMNormalHints(xGlobalDisplay, windowHandle, &hints);
2307                }
2308             }
2309          }
2310       }
2311
2312       if(!ic && im)
2313       {
2314          char fontString[1024] = "--helvetica-*-r-*-*-*-120-*-*-*-*-*-*,-misc-fixed-*-r-*-*-*-130-*-*-*-*-*-*";
2315          XPoint cursor_location = { 0, 0 };
2316          char **missing_charsets;
2317          int num_missing_charsets = 0;
2318          char *default_string;
2319          XFontSet fontset;
2320          XRectangle area = { 0, 0,  400, 400 };
2321          XVaNestedList argList;
2322
2323          // sprintf(fontString, "-*-%s-*-r-*-*-*-%d-*-*-*-*-*-*", "Helvetica" /*window.font.faceName*/, (int)(window.font.size * 20));
2324          fontset = XCreateFontSet(xGlobalDisplay, fontString, &missing_charsets, &num_missing_charsets, &default_string);
2325          argList = XVaCreateNestedList(0,
2326                                        XNSpotLocation, &cursor_location,
2327                                        //XNArea, &area,
2328                                        XNFontSet, fontset,/*
2329                                        XNForeground,
2330                                        WhitePixel(xGlobalDisplay, DefaultScreen(xGlobalDisplay)),
2331                                        XNBackground,
2332                                        BlackPixel(xGlobalDisplay, DefaultScreen(xGlobalDisplay)),*/
2333                                        NULL);
2334          ic = XCreateIC(im, XNInputStyle,
2335             XIMStatusNothing | XIMPreeditPosition,
2336             XNPreeditAttributes, argList,
2337             XNClientWindow, windowHandle, XNFocusWindow, windowHandle, NULL);
2338          XFree(argList);
2339          // Should we free the fontset or not?
2340          // XFreeFontSet(xGlobalDisplay, fontset);
2341          if(ic)
2342             setICPosition = true;
2343          else
2344             ic = XCreateIC(im, XNInputStyle, XIMStatusNothing | XIMPreeditNothing, XNClientWindow, windowHandle, XNFocusWindow, windowHandle, null);
2345       }
2346       if(ic)
2347       {
2348               XGetICValues(ic, XNFilterEvents, &mask, NULL);
2349               mask |= EVENT_MASK;
2350       }
2351       /*
2352       XSelectInput(xGlobalDisplay, windowHandle, mask);
2353
2354       if(capturedWindow == None && !restrictedWindow)
2355       {
2356          XGrabPointer(xGlobalDisplay, (X11Window)windowHandle, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2357             GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
2358          XUngrabPointer(xGlobalDisplay, CurrentTime);
2359       }
2360       */
2361
2362       {
2363          if ( atoms[_motif_wm_hints] != None )
2364          {
2365             MWM_Hints hints
2366             {
2367                (window.nativeDecorations ? 0 : MWM_HINTS_DECORATIONS)|MWM_HINTS_FUNCTIONS,
2368                (window.hasClose ? MWM_FUNC_CLOSE : 0) |
2369                (window.hasMaximize ? MWM_FUNC_MAXIMIZE : 0) |
2370                (window.hasMinimize ? MWM_FUNC_MINIMIZE : 0) |
2371                ((window.moveable || ((BorderBits)window.borderStyle).fixed) ? MWM_FUNC_MOVE : 0) |
2372                (((BorderBits)window.borderStyle).sizable ? MWM_FUNC_RESIZE : 0),
2373                 0, 0, 0
2374             };
2375             XChangeProperty(xGlobalDisplay, windowHandle, atoms[_motif_wm_hints], atoms[_motif_wm_hints], 32,
2376                PropModeReplace, (unsigned char*)&hints, 5);
2377          }
2378
2379          // *** We set this for ourselves, so don't check atomsSupported !!! ***
2380          if(atoms[_net_wm_pid])
2381          {
2382             int pid = getpid();
2383             // printf("Setting _NET_WM_PID to %d\n", pid);
2384             XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_pid], XA_CARDINAL, 32,
2385                PropModeReplace, (unsigned char*)&pid, 1);
2386          }
2387       }
2388
2389       /*
2390       {
2391          Atom protocolsAtom = XInternAtom(xGlobalDisplay, "WM_PROTOCOLS", False);
2392          if ( protocolsAtom != None )
2393          {
2394             MWM_Hints hints = { MWM_HINTS_DECORATIONS|MWM_HINTS_FUNCTIONS, 0, 0, 0, 0 };
2395             XChangeProperty(xGlobalDisplay, windowHandle, atoms[_motif_wm_hints], atoms[_motif_wm_hints], 32,
2396                PropModeReplace, (unsigned char*)&hints, sizeof(hints)/4);
2397          }
2398       }*/
2399       // XFlush(xGlobalDisplay);
2400       window.windowData = XWindowData { visualInfo, ic };
2401
2402       XSaveContext(xGlobalDisplay, windowHandle, windowContext, (XPointer)window);
2403
2404       XSelectInput(xGlobalDisplay, windowHandle, mask);
2405
2406       if(capturedWindow == None && !restrictedWindow)
2407       {
2408          XGrabPointer(xGlobalDisplay, (X11Window)windowHandle, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2409             GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
2410          XUngrabPointer(xGlobalDisplay, CurrentTime);
2411       }
2412
2413       if(window.nativeDecorations && frameExtentSupported != broken)
2414       {
2415          // Request decoration frame extents
2416          XClientMessageEvent event = { 0 };
2417          event.type = ClientMessage;
2418          event.message_type = atoms[_net_request_frame_extents];
2419          event.display = xGlobalDisplay;
2420          event.serial = 0;
2421          event.window = (X11Window)windowHandle;
2422          event.send_event = 1;
2423          window.windowHandle = (void *)windowHandle;
2424          event.format = 32;
2425
2426          if(frameExtentSupported == unknown && !frameExtentRequest)
2427          {
2428             frameExtentRequest = GetTime();
2429             frameExtentWindow = windowHandle;
2430          }
2431
2432          XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false,
2433             SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
2434       }
2435       else
2436          ((XWindowData)window.windowData).gotFrameExtents = true;
2437       return (void *)windowHandle;
2438    }
2439
2440    void DestroyRootWindow(Window window)
2441    {
2442       XEvent event;
2443
2444       XDeleteContext(xGlobalDisplay, (XID)window, windowContext);
2445       XSaveContext(xGlobalDisplay, (X11Window)window.windowHandle, windowContext, null);
2446       XDestroyWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2447       XSync(xGlobalDisplay, 0);
2448       while(XCheckWindowEvent(xGlobalDisplay, (X11Window)window.windowHandle, 0xFFFFFFFF, &event));
2449       window.windowHandle = null;
2450       if(window.windowData)
2451       {
2452          XWindowData windowData = window.windowData;
2453          XFree(windowData.visual);
2454          if(windowData && windowData.ic)
2455             XDestroyIC(windowData.ic);
2456          delete windowData;
2457          // printf("Setting windowData for %s to null\n", window._class.name);
2458          window.windowData = null;
2459       }
2460       if(lastActive == window)
2461          delete lastActive;
2462    }
2463
2464    // -- Window manipulation ---
2465
2466    void SetRootWindowCaption(Window window, char * name)
2467    {
2468       if(window.windowHandle)
2469       {
2470          XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[_net_wm_name],
2471             atoms[utf8_string], 8, PropModeReplace, (byte *)name, name ? strlen(name) : 0);
2472          XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[wm_name],
2473             atoms[utf8_string], 8, PropModeReplace, (byte *)name, name ? strlen(name) : 0);
2474       }
2475    }
2476
2477    void PositionRootWindow(Window window, int x, int y, int w, int h, bool move, bool resize)
2478    {
2479       //Logf("Position root window %s\n", window.name);
2480       if(window.windowHandle && (!window.parent || !window.parent.display))
2481       {
2482          bool visible = window.visible;
2483          if(window.visible && window.created)
2484             XMapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2485          if(window.state == minimized && atomsSupported[_net_wm_state]) return;
2486
2487          if(window.nativeDecorations)
2488          {
2489             XWindowData windowData = window.windowData;
2490
2491             // Was commenting this out was part of #700/#795 fix, but this causes jumping of e.g. About box after getting frame extents PropertyNotify
2492
2493                // && window.state != maximized -- required for Cinnamon on Mint 14/15
2494             if(!windowData.gotFrameExtents && window.state != maximized) return;
2495
2496             x -= windowData.decor.left;
2497             y -= windowData.decor.top;
2498
2499             w -= windowData.decor.left + windowData.decor.right;
2500             h -= windowData.decor.top + windowData.decor.bottom;
2501
2502             // Tweak for first unmaximize on Unity on Ubuntu 11.10
2503             if(window.state == maximized && (desktopX + w > desktopW || desktopY + h > desktopH))
2504             {
2505                w -= 40;
2506                h -= 40;
2507             }
2508          }
2509
2510          x += desktopX;
2511          y += desktopY;
2512
2513          if(move && resize)
2514             XMoveResizeWindow(xGlobalDisplay, (X11Window)window.windowHandle, x, y, w, h);
2515          else if(move)
2516             XMoveWindow(xGlobalDisplay, (X11Window)window.windowHandle, x, y);
2517          else if(resize)
2518             XResizeWindow(xGlobalDisplay, (X11Window)window.windowHandle, w, h);
2519 #if defined(__APPLE__)
2520 //         if(window.created && !visible)
2521   //          XUnmapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2522 #endif
2523       }
2524    }
2525
2526    void OrderRootWindow(Window window, bool topMost)
2527    {
2528
2529    }
2530
2531    void SetRootWindowColor(Window window)
2532    {
2533
2534    }
2535
2536    void OffsetWindow(Window window, int * x, int * y)
2537    {
2538
2539    }
2540
2541    void UpdateRootWindow(Window window)
2542    {
2543       if(!window.parent || !window.parent.display)
2544       {
2545          if(window.visible)
2546          {
2547             Box box = window.box;
2548             box.left -= window.clientStart.x;
2549             box.top -= window.clientStart.y;
2550             box.right -= window.clientStart.x;
2551             box.bottom -= window.clientStart.y;
2552             // Logf("Update root window %s\n", window.name);
2553             window.Update(null);
2554             box.left   += window.clientStart.x;
2555             box.top    += window.clientStart.y;
2556             box.right  += window.clientStart.x;
2557             box.bottom += window.clientStart.y;
2558             window.UpdateDirty(box);
2559          }
2560       }
2561    }
2562
2563    void SetRootWindowState(Window window, WindowState state, bool visible)
2564    {
2565       // Old WM (e.g. TWM), use built-in decorations
2566       if(!atomsSupported[_net_wm_state])
2567          window.nativeDecorations = false;
2568       if(!window.parent || !window.parent.display)
2569       {
2570          //Logf("Set root window state %d %s\n", state, window.name);
2571          if(visible)
2572          {
2573             XMapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2574             WaitForViewableWindow(window);
2575             if(window.creationActivation == activate && state != minimized)
2576                ActivateRootWindow(window);
2577
2578             if(state == minimized && atomsSupported[_net_wm_state])
2579             {
2580                uint iconic = IconicState;
2581                /*
2582                XChangeProperty(xGlobalDisplay, window.windowHandle, atoms[_net_wm_state], XA_ATOM, 32,
2583                   PropModeReplace, (unsigned char*)&atoms[_net_wm_state_hidden], 1);
2584                */
2585                /*
2586                XChangeProperty(xGlobalDisplay, window.windowHandle, atoms[wm_state], XA_CARDINAL, 32,
2587                   PropModeReplace, &iconic, 1);
2588                */
2589
2590                /*
2591                XClientMessageEvent event = { 0 };
2592                event.type = ClientMessage;
2593                event.message_type = atoms[_net_wm_state];
2594                event.display = xGlobalDisplay;
2595                event.serial = 0;
2596                event.window = window.windowHandle;
2597                event.send_event = 1;
2598                event.format = 32;
2599                event.data.l[0] = 2; // 1;
2600                event.data.l[1] = atoms[_net_wm_state_hidden];
2601                XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, &event);
2602                */
2603                /*
2604                XClientMessageEvent event = { 0 };
2605                event.type = ClientMessage;
2606                event.message_type = atoms[wm_state];
2607                event.display = xGlobalDisplay;
2608                event.window = window.windowHandle;
2609                event.send_event = 1;
2610                event.format = 32;
2611                event.data.l[0] = IconicState;
2612                XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, &event);
2613                */
2614
2615                // printf("Attempting to minimize %s\n", window._class.name);
2616                XIconifyWindow(xGlobalDisplay, (X11Window)window.windowHandle, DefaultScreen(xGlobalDisplay));
2617             }
2618             else
2619             {
2620                if(!window.nativeDecorations || (!((XWindowData)window.windowData).gotFrameExtents && window.state == maximized)) //((XWindowData)window.windowData).gotFrameExtents && (!window.nativeDecorations || window.state == state))
2621                {
2622                   int x = window.position.x;
2623                   int y = window.position.y;
2624                   int w = window.size.w;
2625                   int h = window.size.h;
2626
2627                   if(window.nativeDecorations)
2628                   {
2629                      XWindowData windowData = window.windowData;
2630                      x -= windowData.decor.left;
2631                      y -= windowData.decor.top;
2632
2633                      w -= windowData.decor.left + windowData.decor.right;
2634                      h -= windowData.decor.top + windowData.decor.bottom;
2635                   }
2636                   x += desktopX;
2637                   y += desktopY;
2638
2639                   // With native decorations, we do it the first time
2640                   // or the WM (Gnome) is sticking it to the top/right!
2641                   XMoveResizeWindow(xGlobalDisplay,
2642                      (X11Window)window.windowHandle,
2643                      x, y, w, h);
2644                   UpdateRootWindow(window);
2645                }
2646                if(window.nativeDecorations)
2647                {
2648                   // Maximize / Restore the window
2649                   XClientMessageEvent event = { 0 };
2650                   event.type = ClientMessage;
2651                   event.message_type = atoms[_net_wm_state];
2652                   event.display = xGlobalDisplay;
2653                   event.serial = 0;
2654                   event.window = (X11Window)window.windowHandle;
2655                   event.send_event = 1;
2656                   event.format = 32;
2657                   event.data.l[0] = (state == maximized) ? 1 : 0;
2658                   event.data.l[1] = atoms[_net_wm_state_maximized_vert];
2659                   event.data.l[2] = atoms[_net_wm_state_maximized_horz];
2660                   XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false,
2661                      SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
2662                }
2663             }
2664          }
2665          else
2666             XUnmapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2667          //XFlush(xGlobalDisplay);
2668       }
2669    }
2670
2671    void FlashRootWindow(Window window)
2672    {
2673       XClientMessageEvent event = { 0 };
2674       // printf("Attempting to flash root window\n");
2675       event.type = ClientMessage;
2676       event.message_type = atoms[_net_wm_state];
2677       event.display = xGlobalDisplay;
2678       event.serial = 0;
2679       event.window = (X11Window)window.windowHandle;
2680       event.send_event = 1;
2681       event.format = 32;
2682       event.data.l[0] = 1;
2683       event.data.l[1] = atoms[_net_wm_state_demands_attention];
2684       XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
2685    }
2686
2687    void ActivateRootWindow(Window window)
2688    {
2689       if(!window.parent || !window.parent.display)
2690       {
2691          if(!window.style.hidden && window.created)
2692          {
2693             //printf("Activate root window %s\n", window._class.name);
2694             XRaiseWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2695             XMapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2696             WaitForViewableWindow(window);
2697             if(atomsSupported[_net_active_window])
2698             {
2699                XClientMessageEvent event = { 0 };
2700                event.type = ClientMessage;
2701                event.message_type = atoms[_net_active_window];
2702                event.display = xGlobalDisplay;
2703                event.serial = 0;
2704                event.window = (X11Window)window.windowHandle;
2705                event.send_event = 1;
2706                event.format = 32;
2707                event.data.l[0] = 0;
2708
2709                //event.data.l[0] = 2;
2710                //event.data.l[1] = timeStamp;
2711
2712
2713                //event.data.l[1] = atoms[_net_wm_user_time];
2714                //event.data.l[2] = activeWindow; //guiApp.desktop.activeChild.windowHandle;
2715
2716 #ifdef _DEBUG
2717                //printf("(ActivateRootWindow) Setting _NET_ACTIVE_WINDOW for %s (%x)\n", window._class.name, window);
2718 #endif
2719
2720                XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
2721 //#if defined(__APPLE__)
2722                XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToPointerRoot, CurrentTime);
2723 //#endif
2724             }
2725             else
2726                XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToPointerRoot, CurrentTime);
2727          }
2728       }
2729    }
2730
2731    // --- Mouse-based window movement ---
2732
2733    void StartMoving(Window window, int x, int y, bool fromKeyBoard)
2734    {
2735
2736    }
2737
2738    void StopMoving(Window window)
2739    {
2740
2741    }
2742
2743    // -- Mouse manipulation ---
2744
2745    void GetMousePosition(int *x, int *y)
2746    {
2747       X11Window rootWindow, childWindow;
2748       int mx, my;
2749       unsigned int state;
2750       ((GuiApplication)__thisModule.application).Lock();
2751       //XLockDisplay(xGlobalDisplay);
2752       XQueryPointer(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), &childWindow,
2753          &rootWindow, x, y, &mx, &my, &state);
2754       //XUnlockDisplay(xGlobalDisplay);
2755       ((GuiApplication)__thisModule.application).Unlock();
2756    }
2757
2758    void SetMousePosition(int x, int y)
2759    {
2760
2761    }
2762
2763    void SetMouseRange(Window window, Box box)
2764    {
2765       ((GuiApplication)__thisModule.application).Lock();
2766       //XLockDisplay(xGlobalDisplay);
2767       if(box && box.left > 0 && box.top > 0 &&
2768          box.right < guiApp.desktop.clientSize.w - 1 && box.bottom < guiApp.desktop.clientSize.h - 1)
2769       {
2770          if(!window.parent || !window.parent.display)
2771          {
2772             XMoveResizeWindow(xGlobalDisplay, confineWindow, box.left + desktopX, box.top + desktopY,
2773                box.right - box.left + 1, box.bottom - box.top + 1);
2774
2775             if(!restrictedWindow)
2776                XMapWindow(xGlobalDisplay, confineWindow);
2777
2778             XGrabPointer(xGlobalDisplay, (X11Window) window.rootWindow.windowHandle, False,
2779                ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2780                GrabModeAsync, confineWindow, fullScreenMode ? nullCursor : None, CurrentTime);
2781
2782             restrictedWindow = window;
2783          }
2784       }
2785       else if(restrictedWindow)
2786       {
2787          if(capturedWindow != None)
2788          {
2789             XGrabPointer(xGlobalDisplay, (X11Window)capturedWindow,
2790                False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2791                GrabModeAsync, None, fullScreenMode ? nullCursor : None, CurrentTime);
2792          }
2793          else
2794             XUngrabPointer(xGlobalDisplay, CurrentTime);
2795
2796          if(restrictedWindow)
2797             XUnmapWindow(xGlobalDisplay, confineWindow);
2798
2799          restrictedWindow = null;
2800       }
2801       //XUnlockDisplay(xGlobalDisplay);
2802       ((GuiApplication)__thisModule.application).Unlock();
2803    }
2804
2805    void SetMouseCapture(Window window)
2806    {
2807       //*XLockDisplay(xGlobalDisplay);
2808       if(window)
2809       {
2810          if(!window.parent || !window.parent.display)
2811          {
2812             XGrabPointer(xGlobalDisplay, (X11Window)window.windowHandle,
2813                False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2814                GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
2815
2816             capturedWindow = (X11Window) window.windowHandle;
2817          }
2818       }
2819       else if(capturedWindow != None)
2820       {
2821          if(restrictedWindow)
2822             XGrabPointer(xGlobalDisplay, (X11Window) restrictedWindow.rootWindow.windowHandle, False,
2823                ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2824                GrabModeAsync, confineWindow, fullScreenMode ? nullCursor : None, CurrentTime);
2825          else
2826             XUngrabPointer(xGlobalDisplay, CurrentTime);
2827          capturedWindow = None;
2828       }
2829       //*XUnlockDisplay(xGlobalDisplay);
2830    }
2831
2832    // -- Mouse cursor ---
2833
2834    void SetMouseCursor(Window window, int cursor)
2835    {
2836       XDefineCursor(xGlobalDisplay, (X11Window) window.rootWindow.windowHandle,
2837          cursor == -1 ? (X11Cursor)0 : systemCursors[(SystemCursor)cursor]);
2838    }
2839
2840    // --- Caret ---
2841
2842    void SetCaret(int x, int y, int size)
2843    {
2844       Window caretOwner = guiApp.caretOwner;
2845       Window window = caretOwner ? caretOwner.rootWindow : null;
2846       if(window && window.windowData && setICPosition)
2847       {
2848          XWindowData windowData = window.windowData;
2849          if(windowData && windowData.ic)
2850          {
2851             XPoint cursor_location =
2852             {
2853                (short)(caretOwner.caretPos.x - caretOwner.scroll.x + caretOwner.absPosition.x - window.absPosition.x),
2854                (short)(caretOwner.caretPos.y - caretOwner.scroll.y + caretOwner.absPosition.y - window.absPosition.y)
2855             };
2856             XVaNestedList argList = XVaCreateNestedList(0, XNSpotLocation, &cursor_location, NULL);
2857             XSetICValues(windowData.ic, XNPreeditAttributes, argList, 0);
2858          }
2859       }
2860    }
2861
2862    void ClearClipboard()
2863    {
2864       //*XLockDisplay(xGlobalDisplay);
2865       if(clipBoardData)
2866       {
2867          delete clipBoardData;
2868         XSetSelectionOwner(xGlobalDisplay, atoms[clipboard], None, CurrentTime);
2869       }
2870       //*XUnlockDisplay(xGlobalDisplay);
2871    }
2872
2873    bool AllocateClipboard(ClipBoard clipBoard, uint size)
2874    {
2875       bool result = false;
2876       if((clipBoard.text = new0 byte[size]))
2877          result = true;
2878       return result;
2879    }
2880
2881    bool SaveClipboard(ClipBoard clipBoard)
2882    {
2883       bool result = false;
2884       //*XLockDisplay(xGlobalDisplay);
2885       if(clipBoard.text)
2886       {
2887          Window rootWindow = guiApp.desktop;
2888          if(!fullScreenMode)
2889          {
2890             for(rootWindow = rootWindow.children.first;
2891                rootWindow && !rootWindow.windowHandle;
2892                rootWindow = rootWindow.next);
2893          }
2894          if(clipBoardData)
2895             delete clipBoardData;
2896          else if(rootWindow)
2897             XSetSelectionOwner(xGlobalDisplay, atoms[clipboard],
2898                (X11Window) rootWindow.windowHandle, CurrentTime);
2899          clipBoardData = clipBoard.text;
2900          clipBoard.text = null;
2901          result = true;
2902       }
2903       //*XUnlockDisplay(xGlobalDisplay);
2904       return result;
2905    }
2906
2907    bool LoadClipboard(ClipBoard clipBoard)
2908    {
2909       bool result = false;
2910
2911       //*XLockDisplay(xGlobalDisplay);
2912       // The data is inside this client...
2913       if(clipBoardData)
2914       {
2915          clipBoard.text = new char[strlen(clipBoardData)+1];
2916          strcpy(clipBoard.text, clipBoardData);
2917          result = true;
2918       }
2919       // The data is with another client...
2920       else
2921       {
2922          Window rootWindow = guiApp.desktop;
2923          if(!fullScreenMode)
2924          {
2925             for(rootWindow = rootWindow.children.first;
2926                rootWindow && !rootWindow.windowHandle;
2927                rootWindow = rootWindow.next);
2928          }
2929          if(rootWindow)
2930          {
2931             Atom selAtom = atoms[clipboard];
2932             X11Window owner = XGetSelectionOwner(xGlobalDisplay, selAtom);
2933             if(owner != None)
2934             {
2935                Atom atom;
2936                for(atom = atoms[utf8_string]; atom; atom = ((atom == atoms[utf8_string]) ? XA_STRING : 0))
2937                {
2938                   XEvent e;
2939                   XConvertSelection(xGlobalDisplay, selAtom, atom, atoms[app_selection] /*None*/, (X11Window) rootWindow.windowHandle, CurrentTime);
2940                   XIfEvent(xGlobalDisplay, (XEvent *) &e, EventChecker, (void *)SelectionNotify);
2941                   if(e.type == SelectionNotify)
2942                   {
2943                      XSelectionEvent * selection = (XSelectionEvent *) &e;
2944                      //printf("Got a SelectionNotify with %d (%s)\n", selection->_property, XGetAtomName(xGlobalDisplay, selection->_property));
2945                      byte *data = null;
2946                      unsigned long len, size = 0, dummy;
2947                      Atom type;
2948                      int format;
2949                      XGetWindowProperty(xGlobalDisplay, (X11Window) rootWindow.windowHandle, selection->_property ? selection->_property : atom, 0, 0, False, AnyPropertyType, &type, &format, &len, &size, &data);
2950                      if(data)
2951                      {
2952                         XFree(data);
2953                         data = null;
2954                      }
2955                      if(size > 0)
2956                      {
2957                         if(XGetWindowProperty(xGlobalDisplay, (X11Window) rootWindow.windowHandle, selection->_property ? selection->_property : atom, 0, size, False,
2958                               AnyPropertyType, &type,&format,&len, &dummy, &data) == Success)
2959                         {
2960                            clipBoard.text = new char[size+1];
2961                            strncpy(clipBoard.text, data, size);
2962                            clipBoard.text[size] = '\0';
2963                            XFree(data);
2964                            result = true;
2965                            break;
2966                         }
2967                      }
2968                   }
2969                }
2970             }
2971          }
2972       }
2973       //*XUnlockDisplay(xGlobalDisplay);
2974       return result;
2975    }
2976
2977    void UnloadClipboard(ClipBoard clipBoard)
2978    {
2979       delete clipBoard.text;
2980    }
2981
2982    // --- State based input ---
2983
2984    bool AcquireInput(Window window, bool state)
2985    {
2986       return false;
2987    }
2988
2989    bool GetMouseState(MouseButtons * buttons, int * x, int * y)
2990    {
2991       bool result = false;
2992       if(x) *x = 0;
2993       if(y) *y = 0;
2994       return result;
2995    }
2996
2997    bool GetJoystickState(int device, Joystick joystick)
2998    {
2999       bool result = false;
3000    #if defined(__linux__)
3001       if(joystick && device < 4)
3002       {
3003          struct JS_DATA_TYPE js = { 0 };
3004          memset(joystick, 0, sizeof(Joystick));
3005          if(joystickFD[device] && read(joystickFD[device], &js, JS_RETURN) == JS_RETURN)
3006          {
3007             joystick.buttons = js.buttons;
3008             joystick.x = js.x - 128;
3009             joystick.y = js.y - 128;
3010             result = true;
3011          }
3012       }
3013    #endif
3014       return result;
3015    }
3016
3017    bool GetKeyState(Key key)
3018    {
3019       int keyState = 0;
3020       return keyState;
3021    }
3022
3023    void SetTimerResolution(uint hertz)
3024    {
3025       timerDelay = hertz ? (1000000 / hertz) : MAXINT;
3026       /*
3027       hiResTimer.Stop();
3028       if(hertz)
3029       {
3030          hiResTimer.delay = 1000000 / hertz;
3031          hiResTimer.Create();
3032       }
3033       */
3034    }
3035
3036    bool SetIcon(Window window, BitmapResource resource)
3037    {
3038       if(resource)
3039       {
3040          Bitmap bitmap { };
3041          if(bitmap.Load(resource.fileName, null, null))
3042          {
3043             unsigned long * icon = new unsigned long[2 + bitmap.width * bitmap.height];
3044             bitmap.Convert(null, pixelFormat888, null);
3045             icon[0] = bitmap.width;
3046             icon[1] = bitmap.height;
3047             if(sizeof(long) != sizeof(uint32))
3048             {
3049                int c;
3050                for(c = 0; c < bitmap.width * bitmap.height; c++)
3051                   icon[c+2] = ((uint32 *)bitmap.picture)[c];
3052             }
3053             else
3054                memcpy(icon + 2, bitmap.picture, bitmap.width * bitmap.height * sizeof(uint32));
3055             XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[_net_wm_icon],
3056                           XA_CARDINAL,32,PropModeReplace, (byte *)icon, 2+bitmap.width*bitmap.height);
3057            delete icon;
3058          }
3059          delete bitmap;
3060       }
3061       return true;
3062    }
3063 }
3064
3065 default dllexport void * __attribute__((stdcall)) IS_XGetDisplay()
3066 {
3067    return xGlobalDisplay;
3068 }
3069
3070 default dllexport void * __attribute__((stdcall)) IS_XGetWindow(Window window)
3071 {
3072    return window.windowHandle ? window.windowHandle : window.rootWindow.windowHandle;
3073 }
3074
3075 #endif