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