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