Blender V5.3
GHOST_SystemX11.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2001-2002 NaN Holding BV. All rights reserved.
2 * SPDX-FileCopyrightText: 2009 Nokia Corporation and/or its subsidiary(-ies).
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later
5 *
6 * Part of this code from Nokia has been taken from Qt, under LGPL license. */
7
11
12#include <X11/XKBlib.h> /* Allow detectable auto-repeat. */
13#include <X11/Xatom.h>
14#include <X11/Xutil.h>
15#include <X11/keysym.h>
16
17#include "GHOST_EventButton.hh"
18#include "GHOST_EventCursor.hh"
20#include "GHOST_EventKey.hh"
21#include "GHOST_EventWheel.hh"
22#include "GHOST_SystemX11.hh"
23#include "GHOST_TimerManager.hh"
25#include "GHOST_WindowX11.hh"
26#ifdef WITH_INPUT_NDOF
28#endif
29#include "GHOST_utildefines.hh"
30
31#ifdef WITH_XDND
32# include "GHOST_DropTargetX11.hh"
33#endif
34
35#include "GHOST_Debug.hh"
36
37#ifdef WITH_OPENGL_BACKEND
38# include "GHOST_ContextEGL.hh"
39# include "GHOST_ContextGLX.hh"
40#endif
41
42#ifdef WITH_VULKAN_BACKEND
43# include "GHOST_ContextVK.hh"
44#endif
45
46#ifdef WITH_XF86KEYSYM
47# include <X11/XF86keysym.h>
48#endif
49
50#ifdef WITH_X11_XFIXES
51# include <X11/extensions/Xfixes.h>
52/* Workaround for XWayland grab glitch: #53004. */
53# define WITH_XWAYLAND_HACK
54#endif
55
56/* for XIWarpPointer */
57#ifdef WITH_X11_XINPUT
58# include <X11/extensions/XInput2.h>
59#endif
60
61/* For timing */
62#include <sys/time.h>
63#include <unistd.h>
64
65#include <cstdio> /* for fprintf only */
66#include <cstdlib> /* for exit */
67#include <iostream>
68#include <vector>
69
70/* For debugging, so we can break-point X11 errors. */
71// #define USE_X11_ERROR_HANDLERS
72
73#ifdef WITH_X11_XINPUT
74# define USE_XINPUT_HOTPLUG
75#endif
76
77/* see #34039 Fix Alt key glitch on Unity desktop */
78#define USE_UNITY_WORKAROUND
79
80/* Fix 'shortcut' part of keyboard reading code only ever using first defined key-map
81 * instead of active one. See #47228 and D1746 */
82#define USE_NON_LATIN_KB_WORKAROUND
83
84static uchar bit_is_on(const uchar *ptr, int bit)
85{
86 return ptr[bit >> 3] & (1 << (bit & 7));
87}
88
89static GHOST_TKey ghost_key_from_keysym(const KeySym key);
90static GHOST_TKey ghost_key_from_keycode(const XkbDescPtr xkb_descr, const KeyCode keycode);
91static GHOST_TKey ghost_key_from_keysym_or_keycode(const KeySym key_sym,
92 const XkbDescPtr xkb_descr,
93 const KeyCode keycode);
94
95/* these are for copy and select copy */
96static char *txt_cut_buffer = nullptr;
97static char *txt_select_buffer = nullptr;
98
99#ifdef WITH_XWAYLAND_HACK
100static bool use_xwayland_hack = false;
101#endif
102
103using namespace std;
104
106 : GHOST_System(),
107 xkb_descr_(nullptr),
108 keyboard_vector_{0},
109#ifdef WITH_X11_XINPUT
110 last_key_time_(0),
111#endif
112 keycode_last_repeat_key_(uint(-1))
113{
114 XInitThreads();
115 display_ = XOpenDisplay(nullptr);
116
117 if (!display_) {
118 throw std::runtime_error("unable to open a display!");
119 }
120
121#ifdef USE_X11_ERROR_HANDLERS
122 (void)XSetErrorHandler(GHOST_X11_ApplicationErrorHandler);
123 (void)XSetIOErrorHandler(GHOST_X11_ApplicationIOErrorHandler);
124#endif
125
126#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
127 /* NOTE: Don't open connection to XIM server here, because the locale has to be
128 * set before opening the connection but `setlocale()` has not been called yet.
129 * the connection will be opened after entering the event loop. */
130 xim_ = nullptr;
131#endif
132
133#define GHOST_INTERN_ATOM_IF_EXISTS(atom) \
134 { \
135 atom_.atom = XInternAtom(display_, #atom, True); \
136 } \
137 (void)0
138#define GHOST_INTERN_ATOM(atom) \
139 { \
140 atom_.atom = XInternAtom(display_, #atom, False); \
141 } \
142 (void)0
143
144 GHOST_INTERN_ATOM_IF_EXISTS(WM_DELETE_WINDOW);
145 GHOST_INTERN_ATOM(WM_PROTOCOLS);
146 GHOST_INTERN_ATOM(WM_TAKE_FOCUS);
147 GHOST_INTERN_ATOM(WM_STATE);
148 GHOST_INTERN_ATOM(WM_CHANGE_STATE);
149 GHOST_INTERN_ATOM(_NET_WM_STATE);
150 GHOST_INTERN_ATOM(_NET_WM_STATE_MAXIMIZED_HORZ);
151 GHOST_INTERN_ATOM(_NET_WM_STATE_MAXIMIZED_VERT);
152
153 GHOST_INTERN_ATOM(_NET_WM_STATE_FULLSCREEN);
154 GHOST_INTERN_ATOM(_MOTIF_WM_HINTS);
155 GHOST_INTERN_ATOM(TARGETS);
156 GHOST_INTERN_ATOM(STRING);
157 GHOST_INTERN_ATOM(C_STRING);
158 GHOST_INTERN_ATOM(COMPOUND_TEXT);
159 GHOST_INTERN_ATOM(TEXT);
160 GHOST_INTERN_ATOM(CLIPBOARD);
161 GHOST_INTERN_ATOM(PRIMARY);
162 GHOST_INTERN_ATOM(XCLIP_OUT);
163 GHOST_INTERN_ATOM(INCR);
164 GHOST_INTERN_ATOM(UTF8_STRING);
165#ifdef WITH_X11_XINPUT
166 atom_.TABLET = XInternAtom(display_, XI_TABLET, False);
167#endif
168
169#undef GHOST_INTERN_ATOM_IF_EXISTS
170#undef GHOST_INTERN_ATOM
171
172 last_warp_x_ = 0;
173 last_warp_y_ = 0;
174 last_release_keycode_ = 0;
175 last_release_time_ = 0;
176
177 /* Use detectable auto-repeat, mac and windows also do this. */
178 int use_xkb;
179 int xkb_opcode, xkb_event, xkb_error;
180 int xkb_major = XkbMajorVersion, xkb_minor = XkbMinorVersion;
181
182 use_xkb = XkbQueryExtension(
183 display_, &xkb_opcode, &xkb_event, &xkb_error, &xkb_major, &xkb_minor);
184 if (use_xkb) {
185 XkbSetDetectableAutoRepeat(display_, true, nullptr);
186
187 xkb_descr_ = XkbGetMap(display_, 0, XkbUseCoreKbd);
188 if (xkb_descr_) {
189 XkbGetNames(display_, XkbKeyNamesMask, xkb_descr_);
190 XkbGetControls(display_, XkbPerKeyRepeatMask | XkbRepeatKeysMask, xkb_descr_);
191 }
192 }
193
194#ifdef WITH_XWAYLAND_HACK
195 use_xwayland_hack = getenv("WAYLAND_DISPLAY") != nullptr;
196#endif
197
198#ifdef WITH_X11_XINPUT
199 /* Detect if we have XINPUT (for reuse). */
200 {
201 memset(&xinput_version_, 0, sizeof(xinput_version_));
202 XExtensionVersion *version = XGetExtensionVersion(display_, INAME);
203 if (version && (version != (XExtensionVersion *)NoSuchExtension)) {
204 if (version->present) {
205 xinput_version_ = *version;
206 }
207 XFree(version);
208 }
209 }
210
211# ifdef USE_XINPUT_HOTPLUG
212 if (xinput_version_.present) {
213 XEventClass class_presence;
214 int xi_presence;
215 DevicePresence(display_, xi_presence, class_presence);
216 XSelectExtensionEvent(
217 display_, RootWindow(display_, DefaultScreen(display_)), &class_presence, 1);
218 (void)xi_presence;
219 }
220# endif /* USE_XINPUT_HOTPLUG */
221
222 refreshXInputDevices();
223#endif /* WITH_X11_XINPUT */
224}
225
227{
228#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
229 if (xim_) {
230 XCloseIM(xim_);
231 }
232#endif
233
234#ifdef WITH_X11_XINPUT
235 /* Close tablet devices. */
236 clearXInputDevices();
237#endif /* WITH_X11_XINPUT */
238
239 if (xkb_descr_) {
240 XkbFreeKeyboard(xkb_descr_, XkbAllComponentsMask, true);
241 }
242
243 XCloseDisplay(display_);
244}
245
247{
249
250 if (success) {
251#ifdef WITH_INPUT_NDOF
252 ndof_manager_ = new GHOST_NDOFManagerUnix(*this);
253#endif
254 return GHOST_kSuccess;
255 }
256
257 return GHOST_kFailure;
258}
259
261{
262 timespec ts = {0, 0};
263 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
264 GHOST_ASSERT(false, "Could not instantiate monotonic timer!");
265 }
266 /* Taking care not to overflow the tv.tv_sec * 1000 */
267 const uint64_t time = (uint64_t(ts.tv_sec) * 1000) + uint64_t(ts.tv_nsec / 1000000);
268 return time;
269}
270
272{
273 /* NOTE(@ideasman42): Return a time compatible with `getMilliSeconds()`,
274 * this is needed as X11 time-stamps use monotonic time.
275 * The X11 implementation *could* use any basis, in practice though we are supporting
276 * XORG/LIBINPUT which uses time-stamps based on the monotonic time,
277 * Needed to resolve failure to detect double-clicking, see: #40009. */
278
279 /* Accumulate time rollover (as well as store the initial delta from #getMilliSeconds). */
280 static uint64_t timestamp_offset = 0;
281
282 /* The last event time (to detect rollover). */
283 static uint32_t timestamp_prev = 0;
284 /* Causes the X11 time-stamp to be zero based. */
285 static uint32_t timestamp_start = 0;
286
287 static bool is_time_init = false;
288
289#if 0
290 /* Force rollover after 2 seconds (for testing). */
291 {
292 const uint32_t timestamp_wrap_ms = 2000;
293 static uint32_t timestamp_offset_fake = 0;
294 if (!is_time_init) {
295 timestamp_offset_fake = UINT32_MAX - (timestamp + timestamp_wrap_ms);
296 }
297 timestamp = uint32_t(timestamp + timestamp_offset_fake);
298 }
299#endif
300
301 if (!is_time_init) {
302 /* Store the initial delta in the rollover. */
303 const uint64_t current_time = getMilliSeconds();
304 timestamp_offset = current_time;
305 timestamp_start = timestamp;
306 }
307
308 /* Always remove the start time.
309 * This changes the point where `uint32_t` rolls over, but that's OK. */
310 timestamp = uint32_t(timestamp) - timestamp_start;
311
312 if (!is_time_init) {
313 is_time_init = true;
314 timestamp_prev = timestamp;
315 }
316
317 if (timestamp < timestamp_prev) [[unlikely]] {
318 /* Only rollover if this is within a reasonable range. */
319 if (timestamp_prev - timestamp > UINT32_MAX / 2) [[unlikely]] {
320 timestamp_offset += uint64_t(UINT32_MAX) + 1;
321 }
322 }
323 timestamp_prev = timestamp;
324
325 uint64_t timestamp_final = (uint64_t(timestamp) + timestamp_offset);
326
327 return timestamp_final;
328}
329
331{
332 return uint8_t(1);
333}
334
335void GHOST_SystemX11::getMainDisplayDimensions(uint32_t &width, uint32_t &height) const
336{
337 if (display_) {
338 /* NOTE(@ideasman42): for this to work as documented,
339 * we would need to use Xinerama check r54370 for code that did this,
340 * we've since removed since its not worth the extra dependency. */
341 getAllDisplayDimensions(width, height);
342 }
343}
344
345void GHOST_SystemX11::getAllDisplayDimensions(uint32_t &width, uint32_t &height) const
346{
347 if (display_) {
348 width = DisplayWidth(display_, DefaultScreen(display_));
349 height = DisplayHeight(display_, DefaultScreen(display_));
350 }
351}
352
354 int32_t left,
355 int32_t top,
356 uint32_t width,
357 uint32_t height,
359 GHOST_GPUSettings gpu_settings,
360 const bool exclusive,
361 const bool is_dialog,
362 const GHOST_IWindow *parent_window)
363{
364 GHOST_WindowX11 *window = nullptr;
365
366 if (!display_) {
367 return nullptr;
368 }
369
370 const GHOST_ContextParams context_params = GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings);
371 window = new GHOST_WindowX11(this,
372 display_,
373 title,
374 left,
375 top,
376 width,
377 height,
378 state,
379 (GHOST_WindowX11 *)parent_window,
380 gpu_settings.context_type,
381 is_dialog,
382 context_params,
383 exclusive,
384 gpu_settings.preferred_device);
385
386 if (window) {
387 /* Both are now handle in GHOST_WindowX11.cc
388 * Focus and Delete atoms. */
389
390 if (window->getValid()) {
391 /* Store the pointer to the window */
392 window_manager_->addWindow(window);
394 pushEvent(std::make_unique<GHOST_Event>(getMilliSeconds(), GHOST_kEventWindowSize, window));
395 }
396 else {
397 delete window;
398 window = nullptr;
399 }
400 }
401 return window;
402}
403
405{
406 const GHOST_ContextParams context_params_offscreen =
408
409 switch (gpu_settings.context_type) {
410#ifdef WITH_VULKAN_BACKEND
411 case GHOST_kDrawingContextTypeVulkan: {
412 GHOST_Context *context = new GHOST_ContextVK(context_params_offscreen,
413 GHOST_kVulkanPlatformX11,
414 0,
415 display_,
416 nullptr,
417 nullptr,
418 nullptr,
419 1,
420 1,
421 gpu_settings.preferred_device);
422 if (context->initializeDrawingContext()) {
423 return context;
424 }
425 delete context;
426 return nullptr;
427 }
428#endif
429
430#ifdef WITH_OPENGL_BACKEND
431 case GHOST_kDrawingContextTypeOpenGL: {
432 for (int minor = 6; minor >= 3; --minor) {
433 GHOST_Context *context = new GHOST_ContextGLX(
434 context_params_offscreen,
435 (Window) nullptr,
436 display_,
437 (GLXFBConfig) nullptr,
438 GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
439 4,
440 minor,
442 (context_params_offscreen.is_debug ? GLX_CONTEXT_DEBUG_BIT_ARB : 0),
444 if (context->initializeDrawingContext()) {
445 return context;
446 }
447 delete context;
448 }
449 return nullptr;
450 }
451#endif
452
453 default:
454 /* Unsupported backend. */
455 return nullptr;
456 }
457}
458
460{
461 delete context;
462
463 return GHOST_kSuccess;
464}
465
466#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
467static void destroyIMCallback(XIM /*xim*/, XPointer ptr, XPointer /*data*/)
468{
469 GHOST_PRINT("XIM server died\n");
470
471 if (ptr) {
472 *(XIM *)ptr = nullptr;
473 }
474}
475
476bool GHOST_SystemX11::openX11_IM()
477{
478 if (!display_) {
479 return false;
480 }
481
482 /* set locale modifiers such as `@im=ibus` specified by XMODIFIERS. */
483 XSetLocaleModifiers("");
484
485 xim_ = XOpenIM(display_, nullptr, (char *)GHOST_X11_RES_NAME, (char *)GHOST_X11_RES_CLASS);
486 if (!xim_) {
487 return false;
488 }
489
490 XIMCallback destroy;
491 destroy.callback = (XIMProc)destroyIMCallback;
492 destroy.client_data = (XPointer)&xim_;
493 XSetIMValues(xim_, XNDestroyCallback, &destroy, nullptr);
494 return true;
495}
496#endif
497
498GHOST_WindowX11 *GHOST_SystemX11::findGhostWindow(Window xwind) const
499{
500
501 if (xwind == 0) {
502 return nullptr;
503 }
504
505 /* It is not entirely safe to do this as the back-pointer may point
506 * to a window that has recently been removed.
507 * We should always check the window manager's list of windows
508 * and only process events on these windows. */
509
510 const vector<GHOST_IWindow *> &win_vec = window_manager_->getWindows();
511
512 vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
513 vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end();
514
515 for (; win_it != win_end; ++win_it) {
516 GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
517 if (window->getXWindow() == xwind) {
518 return window;
519 }
520 }
521 return nullptr;
522}
523
524static void SleepTillEvent(Display *display, int64_t maxSleep)
525{
526 int fd = ConnectionNumber(display);
527 fd_set fds;
528
529 FD_ZERO(&fds);
530 FD_SET(fd, &fds);
531
532 if (maxSleep == -1) {
533 select(fd + 1, &fds, nullptr, nullptr, nullptr);
534 }
535 else {
536 timeval tv;
537
538 tv.tv_sec = maxSleep / 1000;
539 tv.tv_usec = (maxSleep - tv.tv_sec * 1000) * 1000;
540
541 select(fd + 1, &fds, nullptr, nullptr, &tv);
542 }
543}
544
545/* This function borrowed from QT's X11 support `qclipboard_x11.cpp`. */
549
550static Bool init_timestamp_scanner(Display * /*display*/, XEvent *event, XPointer arg)
551{
552 init_timestamp_data *data = reinterpret_cast<init_timestamp_data *>(arg);
553 switch (event->type) {
554 case ButtonPress:
555 case ButtonRelease:
556 data->timestamp = event->xbutton.time;
557 break;
558 case MotionNotify:
559 data->timestamp = event->xmotion.time;
560 break;
561 case KeyPress:
562 case KeyRelease:
563 data->timestamp = event->xkey.time;
564 break;
565 case PropertyNotify:
566 data->timestamp = event->xproperty.time;
567 break;
568 case EnterNotify:
569 case LeaveNotify:
570 data->timestamp = event->xcrossing.time;
571 break;
572 case SelectionClear:
573 data->timestamp = event->xselectionclear.time;
574 break;
575 default:
576 break;
577 }
578
579 return false;
580}
581
582Time GHOST_SystemX11::lastEventTime(Time default_time)
583{
584 init_timestamp_data data;
585 data.timestamp = default_time;
586 XEvent ev;
587 XCheckIfEvent(display_, &ev, &init_timestamp_scanner, (XPointer)&data);
588
589 return data.timestamp;
590}
591
592bool GHOST_SystemX11::processEvents(bool waitForEvent)
593{
594 /* Get all the current events -- translate them into
595 * ghost events and call base class pushEvent() method. */
596
597 bool anyProcessed = false;
598
599 do {
601
602 if (waitForEvent && dirty_windows_.empty() && !XPending(display_)) {
603 uint64_t next = timerMgr->nextFireTime();
604
605 if (next == GHOST_kFireTimeNever) {
606 SleepTillEvent(display_, -1);
607 }
608 else {
609 const int64_t maxSleep = next - getMilliSeconds();
610
611 if (maxSleep >= 0) {
612 SleepTillEvent(display_, next - getMilliSeconds());
613 }
614 }
615 }
616
617 if (timerMgr->fireTimers(getMilliSeconds())) {
618 anyProcessed = true;
619 }
620
621 while (XPending(display_)) {
622 XEvent xevent;
623 XNextEvent(display_, &xevent);
624
625#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
626 /* open connection to XIM server and create input context (XIC)
627 * when receiving the first FocusIn or KeyPress event after startup,
628 * or recover XIM and XIC when the XIM server has been restarted */
629 if (ELEM(xevent.type, FocusIn, KeyPress)) {
630 if (!xim_ && openX11_IM()) {
631 GHOST_PRINT("Connected to XIM server\n");
632 }
633
634 if (xim_) {
635 GHOST_WindowX11 *window = findGhostWindow(xevent.xany.window);
636 if (window && !window->getX11_XIC() && window->createX11_XIC()) {
637 GHOST_PRINT("XIM input context created\n");
638 if (xevent.type == KeyPress) {
639 /* we can assume the window has input focus
640 * here, because key events are received only
641 * when the window is focused. */
642 XSetICFocus(window->getX11_XIC());
643 }
644 }
645 }
646 }
647
648 /* Ensure generated time-stamps are non-zero. */
649 if (ELEM(xevent.type, KeyPress, KeyRelease)) {
650 if (xevent.xkey.time != 0) {
651 last_key_time_ = xevent.xkey.time;
652 }
653 }
654
655 /* dispatch event to XIM server */
656 if (XFilterEvent(&xevent, (Window) nullptr) == True) {
657 /* do nothing now, the event is consumed by XIM. */
658 continue;
659 }
660#endif
661 /* When using auto-repeat, some key-press events can actually come *after* the
662 * last key-release. The next code takes care of that. */
663 if (xevent.type == KeyRelease) {
664 last_release_keycode_ = xevent.xkey.keycode;
665 last_release_time_ = xevent.xkey.time;
666 }
667 else if (xevent.type == KeyPress) {
668 if ((xevent.xkey.keycode == last_release_keycode_) &&
669 (xevent.xkey.time <= last_release_time_))
670 {
671 continue;
672 }
673 }
674
675 processEvent(&xevent);
676 anyProcessed = true;
677
678#ifdef USE_UNITY_WORKAROUND
679 /* NOTE: processEvent() can't include this code because
680 * KeymapNotify event have no valid window information. */
681
682 /* the X server generates KeymapNotify event immediately after
683 * every EnterNotify and FocusIn event. we handle this event
684 * to correct modifier states. */
685 if (xevent.type == FocusIn) {
686 /* use previous event's window, because KeymapNotify event
687 * has no window information. */
688 GHOST_WindowX11 *window = findGhostWindow(xevent.xany.window);
689 if (window && XPending(display_) >= 2) {
690 XNextEvent(display_, &xevent);
691
692 if (xevent.type == KeymapNotify) {
693 XEvent xev_next;
694
695 /* check if KeyPress or KeyRelease event was generated
696 * in order to confirm the window is active. */
697 XPeekEvent(display_, &xev_next);
698
699 if (ELEM(xev_next.type, KeyPress, KeyRelease)) {
700 const uint64_t event_ms = ms_from_input_time(xev_next.xkey.time);
701 /* XK_Hyper_L/R currently unused. */
702 const static KeySym modifiers[] = {
703 XK_Shift_L,
704 XK_Shift_R,
705 XK_Control_L,
706 XK_Control_R,
707 XK_Alt_L,
708 XK_Alt_R,
709 XK_Super_L,
710 XK_Super_R,
711 XK_Hyper_L,
712 XK_Hyper_R,
713 };
714
715 for (int i = 0; i < int(ARRAY_SIZE(modifiers)); i++) {
716 KeyCode kc = XKeysymToKeycode(display_, modifiers[i]);
717 if (kc != 0 && ((xevent.xkeymap.key_vector[kc >> 3] >> (kc & 7)) & 1) != 0) {
718 pushEvent(std::make_unique<GHOST_EventKey>(event_ms,
720 window,
721 ghost_key_from_keysym(modifiers[i]),
722 false,
723 nullptr));
724 }
725 }
726 }
727 }
728 }
729 }
730#endif /* USE_UNITY_WORKAROUND */
731 }
732
733 if (generateWindowExposeEvents()) {
734 anyProcessed = true;
735 }
736
737#ifdef WITH_INPUT_NDOF
738 if (static_cast<GHOST_NDOFManagerUnix *>(ndof_manager_)->processEvents()) {
739 anyProcessed = true;
740 }
741#endif
742
743 } while (waitForEvent && !anyProcessed);
744
745 return anyProcessed;
746}
747
748#ifdef WITH_X11_XINPUT
749static bool checkTabletProximity(Display *display, XDevice *device)
750{
751 /* we could have true/false/not-found return value, but for now false is OK */
752
753 /* see: state.c from xinput, to get more data out of the device */
754 XDeviceState *state;
755
756 if (device == nullptr) {
757 return false;
758 }
759
760 /* needed since unplugging will abort() without this */
762
763 state = XQueryDeviceState(display, device);
764
766
767 if (state) {
768 XInputClass *cls = state->data;
769 // printf("%d class%s :\n", state->num_classes, (state->num_classes > 1) ? "es" : "");
770 for (int loop = 0; loop < state->num_classes; loop++) {
771 switch (cls->c_class) {
772 case ValuatorClass:
773 XValuatorState *val_state = (XValuatorState *)cls;
774 // printf("ValuatorClass Mode=%s Proximity=%s\n",
775 // val_state->mode & 1 ? "Absolute" : "Relative",
776 // val_state->mode & 2 ? "Out" : "In");
777
778 if ((val_state->mode & 2) == 0) {
779 XFreeDeviceState(state);
780 return true;
781 }
782 break;
783 }
784 cls = (XInputClass *)((char *)cls + cls->length);
785 }
786 XFreeDeviceState(state);
787 }
788 return false;
789}
790#endif /* WITH_X11_XINPUT */
791
792void GHOST_SystemX11::processEvent(XEvent *xe)
793{
794 GHOST_WindowX11 *window = findGhostWindow(xe->xany.window);
795 std::unique_ptr<GHOST_Event> g_event = nullptr;
796
797 /* Detect auto-repeat. */
798 bool is_repeat = false;
799 if (ELEM(xe->type, KeyPress, KeyRelease)) {
800 XKeyEvent *xke = &(xe->xkey);
801
802 /* Set to true if this key will repeat. */
803 bool is_repeat_keycode = false;
804
805 if (xkb_descr_ != nullptr) {
806 /* Use XKB support. */
807 is_repeat_keycode = (
808 /* Should always be true, check just in case. */
809 (xke->keycode < (XkbPerKeyBitArraySize << 3)) &&
810 bit_is_on(xkb_descr_->ctrls->per_key_repeat, xke->keycode));
811 }
812 else {
813 /* No XKB support (filter by modifier). */
814 switch (XLookupKeysym(xke, 0)) {
815 case XK_Shift_L:
816 case XK_Shift_R:
817 case XK_Control_L:
818 case XK_Control_R:
819 case XK_Alt_L:
820 case XK_Alt_R:
821 case XK_Super_L:
822 case XK_Super_R:
823 case XK_Hyper_L:
824 case XK_Hyper_R:
825 case XK_Caps_Lock:
826 case XK_Scroll_Lock:
827 case XK_Num_Lock: {
828 break;
829 }
830 default: {
831 is_repeat_keycode = true;
832 }
833 }
834 }
835
836 if (is_repeat_keycode) {
837 if (xe->type == KeyPress) {
838 if (keycode_last_repeat_key_ == xke->keycode) {
839 is_repeat = true;
840 }
841 keycode_last_repeat_key_ = xke->keycode;
842 }
843 else {
844 if (keycode_last_repeat_key_ == xke->keycode) {
845 keycode_last_repeat_key_ = uint(-1);
846 }
847 }
848 }
849 }
850 else if (xe->type == EnterNotify) {
851 /* We can't tell how the key state changed, clear it to avoid stuck keys. */
852 keycode_last_repeat_key_ = uint(-1);
853 }
854
855#ifdef USE_XINPUT_HOTPLUG
856 /* Hot-Plug support */
857 if (xinput_version_.present) {
858 XEventClass class_presence;
859 int xi_presence;
860
861 DevicePresence(display_, xi_presence, class_presence);
862 (void)class_presence;
863
864 if (xe->type == xi_presence) {
865 const XDevicePresenceNotifyEvent *notify_event = (const XDevicePresenceNotifyEvent *)xe;
866 if (ELEM(notify_event->devchange, DeviceEnabled, DeviceDisabled, DeviceAdded, DeviceRemoved))
867 {
868 refreshXInputDevices();
869
870 /* update all window events */
871 {
872 const vector<GHOST_IWindow *> &win_vec = window_manager_->getWindows();
873 vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
874 vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end();
875
876 for (; win_it != win_end; ++win_it) {
877 GHOST_WindowX11 *window_xinput = static_cast<GHOST_WindowX11 *>(*win_it);
878 window_xinput->refreshXInputDevices();
879 }
880 }
881 }
882 }
883 }
884#endif /* USE_XINPUT_HOTPLUG */
885
886 if (!window) {
887 return;
888 }
889
890#ifdef WITH_X11_XINPUT
891 /* Proximity-Out Events are not reliable, if the tablet is active - check on each event
892 * this adds a little overhead but only while the tablet is in use.
893 * in the future we could have a ghost call window->CheckTabletProximity()
894 * but for now enough parts of the code are checking 'Active'
895 * - campbell */
896 if (window->GetTabletData().Active != GHOST_kTabletModeNone) {
897 bool any_proximity = false;
898
899 for (const GHOST_TabletX11 &xtablet : xtablets_) {
900 if (checkTabletProximity(xe->xany.display, xtablet.Device)) {
901 any_proximity = true;
902 }
903 }
904
905 if (!any_proximity) {
906 // printf("proximity disable\n");
908 }
909 }
910#endif /* WITH_X11_XINPUT */
911 switch (xe->type) {
912 case Expose: {
913 const XExposeEvent &xee = xe->xexpose;
914
915 if (xee.count == 0) {
916 /* Only generate a single expose event per read of the event queue. */
917
918 /* Event has no timestamp. */
919 const uint64_t event_ms = getMilliSeconds();
920
921 g_event = std::make_unique<GHOST_Event>(event_ms, GHOST_kEventWindowUpdate, window);
922 }
923 break;
924 }
925
926 case MotionNotify: {
927 const XMotionEvent &xme = xe->xmotion;
928 const uint64_t event_ms = ms_from_input_time(xme.time);
929
930 bool is_tablet = window->GetTabletData().Active != GHOST_kTabletModeNone;
931
932 if (is_tablet == false && window->getCursorGrabModeIsWarp()) {
933 int32_t x_new = xme.x_root;
934 int32_t y_new = xme.y_root;
935 int32_t x_accum, y_accum;
936
937 /* Warp within bounds. */
938 {
939 GHOST_Rect bounds;
940 int32_t bounds_margin = 0;
941 GHOST_TAxisFlag bounds_axis = GHOST_kAxisNone;
942
943 if (window->getCursorGrabMode() == GHOST_kGrabHide) {
944 window->getClientBounds(bounds);
945
946 /* TODO(@ideasman42): warp the cursor to `window->getCursorGrabInitPos`,
947 * on every motion event, see: D16557 (alternative fix for #102346). */
948 const int32_t subregion_div = 4; /* One quarter of the region. */
949 const int32_t size[2] = {bounds.getWidth(), bounds.getHeight()};
950 const int32_t center[2] = {
951 (bounds.l_ + bounds.r_) / 2,
952 (bounds.t_ + bounds.b_) / 2,
953 };
954 /* Shrink the box to prevent the cursor escaping. */
955 bounds.l_ = center[0] - (size[0] / (subregion_div * 2));
956 bounds.r_ = center[0] + (size[0] / (subregion_div * 2));
957 bounds.t_ = center[1] - (size[1] / (subregion_div * 2));
958 bounds.b_ = center[1] + (size[1] / (subregion_div * 2));
959 bounds_margin = 0;
961 }
962 else {
963 /* Fallback to window bounds. */
964 if (window->getCursorGrabBounds(bounds) == GHOST_kFailure) {
965 window->getClientBounds(bounds);
966 }
967 /* Could also clamp to screen bounds wrap with a window outside the view will
968 * fail at the moment. Use offset of 8 in case the window is at screen bounds. */
969 bounds_margin = 8;
970 bounds_axis = window->getCursorGrabAxis();
971 }
972
973 /* Could also clamp to screen bounds wrap with a window outside the view will
974 * fail at the moment. Use inset in case the window is at screen bounds. */
975 bounds.wrapPoint(x_new, y_new, bounds_margin, bounds_axis);
976 }
977
978 window->getCursorGrabAccum(x_accum, y_accum);
979
980 if (x_new != xme.x_root || y_new != xme.y_root) {
981 /* Use time of last event to avoid wrapping several times on the 'same' actual wrap.
982 * Note that we need to deal with X and Y separately as those might wrap at the same time
983 * but still in two different events (corner case, see #74918).
984 * We also have to add a few extra milliseconds of 'padding', as sometimes we get two
985 * close events that will generate extra wrap on the same axis within those few
986 * milliseconds. */
987 if (x_new != xme.x_root && xme.time > last_warp_x_) {
988 x_accum += (xme.x_root - x_new);
989 last_warp_x_ = lastEventTime(xme.time) + 25;
990 }
991 if (y_new != xme.y_root && xme.time > last_warp_y_) {
992 y_accum += (xme.y_root - y_new);
993 last_warp_y_ = lastEventTime(xme.time) + 25;
994 }
995 window->setCursorGrabAccum(x_accum, y_accum);
996 /* When wrapping we don't need to add an event because the
997 * #setCursorPosition call will cause a new event after. */
998 setCursorPosition(x_new, y_new); /* wrap */
999 }
1000 else {
1001 g_event = std::make_unique<GHOST_EventCursor>(event_ms,
1003 window,
1004 xme.x_root + x_accum,
1005 xme.y_root + y_accum,
1006 window->GetTabletData());
1007 }
1008 }
1009 else {
1010 g_event = std::make_unique<GHOST_EventCursor>(event_ms,
1012 window,
1013 xme.x_root,
1014 xme.y_root,
1015 window->GetTabletData());
1016 }
1017 break;
1018 }
1019
1020 case KeyPress:
1021 case KeyRelease: {
1022 XKeyEvent *xke = &(xe->xkey);
1023#ifdef WITH_X11_XINPUT
1024 /* Can be zero for XIM generated events. */
1025 const Time time = xke->time ? xke->time : last_key_time_;
1026#else
1027 const Time time = xke->time;
1028#endif
1029 const uint64_t event_ms = ms_from_input_time(time);
1030
1031 KeySym key_sym;
1032 char *utf8_buf = nullptr;
1033 char ascii;
1034
1035#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1036 /* `utf8_array[]` is initial buffer used for #Xutf8LookupString().
1037 * if the length of the UTF8 string exceeds this array, allocate
1038 * another memory area and call #Xutf8LookupString() again.
1039 * the last 5 bytes are used to avoid segfault that might happen
1040 * at the end of this buffer when the constructor of #GHOST_EventKey
1041 * reads 6 bytes regardless of the effective data length. */
1042 char utf8_array[16 * 6 + 5]; /* 16 UTF8 characters. */
1043 int len = 1; /* At least one null character will be stored. */
1044#else
1045 char utf8_array[sizeof(GHOST_TEventKeyData::utf8_buf)] = {'\0'};
1046#endif
1047 GHOST_TEventType type = (xke->type == KeyPress) ? GHOST_kEventKeyDown : GHOST_kEventKeyUp;
1048
1049 GHOST_TKey gkey;
1050
1051#ifdef USE_NON_LATIN_KB_WORKAROUND
1052 /* XXX: Code below is kinda awfully convoluted... Issues are:
1053 * - In keyboards like Latin ones, numbers need a 'Shift' to be accessed but key_sym
1054 * is unmodified (or anyone swapping the keys with `xmodmap`).
1055 * - #XLookupKeysym seems to always use first defined key-map (see #47228), which generates
1056 * key-codes unusable by #ghost_key_from_keysym for non-Latin-compatible key-maps.
1057 *
1058 * To address this, we:
1059 * - Try to get a 'number' key_sym using #XLookupKeysym (with virtual shift modifier),
1060 * in a very restrictive set of cases.
1061 * - Fallback to #XLookupString to get a key_sym from active user-defined key-map.
1062 *
1063 * Note that:
1064 * - This effectively 'lock' main number keys to always output number events
1065 * (except when using alt-gr).
1066 * - This enforces users to use an ASCII-compatible key-map with Blender -
1067 * but at least it gives predictable and consistent results.
1068 *
1069 * Also, note that nothing in XLib sources [1] makes it obvious why those two functions give
1070 * different key_sym results.
1071 *
1072 * [1] http://cgit.freedesktop.org/xorg/lib/libX11/tree/src/KeyBind.c
1073 */
1074 KeySym key_sym_str;
1075 /* Mode_switch 'modifier' is `AltGr` - when this one or Shift are enabled,
1076 * we do not want to apply that 'forced number' hack. */
1077 const uint mode_switch_mask = XkbKeysymToModifiers(xke->display, XK_Mode_switch);
1078 const uint number_hack_forbidden_kmods_mask = mode_switch_mask | ShiftMask;
1079 if ((xke->keycode >= 10 && xke->keycode < 20) &&
1080 ((xke->state & number_hack_forbidden_kmods_mask) == 0))
1081 {
1082 key_sym = XLookupKeysym(xke, ShiftMask);
1083 if (!((key_sym >= XK_0) && (key_sym <= XK_9))) {
1084 key_sym = XLookupKeysym(xke, 0);
1085 }
1086 }
1087 else {
1088 key_sym = XLookupKeysym(xke, 0);
1089 }
1090
1091 if (!XLookupString(xke, &ascii, 1, &key_sym_str, nullptr)) {
1092 ascii = '\0';
1093 }
1094
1095 /* Only allow a limited set of keys from XLookupKeysym,
1096 * all others we take from XLookupString, unless it gives unknown key... */
1097 gkey = ghost_key_from_keysym_or_keycode(key_sym, xkb_descr_, xke->keycode);
1098 switch (gkey) {
1099 case GHOST_kKeyRightAlt:
1100 case GHOST_kKeyLeftAlt:
1105 case GHOST_kKeyLeftOS:
1106 case GHOST_kKeyRightOS:
1109 case GHOST_kKey0:
1110 case GHOST_kKey1:
1111 case GHOST_kKey2:
1112 case GHOST_kKey3:
1113 case GHOST_kKey4:
1114 case GHOST_kKey5:
1115 case GHOST_kKey6:
1116 case GHOST_kKey7:
1117 case GHOST_kKey8:
1118 case GHOST_kKey9:
1119 case GHOST_kKeyNumpad0:
1120 case GHOST_kKeyNumpad1:
1121 case GHOST_kKeyNumpad2:
1122 case GHOST_kKeyNumpad3:
1123 case GHOST_kKeyNumpad4:
1124 case GHOST_kKeyNumpad5:
1125 case GHOST_kKeyNumpad6:
1126 case GHOST_kKeyNumpad7:
1127 case GHOST_kKeyNumpad8:
1128 case GHOST_kKeyNumpad9:
1135 break;
1136 default: {
1137 GHOST_TKey gkey_str = ghost_key_from_keysym(key_sym_str);
1138 if (gkey_str != GHOST_kKeyUnknown) {
1139 gkey = gkey_str;
1140 }
1141 }
1142 }
1143#else
1144 /* In keyboards like Latin ones,
1145 * numbers needs a 'Shift' to be accessed but key_sym
1146 * is unmodified (or anyone swapping the keys with `xmodmap`).
1147 *
1148 * Here we look at the 'Shifted' version of the key.
1149 * If it is a number, then we take it instead of the normal key.
1150 *
1151 * The modified key is sent in the `ascii`s variable anyway.
1152 */
1153 if ((xke->keycode >= 10 && xke->keycode < 20) &&
1154 ((key_sym = XLookupKeysym(xke, ShiftMask)) >= XK_0) && (key_sym <= XK_9))
1155 {
1156 /* Pass (keep shifted `key_sym`). */
1157 }
1158 else {
1159 /* regular case */
1160 key_sym = XLookupKeysym(xke, 0);
1161 }
1162
1163 gkey = ghost_key_from_keysym_or_keycode(key_sym, xkb_descr_, xke->keycode);
1164
1165 if (!XLookupString(xke, &ascii, 1, nullptr, nullptr)) {
1166 ascii = '\0';
1167 }
1168#endif
1169
1170#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1171 /* Only used for key-press. */
1172 XIC xic = nullptr;
1173#endif
1174
1175 if (xke->type == KeyPress) {
1176 utf8_buf = utf8_array;
1177#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1178 /* Setting unicode on key-up events gives #XLookupNone status. */
1179 xic = window->getX11_XIC();
1180 if (xic) {
1181 Status status;
1182
1183 /* Use UTF8 because its not locale repentant, from XORG docs. */
1184 if (!(len = Xutf8LookupString(
1185 xic, xke, utf8_buf, sizeof(utf8_array) - 5, &key_sym, &status)))
1186 {
1187 utf8_buf[0] = '\0';
1188 }
1189
1190 if (status == XBufferOverflow) {
1191 utf8_buf = (char *)malloc(len + 5);
1192 len = Xutf8LookupString(xic, xke, utf8_buf, len, &key_sym, &status);
1193 }
1194
1195 if (ELEM(status, XLookupChars, XLookupBoth)) {
1196 /* Check for ASCII control characters.
1197 * Inline `iscntrl` because the users locale must not change behavior. */
1198 if ((utf8_buf[0] < 32 && utf8_buf[0] > 0) || (utf8_buf[0] == 127)) {
1199 utf8_buf[0] = '\0';
1200 }
1201 }
1202 else if (status == XLookupKeySym) {
1203 /* this key doesn't have a text representation, it is a command
1204 * key of some sort */
1205 }
1206 else {
1207 printf("Bad keycode lookup. Keysym 0x%x Status: %s\n",
1208 uint(key_sym),
1209 (status == XLookupNone ? "XLookupNone" :
1210 status == XLookupKeySym ? "XLookupKeySym" :
1211 "Unknown status"));
1212
1213 printf("'%.*s' %p %p\n", len, utf8_buf, xic, xim_);
1214 }
1215 }
1216 else {
1217 utf8_buf[0] = '\0';
1218 }
1219#endif
1220 if (!utf8_buf[0] && ascii) {
1221 utf8_buf[0] = ascii;
1222 utf8_buf[1] = '\0';
1223 }
1224 }
1225
1226 g_event = std::make_unique<GHOST_EventKey>(
1227 event_ms, type, window, gkey, is_repeat, utf8_buf);
1228
1229#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1230 /* When using IM for some languages such as Japanese,
1231 * one event inserts multiple UTF8 characters. */
1232 if (xke->type == KeyPress && xic) {
1233 uchar c;
1234 int i = 0;
1235 while (true) {
1236 /* Search character boundary. */
1237 if (uchar(utf8_buf[i++]) > 0x7f) {
1238 for (; i < len; ++i) {
1239 c = utf8_buf[i];
1240 if (c < 0x80 || c > 0xbf) {
1241 break;
1242 }
1243 }
1244 }
1245
1246 if (i >= len) {
1247 break;
1248 }
1249 /* Enqueue previous character. */
1250 pushEvent(std::move(g_event));
1251
1252 g_event = std::make_unique<GHOST_EventKey>(
1253 event_ms, type, window, gkey, is_repeat, &utf8_buf[i]);
1254 }
1255 }
1256
1257 if (utf8_buf != utf8_array) {
1258 free(utf8_buf);
1259 }
1260#endif
1261
1262 break;
1263 }
1264
1265 case ButtonPress:
1266 case ButtonRelease: {
1267 const XButtonEvent &xbe = xe->xbutton;
1268 const uint64_t event_ms = ms_from_input_time(xbe.time);
1270 GHOST_TEventType type = (xbe.type == ButtonPress) ? GHOST_kEventButtonDown :
1272
1273 /* process wheel mouse events and break, only pass on press events */
1274 if (xbe.button == Button4) {
1275 if (xbe.type == ButtonPress) {
1276 g_event = std::make_unique<GHOST_EventWheel>(
1277 event_ms, window, GHOST_kEventWheelAxisVertical, 1);
1278 }
1279 break;
1280 }
1281 if (xbe.button == Button5) {
1282 if (xbe.type == ButtonPress) {
1283 g_event = std::make_unique<GHOST_EventWheel>(
1284 event_ms, window, GHOST_kEventWheelAxisVertical, -1);
1285 }
1286 break;
1287 }
1288
1289 /* process rest of normal mouse buttons */
1290 if (xbe.button == Button1) {
1291 gbmask = GHOST_kButtonMaskLeft;
1292 }
1293 else if (xbe.button == Button2) {
1294 gbmask = GHOST_kButtonMaskMiddle;
1295 }
1296 else if (xbe.button == Button3) {
1297 gbmask = GHOST_kButtonMaskRight;
1298 /* It seems events 6 and 7 are for horizontal scrolling.
1299 * you can re-order button mapping like this... (swaps 6,7 with 8,9)
1300 * `xmodmap -e "pointer = 1 2 3 4 5 8 9 6 7"` */
1301 }
1302 else if (xbe.button == 6) {
1303 gbmask = GHOST_kButtonMaskButton6;
1304 }
1305 else if (xbe.button == 7) {
1306 gbmask = GHOST_kButtonMaskButton7;
1307 }
1308 else if (xbe.button == 8) {
1309 gbmask = GHOST_kButtonMaskButton4;
1310 }
1311 else if (xbe.button == 9) {
1312 gbmask = GHOST_kButtonMaskButton5;
1313 }
1314 else {
1315 break;
1316 }
1317
1318 g_event = std::make_unique<GHOST_EventButton>(
1319 event_ms, type, window, gbmask, window->GetTabletData());
1320 break;
1321 }
1322
1323 /* change of size, border, layer etc. */
1324 case ConfigureNotify: {
1325 // const XConfigureEvent & xce = xe->xconfigure;
1326 /* Event has no timestamp. */
1327 const uint64_t event_ms = getMilliSeconds();
1328
1329 g_event = std::make_unique<GHOST_Event>(event_ms, GHOST_kEventWindowSize, window);
1330 break;
1331 }
1332
1333 case FocusIn:
1334 case FocusOut: {
1335 const XFocusChangeEvent &xfe = xe->xfocus;
1336
1337 /* TODO: make sure this is the correct place for activate/deactivate */
1338#if 0
1339 printf("X: focus %s for window %d\n", xfe.type == FocusIn ? "in" : "out", int(xfe.window));
1340#endif
1341
1342 /* May have to look at the type of event and filter some out. */
1343
1344 GHOST_TEventType gtype = (xfe.type == FocusIn) ? GHOST_kEventWindowActivate :
1346
1347#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1348 XIC xic = window->getX11_XIC();
1349 if (xic) {
1350 if (xe->type == FocusIn) {
1351 XSetICFocus(xic);
1352 }
1353 else {
1354 XUnsetICFocus(xic);
1355 }
1356 }
1357#endif
1358
1359 g_event = std::make_unique<GHOST_Event>(getMilliSeconds(), gtype, window);
1360 break;
1361 }
1362 case ClientMessage: {
1363 XClientMessageEvent &xcme = xe->xclient;
1364
1365 if (((Atom)xcme.data.l[0]) == atom_.WM_DELETE_WINDOW) {
1366 g_event = std::make_unique<GHOST_Event>(
1368 }
1369 else if (((Atom)xcme.data.l[0]) == atom_.WM_TAKE_FOCUS) {
1370 XWindowAttributes attr;
1371 Window fwin;
1372 int revert_to;
1373
1374 /* as ICCCM say, we need reply this event
1375 * with a #SetInputFocus, the data[1] have
1376 * the valid timestamp (send by the wm).
1377 *
1378 * Some WM send this event before the
1379 * window is really mapped (for example
1380 * change from virtual desktop), so we need
1381 * to be sure that our windows is mapped
1382 * or this call fail and close blender.
1383 */
1384 if (XGetWindowAttributes(display_, xcme.window, &attr) == True) {
1385 if (XGetInputFocus(display_, &fwin, &revert_to) == True) {
1386 if (attr.map_state == IsViewable) {
1387 if (fwin != xcme.window) {
1388 XSetInputFocus(display_, xcme.window, RevertToParent, xcme.data.l[1]);
1389 }
1390 }
1391 }
1392 }
1393 }
1394 else {
1395#ifdef WITH_XDND
1396 /* try to handle drag event
1397 * (if there's no such events, #GHOST_HandleClientMessage will return zero) */
1398 if (window->getDropTarget()->GHOST_HandleClientMessage(xe) == false) {
1399 /* Unknown client message, ignore */
1400 }
1401#else
1402 /* Unknown client message, ignore */
1403#endif
1404 }
1405
1406 break;
1407 }
1408
1409 case DestroyNotify:
1410 ::exit(-1);
1411 /* We're not interested in the following things.(yet...) */
1412 case NoExpose:
1413 case GraphicsExpose:
1414 break;
1415
1416 case EnterNotify:
1417 case LeaveNotify: {
1418 /* #XCrossingEvents pointer leave enter window.
1419 * also do cursor move here, #MotionNotify only
1420 * happens when motion starts & ends inside window.
1421 * we only do moves when the crossing mode is 'normal'
1422 * (really crossing between windows) since some window-managers
1423 * also send grab/un-grab crossings for mouse-wheel events.
1424 */
1425 const XCrossingEvent &xce = xe->xcrossing;
1426 const uint64_t event_ms = ms_from_input_time(xce.time);
1427 if (xce.mode == NotifyNormal) {
1428 g_event = std::make_unique<GHOST_EventCursor>(event_ms,
1430 window,
1431 xce.x_root,
1432 xce.y_root,
1433 window->GetTabletData());
1434 }
1435
1436#if 0
1437 printf(
1438 "X: %s window %d\n", xce.type == EnterNotify ? "entering" : "leaving", int(xce.window));
1439#endif
1440
1441 if (xce.type == EnterNotify) {
1443 }
1444 else {
1446 }
1447
1448 break;
1449 }
1450 case MapNotify:
1451 /*
1452 * From ICCCM:
1453 * [ Clients can select for #StructureNotify on their
1454 * top-level windows to track transition between
1455 * Normal and Iconic states. Receipt of a #MapNotify
1456 * event will indicate a transition to the Normal
1457 * state, and receipt of an #UnmapNotify event will
1458 * indicate a transition to the Iconic state. ]
1459 */
1460 if (window->post_init_ == True) {
1461 /*
1462 * Now we are sure that the window is
1463 * mapped, so only need change the state.
1464 */
1465 window->setState(window->post_state_);
1466 window->post_init_ = False;
1467 }
1468 break;
1469 case UnmapNotify:
1470 break;
1471 case MappingNotify:
1472 case ReparentNotify:
1473 break;
1474 case SelectionRequest: {
1475 XEvent nxe;
1476 XSelectionRequestEvent *xse = &xe->xselectionrequest;
1477
1478 /* support obsolete clients */
1479 if (xse->property == None) {
1480 xse->property = xse->target;
1481 }
1482
1483 nxe.xselection.type = SelectionNotify;
1484 nxe.xselection.requestor = xse->requestor;
1485 nxe.xselection.property = xse->property;
1486 nxe.xselection.display = xse->display;
1487 nxe.xselection.selection = xse->selection;
1488 nxe.xselection.target = xse->target;
1489 nxe.xselection.time = xse->time;
1490
1491 /* Check to see if the requester is asking for String */
1492 if (ELEM(xse->target, atom_.UTF8_STRING, atom_.STRING, atom_.COMPOUND_TEXT, atom_.C_STRING))
1493 {
1494 if (xse->selection == XInternAtom(display_, "PRIMARY", False)) {
1495 XChangeProperty(display_,
1496 xse->requestor,
1497 xse->property,
1498 xse->target,
1499 8,
1500 PropModeReplace,
1502 strlen(txt_select_buffer));
1503 }
1504 else if (xse->selection == XInternAtom(display_, "CLIPBOARD", False)) {
1505 XChangeProperty(display_,
1506 xse->requestor,
1507 xse->property,
1508 xse->target,
1509 8,
1510 PropModeReplace,
1512 strlen(txt_cut_buffer));
1513 }
1514 }
1515 else if (xse->target == atom_.TARGETS) {
1516 const Atom atom_list[] = {
1517 atom_.TARGETS, atom_.UTF8_STRING, atom_.STRING, atom_.COMPOUND_TEXT, atom_.C_STRING};
1518 XChangeProperty(display_,
1519 xse->requestor,
1520 xse->property,
1521 XA_ATOM,
1522 32,
1523 PropModeReplace,
1524 reinterpret_cast<const uchar *>(atom_list),
1525 ARRAY_SIZE(atom_list));
1526 XFlush(display_);
1527 }
1528 else {
1529 /* Change property to None because we do not support the selection request target. */
1530 nxe.xselection.property = None;
1531 }
1532
1533 /* Send the event to the client 0 0 == False, #SelectionNotify */
1534 XSendEvent(display_, xse->requestor, 0, 0, &nxe);
1535 XFlush(display_);
1536 break;
1537 }
1538
1539 default: {
1540#ifdef WITH_X11_XINPUT
1541 for (GHOST_TabletX11 &xtablet : xtablets_) {
1542 if (ELEM(xe->type, xtablet.MotionEvent, xtablet.PressEvent)) {
1543 const XDeviceMotionEvent *data = (const XDeviceMotionEvent *)xe;
1544 if (data->deviceid != xtablet.ID) {
1545 continue;
1546 }
1547
1548 const uchar axis_first = data->first_axis;
1549 const uchar axes_end = axis_first + data->axes_count; /* after the last */
1550 int axis_value;
1551
1552 /* stroke might begin without leading ProxyIn event,
1553 * this happens when window is opened when stylus is already hovering
1554 * around tablet surface */
1555 window->GetTabletData().Active = xtablet.mode;
1556
1557 /* NOTE: This event might be generated with incomplete data-set
1558 * (don't exactly know why, looks like in some cases, if the value does not change,
1559 * it is not included in subsequent #XDeviceMotionEvent events).
1560 * So we have to check which values this event actually contains!
1561 */
1562
1563# define AXIS_VALUE_GET(axis, val) \
1564 ((axis_first <= axis && axes_end > axis) && \
1565 ((void)(val = data->axis_data[axis - axis_first]), true))
1566
1567 if (AXIS_VALUE_GET(2, axis_value)) {
1568 window->GetTabletData().Pressure = axis_value / float(xtablet.PressureLevels);
1569 }
1570
1571 /* NOTE(@broken): the `short` cast and the & 0xffff is bizarre and unexplained anywhere,
1572 * but I got garbage data without it. Found it in the `xidump.c` source.
1573 *
1574 * NOTE(@mont29): The '& 0xffff' just truncates the value to its two lowest bytes,
1575 * this probably means some drivers do not properly set the whole int value?
1576 * Since we convert to float afterward,
1577 * I don't think we need to cast to short here, but do not have a device to check this.
1578 */
1579 if (AXIS_VALUE_GET(3, axis_value)) {
1580 window->GetTabletData().Xtilt = short(axis_value & 0xffff) /
1581 float(xtablet.XtiltLevels);
1582 }
1583 if (AXIS_VALUE_GET(4, axis_value)) {
1584 window->GetTabletData().Ytilt = short(axis_value & 0xffff) /
1585 float(xtablet.YtiltLevels);
1586 }
1587
1588# undef AXIS_VALUE_GET
1589 }
1590 else if (xe->type == xtablet.ProxInEvent) {
1591 const XProximityNotifyEvent *data = (const XProximityNotifyEvent *)xe;
1592 if (data->deviceid != xtablet.ID) {
1593 continue;
1594 }
1595
1596 window->GetTabletData().Active = xtablet.mode;
1597 }
1598 else if (xe->type == xtablet.ProxOutEvent) {
1600 }
1601 }
1602#endif // WITH_X11_XINPUT
1603 break;
1604 }
1605 }
1606
1607 if (g_event) {
1608 pushEvent(std::move(g_event));
1609 }
1610}
1611
1613{
1614 /* NOTE: There are known issues/limitations at the moment:
1615 *
1616 * - Blender has no control of the cursor outside of its window, so it is
1617 * not going to be the eyedropper icon.
1618 * - GHOST does not report click events from outside of the window, so the
1619 * user needs to press Enter instead.
1620 *
1621 * Ref #111303. */
1622
1623 XColor c;
1624 int32_t x, y;
1625
1627 return GHOST_kFailure;
1628 }
1629 XImage *image = XGetImage(
1630 display_, XRootWindow(display_, XDefaultScreen(display_)), x, y, 1, 1, AllPlanes, XYPixmap);
1631 if (image == nullptr) {
1632 return GHOST_kFailure;
1633 }
1634 c.pixel = XGetPixel(image, 0, 0);
1635 XFree(image);
1636 XQueryColor(display_, XDefaultColormap(display_, XDefaultScreen(display_)), &c);
1637
1638 /* X11 returns colors in the [0, 65535] range, so we need to scale back to [0, 1]. */
1639 r_color[0] = c.red / 65535.0f;
1640 r_color[1] = c.green / 65535.0f;
1641 r_color[2] = c.blue / 65535.0f;
1642 return GHOST_kSuccess;
1643}
1644
1646{
1647
1648 /* Analyze the masks returned from #XQueryPointer. */
1649
1650 memset((void *)keyboard_vector_, 0, sizeof(keyboard_vector_));
1651
1652 XQueryKeymap(display_, (char *)keyboard_vector_);
1653
1654 /* Now translate key symbols into key-codes and test with vector. */
1655
1656 const static KeyCode shift_l = XKeysymToKeycode(display_, XK_Shift_L);
1657 const static KeyCode shift_r = XKeysymToKeycode(display_, XK_Shift_R);
1658 const static KeyCode control_l = XKeysymToKeycode(display_, XK_Control_L);
1659 const static KeyCode control_r = XKeysymToKeycode(display_, XK_Control_R);
1660 const static KeyCode alt_l = XKeysymToKeycode(display_, XK_Alt_L);
1661 const static KeyCode alt_r = XKeysymToKeycode(display_, XK_Alt_R);
1662 const static KeyCode super_l = XKeysymToKeycode(display_, XK_Super_L);
1663 const static KeyCode super_r = XKeysymToKeycode(display_, XK_Super_R);
1664 const static KeyCode hyper_l = XKeysymToKeycode(display_, XK_Hyper_L);
1665 const static KeyCode hyper_r = XKeysymToKeycode(display_, XK_Hyper_R);
1666
1667 /* shift */
1669 ((keyboard_vector_[shift_l >> 3] >> (shift_l & 7)) & 1) != 0);
1671 ((keyboard_vector_[shift_r >> 3] >> (shift_r & 7)) & 1) != 0);
1672 /* control */
1674 ((keyboard_vector_[control_l >> 3] >> (control_l & 7)) & 1) != 0);
1676 ((keyboard_vector_[control_r >> 3] >> (control_r & 7)) & 1) != 0);
1677 /* alt */
1678 keys.set(GHOST_kModifierKeyLeftAlt, ((keyboard_vector_[alt_l >> 3] >> (alt_l & 7)) & 1) != 0);
1679 keys.set(GHOST_kModifierKeyRightAlt, ((keyboard_vector_[alt_r >> 3] >> (alt_r & 7)) & 1) != 0);
1680 /* super (windows) - only one GHOST-kModifierKeyOS, so mapping to either */
1681 keys.set(GHOST_kModifierKeyLeftOS, ((keyboard_vector_[super_l >> 3] >> (super_l & 7)) & 1) != 0);
1683 ((keyboard_vector_[super_r >> 3] >> (super_r & 7)) & 1) != 0);
1684 /* hyper */
1686 ((keyboard_vector_[hyper_l >> 3] >> (hyper_l & 7)) & 1) != 0);
1688 ((keyboard_vector_[hyper_r >> 3] >> (hyper_r & 7)) & 1) != 0);
1689
1690 return GHOST_kSuccess;
1691}
1692
1694{
1695 Window root_return, child_return;
1696 int rx, ry, wx, wy;
1697 uint mask_return;
1698
1699 if (XQueryPointer(display_,
1700 RootWindow(display_, DefaultScreen(display_)),
1701 &root_return,
1702 &child_return,
1703 &rx,
1704 &ry,
1705 &wx,
1706 &wy,
1707 &mask_return) == True)
1708 {
1709 buttons.set(GHOST_kButtonMaskLeft, (mask_return & Button1Mask) != 0);
1710 buttons.set(GHOST_kButtonMaskMiddle, (mask_return & Button2Mask) != 0);
1711 buttons.set(GHOST_kButtonMaskRight, (mask_return & Button3Mask) != 0);
1712 buttons.set(GHOST_kButtonMaskButton4, (mask_return & Button4Mask) != 0);
1713 buttons.set(GHOST_kButtonMaskButton5, (mask_return & Button5Mask) != 0);
1714 }
1715 else {
1716 return GHOST_kFailure;
1717 }
1718
1719 return GHOST_kSuccess;
1720}
1721
1723 int32_t &x,
1724 int32_t &y,
1725 Window *child_return)
1726{
1727 int rx, ry, wx, wy;
1728 uint mask_return;
1729 Window root_return;
1730
1731 if (XQueryPointer(display,
1732 RootWindow(display, DefaultScreen(display)),
1733 &root_return,
1734 child_return,
1735 &rx,
1736 &ry,
1737 &wx,
1738 &wy,
1739 &mask_return) == False)
1740 {
1741 return GHOST_kFailure;
1742 }
1743
1744 x = rx;
1745 y = ry;
1746
1747 return GHOST_kSuccess;
1748}
1749
1751{
1752 Window child_return;
1753 return getCursorPosition_impl(display_, x, y, &child_return);
1754}
1755
1757{
1758
1759 /* This is a brute force move in screen coordinates
1760 * #XWarpPointer does relative moves so first determine the
1761 * current pointer position. */
1762
1763 int cx, cy;
1764
1765#ifdef WITH_XWAYLAND_HACK
1766 Window child_return = None;
1767 if (getCursorPosition_impl(display_, cx, cy, &child_return) == GHOST_kFailure) {
1768 return GHOST_kFailure;
1769 }
1770#else
1771 if (getCursorPosition(cx, cy) == GHOST_kFailure) {
1772 return GHOST_kFailure;
1773 }
1774#endif
1775
1776 int relx = x - cx;
1777 int rely = y - cy;
1778
1779#ifdef WITH_XWAYLAND_HACK
1780 if (use_xwayland_hack) {
1781 if (child_return != None) {
1782 XFixesHideCursor(display_, child_return);
1783 }
1784 }
1785#endif
1786
1787#if defined(WITH_X11_XINPUT) && defined(USE_X11_XINPUT_WARP)
1788 if ((xinput_version_.present) && (xinput_version_.major_version >= 2)) {
1789 /* Needed to account for XInput "Coordinate Transformation Matrix", see #48901 */
1790 int device_id;
1791 if (XIGetClientPointer(display_, None, &device_id) != False) {
1792 XIWarpPointer(display_, device_id, None, None, 0, 0, 0, 0, relx, rely);
1793 }
1794 }
1795 else
1796#endif
1797 {
1798 XWarpPointer(display_, None, None, 0, 0, 0, 0, relx, rely);
1799 }
1800
1801#ifdef WITH_XWAYLAND_HACK
1802 if (use_xwayland_hack) {
1803 if (child_return != None) {
1804 XFixesShowCursor(display_, child_return);
1805 }
1806 }
1807#endif
1808
1809 XSync(display_, 0); /* Sync to process all requests */
1810
1811 return GHOST_kSuccess;
1812}
1813
1815{
1816 return GHOST_TCapabilityFlag(
1818 /* NOTE: order the following flags as they they're declared in the source. */
1819 ~(
1820 /* No support yet for image copy/paste. */
1822 /* No support yet for IME input methods. */
1824 /* No support for window decoration styles. */
1826 /* No support yet for RGBA mouse cursors. */
1828 /* No support yet for dynamic cursor generation. */
1830 /* No support for window path meta-data. */
1832}
1833
1835{
1836 GHOST_ASSERT((bad_wind != nullptr), "addDirtyWindow() nullptr ptr trapped (window)");
1837
1838 dirty_windows_.push_back(bad_wind);
1839}
1840
1841bool GHOST_SystemX11::generateWindowExposeEvents()
1842{
1843 vector<GHOST_WindowX11 *>::const_iterator w_start = dirty_windows_.begin();
1844 vector<GHOST_WindowX11 *>::const_iterator w_end = dirty_windows_.end();
1845 bool anyProcessed = false;
1846
1847 for (; w_start != w_end; ++w_start) {
1848 auto g_event = std::make_unique<GHOST_Event>(
1850
1851 (*w_start)->validate();
1852
1853 if (g_event) {
1854 pushEvent(std::move(g_event));
1855 anyProcessed = true;
1856 }
1857 }
1858
1859 dirty_windows_.clear();
1860 return anyProcessed;
1861}
1862
1864 XkbDescPtr xkb_descr,
1865 const KeyCode keycode)
1866{
1867 GHOST_TKey type = ghost_key_from_keysym(key_sym);
1868 if (type == GHOST_kKeyUnknown) {
1869 if (xkb_descr) {
1870 type = ghost_key_from_keycode(xkb_descr, keycode);
1871 }
1872 }
1873 return type;
1874}
1875
1876#define GXMAP(k, x, y) \
1877 case x: \
1878 k = y; \
1879 break
1880
1881static GHOST_TKey ghost_key_from_keysym(const KeySym key)
1882{
1883 GHOST_TKey type;
1884
1885 if ((key >= XK_A) && (key <= XK_Z)) {
1886 type = GHOST_TKey(key - XK_A + int(GHOST_kKeyA));
1887 }
1888 else if ((key >= XK_a) && (key <= XK_z)) {
1889 type = GHOST_TKey(key - XK_a + int(GHOST_kKeyA));
1890 }
1891 else if ((key >= XK_0) && (key <= XK_9)) {
1892 type = GHOST_TKey(key - XK_0 + int(GHOST_kKey0));
1893 }
1894 else if ((key >= XK_F1) && (key <= XK_F24)) {
1895 type = GHOST_TKey(key - XK_F1 + int(GHOST_kKeyF1));
1896 }
1897 else {
1898 switch (key) {
1899 GXMAP(type, XK_BackSpace, GHOST_kKeyBackSpace);
1900 GXMAP(type, XK_Tab, GHOST_kKeyTab);
1901 GXMAP(type, XK_ISO_Left_Tab, GHOST_kKeyTab);
1902 GXMAP(type, XK_Return, GHOST_kKeyEnter);
1903 GXMAP(type, XK_Escape, GHOST_kKeyEsc);
1904 GXMAP(type, XK_space, GHOST_kKeySpace);
1905
1906 GXMAP(type, XK_Linefeed, GHOST_kKeyLinefeed);
1907 GXMAP(type, XK_semicolon, GHOST_kKeySemicolon);
1908 GXMAP(type, XK_period, GHOST_kKeyPeriod);
1909 GXMAP(type, XK_comma, GHOST_kKeyComma);
1910 GXMAP(type, XK_quoteright, GHOST_kKeyQuote);
1911 GXMAP(type, XK_quoteleft, GHOST_kKeyAccentGrave);
1912 GXMAP(type, XK_minus, GHOST_kKeyMinus);
1913 GXMAP(type, XK_plus, GHOST_kKeyPlus);
1914 GXMAP(type, XK_slash, GHOST_kKeySlash);
1915 GXMAP(type, XK_backslash, GHOST_kKeyBackslash);
1916 GXMAP(type, XK_equal, GHOST_kKeyEqual);
1917 GXMAP(type, XK_bracketleft, GHOST_kKeyLeftBracket);
1918 GXMAP(type, XK_bracketright, GHOST_kKeyRightBracket);
1919 GXMAP(type, XK_Pause, GHOST_kKeyPause);
1920
1921 GXMAP(type, XK_Shift_L, GHOST_kKeyLeftShift);
1922 GXMAP(type, XK_Shift_R, GHOST_kKeyRightShift);
1923 GXMAP(type, XK_Control_L, GHOST_kKeyLeftControl);
1924 GXMAP(type, XK_Control_R, GHOST_kKeyRightControl);
1925 GXMAP(type, XK_Alt_L, GHOST_kKeyLeftAlt);
1926 GXMAP(type, XK_Alt_R, GHOST_kKeyRightAlt);
1927 GXMAP(type, XK_Super_L, GHOST_kKeyLeftOS);
1928 GXMAP(type, XK_Super_R, GHOST_kKeyRightOS);
1929 GXMAP(type, XK_Hyper_L, GHOST_kKeyLeftHyper);
1930 GXMAP(type, XK_Hyper_R, GHOST_kKeyRightHyper);
1931
1932 GXMAP(type, XK_Insert, GHOST_kKeyInsert);
1933 GXMAP(type, XK_Delete, GHOST_kKeyDelete);
1934 GXMAP(type, XK_Home, GHOST_kKeyHome);
1935 GXMAP(type, XK_End, GHOST_kKeyEnd);
1936 GXMAP(type, XK_Page_Up, GHOST_kKeyUpPage);
1937 GXMAP(type, XK_Page_Down, GHOST_kKeyDownPage);
1938
1939 GXMAP(type, XK_Left, GHOST_kKeyLeftArrow);
1940 GXMAP(type, XK_Right, GHOST_kKeyRightArrow);
1941 GXMAP(type, XK_Up, GHOST_kKeyUpArrow);
1942 GXMAP(type, XK_Down, GHOST_kKeyDownArrow);
1943
1944 GXMAP(type, XK_Caps_Lock, GHOST_kKeyCapsLock);
1945 GXMAP(type, XK_Scroll_Lock, GHOST_kKeyScrollLock);
1946 GXMAP(type, XK_Num_Lock, GHOST_kKeyNumLock);
1947 GXMAP(type, XK_Menu, GHOST_kKeyApp);
1948
1949 /* keypad events */
1950
1951 GXMAP(type, XK_KP_0, GHOST_kKeyNumpad0);
1952 GXMAP(type, XK_KP_1, GHOST_kKeyNumpad1);
1953 GXMAP(type, XK_KP_2, GHOST_kKeyNumpad2);
1954 GXMAP(type, XK_KP_3, GHOST_kKeyNumpad3);
1955 GXMAP(type, XK_KP_4, GHOST_kKeyNumpad4);
1956 GXMAP(type, XK_KP_5, GHOST_kKeyNumpad5);
1957 GXMAP(type, XK_KP_6, GHOST_kKeyNumpad6);
1958 GXMAP(type, XK_KP_7, GHOST_kKeyNumpad7);
1959 GXMAP(type, XK_KP_8, GHOST_kKeyNumpad8);
1960 GXMAP(type, XK_KP_9, GHOST_kKeyNumpad9);
1961 GXMAP(type, XK_KP_Decimal, GHOST_kKeyNumpadPeriod);
1962
1963 GXMAP(type, XK_KP_Insert, GHOST_kKeyNumpad0);
1964 GXMAP(type, XK_KP_End, GHOST_kKeyNumpad1);
1965 GXMAP(type, XK_KP_Down, GHOST_kKeyNumpad2);
1966 GXMAP(type, XK_KP_Page_Down, GHOST_kKeyNumpad3);
1967 GXMAP(type, XK_KP_Left, GHOST_kKeyNumpad4);
1968 GXMAP(type, XK_KP_Begin, GHOST_kKeyNumpad5);
1969 GXMAP(type, XK_KP_Right, GHOST_kKeyNumpad6);
1970 GXMAP(type, XK_KP_Home, GHOST_kKeyNumpad7);
1971 GXMAP(type, XK_KP_Up, GHOST_kKeyNumpad8);
1972 GXMAP(type, XK_KP_Page_Up, GHOST_kKeyNumpad9);
1973 GXMAP(type, XK_KP_Delete, GHOST_kKeyNumpadPeriod);
1974
1975 GXMAP(type, XK_KP_Enter, GHOST_kKeyNumpadEnter);
1976 GXMAP(type, XK_KP_Add, GHOST_kKeyNumpadPlus);
1977 GXMAP(type, XK_KP_Subtract, GHOST_kKeyNumpadMinus);
1978 GXMAP(type, XK_KP_Multiply, GHOST_kKeyNumpadAsterisk);
1979 GXMAP(type, XK_KP_Divide, GHOST_kKeyNumpadSlash);
1980
1981 /* Media keys in some keyboards and laptops with XFree86/XORG. */
1982#ifdef WITH_XF86KEYSYM
1983 GXMAP(type, XF86XK_AudioPlay, GHOST_kKeyMediaPlay);
1984 GXMAP(type, XF86XK_AudioStop, GHOST_kKeyMediaStop);
1985 GXMAP(type, XF86XK_AudioPrev, GHOST_kKeyMediaFirst);
1986 GXMAP(type, XF86XK_AudioRewind, GHOST_kKeyMediaFirst);
1987 GXMAP(type, XF86XK_AudioNext, GHOST_kKeyMediaLast);
1988# ifdef XF86XK_AudioForward /* Debian lenny's XF86keysym.h has no XF86XK_AudioForward define */
1989 GXMAP(type, XF86XK_AudioForward, GHOST_kKeyMediaLast);
1990# endif
1991#endif
1992 default:
1993#ifdef WITH_GHOST_DEBUG
1994 printf("%s: unknown key: %lu / 0x%lx\n", __func__, key, key);
1995#endif
1996 type = GHOST_kKeyUnknown;
1997 break;
1998 }
1999 }
2000
2001 return type;
2002}
2003
2004#undef GXMAP
2005
2006#define MAKE_ID(a, b, c, d) (int(d) << 24 | int(c) << 16 | (b) << 8 | (a))
2007
2008static GHOST_TKey ghost_key_from_keycode(const XkbDescPtr xkb_descr, const KeyCode keycode)
2009{
2010 GHOST_ASSERT(XkbKeyNameLength == 4, "Name length is invalid!");
2011 if (keycode >= xkb_descr->min_key_code && keycode <= xkb_descr->max_key_code) {
2012 const char *id_str = xkb_descr->names->keys[keycode].name;
2013 const uint32_t id = MAKE_ID(id_str[0], id_str[1], id_str[2], id_str[3]);
2014 switch (id) {
2015 case MAKE_ID('T', 'L', 'D', 'E'):
2016 return GHOST_kKeyAccentGrave;
2017 case MAKE_ID('L', 'S', 'G', 'T'):
2018 return GHOST_kKeyGrLess;
2019#ifdef WITH_GHOST_DEBUG
2020 default:
2021 printf("%s unhandled keycode: %.*s\n", __func__, XkbKeyNameLength, id_str);
2022 break;
2023#endif
2024 }
2025 }
2026 else if (keycode != 0) {
2027 GHOST_ASSERT(false, "KeyCode out of range!");
2028 }
2029 return GHOST_kKeyUnknown;
2030}
2031
2032#undef MAKE_ID
2033
2034/* From `xclip.c` #xcout() v0.11. */
2035
2036#define XCLIB_XCOUT_NONE 0 /* no context */
2037#define XCLIB_XCOUT_SENTCONVSEL 1 /* sent a request */
2038#define XCLIB_XCOUT_INCR 2 /* in an incr loop */
2039#define XCLIB_XCOUT_FALLBACK 3 /* STRING failed, need fallback to UTF8 */
2040#define XCLIB_XCOUT_FALLBACK_UTF8 4 /* UTF8 failed, move to compound. */
2041#define XCLIB_XCOUT_FALLBACK_COMP 5 /* compound failed, move to text. */
2042#define XCLIB_XCOUT_FALLBACK_TEXT 6
2043
2044/* Retrieves the contents of a selections. */
2046 const XEvent *evt, Atom sel, Atom target, uchar **txt, ulong *len, uint *context) const
2047{
2048 Atom pty_type;
2049 int pty_format;
2050 uchar *buffer;
2051 ulong pty_size, pty_items;
2052 uchar *ltxt = *txt;
2053
2054 const vector<GHOST_IWindow *> &win_vec = window_manager_->getWindows();
2055 vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
2056 GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
2057 Window win = window->getXWindow();
2058
2059 switch (*context) {
2060 /* There is no context, do an XConvertSelection() */
2061 case XCLIB_XCOUT_NONE:
2062 /* Initialize return length to 0. */
2063 if (*len > 0) {
2064 free(*txt);
2065 *len = 0;
2066 }
2067
2068 /* Send a selection request */
2069 XConvertSelection(display_, sel, target, atom_.XCLIP_OUT, win, CurrentTime);
2070 *context = XCLIB_XCOUT_SENTCONVSEL;
2071 return;
2072
2074 if (evt->type != SelectionNotify) {
2075 return;
2076 }
2077
2078 if (target == atom_.UTF8_STRING && evt->xselection.property == None) {
2079 *context = XCLIB_XCOUT_FALLBACK_UTF8;
2080 return;
2081 }
2082 if (target == atom_.COMPOUND_TEXT && evt->xselection.property == None) {
2083 *context = XCLIB_XCOUT_FALLBACK_COMP;
2084 return;
2085 }
2086 if (target == atom_.TEXT && evt->xselection.property == None) {
2087 *context = XCLIB_XCOUT_FALLBACK_TEXT;
2088 return;
2089 }
2090
2091 /* find the size and format of the data in property */
2092 XGetWindowProperty(display_,
2093 win,
2094 atom_.XCLIP_OUT,
2095 0,
2096 0,
2097 False,
2098 AnyPropertyType,
2099 &pty_type,
2100 &pty_format,
2101 &pty_items,
2102 &pty_size,
2103 &buffer);
2104 XFree(buffer);
2105
2106 if (pty_type == atom_.INCR) {
2107 /* start INCR mechanism by deleting property */
2108 XDeleteProperty(display_, win, atom_.XCLIP_OUT);
2109 XFlush(display_);
2110 *context = XCLIB_XCOUT_INCR;
2111 return;
2112 }
2113
2114 /* If it's not INCR, and not `format == 8`, then there's
2115 * nothing in the selection (that `xclip` understands, anyway). */
2116
2117 if (pty_format != 8) {
2118 *context = XCLIB_XCOUT_NONE;
2119 return;
2120 }
2121
2122 /* Not using INCR mechanism, just read the property. */
2123 XGetWindowProperty(display_,
2124 win,
2125 atom_.XCLIP_OUT,
2126 0,
2127 long(pty_size),
2128 False,
2129 AnyPropertyType,
2130 &pty_type,
2131 &pty_format,
2132 &pty_items,
2133 &pty_size,
2134 &buffer);
2135
2136 /* finished with property, delete it */
2137 XDeleteProperty(display_, win, atom_.XCLIP_OUT);
2138
2139 /* copy the buffer to the pointer for returned data */
2140 ltxt = (uchar *)malloc(pty_items);
2141 memcpy(ltxt, buffer, pty_items);
2142
2143 /* set the length of the returned data */
2144 *len = pty_items;
2145 *txt = ltxt;
2146
2147 /* free the buffer */
2148 XFree(buffer);
2149
2150 *context = XCLIB_XCOUT_NONE;
2151
2152 /* complete contents of selection fetched, return 1 */
2153 return;
2154
2155 case XCLIB_XCOUT_INCR:
2156 /* To use the INCR method, we basically delete the
2157 * property with the selection in it, wait for an
2158 * event indicating that the property has been created,
2159 * then read it, delete it, etc. */
2160
2161 /* make sure that the event is relevant */
2162 if (evt->type != PropertyNotify) {
2163 return;
2164 }
2165
2166 /* skip unless the property has a new value */
2167 if (evt->xproperty.state != PropertyNewValue) {
2168 return;
2169 }
2170
2171 /* check size and format of the property */
2172 XGetWindowProperty(display_,
2173 win,
2174 atom_.XCLIP_OUT,
2175 0,
2176 0,
2177 False,
2178 AnyPropertyType,
2179 &pty_type,
2180 &pty_format,
2181 &pty_items,
2182 &pty_size,
2183 &buffer);
2184
2185 if (pty_format != 8) {
2186 /* property does not contain text, delete it
2187 * to tell the other X client that we have read
2188 * it and to send the next property */
2189 XFree(buffer);
2190 XDeleteProperty(display_, win, atom_.XCLIP_OUT);
2191 return;
2192 }
2193
2194 if (pty_size == 0) {
2195 /* no more data, exit from loop */
2196 XFree(buffer);
2197 XDeleteProperty(display_, win, atom_.XCLIP_OUT);
2198 *context = XCLIB_XCOUT_NONE;
2199
2200 /* this means that an INCR transfer is now
2201 * complete, return 1 */
2202 return;
2203 }
2204
2205 XFree(buffer);
2206
2207 /* if we have come this far, the property contains
2208 * text, we know the size. */
2209 XGetWindowProperty(display_,
2210 win,
2211 atom_.XCLIP_OUT,
2212 0,
2213 long(pty_size),
2214 False,
2215 AnyPropertyType,
2216 &pty_type,
2217 &pty_format,
2218 &pty_items,
2219 &pty_size,
2220 &buffer);
2221
2222 /* allocate memory to accommodate data in *txt */
2223 if (*len == 0) {
2224 *len = pty_items;
2225 ltxt = (uchar *)malloc(*len);
2226 }
2227 else {
2228 *len += pty_items;
2229 ltxt = (uchar *)realloc(ltxt, *len);
2230 }
2231
2232 /* add data to ltxt */
2233 memcpy(&ltxt[*len - pty_items], buffer, pty_items);
2234
2235 *txt = ltxt;
2236 XFree(buffer);
2237
2238 /* delete property to get the next item */
2239 XDeleteProperty(display_, win, atom_.XCLIP_OUT);
2240 XFlush(display_);
2241 return;
2242 }
2243}
2244
2245char *GHOST_SystemX11::getClipboard(bool selection) const
2246{
2247 Atom sseln;
2248 Atom target = atom_.UTF8_STRING;
2249 Window owner;
2250
2251 /* From `xclip.c` `doOut()` v0.11. */
2252 char *sel_buf;
2253 ulong sel_len = 0;
2254 XEvent evt;
2255 uint context = XCLIB_XCOUT_NONE;
2256
2257 if (selection == True) {
2258 sseln = atom_.PRIMARY;
2259 }
2260 else {
2261 sseln = atom_.CLIPBOARD;
2262 }
2263
2264 const vector<GHOST_IWindow *> &win_vec = window_manager_->getWindows();
2265 vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
2266 GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
2267 Window win = window->getXWindow();
2268
2269 /* check if we are the owner. */
2270 owner = XGetSelectionOwner(display_, sseln);
2271 if (owner == win) {
2272 if (sseln == atom_.CLIPBOARD) {
2273 size_t sel_buf_size = strlen(txt_cut_buffer) + 1;
2274 sel_buf = (char *)malloc(sel_buf_size);
2275 memcpy(sel_buf, txt_cut_buffer, sel_buf_size);
2276 return sel_buf;
2277 }
2278 size_t sel_buf_size = strlen(txt_select_buffer) + 1;
2279 sel_buf = (char *)malloc(sel_buf_size);
2280 memcpy(sel_buf, txt_select_buffer, sel_buf_size);
2281 return sel_buf;
2282 }
2283 if (owner == None) {
2284 return nullptr;
2285 }
2286
2287 /* Restore events so copy doesn't swallow other event types (keyboard/mouse). */
2288 vector<XEvent> restore_events;
2289
2290 while (true) {
2291 /* only get an event if xcout() is doing something */
2292 bool restore_this_event = false;
2293 if (context != XCLIB_XCOUT_NONE) {
2294 XNextEvent(display_, &evt);
2295 restore_this_event = (evt.type != SelectionNotify);
2296 }
2297
2298 /* fetch the selection, or part of it */
2299 getClipboard_xcout(&evt, sseln, target, (uchar **)&sel_buf, &sel_len, &context);
2300
2301 if (restore_this_event) {
2302 restore_events.push_back(evt);
2303 }
2304
2305 /* Fallback is needed. Set #XA_STRING to target and restart the loop. */
2306 if (context == XCLIB_XCOUT_FALLBACK) {
2307 context = XCLIB_XCOUT_NONE;
2308 target = atom_.STRING;
2309 continue;
2310 }
2311 if (context == XCLIB_XCOUT_FALLBACK_UTF8) {
2312 /* utf8 fail, move to compound text. */
2313 context = XCLIB_XCOUT_NONE;
2314 target = atom_.COMPOUND_TEXT;
2315 continue;
2316 }
2317 if (context == XCLIB_XCOUT_FALLBACK_COMP) {
2318 /* Compound text fail, move to text. */
2319 context = XCLIB_XCOUT_NONE;
2320 target = atom_.TEXT;
2321 continue;
2322 }
2323 if (context == XCLIB_XCOUT_FALLBACK_TEXT) {
2324 /* Text fail, nothing else to try, break. */
2325 context = XCLIB_XCOUT_NONE;
2326 }
2327
2328 /* Only continue if #xcout() is doing something. */
2329 if (context == XCLIB_XCOUT_NONE) {
2330 break;
2331 }
2332 }
2333
2334 while (!restore_events.empty()) {
2335 XPutBackEvent(display_, &restore_events.back());
2336 restore_events.pop_back();
2337 }
2338
2339 if (sel_len) {
2340 /* Only print the buffer out, and free it, if it's not empty. */
2341 char *tmp_data = (char *)malloc(sel_len + 1);
2342 memcpy(tmp_data, (char *)sel_buf, sel_len);
2343 tmp_data[sel_len] = '\0';
2344
2345 if (sseln == atom_.STRING) {
2346 XFree(sel_buf);
2347 }
2348 else {
2349 free(sel_buf);
2350 }
2351
2352 return tmp_data;
2353 }
2354 return nullptr;
2355}
2356
2357void GHOST_SystemX11::putClipboard(const char *buffer, bool selection) const
2358{
2359 Window window_, owner;
2360
2361 const vector<GHOST_IWindow *> &win_vec = window_manager_->getWindows();
2362 vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
2363 GHOST_WindowX11 *window = static_cast<GHOST_WindowX11 *>(*win_it);
2364 window_ = window->getXWindow();
2365
2366 if (buffer) {
2367 if (selection == False) {
2368 XSetSelectionOwner(display_, atom_.CLIPBOARD, window_, CurrentTime);
2369 owner = XGetSelectionOwner(display_, atom_.CLIPBOARD);
2370 if (txt_cut_buffer) {
2371 free((void *)txt_cut_buffer);
2372 }
2373
2374 size_t buffer_size = strlen(buffer) + 1;
2375 txt_cut_buffer = (char *)malloc(buffer_size);
2376 memcpy(txt_cut_buffer, buffer, buffer_size);
2377 }
2378 else {
2379 XSetSelectionOwner(display_, atom_.PRIMARY, window_, CurrentTime);
2380 owner = XGetSelectionOwner(display_, atom_.PRIMARY);
2381 if (txt_select_buffer) {
2382 free((void *)txt_select_buffer);
2383 }
2384
2385 size_t buffer_size = strlen(buffer) + 1;
2386 txt_select_buffer = (char *)malloc(buffer_size);
2387 memcpy(txt_select_buffer, buffer, buffer_size);
2388 }
2389
2390 if (owner != window_) {
2391 fprintf(stderr, "failed to own primary\n");
2392 }
2393 }
2394}
2395
2396/* -------------------------------------------------------------------- */
2399
2401 public:
2402 /* Width of the dialog. */
2403 uint width;
2404 /* Height of the dialog. */
2406 /* Default padding (x direction) between controls and edge of dialog. */
2408 /* Default padding (y direction) between controls and edge of dialog. */
2410 /* Width of a single button. */
2412 /* Height of a single button. */
2414 /* Inset of a button to its text. */
2416 /* Size of the border of the button. */
2418 /* Height of a line of text */
2420 /* Offset of the text inside the button. */
2422
2423 /* Construct a new #DialogData with the default settings. */
2425 : width(640),
2426 height(175),
2427 padding_x(10),
2428 padding_y(5),
2429 button_width(130),
2430 button_height(24),
2431 button_inset_x(10),
2433 line_height(16)
2434 {
2436 }
2437
2438 void drawButton(Display *display,
2439 Window &window,
2440 GC &borderGC,
2441 GC &buttonGC,
2442 uint button_num,
2443 const char *label)
2444 {
2445 XFillRectangle(display,
2446 window,
2447 borderGC,
2448 width - (padding_x + button_width) * button_num,
2452
2453 XFillRectangle(display,
2454 window,
2455 buttonGC,
2456 width - (padding_x + button_width) * button_num + button_border_size,
2460
2461 XDrawString(display,
2462 window,
2463 borderGC,
2464 width - (padding_x + button_width) * button_num + button_inset_x,
2466 label,
2467 strlen(label));
2468 }
2469
2470 /* Is the mouse inside the given button */
2471 bool isInsideButton(const XEvent &e, uint button_num) const
2472 {
2473 return (
2474 (e.xmotion.y > int(height - padding_y - button_height)) &&
2475 (e.xmotion.y < int(height - padding_y)) &&
2476 (e.xmotion.x > int(width - (padding_x + button_width) * button_num)) &&
2477 (e.xmotion.x < int(width - padding_x - (padding_x + button_width) * (button_num - 1))));
2478 }
2479};
2480
2481static void split(const char *text, const char *seps, char ***str, int *count)
2482{
2483 const char *tok;
2484 char *data;
2485 int i;
2486 *count = 0;
2487
2488 data = strdup(text);
2489 for (tok = strtok(data, seps); tok != nullptr; tok = strtok(nullptr, seps)) {
2490 (*count)++;
2491 }
2492 free(data);
2493
2494 data = strdup(text);
2495 *str = (char **)malloc(size_t(*count) * sizeof(char *));
2496 for (i = 0, tok = strtok(data, seps); tok != nullptr; tok = strtok(nullptr, seps), i++) {
2497 (*str)[i] = strdup(tok);
2498 }
2499 free(data);
2500}
2501
2503 const char *message,
2504 const char *help_label,
2505 const char *continue_label,
2506 const char *link,
2507 GHOST_DialogOptions /*dialog_options*/) const
2508{
2509 char **text_splitted = nullptr;
2510 int textLines = 0;
2511 split(message, "\n", &text_splitted, &textLines);
2512
2513 DialogData dialog_data;
2514 XSizeHints hints;
2515
2516 Window window;
2517 XEvent e;
2518 int screen = DefaultScreen(display_);
2519 window = XCreateSimpleWindow(display_,
2520 RootWindow(display_, screen),
2521 0,
2522 0,
2523 dialog_data.width,
2524 dialog_data.height,
2525 1,
2526 BlackPixel(display_, screen),
2527 WhitePixel(display_, screen));
2528
2529 /* Window Should not be resizable */
2530 {
2531 hints.flags = PSize | PMinSize | PMaxSize;
2532 hints.min_width = hints.max_width = hints.base_width = dialog_data.width;
2533 hints.min_height = hints.max_height = hints.base_height = dialog_data.height;
2534 XSetWMNormalHints(display_, window, &hints);
2535 }
2536
2537 /* Set title */
2538 {
2539 Atom wm_Name = XInternAtom(display_, "_NET_WM_NAME", False);
2540 Atom utf8Str = XInternAtom(display_, "UTF8_STRING", False);
2541
2542 Atom winType = XInternAtom(display_, "_NET_WM_WINDOW_TYPE", False);
2543 Atom typeDialog = XInternAtom(display_, "_NET_WM_WINDOW_TYPE_DIALOG", False);
2544
2545 XChangeProperty(display_,
2546 window,
2547 wm_Name,
2548 utf8Str,
2549 8,
2550 PropModeReplace,
2551 (const uchar *)title,
2552 int(strlen(title)));
2553
2554 XChangeProperty(
2555 display_, window, winType, XA_ATOM, 32, PropModeReplace, (uchar *)&typeDialog, 1);
2556 }
2557
2558 /* Create buttons GC */
2559 XGCValues buttonBorderGCValues;
2560 buttonBorderGCValues.foreground = BlackPixel(display_, screen);
2561 buttonBorderGCValues.background = WhitePixel(display_, screen);
2562 XGCValues buttonGCValues;
2563 buttonGCValues.foreground = WhitePixel(display_, screen);
2564 buttonGCValues.background = BlackPixel(display_, screen);
2565
2566 GC buttonBorderGC = XCreateGC(display_, window, GCForeground, &buttonBorderGCValues);
2567 GC buttonGC = XCreateGC(display_, window, GCForeground, &buttonGCValues);
2568
2569 XSelectInput(display_, window, ExposureMask | ButtonPressMask | ButtonReleaseMask);
2570 XMapWindow(display_, window);
2571
2572 const bool has_link = link && strlen(link);
2573
2574 while (true) {
2575 XNextEvent(display_, &e);
2576 if (e.type == Expose) {
2577 for (int i = 0; i < textLines; i++) {
2578 XDrawString(display_,
2579 window,
2580 DefaultGC(display_, screen),
2581 dialog_data.padding_x,
2582 dialog_data.padding_x + (i + 1) * dialog_data.line_height,
2583 text_splitted[i],
2584 int(strlen(text_splitted[i])));
2585 }
2586 dialog_data.drawButton(display_, window, buttonBorderGC, buttonGC, 1, continue_label);
2587 if (has_link) {
2588 dialog_data.drawButton(display_, window, buttonBorderGC, buttonGC, 2, help_label);
2589 }
2590 }
2591 else if (e.type == ButtonRelease) {
2592 if (dialog_data.isInsideButton(e, 1)) {
2593 break;
2594 }
2595 if (dialog_data.isInsideButton(e, 2)) {
2596 if (has_link) {
2597 string cmd = "xdg-open \"" + string(link) + "\"";
2598 if (system(cmd.c_str()) != 0) {
2599 GHOST_PRINTF("GHOST_SystemX11::showMessageBox: Unable to run system command [%s]",
2600 cmd.c_str());
2601 }
2602 }
2603 break;
2604 }
2605 }
2606 }
2607
2608 for (int i = 0; i < textLines; i++) {
2609 free(text_splitted[i]);
2610 }
2611 free(text_splitted);
2612
2613 XDestroyWindow(display_, window);
2614 XFreeGC(display_, buttonBorderGC);
2615 XFreeGC(display_, buttonGC);
2616 return GHOST_kSuccess;
2617}
2618
2620
2621#ifdef WITH_XDND
2622GHOST_TSuccess GHOST_SystemX11::pushDragDropEvent(GHOST_TEventType eventType,
2623 GHOST_TDragnDropTypes draggedObjectType,
2624 GHOST_IWindow *window,
2625 int mouseX,
2626 int mouseY,
2627 void *data)
2628{
2629 GHOST_SystemX11 *system = ((GHOST_SystemX11 *)getSystem());
2630
2631 /* Caller has no timestamp. */
2632 const uint64_t event_ms = system->getMilliSeconds();
2633
2634 return system->pushEvent(std::make_unique<GHOST_EventDragnDrop>(
2635 event_ms, eventType, draggedObjectType, window, mouseX, mouseY, data));
2636}
2637#endif
2645int GHOST_X11_ApplicationErrorHandler(Display *display, XErrorEvent *event)
2646{
2648 if (!system->isDebugEnabled()) {
2649 return 0;
2650 }
2651
2652 char error_code_str[512];
2653
2654 XGetErrorText(display, event->error_code, error_code_str, sizeof(error_code_str));
2655
2656 fprintf(stderr,
2657 "Received X11 Error:\n"
2658 "\terror code: %d\n"
2659 "\trequest code: %d\n"
2660 "\tminor code: %d\n"
2661 "\terror text: %s\n",
2662 event->error_code,
2663 event->request_code,
2664 event->minor_code,
2665 error_code_str);
2666
2667 /* No exit! - but keep lint happy */
2668 return 0;
2669}
2670
2672{
2674 if (!system->isDebugEnabled()) {
2675 return 0;
2676 }
2677
2678 fprintf(stderr, "Ignoring Xlib error: error IO\n");
2679
2680 /* No exit! - but keep lint happy */
2681 return 0;
2682}
2683
2684#ifdef WITH_X11_XINPUT
2685
2686static bool is_filler_char(char c)
2687{
2688 return isspace(c) || ELEM(c, '_', '-', ';', ':');
2689}
2690
2691/* These C functions are copied from Wine 3.12's `wintab.c` */
2692static bool match_token(const char *haystack, const char *needle)
2693{
2694 const char *h, *n;
2695 for (h = haystack; *h;) {
2696 while (*h && is_filler_char(*h)) {
2697 h++;
2698 }
2699 if (!*h) {
2700 break;
2701 }
2702
2703 for (n = needle; *n && *h && tolower(*h) == tolower(*n); n++) {
2704 h++;
2705 }
2706 if (!*n && (is_filler_char(*h) || !*h)) {
2707 return true;
2708 }
2709
2710 while (*h && !is_filler_char(*h)) {
2711 h++;
2712 }
2713 }
2714 return false;
2715}
2716
2717/* Determining if an X device is a Tablet style device is an imperfect science.
2718 * We rely on common conventions around device names as well as the type reported
2719 * by WACOM tablets. This code will likely need to be expanded for alternate tablet types
2720 *
2721 * WINTAB refers to any device that interacts with the tablet as a cursor,
2722 * (stylus, eraser, tablet mouse, airbrush, etc)
2723 * this is not to be confused with WACOM X11 configuration "cursor" device.
2724 * WACOM tablets X11 configuration "cursor" refers to its device slot (which we mirror with
2725 * our `gSysCursors`) for puck like devices (tablet mice essentially).
2726 */
2727static GHOST_TTabletMode tablet_mode_from_name(const char *name, const char *type)
2728{
2729 int i;
2730 static const char *tablet_stylus_whitelist[] = {"stylus", "wizardpen", "acecad", "pen", nullptr};
2731
2732 static const char *type_blacklist[] = {"pad", "cursor", "touch", nullptr};
2733
2734 /* Skip some known unsupported types. */
2735 for (i = 0; type_blacklist[i] != nullptr; i++) {
2736 if (type && (strcasecmp(type, type_blacklist[i]) == 0)) {
2737 return GHOST_kTabletModeNone;
2738 }
2739 }
2740
2741 /* First check device type to avoid cases where name is "Pen and Eraser" and type is "ERASER" */
2742 for (i = 0; tablet_stylus_whitelist[i] != nullptr; i++) {
2743 if (type && match_token(type, tablet_stylus_whitelist[i])) {
2745 }
2746 }
2747 if (type && match_token(type, "eraser")) {
2749 }
2750 for (i = 0; tablet_stylus_whitelist[i] != nullptr; i++) {
2751 if (name && match_token(name, tablet_stylus_whitelist[i])) {
2753 }
2754 }
2755 if (name && match_token(name, "eraser")) {
2757 }
2758
2759 return GHOST_kTabletModeNone;
2760}
2761
2762/* End code copied from Wine. */
2763
2764void GHOST_SystemX11::refreshXInputDevices()
2765{
2766 if (xinput_version_.present) {
2767 /* Close tablet devices. */
2768 clearXInputDevices();
2769
2770 /* Install our error handler to override Xlib's termination behavior */
2771 GHOST_X11_ERROR_HANDLERS_OVERRIDE(handler_store);
2772
2773 {
2774 int device_count;
2775 XDeviceInfo *device_info = XListInputDevices(display_, &device_count);
2776
2777 for (int i = 0; i < device_count; ++i) {
2778 char *device_type = device_info[i].type ? XGetAtomName(display_, device_info[i].type) :
2779 nullptr;
2780 GHOST_TTabletMode tablet_mode = tablet_mode_from_name(device_info[i].name, device_type);
2781
2782 // printf("Tablet type:'%s', name:'%s', index:%d\n", device_type, device_info[i].name, i);
2783
2784 if (device_type) {
2785 XFree((void *)device_type);
2786 }
2787
2789 continue;
2790 }
2791
2792 GHOST_TabletX11 xtablet = {tablet_mode};
2793 xtablet.ID = device_info[i].id;
2794 xtablet.Device = XOpenDevice(display_, xtablet.ID);
2795
2796 if (xtablet.Device != nullptr) {
2797 /* Find how many pressure levels tablet has */
2798 XAnyClassPtr ici = device_info[i].inputclassinfo;
2799
2800 if (ici != nullptr) {
2801 for (int j = 0; j < device_info[i].num_classes; ++j) {
2802 if (ici->c_class == ValuatorClass) {
2803 XValuatorInfo *xvi = (XValuatorInfo *)ici;
2804 if (xvi->axes != nullptr) {
2805 xtablet.PressureLevels = xvi->axes[2].max_value;
2806
2807 if (xvi->num_axes > 3) {
2808 /* This is assuming that the tablet has the same tilt resolution in both
2809 * positive and negative directions. It would be rather weird if it didn't. */
2810 xtablet.XtiltLevels = xvi->axes[3].max_value;
2811 xtablet.YtiltLevels = xvi->axes[4].max_value;
2812 }
2813 else {
2814 xtablet.XtiltLevels = 0;
2815 xtablet.YtiltLevels = 0;
2816 }
2817
2818 break;
2819 }
2820 }
2821
2822 ici = (XAnyClassPtr)(((char *)ici) + ici->length);
2823 }
2824 }
2825
2826 xtablets_.push_back(xtablet);
2827 }
2828 }
2829
2830 XFreeDeviceList(device_info);
2831 }
2832
2833 GHOST_X11_ERROR_HANDLERS_RESTORE(handler_store);
2834 }
2835}
2836
2837void GHOST_SystemX11::clearXInputDevices()
2838{
2839 for (GHOST_TabletX11 &xtablet : xtablets_) {
2840 if (xtablet.Device) {
2841 XCloseDevice(display_, xtablet.Device);
2842 }
2843 }
2844
2845 xtablets_.clear();
2846}
2847
2848#endif /* WITH_X11_XINPUT */
#define UINT32_MAX
#define GHOST_OPENGL_GLX_RESET_NOTIFICATION_STRATEGY
#define GHOST_OPENGL_GLX_CONTEXT_FLAGS
#define Window
#define Display
#define GHOST_PRINTF(x,...)
#define GHOST_ASSERT(x, info)
#define GHOST_PRINT(x)
#define GXMAP(k, x, y)
#define pushEvent
static char * txt_select_buffer
static Bool init_timestamp_scanner(Display *, XEvent *event, XPointer arg)
static void split(const char *text, const char *seps, char ***str, int *count)
int GHOST_X11_ApplicationErrorHandler(Display *display, XErrorEvent *event)
#define XCLIB_XCOUT_INCR
#define XCLIB_XCOUT_FALLBACK_UTF8
static char * txt_cut_buffer
#define XCLIB_XCOUT_FALLBACK
#define GHOST_INTERN_ATOM(atom)
static void SleepTillEvent(Display *display, int64_t maxSleep)
#define XCLIB_XCOUT_FALLBACK_COMP
static uchar bit_is_on(const uchar *ptr, int bit)
static GHOST_TKey ghost_key_from_keysym_or_keycode(const KeySym key_sym, const XkbDescPtr xkb_descr, const KeyCode keycode)
#define XCLIB_XCOUT_SENTCONVSEL
#define XCLIB_XCOUT_FALLBACK_TEXT
static GHOST_TKey ghost_key_from_keycode(const XkbDescPtr xkb_descr, const KeyCode keycode)
int GHOST_X11_ApplicationIOErrorHandler(Display *)
#define XCLIB_XCOUT_NONE
static GHOST_TSuccess getCursorPosition_impl(Display *display, int32_t &x, int32_t &y, Window *child_return)
#define GHOST_INTERN_ATOM_IF_EXISTS(atom)
static GHOST_TKey ghost_key_from_keysym(const KeySym key)
int GHOST_X11_ApplicationErrorHandler(Display *display, XErrorEvent *event)
#define GHOST_X11_ERROR_HANDLERS_OVERRIDE(var)
int GHOST_X11_ApplicationIOErrorHandler(Display *display)
#define GHOST_X11_ERROR_HANDLERS_RESTORE(var)
@ GHOST_kEventWheelAxisVertical
GHOST_TWindowState
GHOST_TEventType
@ GHOST_kEventWindowClose
@ GHOST_kEventWindowSize
@ GHOST_kEventCursorMove
@ GHOST_kEventButtonUp
@ GHOST_kEventWindowActivate
@ GHOST_kEventWindowUpdate
@ GHOST_kEventWindowDeactivate
@ GHOST_kEventButtonDown
@ GHOST_kEventKeyDown
@ GHOST_kEventKeyUp
GHOST_TTabletMode
@ GHOST_kTabletModeEraser
@ GHOST_kTabletModeStylus
@ GHOST_kTabletModeNone
GHOST_TCapabilityFlag
@ GHOST_kCapabilityCursorRGBA
@ GHOST_kCapabilityInputIME
@ GHOST_kCapabilityCursorGenerator
@ GHOST_kCapabilityWindowPath
@ GHOST_kCapabilityClipboardImage
@ GHOST_kCapabilityWindowDecorationStyles
#define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings)
GHOST_TAxisFlag
@ GHOST_kAxisX
@ GHOST_kAxisY
@ GHOST_kAxisNone
#define GHOST_CAPABILITY_FLAG_ALL
GHOST_TKey
@ GHOST_kKeyLeftOS
@ GHOST_kKeyInsert
@ GHOST_kKeySemicolon
@ GHOST_kKey5
@ GHOST_kKeyMediaPlay
@ GHOST_kKeyQuote
@ GHOST_kKey4
@ GHOST_kKeyNumpad3
@ GHOST_kKeyAccentGrave
@ GHOST_kKeyNumpad1
@ GHOST_kKeyLeftAlt
@ GHOST_kKey3
@ GHOST_kKeyRightShift
@ GHOST_kKeyNumLock
@ GHOST_kKeyEnter
@ GHOST_kKeyNumpadSlash
@ GHOST_kKeyRightArrow
@ GHOST_kKeyNumpad4
@ GHOST_kKeyPause
@ GHOST_kKeyCapsLock
@ GHOST_kKeyApp
@ GHOST_kKeyMinus
@ GHOST_kKey6
@ GHOST_kKeyMediaStop
@ GHOST_kKeyBackSpace
@ GHOST_kKey0
@ GHOST_kKeyDownPage
@ GHOST_kKeyGrLess
@ GHOST_kKeyDownArrow
@ GHOST_kKeyRightOS
@ GHOST_kKeyNumpadPeriod
@ GHOST_kKeyF1
@ GHOST_kKeyNumpadAsterisk
@ GHOST_kKeyLeftControl
@ GHOST_kKeyLeftBracket
@ GHOST_kKey1
@ GHOST_kKeyTab
@ GHOST_kKey8
@ GHOST_kKeyComma
@ GHOST_kKeyRightBracket
@ GHOST_kKeyBackslash
@ GHOST_kKeyLinefeed
@ GHOST_kKeyNumpad2
@ GHOST_kKeyLeftHyper
@ GHOST_kKeyRightAlt
@ GHOST_kKeyPeriod
@ GHOST_kKeyNumpadPlus
@ GHOST_kKeyUpPage
@ GHOST_kKey9
@ GHOST_kKeyNumpad5
@ GHOST_kKeyLeftArrow
@ GHOST_kKeyEqual
@ GHOST_kKey7
@ GHOST_kKeyHome
@ GHOST_kKeyNumpad6
@ GHOST_kKeyNumpad8
@ GHOST_kKeyNumpad9
@ GHOST_kKeyEnd
@ GHOST_kKeyUpArrow
@ GHOST_kKeyDelete
@ GHOST_kKeyNumpad0
@ GHOST_kKeyA
@ GHOST_kKey2
@ GHOST_kKeyMediaFirst
@ GHOST_kKeyNumpad7
@ GHOST_kKeyRightControl
@ GHOST_kKeyEsc
@ GHOST_kKeyPlus
@ GHOST_kKeyUnknown
@ GHOST_kKeyScrollLock
@ GHOST_kKeySlash
@ GHOST_kKeyNumpadEnter
@ GHOST_kKeyNumpadMinus
@ GHOST_kKeyRightHyper
@ GHOST_kKeyLeftShift
@ GHOST_kKeyMediaLast
@ GHOST_kKeySpace
@ GHOST_kModifierKeyRightControl
@ GHOST_kModifierKeyLeftControl
@ GHOST_kModifierKeyRightHyper
@ GHOST_kModifierKeyRightAlt
@ GHOST_kModifierKeyRightShift
@ GHOST_kModifierKeyLeftAlt
@ GHOST_kModifierKeyLeftShift
@ GHOST_kModifierKeyLeftOS
@ GHOST_kModifierKeyRightOS
@ GHOST_kModifierKeyLeftHyper
GHOST_TSuccess
@ GHOST_kFailure
@ GHOST_kSuccess
@ GHOST_kFireTimeNever
@ GHOST_kGrabHide
#define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpu_settings)
GHOST_TDragnDropTypes
GHOST_TButton
@ GHOST_kButtonMaskRight
@ GHOST_kButtonMaskButton4
@ GHOST_kButtonMaskLeft
@ GHOST_kButtonMaskButton7
@ GHOST_kButtonMaskButton6
@ GHOST_kButtonMaskButton5
@ GHOST_kButtonMaskMiddle
GHOST_DialogOptions
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
#define MAKE_ID(a, b, c, d)
Definition blendthumb.hh:50
#define ELEM(...)
long long int int64_t
unsigned long long int uint64_t
void drawButton(Display *display, Window &window, GC &borderGC, GC &buttonGC, uint button_num, const char *label)
bool isInsideButton(const XEvent &e, uint button_num) const
GHOST_ContextGLX(const GHOST_ContextParams &context_params, Window window, Display *display, GLXFBConfig fbconfig, int contextProfileMask, int contextMajorVersion, int contextMinorVersion, int contextFlags, int contextResetNotificationStrategy)
GHOST_ContextVK(const GHOST_ContextParams &context_params, GHOST_TVulkanPlatformType platform, Window window, Display *display, wl_surface *wayland_surface, wl_display *wayland_display, const GHOST_ContextVK_WindowInfo *wayland_window_info, int contextMajorVersion, int contextMinorVersion, const GHOST_GPUDevice &preferred_device, const GHOST_WindowHDRInfo *hdr_info_=nullptr)
static GHOST_ISystem * getSystem()
virtual bool isDebugEnabled()=0
GHOST_NDOFManagerUnix(GHOST_System &)
int32_t t_
int32_t r_
virtual void wrapPoint(int32_t &x, int32_t &y, int32_t ofs, GHOST_TAxisFlag axis)
virtual int32_t getHeight() const
int32_t b_
int32_t l_
virtual int32_t getWidth() const
char * getClipboard(bool selection) const override
void putClipboard(const char *buffer, bool selection) const override
void getClipboard_xcout(const XEvent *evt, Atom sel, Atom target, unsigned char **txt, unsigned long *len, unsigned int *context) const
~GHOST_SystemX11() override
GHOST_IWindow * createWindow(const char *title, int32_t left, int32_t top, uint32_t width, uint32_t height, GHOST_TWindowState state, GHOST_GPUSettings gpu_settings, const bool exclusive=false, const bool is_dialog=false, const GHOST_IWindow *parent_window=nullptr) override
GHOST_TSuccess getModifierKeys(GHOST_ModifierKeys &keys) const override
void addDirtyWindow(GHOST_WindowX11 *bad_wind)
struct GHOST_SystemX11::@003156166302234033336315056153017030021063326072 atom_
GHOST_TSuccess getButtons(GHOST_Buttons &buttons) const override
void getAllDisplayDimensions(uint32_t &width, uint32_t &height) const override
GHOST_TSuccess setCursorPosition(int32_t x, int32_t y) override
GHOST_TCapabilityFlag getCapabilities() const override
bool processEvents(bool waitForEvent) override
void getMainDisplayDimensions(uint32_t &width, uint32_t &height) const override
uint8_t getNumDisplays() const override
GHOST_TSuccess disposeContext(GHOST_IContext *context) override
GHOST_IContext * createOffscreenContext(GHOST_GPUSettings gpu_settings) override
uint64_t ms_from_input_time(const Time timestamp) const
GHOST_TSuccess getCursorPosition(int32_t &x, int32_t &y) const override
GHOST_TSuccess init() override
GHOST_TSuccess showMessageBox(const char *title, const char *message, const char *help_label, const char *continue_label, const char *link, GHOST_DialogOptions dialog_options) const override
uint64_t getMilliSeconds() const override
GHOST_TSuccess getPixelAtCursor(float r_color[3]) const override
GHOST_WindowManager * window_manager_
GHOST_TSuccess init() override
GHOST_TimerManager * getTimerManager() const
GHOST_TSuccess pushEvent(std::unique_ptr< const GHOST_IEvent > event)
GHOST_TSuccess exit() override
bool fireTimers(uint64_t time)
GHOST_TSuccess addWindow(GHOST_IWindow *window)
const std::vector< GHOST_IWindow * > & getWindows() const
GHOST_TSuccess setActiveWindow(GHOST_IWindow *window)
void setWindowInactive(const GHOST_IWindow *window)
GHOST_WindowX11(GHOST_SystemX11 *system, Display *display, const char *title, int32_t left, int32_t top, uint32_t width, uint32_t height, GHOST_TWindowState state, GHOST_WindowX11 *parent_window, GHOST_TDrawingContextType type, const bool is_dialog, const GHOST_ContextParams &context_params, const bool exclusive, const GHOST_GPUDevice &preferred_device)
bool getValid() const override
GHOST_TabletData & GetTabletData()
GHOST_TSuccess setState(GHOST_TWindowState state) override
void getClientBounds(GHOST_Rect &bounds) const override
GHOST_TWindowState post_state_
virtual GHOST_TSuccess getCursorGrabBounds(GHOST_Rect &bounds) const
void setCursorGrabAccum(int32_t x, int32_t y)
GHOST_TAxisFlag getCursorGrabAxis() const
GHOST_TGrabCursorMode getCursorGrabMode() const
bool getCursorGrabModeIsWarp() const
void getCursorGrabAccum(int32_t &x, int32_t &y) const
#define printf
#define str(s)
#define image(slot, qualifiers, format)
#define select(A, B, C)
unsigned int uchar
const int state
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
Definition math_dual.h:263
void free(struct bMotionPath *mpath)
std::string time(const std::tm &date_time, TimeFormat format=TimeFormat::H24)
int size(const AssetLibraryReference *library_reference)
unsigned int uint
Definition BKE_text.h:55
BMesh const char void * data
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
void set(GHOST_TButton mask, bool down)
GHOST_TDrawingContextType context_type
GHOST_GPUDevice preferred_device
void set(GHOST_TModifierKey mask, bool down)
GHOST_TTabletMode Active