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