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