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