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