1 namespace gui::drivers;
4 #if !defined(ECERE_VANILLA) && !defined(ECERE_NO3D) && !defined(ECERE_NOGL)
5 import "OpenGLDisplayDriver"
8 #if (defined(__unix__) || defined(__APPLE__)) && !defined(ECERE_MINIGLX) && !defined(__EMSCRIPTEN__)
13 #define property _property
18 #include <linux/joystick.h>
20 #include <sys/param.h>
23 #include <sys/select.h>
25 #if defined(__APPLE__)
27 #include <mach/mach.h>
28 #include <mach/task.h>
29 #include <mach/semaphore.h>
32 #include <semaphore.h>
39 #define Window X11Window
40 #define Cursor X11Cursor
42 #define Display X11Display
44 #define KeyCode X11KeyCode
45 #define Picture X11Picture
48 #define _XTYPEDEF_BOOL
51 #include <X11/Xatom.h>
53 #if !defined(__EMSCRIPTEN__)
54 #include <X11/Xresource.h>
56 #include <X11/Xutil.h>
57 #include <X11/XKBlib.h>
58 #include <X11/keysym.h>
59 #include <X11/cursorfont.h>
61 #if !defined(ECERE_NO3D) && !defined(ECERE_NOGL)
62 #if defined(__EMSCRIPTEN__)
68 #if !defined(__EMSCRIPTEN__)
69 #include <X11/extensions/Xrender.h>
71 #include <X11/extensions/XShm.h>
89 import "XDisplayDriver"
91 // These are the events we care about
92 #define EVENT_MASK StructureNotifyMask | \
93 ButtonPressMask | ButtonReleaseMask | PointerMotionMask | \
94 KeyPressMask | KeyReleaseMask | ExposureMask | FocusChangeMask | \
97 void * xGlobalDisplay;
100 static XContext windowContext;
101 static Window lastActive;
103 static char * clipBoardData;
105 static Thread /* xThread, */ timerThread;
106 static bool xTerminate;
107 static Semaphore xSemaphore { };
108 static Mutex xMutex { };
109 static bool fullScreenMode;
110 static int desktopX = 0, desktopY = 0, desktopW = 0, desktopH = 0;
111 X11Window confineWindow;
112 static X11Cursor nullCursor;
113 static X11Window capturedWindow = None;
114 static Window restrictedWindow = null;
115 static bool gotAnXEvent = false;
116 //static XEvent xEvent;
117 static int joystickFD[4];
118 static X11Window activeWindow;
119 static X11Cursor systemCursors[SystemCursor];
121 static Window acquiredInputWindow;
122 static Point acquireStart;
123 static Point lastMouse;
124 static MouseButtons buttonsState;
126 static bool keyStates[KeyCode];
128 static enum NETWMStateAction { remove = 0, add = 1, toggle = 2 };
130 static enum AtomIdents
132 clipboard, multiple, targets, utf8_string, wm_delete_window, wm_hints, wm_name, wm_protocols, wm_state, wm_take_focus, wm_transient_for,
134 _net_active_window, _net_current_desktop, _net_number_of_desktops, _net_wm_icon, _net_wm_name, _net_wm_pid,
135 _net_wm_state, _net_wm_state_demands_attention, _net_wm_state_hidden, _net_wm_user_time, _net_wm_window_type,
136 _net_wm_window_type_desktop, _net_wm_window_type_dialog, _net_wm_window_type_dock, _net_wm_window_type_dropdown_menu,
137 _net_wm_window_type_menu, _net_wm_window_type_normal, _net_wm_window_type_popup_menu, _net_wm_window_type_splash,
138 _net_wm_window_type_toolbar, _net_wm_window_type_utility, _net_workarea, _net_frame_extents, _net_request_frame_extents,
139 _net_wm_state_maximized_vert, _net_wm_state_maximized_horz, _net_wm_state_modal, app_selection, _net_supported,
140 _net_wm_state_skip_taskbar, _net_wm_state_fullscreen, _net_wm_state_above, capsLock, numLock, scrollLock
143 static Atom atoms[AtomIdents];
144 static bool atomsSupported[AtomIdents];
146 static const char *atomNames[AtomIdents] = {
147 "CLIPBOARD", //clipboard
148 "MULTIPLE", //multiple
150 "UTF8_STRING", //utf8_string
151 "WM_DELETE_WINDOW", //wm_delete_window
152 "WM_HINTS", //wm_hints
154 "WM_PROTOCOLS", //wm_protocols
155 "WM_STATE", //wm_state
156 "WM_TAKE_FOCUS", //wm_take_focus
157 "WM_TRANSIENT_FOR", //wm_transient_for
158 "_MOTIF_WM_HINTS", //_motif_wm_hints
159 "_NET_ACTIVE_WINDOW", //_net_active_window
160 "_NET_CURRENT_DESKTOP", //_net_current_desktop
161 "_NET_NUMBER_OF_DESKTOPS", //_net_number_of_desktops
162 "_NET_WM_ICON", //_net_wm_icon
163 "_NET_WM_NAME", //_net_wm_name
164 "_NET_WM_PID", //_net_wm_pid
165 "_NET_WM_STATE", //_net_wm_state
166 "_NET_WM_STATE_DEMANDS_ATTENTION", //_net_wm_state_demands_attention
167 "_NET_WM_STATE_HIDDEN", //_net_wm_state_hidden
168 "_NET_WM_USER_TIME", //_net_wm_user_time
169 "_NET_WM_WINDOW_TYPE", //_net_wm_window_type
170 "_NET_WM_WINDOW_TYPE_DESKTOP", //_net_wm_window_type_desktop
171 "_NET_WM_WINDOW_TYPE_DIALOG", //_net_wm_window_type_dialog
172 "_NET_WM_WINDOW_TYPE_DOCK", //_net_wm_window_type_dock
173 "_NET_WM_WINDOW_TYPE_DROPDOWN_MENU", //_net_wm_window_type_dropdown_menu
174 "_NET_WM_WINDOW_TYPE_MENU", //_net_wm_window_type_menu
175 "_NET_WM_WINDOW_TYPE_NORMAL", //_net_wm_window_type_normal
176 "_NET_WM_WINDOW_TYPE_POPUP_MENU", //_net_wm_window_type_popup_menu
177 "_NET_WM_WINDOW_TYPE_SPLASH", //_net_wm_window_type_splash
178 "_NET_WM_WINDOW_TYPE_TOOLBAR", //_net_wm_window_type_toolbar
179 "_NET_WM_WINDOW_TYPE_UTILITY", //_net_wm_window_type_utility
180 "_NET_WORKAREA", //_net_workarea
181 "_NET_FRAME_EXTENTS", // _net_frame_extents
182 "_NET_REQUEST_FRAME_EXTENTS", // _net_request_frame_extents
183 "_NET_WM_STATE_MAXIMIZED_VERT", // _net_wm_state_maximized_vert
184 "_NET_WM_STATE_MAXIMIZED_HORZ", // _net_wm_state_maximized_horz
185 "_NET_WM_STATE_MODAL", // _net_wm_state_modal
188 "_NET_WM_STATE_SKIP_TASKBAR",
189 "_NET_WM_STATE_FULLSCREEN",
190 "_NET_WM_STATE_ABOVE",
196 _NET_WM_STATE_STICKY, ATOM
197 _NET_WM_STATE_SHADED, ATOM
198 _NET_WM_STATE_SKIP_PAGER, ATOM
199 _NET_WM_STATE_BELOW, ATOM
202 static bool autoRepeatDetectable;
203 static bool setICPosition;
205 PixelFormat xSystemPixelFormat;
206 Visual * xSystemVisual;
209 static void SetNETWMState(X11Window windowHandle, bool throughRoot, NETWMStateAction action, Atom atom1, Atom atom2)
211 if(atomsSupported[_net_wm_state])
214 unsigned long count, fill;
217 /*uint state = WithdrawnState;
219 if(XGetWindowProperty(xGlobalDisplay, windowHandle, atoms[wm_state], 0, 3, False,
220 atoms[wm_state], &type, &format, &count, &fill, &data) == Success && count)
222 state = *(uint *)data;
225 if(!throughRoot) //state == WithdrawnState)
227 // We need to handle modifying these ourselves for withdrawn windows...
230 Atom values[2] = { atom1, atom2 };
231 XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_state], XA_ATOM,
232 32, PropModeAppend, (byte *)values, atom2 ? 2 : 1);
234 else if(XGetWindowProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_state], 0, 32, False,
235 XA_ATOM, &type, &format, &count, &fill, &data) == Success)
237 Atom * values = (Atom *) data;
239 for (i = 0; i < count; i++)
241 if(values[i] == atom1 || (atom2 && values[i] == atom2))
244 memmove(values + i, values + i + 1, sizeof(Atom) * (count - i - 1));
249 XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_state], XA_ATOM, 32, PropModeReplace, (byte *)values, (int)count);
255 XClientMessageEvent event = { 0 };
256 event.type = ClientMessage;
257 event.message_type = atoms[_net_wm_state];
258 event.display = xGlobalDisplay;
260 event.window = windowHandle;
261 event.send_event = 1;
263 event.data.l[0] = action;
264 event.data.l[1] = atom1;
265 event.data.l[2] = atom2;
266 XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false,
267 SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
273 static X11Time timeStamp;
275 class XWindowData : struct
278 XVisualInfo * visual;
283 bool gotFrameExtents;
284 bool currentlyVisible;
287 bool XGetBorderWidths(Window window, Box box)
289 XWindowData windowData = window.windowData;
292 if(window.state == maximized)
293 box = { 0, 0, 0, 0 };
295 box = windowData.decor;
301 static Visual * FindFullColorVisual(X11Display *dpy, int * depth)
304 XVisualInfo *vinfo_ret;
307 vinfo._class = TrueColor;
308 vinfo_ret = XGetVisualInfo(dpy, VisualClassMask, &vinfo, &numitems);
314 if(vinfo_ret[numitems-1].depth > maxdepth)
315 maxdepth = vinfo_ret[numitems-1].depth;
318 XFree((void *) vinfo_ret);
321 if(XMatchVisualInfo(dpy, DefaultScreen(dpy), maxdepth, TrueColor, &vinfo))
331 static void RepositionDesktop(bool updateChildren)
335 Screen * x_screen = XDefaultScreenOfDisplay(xGlobalDisplay);
340 unsigned long len, fill;
342 static double lastTime = 0, time;
345 if(desktopW && desktopH && time - lastTime < 1.5) return;
348 w = XDisplayWidth(xGlobalDisplay, DefaultScreen(xGlobalDisplay));
349 h = XDisplayHeight(xGlobalDisplay, DefaultScreen(xGlobalDisplay));
350 x_root = XRootWindowOfScreen(x_screen);
352 if(atomsSupported[_net_number_of_desktops])
354 if(XGetWindowProperty(xGlobalDisplay, x_root, atoms[_net_number_of_desktops], 0, 1, False,
355 XA_CARDINAL, &type, &format, &len, &fill,
358 printf("cant get xa desktops property\n");
365 desktops = (int)*(long *)data;
367 printf("_NET_NUMBER_OF_DESKTOPS is %d\n", desktops);
374 if(atomsSupported[_net_current_desktop])
376 if(XGetWindowProperty(xGlobalDisplay, x_root, atoms[_net_current_desktop], 0, 1, False,
377 XA_CARDINAL, &type, &format, &len, &fill,
380 printf("cant get xa current property\n");
385 current = (int)*(long *)data;
389 //printf("_NET_CURRENT_DESKTOP is %d\n", current);
392 if(atomsSupported[_net_workarea])
396 if(XGetWindowProperty(xGlobalDisplay, x_root, atoms[_net_workarea], 0, (4 * 32),
397 False, AnyPropertyType, &type, &format, &len,
398 &fill, &data) != Success)
400 //printf("warning\n");
404 if(type == None || format == 0)
416 workareas = (long *)data;
418 x = (int)workareas[current * 4];
419 y = (int)workareas[current * 4 + 1];
420 w = (int)workareas[current * 4 + 2];
421 h = (int)workareas[current * 4 + 3];
423 //printf("_NET_WORKAREA is x = %d, y = %d, w = %d, h = %d\n", x, y, w, h);
427 // printf("Work Area width: %d, height %d\n", w, h);
430 if(desktopX != x || desktopY != y || desktopW != w || desktopH != h)
433 // Don't change the desktop area if another fullscreen application is running
434 // (Attemps to solve the debugging IDE being re-activated while switching debugged app between fullscreen/windowed on Cinnamon)
435 if(XGetWindowProperty(xGlobalDisplay, x_root, atoms[_net_active_window], 0, 32,
436 False, AnyPropertyType, &type, &format, &len,
437 &fill, &data) == Success && data)
439 X11Window active = *(long *)data;
441 if(XGetWindowProperty(xGlobalDisplay, active, atoms[_net_wm_state], 0, 32, False,
442 XA_ATOM, &type, &format, &len, &fill, &data) == Success)
444 Atom * values = (Atom *) data;
446 for (i = 0; i < len; i++)
448 if(values[i] == atoms[_net_wm_state_fullscreen])
459 guiApp.SetDesktopPosition(x, y, w, h, updateChildren);
468 /****************************************************************************
469 /// PRIVATE UTILITY FUNCTIONS /////////////
470 ****************************************************************************/
471 // --- Keyboard Input ---
472 #define KEYCODE_HOME 0x59
473 #define KEYCODE_UP 0x5A
474 #define KEYCODE_PGUP 0x5B
475 #define KEYCODE_LEFT 0x5C
476 #define KEYCODE_RIGHT 0x5E
477 #define KEYCODE_END 0x5F
478 #define KEYCODE_DOWN 0x60
479 #define KEYCODE_PGDWN 0x61
480 #define KEYCODE_INS 0x62
481 #define KEYCODE_DEL 0x63
482 #define KEYCODE_SLASH 0x68
485 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit;
486 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyUp;
487 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyDown;
488 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit;
489 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMouseMove;
490 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftDoubleClick;
491 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonDown;
492 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonUp;
493 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleDoubleClick;
494 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonDown;
495 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonUp;
496 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightDoubleClick;
497 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonDown;
498 extern int __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonUp;
501 static bool ProcessKeyMessage(Window window, uint keyCode, int release, XKeyEvent * event)
506 KeySym keysym = NoSymbol;
508 static long bufsize = 16;
509 static char *buf = NULL;
510 XWindowData windowData = window.windowData;
513 if(window.destroyed) return result;
515 // Logf("Got 0x%x (%d)\n", keyCode, key);
517 // Translate the key code
520 //Logf("Got 0x%x (%d)\n", key, key);
524 case KEYCODE_HOME: key = home; break;
525 case KEYCODE_UP: key = up; break;
526 case KEYCODE_PGUP: key = pageUp; break;
527 case KEYCODE_LEFT: key = left; break;
528 case KEYCODE_RIGHT: key = right; break;
529 case KEYCODE_END: key = end; break;
530 case KEYCODE_DOWN: key = down; break;
531 case KEYCODE_PGDWN: key = pageDown; break;
532 case KEYCODE_INS: key = insert; break;
533 case KEYCODE_DEL: key = del; break;
534 case KEYCODE_SLASH: key = keyPadSlash; break;
537 ch = (byte)Interface::TranslateKey(key, event->state & ShiftMask);
541 Logf("Key up: %3d (%2x)\n", key, key);
543 Logf("Key down: %3d (%2x)\n", key, key);
547 buf = malloc((uint)bufsize);
549 // TOCHECK: X*LookupString man page says we shouldn't invoke it for non KeyPress events
550 if(windowData && windowData.ic) // && event->type == KeyPress)
553 #ifdef X_HAVE_UTF8_STRING
554 #define LookupString Xutf8LookupString
556 #define LookupString XmbLookupString
558 buflength = LookupString(windowData.ic, event, buf, (int)bufsize, &keysym, &status);
559 if(status == XBufferOverflow)
561 buf = realloc(buf, (uint)(bufsize = buflength));
562 buflength = LookupString(windowData.ic, event, buf, (int)bufsize, &keysym, &status);
564 if(status != XLookupKeySym && status != XLookupBoth && release == 1)
565 keysym = XLookupKeysym(event, 0);
569 keysym = XLookupKeysym(event, 0);
572 // printf("Got keysym %d (%x)\n", keysym, keysym);
573 if(keysym != NoSymbol) //status == XLookupKeySym || status == XLookupBoth)
577 case XK_BackSpace: key = backSpace; break;
578 case XK_ISO_Left_Tab: key = tab; break;
579 case XK_Tab: key = tab; break;
582 case XK_Return: key = enter; break;
583 case XK_Pause: key = pauseBreak; break;
584 case XK_Scroll_Lock: key = scrollLock; break;
585 case XK_Sys_Req: key = printScreen; break;
586 case XK_Escape: key = escape; break;
587 case XK_Delete: key = del; break;
589 case XK_Home: key = home; break;
590 case XK_Left: key = left; break;
591 case XK_Up: key = up; break;
592 case XK_Right: key = right; break;
593 case XK_Down: key = down; break;
595 case XK_Page_Up: key = pageUp; break;
597 case XK_Page_Down: key = pageDown; break;
598 case XK_End: key = end; break;
604 case XK_Insert: key = insert; break;
611 case XK_Help: key = insert; break;
613 case XK_Break: key = Key { pauseBreak, ctrl = true }; break;
615 case XK_Mode_switch: key = leftAlt; break;
617 // case XK_script_switch:
618 case XK_Num_Lock: key = numLock; break;
622 case XK_KP_Enter: key = keyPadEnter; break;
627 case XK_KP_Home: key = keyPadHome; break;
628 case XK_KP_Left: key = keyPadLeft; break;
629 case XK_KP_Up: key = keyPadUp; break;
630 case XK_KP_Right: key = keyPadRight; break;
631 case XK_KP_Down: key = keyPadDown; break;
633 case XK_KP_Page_Up: key = keyPadPageUp; break;
635 case XK_KP_Page_Down:key = keyPadPageDown; break;
636 case XK_KP_End: key = keyPadEnd; break;
638 case XK_KP_Insert: key = keyPadInsert; break;
639 case XK_KP_Delete: key = keyPadDelete; break;
641 case XK_KP_Multiply: key = keyPadStar; break;
642 case XK_KP_Add: key = keyPadPlus; break;
643 case XK_KP_Separator:key = keyPadDelete; break;
644 case XK_KP_Subtract: key = keyPadMinus; break;
645 // case XK_KP_Decimal:
646 case XK_KP_Divide: key = keyPadSlash; break;
648 case XK_KP_0: key = keyPad0; break;
649 case XK_KP_1: key = keyPad1; break;
650 case XK_KP_2: key = keyPad2; break;
651 case XK_KP_3: key = keyPad3; break;
652 case XK_KP_4: key = keyPad4; break;
653 case XK_KP_5: key = keyPad5; break;
654 case XK_KP_6: key = keyPad6; break;
655 case XK_KP_7: key = keyPad7; break;
656 case XK_KP_8: key = keyPad8; break;
657 case XK_KP_9: key = keyPad9; break;
659 case XK_F1: key = f1; break;
660 case XK_F2: key = f2; break;
661 case XK_F3: key = f3; break;
662 case XK_F4: key = f4; break;
663 case XK_F5: key = f5; break;
664 case XK_F6: key = f6; break;
665 case XK_F7: key = f7; break;
666 case XK_F8: key = f8; break;
667 case XK_F9: key = f9; break;
668 case XK_F10: key = f10; break;
669 case XK_F11: key = f11; break;
671 case XK_F12: key = f12; break;
721 case XK_Shift_L: key = leftShift; break;
722 case XK_Shift_R: key = rightShift; break;
723 case XK_Control_L: key = leftControl; break;
724 case XK_Control_R: key = rightControl; break;
725 case XK_Caps_Lock: key = capsLock; break;
726 // case XK_Shift_Lock:
729 case XK_Alt_L: key = leftAlt; break;
730 case XK_Alt_R: key = rightAlt; break;
736 case XK_space: key = space; break;
737 case XK_exclam: key = bang; break;
738 case XK_quotedbl: key = doubleQuote; break;
739 case XK_numbersign: key = pound; break;
740 case XK_dollar: key = dollar; break;
741 case XK_percent: key = percent; break;
742 case XK_ampersand: key = ampersand; break;
743 case XK_apostrophe: key = quote; break;
744 // case XK_quoteright: key = quote; break;
745 case XK_parenleft: key = leftParanthesis; break;
746 case XK_parenright: key = rightParanthesis; break;
747 case XK_asterisk: key = star; break;
748 case XK_plus: key = plus; break;
749 case XK_comma: key = comma; break;
750 case XK_minus: key = minus; break;
751 case XK_period: key = period; break;
752 case XK_slash: key = slash; break;
753 case XK_0: key = k0; break;
754 case XK_1: key = k1; break;
755 case XK_2: key = k2; break;
756 case XK_3: key = k3; break;
757 case XK_4: key = k4; break;
758 case XK_5: key = k5; break;
759 case XK_6: key = k6; break;
760 case XK_7: key = k7; break;
761 case XK_8: key = k8; break;
762 case XK_9: key = k9; break;
763 case XK_colon: key = colon; break;
764 case XK_semicolon: key = semicolon; break;
765 case XK_less: key = smallerThan; break;
766 case XK_equal: key = equal; break;
767 case XK_greater: key = greaterThan; break;
768 case XK_question: key = questionMark; break;
769 case XK_at: key = ampersand; break;
770 case XK_A: key = a; break;
771 case XK_B: key = b; break;
772 case XK_C: key = c; break;
773 case XK_D: key = d; break;
774 case XK_E: key = e; break;
775 case XK_F: key = f; break;
776 case XK_G: key = g; break;
777 case XK_H: key = h; break;
778 case XK_I: key = i; break;
779 case XK_J: key = j; break;
780 case XK_K: key = k; break;
781 case XK_L: key = l; break;
782 case XK_M: key = m; break;
783 case XK_N: key = n; break;
784 case XK_O: key = o; break;
785 case XK_P: key = p; break;
786 case XK_Q: key = q; break;
787 case XK_R: key = r; break;
788 case XK_S: key = s; break;
789 case XK_T: key = t; break;
790 case XK_U: key = u; break;
791 case XK_V: key = v; break;
792 case XK_W: key = w; break;
793 case XK_X: key = x; break;
794 case XK_Y: key = y; break;
795 case XK_Z: key = z; break;
796 case XK_bracketleft: key = leftBracket; break;
797 case XK_backslash: key = backSlash; break;
798 case XK_bracketright: key = rightBracket; break;
799 case XK_asciicircum: key = circumflex; break;
800 case XK_underscore: key = underscore; break;
801 // case XK_grave: key = backQuote; break;
802 case XK_quoteleft: key = backQuote; break;
803 case XK_a: key = a; break;
804 case XK_b: key = b; break;
805 case XK_c: key = c; break;
806 case XK_d: key = d; break;
807 case XK_e: key = e; break;
808 case XK_f: key = f; break;
809 case XK_g: key = g; break;
810 case XK_h: key = h; break;
811 case XK_i: key = i; break;
812 case XK_j: key = j; break;
813 case XK_k: key = k; break;
814 case XK_l: key = l; break;
815 case XK_m: key = m; break;
816 case XK_n: key = n; break;
817 case XK_o: key = o; break;
818 case XK_p: key = p; break;
819 case XK_q: key = q; break;
820 case XK_r: key = r; break;
821 case XK_s: key = s; break;
822 case XK_t: key = t; break;
823 case XK_u: key = u; break;
824 case XK_v: key = v; break;
825 case XK_w: key = w; break;
826 case XK_x: key = x; break;
827 case XK_y: key = y; break;
828 case XK_z: key = z; break;
829 case XK_braceleft: key = leftBracket; break;
830 case XK_bar: key = pipe; break;
831 case XK_braceright: key = rightBracket; break;
832 case XK_asciitilde: key = tilde; break;
837 ch = (byte)Interface::TranslateKey(key, (event->state & ShiftMask) != 0);
838 // 127 is delete, we don't treat that as a character (Use (SmartKey)key == del)
839 if(ch == 128 || ch == 127) ch = 0;
842 if(keysym == XK_ISO_Left_Tab)
844 if(key != leftShift && key != rightShift && event->state & ShiftMask)
846 if(key != leftControl && key != rightControl && event->state & ControlMask)
848 if(key != leftAlt && key != rightAlt && event->state & Mod1Mask)
850 if(fullScreenMode && key == tab)
852 XUngrabKeyboard(xGlobalDisplay, CurrentTime);
853 guiApp.SetAppFocus(false);
854 SetNETWMState((X11Window)window.windowHandle, true, remove, atoms[_net_wm_state_fullscreen], 0);
855 XIconifyWindow(xGlobalDisplay, (X11Window)window.windowHandle, DefaultScreen(xGlobalDisplay));
856 if(acquiredInputWindow)
857 XInterface::SetMousePosition(guiApp.acquiredMouseX, guiApp.acquiredMouseY);
863 if(key != leftAlt && key != rightAlt && event->state & (1<<13))
871 // 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);
878 if(key < KeyCode::enumSize)
879 keyStates[key] = false;
880 if(windowData && windowData.ic) ch = buflength ? UTF8GetChar(buf, &numBytes) : 0;
881 if(ch == 127) ch = 0;
882 // printf("Release! %d %d %d\n", keysym, code, ch);
883 result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyUp, code, ch);
890 if(key < KeyCode::enumSize)
891 keyStates[key] = true;
893 if(windowData.ic && buflength)
895 for(c = 0; c<buflength;)
898 ch = UTF8GetChar(buf + c, &numBytes);
899 if(ch == 127) ch = 0;
900 result = window.KeyMessage((c == 0) ?
901 __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyDown : __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit,
902 (c == 0) ? code : 0, ch);
904 if(!numBytes) c = buflength;
908 result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyDown, code, ch);
912 if(buflength && windowData.ic)
913 for(c = 0; c<buflength;)
916 ch = UTF8GetChar(buf + c, &numBytes);
917 if(ch == 127) ch = 0;
918 result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit, code, ch);
920 if(!numBytes) c = buflength;
923 result = window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit, code, ch);
931 static uint E_CALL XEventThread(void * data)
937 if(xTerminate) break;
940 XPeekEvent(xGlobalDisplay, &e);
942 guiApp.SignalEvent();
949 static X11Bool EventChecker(void *display, XEvent *event, char * data)
951 return (!data || (event->type == (int)(intptr_t) data)) && event->type != NoExpose && event->type != GraphicsExpose;
954 static X11Bool ConfigureNotifyChecker(void *display, XConfigureEvent *event, char * data)
956 return (!data || (event->window == (X11Window) data)) && event->type == ConfigureNotify;
959 static X11Bool FocusInChecker(void *display, XFocusChangeEvent *event, char * data)
961 X11Bool result = False;
962 if(event->type == FocusIn)
964 Window window = null;
965 // --- This deadlocks and I think Xorg should fix this.
966 // XFindContext(xGlobalDisplay, event->window, windowContext, (XPointer *) &window);
967 if((X11Window)guiApp.desktop.windowHandle == event->window)
968 window = guiApp.desktop;
971 for(window = guiApp.desktop.firstChild; window; window = window.next)
972 if((X11Window)window.windowHandle == event->window)
981 static enum FrameExtentSupport { unknown, working, broken };
983 static FrameExtentSupport frameExtentSupported;
984 static Time frameExtentRequest;
985 static X11Window frameExtentWindow;
987 static uint timerDelay = MAXINT;
988 #define RESOLUTION (18.2 * 100)
989 static uint XTimerThread(Thread thread)
991 int s = ConnectionNumber(xGlobalDisplay);
993 Time lastTime, thisTime;
994 lastTime = GetTime();
999 //bool waitSemaphore = false;
1000 fd_set readSet, writeSet, exceptSet;
1001 struct timeval tv = { (timerDelay == MAXINT) ? 0 : (timerDelay / 1000000), (timerDelay == MAXINT) ? (int)(1000000 / 18.2) : (timerDelay % 1000000) };
1003 if(xTerminate) break;
1006 FD_ZERO(&exceptSet);
1007 FD_SET(s, &readSet);
1008 FD_SET(s, &exceptSet);
1010 if(select(s + 1, &readSet, null, null, &tv))
1012 if(FD_ISSET(s, &readSet))
1015 if(frameExtentSupported == unknown && frameExtentRequest && GetTime() - frameExtentRequest > 1)
1017 XPropertyEvent event = { 0 };
1018 event.type = PropertyNotify;
1019 event.state = PropertyNewValue;
1020 event.atom = atoms[_net_frame_extents];
1021 event.display = xGlobalDisplay;
1023 event.window = frameExtentWindow;
1024 event.send_event = 1;
1026 frameExtentSupported = broken;
1028 XSendEvent(xGlobalDisplay, frameExtentWindow, bool::false,
1029 PropertyChangeMask, (union _XEvent *)&event);
1032 guiApp.SignalEvent();
1037 Sleep(1.0 / RESOLUTION);
1038 thisTime = GetTime();
1039 if(xTerminate) break;
1040 if(thisTime - lastTime > (1.0 / 18.2))
1042 guiApp.SignalEvent();
1043 lastTime = thisTime;
1050 XLockDisplay(xGlobalDisplay);
1051 if(XCheckIfEvent(xGlobalDisplay, &xEvent, EventChecker, null))
1054 guiApp.SignalEvent();
1056 XUnlockDisplay(xGlobalDisplay);
1065 static int MyXErrorHandler(X11Display * display, XErrorEvent * event)
1069 XGetErrorText(xGlobalDisplay, event->error_code, buffer, sizeof(buffer));
1071 Logf("X Error: %s\n", buffer);
1076 static int MyXIOErrorHandler(X11Display * display)
1078 Log("X IO Error\n");
1082 // Motif Hints (to get rid of the decorations)
1083 #define MWM_HINTS_FUNCTIONS (1L << 0)
1084 #define MWM_HINTS_DECORATIONS (1L << 1)
1085 #define MWM_HINTS_INPUT_MODE (1L << 2)
1086 #define MWM_HINTS_STATUS (1L << 3)
1088 #define MWM_DECOR_ALL (1L << 0)
1089 #define MWM_DECOR_BORDER (1L << 1)
1090 #define MWM_DECOR_RESIZEH (1L << 2)
1091 #define MWM_DECOR_TITLE (1L << 3)
1092 #define MWM_DECOR_MENU (1L << 4)
1093 #define MWM_DECOR_MINIMIZE (1L << 5)
1094 #define MWM_DECOR_MAXIMIZE (1L << 6)
1096 #define MWM_FUNC_ALL (1L << 0)
1097 #define MWM_FUNC_RESIZE (1L << 1)
1098 #define MWM_FUNC_MOVE (1L << 2)
1099 #define MWM_FUNC_MINIMIZE (1L << 3)
1100 #define MWM_FUNC_MAXIMIZE (1L << 4)
1101 #define MWM_FUNC_CLOSE (1L << 5)
1105 unsigned long flags;
1106 unsigned long functions;
1107 unsigned long decorations;
1109 unsigned long status;
1112 static void WaitForViewableWindow(Window window)
1115 //Logf("Wait for viewable %s\n", window.name);
1116 XFlush(xGlobalDisplay);
1117 //while(attempts++ < 40)
1120 XWindowAttributes attributes = { 0 };
1121 if(!XGetWindowAttributes(xGlobalDisplay, (X11Window)window.windowHandle, &attributes))
1123 if(attributes.map_state == IsViewable)
1126 Sleep(1.0 / RESOLUTION);
1130 static bool RequestFrameExtents(X11Window windowHandle)
1132 if(frameExtentSupported != broken)
1134 // Request decoration frame extents
1135 XClientMessageEvent event = { 0 };
1136 event.type = ClientMessage;
1137 event.message_type = atoms[_net_request_frame_extents];
1138 event.display = xGlobalDisplay;
1140 event.window = windowHandle;
1141 event.send_event = 1;
1144 if(frameExtentSupported == unknown && !frameExtentRequest)
1146 frameExtentRequest = GetTime();
1147 frameExtentWindow = windowHandle;
1150 XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false,
1151 SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
1157 static bool GetFrameExtents(Window window, bool update)
1159 XWindowData windowData = window.windowData;
1160 bool result = false;
1162 unsigned long len, fill;
1166 if(XGetWindowProperty(xGlobalDisplay, (X11Window)window.windowHandle,
1167 atoms[_net_frame_extents], 0, 4,
1168 False, XA_CARDINAL, &type, &format, &len,
1169 &fill, &data) == Success && data)
1171 long *extents = (long *)data;
1172 bool change = extents[0] != windowData.decor.left ||
1173 extents[1] != windowData.decor.right ||
1174 extents[2] != windowData.decor.top ||
1175 extents[3] != windowData.decor.bottom;
1177 bool hadFrameExtents = windowData.gotFrameExtents;
1178 Box oldDecor = windowData.decor;
1180 frameExtentSupported = working;
1181 frameExtentWindow = 0;
1182 frameExtentRequest = 0;
1184 if(!hadFrameExtents || extents[0] || extents[1] || extents[2] || extents[3])
1188 left = (int)extents[0], right = (int)extents[1],
1189 top = (int)extents[2], bottom = (int)extents[3]
1191 windowData.gotFrameExtents = true;
1192 if(update && change && ((Window)window).clientSize.w > 0)
1194 int x = window.position.x, y = window.position.y, w = window.size.w, h = window.size.h;
1195 if(!hadFrameExtents && window.state != maximized)
1197 window.ComputeAnchors(
1198 window.normalAnchor,
1199 window.normalSizeAnchor,
1204 x += windowData.decor.left - oldDecor.left;
1205 y += windowData.decor.top - oldDecor.top;
1207 w += windowData.decor.left - oldDecor.left + windowData.decor.right - oldDecor.right;
1208 h += windowData.decor.top - oldDecor.top + windowData.decor.bottom - oldDecor.bottom;
1211 if(window.state != maximized)
1213 window.Position(x, y, w, h, true, true, true, true, false, !hadFrameExtents && window.state != maximized);
1214 XInterface::UpdateRootWindow(window);
1224 static bool WaitForFrameExtents(Window window, bool update)
1227 //XFlush(xGlobalDisplay);
1228 while(attempts++ < 40)
1230 if(GetFrameExtents(window, update)) return true;
1231 Sleep(1.0 / RESOLUTION);
1236 /****************************************************************************
1237 /// DRIVER IMPLEMENTATION /////////////
1238 ****************************************************************************/
1240 /*static */class HiResTimer : Thread
1259 // Sleep(delay / 1000000.0);
1260 struct timeval tv = { delay / 1000000, delay % 1000000 };
1261 select(0,null,null,null, &tv);
1262 guiApp.SignalEvent();
1268 static HiResTimer hiResTimer { };
1272 #include <sys/ipc.h>
1273 #include <sys/shm.h>
1285 static int terminatePid;
1287 static void SigIntHandler(int value)
1289 // printf("SigHandler %d\n", getpid());
1290 if(!terminatePid || terminatePid == getpid())
1293 terminatePid = getpid();
1294 // printf("terminateX now equals %d\n", terminateX);
1295 if(guiApp && guiApp.semaphore)
1296 guiApp.semaphore.Release();
1299 struct shmid_ds info;
1300 int maxid = shmctl (0, SHM_INFO, &info);
1301 int pid = getpgrp();
1302 int thisPid = getpid();
1303 //if(thisPid == pid)
1309 for(id = 0; id <= maxid; id++)
1311 struct shmid_ds shmseg;
1313 if((shmid = shmctl(id, SHM_STAT, &shmseg)) >= 0)
1315 if(shmseg.shm_cpid == pid || shmseg.shm_cpid == thisPid)
1317 printf("%d (%d) belongs to us (%d)\n", shmid, id, shmseg.shm_cpid);
1318 shmctl(shmid, IPC_RMID, 0);
1326 /*else if(guiApp.desktop)
1327 guiApp.desktop.Destroy(0);*/
1330 static void X11UpdateState(Window window, bool * unmaximized)
1332 if(atomsSupported[_net_wm_state]) //window.nativeDecorations)
1335 unsigned long len, fill;
1338 if(XGetWindowProperty(xGlobalDisplay, (X11Window)window.systemHandle, atoms[_net_wm_state], 0, 32, False,
1339 XA_ATOM, &type, &format, &len, &fill, &data) == Success)
1341 bool maxVert = false, maxHorz = false, isMinimized = false;
1342 Atom * hints = (Atom *)data;
1344 for(c = 0; c < len && hints[c]; c++)
1346 if(hints[c] == atoms[_net_wm_state_maximized_vert])
1348 else if(hints[c] == atoms[_net_wm_state_maximized_horz])
1350 else if(hints[c] == atoms[_net_wm_state_hidden])
1355 if(maxVert && maxHorz)
1357 if(window.state != maximized)
1359 *&window.state = maximized;
1360 if(!window.nativeDecorations)
1361 window.CreateSystemChildren();
1364 else if(isMinimized)
1366 if(window.state != minimized)
1368 *&window.state = minimized;
1369 if(!window.nativeDecorations)
1370 window.CreateSystemChildren();
1373 else if(window.state != normal)
1375 if(unmaximized && window.state == maximized)
1376 *unmaximized = true;
1377 *&window.state = normal;
1378 if(!window.nativeDecorations)
1379 window.CreateSystemChildren();
1385 class XInterface : Interface
1387 class_property(name) = "X";
1389 // --- User Interface System ---
1392 setlocale(LC_ALL, "en_US.UTF-8");
1395 XSetLocaleModifiers("");
1396 XSetErrorHandler(MyXErrorHandler);
1397 XSetIOErrorHandler(MyXIOErrorHandler);
1399 signal(SIGINT, SigIntHandler);
1402 xGlobalDisplay = XOpenDisplay(null);
1404 #if (defined(__unix__) || defined(__APPLE__)) && !defined(__ANDROID__)
1406 XLockDisplay(xGlobalDisplay);
1409 // XSynchronize(xGlobalDisplay, True);
1410 frameExtentSupported = unknown;
1412 joystickFD[0] = open("/dev/js0", O_RDONLY);
1413 joystickFD[1] = open("/dev/js1", O_RDONLY);
1414 joystickFD[2] = open("/dev/js2", O_RDONLY);
1415 joystickFD[3] = open("/dev/js3", O_RDONLY);
1419 XWindowAttributes attributes = { 0 };
1421 systemCursors[iBeam] = XCreateFontCursor(xGlobalDisplay, XC_xterm);
1422 systemCursors[cross] = XCreateFontCursor(xGlobalDisplay, XC_tcross);
1423 systemCursors[moving] = XCreateFontCursor(xGlobalDisplay, XC_fleur);
1424 systemCursors[sizeNESW] = XCreateFontCursor(xGlobalDisplay, XC_bottom_left_corner);
1425 systemCursors[sizeNS] = XCreateFontCursor(xGlobalDisplay, XC_sb_v_double_arrow);
1426 systemCursors[sizeNWSE] = XCreateFontCursor(xGlobalDisplay, XC_bottom_right_corner);
1427 systemCursors[sizeWE] = XCreateFontCursor(xGlobalDisplay, XC_sb_h_double_arrow);
1428 systemCursors[hand] = XCreateFontCursor(xGlobalDisplay, XC_hand2);
1429 systemCursors[arrow] = XCreateFontCursor(xGlobalDisplay, XC_left_ptr);
1431 XGetWindowAttributes(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), &attributes);
1432 xSystemDepth = attributes.depth;
1433 xSystemVisual = attributes.visual;
1434 switch(xSystemDepth)
1436 case 32: case 24: xSystemPixelFormat = pixelFormat888; break;
1441 XVisualInfo *vinfo_ret;
1444 vinfo.visualid = XVisualIDFromVisual(xSystemVisual);
1445 vinfo_ret = XGetVisualInfo(xGlobalDisplay, VisualIDMask, &vinfo, &numitems);
1448 xSystemPixelFormat = (vinfo_ret->green_mask == 0x3E0) ? pixelFormat555 : pixelFormat565;
1450 if(GetXRenderFormat(xSystemPixelFormat, 0))
1452 // printf("Got X Render format %d\n", xSystemPixelFormat);
1456 printf("No X Format?\n");
1457 xSystemPixelFormat = (xSystemPixelFormat == pixelFormat555) ? pixelFormat565 : pixelFormat555;
1459 // vinfo._class = DirectColor;
1461 vinfo.bits_per_rgb = 5;
1462 vinfo.depth = xSystemDepth;
1463 vinfo.green_mask = (xSystemPixelFormat == pixelFormat555) ? 0x3E0 : 0x7E0;
1464 vinfo.red_mask = (xSystemPixelFormat == pixelFormat555) ? 0x7C00 : 0xF800;
1465 XFree((void *) vinfo_ret);
1466 if(XMatchVisualInfo(xGlobalDisplay, DefaultScreen(xGlobalDisplay), vinfo.depth, vinfo._class, &vinfo))
1467 //vinfo_ret = XGetVisualInfo(xGlobalDisplay, VisualDepthMask|VisualRedMaskMask|VisualGreenMaskMask|VisualBlueMaskMask, &vinfo, &numitems);
1470 //vinfo = *vinfo_ret;
1471 if(GetXRenderFormat(xSystemPixelFormat, 0))
1473 // printf("Got X Render format %d (second try)\n", xSystemPixelFormat);
1474 // printf("red mask: %x, green mask: %x, blue mask: %x\n", vinfo.red_mask,vinfo.green_mask, vinfo.blue_mask);
1476 xSystemVisual = vinfo.visual;
1479 printf("Could not get a 555 visual\n");
1485 // printf("Got a depth of %d\n", xSystemDepth);
1488 int major, minor, pixmaps;
1489 xSharedMemory = XShmQueryExtension(xGlobalDisplay) && XShmQueryVersion(xGlobalDisplay, &major, &minor, &pixmaps) && pixmaps;
1492 // printf("Opening IM\n");
1493 im = XOpenIM(xGlobalDisplay, null, null, null);
1496 XColor fore = { 0 }, back = { 0 };
1497 Pixmap pixmap = XCreatePixmap(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), 1, 1, 1);
1498 Pixmap mask = XCreatePixmap(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), 1, 1, 1);
1499 XSetWindowAttributes attributes = { 0 };
1501 XkbSetDetectableAutoRepeat(xGlobalDisplay, True, (int *)&autoRepeatDetectable);
1503 XInternAtoms(xGlobalDisplay, (char**)atomNames, AtomIdents::enumSize, False, atoms);
1505 // Check which atoms are supported by the WM
1508 unsigned long count, fill;
1512 if(XGetWindowProperty(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), atoms[_net_supported],
1513 0, 10000, False, XA_ATOM, &type, &format, &count, &fill, (void *)&data) == Success)
1516 for (i = 0; i < count; i++)
1519 for(j = 0; j < AtomIdents::enumSize; j++)
1521 if(atoms[j] == data[i])
1523 atomsSupported[j] = true;
1533 if(atomsSupported[_net_workarea])
1534 printf("Warning: _NET_WORKAREA extension not supported\n");
1537 attributes.override_redirect = True;
1540 windowContext = XUniqueContext();
1543 nullCursor = XCreatePixmapCursor(xGlobalDisplay, pixmap, mask, &fore, &back, 0, 0);
1544 confineWindow = XCreateWindow(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay),
1545 0,0,1,1,0, CopyFromParent, InputOnly, xSystemVisual /*CopyFromParent*/, CWOverrideRedirect, &attributes);
1548 // IM initialization
1550 /*ic = XCreateIC(im, XNInputStyle,
1551 XIMPreeditNothing | XIMStatusNothing,
1552 // XIMPreeditNone | XIMStatusNone | XIMPreeditPosition | XIMStatusArea | XIMPreeditArea | XIMStatusArea | XIMPreeditNothing | XIMStatusNothing,
1553 XNClientWindow, confineWindow, XNFocusWindow, confineWindow, 0);
1558 XIMStyle clientCanDo;
1559 XIMStyle styleWeWillUse = null;
1561 XVaNestedList arglist;
1562 unsigned long imEventMask;
1564 XGetImValues(im, XNQueryInputStyle, &IMcando, null);
1567 XIMPreeditNone | XIMStatusNone |
1568 XIMPreeditPosition | XIMStatusArea |
1569 XIMPreeditArea | XIMStatusArea |
1570 XIMPreeditNothing | XIMStatusNothing;
1572 for(i=0; i<IMcando->count_styles; i++)
1575 tmpStyle = IMcando->support_styles[i];
1576 if ( ((tmpStyle & clientCanDo) == tmpStyle) && prefer(tmpStyle, styleWeWillUse) )
1577 styleWeWillUse = tmpStyle;
1579 if(styleWeWillUse = null)
1583 arglist = XVaCreateNestedList(0, XNFontSet, fontset,
1585 WhitePixel(xGlobalDisplay, screen),
1587 BlackPixel(xGlobalDisplay, screen),
1589 ic = XCreateIC(im, XNInputStyle, styleWeWillUse,
1590 XNClientWindow, window, XNFocusWindow, window,
1591 XNStatusAttributes, arglist,
1592 XNPreeditAttributes, arglist, NULL);
1597 XGetWindowAttributes(xGlobalDisplay, win, &winAtts);
1598 XGetICValues(ic, XNFilterEvents, &imEventMask, null);
1599 imEventMask |= winAtts.your_event_mask;
1600 XSelectInput(xGlobalDisplay, window, imEventMask);
1606 timerThread = Thread { };
1608 timerThread.Main = XTimerThread;
1609 timerThread.Create();
1622 // WHY WAS THIS COMMENTED HERE?
1623 // Probably because it was causing crashes, the proper fix should now be in DestroyRootWindow
1627 xSemaphore.Release();
1633 XFreeCursor(xGlobalDisplay, systemCursors[iBeam]);
1634 XFreeCursor(xGlobalDisplay, systemCursors[cross]);
1635 XFreeCursor(xGlobalDisplay, systemCursors[moving]);
1636 XFreeCursor(xGlobalDisplay, systemCursors[sizeNESW]);
1637 XFreeCursor(xGlobalDisplay, systemCursors[sizeNS]);
1638 XFreeCursor(xGlobalDisplay, systemCursors[sizeNWSE]);
1639 XFreeCursor(xGlobalDisplay, systemCursors[sizeWE]);
1640 XFreeCursor(xGlobalDisplay, systemCursors[hand]);
1641 XFreeCursor(xGlobalDisplay, systemCursors[arrow]);
1643 //XPutBackEvent(xGlobalDisplay, &e);
1647 /*if(windowData && windowData.ic)
1649 XDestroyIC(windowData.ic);
1650 windowData.ic = null;
1657 XCloseDisplay(xGlobalDisplay);
1658 xGlobalDisplay = null;
1660 if(joystickFD[0] != -1) close(joystickFD[0]);
1661 if(joystickFD[1] != -1) close(joystickFD[1]);
1662 if(joystickFD[2] != -1) close(joystickFD[2]);
1663 if(joystickFD[3] != -1) close(joystickFD[3]);
1666 #define DBLCLICK_DELAY 300 // 0.3 second
1667 #define DBLCLICK_DELTA 1
1669 bool ProcessInput(bool processAll)
1671 bool eventAvailable = false;
1674 if(!fullScreenMode) RepositionDesktop(true);
1676 //* XLockDisplay(xGlobalDisplay);
1677 while(!xTerminate && (/*gotAnXEvent || */XCheckIfEvent(xGlobalDisplay, &e, EventChecker, null)))
1679 Window window = null;
1680 XAnyEvent * thisEvent = (XAnyEvent *)&e;
1681 // printf("Got an event: %d\n", thisEvent->type);
1683 //if(gotAnXEvent) { thisEvent = (XAnyEvent *)&xEvent; gotAnXEvent = false; }
1685 if(im && XFilterEvent((union _XEvent *)thisEvent, None))
1687 eventAvailable = true;
1688 XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
1691 XWindowData windowData = window.windowData;
1692 static uint lastKeyCode = 0;
1693 switch(thisEvent->type)
1697 XKeyEvent * event = (XKeyEvent *) thisEvent;
1699 timeStamp = event->time;
1702 Window modalRoot = window.FindModal();
1703 XWindowData windowData;
1705 activeWindow = (X11Window)window.windowHandle;
1707 if(!window.parent || window != window.parent.activeChild)
1710 modalRoot.ExternalActivate(true, true, window, null);
1712 window.ExternalActivate(true, true, window, null); // lastActive);
1713 windowData = modalRoot ? modalRoot.windowData : window.windowData;
1714 if(windowData && windowData.ic)
1716 // XSetICValues(ic, XNClientWindow, window.windowHandle, XNFocusWindow, window.windowHandle, NULL);
1717 XSetICFocus(windowData.ic);
1721 //*XUnlockDisplay(xGlobalDisplay);
1722 ProcessKeyMessage(window, event->keycode, (event->keycode == lastKeyCode) ? 2 : 0, event);
1723 //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1724 lastKeyCode = event->keycode;
1730 XKeyEvent * event = (XKeyEvent *) thisEvent;
1733 timeStamp = event->time;
1734 if(!autoRepeatDetectable && XCheckIfEvent(xGlobalDisplay, (XEvent *)&nextEvent, EventChecker, (void *)KeyPress))
1736 if(im && XFilterEvent(&nextEvent, None))
1739 if(((XKeyEvent *)&nextEvent)->keycode == event->keycode)
1741 //*XUnlockDisplay(xGlobalDisplay);
1742 ProcessKeyMessage(window, event->keycode, 2, event);
1746 //*XUnlockDisplay(xGlobalDisplay);
1747 // printf("Keycode not the same :(\n");
1748 ProcessKeyMessage(window, event->keycode, 1, event);
1749 ProcessKeyMessage(window, ((XKeyEvent *)&nextEvent)->keycode, 0, (XKeyEvent *)&nextEvent);
1754 //*XUnlockDisplay(xGlobalDisplay);
1755 // printf("No KeyPress ahead\n");
1756 ProcessKeyMessage(window, event->keycode, 1, event);
1758 //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1763 XButtonEvent * event = (XButtonEvent *) thisEvent;
1765 static double lastTime[3];
1766 static Window lastWindow[3];
1767 static Point lastPos[3];
1769 Modifiers keyFlags = 0;
1771 uint button, buttonDouble, whichButton;
1772 uint buttonMask = 0;
1773 int x = event->x_root, y = event->y_root;
1774 timeStamp = event->time;
1775 if(event->button == Button1)
1777 // Force a raise on click here to deal with confused active state preventing to bring the window up
1780 if(!atomsSupported[_net_active_window] && !window.isRemote)
1781 XRaiseWindow(xGlobalDisplay, (X11Window)window.windowHandle);
1782 XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToParent, CurrentTime);
1784 button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonDown;
1785 buttonDouble = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftDoubleClick;
1787 buttonMask = Button1Mask;
1788 keyFlags.left = true;
1789 buttonsState.left = true;
1791 else if(event->button == Button3)
1793 button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonDown;
1794 buttonDouble = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightDoubleClick;
1796 buttonMask = Button3Mask;
1797 keyFlags.right = true;
1798 buttonsState.right = true;
1800 else if(event->button == Button2)
1802 button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonDown;
1803 buttonDouble = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleDoubleClick;
1805 buttonMask = Button2Mask;
1806 keyFlags.middle = true;
1807 buttonsState.middle = true;
1809 if(event->state & buttonMask)
1814 doubleClick = event->time - lastTime[whichButton] < DBLCLICK_DELAY &&
1815 window == lastWindow[whichButton] &&
1816 Abs(event->x_root - lastPos[whichButton].x) < DBLCLICK_DELTA &&
1817 Abs(event->y_root - lastPos[whichButton].y) < DBLCLICK_DELTA;
1818 lastTime[whichButton] = doubleClick ? 0 : event->time;
1819 lastWindow[whichButton] = window;
1820 lastPos[whichButton].x = event->x_root;
1821 lastPos[whichButton].y = event->y_root;
1824 if(event->state & ShiftMask) keyFlags.shift = true;
1825 if(event->state & ControlMask) keyFlags.ctrl = true;
1826 if(event->state & Mod1Mask) keyFlags.alt = true;
1827 if(event->state & Button1Mask) keyFlags.left = true;
1828 if(event->state & Button2Mask) keyFlags.middle = true;
1829 if(event->state & Button3Mask) keyFlags.right = true;
1830 //*XUnlockDisplay(xGlobalDisplay);
1833 if(event->button == Button4 || event->button == Button5)
1835 window.KeyMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnKeyHit, { modifiers = keyFlags, code = (event->button == Button4) ? wheelUp : wheelDown }, 0);
1841 if(!window.MouseMessage(buttonDouble, x, y, &keyFlags, false, true))
1843 //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1848 window.MouseMessage(button, x, y, &keyFlags, false, /*doubleClick? false : */true);
1850 //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1856 Modifiers keyFlags = 0;
1857 XButtonEvent * event = (XButtonEvent *) thisEvent;
1860 int x = event->x_root, y = event->y_root;
1861 if(event->button == Button1)
1863 button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnLeftButtonUp;
1864 buttonMask = Button1Mask;
1865 buttonsState.left = false;
1867 else if(event->button == Button3)
1869 button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnRightButtonUp;
1870 buttonMask = Button3Mask;
1871 buttonsState.right = false;
1875 button = __ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMiddleButtonUp;
1876 buttonMask = Button2Mask;
1877 buttonsState.middle = false;
1879 timeStamp = event->time;
1880 if(!(event->state & buttonMask)) break;
1881 if(event->state & ShiftMask) keyFlags.shift = true;
1882 if(event->state & ControlMask) keyFlags.ctrl = true;
1883 if(event->state & Mod1Mask) keyFlags.alt = true;
1884 if(event->state & Button1Mask) keyFlags.left = true;
1885 if(event->state & Button2Mask) keyFlags.middle = true;
1886 if(event->state & Button3Mask) keyFlags.right = true;
1887 if(guiApp.windowCaptured && guiApp.windowCaptured != window)
1889 // X hasn't noticed the capture yet, so fix it!
1890 x += window.absPosition.x;
1891 y += window.absPosition.y;
1892 window = guiApp.windowCaptured.rootWindow;
1893 x -= window.absPosition.x;
1894 y -= window.absPosition.y;
1896 //*XUnlockDisplay(xGlobalDisplay);
1898 window.MouseMessage(button, x, y, &keyFlags, false, false);
1900 //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1905 //static uint lastTime = 0;
1906 XMotionEvent * event = (XMotionEvent *) thisEvent;
1907 while(XCheckIfEvent(xGlobalDisplay, (XEvent *)thisEvent, EventChecker, (void *)MotionNotify));
1908 // if(event->time - lastTime > 15)
1910 Modifiers keyFlags = 0;
1911 timeStamp = event->time;
1912 // int x = event->x_root, y = event->y_root;
1914 if(event->state & ShiftMask) keyFlags.shift = true;
1915 if(event->state & ControlMask) keyFlags.ctrl = true;
1916 if(event->state & Mod1Mask) keyFlags.alt = true;
1917 if(event->state & Button1Mask) keyFlags.left = true;
1918 if(event->state & Button2Mask) keyFlags.middle = true;
1919 if(event->state & Button3Mask) keyFlags.right = true;
1920 //*XUnlockDisplay(xGlobalDisplay);
1922 if(window == acquiredInputWindow)
1924 lastMouse.x = event->x_root;
1925 lastMouse.y = event->y_root;
1927 window.MouseMessage(__ecereVMethodID___ecereNameSpace__ecere__gui__Window_OnMouseMove,
1928 event->x_root, event->y_root, &keyFlags, false, false);
1930 //*if(xGlobalDisplay) XLockDisplay(xGlobalDisplay);
1931 //lastTime = (uint)event->time;
1937 XExposeEvent * event = (XExposeEvent *) thisEvent;
1939 box.left = event->x;
1941 box.right = box.left + event->width - 1;
1942 box.bottom = box.top + event->height - 1;
1943 window.UpdateDirty(box);
1946 case SelectionRequest:
1948 XSelectionRequestEvent *req = (XSelectionRequestEvent *) thisEvent;
1950 if(req->target == atoms[targets] && clipBoardData)
1952 Atom * supportedTargets = new Atom[4];
1953 supportedTargets[0] = atoms[targets];
1954 supportedTargets[1] = atoms[multiple];
1955 supportedTargets[2] = XA_STRING;
1956 supportedTargets[3] = atoms[utf8_string];
1957 XChangeProperty(xGlobalDisplay,req->requestor, req->_property,
1958 XA_ATOM,32,PropModeReplace, (byte *) supportedTargets, 4*sizeof(Atom));
1959 respond.xselection._property = req->_property;
1960 delete supportedTargets;
1962 else if((req->target == XA_STRING || req->target == atoms[utf8_string]) && clipBoardData)
1964 Atom _property = (req->_property == None) ? req->target : req->_property;
1965 XChangeProperty(xGlobalDisplay,req->requestor, _property,
1966 req->target/*req->_property*/,8,PropModeReplace, (byte *) clipBoardData, strlen(clipBoardData));
1967 respond.xselection._property = _property;
1970 respond.xselection._property = None;
1972 respond.xselection.type = SelectionNotify;
1973 respond.xselection.display = req->display;
1974 respond.xselection.requestor = req->requestor;
1975 respond.xselection.selection =req->selection;
1976 respond.xselection.target = req->target;
1977 respond.xselection.time = CurrentTime;
1978 XSendEvent(xGlobalDisplay, req->requestor,0,0,&respond);
1981 case SelectionClear:
1983 delete clipBoardData;
1988 lastMouse = acquireStart;
1990 guiApp.SetAppFocus(true);
1992 X11UpdateState(window, null);
1996 if(acquiredInputWindow)
1998 GetMousePosition(&guiApp.acquiredMouseX, &guiApp.acquiredMouseY);
1999 lastMouse = { window.size.w/2, window.size.h/2 };
2000 SetMousePosition(lastMouse.x, lastMouse.y);
2002 XRaiseWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2003 SetNETWMState((X11Window)window.windowHandle, true, add, atoms[_net_wm_state_fullscreen], 0);
2004 XGrabKeyboard(xGlobalDisplay, (X11Window)window.windowHandle, False, GrabModeAsync, GrabModeAsync, CurrentTime);
2005 XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToParent, timeStamp);
2006 XInterface::UpdateRootWindow(window);
2010 if(activeWindow != (X11Window)window.windowHandle)
2012 Window modalRoot = window.FindModal();
2013 XWindowData windowData;
2015 activeWindow = (X11Window)window.windowHandle;
2017 if(window.parent && window == window.parent.activeChild) break;
2019 //if(window.creationActivation == activate && guiApp.desktop.active)
2022 modalRoot.ExternalActivate(true, true, window, null); // lastActive);
2024 window.ExternalActivate(true, true, window, null); // lastActive);
2026 windowData = modalRoot ? modalRoot.windowData : window.windowData;
2027 if(windowData && windowData.ic)
2029 // XSetICValues(ic, XNClientWindow, window.windowHandle, XNFocusWindow, window.windowHandle, NULL);
2030 XSetICFocus(windowData.ic);
2032 //delete lastActive;
2033 //lastActive = window;
2034 //incref lastActive;
2042 //printf("Processing a FocusOut Event for %s (%x)\n", window._class.name, window);
2046 if(XCheckTypedWindowEvent(xGlobalDisplay, thisEvent->window, FocusIn, (XEvent *)thisEvent))
2052 if(XCheckIfEvent(xGlobalDisplay, (XEvent *)thisEvent, (void *)FocusInChecker, null))
2055 XPutBackEvent(xGlobalDisplay, (XEvent *)thisEvent);
2060 if(fullScreenMode || (X11Window)window.windowHandle == activeWindow)
2061 guiApp.SetAppFocus(false);
2065 //XUngrabKeyboard(xGlobalDisplay, CurrentTime);
2066 //SetNETWMState((X11Window)window.windowHandle, true, remove, atoms[_net_wm_state_fullscreen], 0);
2067 //XIconifyWindow(xGlobalDisplay, (X11Window)window.windowHandle, DefaultScreen(xGlobalDisplay));
2071 if(thisEvent->window == activeWindow)
2072 activeWindow = (X11Window)null;
2074 if(XCheckTypedEvent(xGlobalDisplay, FocusIn, (XEvent *)thisEvent))
2076 if(XCheckTypedWindowEvent(xGlobalDisplay, thisEvent->window, FocusOut, (XEvent *)thisEvent))
2078 XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
2080 XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
2083 Window windowCopy = window;
2084 XWindowData windowData;
2085 if(windowCopy == windowCopy.parent.activeChild) break;
2087 windowCopy.ExternalActivate(true, true, windowCopy, lastActive);
2089 windowData = windowCopy.windowData;
2090 if(windowData && windowData.ic)
2091 XSetICFocus(windowData.ic);
2094 lastActive = windowCopy;
2099 // XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
2102 if(window != window.parent.activeChild) break;
2104 window.ExternalActivate(false, true, window, lastActive);
2110 XWindowData windowData;
2111 XFindContext(xGlobalDisplay, thisEvent->window, windowContext, (XPointer *) &window);
2115 XFocusChangeEvent *event = (XFocusChangeEvent *) thisEvent;
2116 Window modalRoot = window.FindModal();
2121 modalRoot.ExternalActivate(true, true, window, lastActive);
2125 window.ExternalActivate(true, true, window, lastActive);
2127 windowData = modalRoot ? modalRoot.windowData : window.windowData;
2128 if(windowData && windowData.ic)
2129 XSetICFocus(windowData.ic);
2132 lastActive = window;
2141 if(window.parent && window != window.parent.activeChild && window != guiApp.interimWindow) break;
2145 //printf("Deactivating %s\n", window._class.name);
2148 if(!window.ExternalActivate(false, true, window, null /*lastActive*/))
2150 XCheckTypedEvent(xGlobalDisplay, /*thisEvent->window, */ButtonPress, (XEvent *)thisEvent);
2153 //delete lastActive;
2155 lastActive = window;
2162 case ConfigureNotify:
2164 XConfigureEvent * event = (XConfigureEvent *) thisEvent;
2165 bool unmaximized = false;
2167 if(!window.visible || fullScreenMode) break;
2168 while(XCheckIfEvent(xGlobalDisplay, (XEvent *)thisEvent, (void *)ConfigureNotifyChecker, (void *)window.windowHandle));
2169 //if(event->x - desktopX != window.position.x || event->y - desktopY != window.position.y || event->width != window.size.w || event->height != window.size.h)
2170 X11UpdateState(window, &um);
2171 unmaximized = false;
2173 bool offset = false;
2175 if(unmaximized && window.nativeDecorations && ((BorderBits)window.borderStyle).fixed)
2177 if(window.nativeDecorations && RequestFrameExtents((X11Window)window.windowHandle))
2178 WaitForFrameExtents(window, false);
2180 // Ensure we set the normal size anchor when un-maximizing
2181 window.ComputeAnchors(window.normalAnchor, window.normalSizeAnchor, &x, &y, &w, &h);
2187 w = event->width, h = event->height;
2189 //if(event->send_event)
2191 X11Window rootChild;
2193 XTranslateCoordinates(xGlobalDisplay, event->window,
2194 RootWindow(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), 0, 0,
2195 &rootX, &rootY, &rootChild);
2197 if(x != rootX || y != rootY)
2199 if(!event->send_event)
2211 if(window.nativeDecorations && window.state != maximized && ((BorderBits)window.borderStyle).fixed)
2213 x -= windowData.decor.left;
2214 y -= windowData.decor.top;
2215 w += windowData.decor.left + windowData.decor.right;
2216 h += windowData.decor.top + windowData.decor.bottom;
2220 window.Position(x, y, w, h, um, true, true, true, false, unmaximized);
2222 // Break the anchors for moveable/resizable windows
2223 // Avoid doing this if the translation wasn't in sync as it will cause the window to move around
2224 if(!unmaximized && !offset && window.style.fixed && window.state == normal)
2226 window.normalAnchor = Anchor
2228 left = x + windowData.decor.left,
2229 top = y + windowData.decor.top
2231 window.normalSizeAnchor =
2232 SizeAnchor { { window.clientSize.w, window.clientSize.h }, isClientW = true, isClientH = true };
2239 XClientMessageEvent * event = (XClientMessageEvent *) thisEvent;
2241 if(event->data.l[0] == atoms[wm_delete_window])
2246 if(event->data.l[0] == atoms[wm_take_focus])
2249 XWindowData windowData;
2254 XRaiseWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2255 XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToParent, timeStamp);
2256 XGrabKeyboard(xGlobalDisplay, (X11Window)window.windowHandle, False, GrabModeAsync, GrabModeAsync, CurrentTime);
2257 guiApp.SetAppFocus(true);
2261 //activeWindow = (X11Window)window.windowHandle;
2263 timeStamp = (X11Time)event->data.l[1];
2265 windowData = window.windowData;
2266 laterFocus = windowData.laterFocus;
2267 windowData.laterFocus = true;
2270 //printf("Processing a ClientMessage WM_TAKE_FOCUS Event for %s (%x)\n", window._class.name, window);
2272 if(guiApp.interimWindow && guiApp.interimWindow.created && window != guiApp.interimWindow) break; //window == window.parent.activeChild) break;
2273 // if(window == window.parent.activeChild) break;
2278 //XFlush(xGlobalDisplay);
2279 while(XCheckTypedEvent(xGlobalDisplay, FocusOut, &checkEvent))
2281 XFocusChangeEvent *event = (XFocusChangeEvent *) &checkEvent;
2283 XFindContext(xGlobalDisplay, event->window, windowContext, (XPointer *) &window);
2284 if(window.parent && window != window.parent.activeChild) break;
2288 //printf("Found a FocusOut ahead, deactivating %s (%d)\n", window._class.name, window);
2291 if(!window.ExternalActivate(false, true, window, null /*lastActive*/))
2293 XCheckTypedEvent(xGlobalDisplay, /*thisEvent->window, */ButtonPress, (XEvent *)thisEvent);
2300 lastMouse = acquireStart;
2301 modalRoot = window.FindModal();
2302 windowData = modalRoot ? modalRoot.windowData : window.windowData;
2305 if(laterFocus || (modalRoot ? modalRoot : window).creationActivation == activate)
2309 XRaiseWindow(xGlobalDisplay, (X11Window)modalRoot.windowHandle);
2310 WaitForViewableWindow(modalRoot);
2311 if(atomsSupported[_net_active_window])
2313 XClientMessageEvent event = { 0 };
2314 event.type = ClientMessage;
2315 event.message_type = atoms[_net_active_window];
2316 event.display = xGlobalDisplay;
2318 event.window = (X11Window)modalRoot.windowHandle;
2319 event.send_event = 1;
2321 event.data.l[0] = /*0*/ 1;
2322 event.data.l[1] = timeStamp;
2323 event.data.l[2] = activeWindow;
2325 event.data.l[2] = activeWindow; //guiApp.desktop.activeChild.windowHandle;
2328 //printf("(ClientMessage - %s) Setting _NET_ACTIVE_WINDOW for %s (%x)\n", window._class.name, modalRoot._class.name, modalRoot);
2331 XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
2332 XSetInputFocus(xGlobalDisplay, (X11Window)modalRoot.windowHandle, RevertToParent, timeStamp);
2333 guiApp.SetAppFocus(true);
2334 activeWindow = (X11Window)window.windowHandle;
2336 //XFlush(xGlobalDisplay);
2337 //printf("Done.\n");
2342 XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToParent, timeStamp);
2343 guiApp.SetAppFocus(true);
2344 activeWindow = (X11Window)window.windowHandle;
2345 window.ExternalActivate(true, true, window, null); // lastActive);
2346 if(windowData && windowData.ic)
2348 // XSetICValues(ic, XNClientWindow, window.windowHandle, XNFocusWindow, window.windowHandle, NULL);
2349 //XSetICFocus(windowData.ic);
2353 windowData.laterFocus = true;
2355 lastActive = window;
2362 case PropertyNotify:
2364 XWindowData windowData = window.windowData;
2365 XPropertyEvent * event = (XPropertyEvent *) thisEvent;
2366 if(!fullScreenMode && event->atom == atoms[_net_frame_extents] &&
2367 event->state == PropertyNewValue && windowData)
2369 if(!GetFrameExtents(window, true))
2370 windowData.gotFrameExtents = true; // Unsupported?
2375 if(!processAll) break;
2378 //*if(xGlobalDisplay) XUnlockDisplay(xGlobalDisplay);
2387 gotAnXEvent = false;
2389 xSemaphore.Release();
2394 void Lock(Window window)
2396 //*XLockDisplay(xGlobalDisplay);
2399 void Unlock(Window window)
2401 //*XUnlockDisplay(xGlobalDisplay);
2404 const char ** GraphicsDrivers(int * numDrivers)
2406 static const char *graphicsDrivers[] = { "X", "OpenGL" };
2407 *numDrivers = sizeof(graphicsDrivers) / sizeof(char *);
2408 return (const char **)graphicsDrivers;
2411 void GetCurrentMode(bool * fullScreen, int * resolution, int * colorDepth, int * refreshRate)
2413 *fullScreen = fullScreenMode;
2416 void EnsureFullScreen(bool *fullScreen)
2421 bool ScreenMode(bool fullScreen, int resolution, int colorDepth, int refreshRate, bool * textMode)
2425 fullScreenMode = fullScreen;
2433 //static bool firstTime = true;
2434 //firstTime = false;
2435 desktopX = desktopY = desktopW = desktopH = 0;
2437 RepositionDesktop(false);
2442 // --- Window Creation ---
2443 void * CreateRootWindow(Window window)
2445 X11Window windowHandle;
2446 XSetWindowAttributes attributes = { 0 };
2447 XVisualInfo * visualInfo = null;
2451 unsigned long mask = EVENT_MASK;
2453 // Old WM (e.g. TWM), use built-in decorations
2454 if(!atomsSupported[_net_wm_state])
2455 window.nativeDecorations = false;
2456 attributes.override_redirect = (window.interim || (!atomsSupported[_net_wm_state] && !window.nativeDecorations)) ? True : False;
2457 attributes.event_mask = EVENT_MASK;
2458 //printf("%s\n", guiApp.defaultDisplayDriver);
2459 #if !defined(ECERE_VANILLA) && !defined(ECERE_NO3D) && !defined(ECERE_NOGL)
2460 if(window.dispDriver == class(OpenGLDisplayDriver) || !strcmp(guiApp.defaultDisplayDriver, "OpenGL"))
2464 for(samples = 4;; samples /= 2)
2469 GLX_RENDER_TYPE, GLX_RGBA_BIT,
2470 GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
2471 GLX_DOUBLEBUFFER, True,
2477 int numAttribs = 14;
2479 GLXFBConfig *fbconfigs = null, fbconfig;
2482 //printf("Samples = %d, alpha = %d\n", samples, alpha);
2485 attrib[numAttribs++] = GLX_ALPHA_SIZE;
2486 attrib[numAttribs++] = 1;
2490 attrib[numAttribs++] = GLX_SAMPLE_BUFFERS_ARB;
2491 attrib[numAttribs++] = GL_TRUE;
2492 attrib[numAttribs++] = GLX_SAMPLES_ARB;
2493 attrib[numAttribs++] = samples;
2495 attrib[numAttribs] = None;
2497 // visualInfo = glXChooseVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib);
2499 //printf("Trying %d samples...\n", samples);
2500 fbconfigs = glXChooseFBConfig(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrib, &numfbconfigs);
2503 for (i = 0; i < numfbconfigs; i++)
2505 XRenderPictFormat * format;
2506 visualInfo = glXGetVisualFromFBConfig(xGlobalDisplay, fbconfigs[i]);
2507 if (!visualInfo) continue;
2508 if(window.alphaBlend)
2510 format = XRenderFindVisualFormat(xGlobalDisplay, visualInfo->visual);
2511 if (!format) { XFree(visualInfo); continue; }
2512 if(format->direct.alphaMask > 0)
2514 //printf("Found what we're looking for (alphaBlend)\n");
2515 fbconfig = fbconfigs[i];
2522 //printf("Found what we're looking for\n");
2527 if (i == numfbconfigs)
2529 fbconfig = fbconfigs[0];
2530 visualInfo = glXGetVisualFromFBConfig(xGlobalDisplay, fbconfig);
2535 if(found || (!samples && !alpha))
2537 //printf("Stopping now\n");
2542 if(samples == 1) samples = 0;
2543 else if(!samples) alpha = false;
2550 GLX_USE_GL, GLX_DEPTH_SIZE, 1,
2552 GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1,
2556 visualInfo = glXChooseVisual(xGlobalDisplay, DefaultScreen(xGlobalDisplay), attrList);
2559 depth = visualInfo ? visualInfo->depth : (window.alphaBlend ? 32 : xSystemDepth);
2560 visual = visualInfo ? visualInfo->visual : (window.alphaBlend ? FindFullColorVisual (xGlobalDisplay, &depth) : xSystemVisual);
2561 // printf("visual: %d, depth: %d\n", visual, depth);
2565 attributes.colormap = XCreateColormap(xGlobalDisplay, XRootWindow(xGlobalDisplay, DefaultScreen(xGlobalDisplay)), visual, AllocNone);
2566 attributes.border_pixel = 0;
2573 windowHandle = XCreateWindow(xGlobalDisplay,
2574 DefaultRootWindow(xGlobalDisplay),
2576 XDisplayWidth(xGlobalDisplay, DefaultScreen(xGlobalDisplay)),
2577 XDisplayHeight(xGlobalDisplay, DefaultScreen(xGlobalDisplay)),
2578 0, depth, InputOutput, visual ? visual : CopyFromParent,
2579 CWEventMask | (visual ? (CWColormap | CWBorderPixel) : 0) | CWOverrideRedirect,
2583 XSizeHints hints = { 0 };
2584 XSetWMNormalHints(xGlobalDisplay, windowHandle, &hints);
2588 String caption = window.caption;
2589 XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_name],
2590 atoms[utf8_string], 8, PropModeReplace, (byte *)window.caption, caption ? strlen(caption) : 0);
2591 XChangeProperty(xGlobalDisplay, windowHandle, atoms[wm_name],
2592 atoms[utf8_string], 8, PropModeReplace, (byte *)window.caption, caption ? strlen(caption) : 0);
2595 SetNETWMState((X11Window)windowHandle, false, add, atoms[_net_wm_state_fullscreen], 0);
2596 //SetNETWMState((X11Window)windowHandle, false, add, atoms[_net_wm_state_above], 0);
2601 hints[0] = atoms[_net_wm_window_type_normal];
2603 XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_window_type], XA_ATOM, 32,
2604 PropModeReplace, (unsigned char*)&hints, count);
2609 xwmHints.flags = InputHint;
2611 XSetWMHints(xGlobalDisplay, windowHandle, &xwmHints);
2614 Atom protocols[2] = { atoms[wm_delete_window], atoms[wm_take_focus] };
2615 XSetWMProtocols(xGlobalDisplay, windowHandle, protocols, 2);
2619 Unsupported for now...
2620 else if(window.systemParent)
2627 if(window.windowHandle)
2628 windowHandle = (X11Window)window.windowHandle;
2631 X11Window parentWindow = (X11Window)null;
2632 int x = window.position.x + desktopX, y = window.position.y + desktopY;
2633 int w = window.state == normal ? Max(1, window.size.w) : Max(1, window.normalSizeAnchor.size.w);
2634 int h = window.state == normal ? Max(1, window.size.h) : Max(1, window.normalSizeAnchor.size.h);
2635 MinMaxValue smw = 0, smh = 0;
2636 MinMaxValue minW = window.minSize.w, minH = window.minSize.h;
2637 window.OnResizing((int *)&minW, (int *)&minH);
2639 // To fix jumping message boxes on Cinnamon:
2640 if(window.state == normal && (minW > window.minSize.w || minH > window.minSize.w))
2641 window.ComputeAnchors(window.normalAnchor, window.normalSizeAnchor, &x, &y, &w, &h);
2643 window.SetWindowMinimum(&smw, &smh);
2644 minW = Max(minW, smw);
2645 minH = Max(minH, smh);
2647 if(!window.nativeDecorations && window.state != normal)
2649 w += window.size.w - window.clientSize.w;
2650 h += window.size.h - window.clientSize.h;
2653 if(window.master.rootWindow && window.master.rootWindow != guiApp.desktop && (window._isModal || window.style.interim))
2655 Window master = window.master;
2656 Window rootWindow = master.rootWindow;
2658 parentWindow = rootWindow.is3D ? (X11Window)rootWindow.parent.windowHandle : (X11Window)rootWindow.windowHandle;
2660 // parentWindow = window.master.rootWindow.is3D ? window.master.rootWindow.parent.windowHandle : window.master.rootWindow.windowHandle;
2662 if(window.style.showInTaskBar)
2663 parentWindow = (X11Window)null;
2665 windowHandle = XCreateWindow(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay),
2667 0, depth, InputOutput, visual ? visual : CopyFromParent,
2668 CWEventMask | CWOverrideRedirect | (visual ? (CWColormap | CWBorderPixel) : 0), &attributes);
2670 if(parentWindow && (window.interim || window.isModal))
2672 //printf("Setting WM_TRANSIENT_FOR of %s to %s\n", window._class.name, window.master.rootWindow._class.name);
2673 XSetTransientForHint(xGlobalDisplay, windowHandle, parentWindow);
2674 //XFlush(xGlobalDisplay);
2675 //printf("Done.\n");
2676 //XChangeProperty(xGlobalDisplay, windowHandle, atoms[wm_transient_for], XA_WINDOW, 32, PropModeReplace, (unsigned char*)&parentWindow, 1);
2678 SetNETWMState(windowHandle, false, add, atoms[_net_wm_state_modal], 0);
2684 if(parentWindow && window.interim)
2686 hints[0] = atoms[_net_wm_window_type_dropdown_menu];
2687 hints[1] = atoms[_net_wm_window_type_popup_menu];
2688 hints[2] = atoms[_net_wm_window_type_menu];
2691 else if(parentWindow)
2693 hints[0] = atoms[_net_wm_window_type_normal];
2694 SetNETWMState(windowHandle, false, add, atoms[_net_wm_state_skip_taskbar], 0);
2696 // Some WMs won't show a close button if dialog is set
2697 // Additionally, this casues jumping of all dialog windows on Cinnamon
2698 //hints[0] = atoms[_net_wm_window_type_dialog];
2703 hints[0] = atoms[_net_wm_window_type_normal];
2706 XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_window_type], XA_ATOM, 32,
2707 PropModeReplace, (unsigned char*)&hints, count);
2709 if(window.stayOnTop)
2710 SetNETWMState((X11Window)windowHandle, false, add, atoms[_net_wm_state_above], 0);
2714 xwmHints.flags = InputHint;
2716 XSetWMHints(xGlobalDisplay, windowHandle, &xwmHints);
2719 Atom protocols[2] = { atoms[wm_delete_window], atoms[wm_take_focus] };
2720 XSetWMProtocols(xGlobalDisplay, windowHandle, protocols, 2);
2723 // Set Normal hints for minimum/maximum size
2725 XSizeHints hints = { 0 };
2726 hints.min_width = minW;
2727 hints.min_height = minH;
2728 hints.flags |= PMinSize;
2730 if(window.maxSize.w < MAXINT || window.minSize.h < MAXINT)
2732 hints.max_width = window.maxSize.w;
2733 hints.max_height = window.maxSize.h;
2734 hints.flags |= PMaxSize;
2738 hints.flags |= PPosition;
2742 hints.flags |= PSize;
2744 XSetWMNormalHints(xGlobalDisplay, windowHandle, &hints);
2752 char fontString[1024] = "--helvetica-*-r-*-*-*-120-*-*-*-*-*-*,-misc-fixed-*-r-*-*-*-130-*-*-*-*-*-*";
2753 XPoint cursor_location = { 0, 0 };
2754 char **missing_charsets;
2755 int num_missing_charsets = 0;
2756 char *default_string;
2758 //XRectangle area = { 0, 0, 400, 400 };
2759 XVaNestedList argList;
2761 // sprintf(fontString, "-*-%s-*-r-*-*-*-%d-*-*-*-*-*-*", "Helvetica" /*window.font.faceName*/, (int)(window.font.size * 20));
2762 fontset = XCreateFontSet(xGlobalDisplay, fontString, &missing_charsets, &num_missing_charsets, &default_string);
2763 argList = XVaCreateNestedList(0,
2764 XNSpotLocation, &cursor_location,
2766 XNFontSet, fontset,/*
2768 WhitePixel(xGlobalDisplay, DefaultScreen(xGlobalDisplay)),
2770 BlackPixel(xGlobalDisplay, DefaultScreen(xGlobalDisplay)),*/
2772 ic = XCreateIC(im, XNInputStyle,
2773 XIMStatusNothing | XIMPreeditPosition,
2774 XNPreeditAttributes, argList,
2775 XNClientWindow, windowHandle, XNFocusWindow, windowHandle, NULL);
2777 // Should we free the fontset or not?
2778 // XFreeFontSet(xGlobalDisplay, fontset);
2780 setICPosition = true;
2782 ic = XCreateIC(im, XNInputStyle, XIMStatusNothing | XIMPreeditNothing, XNClientWindow, windowHandle, XNFocusWindow, windowHandle, null);
2786 XGetICValues(ic, XNFilterEvents, &mask, NULL);
2790 XSelectInput(xGlobalDisplay, windowHandle, mask);
2792 if(capturedWindow == None && !restrictedWindow)
2794 XGrabPointer(xGlobalDisplay, (X11Window)windowHandle, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2795 GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
2796 XUngrabPointer(xGlobalDisplay, CurrentTime);
2801 if ( atoms[_motif_wm_hints] != None )
2803 BorderBits borderBits = (BorderBits)window.borderStyle;
2804 bool hasTitleBar = borderBits.fixed;
2807 ((window.nativeDecorations && hasTitleBar) ? 0 : MWM_HINTS_DECORATIONS)|MWM_HINTS_FUNCTIONS,
2808 (window.hasClose ? MWM_FUNC_CLOSE : 0) |
2809 (fullScreenMode || window.hasMaximize ? MWM_FUNC_MAXIMIZE : 0) |
2810 (fullScreenMode || window.hasMinimize ? MWM_FUNC_MINIMIZE : 0) |
2811 ((fullScreenMode || window.moveable || hasTitleBar) ? MWM_FUNC_MOVE : 0) |
2812 (fullScreenMode || borderBits.sizable ? MWM_FUNC_RESIZE : 0),
2815 XChangeProperty(xGlobalDisplay, windowHandle, atoms[_motif_wm_hints], atoms[_motif_wm_hints], 32,
2816 PropModeReplace, (unsigned char*)&hints, 5);
2819 // *** We set this for ourselves, so don't check atomsSupported !!! ***
2820 if(atoms[_net_wm_pid])
2823 // printf("Setting _NET_WM_PID to %d\n", pid);
2824 XChangeProperty(xGlobalDisplay, windowHandle, atoms[_net_wm_pid], XA_CARDINAL, 32,
2825 PropModeReplace, (unsigned char*)&pid, 1);
2830 XWMHints wmHints = { 0 };
2831 wmHints.input = True;
2832 XSetWMHints(xGlobalDisplay, windowHandle, &wmHints);
2835 // XFlush(xGlobalDisplay);
2836 window.windowData = XWindowData { visualInfo, ic };
2838 XSaveContext(xGlobalDisplay, windowHandle, windowContext, (XPointer)window);
2840 XSelectInput(xGlobalDisplay, windowHandle, mask);
2842 if(capturedWindow == None && !restrictedWindow)
2844 XGrabPointer(xGlobalDisplay, (X11Window)windowHandle, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
2845 GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
2846 XUngrabPointer(xGlobalDisplay, CurrentTime);
2849 if(fullScreenMode || !window.nativeDecorations || !((BorderBits)window.borderStyle).fixed || !RequestFrameExtents(windowHandle))
2850 ((XWindowData)window.windowData).gotFrameExtents = true;
2852 window.windowHandle = (void *)windowHandle;
2853 if(window.state != maximized)
2854 WaitForFrameExtents(window, true);
2856 //GetFrameExtents(window, true);
2860 XMapWindow(xGlobalDisplay, windowHandle);
2861 XGrabKeyboard(xGlobalDisplay, windowHandle, False, GrabModeAsync, GrabModeAsync, CurrentTime);
2863 return (void *)windowHandle;
2866 void DestroyRootWindow(Window window)
2869 if(window == acquiredInputWindow)
2870 delete acquiredInputWindow;
2872 XDeleteContext(xGlobalDisplay, (XID)window, windowContext);
2873 XSaveContext(xGlobalDisplay, (X11Window)window.windowHandle, windowContext, null);
2874 XDestroyWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2875 XSync(xGlobalDisplay, 0);
2876 while(XCheckWindowEvent(xGlobalDisplay, (X11Window)window.windowHandle, 0xFFFFFFFF, &event));
2877 window.windowHandle = null;
2878 if(window.windowData)
2880 XWindowData windowData = window.windowData;
2881 XFree(windowData.visual);
2882 if(windowData && windowData.ic)
2883 XDestroyIC(windowData.ic);
2885 // printf("Setting windowData for %s to null\n", window._class.name);
2886 window.windowData = null;
2888 if(lastActive == window)
2892 // -- Window manipulation ---
2894 void SetRootWindowCaption(Window window, const char * name)
2896 if(window.windowHandle)
2898 XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[_net_wm_name],
2899 atoms[utf8_string], 8, PropModeReplace, (byte *)name, name ? strlen(name) : 0);
2900 XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[wm_name],
2901 atoms[utf8_string], 8, PropModeReplace, (byte *)name, name ? strlen(name) : 0);
2905 void PositionRootWindow(Window window, int x, int y, int w, int h, bool move, bool resize)
2907 //Logf("Position root window %s\n", window.name);
2908 if(window.windowHandle && (!window.parent || !window.parent.display))
2910 if(window.visible && window.created)
2912 long t = (window.creationActivation == activate && guiApp.desktop.active) ? (int)timeStamp : 0;
2913 XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[_net_wm_user_time],
2914 XA_CARDINAL,32,PropModeReplace, (byte *)&t, 1);
2915 XMapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
2917 if(window.state == minimized && atomsSupported[_net_wm_state]) return;
2919 if(window.nativeDecorations)
2921 XWindowData windowData = window.windowData;
2923 // Was commenting this out was part of #700/#795 fix, but this causes jumping of e.g. About box after getting frame extents PropertyNotify
2925 // && window.state != maximized -- required for Cinnamon on Mint 14/15
2926 if(!windowData.gotFrameExtents && window.state != maximized)
2928 if(WaitForFrameExtents(window, false))
2930 x += windowData.decor.left;
2931 y += windowData.decor.top ;
2933 w += windowData.decor.left + windowData.decor.right;
2934 h += windowData.decor.top + windowData.decor.bottom;
2938 x -= windowData.decor.left;
2939 y -= windowData.decor.top;
2941 w -= windowData.decor.left + windowData.decor.right;
2942 h -= windowData.decor.top + windowData.decor.bottom;
2944 // Tweak for first unmaximize on Unity on Ubuntu 11.10
2945 /*if(window.state == maximized && (desktopX + w > desktopW || desktopY + h > desktopH))
2955 if(!fullScreenMode && (!atomsSupported[_net_wm_state] || (window.state != maximized || !window.visible)))
2958 XMoveResizeWindow(xGlobalDisplay, (X11Window)window.windowHandle, x, y, w, h);
2960 XMoveWindow(xGlobalDisplay, (X11Window)window.windowHandle, x, y);
2962 XResizeWindow(xGlobalDisplay, (X11Window)window.windowHandle, w, h);
2964 // Reset min/max for fixed size windows on WMs not looking at MWM_FUNC_RESIZE (e.g. Cinnamon)
2965 if(window.style.fixed && !window.style.sizable && window.state != maximized)
2967 XSizeHints hints = { 0 };
2969 XGetWMNormalHints(xGlobalDisplay, (X11Window)window.windowHandle, &hints, &supplied);
2970 hints.min_width = hints.max_width = w;
2971 hints.min_height = hints.max_height = h;
2972 hints.flags |= PMinSize|PMaxSize;
2973 XSetWMNormalHints(xGlobalDisplay, (X11Window)window.windowHandle, &hints);
2979 void OrderRootWindow(Window window, bool topMost)
2981 SetNETWMState((X11Window)window.windowHandle, false, topMost ? add : remove, atoms[_net_wm_state_above], 0);
2984 void SetRootWindowColor(Window window)
2989 void OffsetWindow(Window window, int * x, int * y)
2994 void UpdateRootWindow(Window window)
2996 if(!window.parent || !window.parent.display)
3000 Box box = window.box;
3001 box.left -= window.clientStart.x;
3002 box.top -= window.clientStart.y;
3003 box.right -= window.clientStart.x;
3004 box.bottom -= window.clientStart.y;
3005 // Logf("Update root window %s\n", window.name);
3006 window.Update(null);
3007 box.left += window.clientStart.x;
3008 box.top += window.clientStart.y;
3009 box.right += window.clientStart.x;
3010 box.bottom += window.clientStart.y;
3011 window.UpdateDirty(box);
3016 void SetRootWindowState(Window window, WindowState state, bool visible)
3018 WindowState curState = window.state;
3019 *&window.state = state;
3020 // Old WM (e.g. TWM), use built-in decorations
3021 if(!atomsSupported[_net_wm_state])
3022 window.nativeDecorations = false;
3023 if(!window.parent || !window.parent.display)
3025 XWindowData windowData = window.windowData;
3026 //Logf("Set root window state %d %s\n", state, window.name);
3029 if(!windowData.currentlyVisible)
3031 long t = (window.creationActivation == activate && guiApp.desktop.active) ? timeStamp : 0;
3032 XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[_net_wm_user_time],
3033 XA_CARDINAL,32,PropModeReplace, (byte *)&t, 1);
3034 XMapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
3035 windowData.currentlyVisible = true;
3036 WaitForViewableWindow(window);
3037 if(window.creationActivation == activate && guiApp.desktop.active && state != minimized)
3038 ActivateRootWindow(window);
3041 if(fullScreenMode && state != minimized)
3043 int w = XDisplayWidth(xGlobalDisplay, DefaultScreen(xGlobalDisplay));
3044 int h = XDisplayHeight(xGlobalDisplay, DefaultScreen(xGlobalDisplay));
3045 SetNETWMState((X11Window)window.windowHandle, true, add, atoms[_net_wm_state_fullscreen], 0);
3046 XMoveResizeWindow(xGlobalDisplay, (X11Window)window.windowHandle, 0, 0, w, h);
3048 guiApp.SetDesktopPosition(0, 0, w, h, true);
3049 window.Position(0, 0, w, h, true, true, true, true, false, false);
3052 if(state == minimized && atomsSupported[_net_wm_state])
3054 //uint iconic = IconicState;
3056 // SetNETWMState(window.windowHandle, true, add, atoms[_net_wm_state_hidden], null);
3058 XChangeProperty(xGlobalDisplay, window.windowHandle, atoms[wm_state], XA_CARDINAL, 32,
3059 PropModeReplace, &iconic, 1);
3063 XClientMessageEvent event = { 0 };
3064 event.type = ClientMessage;
3065 event.message_type = atoms[wm_state];
3066 event.display = xGlobalDisplay;
3067 event.window = window.windowHandle;
3068 event.send_event = 1;
3070 event.data.l[0] = IconicState;
3071 XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, &event);
3074 // printf("Attempting to minimize %s\n", window._class.name);
3076 XIconifyWindow(xGlobalDisplay, (X11Window)window.windowHandle, DefaultScreen(xGlobalDisplay));
3078 else if(!fullScreenMode)
3080 //((XWindowData)window.windowData).gotFrameExtents && (!window.nativeDecorations || window.state == state))
3081 if(!atomsSupported[_net_wm_state] || (!((XWindowData)window.windowData).gotFrameExtents && window.state == maximized))
3083 // Running this block avoids the initial IDE maximized->unmaximized flicker
3084 //if(window.state != maximized || !atomsSupported[_net_wm_state] || window.nativeDecorations)
3086 int x = window.position.x;
3087 int y = window.position.y;
3088 int w = window.size.w;
3089 int h = window.size.h;
3091 if(window.nativeDecorations)
3093 XWindowData windowData = window.windowData;
3094 x -= windowData.decor.left;
3095 y -= windowData.decor.top;
3097 w -= windowData.decor.left + windowData.decor.right;
3098 h -= windowData.decor.top + windowData.decor.bottom;
3103 XMoveResizeWindow(xGlobalDisplay,
3104 (X11Window)window.windowHandle,
3107 UpdateRootWindow(window);
3109 if(atomsSupported[_net_wm_state])
3111 // Maximize / Restore the window
3112 if(curState != state)
3113 SetNETWMState((X11Window)window.windowHandle, true, state == maximized ? add : remove,
3114 atoms[_net_wm_state_maximized_vert], atoms[_net_wm_state_maximized_horz]);
3116 if(state == maximized)
3118 // Prevent the code in ConfigureNotify to think the window has been unmaximized
3119 // if the Window Manager hasn't set the hints yet.
3120 XFlush(xGlobalDisplay);
3128 XUnmapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
3129 windowData.currentlyVisible = false;
3131 //XFlush(xGlobalDisplay);
3133 *&window.state = curState;
3136 void FlashRootWindow(Window window)
3138 void * hwnd = window.windowHandle;
3139 Window master = window.master, rootWindow = (master && master != guiApp.desktop) ? master.rootWindow : null;
3140 if(!window.style.showInTaskBar && rootWindow && (window._isModal || window.style.interim))
3141 hwnd = rootWindow.windowHandle;
3143 // printf("Attempting to flash root window\n");
3144 SetNETWMState((X11Window)hwnd, true, add, atoms[_net_wm_state_demands_attention], 0);
3147 void ActivateRootWindow(Window window)
3149 if(!window.parent || !window.parent.display)
3151 if(!window.style.hidden && window.created)
3153 XWindowData windowData = window.windowData;
3154 //printf("Activate root window %s\n", window._class.name);
3155 if(!windowData.currentlyVisible)
3157 long t = (window.creationActivation == activate && guiApp.desktop.active) ? timeStamp : 0;
3158 XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[_net_wm_user_time],
3159 XA_CARDINAL,32,PropModeReplace, (byte *)&t, 1);
3160 XMapWindow(xGlobalDisplay, (X11Window)window.windowHandle);
3161 WaitForViewableWindow(window);
3162 windowData.currentlyVisible = true;
3164 XRaiseWindow(xGlobalDisplay, (X11Window)window.windowHandle);
3165 if(atomsSupported[_net_active_window])
3167 XClientMessageEvent event = { 0 };
3168 event.type = ClientMessage;
3169 event.message_type = atoms[_net_active_window];
3170 event.display = xGlobalDisplay;
3172 event.window = (X11Window)window.windowHandle;
3173 event.send_event = 1;
3175 event.data.l[0] = /*0*/ 1;
3176 // WMs will complain about using CurrentTime here, but when ActivateRootWindow() is called we really need to take over,
3177 // otherwise a debugged application stays on top of the IDE when we hit a breakpoint (there was no user interaction with the IDE,
3178 // but it really should be activated)
3179 event.data.l[1] = CurrentTime; //timeStamp;
3180 event.data.l[2] = activeWindow; //guiApp.desktop.activeChild.windowHandle;
3183 //printf("(ActivateRootWindow) Setting _NET_ACTIVE_WINDOW for %s (%x)\n", window._class.name, window);
3186 XSendEvent(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), bool::false, SubstructureRedirectMask | SubstructureNotifyMask, (union _XEvent *)&event);
3187 //#if defined(__APPLE__)
3188 XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToParent, CurrentTime);
3192 XSetInputFocus(xGlobalDisplay, (X11Window)window.windowHandle, RevertToParent, CurrentTime);
3197 // --- Mouse-based window movement ---
3199 void StartMoving(Window window, int x, int y, bool fromKeyBoard)
3204 void StopMoving(Window window)
3209 // -- Mouse manipulation ---
3211 void GetMousePosition(int *x, int *y)
3213 X11Window rootWindow, childWindow;
3216 ((GuiApplication)__thisModule.application).Lock();
3217 //XLockDisplay(xGlobalDisplay);
3218 XQueryPointer(xGlobalDisplay, DefaultRootWindow(xGlobalDisplay), &childWindow,
3219 &rootWindow, x, y, &mx, &my, &state);
3220 //XUnlockDisplay(xGlobalDisplay);
3221 ((GuiApplication)__thisModule.application).Unlock();
3224 void SetMousePosition(int x, int y)
3226 XWarpPointer(xGlobalDisplay, None, DefaultRootWindow(xGlobalDisplay), 0, 0, 0, 0, x, y);
3227 XFlush(xGlobalDisplay);
3230 void SetMouseRange(Window window, Box box)
3232 ((GuiApplication)__thisModule.application).Lock();
3233 //XLockDisplay(xGlobalDisplay);
3234 if(box && box.left > 0 && box.top > 0 &&
3235 box.right < guiApp.desktop.clientSize.w - 1 && box.bottom < guiApp.desktop.clientSize.h - 1)
3237 if(!window.parent || !window.parent.display)
3239 XMoveResizeWindow(xGlobalDisplay, confineWindow, box.left /*+ desktopX*/, box.top /*+ desktopY*/,
3240 box.right - box.left + 1, box.bottom - box.top + 1);
3242 if(!restrictedWindow)
3243 XMapWindow(xGlobalDisplay, confineWindow);
3245 XGrabPointer(xGlobalDisplay, (X11Window) window.rootWindow.windowHandle, False,
3246 ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
3247 GrabModeAsync, confineWindow, fullScreenMode ? nullCursor : None, CurrentTime);
3249 restrictedWindow = window;
3252 else if(restrictedWindow)
3254 if(capturedWindow != None)
3256 XGrabPointer(xGlobalDisplay, (X11Window)capturedWindow,
3257 False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
3258 GrabModeAsync, None, fullScreenMode ? nullCursor : None, CurrentTime);
3261 XUngrabPointer(xGlobalDisplay, CurrentTime);
3263 if(restrictedWindow)
3264 XUnmapWindow(xGlobalDisplay, confineWindow);
3266 restrictedWindow = null;
3268 //XUnlockDisplay(xGlobalDisplay);
3269 ((GuiApplication)__thisModule.application).Unlock();
3272 void SetMouseCapture(Window window)
3274 //*XLockDisplay(xGlobalDisplay);
3277 if(!window.parent || !window.parent.display)
3279 XGrabPointer(xGlobalDisplay, (X11Window)window.windowHandle,
3280 False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
3281 GrabModeAsync, restrictedWindow ? confineWindow : None, fullScreenMode ? nullCursor : None, CurrentTime);
3283 capturedWindow = (X11Window) window.windowHandle;
3286 else if(capturedWindow != None)
3288 if(restrictedWindow)
3289 XGrabPointer(xGlobalDisplay, (X11Window) restrictedWindow.rootWindow.windowHandle, False,
3290 ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
3291 GrabModeAsync, confineWindow, fullScreenMode ? nullCursor : None, CurrentTime);
3293 XUngrabPointer(xGlobalDisplay, CurrentTime);
3294 capturedWindow = None;
3296 //*XUnlockDisplay(xGlobalDisplay);
3299 // -- Mouse cursor ---
3301 void SetMouseCursor(Window window, int cursor)
3303 if(window.rootWindow.windowHandle)
3304 XDefineCursor(xGlobalDisplay, (X11Window) window.rootWindow.windowHandle,
3305 (acquiredInputWindow || cursor == -1) ? nullCursor : systemCursors[(SystemCursor)cursor]);
3310 void SetCaret(int x, int y, int size)
3312 Window caretOwner = guiApp.caretOwner;
3313 Window window = caretOwner ? caretOwner.rootWindow : null;
3314 if(window && window.windowData && setICPosition)
3316 XWindowData windowData = window.windowData;
3317 if(windowData && windowData.ic)
3319 XPoint cursor_location =
3321 (short)(caretOwner.caretPos.x - caretOwner.scroll.x + caretOwner.absPosition.x - window.absPosition.x),
3322 (short)(caretOwner.caretPos.y - caretOwner.scroll.y + caretOwner.absPosition.y - window.absPosition.y)
3324 XVaNestedList argList = XVaCreateNestedList(0, XNSpotLocation, &cursor_location, NULL);
3325 XSetICValues(windowData.ic, XNPreeditAttributes, argList, NULL);
3330 void ClearClipboard()
3332 //*XLockDisplay(xGlobalDisplay);
3335 delete clipBoardData;
3336 XSetSelectionOwner(xGlobalDisplay, atoms[clipboard], None, CurrentTime);
3338 //*XUnlockDisplay(xGlobalDisplay);
3341 bool AllocateClipboard(ClipBoard clipBoard, uint size)
3343 bool result = false;
3344 if((clipBoard.text = new0 byte[size]))
3349 bool SaveClipboard(ClipBoard clipBoard)
3351 bool result = false;
3352 //*XLockDisplay(xGlobalDisplay);
3355 Window rootWindow = guiApp.desktop;
3358 for(rootWindow = rootWindow.children.first;
3359 rootWindow && !rootWindow.windowHandle;
3360 rootWindow = rootWindow.next);
3363 delete clipBoardData;
3365 XSetSelectionOwner(xGlobalDisplay, atoms[clipboard],
3366 (X11Window) rootWindow.windowHandle, CurrentTime);
3367 clipBoardData = clipBoard.text;
3368 clipBoard.text = null;
3371 //*XUnlockDisplay(xGlobalDisplay);
3375 bool LoadClipboard(ClipBoard clipBoard)
3377 bool result = false;
3379 //*XLockDisplay(xGlobalDisplay);
3380 // The data is inside this client...
3383 clipBoard.text = new char[strlen(clipBoardData)+1];
3384 strcpy(clipBoard.text, clipBoardData);
3387 // The data is with another client...
3390 Window rootWindow = guiApp.desktop;
3393 for(rootWindow = rootWindow.children.first;
3394 rootWindow && !rootWindow.windowHandle;
3395 rootWindow = rootWindow.next);
3399 Atom selAtom = atoms[clipboard];
3400 X11Window owner = XGetSelectionOwner(xGlobalDisplay, selAtom);
3404 for(atom = atoms[utf8_string]; atom; atom = ((atom == atoms[utf8_string]) ? XA_STRING : 0))
3407 XConvertSelection(xGlobalDisplay, selAtom, atom, atoms[app_selection] /*None*/, (X11Window) rootWindow.windowHandle, CurrentTime);
3408 XIfEvent(xGlobalDisplay, (XEvent *) &e, EventChecker, (void *)SelectionNotify);
3409 if(e.type == SelectionNotify)
3411 XSelectionEvent * selection = (XSelectionEvent *) &e;
3412 //printf("Got a SelectionNotify with %d (%s)\n", selection->_property, XGetAtomName(xGlobalDisplay, selection->_property));
3414 unsigned long len, size = 0, dummy;
3417 XGetWindowProperty(xGlobalDisplay, (X11Window) rootWindow.windowHandle, selection->_property ? selection->_property : atom, 0, 0, False, AnyPropertyType, &type, &format, &len, &size, &data);
3425 if(XGetWindowProperty(xGlobalDisplay, (X11Window) rootWindow.windowHandle, selection->_property ? selection->_property : atom, 0, size, False,
3426 AnyPropertyType, &type,&format,&len, &dummy, &data) == Success)
3428 clipBoard.text = new char[size+1];
3429 strncpy(clipBoard.text, (char *)data, size);
3430 clipBoard.text[size] = '\0';
3441 //*XUnlockDisplay(xGlobalDisplay);
3445 void UnloadClipboard(ClipBoard clipBoard)
3447 delete clipBoard.text;
3450 // --- State based input ---
3452 bool AcquireInput(Window window, bool state)
3456 GetMousePosition(&acquireStart.x, &acquireStart.y);
3457 lastMouse = acquireStart;
3458 acquiredInputWindow = window;
3459 incref acquiredInputWindow;
3461 else if(acquiredInputWindow)
3462 delete acquiredInputWindow;
3466 bool GetMouseState(MouseButtons * buttons, int * x, int * y)
3468 bool result = false;
3469 if(acquiredInputWindow && guiApp.desktop.active)
3471 if(x) *x = lastMouse.x - acquireStart.x;
3472 if(y) *y = lastMouse.y - acquireStart.y;
3473 *buttons = buttonsState;
3474 SetMousePosition(acquireStart.x, acquireStart.y);
3475 lastMouse = acquireStart;
3482 if(buttons) *buttons = 0;
3487 bool GetJoystickState(int device, Joystick joystick)
3489 bool result = false;
3490 #if defined(__linux__)
3491 if(joystick && device < 4)
3493 struct JS_DATA_TYPE js = { 0 };
3494 memset(joystick, 0, sizeof(Joystick));
3495 if(joystickFD[device] && read(joystickFD[device], &js, JS_RETURN) == JS_RETURN)
3497 joystick.buttons = js.buttons;
3498 joystick.x = js.x - 128;
3499 joystick.y = js.y - 128;
3507 bool GetKeyState(Key key)
3509 if(key == capsState || key == numState || key == scrollState)
3516 case capsState: atom = atoms[capsLock]; idx = 0; break;
3517 case numState: atom = atoms[numLock]; idx = 1; break;
3518 case scrollState: atom = atoms[scrollLock]; idx = 2; break;
3520 /*XkbGetIndicatorState(xGlobalDisplay, XkbUseCoreKbd, &state);
3521 state = (state & (1 << idx)) ? 1 : 0;*/
3522 XkbGetNamedIndicator(xGlobalDisplay, /*XkbUseCoreKbd,*/ atom, &idx, &state, NULL, NULL);
3528 return keyStates[leftAlt] || keyStates[rightAlt];
3529 else if(key == shift)
3530 return keyStates[leftShift] || keyStates[rightShift];
3531 else if(key == control)
3532 return keyStates[leftControl] || keyStates[rightControl];
3534 return keyStates[key.code];
3538 void SetTimerResolution(uint hertz)
3540 timerDelay = hertz ? (1000000 / hertz) : MAXINT;
3545 hiResTimer.delay = 1000000 / hertz;
3546 hiResTimer.Create();
3551 bool SetIcon(Window window, BitmapResource resource)
3556 if(bitmap.Load(resource.fileName, null, null))
3558 unsigned long * icon = new unsigned long[2 + bitmap.width * bitmap.height];
3559 bitmap.Convert(null, pixelFormat888, null);
3560 icon[0] = bitmap.width;
3561 icon[1] = bitmap.height;
3562 if(sizeof(long) != sizeof(uint32))
3565 for(c = 0; c < bitmap.width * bitmap.height; c++)
3566 icon[c+2] = ((uint32 *)bitmap.picture)[c];
3569 memcpy(icon + 2, bitmap.picture, bitmap.width * bitmap.height * sizeof(uint32));
3570 XChangeProperty(xGlobalDisplay, (X11Window)window.windowHandle, atoms[_net_wm_icon],
3571 XA_CARDINAL,32,PropModeReplace, (byte *)icon, 2+bitmap.width*bitmap.height);
3580 default dllexport void * IS_XGetDisplay()
3582 return xGlobalDisplay;
3585 default dllexport void * IS_XGetWindow(Window window)
3587 return window.windowHandle ? window.windowHandle : window.rootWindow.windowHandle;