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