X11: support multiple tablet devices.
[blender.git] / intern / ghost / intern / GHOST_SystemX11.cpp
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * Part of this code has been taken from Qt, under LGPL license
26  * Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
27  *
28  * ***** END GPL LICENSE BLOCK *****
29  */
30
31 /** \file ghost/intern/GHOST_SystemX11.cpp
32  *  \ingroup GHOST
33  */
34
35 #include <X11/Xatom.h>
36 #include <X11/keysym.h>
37 #include <X11/XKBlib.h> /* allow detectable autorepeate */
38 #include <X11/Xutil.h>
39
40 #include "GHOST_SystemX11.h"
41 #include "GHOST_WindowX11.h"
42 #include "GHOST_WindowManager.h"
43 #include "GHOST_TimerManager.h"
44 #include "GHOST_EventCursor.h"
45 #include "GHOST_EventKey.h"
46 #include "GHOST_EventButton.h"
47 #include "GHOST_EventWheel.h"
48 #include "GHOST_DisplayManagerX11.h"
49 #include "GHOST_EventDragnDrop.h"
50 #ifdef WITH_INPUT_NDOF
51 #  include "GHOST_NDOFManagerUnix.h"
52 #endif
53
54 #ifdef WITH_XDND
55 #  include "GHOST_DropTargetX11.h"
56 #endif
57
58 #include "GHOST_Debug.h"
59
60 #if defined(WITH_GL_EGL)
61 #  include "GHOST_ContextEGL.h"
62 #else
63 #  include "GHOST_ContextGLX.h"
64 #endif
65
66 #ifdef WITH_XF86KEYSYM
67 #include <X11/XF86keysym.h>
68 #endif
69
70 #ifdef WITH_X11_XFIXES
71 #  include <X11/extensions/Xfixes.h>
72 /* Workaround for XWayland grab glitch: T53004. */
73 #define WITH_XWAYLAND_HACK
74 #endif
75
76 /* for XIWarpPointer */
77 #ifdef WITH_X11_XINPUT
78 #  include <X11/extensions/XInput2.h>
79 #endif
80
81 /* For timing */
82 #include <sys/time.h>
83 #include <unistd.h>
84
85 #include <iostream>
86 #include <vector>
87 #include <stdio.h> /* for fprintf only */
88 #include <cstdlib> /* for exit */
89
90 /* for debugging - so we can breakpoint X11 errors */
91 // #define USE_X11_ERROR_HANDLERS
92
93 #ifdef WITH_X11_XINPUT
94 #  define USE_XINPUT_HOTPLUG
95 #endif
96
97 /* see [#34039] Fix Alt key glitch on Unity desktop */
98 #define USE_UNITY_WORKAROUND
99
100 /* Fix 'shortcut' part of keyboard reading code only ever using first defined keymap instead of active one.
101  * See T47228 and D1746 */
102 #define USE_NON_LATIN_KB_WORKAROUND
103
104 static GHOST_TKey ghost_key_from_keysym(
105         const KeySym key);
106 static GHOST_TKey ghost_key_from_keycode(
107         const XkbDescPtr xkb_descr, const KeyCode keycode);
108 static GHOST_TKey ghost_key_from_keysym_or_keycode(
109         const KeySym key, const XkbDescPtr xkb_descr, const KeyCode keycode);
110
111 /* these are for copy and select copy */
112 static char *txt_cut_buffer = NULL;
113 static char *txt_select_buffer = NULL;
114
115 #ifdef WITH_XWAYLAND_HACK
116 static bool use_xwayland_hack = false;
117 #endif
118
119 using namespace std;
120
121 GHOST_SystemX11::
122 GHOST_SystemX11(
123         )
124     : GHOST_System(),
125       m_xkb_descr(NULL),
126       m_start_time(0)
127 {
128         XInitThreads();
129         m_display = XOpenDisplay(NULL);
130
131         if (!m_display) {
132                 std::cerr << "Unable to open a display" << std::endl;
133                 abort(); /* was return before, but this would just mean it will crash later */
134         }
135
136 #ifdef USE_X11_ERROR_HANDLERS
137         (void) XSetErrorHandler(GHOST_X11_ApplicationErrorHandler);
138         (void) XSetIOErrorHandler(GHOST_X11_ApplicationIOErrorHandler);
139 #endif
140
141 #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
142         /* note -- don't open connection to XIM server here, because the locale
143          * has to be set before opening the connection but setlocale() has not
144          * been called yet.  the connection will be opened after entering
145          * the event loop. */
146         m_xim = NULL;
147 #endif
148
149 #define GHOST_INTERN_ATOM_IF_EXISTS(atom) { m_atom.atom = XInternAtom(m_display, #atom , True);  } (void)0
150 #define GHOST_INTERN_ATOM(atom)           { m_atom.atom = XInternAtom(m_display, #atom , False); } (void)0
151
152         GHOST_INTERN_ATOM_IF_EXISTS(WM_DELETE_WINDOW);
153         GHOST_INTERN_ATOM(WM_PROTOCOLS);
154         GHOST_INTERN_ATOM(WM_TAKE_FOCUS);
155         GHOST_INTERN_ATOM(WM_STATE);
156         GHOST_INTERN_ATOM(WM_CHANGE_STATE);
157         GHOST_INTERN_ATOM(_NET_WM_STATE);
158         GHOST_INTERN_ATOM(_NET_WM_STATE_MAXIMIZED_HORZ);
159         GHOST_INTERN_ATOM(_NET_WM_STATE_MAXIMIZED_VERT);
160
161         GHOST_INTERN_ATOM(_NET_WM_STATE_FULLSCREEN);
162         GHOST_INTERN_ATOM(_MOTIF_WM_HINTS);
163         GHOST_INTERN_ATOM(TARGETS);
164         GHOST_INTERN_ATOM(STRING);
165         GHOST_INTERN_ATOM(COMPOUND_TEXT);
166         GHOST_INTERN_ATOM(TEXT);
167         GHOST_INTERN_ATOM(CLIPBOARD);
168         GHOST_INTERN_ATOM(PRIMARY);
169         GHOST_INTERN_ATOM(XCLIP_OUT);
170         GHOST_INTERN_ATOM(INCR);
171         GHOST_INTERN_ATOM(UTF8_STRING);
172 #ifdef WITH_X11_XINPUT
173         m_atom.TABLET = XInternAtom(m_display, XI_TABLET, False);
174 #endif
175
176 #undef GHOST_INTERN_ATOM_IF_EXISTS
177 #undef GHOST_INTERN_ATOM
178
179         m_last_warp = 0;
180         m_last_release_keycode = 0;
181         m_last_release_time = 0;
182
183         /* compute the initial time */
184         timeval tv;
185         if (gettimeofday(&tv, NULL) == -1) {
186                 GHOST_ASSERT(false, "Could not instantiate timer!");
187         }
188
189         /* Taking care not to overflow the tv.tv_sec * 1000 */
190         m_start_time = GHOST_TUns64(tv.tv_sec) * 1000 + tv.tv_usec / 1000;
191
192
193         /* use detectable autorepeate, mac and windows also do this */
194         int use_xkb;
195         int xkb_opcode, xkb_event, xkb_error;
196         int xkb_major = XkbMajorVersion, xkb_minor = XkbMinorVersion;
197
198         use_xkb = XkbQueryExtension(m_display, &xkb_opcode, &xkb_event, &xkb_error, &xkb_major, &xkb_minor);
199         if (use_xkb) {
200                 XkbSetDetectableAutoRepeat(m_display, true, NULL);
201
202                 m_xkb_descr = XkbGetMap(m_display, 0, XkbUseCoreKbd);
203                 if (m_xkb_descr) {
204                         XkbGetNames(m_display, XkbKeyNamesMask, m_xkb_descr);
205                 }
206         }
207
208 #ifdef WITH_XWAYLAND_HACK
209         use_xwayland_hack = getenv("WAYLAND_DISPLAY") != NULL;
210 #endif
211
212 #ifdef WITH_X11_XINPUT
213         /* detect if we have xinput (for reuse) */
214         {
215                 memset(&m_xinput_version, 0, sizeof(m_xinput_version));
216                 XExtensionVersion *version = XGetExtensionVersion(m_display, INAME);
217                 if (version && (version != (XExtensionVersion *)NoSuchExtension)) {
218                         if (version->present) {
219                                 m_xinput_version = *version;
220                         }
221                         XFree(version);
222                 }
223         }
224
225 #ifdef USE_XINPUT_HOTPLUG
226         if (m_xinput_version.present) {
227                 XEventClass class_presence;
228                 int xi_presence;
229                 DevicePresence(m_display, xi_presence, class_presence);
230                 XSelectExtensionEvent(
231                         m_display,
232                         RootWindow(m_display, DefaultScreen(m_display)),
233                         &class_presence, 1);
234                 (void)xi_presence;
235         }
236 #endif  /* USE_XINPUT_HOTPLUG */
237
238         refreshXInputDevices();
239 #endif  /* WITH_X11_XINPUT */
240 }
241
242 GHOST_SystemX11::
243 ~GHOST_SystemX11()
244 {
245 #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
246         if (m_xim) {
247                 XCloseIM(m_xim);
248         }
249 #endif
250
251 #ifdef WITH_X11_XINPUT
252         /* Close tablet devices. */
253         clearXInputDevices();
254 #endif /* WITH_X11_XINPUT */
255
256         if (m_xkb_descr) {
257                 XkbFreeKeyboard (m_xkb_descr, XkbAllComponentsMask, true);
258         }
259
260         XCloseDisplay(m_display);
261 }
262
263
264 GHOST_TSuccess
265 GHOST_SystemX11::
266 init()
267 {
268         GHOST_TSuccess success = GHOST_System::init();
269
270         if (success) {
271 #ifdef WITH_INPUT_NDOF
272                 m_ndofManager = new GHOST_NDOFManagerUnix(*this);
273 #endif
274                 m_displayManager = new GHOST_DisplayManagerX11(this);
275
276                 if (m_displayManager) {
277                         return GHOST_kSuccess;
278                 }
279         }
280
281         return GHOST_kFailure;
282 }
283
284 GHOST_TUns64
285 GHOST_SystemX11::
286 getMilliSeconds() const
287 {
288         timeval tv;
289         if (gettimeofday(&tv, NULL) == -1) {
290                 GHOST_ASSERT(false, "Could not compute time!");
291         }
292
293         /* Taking care not to overflow the tv.tv_sec * 1000 */
294         return GHOST_TUns64(tv.tv_sec) * 1000 + tv.tv_usec / 1000 - m_start_time;
295 }
296
297 GHOST_TUns8
298 GHOST_SystemX11::
299 getNumDisplays() const
300 {
301         return GHOST_TUns8(1);
302 }
303
304 /**
305  * Returns the dimensions of the main display on this system.
306  * \return The dimension of the main display.
307  */
308 void
309 GHOST_SystemX11::
310 getMainDisplayDimensions(
311                 GHOST_TUns32& width,
312                 GHOST_TUns32& height) const
313 {
314         if (m_display) {
315                 /* note, for this to work as documented,
316                  * we would need to use Xinerama check r54370 for code that did this,
317                  * we've since removed since its not worth the extra dep - campbell */
318                 getAllDisplayDimensions(width, height);
319         }
320 }
321
322
323 /**
324  * Returns the dimensions of the main display on this system.
325  * \return The dimension of the main display.
326  */
327 void
328 GHOST_SystemX11::
329 getAllDisplayDimensions(
330                 GHOST_TUns32& width,
331                 GHOST_TUns32& height) const
332 {
333         if (m_display) {
334                 width  = DisplayWidth(m_display, DefaultScreen(m_display));
335                 height = DisplayHeight(m_display, DefaultScreen(m_display));
336         }
337 }
338
339 /**
340  * Create a new window.
341  * The new window is added to the list of windows managed.
342  * Never explicitly delete the window, use disposeWindow() instead.
343  * \param       title   The name of the window (displayed in the title bar of the window if the OS supports it).
344  * \param       left    The coordinate of the left edge of the window.
345  * \param       top             The coordinate of the top edge of the window.
346  * \param       width   The width the window.
347  * \param       height  The height the window.
348  * \param       state   The state of the window when opened.
349  * \param       type    The type of drawing context installed in this window.
350  * \param glSettings: Misc OpenGL settings.
351  * \param exclusive: Use to show the window ontop and ignore others (used fullscreen).
352  * \param       parentWindow    Parent (embedder) window
353  * \return      The new window (or 0 if creation failed).
354  */
355 GHOST_IWindow *
356 GHOST_SystemX11::
357 createWindow(const STR_String& title,
358                 GHOST_TInt32 left,
359                 GHOST_TInt32 top,
360                 GHOST_TUns32 width,
361                 GHOST_TUns32 height,
362                 GHOST_TWindowState state,
363                 GHOST_TDrawingContextType type,
364                 GHOST_GLSettings glSettings,
365                 const bool exclusive,
366                 const GHOST_TEmbedderWindowID parentWindow)
367 {
368         GHOST_WindowX11 *window = NULL;
369
370         if (!m_display) return 0;
371
372         window = new GHOST_WindowX11(this, m_display, title,
373                                      left, top, width, height,
374                                      state, parentWindow, type,
375                                      ((glSettings.flags & GHOST_glStereoVisual) != 0), exclusive,
376                                      ((glSettings.flags & GHOST_glAlphaBackground) != 0),
377                                      glSettings.numOfAASamples, (glSettings.flags & GHOST_glDebugContext) != 0);
378
379         if (window) {
380                 /* Both are now handle in GHOST_WindowX11.cpp
381                  * Focus and Delete atoms. */
382
383                 if (window->getValid()) {
384                         /* Store the pointer to the window */
385                         m_windowManager->addWindow(window);
386                         m_windowManager->setActiveWindow(window);
387                         pushEvent(new GHOST_Event(getMilliSeconds(), GHOST_kEventWindowSize, window) );
388                 }
389                 else {
390                         delete window;
391                         window = NULL;
392                 }
393         }
394         return window;
395 }
396
397 bool GHOST_SystemX11::supportsNativeDialogs(void)
398 {
399         return false;
400 }
401
402 /**
403  * Create a new offscreen context.
404  * Never explicitly delete the context, use disposeContext() instead.
405  * \return  The new context (or 0 if creation failed).
406  */
407 GHOST_IContext *
408 GHOST_SystemX11::
409 createOffscreenContext()
410 {
411         // During development:
412         //   try 4.x compatibility profile
413         //   try 3.3 compatibility profile
414         //   fall back to 3.0 if needed
415         //
416         // Final Blender 2.8:
417         //   try 4.x core profile
418         //   try 3.3 core profile
419         //   no fallbacks
420
421 #if defined(WITH_GL_PROFILE_CORE)
422         {
423                 const char *version_major = (char*)glewGetString(GLEW_VERSION_MAJOR);
424                 if (version_major != NULL && version_major[0] == '1') {
425                         fprintf(stderr, "Error: GLEW version 2.0 and above is required.\n");
426                         abort();
427                 }
428         }
429 #endif
430
431         const int profile_mask =
432 #if defined(WITH_GL_PROFILE_CORE)
433                 GLX_CONTEXT_CORE_PROFILE_BIT_ARB;
434 #elif defined(WITH_GL_PROFILE_COMPAT)
435                 GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB;
436 #else
437 #  error // must specify either core or compat at build time
438 #endif
439
440         GHOST_Context *context;
441
442         for (int minor = 5; minor >= 0; --minor) {
443                 context = new GHOST_ContextGLX(
444                         false,
445                         0,
446                         (Window)NULL,
447                         m_display,
448                         (GLXFBConfig)NULL,
449                         profile_mask,
450                         4, minor,
451                         GHOST_OPENGL_GLX_CONTEXT_FLAGS | (false ? GLX_CONTEXT_DEBUG_BIT_ARB : 0),
452                         GHOST_OPENGL_GLX_RESET_NOTIFICATION_STRATEGY);
453
454                 if (context->initializeDrawingContext())
455                         return context;
456                 else
457                         delete context;
458         }
459
460         context = new GHOST_ContextGLX(
461                 false,
462                 0,
463                 (Window)NULL,
464                 m_display,
465                 (GLXFBConfig)NULL,
466                 profile_mask,
467                 3, 3,
468                 GHOST_OPENGL_GLX_CONTEXT_FLAGS | (false ? GLX_CONTEXT_DEBUG_BIT_ARB : 0),
469                 GHOST_OPENGL_GLX_RESET_NOTIFICATION_STRATEGY);
470
471         if (context->initializeDrawingContext())
472                 return context;
473         else
474                 delete context;
475
476         return NULL;
477 }
478
479 /**
480  * Dispose of a context.
481  * \param   context Pointer to the context to be disposed.
482  * \return  Indication of success.
483  */
484 GHOST_TSuccess
485 GHOST_SystemX11::
486 disposeContext(GHOST_IContext *context)
487 {
488         delete context;
489
490         return GHOST_kSuccess;
491 }
492
493 #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
494 static void destroyIMCallback(XIM /*xim*/, XPointer ptr, XPointer /*data*/)
495 {
496         GHOST_PRINT("XIM server died\n");
497
498         if (ptr)
499                 *(XIM *)ptr = NULL;
500 }
501
502 bool GHOST_SystemX11::openX11_IM()
503 {
504         if (!m_display)
505                 return false;
506
507         /* set locale modifiers such as "@im=ibus" specified by XMODIFIERS */
508         XSetLocaleModifiers("");
509
510         m_xim = XOpenIM(m_display, NULL, (char *)GHOST_X11_RES_NAME, (char *)GHOST_X11_RES_CLASS);
511         if (!m_xim)
512                 return false;
513
514         XIMCallback destroy;
515         destroy.callback = (XIMProc)destroyIMCallback;
516         destroy.client_data = (XPointer)&m_xim;
517         XSetIMValues(m_xim, XNDestroyCallback, &destroy, NULL);
518         return true;
519 }
520 #endif
521
522 GHOST_WindowX11 *
523 GHOST_SystemX11::
524 findGhostWindow(
525                 Window xwind) const
526 {
527
528         if (xwind == 0) return NULL;
529
530         /* It is not entirely safe to do this as the backptr may point
531          * to a window that has recently been removed.
532          * We should always check the window manager's list of windows
533          * and only process events on these windows. */
534
535         vector<GHOST_IWindow *> & win_vec = m_windowManager->getWindows();
536
537         vector<GHOST_IWindow *>::iterator win_it = win_vec.begin();
538         vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end();
539
540         for (; win_it != win_end; ++win_it) {
541                 GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
542                 if (window->getXWindow() == xwind) {
543                         return window;
544                 }
545         }
546         return NULL;
547
548 }
549
550 static void SleepTillEvent(Display *display, GHOST_TInt64 maxSleep)
551 {
552         int fd = ConnectionNumber(display);
553         fd_set fds;
554
555         FD_ZERO(&fds);
556         FD_SET(fd, &fds);
557
558         if (maxSleep == -1) {
559                 select(fd + 1, &fds, NULL, NULL, NULL);
560         }
561         else {
562                 timeval tv;
563
564                 tv.tv_sec = maxSleep / 1000;
565                 tv.tv_usec = (maxSleep - tv.tv_sec * 1000) * 1000;
566
567                 select(fd + 1, &fds, NULL, NULL, &tv);
568         }
569 }
570
571 /* This function borrowed from Qt's X11 support
572  * qclipboard_x11.cpp
573  *  */
574 struct init_timestamp_data {
575         Time timestamp;
576 };
577
578 static Bool init_timestamp_scanner(Display *, XEvent *event, XPointer arg)
579 {
580         init_timestamp_data *data =
581             reinterpret_cast<init_timestamp_data *>(arg);
582         switch (event->type) {
583                 case ButtonPress:
584                 case ButtonRelease:
585                         data->timestamp = event->xbutton.time;
586                         break;
587                 case MotionNotify:
588                         data->timestamp = event->xmotion.time;
589                         break;
590                 case KeyPress:
591                 case KeyRelease:
592                         data->timestamp = event->xkey.time;
593                         break;
594                 case PropertyNotify:
595                         data->timestamp = event->xproperty.time;
596                         break;
597                 case EnterNotify:
598                 case LeaveNotify:
599                         data->timestamp = event->xcrossing.time;
600                         break;
601                 case SelectionClear:
602                         data->timestamp = event->xselectionclear.time;
603                         break;
604                 default:
605                         break;
606         }
607
608         return false;
609 }
610
611 Time
612 GHOST_SystemX11::
613 lastEventTime(Time default_time) {
614         init_timestamp_data data;
615         data.timestamp = default_time;
616         XEvent ev;
617         XCheckIfEvent(m_display, &ev, &init_timestamp_scanner, (XPointer) & data);
618
619         return data.timestamp;
620 }
621
622 bool
623 GHOST_SystemX11::
624 processEvents(
625                 bool waitForEvent)
626 {
627         /* Get all the current events -- translate them into
628          * ghost events and call base class pushEvent() method. */
629
630         bool anyProcessed = false;
631
632         do {
633                 GHOST_TimerManager *timerMgr = getTimerManager();
634
635                 if (waitForEvent && m_dirty_windows.empty() && !XPending(m_display)) {
636                         GHOST_TUns64 next = timerMgr->nextFireTime();
637
638                         if (next == GHOST_kFireTimeNever) {
639                                 SleepTillEvent(m_display, -1);
640                         }
641                         else {
642                                 GHOST_TInt64 maxSleep = next - getMilliSeconds();
643
644                                 if (maxSleep >= 0)
645                                         SleepTillEvent(m_display, next - getMilliSeconds());
646                         }
647                 }
648
649                 if (timerMgr->fireTimers(getMilliSeconds())) {
650                         anyProcessed = true;
651                 }
652
653                 while (XPending(m_display)) {
654                         XEvent xevent;
655                         XNextEvent(m_display, &xevent);
656
657 #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
658                         /* open connection to XIM server and create input context (XIC)
659                          * when receiving the first FocusIn or KeyPress event after startup,
660                          * or recover XIM and XIC when the XIM server has been restarted */
661                         if (xevent.type == FocusIn || xevent.type == KeyPress) {
662                                 if (!m_xim && openX11_IM()) {
663                                         GHOST_PRINT("Connected to XIM server\n");
664                                 }
665
666                                 if (m_xim) {
667                                         GHOST_WindowX11 * window = findGhostWindow(xevent.xany.window);
668                                         if (window && !window->getX11_XIC() && window->createX11_XIC()) {
669                                                 GHOST_PRINT("XIM input context created\n");
670                                                 if (xevent.type == KeyPress)
671                                                         /* we can assume the window has input focus
672                                                          * here, because key events are received only
673                                                          * when the window is focused. */
674                                                         XSetICFocus(window->getX11_XIC());
675                                         }
676                                 }
677                         }
678
679                         /* dispatch event to XIM server */
680                         if ((XFilterEvent(&xevent, (Window)NULL) == True)) {
681                                 /* do nothing now, the event is consumed by XIM. */
682                                 continue;
683                         }
684 #endif
685                         /* when using autorepeat, some keypress events can actually come *after* the
686                          * last keyrelease. The next code takes care of that */
687                         if (xevent.type == KeyRelease) {
688                                 m_last_release_keycode = xevent.xkey.keycode;
689                                 m_last_release_time = xevent.xkey.time;
690                         }
691                         else if (xevent.type == KeyPress) {
692                                 if ((xevent.xkey.keycode == m_last_release_keycode) && ((xevent.xkey.time <= m_last_release_time)))
693                                         continue;
694                         }
695
696                         processEvent(&xevent);
697                         anyProcessed = true;
698
699
700 #ifdef USE_UNITY_WORKAROUND
701                         /* note: processEvent() can't include this code because
702                          * KeymapNotify event have no valid window information. */
703
704                         /* the X server generates KeymapNotify event immediately after
705                          * every EnterNotify and FocusIn event.  we handle this event
706                          * to correct modifier states. */
707                         if (xevent.type == FocusIn) {
708                                 /* use previous event's window, because KeymapNotify event
709                                  * has no window information. */
710                                 GHOST_WindowX11 *window = findGhostWindow(xevent.xany.window);
711                                 if (window && XPending(m_display) >= 2) {
712                                         XNextEvent(m_display, &xevent);
713
714                                         if (xevent.type == KeymapNotify) {
715                                                 XEvent xev_next;
716
717                                                 /* check if KeyPress or KeyRelease event was generated
718                                                  * in order to confirm the window is active. */
719                                                 XPeekEvent(m_display, &xev_next);
720
721                                                 if (xev_next.type == KeyPress || xev_next.type == KeyRelease) {
722                                                         /* XK_Hyper_L/R currently unused */
723                                                         const static KeySym modifiers[8] = {XK_Shift_L, XK_Shift_R,
724                                                                                             XK_Control_L, XK_Control_R,
725                                                                                             XK_Alt_L, XK_Alt_R,
726                                                                                             XK_Super_L, XK_Super_R};
727
728                                                         for (int i = 0; i < (sizeof(modifiers) / sizeof(*modifiers)); i++) {
729                                                                 KeyCode kc = XKeysymToKeycode(m_display, modifiers[i]);
730                                                                 if (((xevent.xkeymap.key_vector[kc >> 3] >> (kc & 7)) & 1) != 0) {
731                                                                         pushEvent(new GHOST_EventKey(
732                                                                                       getMilliSeconds(),
733                                                                                       GHOST_kEventKeyDown,
734                                                                                       window,
735                                                                                       ghost_key_from_keysym(modifiers[i]),
736                                                                                       '\0',
737                                                                                       NULL));
738                                                                 }
739                                                         }
740                                                 }
741                                         }
742                                 }
743                         }
744 #endif  /* USE_UNITY_WORKAROUND */
745
746                 }
747
748                 if (generateWindowExposeEvents()) {
749                         anyProcessed = true;
750                 }
751
752 #ifdef WITH_INPUT_NDOF
753                 if (static_cast<GHOST_NDOFManagerUnix *>(m_ndofManager)->processEvents()) {
754                         anyProcessed = true;
755                 }
756 #endif
757
758         } while (waitForEvent && !anyProcessed);
759
760         return anyProcessed;
761 }
762
763
764 #ifdef WITH_X11_XINPUT
765 static bool checkTabletProximity(Display *display, XDevice *device)
766 {
767         /* we could have true/false/not-found return value, but for now false is OK */
768
769         /* see: state.c from xinput, to get more data out of the device */
770         XDeviceState *state;
771
772         if (device == NULL) {
773                 return false;
774         }
775
776         /* needed since unplugging will abort() without this */
777         GHOST_X11_ERROR_HANDLERS_OVERRIDE(handler_store);
778
779         state = XQueryDeviceState(display, device);
780
781         GHOST_X11_ERROR_HANDLERS_RESTORE(handler_store);
782
783         if (state) {
784                 XInputClass *cls = state->data;
785                 // printf("%d class%s :\n", state->num_classes,
786                 //       (state->num_classes > 1) ? "es" : "");
787                 for (int loop = 0; loop < state->num_classes; loop++) {
788                         switch (cls->c_class) {
789                                 case ValuatorClass:
790                                         XValuatorState *val_state = (XValuatorState *)cls;
791                                         // printf("ValuatorClass Mode=%s Proximity=%s\n",
792                                         //        val_state->mode & 1 ? "Absolute" : "Relative",
793                                         //        val_state->mode & 2 ? "Out" : "In");
794
795                                         if ((val_state->mode & 2) == 0) {
796                                                 XFreeDeviceState(state);
797                                                 return true;
798                                         }
799                                         break;
800                         }
801                         cls = (XInputClass *) ((char *)cls + cls->length);
802                 }
803                 XFreeDeviceState(state);
804         }
805         return false;
806 }
807 #endif /* WITH_X11_XINPUT */
808
809 void
810 GHOST_SystemX11::processEvent(XEvent *xe)
811 {
812         GHOST_WindowX11 *window = findGhostWindow(xe->xany.window);
813         GHOST_Event *g_event = NULL;
814
815 #ifdef USE_XINPUT_HOTPLUG
816         /* Hot-Plug support */
817         if (m_xinput_version.present) {
818                 XEventClass class_presence;
819                 int xi_presence;
820
821                 DevicePresence(m_display, xi_presence, class_presence);
822                 (void)class_presence;
823
824                 if (xe->type == xi_presence) {
825                         XDevicePresenceNotifyEvent *notify_event = (XDevicePresenceNotifyEvent *)xe;
826                         if ((notify_event->devchange == DeviceEnabled) ||
827                             (notify_event->devchange == DeviceDisabled) ||
828                             (notify_event->devchange == DeviceAdded) ||
829                             (notify_event->devchange == DeviceRemoved))
830                         {
831                                 refreshXInputDevices();
832
833                                 /* update all window events */
834                                 {
835                                         vector<GHOST_IWindow *> & win_vec = m_windowManager->getWindows();
836                                         vector<GHOST_IWindow *>::iterator win_it = win_vec.begin();
837                                         vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end();
838
839                                         for (; win_it != win_end; ++win_it) {
840                                                 GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
841                                                 window->refreshXInputDevices();
842                                         }
843                                 }
844                         }
845                 }
846         }
847 #endif  /* USE_XINPUT_HOTPLUG */
848
849
850         if (!window) {
851                 return;
852         }
853
854 #ifdef WITH_X11_XINPUT
855         /* Proximity-Out Events are not reliable, if the tablet is active - check on each event
856          * this adds a little overhead but only while the tablet is in use.
857          * in the future we could have a ghost call window->CheckTabletProximity()
858          * but for now enough parts of the code are checking 'Active'
859          * - campbell */
860         if (window->GetTabletData()->Active != GHOST_kTabletModeNone) {
861                 bool any_proximity = false;
862
863                 for (GHOST_TabletX11& xtablet: m_xtablets) {
864                         if (checkTabletProximity(xe->xany.display, xtablet.Device)) {
865                                 any_proximity = true;
866                         }
867                 }
868
869                 if (!any_proximity) {
870                         // printf("proximity disable\n");
871                         window->GetTabletData()->Active = GHOST_kTabletModeNone;
872                 }
873         }
874 #endif /* WITH_X11_XINPUT */
875         switch (xe->type) {
876                 case Expose:
877                 {
878                         XExposeEvent & xee = xe->xexpose;
879
880                         if (xee.count == 0) {
881                                 /* Only generate a single expose event
882                                  * per read of the event queue. */
883
884                                 g_event = new
885                                           GHOST_Event(
886                                     getMilliSeconds(),
887                                     GHOST_kEventWindowUpdate,
888                                     window
889                                     );
890                         }
891                         break;
892                 }
893
894                 case MotionNotify:
895                 {
896                         XMotionEvent &xme = xe->xmotion;
897
898 #ifdef WITH_X11_XINPUT
899                         bool is_tablet = window->GetTabletData()->Active != GHOST_kTabletModeNone;
900 #else
901                         bool is_tablet = false;
902 #endif
903
904                         if (is_tablet == false && window->getCursorGrabModeIsWarp()) {
905                                 GHOST_TInt32 x_new = xme.x_root;
906                                 GHOST_TInt32 y_new = xme.y_root;
907                                 GHOST_TInt32 x_accum, y_accum;
908                                 GHOST_Rect bounds;
909
910                                 /* fallback to window bounds */
911                                 if (window->getCursorGrabBounds(bounds) == GHOST_kFailure)
912                                         window->getClientBounds(bounds);
913
914                                 /* could also clamp to screen bounds
915                                  * wrap with a window outside the view will fail atm  */
916                                 bounds.wrapPoint(x_new, y_new, 8); /* offset of one incase blender is at screen bounds */
917                                 window->getCursorGrabAccum(x_accum, y_accum);
918
919                                 if (x_new != xme.x_root || y_new != xme.y_root) {
920                                         if (xme.time > m_last_warp) {
921                                                 /* when wrapping we don't need to add an event because the
922                                                  * setCursorPosition call will cause a new event after */
923                                                 setCursorPosition(x_new, y_new); /* wrap */
924                                                 window->setCursorGrabAccum(x_accum + (xme.x_root - x_new), y_accum + (xme.y_root - y_new));
925                                                 m_last_warp = lastEventTime(xme.time);
926                                         }
927                                         else {
928                                                 setCursorPosition(x_new, y_new); /* wrap but don't accumulate */
929                                         }
930                                 }
931                                 else {
932                                         g_event = new
933                                                   GHOST_EventCursor(
934                                             getMilliSeconds(),
935                                             GHOST_kEventCursorMove,
936                                             window,
937                                             xme.x_root + x_accum,
938                                             xme.y_root + y_accum
939                                             );
940                                 }
941                         }
942                         else {
943                                 g_event = new
944                                           GHOST_EventCursor(
945                                     getMilliSeconds(),
946                                     GHOST_kEventCursorMove,
947                                     window,
948                                     xme.x_root,
949                                     xme.y_root
950                                     );
951                         }
952                         break;
953                 }
954
955                 case KeyPress:
956                 case KeyRelease:
957                 {
958                         XKeyEvent *xke = &(xe->xkey);
959                         KeySym key_sym;
960                         char ascii;
961 #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
962                         /* utf8_array[] is initial buffer used for Xutf8LookupString().
963                          * if the length of the utf8 string exceeds this array, allocate
964                          * another memory area and call Xutf8LookupString() again.
965                          * the last 5 bytes are used to avoid segfault that might happen
966                          * at the end of this buffer when the constructor of GHOST_EventKey
967                          * reads 6 bytes regardless of the effective data length. */
968                         char utf8_array[16 * 6 + 5]; /* 16 utf8 characters */
969                         char *utf8_buf = utf8_array;
970                         int len = 1; /* at least one null character will be stored */
971 #else
972                         char *utf8_buf = NULL;
973 #endif
974
975                         GHOST_TEventType type = (xke->type == KeyPress) ?  GHOST_kEventKeyDown : GHOST_kEventKeyUp;
976
977                         GHOST_TKey gkey;
978
979 #ifdef USE_NON_LATIN_KB_WORKAROUND
980                         /* XXX Code below is kinda awfully convoluted... Issues are:
981                          *
982                          *     - In keyboards like latin ones, numbers need a 'Shift' to be accessed but key_sym
983                          *       is unmodified (or anyone swapping the keys with xmodmap).
984                          *
985                          *     - XLookupKeysym seems to always use first defined keymap (see T47228), which generates
986                          *       keycodes unusable by ghost_key_from_keysym for non-latin-compatible keymaps.
987                          *
988                          * To address this, we:
989                          *
990                          *     - Try to get a 'number' key_sym using XLookupKeysym (with virtual shift modifier),
991                          *       in a very restrictive set of cases.
992                          *     - Fallback to XLookupString to get a key_sym from active user-defined keymap.
993                          *
994                          * Note that:
995                          *     - This effectively 'lock' main number keys to always output number events (except when using alt-gr).
996                          *     - This enforces users to use an ascii-compatible keymap with Blender - but at least it gives
997                          *       predictable and consistent results.
998                          *
999                          * Also, note that nothing in XLib sources [1] makes it obvious why those two functions give different
1000                          * key_sym results...
1001                          *
1002                          * [1] http://cgit.freedesktop.org/xorg/lib/libX11/tree/src/KeyBind.c
1003                          */
1004                         KeySym key_sym_str;
1005                         /* Mode_switch 'modifier' is AltGr - when this one or Shift are enabled, we do not want to apply
1006                          * that 'forced number' hack. */
1007                         const unsigned int mode_switch_mask = XkbKeysymToModifiers(xke->display, XK_Mode_switch);
1008                         const unsigned int number_hack_forbidden_kmods_mask = mode_switch_mask | ShiftMask;
1009                         if ((xke->keycode >= 10 && xke->keycode < 20) && ((xke->state & number_hack_forbidden_kmods_mask) == 0)) {
1010                                 key_sym = XLookupKeysym(xke, ShiftMask);
1011                                 if (!((key_sym >= XK_0) && (key_sym <= XK_9))) {
1012                                         key_sym = XLookupKeysym(xke, 0);
1013                                 }
1014                         }
1015                         else {
1016                                 key_sym = XLookupKeysym(xke, 0);
1017                         }
1018
1019                         if (!XLookupString(xke, &ascii, 1, &key_sym_str, NULL)) {
1020                                 ascii = '\0';
1021                         }
1022
1023                         /* Only allow a limited set of keys from XLookupKeysym, all others we take from XLookupString,
1024                          * unless it gives unknown key... */
1025                         gkey = ghost_key_from_keysym_or_keycode(key_sym, m_xkb_descr, xke->keycode);
1026                         switch (gkey) {
1027                                 case GHOST_kKeyRightAlt:
1028                                 case GHOST_kKeyLeftAlt:
1029                                 case GHOST_kKeyRightShift:
1030                                 case GHOST_kKeyLeftShift:
1031                                 case GHOST_kKeyRightControl:
1032                                 case GHOST_kKeyLeftControl:
1033                                 case GHOST_kKeyOS:
1034                                 case GHOST_kKey0:
1035                                 case GHOST_kKey1:
1036                                 case GHOST_kKey2:
1037                                 case GHOST_kKey3:
1038                                 case GHOST_kKey4:
1039                                 case GHOST_kKey5:
1040                                 case GHOST_kKey6:
1041                                 case GHOST_kKey7:
1042                                 case GHOST_kKey8:
1043                                 case GHOST_kKey9:
1044                                 case GHOST_kKeyNumpad0:
1045                                 case GHOST_kKeyNumpad1:
1046                                 case GHOST_kKeyNumpad2:
1047                                 case GHOST_kKeyNumpad3:
1048                                 case GHOST_kKeyNumpad4:
1049                                 case GHOST_kKeyNumpad5:
1050                                 case GHOST_kKeyNumpad6:
1051                                 case GHOST_kKeyNumpad7:
1052                                 case GHOST_kKeyNumpad8:
1053                                 case GHOST_kKeyNumpad9:
1054                                 case GHOST_kKeyNumpadPeriod:
1055                                 case GHOST_kKeyNumpadEnter:
1056                                 case GHOST_kKeyNumpadPlus:
1057                                 case GHOST_kKeyNumpadMinus:
1058                                 case GHOST_kKeyNumpadAsterisk:
1059                                 case GHOST_kKeyNumpadSlash:
1060                                         break;
1061                                 default:
1062                                 {
1063                                         GHOST_TKey gkey_str = ghost_key_from_keysym(key_sym_str);
1064                                         if (gkey_str != GHOST_kKeyUnknown) {
1065                                                 gkey = gkey_str;
1066                                         }
1067                                 }
1068                         }
1069 #else
1070                         /* In keyboards like latin ones,
1071                          * numbers needs a 'Shift' to be accessed but key_sym
1072                          * is unmodified (or anyone swapping the keys with xmodmap).
1073                          *
1074                          * Here we look at the 'Shifted' version of the key.
1075                          * If it is a number, then we take it instead of the normal key.
1076                          *
1077                          * The modified key is sent in the 'ascii's variable anyway.
1078                          */
1079                         if ((xke->keycode >= 10 && xke->keycode < 20) &&
1080                             ((key_sym = XLookupKeysym(xke, ShiftMask)) >= XK_0) && (key_sym <= XK_9))
1081                         {
1082                                 /* pass (keep shift'ed key_sym) */
1083                         }
1084                         else {
1085                                 /* regular case */
1086                                 key_sym = XLookupKeysym(xke, 0);
1087                         }
1088
1089                         gkey = ghost_key_from_keysym_or_keycode(key_sym, m_xkb_descr, xke->keycode);
1090
1091                         if (!XLookupString(xke, &ascii, 1, NULL, NULL)) {
1092                                 ascii = '\0';
1093                         }
1094 #endif
1095
1096 #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1097                         /* getting unicode on key-up events gives XLookupNone status */
1098                         XIC xic = window->getX11_XIC();
1099                         if (xic && xke->type == KeyPress) {
1100                                 Status status;
1101
1102                                 /* use utf8 because its not locale depentant, from xorg docs */
1103                                 if (!(len = Xutf8LookupString(xic, xke, utf8_buf, sizeof(utf8_array) - 5, &key_sym, &status))) {
1104                                         utf8_buf[0] = '\0';
1105                                 }
1106
1107                                 if (status == XBufferOverflow) {
1108                                         utf8_buf = (char *) malloc(len + 5);
1109                                         len = Xutf8LookupString(xic, xke, utf8_buf, len, &key_sym, &status);
1110                                 }
1111
1112                                 if ((status == XLookupChars || status == XLookupBoth)) {
1113                                         if ((unsigned char)utf8_buf[0] >= 32) { /* not an ascii control character */
1114                                                 /* do nothing for now, this is valid utf8 */
1115                                         }
1116                                         else {
1117                                                 utf8_buf[0] = '\0';
1118                                         }
1119                                 }
1120                                 else if (status == XLookupKeySym) {
1121                                         /* this key doesn't have a text representation, it is a command
1122                                          * key of some sort */;
1123                                 }
1124                                 else {
1125                                         printf("Bad keycode lookup. Keysym 0x%x Status: %s\n",
1126                                                (unsigned int) key_sym,
1127                                                (status == XLookupNone ? "XLookupNone" :
1128                                                 status == XLookupKeySym ? "XLookupKeySym" :
1129                                                 "Unknown status"));
1130
1131                                         printf("'%.*s' %p %p\n", len, utf8_buf, xic, m_xim);
1132                                 }
1133                         }
1134                         else {
1135                                 utf8_buf[0] = '\0';
1136                         }
1137 #endif
1138
1139                         g_event = new
1140                                   GHOST_EventKey(
1141                             getMilliSeconds(),
1142                             type,
1143                             window,
1144                             gkey,
1145                             ascii,
1146                             utf8_buf
1147                             );
1148
1149 #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1150                         /* when using IM for some languages such as Japanese,
1151                          * one event inserts multiple utf8 characters */
1152                         if (xic && xke->type == KeyPress) {
1153                                 unsigned char c;
1154                                 int i = 0;
1155                                 while (1) {
1156                                         /* search character boundary */
1157                                         if ((unsigned char)utf8_buf[i++] > 0x7f) {
1158                                                 for (; i < len; ++i) {
1159                                                         c = utf8_buf[i];
1160                                                         if (c < 0x80 || c > 0xbf) break;
1161                                                 }
1162                                         }
1163
1164                                         if (i >= len) break;
1165
1166                                         /* enqueue previous character */
1167                                         pushEvent(g_event);
1168
1169                                         g_event = new
1170                                                   GHOST_EventKey(
1171                                             getMilliSeconds(),
1172                                             type,
1173                                             window,
1174                                             gkey,
1175                                             '\0',
1176                                             &utf8_buf[i]
1177                                             );
1178                                 }
1179                         }
1180
1181                         if (utf8_buf != utf8_array)
1182                                 free(utf8_buf);
1183 #endif
1184
1185                         break;
1186                 }
1187
1188                 case ButtonPress:
1189                 case ButtonRelease:
1190                 {
1191                         XButtonEvent & xbe = xe->xbutton;
1192                         GHOST_TButtonMask gbmask = GHOST_kButtonMaskLeft;
1193                         GHOST_TEventType type = (xbe.type == ButtonPress) ?
1194                                                 GHOST_kEventButtonDown : GHOST_kEventButtonUp;
1195
1196                         /* process wheel mouse events and break, only pass on press events */
1197                         if (xbe.button == Button4) {
1198                                 if (xbe.type == ButtonPress)
1199                                         g_event = new GHOST_EventWheel(getMilliSeconds(), window, 1);
1200                                 break;
1201                         }
1202                         else if (xbe.button == Button5) {
1203                                 if (xbe.type == ButtonPress)
1204                                         g_event = new GHOST_EventWheel(getMilliSeconds(), window, -1);
1205                                 break;
1206                         }
1207
1208                         /* process rest of normal mouse buttons */
1209                         if (xbe.button == Button1)
1210                                 gbmask = GHOST_kButtonMaskLeft;
1211                         else if (xbe.button == Button2)
1212                                 gbmask = GHOST_kButtonMaskMiddle;
1213                         else if (xbe.button == Button3)
1214                                 gbmask = GHOST_kButtonMaskRight;
1215                         /* It seems events 6 and 7 are for horizontal scrolling.
1216                          * you can re-order button mapping like this... (swaps 6,7 with 8,9)
1217                          *   xmodmap -e "pointer = 1 2 3 4 5 8 9 6 7"
1218                          */
1219                         else if (xbe.button == 6)
1220                                 gbmask = GHOST_kButtonMaskButton6;
1221                         else if (xbe.button == 7)
1222                                 gbmask = GHOST_kButtonMaskButton7;
1223                         else if (xbe.button == 8)
1224                                 gbmask = GHOST_kButtonMaskButton4;
1225                         else if (xbe.button == 9)
1226                                 gbmask = GHOST_kButtonMaskButton5;
1227                         else
1228                                 break;
1229
1230                         g_event = new
1231                                   GHOST_EventButton(
1232                             getMilliSeconds(),
1233                             type,
1234                             window,
1235                             gbmask
1236                             );
1237                         break;
1238                 }
1239
1240                 /* change of size, border, layer etc. */
1241                 case ConfigureNotify:
1242                 {
1243                         /* XConfigureEvent & xce = xe->xconfigure; */
1244
1245                         g_event = new
1246                                   GHOST_Event(
1247                             getMilliSeconds(),
1248                             GHOST_kEventWindowSize,
1249                             window
1250                             );
1251                         break;
1252                 }
1253
1254                 case FocusIn:
1255                 case FocusOut:
1256                 {
1257                         XFocusChangeEvent &xfe = xe->xfocus;
1258
1259                         /* TODO: make sure this is the correct place for activate/deactivate */
1260                         // printf("X: focus %s for window %d\n", xfe.type == FocusIn ? "in" : "out", (int) xfe.window);
1261
1262                         /* May have to look at the type of event and filter some out. */
1263
1264                         GHOST_TEventType gtype = (xfe.type == FocusIn) ?
1265                                                  GHOST_kEventWindowActivate : GHOST_kEventWindowDeactivate;
1266
1267 #if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1268                         XIC xic = window->getX11_XIC();
1269                         if (xic) {
1270                                 if (xe->type == FocusIn)
1271                                         XSetICFocus(xic);
1272                                 else
1273                                         XUnsetICFocus(xic);
1274                         }
1275 #endif
1276
1277                         g_event = new
1278                                   GHOST_Event(
1279                             getMilliSeconds(),
1280                             gtype,
1281                             window
1282                             );
1283                         break;
1284
1285                 }
1286                 case ClientMessage:
1287                 {
1288                         XClientMessageEvent & xcme = xe->xclient;
1289
1290                         if (((Atom)xcme.data.l[0]) == m_atom.WM_DELETE_WINDOW) {
1291                                 g_event = new
1292                                           GHOST_Event(
1293                                     getMilliSeconds(),
1294                                     GHOST_kEventWindowClose,
1295                                     window
1296                                     );
1297                         }
1298                         else if (((Atom)xcme.data.l[0]) == m_atom.WM_TAKE_FOCUS) {
1299                                 XWindowAttributes attr;
1300                                 Window fwin;
1301                                 int revert_to;
1302
1303                                 /* as ICCCM say, we need reply this event
1304                                  * with a SetInputFocus, the data[1] have
1305                                  * the valid timestamp (send by the wm).
1306                                  *
1307                                  * Some WM send this event before the
1308                                  * window is really mapped (for example
1309                                  * change from virtual desktop), so we need
1310                                  * to be sure that our windows is mapped
1311                                  * or this call fail and close blender.
1312                                  */
1313                                 if (XGetWindowAttributes(m_display, xcme.window, &attr) == True) {
1314                                         if (XGetInputFocus(m_display, &fwin, &revert_to) == True) {
1315                                                 if (attr.map_state == IsViewable) {
1316                                                         if (fwin != xcme.window)
1317                                                                 XSetInputFocus(m_display, xcme.window, RevertToParent, xcme.data.l[1]);
1318                                                 }
1319                                         }
1320                                 }
1321                         }
1322                         else {
1323 #ifdef WITH_XDND
1324                                 /* try to handle drag event (if there's no such events, GHOST_HandleClientMessage will return zero) */
1325                                 if (window->getDropTarget()->GHOST_HandleClientMessage(xe) == false) {
1326                                         /* Unknown client message, ignore */
1327                                 }
1328 #else
1329                                 /* Unknown client message, ignore */
1330 #endif
1331                         }
1332
1333                         break;
1334                 }
1335
1336                 case DestroyNotify:
1337                         ::exit(-1);
1338                 /* We're not interested in the following things.(yet...) */
1339                 case NoExpose:
1340                 case GraphicsExpose:
1341                         break;
1342
1343                 case EnterNotify:
1344                 case LeaveNotify:
1345                 {
1346                         /* XCrossingEvents pointer leave enter window.
1347                          * also do cursor move here, MotionNotify only
1348                          * happens when motion starts & ends inside window.
1349                          * we only do moves when the crossing mode is 'normal'
1350                          * (really crossing between windows) since some windowmanagers
1351                          * also send grab/ungrab crossings for mousewheel events.
1352                          */
1353                         XCrossingEvent &xce = xe->xcrossing;
1354                         if (xce.mode == NotifyNormal) {
1355                                 g_event = new
1356                                           GHOST_EventCursor(
1357                                     getMilliSeconds(),
1358                                     GHOST_kEventCursorMove,
1359                                     window,
1360                                     xce.x_root,
1361                                     xce.y_root
1362                                     );
1363                         }
1364
1365                         // printf("X: %s window %d\n", xce.type == EnterNotify ? "entering" : "leaving", (int) xce.window);
1366
1367                         if (xce.type == EnterNotify)
1368                                 m_windowManager->setActiveWindow(window);
1369                         else
1370                                 m_windowManager->setWindowInactive(window);
1371
1372                         break;
1373                 }
1374                 case MapNotify:
1375                         /*
1376                          * From ICCCM:
1377                          * [ Clients can select for StructureNotify on their
1378                          *   top-level windows to track transition between
1379                          *   Normal and Iconic states. Receipt of a MapNotify
1380                          *   event will indicate a transition to the Normal
1381                          *   state, and receipt of an UnmapNotify event will
1382                          *   indicate a transition to the Iconic state. ]
1383                          */
1384                         if (window->m_post_init == True) {
1385                                 /*
1386                                  * Now we are sure that the window is
1387                                  * mapped, so only need change the state.
1388                                  */
1389                                 window->setState(window->m_post_state);
1390                                 window->m_post_init = False;
1391                         }
1392                         break;
1393                 case UnmapNotify:
1394                         break;
1395                 case MappingNotify:
1396                 case ReparentNotify:
1397                         break;
1398                 case SelectionRequest:
1399                 {
1400                         XEvent nxe;
1401                         Atom target, utf8_string, string, compound_text, c_string;
1402                         XSelectionRequestEvent *xse = &xe->xselectionrequest;
1403
1404                         target = XInternAtom(m_display, "TARGETS", False);
1405                         utf8_string = XInternAtom(m_display, "UTF8_STRING", False);
1406                         string = XInternAtom(m_display, "STRING", False);
1407                         compound_text = XInternAtom(m_display, "COMPOUND_TEXT", False);
1408                         c_string = XInternAtom(m_display, "C_STRING", False);
1409
1410                         /* support obsolete clients */
1411                         if (xse->property == None) {
1412                                 xse->property = xse->target;
1413                         }
1414
1415                         nxe.xselection.type = SelectionNotify;
1416                         nxe.xselection.requestor = xse->requestor;
1417                         nxe.xselection.property = xse->property;
1418                         nxe.xselection.display = xse->display;
1419                         nxe.xselection.selection = xse->selection;
1420                         nxe.xselection.target = xse->target;
1421                         nxe.xselection.time = xse->time;
1422
1423                         /* Check to see if the requestor is asking for String */
1424                         if (xse->target == utf8_string ||
1425                             xse->target == string ||
1426                             xse->target == compound_text ||
1427                             xse->target == c_string)
1428                         {
1429                                 if (xse->selection == XInternAtom(m_display, "PRIMARY", False)) {
1430                                         XChangeProperty(m_display, xse->requestor, xse->property, xse->target, 8, PropModeReplace,
1431                                                         (unsigned char *)txt_select_buffer, strlen(txt_select_buffer));
1432                                 }
1433                                 else if (xse->selection == XInternAtom(m_display, "CLIPBOARD", False)) {
1434                                         XChangeProperty(m_display, xse->requestor, xse->property, xse->target, 8, PropModeReplace,
1435                                                         (unsigned char *)txt_cut_buffer, strlen(txt_cut_buffer));
1436                                 }
1437                         }
1438                         else if (xse->target == target) {
1439                                 Atom alist[5];
1440                                 alist[0] = target;
1441                                 alist[1] = utf8_string;
1442                                 alist[2] = string;
1443                                 alist[3] = compound_text;
1444                                 alist[4] = c_string;
1445                                 XChangeProperty(m_display, xse->requestor, xse->property, xse->target, 32, PropModeReplace,
1446                                                 (unsigned char *)alist, 5);
1447                                 XFlush(m_display);
1448                         }
1449                         else {
1450                                 /* Change property to None because we do not support anything but STRING */
1451                                 nxe.xselection.property = None;
1452                         }
1453
1454                         /* Send the event to the client 0 0 == False, SelectionNotify */
1455                         XSendEvent(m_display, xse->requestor, 0, 0, &nxe);
1456                         XFlush(m_display);
1457                         break;
1458                 }
1459
1460                 default:
1461                 {
1462 #ifdef WITH_X11_XINPUT
1463                         for (GHOST_TabletX11& xtablet: m_xtablets) {
1464                                 if (xe->type == xtablet.MotionEvent || xe->type == xtablet.PressEvent) {
1465                                         XDeviceMotionEvent *data = (XDeviceMotionEvent *)xe;
1466                                         if (data->deviceid != xtablet.ID) {
1467                                                 continue;
1468                                         }
1469
1470                                         const unsigned char axis_first = data->first_axis;
1471                                         const unsigned char axes_end = axis_first + data->axes_count;  /* after the last */
1472                                         int axis_value;
1473
1474                                         /* stroke might begin without leading ProxyIn event,
1475                                          * this happens when window is opened when stylus is already hovering
1476                                          * around tablet surface */
1477                                         window->GetTabletData()->Active = xtablet.mode;
1478
1479                                         /* Note: This event might be generated with incomplete dataset (don't exactly know why, looks like in
1480                                          *       some cases, if the value does not change, it is not included in subsequent XDeviceMotionEvent
1481                                          *       events). So we have to check which values this event actually contains!
1482                                          */
1483
1484 #define AXIS_VALUE_GET(axis, val) \
1485         ((axis_first <= axis && axes_end > axis) && ((void)(val = data->axis_data[axis - axis_first]), true))
1486
1487                                         if (AXIS_VALUE_GET(2, axis_value)) {
1488                                                 window->GetTabletData()->Pressure = axis_value / ((float)xtablet.PressureLevels);
1489                                         }
1490
1491                                         /* the (short) cast and the & 0xffff is bizarre and unexplained anywhere,
1492                                          * but I got garbage data without it. Found it in the xidump.c source --matt
1493                                          *
1494                                          * The '& 0xffff' just truncates the value to its two lowest bytes, this probably means
1495                                          * some drivers do not properly set the whole int value? Since we convert to float afterward,
1496                                          * I don't think we need to cast to short here, but do not have a device to check this. --mont29
1497                                          */
1498                                         if (AXIS_VALUE_GET(3, axis_value)) {
1499                                                 window->GetTabletData()->Xtilt = (short)(axis_value & 0xffff) /
1500                                                                                                                  ((float)xtablet.XtiltLevels);
1501                                         }
1502                                         if (AXIS_VALUE_GET(4, axis_value)) {
1503                                                 window->GetTabletData()->Ytilt = (short)(axis_value & 0xffff) /
1504                                                                                                                  ((float)xtablet.YtiltLevels);
1505                                         }
1506
1507 #undef AXIS_VALUE_GET
1508
1509                                 }
1510                                 else if (xe->type == xtablet.ProxInEvent) {
1511                                         XProximityNotifyEvent *data = (XProximityNotifyEvent *)xe;
1512                                         if (data->deviceid != xtablet.ID) {
1513                                                 continue;
1514                                         }
1515
1516                                         window->GetTabletData()->Active = xtablet.mode;
1517                                 }
1518                                 else if (xe->type == xtablet.ProxOutEvent) {
1519                                         window->GetTabletData()->Active = GHOST_kTabletModeNone;
1520                                 }
1521                         }
1522 #endif // WITH_X11_XINPUT
1523                         break;
1524                 }
1525         }
1526
1527         if (g_event) {
1528                 pushEvent(g_event);
1529         }
1530 }
1531
1532 GHOST_TSuccess
1533 GHOST_SystemX11::
1534 getModifierKeys(
1535                 GHOST_ModifierKeys& keys) const
1536 {
1537
1538         /* analyse the masks retuned from XQueryPointer. */
1539
1540         memset((void *)m_keyboard_vector, 0, sizeof(m_keyboard_vector));
1541
1542         XQueryKeymap(m_display, (char *)m_keyboard_vector);
1543
1544         /* now translate key symbols into keycodes and
1545          * test with vector. */
1546
1547         const static KeyCode shift_l = XKeysymToKeycode(m_display, XK_Shift_L);
1548         const static KeyCode shift_r = XKeysymToKeycode(m_display, XK_Shift_R);
1549         const static KeyCode control_l = XKeysymToKeycode(m_display, XK_Control_L);
1550         const static KeyCode control_r = XKeysymToKeycode(m_display, XK_Control_R);
1551         const static KeyCode alt_l = XKeysymToKeycode(m_display, XK_Alt_L);
1552         const static KeyCode alt_r = XKeysymToKeycode(m_display, XK_Alt_R);
1553         const static KeyCode super_l = XKeysymToKeycode(m_display, XK_Super_L);
1554         const static KeyCode super_r = XKeysymToKeycode(m_display, XK_Super_R);
1555
1556         /* shift */
1557         keys.set(GHOST_kModifierKeyLeftShift, ((m_keyboard_vector[shift_l >> 3] >> (shift_l & 7)) & 1) != 0);
1558         keys.set(GHOST_kModifierKeyRightShift, ((m_keyboard_vector[shift_r >> 3] >> (shift_r & 7)) & 1) != 0);
1559         /* control */
1560         keys.set(GHOST_kModifierKeyLeftControl, ((m_keyboard_vector[control_l >> 3] >> (control_l & 7)) & 1) != 0);
1561         keys.set(GHOST_kModifierKeyRightControl, ((m_keyboard_vector[control_r >> 3] >> (control_r & 7)) & 1) != 0);
1562         /* alt */
1563         keys.set(GHOST_kModifierKeyLeftAlt, ((m_keyboard_vector[alt_l >> 3] >> (alt_l & 7)) & 1) != 0);
1564         keys.set(GHOST_kModifierKeyRightAlt, ((m_keyboard_vector[alt_r >> 3] >> (alt_r & 7)) & 1) != 0);
1565         /* super (windows) - only one GHOST-kModifierKeyOS, so mapping to either */
1566         keys.set(GHOST_kModifierKeyOS, ( ((m_keyboard_vector[super_l >> 3] >> (super_l & 7)) & 1) ||
1567                                          ((m_keyboard_vector[super_r >> 3] >> (super_r & 7)) & 1) ) != 0);
1568
1569         return GHOST_kSuccess;
1570 }
1571
1572 GHOST_TSuccess
1573 GHOST_SystemX11::
1574 getButtons(
1575                 GHOST_Buttons& buttons) const
1576 {
1577         Window root_return, child_return;
1578         int rx, ry, wx, wy;
1579         unsigned int mask_return;
1580
1581         if (XQueryPointer(m_display,
1582                           RootWindow(m_display, DefaultScreen(m_display)),
1583                           &root_return,
1584                           &child_return,
1585                           &rx, &ry,
1586                           &wx, &wy,
1587                           &mask_return) == True)
1588         {
1589                 buttons.set(GHOST_kButtonMaskLeft,   (mask_return & Button1Mask) != 0);
1590                 buttons.set(GHOST_kButtonMaskMiddle, (mask_return & Button2Mask) != 0);
1591                 buttons.set(GHOST_kButtonMaskRight,  (mask_return & Button3Mask) != 0);
1592         }
1593         else {
1594                 return GHOST_kFailure;
1595         }
1596
1597         return GHOST_kSuccess;
1598 }
1599
1600 static GHOST_TSuccess getCursorPosition_impl(
1601         Display *display,
1602         GHOST_TInt32& x,
1603         GHOST_TInt32& y,
1604         Window *child_return)
1605 {
1606         int rx, ry, wx, wy;
1607         unsigned int mask_return;
1608         Window root_return;
1609
1610         if (XQueryPointer(
1611                 display,
1612                 RootWindow(display, DefaultScreen(display)),
1613                 &root_return,
1614                 child_return,
1615                 &rx, &ry,
1616                 &wx, &wy,
1617                 &mask_return
1618                 ) == False) {
1619                 return GHOST_kFailure;
1620         }
1621         else {
1622                 x = rx;
1623                 y = ry;
1624         }
1625         return GHOST_kSuccess;
1626 }
1627
1628 GHOST_TSuccess
1629 GHOST_SystemX11::
1630 getCursorPosition(
1631                 GHOST_TInt32& x,
1632                 GHOST_TInt32& y) const
1633 {
1634         Window child_return;
1635         return getCursorPosition_impl(m_display, x, y, &child_return);
1636 }
1637
1638
1639 GHOST_TSuccess
1640 GHOST_SystemX11::
1641 setCursorPosition(
1642                 GHOST_TInt32 x,
1643                 GHOST_TInt32 y)
1644 {
1645
1646         /* This is a brute force move in screen coordinates
1647          * XWarpPointer does relative moves so first determine the
1648          * current pointer position. */
1649
1650         int cx, cy;
1651
1652 #ifdef WITH_XWAYLAND_HACK
1653         Window child_return = None;
1654         if (getCursorPosition_impl(m_display, cx, cy, &child_return) == GHOST_kFailure) {
1655                 return GHOST_kFailure;
1656         }
1657 #else
1658         if (getCursorPosition(cx, cy) == GHOST_kFailure) {
1659                 return GHOST_kFailure;
1660         }
1661 #endif
1662
1663         int relx = x - cx;
1664         int rely = y - cy;
1665
1666 #ifdef WITH_XWAYLAND_HACK
1667         if (use_xwayland_hack) {
1668                 if (child_return != None) {
1669                         XFixesHideCursor(m_display, child_return);
1670                 }
1671         }
1672 #endif
1673
1674 #ifdef WITH_X11_XINPUT
1675         if ((m_xinput_version.present) &&
1676             (m_xinput_version.major_version >= 2))
1677         {
1678                 /* Needed to account for XInput "Coordinate Transformation Matrix", see T48901 */
1679                 int device_id;
1680                 if (XIGetClientPointer(m_display, None, &device_id) != False) {
1681                         XIWarpPointer(m_display, device_id, None, None, 0, 0, 0, 0, relx, rely);
1682                 }
1683         }
1684         else
1685 #endif
1686         {
1687                 XWarpPointer(m_display, None, None, 0, 0, 0, 0, relx, rely);
1688         }
1689
1690 #ifdef WITH_XWAYLAND_HACK
1691         if (use_xwayland_hack) {
1692                 if (child_return != None) {
1693                         XFixesShowCursor(m_display, child_return);
1694                 }
1695         }
1696 #endif
1697
1698         XSync(m_display, 0); /* Sync to process all requests */
1699
1700         return GHOST_kSuccess;
1701 }
1702
1703
1704 void
1705 GHOST_SystemX11::
1706 addDirtyWindow(
1707                 GHOST_WindowX11 *bad_wind)
1708 {
1709         GHOST_ASSERT((bad_wind != NULL), "addDirtyWindow() NULL ptr trapped (window)");
1710
1711         m_dirty_windows.push_back(bad_wind);
1712 }
1713
1714
1715 bool
1716 GHOST_SystemX11::
1717 generateWindowExposeEvents()
1718 {
1719         vector<GHOST_WindowX11 *>::iterator w_start = m_dirty_windows.begin();
1720         vector<GHOST_WindowX11 *>::const_iterator w_end = m_dirty_windows.end();
1721         bool anyProcessed = false;
1722
1723         for (; w_start != w_end; ++w_start) {
1724                 GHOST_Event *g_event = new
1725                                        GHOST_Event(
1726                     getMilliSeconds(),
1727                     GHOST_kEventWindowUpdate,
1728                     *w_start
1729                     );
1730
1731                 (*w_start)->validate();
1732
1733                 if (g_event) {
1734                         pushEvent(g_event);
1735                         anyProcessed = true;
1736                 }
1737         }
1738
1739         m_dirty_windows.clear();
1740         return anyProcessed;
1741 }
1742
1743 static GHOST_TKey
1744 ghost_key_from_keysym_or_keycode(const KeySym keysym, XkbDescPtr xkb_descr, const KeyCode keycode)
1745 {
1746         GHOST_TKey type = ghost_key_from_keysym(keysym);
1747         if (type == GHOST_kKeyUnknown) {
1748                 if (xkb_descr) {
1749                         type = ghost_key_from_keycode(xkb_descr, keycode);
1750                 }
1751         }
1752         return type;
1753 }
1754
1755 #define GXMAP(k, x, y) case x: k = y; break
1756
1757 static GHOST_TKey
1758 ghost_key_from_keysym(const KeySym key)
1759 {
1760         GHOST_TKey type;
1761
1762         if ((key >= XK_A) && (key <= XK_Z)) {
1763                 type = GHOST_TKey(key - XK_A + int(GHOST_kKeyA));
1764         }
1765         else if ((key >= XK_a) && (key <= XK_z)) {
1766                 type = GHOST_TKey(key - XK_a + int(GHOST_kKeyA));
1767         }
1768         else if ((key >= XK_0) && (key <= XK_9)) {
1769                 type = GHOST_TKey(key - XK_0 + int(GHOST_kKey0));
1770         }
1771         else if ((key >= XK_F1) && (key <= XK_F24)) {
1772                 type = GHOST_TKey(key - XK_F1 + int(GHOST_kKeyF1));
1773         }
1774         else {
1775                 switch (key) {
1776                         GXMAP(type, XK_BackSpace,    GHOST_kKeyBackSpace);
1777                         GXMAP(type, XK_Tab,          GHOST_kKeyTab);
1778                         GXMAP(type, XK_ISO_Left_Tab, GHOST_kKeyTab);
1779                         GXMAP(type, XK_Return,       GHOST_kKeyEnter);
1780                         GXMAP(type, XK_Escape,       GHOST_kKeyEsc);
1781                         GXMAP(type, XK_space,        GHOST_kKeySpace);
1782
1783                         GXMAP(type, XK_Linefeed,     GHOST_kKeyLinefeed);
1784                         GXMAP(type, XK_semicolon,    GHOST_kKeySemicolon);
1785                         GXMAP(type, XK_period,       GHOST_kKeyPeriod);
1786                         GXMAP(type, XK_comma,        GHOST_kKeyComma);
1787                         GXMAP(type, XK_quoteright,   GHOST_kKeyQuote);
1788                         GXMAP(type, XK_quoteleft,    GHOST_kKeyAccentGrave);
1789                         GXMAP(type, XK_minus,        GHOST_kKeyMinus);
1790                         GXMAP(type, XK_plus,         GHOST_kKeyPlus);
1791                         GXMAP(type, XK_slash,        GHOST_kKeySlash);
1792                         GXMAP(type, XK_backslash,    GHOST_kKeyBackslash);
1793                         GXMAP(type, XK_equal,        GHOST_kKeyEqual);
1794                         GXMAP(type, XK_bracketleft,  GHOST_kKeyLeftBracket);
1795                         GXMAP(type, XK_bracketright, GHOST_kKeyRightBracket);
1796                         GXMAP(type, XK_Pause,        GHOST_kKeyPause);
1797
1798                         GXMAP(type, XK_Shift_L,      GHOST_kKeyLeftShift);
1799                         GXMAP(type, XK_Shift_R,      GHOST_kKeyRightShift);
1800                         GXMAP(type, XK_Control_L,    GHOST_kKeyLeftControl);
1801                         GXMAP(type, XK_Control_R,    GHOST_kKeyRightControl);
1802                         GXMAP(type, XK_Alt_L,        GHOST_kKeyLeftAlt);
1803                         GXMAP(type, XK_Alt_R,        GHOST_kKeyRightAlt);
1804                         GXMAP(type, XK_Super_L,      GHOST_kKeyOS);
1805                         GXMAP(type, XK_Super_R,      GHOST_kKeyOS);
1806
1807                         GXMAP(type, XK_Insert,       GHOST_kKeyInsert);
1808                         GXMAP(type, XK_Delete,       GHOST_kKeyDelete);
1809                         GXMAP(type, XK_Home,         GHOST_kKeyHome);
1810                         GXMAP(type, XK_End,          GHOST_kKeyEnd);
1811                         GXMAP(type, XK_Page_Up,      GHOST_kKeyUpPage);
1812                         GXMAP(type, XK_Page_Down,    GHOST_kKeyDownPage);
1813
1814                         GXMAP(type, XK_Left,         GHOST_kKeyLeftArrow);
1815                         GXMAP(type, XK_Right,        GHOST_kKeyRightArrow);
1816                         GXMAP(type, XK_Up,           GHOST_kKeyUpArrow);
1817                         GXMAP(type, XK_Down,         GHOST_kKeyDownArrow);
1818
1819                         GXMAP(type, XK_Caps_Lock,    GHOST_kKeyCapsLock);
1820                         GXMAP(type, XK_Scroll_Lock,  GHOST_kKeyScrollLock);
1821                         GXMAP(type, XK_Num_Lock,     GHOST_kKeyNumLock);
1822
1823                         /* keypad events */
1824
1825                         GXMAP(type, XK_KP_0,         GHOST_kKeyNumpad0);
1826                         GXMAP(type, XK_KP_1,         GHOST_kKeyNumpad1);
1827                         GXMAP(type, XK_KP_2,         GHOST_kKeyNumpad2);
1828                         GXMAP(type, XK_KP_3,         GHOST_kKeyNumpad3);
1829                         GXMAP(type, XK_KP_4,         GHOST_kKeyNumpad4);
1830                         GXMAP(type, XK_KP_5,         GHOST_kKeyNumpad5);
1831                         GXMAP(type, XK_KP_6,         GHOST_kKeyNumpad6);
1832                         GXMAP(type, XK_KP_7,         GHOST_kKeyNumpad7);
1833                         GXMAP(type, XK_KP_8,         GHOST_kKeyNumpad8);
1834                         GXMAP(type, XK_KP_9,         GHOST_kKeyNumpad9);
1835                         GXMAP(type, XK_KP_Decimal,   GHOST_kKeyNumpadPeriod);
1836
1837                         GXMAP(type, XK_KP_Insert,    GHOST_kKeyNumpad0);
1838                         GXMAP(type, XK_KP_End,       GHOST_kKeyNumpad1);
1839                         GXMAP(type, XK_KP_Down,      GHOST_kKeyNumpad2);
1840                         GXMAP(type, XK_KP_Page_Down, GHOST_kKeyNumpad3);
1841                         GXMAP(type, XK_KP_Left,      GHOST_kKeyNumpad4);
1842                         GXMAP(type, XK_KP_Begin,     GHOST_kKeyNumpad5);
1843                         GXMAP(type, XK_KP_Right,     GHOST_kKeyNumpad6);
1844                         GXMAP(type, XK_KP_Home,      GHOST_kKeyNumpad7);
1845                         GXMAP(type, XK_KP_Up,        GHOST_kKeyNumpad8);
1846                         GXMAP(type, XK_KP_Page_Up,   GHOST_kKeyNumpad9);
1847                         GXMAP(type, XK_KP_Delete,    GHOST_kKeyNumpadPeriod);
1848
1849                         GXMAP(type, XK_KP_Enter,     GHOST_kKeyNumpadEnter);
1850                         GXMAP(type, XK_KP_Add,       GHOST_kKeyNumpadPlus);
1851                         GXMAP(type, XK_KP_Subtract,  GHOST_kKeyNumpadMinus);
1852                         GXMAP(type, XK_KP_Multiply,  GHOST_kKeyNumpadAsterisk);
1853                         GXMAP(type, XK_KP_Divide,    GHOST_kKeyNumpadSlash);
1854
1855                         /* Media keys in some keyboards and laptops with XFree86/Xorg */
1856 #ifdef WITH_XF86KEYSYM
1857                         GXMAP(type, XF86XK_AudioPlay,    GHOST_kKeyMediaPlay);
1858                         GXMAP(type, XF86XK_AudioStop,    GHOST_kKeyMediaStop);
1859                         GXMAP(type, XF86XK_AudioPrev,    GHOST_kKeyMediaFirst);
1860                         GXMAP(type, XF86XK_AudioRewind,  GHOST_kKeyMediaFirst);
1861                         GXMAP(type, XF86XK_AudioNext,    GHOST_kKeyMediaLast);
1862 #ifdef XF86XK_AudioForward /* Debian lenny's XF86keysym.h has no XF86XK_AudioForward define */
1863                         GXMAP(type, XF86XK_AudioForward, GHOST_kKeyMediaLast);
1864 #endif
1865 #endif
1866                         default:
1867 #ifdef GHOST_DEBUG
1868                                 printf("%s: unknown key: %lu / 0x%lx\n", __func__, key, key);
1869 #endif
1870                                 type = GHOST_kKeyUnknown;
1871                                 break;
1872                 }
1873         }
1874
1875         return type;
1876 }
1877
1878 #undef GXMAP
1879
1880 #define MAKE_ID(a, b, c, d) ((int)(d) << 24 | (int)(c) << 16 | (b) << 8 | (a))
1881
1882 static GHOST_TKey
1883 ghost_key_from_keycode(const XkbDescPtr xkb_descr, const KeyCode keycode)
1884 {
1885         GHOST_ASSERT(XkbKeyNameLength == 4, "Name length is invalid!");
1886         if (keycode >= xkb_descr->min_key_code && keycode <= xkb_descr->max_key_code) {
1887                 const char *id_str = xkb_descr->names->keys[keycode].name;
1888                 const uint32_t id = MAKE_ID(id_str[0], id_str[1], id_str[2], id_str[3]);
1889                 switch (id) {
1890                         case MAKE_ID('T', 'L', 'D', 'E'):
1891                                 return GHOST_kKeyAccentGrave;
1892 #ifdef GHOST_DEBUG
1893                         default:
1894                                 printf("%s unhandled keycode: %.*s\n", __func__, XkbKeyNameLength, id_str);
1895                                 break;
1896 #endif
1897                 }
1898         }
1899         else if (keycode != 0) {
1900                 GHOST_ASSERT(false, "KeyCode out of range!");
1901         }
1902         return GHOST_kKeyUnknown;
1903 }
1904
1905 #undef MAKE_ID
1906
1907 /* from xclip.c xcout() v0.11 */
1908
1909 #define XCLIB_XCOUT_NONE            0 /* no context */
1910 #define XCLIB_XCOUT_SENTCONVSEL     1 /* sent a request */
1911 #define XCLIB_XCOUT_INCR            2 /* in an incr loop */
1912 #define XCLIB_XCOUT_FALLBACK        3 /* STRING failed, need fallback to UTF8 */
1913 #define XCLIB_XCOUT_FALLBACK_UTF8   4 /* UTF8 failed, move to compouned */
1914 #define XCLIB_XCOUT_FALLBACK_COMP   5 /* compouned failed, move to text. */
1915 #define XCLIB_XCOUT_FALLBACK_TEXT   6
1916
1917 /* Retrieves the contents of a selections. */
1918 void GHOST_SystemX11::getClipboard_xcout(const XEvent *evt,
1919                 Atom sel, Atom target, unsigned char **txt,
1920                 unsigned long *len, unsigned int *context) const
1921 {
1922         Atom pty_type;
1923         int pty_format;
1924         unsigned char *buffer;
1925         unsigned long pty_size, pty_items;
1926         unsigned char *ltxt = *txt;
1927
1928         vector<GHOST_IWindow *> & win_vec = m_windowManager->getWindows();
1929         vector<GHOST_IWindow *>::iterator win_it = win_vec.begin();
1930         GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
1931         Window win = window->getXWindow();
1932
1933         switch (*context) {
1934                 /* There is no context, do an XConvertSelection() */
1935                 case XCLIB_XCOUT_NONE:
1936                         /* Initialise return length to 0 */
1937                         if (*len > 0) {
1938                                 free(*txt);
1939                                 *len = 0;
1940                         }
1941
1942                         /* Send a selection request */
1943                         XConvertSelection(m_display, sel, target, m_atom.XCLIP_OUT, win, CurrentTime);
1944                         *context = XCLIB_XCOUT_SENTCONVSEL;
1945                         return;
1946
1947                 case XCLIB_XCOUT_SENTCONVSEL:
1948                         if (evt->type != SelectionNotify)
1949                                 return;
1950
1951                         if (target == m_atom.UTF8_STRING && evt->xselection.property == None) {
1952                                 *context = XCLIB_XCOUT_FALLBACK_UTF8;
1953                                 return;
1954                         }
1955                         else if (target == m_atom.COMPOUND_TEXT && evt->xselection.property == None) {
1956                                 *context = XCLIB_XCOUT_FALLBACK_COMP;
1957                                 return;
1958                         }
1959                         else if (target == m_atom.TEXT && evt->xselection.property == None) {
1960                                 *context = XCLIB_XCOUT_FALLBACK_TEXT;
1961                                 return;
1962                         }
1963
1964                         /* find the size and format of the data in property */
1965                         XGetWindowProperty(m_display, win, m_atom.XCLIP_OUT, 0, 0, False,
1966                                            AnyPropertyType, &pty_type, &pty_format,
1967                                            &pty_items, &pty_size, &buffer);
1968                         XFree(buffer);
1969
1970                         if (pty_type == m_atom.INCR) {
1971                                 /* start INCR mechanism by deleting property */
1972                                 XDeleteProperty(m_display, win, m_atom.XCLIP_OUT);
1973                                 XFlush(m_display);
1974                                 *context = XCLIB_XCOUT_INCR;
1975                                 return;
1976                         }
1977
1978                         /* if it's not incr, and not format == 8, then there's
1979                          * nothing in the selection (that xclip understands, anyway) */
1980
1981                         if (pty_format != 8) {
1982                                 *context = XCLIB_XCOUT_NONE;
1983                                 return;
1984                         }
1985
1986                         // not using INCR mechanism, just read the property
1987                         XGetWindowProperty(m_display, win, m_atom.XCLIP_OUT, 0, (long) pty_size,
1988                                            False, AnyPropertyType, &pty_type,
1989                                            &pty_format, &pty_items, &pty_size, &buffer);
1990
1991                         /* finished with property, delete it */
1992                         XDeleteProperty(m_display, win, m_atom.XCLIP_OUT);
1993
1994                         /* copy the buffer to the pointer for returned data */
1995                         ltxt = (unsigned char *) malloc(pty_items);
1996                         memcpy(ltxt, buffer, pty_items);
1997
1998                         /* set the length of the returned data */
1999                         *len = pty_items;
2000                         *txt = ltxt;
2001
2002                         /* free the buffer */
2003                         XFree(buffer);
2004
2005                         *context = XCLIB_XCOUT_NONE;
2006
2007                         /* complete contents of selection fetched, return 1 */
2008                         return;
2009
2010                 case XCLIB_XCOUT_INCR:
2011                         /* To use the INCR method, we basically delete the
2012                          * property with the selection in it, wait for an
2013                          * event indicating that the property has been created,
2014                          * then read it, delete it, etc. */
2015
2016                         /* make sure that the event is relevant */
2017                         if (evt->type != PropertyNotify)
2018                                 return;
2019
2020                         /* skip unless the property has a new value */
2021                         if (evt->xproperty.state != PropertyNewValue)
2022                                 return;
2023
2024                         /* check size and format of the property */
2025                         XGetWindowProperty(m_display, win, m_atom.XCLIP_OUT, 0, 0, False,
2026                                            AnyPropertyType, &pty_type, &pty_format,
2027                                            &pty_items, &pty_size, &buffer);
2028
2029                         if (pty_format != 8) {
2030                                 /* property does not contain text, delete it
2031                                  * to tell the other X client that we have read
2032                                  * it and to send the next property */
2033                                 XFree(buffer);
2034                                 XDeleteProperty(m_display, win, m_atom.XCLIP_OUT);
2035                                 return;
2036                         }
2037
2038                         if (pty_size == 0) {
2039                                 /* no more data, exit from loop */
2040                                 XFree(buffer);
2041                                 XDeleteProperty(m_display, win, m_atom.XCLIP_OUT);
2042                                 *context = XCLIB_XCOUT_NONE;
2043
2044                                 /* this means that an INCR transfer is now
2045                                  * complete, return 1 */
2046                                 return;
2047                         }
2048
2049                         XFree(buffer);
2050
2051                         /* if we have come this far, the property contains
2052                          * text, we know the size. */
2053                         XGetWindowProperty(m_display, win, m_atom.XCLIP_OUT, 0, (long) pty_size,
2054                                            False, AnyPropertyType, &pty_type, &pty_format,
2055                                            &pty_items, &pty_size, &buffer);
2056
2057                         /* allocate memory to accommodate data in *txt */
2058                         if (*len == 0) {
2059                                 *len = pty_items;
2060                                 ltxt = (unsigned char *) malloc(*len);
2061                         }
2062                         else {
2063                                 *len += pty_items;
2064                                 ltxt = (unsigned char *) realloc(ltxt, *len);
2065                         }
2066
2067                         /* add data to ltxt */
2068                         memcpy(&ltxt[*len - pty_items], buffer, pty_items);
2069
2070                         *txt = ltxt;
2071                         XFree(buffer);
2072
2073                         /* delete property to get the next item */
2074                         XDeleteProperty(m_display, win, m_atom.XCLIP_OUT);
2075                         XFlush(m_display);
2076                         return;
2077         }
2078         return;
2079 }
2080
2081 GHOST_TUns8 *GHOST_SystemX11::getClipboard(bool selection) const
2082 {
2083         Atom sseln;
2084         Atom target = m_atom.UTF8_STRING;
2085         Window owner;
2086
2087         /* from xclip.c doOut() v0.11 */
2088         unsigned char *sel_buf;
2089         unsigned long sel_len = 0;
2090         XEvent evt;
2091         unsigned int context = XCLIB_XCOUT_NONE;
2092
2093         if (selection == True)
2094                 sseln = m_atom.PRIMARY;
2095         else
2096                 sseln = m_atom.CLIPBOARD;
2097
2098         vector<GHOST_IWindow *> & win_vec = m_windowManager->getWindows();
2099         vector<GHOST_IWindow *>::iterator win_it = win_vec.begin();
2100         GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
2101         Window win = window->getXWindow();
2102
2103         /* check if we are the owner. */
2104         owner = XGetSelectionOwner(m_display, sseln);
2105         if (owner == win) {
2106                 if (sseln == m_atom.CLIPBOARD) {
2107                         sel_buf = (unsigned char *)malloc(strlen(txt_cut_buffer) + 1);
2108                         strcpy((char *)sel_buf, txt_cut_buffer);
2109                         return sel_buf;
2110                 }
2111                 else {
2112                         sel_buf = (unsigned char *)malloc(strlen(txt_select_buffer) + 1);
2113                         strcpy((char *)sel_buf, txt_select_buffer);
2114                         return sel_buf;
2115                 }
2116         }
2117         else if (owner == None)
2118                 return(NULL);
2119
2120         while (1) {
2121                 /* only get an event if xcout() is doing something */
2122                 if (context != XCLIB_XCOUT_NONE)
2123                         XNextEvent(m_display, &evt);
2124
2125                 /* fetch the selection, or part of it */
2126                 getClipboard_xcout(&evt, sseln, target, &sel_buf, &sel_len, &context);
2127
2128                 /* fallback is needed. set XA_STRING to target and restart the loop. */
2129                 if (context == XCLIB_XCOUT_FALLBACK) {
2130                         context = XCLIB_XCOUT_NONE;
2131                         target = m_atom.STRING;
2132                         continue;
2133                 }
2134                 else if (context == XCLIB_XCOUT_FALLBACK_UTF8) {
2135                         /* utf8 fail, move to compouned text. */
2136                         context = XCLIB_XCOUT_NONE;
2137                         target = m_atom.COMPOUND_TEXT;
2138                         continue;
2139                 }
2140                 else if (context == XCLIB_XCOUT_FALLBACK_COMP) {
2141                         /* compouned text fail, move to text. */
2142                         context = XCLIB_XCOUT_NONE;
2143                         target = m_atom.TEXT;
2144                         continue;
2145                 }
2146                 else if (context == XCLIB_XCOUT_FALLBACK_TEXT) {
2147                         /* text fail, nothing else to try, break. */
2148                         context = XCLIB_XCOUT_NONE;
2149                 }
2150
2151                 /* only continue if xcout() is doing something */
2152                 if (context == XCLIB_XCOUT_NONE)
2153                         break;
2154         }
2155
2156         if (sel_len) {
2157                 /* only print the buffer out, and free it, if it's not
2158                  * empty
2159                  */
2160                 unsigned char *tmp_data = (unsigned char *) malloc(sel_len + 1);
2161                 memcpy((char *)tmp_data, (char *)sel_buf, sel_len);
2162                 tmp_data[sel_len] = '\0';
2163
2164                 if (sseln == m_atom.STRING)
2165                         XFree(sel_buf);
2166                 else
2167                         free(sel_buf);
2168
2169                 return tmp_data;
2170         }
2171         return(NULL);
2172 }
2173
2174 void GHOST_SystemX11::putClipboard(GHOST_TInt8 *buffer, bool selection) const
2175 {
2176         Window m_window, owner;
2177
2178         vector<GHOST_IWindow *> & win_vec = m_windowManager->getWindows();
2179         vector<GHOST_IWindow *>::iterator win_it = win_vec.begin();
2180         GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
2181         m_window = window->getXWindow();
2182
2183         if (buffer) {
2184                 if (selection == False) {
2185                         XSetSelectionOwner(m_display, m_atom.CLIPBOARD, m_window, CurrentTime);
2186                         owner = XGetSelectionOwner(m_display, m_atom.CLIPBOARD);
2187                         if (txt_cut_buffer)
2188                                 free((void *)txt_cut_buffer);
2189
2190                         txt_cut_buffer = (char *) malloc(strlen(buffer) + 1);
2191                         strcpy(txt_cut_buffer, buffer);
2192                 }
2193                 else {
2194                         XSetSelectionOwner(m_display, m_atom.PRIMARY, m_window, CurrentTime);
2195                         owner = XGetSelectionOwner(m_display, m_atom.PRIMARY);
2196                         if (txt_select_buffer)
2197                                 free((void *)txt_select_buffer);
2198
2199                         txt_select_buffer = (char *) malloc(strlen(buffer) + 1);
2200                         strcpy(txt_select_buffer, buffer);
2201                 }
2202
2203                 if (owner != m_window)
2204                         fprintf(stderr, "failed to own primary\n");
2205         }
2206 }
2207
2208 #ifdef WITH_XDND
2209 GHOST_TSuccess GHOST_SystemX11::pushDragDropEvent(GHOST_TEventType eventType,
2210                 GHOST_TDragnDropTypes draggedObjectType,
2211                 GHOST_IWindow *window,
2212                 int mouseX, int mouseY,
2213                 void *data)
2214 {
2215         GHOST_SystemX11 *system = ((GHOST_SystemX11 *)getSystem());
2216         return system->pushEvent(new GHOST_EventDragnDrop(system->getMilliSeconds(),
2217                                                           eventType,
2218                                                           draggedObjectType,
2219                                                           window, mouseX, mouseY, data)
2220                                  );
2221 }
2222 #endif
2223 /**
2224  * These callbacks can be used for debugging, so we can breakpoint on an X11 error.
2225  *
2226  * Dummy function to get around IO Handler exiting if device invalid
2227  * Basically it will not crash blender now if you have a X device that
2228  * is configured but not plugged in.
2229  */
2230 int GHOST_X11_ApplicationErrorHandler(Display *display, XErrorEvent *event)
2231 {
2232         char error_code_str[512];
2233
2234         XGetErrorText(display, event->error_code, error_code_str, sizeof(error_code_str));
2235
2236         fprintf(stderr,
2237                 "Received X11 Error:\n"
2238                 "\terror code:   %d\n"
2239                 "\trequest code: %d\n"
2240                 "\tminor code:   %d\n"
2241                 "\terror text:   %s\n",
2242                 event->error_code, event->request_code, event->minor_code, error_code_str);
2243
2244         /* No exit! - but keep lint happy */
2245         return 0;
2246 }
2247
2248 int GHOST_X11_ApplicationIOErrorHandler(Display * /*display*/)
2249 {
2250         fprintf(stderr, "Ignoring Xlib error: error IO\n");
2251
2252         /* No exit! - but keep lint happy */
2253         return 0;
2254 }
2255
2256 #ifdef WITH_X11_XINPUT
2257
2258 /* These C functions are copied from Wine 3.12's wintab.c */
2259 static bool match_token(const char *haystack, const char *needle)
2260 {
2261         const char *p, *q;
2262         for (p = haystack; *p; ) {
2263                 while (*p && isspace(*p))
2264                         p++;
2265                 if (!*p)
2266                         break;
2267
2268                 for (q = needle; *q && *p && tolower(*p) == tolower(*q); q++)
2269                         p++;
2270                 if (!*q && (isspace(*p) || !*p))
2271                         return true;
2272
2273                 while (*p && !isspace(*p))
2274                         p++;
2275         }
2276         return false;
2277 }
2278
2279 /* Determining if an X device is a Tablet style device is an imperfect science.
2280  * We rely on common conventions around device names as well as the type reported
2281  * by Wacom tablets.  This code will likely need to be expanded for alternate tablet types
2282  *
2283  * Wintab refers to any device that interacts with the tablet as a cursor,
2284  * (stylus, eraser, tablet mouse, airbrush, etc)
2285  * this is not to be confused with wacom x11 configuration "cursor" device.
2286  * Wacoms x11 config "cursor" refers to its device slot (which we mirror with
2287  * our gSysCursors) for puck like devices (tablet mice essentially).
2288  */
2289 static GHOST_TTabletMode tablet_mode_from_name(const char *name, const char *type)
2290 {
2291         int i;
2292         static const char* tablet_stylus_whitelist[] = {
2293                 "stylus",
2294                 "wizardpen",
2295                 "acecad",
2296                 "pen",
2297                 NULL
2298         };
2299
2300         static const char* type_blacklist[] = {
2301                 "pad",
2302                 "cursor",
2303                 "touch",
2304                 NULL
2305         };
2306
2307         /* Skip some known unsupported types. */
2308         for (i=0; type_blacklist[i] != NULL; i++) {
2309                 if (type && (strcasecmp(type, type_blacklist[i]) == 0)) {
2310                         return GHOST_kTabletModeNone;
2311                 }
2312         }
2313
2314         /* First check device type to avoid cases where name is "Pen and Eraser" and type is "ERASER" */
2315         for (i=0; tablet_stylus_whitelist[i] != NULL; i++) {
2316                 if (type && match_token(type, tablet_stylus_whitelist[i])) {
2317                         return GHOST_kTabletModeStylus;
2318                 }
2319         }
2320         if (type && match_token(type, "eraser")) {
2321                 return GHOST_kTabletModeEraser;
2322         }
2323         for (i=0; tablet_stylus_whitelist[i] != NULL; i++) {
2324                 if (name && match_token(name, tablet_stylus_whitelist[i])) {
2325                         return GHOST_kTabletModeStylus;
2326                 }
2327         }
2328         if (name && match_token(name, "eraser")) {
2329                 return GHOST_kTabletModeEraser;
2330         }
2331
2332         return GHOST_kTabletModeNone;
2333 }
2334
2335 /* End code copied from Wine. */
2336
2337 void GHOST_SystemX11::refreshXInputDevices()
2338 {
2339         if (m_xinput_version.present) {
2340                 /* Close tablet devices. */
2341                 clearXInputDevices();
2342
2343                 /* Install our error handler to override Xlib's termination behavior */
2344                 GHOST_X11_ERROR_HANDLERS_OVERRIDE(handler_store);
2345
2346                 {
2347                         int device_count;
2348                         XDeviceInfo *device_info = XListInputDevices(m_display, &device_count);
2349
2350
2351                         for (int i = 0; i < device_count; ++i) {
2352                                 char *device_type = device_info[i].type ? XGetAtomName(m_display, device_info[i].type) : NULL;
2353                                 GHOST_TTabletMode tablet_mode = tablet_mode_from_name(device_info[i].name, device_type);
2354
2355 //                              printf("Tablet type:'%s', name:'%s', index:%d\n", device_type, device_info[i].name, i);
2356
2357                                 if (device_type) {
2358                                         XFree((void *)device_type);
2359                                 }
2360
2361                                 if (!(tablet_mode == GHOST_kTabletModeStylus || tablet_mode == GHOST_kTabletModeEraser)) {
2362                                         continue;
2363                                 }
2364
2365                                 GHOST_TabletX11 xtablet = {tablet_mode};
2366                                 xtablet.ID = device_info[i].id;
2367                                 xtablet.Device = XOpenDevice(m_display, xtablet.ID);
2368
2369                                 if (xtablet.Device != NULL) {
2370                                         /* Find how many pressure levels tablet has */
2371                                         XAnyClassPtr ici = device_info[i].inputclassinfo;
2372
2373                                         for (int j = 0; j < xtablet.Device->num_classes; ++j) {
2374                                                 if (ici->c_class == ValuatorClass) {
2375                                                         XValuatorInfo *xvi = (XValuatorInfo *)ici;
2376                                                         xtablet.PressureLevels = xvi->axes[2].max_value;
2377
2378                                                         if (xvi->num_axes > 3) {
2379                                                                 /* this is assuming that the tablet has the same tilt resolution in both
2380                                                                  * positive and negative directions. It would be rather weird if it didn't.. */
2381                                                                 xtablet.XtiltLevels = xvi->axes[3].max_value;
2382                                                                 xtablet.YtiltLevels = xvi->axes[4].max_value;
2383                                                         }
2384                                                         else {
2385                                                                 xtablet.XtiltLevels = 0;
2386                                                                 xtablet.YtiltLevels = 0;
2387                                                         }
2388
2389                                                         break;
2390                                                 }
2391
2392                                                 ici = (XAnyClassPtr)(((char *)ici) + ici->length);
2393                                         }
2394
2395                                         m_xtablets.push_back(xtablet);
2396                                 }
2397
2398                         }
2399
2400                         XFreeDeviceList(device_info);
2401                 }
2402
2403                 GHOST_X11_ERROR_HANDLERS_RESTORE(handler_store);
2404         }
2405 }
2406
2407 void GHOST_SystemX11::clearXInputDevices()
2408 {
2409         for (GHOST_TabletX11& xtablet: m_xtablets) {
2410                 if (xtablet.Device)
2411                         XCloseDevice(m_display, xtablet.Device);
2412         }
2413
2414         m_xtablets.clear();
2415 }
2416
2417 #endif /* WITH_X11_XINPUT */