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