ide/ProjectSettings: Fixed overriding to 'false' Project setting bool in config or...
[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                   if(event->button == Button1)
1368                   {
1369                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonUp;
1370                      buttonMask = Button1Mask;
1371                   }
1372                   else if(event->button == Button3)
1373                   {
1374                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonUp;
1375                      buttonMask = Button3Mask;
1376                   }
1377                   else
1378                   {
1379                      button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonUp;
1380                      buttonMask = Button2Mask;
1381                   }
1382                   if(!(event->state & buttonMask)) break;
1383                   if(event->state & ShiftMask)     keyFlags.shift = true;
1384                   if(event->state & ControlMask)   keyFlags.ctrl = true;
1385                   if(event->state & Mod1Mask)      keyFlags.alt = true;
1386                   if(event->state & Button1Mask)   keyFlags.left = true;
1387                   if(event->state & Button2Mask)   keyFlags.middle = true;
1388                   if(event->state & Button3Mask)   keyFlags.right = true;
1389                   //*XUnlockDisplay(xGlobalDisplay);
1390                   incref window;
1391                   window.MouseMessage(button, event->x_root, event->y_root, &keyFlags, false, false);
1392                   delete window;
1393                   //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1394                   break;
1395                }
1396                case MotionNotify:
1397                { 
1398                   static uint lastTime = 0;
1399                   XMotionEvent * event = (XMotionEvent *) thisEvent;
1400                   while(XCheckIfEvent(xGlobalDisplay, (XEvent *)thisEvent, EventChecker, (void *)MotionNotify));
1401                   // if(event->time - lastTime > 15)
1402                   {
1403                      Modifiers keyFlags = 0;
1404                      
1405                      if(event->state & ShiftMask)     keyFlags.shift = true;
1406                      if(event->state & ControlMask)   keyFlags.ctrl = true;
1407                      if(event->state & Mod1Mask)      keyFlags.alt = true;
1408                      if(event->state & Button1Mask)   keyFlags.left = true;
1409                      if(event->state & Button2Mask)   keyFlags.middle = true;
1410                      if(event->state & Button3Mask)   keyFlags.right = true;
1411                      //*XUnlockDisplay(xGlobalDisplay);
1412                      incref window;
1413                      window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMouseMove,
1414                         event->x_root, event->y_root, &keyFlags, false, false);
1415                      delete window;
1416                      //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1417                      lastTime = event->time;
1418                   }
1419                   break;
1420                }
1421                case Expose:
1422                {
1423                   XExposeEvent * event = (XExposeEvent *) thisEvent;
1424                   Box box;
1425                   box.left = event->x - window.clientStart.x;
1426                   box.top = event->y - window.clientStart.y;
1427                   box.right = box.left + event->width - 1;
1428                   box.bottom = box.top + event->height - 1;
1429                   window.Update(box);
1430                   box.left   += window.clientStart.x;
1431                   box.top    += window.clientStart.y;
1432                   box.right  += window.clientStart.x;
1433                   box.bottom += window.clientStart.y;
1434                   window.UpdateDirty(box);
1435                   break;
1436                }
1437                case SelectionRequest:
1438                {
1439                     XSelectionRequestEvent *req = (XSelectionRequestEvent *) thisEvent;
1440                     XEvent respond;
1441                          if(req->target == atoms[targets] && clipBoardData)
1442                   {
1443                      Atom * supportedTargets = new Atom[4];
1444                      supportedTargets[0] = atoms[targets];
1445                      supportedTargets[1] = atoms[multiple];
1446                      supportedTargets[2] = XA_STRING;
1447                      supportedTargets[3] = atoms[utf8_string];
1448                      XChangeProperty(xGlobalDisplay,req->requestor, req->_property,
1449                                          XA_ATOM,32,PropModeReplace, (byte *) supportedTargets, 4*sizeof(Atom));
1450                      respond.xselection._property = req->_property;
1451                      delete supportedTargets;
1452                   }
1453                   else if((req->target == XA_STRING || req->target == atoms[utf8_string]) && clipBoardData)
1454                          {
1455                      Atom _property = (req->_property == None) ? req->target : req->_property;
1456                                  XChangeProperty(xGlobalDisplay,req->requestor, _property,
1457                                          req->target/*req->_property*/,8,PropModeReplace, (byte *) clipBoardData, strlen(clipBoardData));
1458                                  respond.xselection._property = _property;
1459                          }
1460                   else
1461                                  respond.xselection._property = None;
1462                          
1463                   respond.xselection.type = SelectionNotify;
1464                          respond.xselection.display = req->display;
1465                          respond.xselection.requestor = req->requestor;
1466                          respond.xselection.selection =req->selection;
1467                          respond.xselection.target = req->target;
1468                          respond.xselection.time = CurrentTime;
1469                          XSendEvent(xGlobalDisplay, req->requestor,0,0,&respond);
1470                   break;
1471                }
1472                case SelectionClear:
1473                {
1474                   delete clipBoardData;
1475                   break;
1476                }
1477                case FocusIn:
1478                {
1479                   XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1480                   Window modalRoot = window.FindModal();
1481                   XWindowData windowData;
1482                   activeWindow = (uint)window.windowHandle;
1483
1484                   if(window.parent && window == window.parent.activeChild) break;
1485                   incref window;
1486                   //if(window.creationActivation == activate)
1487                   {
1488                      if(modalRoot)
1489                         modalRoot.ExternalActivate(true, true, window, null); // lastActive);
1490                      else
1491                         window.ExternalActivate(true, true, window, null); // lastActive); 
1492                   } 
1493                   windowData = modalRoot ? modalRoot.windowData : window.windowData;
1494                   if(windowData && windowData.ic)
1495                   {
1496                      // XSetICValues(ic, XNClientWindow, window.windowHandle, XNFocusWindow, window.windowHandle, 0);
1497                      XSetICFocus(windowData.ic);
1498                   }
1499                   //delete lastActive;
1500                   //lastActive = window;
1501                   //incref lastActive;
1502                   delete window;
1503                   break;
1504                }
1505                case FocusOut:
1506                {
1507 #ifdef _DEBUG
1508                   //printf("Processing a FocusOut Event for %s (%x)\n", window._class.name, window);
1509 #endif
1510
1511                   if(XCheckTypedWindowEvent(xGlobalDisplay, thisEvent->window, FocusIn, (XEvent *)thisEvent))
1512                   {
1513                      break;
1514                   }
1515                   if(thisEvent->window == activeWindow)
1516                      activeWindow = (uint)null;
1517 #if 0
1518                   if(XCheckTypedEvent(xGlobalDisplay, FocusIn, (XEvent *)thisEvent))
1519                   {
1520                      if(XCheckTypedWindowEvent(xGlobalDisplay, thisEvent->window, FocusOut, (XEvent *)thisEvent))
1521                      {
1522                         XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1523                         
1524                         XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1525                         if(window)
1526                         {
1527                            Window windowCopy = window;
1528                            XWindowData windowData;
1529                            if(windowCopy == windowCopy.parent.activeChild) break;
1530                            incref windowCopy;
1531                            windowCopy.ExternalActivate(true, true,  windowCopy, lastActive);
1532
1533                            windowData = windowCopy.windowData;
1534                            if(windowData && windowData.ic)
1535                               XSetICFocus(windowData.ic);
1536
1537                            delete lastActive;
1538                            lastActive = windowCopy;
1539                            incref lastActive;
1540                            delete windowCopy;
1541                         }
1542
1543                         // XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1544                         if(window)
1545                         {
1546                            if(window != window.parent.activeChild) break;
1547                            incref window;
1548                            window.ExternalActivate(false, true,  window, lastActive);
1549                            delete window;
1550                         }
1551                      }
1552                      else
1553                      {
1554                         XWindowData windowData;
1555                         XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1556                         
1557                         if(window)
1558                         {
1559                            XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1560                            Window modalRoot = window.FindModal();
1561
1562                            incref window;
1563                            if(modalRoot)
1564                            {
1565                               modalRoot.ExternalActivate(true, true, window, lastActive);
1566                            }
1567                            else
1568                            {
1569                               window.ExternalActivate(true, true, window, lastActive);
1570                            }
1571                            windowData = modalRoot ? modalRoot.windowData : window.windowData;
1572                            if(windowData && windowData.ic)
1573                               XSetICFocus(windowData.ic);
1574
1575                            delete lastActive;
1576                            lastActive = window;
1577                            incref lastActive;
1578                            delete window;
1579                         }
1580                      }
1581                   }
1582                   else
1583 #endif
1584                   {
1585                      XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
1586                      if(window != window.parent.activeChild && window != guiApp.interimWindow) break;
1587                      incref window;
1588
1589 #ifdef _DEBUG
1590                      //printf("Deactivating %s\n", window._class.name);
1591 #endif
1592
1593                      if(!window.ExternalActivate(false, true, window, null /*lastActive*/))
1594                      {
1595                         XCheckTypedEvent(xGlobalDisplay, /*thisEvent->window, */ButtonPress, (XEvent *)thisEvent);
1596                      }
1597                      
1598                      //delete lastActive;
1599                      /*
1600                      lastActive = window;
1601                      incref lastActive;
1602                      */
1603                      delete window;
1604                   }
1605                   break;
1606                }
1607                case ConfigureNotify:
1608                {
1609                   XConfigureEvent * event = (XConfigureEvent *) thisEvent;
1610                   while(XCheckIfEvent(xGlobalDisplay, (XEvent *)thisEvent, (void *)ConfigureNotifyChecker, (void *)window.windowHandle));
1611                   //if(event->x - desktopX != window.position.x || event->y - desktopY != window.position.y || event->width != window.size.w || event->height != window.size.h)
1612
1613                   // TODO: Support _NET_REQUEST_FRAME_EXTENTS message / _NET_FRAME_EXTENTS property for decoration size awareness
1614
1615                   window.ExternalPosition(event->x - desktopX, event->y - desktopY, event->width, event->height);
1616                   break;
1617                }
1618                case ClientMessage:
1619                {
1620                   XClientMessageEvent * event = (XClientMessageEvent *) thisEvent;
1621
1622                   if(event->data.l[0] == atoms[wm_delete_window])
1623                   {
1624                      window.Destroy(0);
1625                   }
1626
1627                   if(event->data.l[0] == atoms[wm_take_focus])
1628                   {
1629                      Window modalRoot;
1630                      XWindowData windowData;
1631                      bool laterFocus;
1632                      activeWindow = (uint)window.windowHandle;
1633
1634                      timeStamp = event->data.l[1];
1635                      
1636                      windowData = window.windowData;
1637                      laterFocus = windowData.laterFocus;
1638                      windowData.laterFocus = true;
1639
1640 #ifdef _DEBUG
1641                      //printf("Processing a ClientMessage WM_TAKE_FOCUS Event for %s (%x)\n", window._class.name, window);
1642 #endif
1643                      if(guiApp.interimWindow && guiApp.interimWindow.created && window != guiApp.interimWindow) break; //window == window.parent.activeChild) break;
1644                      // if(window == window.parent.activeChild) break;
1645                      incref window;
1646    
1647                      {
1648                         XEvent checkEvent;
1649                         //XFlush(xGlobalDisplay);
1650                         while(XCheckTypedEvent(xGlobalDisplay, FocusOut, &checkEvent))
1651                         {
1652                            XFocusChangeEvent *event = (XFocusChangeEvent *) &checkEvent;
1653                            Window window;
1654                            XFindContext(xGlobalDisplay, event->window, windowContext, (XPointer *) &window);
1655                            if(window != window.parent.activeChild) break;
1656                            incref window;
1657
1658       #ifdef _DEBUG
1659                            //printf("Found a FocusOut ahead, deactivating %s (%d)\n", window._class.name, window);
1660       #endif
1661
1662                            if(!window.ExternalActivate(false, true, window, null /*lastActive*/))
1663                            {
1664                               XCheckTypedEvent(xGlobalDisplay, /*thisEvent->window, */ButtonPress, (XEvent *)thisEvent);
1665                            }
1666                            delete lastActive;
1667                            delete window;
1668                         }
1669                      }
1670
1671                      modalRoot = window.FindModal();
1672                      windowData = modalRoot ? modalRoot.windowData : window.windowData;
1673                      if(windowData)
1674                      {
1675                         if(laterFocus || (modalRoot ? modalRoot : window).creationActivation == activate)
1676                         {
1677                            if(modalRoot)
1678                            {
1679                               XRaiseWindow(xGlobalDisplay, (int)modalRoot.windowHandle);
1680                               WaitForViewableWindow(modalRoot);
1681                               if(atoms[_net_active_window])
1682                               {
1683                                  XClientMessageEvent event = { 0 };
1684                                  event.type = ClientMessage;
1685                                  event.message_type = atoms[_net_active_window];
1686                                  event.display = xGlobalDisplay;
1687                                  event.serial = 0;
1688                                  event.window = (uint)modalRoot.windowHandle;
1689                                  event.send_event = 1;
1690                                  event.format = 32;
1691                                  event.data.l[0] = 0;
1692                                  /*
1693                                  event.data.l[0] = 1;
1694                                  event.data.l[1] = atoms[_net_wm_user_time];
1695                                  event.data.l[2] = activeWindow; //guiApp.desktop.activeChild.windowHandle;
1696                                  */
1697 #ifdef _DEBUG
1698                                  //printf("(ClientMessage - %s) Setting _NET_ACTIVE_WINDOW for %s (%x)\n", window._class.name, modalRoot._class.name, modalRoot);
1699 #endif
1700
1701                                  XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
1702                                  XSetInputFocus(xGlobalDisplay, (int)modalRoot.windowHandle, RevertToPointerRoot, (uint)timeStamp);
1703
1704                                  //XFlush(xGlobalDisplay);
1705                                  //printf("Done.\n");
1706                               }
1707                            }
1708                            else
1709                            {
1710                               XSetInputFocus(xGlobalDisplay, (int)window.windowHandle, RevertToPointerRoot, (uint)timeStamp);
1711                               window.ExternalActivate(true, true, window, null); // lastActive); 
1712                               if(windowData && windowData.ic)
1713                               {
1714                                  // XSetICValues(ic, XNClientWindow, window.windowHandle, XNFocusWindow, window.windowHandle, 0);
1715                                  //XSetICFocus(windowData.ic);
1716                               }
1717                            }
1718                         }
1719                         windowData.laterFocus = true;
1720                         delete lastActive;
1721                         lastActive = window;
1722                         incref lastActive;
1723                      }
1724                      delete window;
1725                   }
1726                   break;
1727                }
1728             }
1729             if(!processAll) break;
1730          }
1731       }
1732       //*if(xGlobalDisplay) XUnlockDisplay(xGlobalDisplay);
1733       //xMutex.Release();
1734       if(!eventAvailable)
1735          return false;
1736       return true;
1737    }
1738
1739    void Wait()
1740    {
1741       gotAnXEvent = false;
1742       xMutex.Release();
1743       xSemaphore.Release();
1744       guiApp.WaitEvent();
1745       xMutex.Wait();
1746    }
1747
1748    void Lock(Window window)
1749    {
1750       //*XLockDisplay(xGlobalDisplay);
1751    }
1752
1753    void Unlock(Window window)
1754    {
1755       //*XUnlockDisplay(xGlobalDisplay);
1756    }
1757
1758    char ** GraphicsDrivers(int * numDrivers)
1759    {
1760       static char *graphicsDrivers[] = { "X", "OpenGL" };
1761       *numDrivers = sizeof(graphicsDrivers) / sizeof(char *);
1762       return (char **)graphicsDrivers;
1763    }
1764
1765    void GetCurrentMode(bool * fullScreen, int * resolution, int * colorDepth, int * refreshRate)
1766    {
1767       *fullScreen = fullScreenMode;
1768    }
1769
1770    void EnsureFullScreen(bool *fullScreen)
1771    {
1772
1773    }
1774
1775    bool ScreenMode(bool fullScreen, int resolution, int colorDepth, int refreshRate, bool * textMode)
1776    {
1777       bool result = true;
1778
1779       fullScreenMode = fullScreen;
1780
1781       if(fullScreen)
1782       {
1783
1784       }
1785       else
1786       {
1787          static bool firstTime = true;
1788          firstTime = false;
1789          desktopX = desktopY = desktopW = desktopH = 0;
1790
1791          RepositionDesktop(false);
1792       }
1793       return result;
1794    }
1795
1796    // --- Window Creation ---
1797    void * CreateRootWindow(Window window)
1798    {
1799       X11Window windowHandle;
1800       XSetWindowAttributes attributes = { 0 };
1801       XVisualInfo * visualInfo = null;
1802       int depth;
1803       Visual * visual;
1804       XIC ic = null;
1805       unsigned int mask = EVENT_MASK;
1806
1807       attributes.override_redirect = window.interim ? True : False;
1808       attributes.event_mask = EVENT_MASK;
1809       //printf("%s\n", guiApp.defaultDisplayDriver);
1810 #if !defined(ECERE_VANILLA) && !defined(ECERE_NO3D)
1811       if(window.dispDriver == class(OpenGLDisplayDriver) || !strcmp(guiApp.defaultDisplayDriver, "OpenGL"))
1812       {
1813          int samples;
1814          bool alpha = true;
1815          for(samples = 4;; samples /= 2)
1816          {
1817             bool found = false;
1818             int attrib[30] =
1819             {
1820                GLX_RENDER_TYPE, GLX_RGBA_BIT,
1821                GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
1822                GLX_DOUBLEBUFFER, True,
1823                GLX_DEPTH_SIZE, 1,
1824                GLX_RED_SIZE, 1,
1825                GLX_GREEN_SIZE, 1,
1826                GLX_BLUE_SIZE, 1
1827             };
1828             int numAttribs = 14;
1829             
1830             GLXFBConfig *fbconfigs = null, fbconfig;
1831             int numfbconfigs;
1832             int i;
1833             //printf("Samples = %d, alpha = %d\n", samples, alpha);
1834             if(alpha)
1835             {
1836                attrib[numAttribs++] = GLX_ALPHA_SIZE;
1837                attrib[numAttribs++] = 1;
1838             }
1839             if(samples)
1840             {
1841                attrib[numAttribs++] = GLX_SAMPLE_BUFFERS_ARB;
1842                attrib[numAttribs++] = GL_TRUE;
1843                attrib[numAttribs++] = GLX_SAMPLES_ARB;
1844                attrib[numAttribs++] = samples;
1845             }
1846             attrib[numAttribs] = None;
1847
1848             // visualInfo = glXChooseVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib);
1849
1850             //printf("Trying %d samples...\n", samples);
1851             fbconfigs = glXChooseFBConfig(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib, &numfbconfigs);
1852             if(fbconfigs)
1853             {
1854                for (i = 0; i < numfbconfigs; i++)
1855                {
1856                   XRenderPictFormat * format;
1857                   visualInfo = glXGetVisualFromFBConfig(xGlobalDisplay, fbconfigs[i]);
1858                   if (!visualInfo) continue;
1859                   if(window.alphaBlend)
1860                   {
1861                      format = XRenderFindVisualFormat(xGlobalDisplay, visualInfo->visual);
1862                      if (!format) { XFree(visualInfo); continue; }
1863                      if(format->direct.alphaMask > 0)
1864                      {
1865                         //printf("Found what we're looking for (alphaBlend)\n");
1866                         fbconfig = fbconfigs[i];
1867                         found = true;
1868                         break;
1869                      }
1870                   }
1871                   else
1872                   {
1873                      //printf("Found what we're looking for\n");
1874                      found = true;
1875                      break;
1876                   }
1877                }
1878                if (i == numfbconfigs)
1879                {
1880                   fbconfig = fbconfigs[0];
1881                   visualInfo = glXGetVisualFromFBConfig(xGlobalDisplay, fbconfig);
1882                }
1883             }
1884             if(fbconfigs)
1885                XFree(fbconfigs);
1886             if(found || (!samples && !alpha))
1887             {
1888                //printf("Stopping now\n");
1889                break;
1890             }
1891             else
1892                XFree(visualInfo);
1893             if(samples == 1) samples = 0;
1894             else if(!samples) alpha = false;
1895          }
1896       } 
1897 #endif
1898       depth = visualInfo ? visualInfo->depth : (window.alphaBlend ? 32 : xSystemDepth);
1899       visual = visualInfo ? visualInfo->visual : (window.alphaBlend ? FindFullColorVisual (xGlobalDisplay, &depth) : xSystemVisual);
1900       // printf("visual: %d, depth: %d\n", visual, depth);
1901
1902       if(visual)
1903       {
1904          attributes.colormap = XCreateColormap(xGlobalDisplay, XRootWindow(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), visual, AllocNone);
1905          attributes.border_pixel = 0;
1906       }
1907       else
1908          return null;
1909
1910       if(fullScreenMode)
1911       {
1912          windowHandle = XCreateWindow(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay),
1913             0,0,guiApp.desktop.size.w,guiApp.desktop.size.h,0, depth, InputOutput, visual ? visual : CopyFromParent, 
1914             CWEventMask | (visual ? (CWColormap | CWBorderPixel) : 0)/*| CWOverrideRedirect*/, &attributes);
1915       }
1916       /*
1917          Unsupported for now...
1918       else if(window.systemParent)
1919       {
1920
1921       }
1922       */
1923       else
1924       {
1925          if(window.windowHandle)
1926             windowHandle = (int)window.windowHandle;
1927          else
1928          {
1929             X11Window parentWindow = (uint)null;
1930
1931             if(window.master.rootWindow && window.master.rootWindow != guiApp.desktop && (window._isModal || window.style.interim))
1932             {
1933                Window master = window.master;
1934                Window rootWindow = master.rootWindow;
1935
1936                parentWindow = rootWindow.is3D ? (uint)rootWindow.parent.windowHandle : (uint)rootWindow.windowHandle;
1937
1938                // parentWindow = window.master.rootWindow.is3D ? window.master.rootWindow.parent.windowHandle : window.master.rootWindow.windowHandle;
1939             }
1940             if(window.style.showInTaskBar)
1941                parentWindow = (uint)null;
1942
1943             windowHandle = XCreateWindow(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), 
1944                0,0,1,1,0, depth, InputOutput, visual ? visual : CopyFromParent, 
1945                CWEventMask | CWOverrideRedirect | (visual ? (CWColormap | CWBorderPixel) : 0), &attributes);
1946
1947             if(parentWindow && window.interim)
1948             {
1949                //printf("Setting WM_TRANSIENT_FOR of %s to %s\n", window._class.name, window.master.rootWindow._class.name);
1950                XSetTransientForHint(xGlobalDisplay, windowHandle, parentWindow);
1951                //XFlush(xGlobalDisplay);
1952                //printf("Done.\n");
1953                //XChangeProperty(xGlobalDisplay, windowHandle, atoms[wm_transient_for], XA_WINDOW, 32, PropModeReplace, (unsigned char*)&parentWindow, 1);
1954             }
1955
1956             {
1957 #if defined(__APPLE__)
1958                Atom hints[2] =
1959                {
1960                   parentWindow ? atoms[_net_wm_window_type_popup_menu] : atoms[_net_wm_window_type_normal]
1961                };
1962                
1963                XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_window_type], XA_ATOM, 32,
1964                   PropModeReplace, (unsigned char*)&hints, 1);
1965 #else
1966                Atom hints[2] =
1967                {
1968                   parentWindow ? atoms[_net_wm_window_type_menu] : atoms[_net_wm_window_type_normal],
1969                   parentWindow ? atoms[_net_wm_window_type_popup_menu] : 0
1970                };
1971                XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_window_type], XA_ATOM, 32,
1972                   PropModeReplace, (unsigned char*)&hints, parentWindow ? 2 : 1);
1973 #endif
1974                {
1975                   XWMHints xwmHints;
1976                   xwmHints.flags = InputHint;
1977                   xwmHints.input = 0;
1978                   XSetWMHints(xGlobalDisplay, windowHandle, &xwmHints);
1979                }
1980                {
1981                   Atom protocols[2] = { atoms[wm_delete_window], atoms[wm_take_focus] };
1982                   XSetWMProtocols(xGlobalDisplay, windowHandle, protocols, 2);
1983                }
1984             }
1985          }
1986       }
1987
1988       if(!ic && im)
1989       {
1990          char fontString[1024] = "--helvetica-*-r-*-*-*-120-*-*-*-*-*-*,-misc-fixed-*-r-*-*-*-130-*-*-*-*-*-*";
1991          XPoint cursor_location = { 0, 0 };
1992          char **missing_charsets;
1993          int num_missing_charsets = 0;
1994          char *default_string;
1995          XFontSet fontset;
1996          XRectangle area = { 0, 0,  400, 400 };         
1997          XVaNestedList argList;
1998
1999          // sprintf(fontString, "-*-%s-*-r-*-*-*-%d-*-*-*-*-*-*", "Helvetica" /*window.font.faceName*/, (int)(window.font.size * 20));
2000          fontset = XCreateFontSet(xGlobalDisplay, fontString, &missing_charsets, &num_missing_charsets, &default_string);
2001          argList = XVaCreateNestedList(0,
2002                                        XNSpotLocation, &cursor_location, 
2003                                        //XNArea, &area,
2004                                        XNFontSet, fontset,/*
2005                                        XNForeground,
2006                                        WhitePixel(xGlobalDisplay, DefaultScreen(xGlobalDisplay)),
2007                                        XNBackground,
2008                                        BlackPixel(xGlobalDisplay, DefaultScreen(xGlobalDisplay)),*/
2009                                        NULL);
2010          ic = XCreateIC(im, XNInputStyle,
2011             XIMStatusNothing | XIMPreeditPosition,
2012             XNPreeditAttributes, argList,
2013             XNClientWindow, windowHandle, XNFocusWindow, windowHandle, 0);
2014          XFree(argList);
2015          // Should we free the fontset or not?
2016          // XFreeFontSet(xGlobalDisplay, fontset);
2017          if(ic)
2018             setICPosition = true;
2019          else
2020             ic = XCreateIC(im, XNInputStyle, XIMStatusNothing | XIMPreeditNothing, XNClientWindow, windowHandle, XNFocusWindow, windowHandle, 0);
2021       }
2022       if(ic)
2023       {
2024               XGetICValues(ic, XNFilterEvents, &mask, NULL);
2025               mask |= EVENT_MASK;
2026       }
2027       /*
2028       XSelectInput(xGlobalDisplay, windowHandle, mask);
2029
2030       if(capturedWindow == None && !restrictedWindow)
2031       {
2032          XGrabPointer(xGlobalDisplay, (int)windowHandle, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2033             GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
2034          XUngrabPointer(xGlobalDisplay, CurrentTime);
2035       }
2036       */
2037
2038       {
2039          if ( atoms[_motif_wm_hints] != None ) 
2040          {
2041             MWM_Hints hints
2042             {
2043                (window.nativeDecorations ? 0 : MWM_HINTS_DECORATIONS)|MWM_HINTS_FUNCTIONS,
2044                (window.hasClose ? MWM_FUNC_CLOSE : 0) |
2045                (window.hasMaximize ? MWM_FUNC_MAXIMIZE : 0) |
2046                (window.hasMinimize ? MWM_FUNC_MINIMIZE : 0) |
2047                ((window.moveable || ((BorderBits)window.borderStyle).fixed) ? MWM_FUNC_MOVE : 0) |
2048                (((BorderBits)window.borderStyle).sizable ? MWM_FUNC_RESIZE : 0),
2049                 0, 0, 0
2050             };
2051             XChangeProperty(xGlobalDisplay, windowHandle, atoms[_motif_wm_hints], atoms[_motif_wm_hints], 32,
2052                PropModeReplace, (unsigned char*)&hints, sizeof(hints)/4);
2053          }
2054          if(atoms[_net_wm_pid] != None)
2055          {
2056             int pid = getpid();
2057             // printf("Setting _NET_WM_PID to %d\n", pid); 
2058             XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_pid], XA_CARDINAL, 32,
2059                PropModeReplace, (unsigned char*)&pid, 1);            
2060          }
2061       }
2062       
2063       /*
2064       {
2065          Atom protocolsAtom = XInternAtom(xGlobalDisplay, "WM_PROTOCOLS", False);
2066          if ( protocolsAtom != None ) 
2067          {
2068             MWM_Hints hints = { MWM_HINTS_DECORATIONS|MWM_HINTS_FUNCTIONS, 0, 0, 0, 0 };
2069             XChangeProperty(xGlobalDisplay, windowHandle, atoms[_motif_wm_hints], atoms[_motif_wm_hints], 32,
2070                PropModeReplace, (unsigned char*)&hints, sizeof(hints)/4);
2071          }
2072       }*/
2073       // XFlush(xGlobalDisplay);
2074       window.windowData = XWindowData { visualInfo, ic };
2075       
2076       XSaveContext(xGlobalDisplay, windowHandle, windowContext, (XPointer)window);
2077
2078       XSelectInput(xGlobalDisplay, windowHandle, mask);
2079
2080       if(capturedWindow == None && !restrictedWindow)
2081       {
2082          XGrabPointer(xGlobalDisplay, (int)windowHandle, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2083             GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
2084          XUngrabPointer(xGlobalDisplay, CurrentTime);
2085       }
2086       return (void *)windowHandle;
2087    }
2088
2089    void DestroyRootWindow(Window window)
2090    {
2091       XEvent event;
2092
2093       XDeleteContext(xGlobalDisplay, (XID)window, windowContext); 
2094       XSaveContext(xGlobalDisplay, (int)window.windowHandle, windowContext, null);
2095       XDestroyWindow(xGlobalDisplay, (int)window.windowHandle);
2096       XSync(xGlobalDisplay, 0);
2097       while(XCheckWindowEvent(xGlobalDisplay, (int)window.windowHandle, 0xFFFFFFFF, &event));
2098       window.windowHandle = null;
2099       if(window.windowData)
2100       {
2101          XWindowData windowData = window.windowData;
2102          XFree(windowData.visual);
2103          if(windowData && windowData.ic)
2104             XDestroyIC(windowData.ic);
2105          delete windowData;
2106          // printf("Setting windowData for %s to null\n", window._class.name);
2107          window.windowData = null;
2108       }
2109       if(lastActive == window)
2110          delete lastActive;
2111    }
2112
2113    // -- Window manipulation ---
2114
2115    void SetRootWindowCaption(Window window, char * name)
2116    {
2117       if(window.windowHandle)
2118       {
2119          XChangeProperty(xGlobalDisplay, (int)window.windowHandle, atoms[_net_wm_name],
2120             atoms[utf8_string], 8, PropModeReplace, (byte *)name, name ? strlen(name) : 0);
2121          XChangeProperty(xGlobalDisplay, (int)window.windowHandle, atoms[wm_name],
2122             atoms[utf8_string], 8, PropModeReplace, (byte *)name, name ? strlen(name) : 0);
2123       }   
2124    }
2125
2126    void PositionRootWindow(Window window, int x, int y, int w, int h, bool move, bool resize)
2127    {
2128       //Logf("Position root window %s\n", window.name);
2129       if(!window.parent || !window.parent.display)
2130       {
2131 #if defined(__APPLE__)
2132          bool visible = window.visible;
2133          if(window.visible)
2134          {
2135             XMapWindow(xGlobalDisplay, (int)window.windowHandle);
2136             WaitForViewableWindow(window);
2137          }
2138 #endif
2139          if(window.state == minimized) return;
2140
2141          if(move && resize)
2142             XMoveResizeWindow(xGlobalDisplay, (int)window.windowHandle, x + desktopX, y + desktopY, w, h);
2143          else if(move)
2144             XMoveWindow(xGlobalDisplay, (int)window.windowHandle, x + desktopX, y + desktopY);
2145          else if(resize)
2146             XResizeWindow(xGlobalDisplay, (int)window.windowHandle, w, h);
2147 #if defined(__APPLE__)
2148 //         if(window.created && !visible)
2149   //          XUnmapWindow(xGlobalDisplay, (int)window.windowHandle);
2150 #endif
2151       }
2152    }
2153
2154    void OrderRootWindow(Window window, bool topMost)
2155    {
2156
2157    }
2158
2159    void SetRootWindowColor(Window window)
2160    {
2161
2162    }
2163
2164    void OffsetWindow(Window window, int * x, int * y)
2165    {
2166
2167    }
2168
2169    void UpdateRootWindow(Window window)
2170    {
2171       if(!window.parent || !window.parent.display)
2172       {
2173          if(window.visible)
2174          {
2175             Box box = window.box;
2176             box.left -= window.clientStart.x;
2177             box.top -= window.clientStart.y;
2178             box.right -= window.clientStart.x;
2179             box.bottom -= window.clientStart.y;
2180             // Logf("Update root window %s\n", window.name);
2181             window.Update(null);
2182             box.left   += window.clientStart.x;
2183             box.top    += window.clientStart.y;
2184             box.right  += window.clientStart.x;
2185             box.bottom += window.clientStart.y;
2186             window.UpdateDirty(box);
2187          }
2188       }
2189    }
2190
2191
2192    void SetRootWindowState(Window window, WindowState state, bool visible)
2193    {
2194       if(!window.parent || !window.parent.display)
2195       {
2196          //Logf("Set root window state %d %s\n", state, window.name);
2197          if(visible)
2198          {
2199             XMapWindow(xGlobalDisplay, (int)window.windowHandle);
2200 #if defined(__APPLE__)
2201             WaitForViewableWindow(window);
2202 #endif
2203             if(window.creationActivation == activate && state != minimized)
2204                ActivateRootWindow(window);
2205             
2206             if(state == minimized)
2207             {
2208                uint iconic = IconicState;
2209                /*
2210                XChangeProperty(xGlobalDisplay, window.windowHandle, atoms[_net_wm_state], XA_ATOM, 32,
2211                   PropModeReplace, (unsigned char*)&atoms[_net_wm_state_hidden], 1);
2212                */
2213                /*
2214                XChangeProperty(xGlobalDisplay, window.windowHandle, atoms[wm_state], XA_CARDINAL, 32,
2215                   PropModeReplace, &iconic, 1);
2216                */
2217                
2218                /*
2219                XClientMessageEvent event = { 0 };
2220                event.type = ClientMessage;
2221                event.message_type = atoms[_net_wm_state];
2222                event.display = xGlobalDisplay;
2223                event.serial = 0;
2224                event.window = window.windowHandle;
2225                event.send_event = 1;
2226                event.format = 32;
2227                event.data.l[0] = 2; // 1;
2228                event.data.l[1] = atoms[_net_wm_state_hidden];
2229                XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, &event);
2230                */
2231                /*
2232                XClientMessageEvent event = { 0 };
2233                event.type = ClientMessage;
2234                event.message_type = atoms[wm_state];
2235                event.display = xGlobalDisplay;
2236                event.window = window.windowHandle;
2237                event.send_event = 1;
2238                event.format = 32;
2239                event.data.l[0] = IconicState;
2240                XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, &event);
2241                */
2242
2243                // printf("Attempting to minimize %s\n", window._class.name);
2244                XIconifyWindow(xGlobalDisplay, (uint)window.windowHandle, DefaultScreen(xGlobalDisplay));
2245             }
2246             else
2247             {
2248                XMoveResizeWindow(xGlobalDisplay, 
2249                   (int)window.windowHandle, window.position.x + desktopX, window.position.y + desktopY, window.size.w, window.size.h);
2250             }
2251          }
2252          else
2253             XUnmapWindow(xGlobalDisplay, (int)window.windowHandle);
2254          //XFlush(xGlobalDisplay);
2255       }
2256    }
2257
2258    void FlashRootWindow(Window window)
2259    {
2260       XClientMessageEvent event = { 0 };
2261       // printf("Attempting to flash root window\n");
2262       event.type = ClientMessage;
2263       event.message_type = atoms[_net_wm_state];
2264       event.display = xGlobalDisplay;
2265       event.serial = 0;
2266       event.window = (uint)window.windowHandle;
2267       event.send_event = 1;
2268       event.format = 32;
2269       event.data.l[0] = 1;
2270       event.data.l[1] = atoms[_net_wm_state_demands_attention];
2271       XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
2272    }
2273
2274    void ActivateRootWindow(Window window)
2275    {
2276       if(!window.parent || !window.parent.display)
2277       {
2278          if(!window.style.hidden && window.created)
2279          {
2280             //printf("Activate root window %s\n", window._class.name);
2281             XRaiseWindow(xGlobalDisplay, (int)window.windowHandle);
2282             XMapWindow(xGlobalDisplay, (int)window.windowHandle);
2283             WaitForViewableWindow(window);
2284             if(atoms[_net_active_window])
2285             {
2286                XClientMessageEvent event = { 0 };
2287                event.type = ClientMessage;
2288                event.message_type = atoms[_net_active_window];
2289                event.display = xGlobalDisplay;
2290                event.serial = 0;
2291                event.window = (uint)window.windowHandle;
2292                event.send_event = 1;
2293                event.format = 32;
2294                event.data.l[0] = 0;
2295                
2296                //event.data.l[0] = 2;
2297                //event.data.l[1] = timeStamp;
2298                
2299
2300                //event.data.l[1] = atoms[_net_wm_user_time];
2301                //event.data.l[2] = activeWindow; //guiApp.desktop.activeChild.windowHandle;
2302                
2303 #ifdef _DEBUG
2304                //printf("(ActivateRootWindow) Setting _NET_ACTIVE_WINDOW for %s (%x)\n", window._class.name, window);
2305 #endif
2306                
2307                XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
2308 //#if defined(__APPLE__)
2309                XSetInputFocus(xGlobalDisplay, (int)window.windowHandle, RevertToPointerRoot, CurrentTime);
2310 //#endif
2311             }
2312             else
2313                XSetInputFocus(xGlobalDisplay, (int)window.windowHandle, RevertToPointerRoot, CurrentTime);
2314          }
2315       }
2316    }
2317
2318    // --- Mouse-based window movement ---
2319
2320    void StartMoving(Window window, int x, int y, bool fromKeyBoard)
2321    {
2322
2323    }
2324
2325    void StopMoving(Window window)
2326    {
2327
2328    }
2329
2330    // -- Mouse manipulation ---
2331
2332    void GetMousePosition(int *x, int *y)
2333    {
2334       int rootWindow, childWindow;
2335       int mx, my;
2336       unsigned int state;
2337       ((GuiApplication)__thisModule.application).Lock();
2338       //XLockDisplay(xGlobalDisplay);
2339       XQueryPointer(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), &childWindow, 
2340          &rootWindow, x, y, &mx, &my, &state);
2341       //XUnlockDisplay(xGlobalDisplay);
2342       ((GuiApplication)__thisModule.application).Unlock();
2343    }
2344
2345    void SetMousePosition(int x, int y)
2346    {
2347
2348    }
2349
2350    void SetMouseRange(Window window, Box box)
2351    {
2352       ((GuiApplication)__thisModule.application).Lock();
2353       //XLockDisplay(xGlobalDisplay);
2354       if(box && box.left > 0 && box.top > 0 && 
2355          box.right < guiApp.desktop.clientSize.w - 1 && box.bottom < guiApp.desktop.clientSize.h - 1)
2356       {
2357          if(!window.parent || !window.parent.display)
2358          {
2359             XMoveResizeWindow(xGlobalDisplay, confineWindow, box.left + desktopX, box.top + desktopY, 
2360                box.right - box.left + 1, box.bottom - box.top + 1);
2361       
2362             if(!restrictedWindow)
2363                XMapWindow(xGlobalDisplay, confineWindow);
2364
2365             XGrabPointer(xGlobalDisplay, (int) window.rootWindow.windowHandle, False,
2366                ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2367                GrabModeAsync, confineWindow, fullScreenMode ? nullCursor : None, CurrentTime);
2368
2369             restrictedWindow = window;
2370          }
2371       }
2372       else if(restrictedWindow)
2373       {
2374          if(capturedWindow != None)
2375          {
2376             XGrabPointer(xGlobalDisplay, (int)capturedWindow,
2377                False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2378                GrabModeAsync, None, fullScreenMode ? nullCursor : None, CurrentTime);
2379          }
2380          else
2381             XUngrabPointer(xGlobalDisplay, CurrentTime);
2382          
2383          if(restrictedWindow)
2384             XUnmapWindow(xGlobalDisplay, confineWindow);
2385
2386          restrictedWindow = null;
2387       }
2388       //XUnlockDisplay(xGlobalDisplay);
2389       ((GuiApplication)__thisModule.application).Unlock();
2390    }
2391
2392    void SetMouseCapture(Window window)
2393    {
2394       //*XLockDisplay(xGlobalDisplay);
2395       if(window)
2396       {
2397          if(!window.parent || !window.parent.display)
2398          {
2399             XGrabPointer(xGlobalDisplay, (int)window.windowHandle,
2400                False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2401                GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
2402
2403             capturedWindow = (X11Window) window.windowHandle;
2404          }
2405       }
2406       else if(capturedWindow != None)
2407       {
2408          if(restrictedWindow)
2409             XGrabPointer(xGlobalDisplay, (int) restrictedWindow.rootWindow.windowHandle, False, 
2410                ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2411                GrabModeAsync, confineWindow, fullScreenMode ? nullCursor : None, CurrentTime);
2412          else
2413             XUngrabPointer(xGlobalDisplay, CurrentTime);
2414          capturedWindow = None;
2415       }
2416       //*XUnlockDisplay(xGlobalDisplay);
2417    }
2418
2419    // -- Mouse cursor ---
2420
2421    void SetMouseCursor(int cursor)
2422    {
2423       //*XLockDisplay(xGlobalDisplay);
2424       if(cursor == -1)
2425       {
2426          XDefineCursor(xGlobalDisplay, (int) guiApp.desktop.windowHandle, nullCursor);
2427       }
2428       //*XUnlockDisplay(xGlobalDisplay);
2429    }
2430
2431    // --- Caret ---
2432
2433    void SetCaret(int x, int y, int size)
2434    {
2435       Window caretOwner = guiApp.caretOwner;
2436       Window window = caretOwner ? caretOwner.rootWindow : null;
2437       if(window && window.windowData && setICPosition)
2438       {
2439          XWindowData windowData = window.windowData;
2440          if(windowData && windowData.ic)
2441          {
2442             XPoint cursor_location =
2443             {
2444                (short)(caretOwner.caretPos.x - caretOwner.scroll.x + caretOwner.absPosition.x - window.absPosition.x),
2445                (short)(caretOwner.caretPos.y - caretOwner.scroll.y + caretOwner.absPosition.y - window.absPosition.y)
2446             };
2447             XVaNestedList argList = XVaCreateNestedList(0, XNSpotLocation, &cursor_location, NULL);
2448             XSetICValues(windowData.ic, XNPreeditAttributes, argList, 0);
2449          }
2450       }
2451    }  
2452
2453    void ClearClipboard()
2454    {
2455       //*XLockDisplay(xGlobalDisplay);
2456       if(clipBoardData)
2457       {
2458          delete clipBoardData;
2459         XSetSelectionOwner(xGlobalDisplay, atoms[clipboard], None, CurrentTime);
2460       }
2461       //*XUnlockDisplay(xGlobalDisplay);
2462    }
2463
2464    bool AllocateClipboard(ClipBoard clipBoard, uint size)
2465    {
2466       bool result = false;
2467       if((clipBoard.text = new0 byte[size]))
2468          result = true;   
2469       return result;
2470    }
2471
2472    bool SaveClipboard(ClipBoard clipBoard)
2473    {
2474       bool result = false;
2475       //*XLockDisplay(xGlobalDisplay);
2476       if(clipBoard.text)
2477       {
2478          Window rootWindow = guiApp.desktop;
2479          if(!fullScreenMode) 
2480          {
2481             for(rootWindow = rootWindow.children.first; 
2482                rootWindow && !rootWindow.windowHandle; 
2483                rootWindow = rootWindow.next);
2484          }
2485          if(clipBoardData)
2486             delete clipBoardData;
2487          else if(rootWindow)
2488            XSetSelectionOwner(xGlobalDisplay, atoms[clipboard], 
2489                (int) rootWindow.windowHandle, CurrentTime);
2490          clipBoardData = clipBoard.text;
2491          clipBoard.text = null;
2492          result = true;
2493       }
2494       //*XUnlockDisplay(xGlobalDisplay);
2495       return result;
2496    }
2497
2498    bool LoadClipboard(ClipBoard clipBoard)
2499    {
2500       bool result = false;
2501
2502       //*XLockDisplay(xGlobalDisplay);
2503       // The data is inside this client...
2504       if(clipBoardData)
2505       {
2506          clipBoard.text = new char[strlen(clipBoardData)+1];
2507          strcpy(clipBoard.text, clipBoardData);
2508          result = true;
2509       }
2510       // The data is with another client...
2511       else
2512       {
2513          Window rootWindow = guiApp.desktop;
2514          if(!fullScreenMode)
2515          {
2516             for(rootWindow = rootWindow.children.first; 
2517                rootWindow && !rootWindow.windowHandle; 
2518                rootWindow = rootWindow.next);
2519          }
2520          if(rootWindow)
2521          {
2522             int selAtom = atoms[clipboard];
2523             int owner = XGetSelectionOwner(xGlobalDisplay, selAtom);
2524             if(owner != None)
2525             {
2526                int atom;
2527                for(atom = atoms[utf8_string]; atom; atom = ((atom == atoms[utf8_string]) ? XA_STRING : 0))
2528                {
2529                   XEvent e;
2530                   XConvertSelection(xGlobalDisplay, selAtom, atom, atoms[app_selection] /*None*/, (int) rootWindow.windowHandle, CurrentTime);
2531                   XIfEvent(xGlobalDisplay, (XEvent *) &e, EventChecker, (void *)SelectionNotify);
2532                   if(e.type == SelectionNotify)
2533                   {
2534                      XSelectionEvent * selection = (XSelectionEvent *) &e;
2535                      //printf("Got a SelectionNotify with %d (%s)\n", selection->_property, XGetAtomName(xGlobalDisplay, selection->_property));
2536                      byte *data;
2537                      uint len, size = 0, dummy;
2538                      Atom type;
2539                      int format;
2540                      XGetWindowProperty(xGlobalDisplay, (int) rootWindow.windowHandle, selection->_property ? selection->_property : atom, 0, 0, 0, AnyPropertyType, &type, &format, &len, &size, &data);
2541                      if(size > 0)
2542                      {
2543                         if(XGetWindowProperty(xGlobalDisplay, (int) rootWindow.windowHandle, selection->_property ? selection->_property : atom, 0,size,0,
2544                               AnyPropertyType, &type,&format,&len, &dummy, &data) == Success)
2545                         {
2546                            clipBoard.text = new char[size+1];
2547                            strncpy(clipBoard.text, data, size);
2548                            clipBoard.text[size] = '\0';
2549                            XFree(data);
2550                            result = true;
2551                            break;
2552                         }
2553                      }
2554                   }
2555                }
2556             }
2557          }
2558       }
2559       //*XUnlockDisplay(xGlobalDisplay);
2560       return result;
2561    }
2562
2563    void UnloadClipboard(ClipBoard clipBoard)
2564    {
2565       delete clipBoard.text;
2566    }
2567
2568    // --- State based input ---
2569
2570    bool AcquireInput(Window window, bool state)
2571    {
2572       return false;
2573    }
2574
2575    bool GetMouseState(MouseButtons * buttons, int * x, int * y)
2576    {
2577       bool result = false;
2578       if(x) *x = 0;
2579       if(y) *y = 0;
2580       return result;
2581    }
2582
2583    bool GetJoystickState(int device, Joystick joystick)
2584    {
2585       bool result = false;
2586    #if defined(__linux__)   
2587       if(joystick && device < 4)
2588       {
2589          struct JS_DATA_TYPE js = { 0 };
2590          memset(joystick, 0, sizeof(Joystick));
2591          if(joystickFD[device] && read(joystickFD[device], &js, JS_RETURN) == JS_RETURN)
2592          {
2593             joystick.buttons = js.buttons;
2594             joystick.x = js.x - 128;
2595             joystick.y = js.y - 128;
2596             result = true;
2597          }
2598       }
2599    #endif   
2600       return result;
2601    }
2602
2603    bool GetKeyState(Key key)
2604    {
2605       int keyState = 0;
2606       return keyState;
2607    }
2608
2609    void SetTimerResolution(uint hertz)
2610    {
2611       timerDelay = hertz ? (1000000 / hertz) : MAXINT;
2612       /*
2613       hiResTimer.Stop();
2614       if(hertz)
2615       {
2616          hiResTimer.delay = 1000000 / hertz;
2617          hiResTimer.Create();
2618       }
2619       */
2620    }  
2621
2622    bool SetIcon(Window window, BitmapResource resource)
2623    {
2624       if(resource)
2625       {
2626          Bitmap bitmap { };
2627          if(bitmap.Load(resource.fileName, null, null))
2628          {
2629             uint * icon = new uint[2 + bitmap.width * bitmap.height];
2630             bitmap.Convert(null, pixelFormat888, null);
2631             icon[0] = bitmap.width;
2632             icon[1] = bitmap.height;
2633             memcpy(icon + 2, bitmap.picture, bitmap.width * bitmap.height * 4);
2634             XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[_net_wm_icon],
2635                           XA_CARDINAL,32,PropModeReplace, (byte *)icon, 2+bitmap.width*bitmap.height);
2636            delete icon;
2637          }
2638          delete bitmap;
2639       }
2640       return true;
2641    }
2642 }
2643
2644 default dllexport void * __attribute__((stdcall)) IS_XGetDisplay()
2645 {
2646    return xGlobalDisplay;
2647 }
2648
2649 default dllexport void * __attribute__((stdcall)) IS_XGetWindow(Window window)
2650 {
2651    return window.windowHandle ? window.windowHandle : window.rootWindow.windowHandle;
2652 }
2653
2654 #endif