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