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