12#include <X11/XKBlib.h>
15#include <X11/keysym.h>
37#ifdef WITH_OPENGL_BACKEND
42#ifdef WITH_VULKAN_BACKEND
47# include <X11/XF86keysym.h>
51# include <X11/extensions/Xfixes.h>
53# define WITH_XWAYLAND_HACK
58# include <X11/extensions/XInput2.h>
74# define USE_XINPUT_HOTPLUG
78#define USE_UNITY_WORKAROUND
82#define USE_NON_LATIN_KB_WORKAROUND
86 return ptr[bit >> 3] & (1 << (bit & 7));
92 const XkbDescPtr xkb_descr,
93 const KeyCode keycode);
99#ifdef WITH_XWAYLAND_HACK
100static bool use_xwayland_hack =
false;
109#ifdef WITH_X11_XINPUT
112 keycode_last_repeat_key_(uint(-1))
115 display_ = XOpenDisplay(
nullptr);
118 throw std::runtime_error(
"unable to open a display!");
121#ifdef USE_X11_ERROR_HANDLERS
126#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
133#define GHOST_INTERN_ATOM_IF_EXISTS(atom) \
135 atom_.atom = XInternAtom(display_, #atom, True); \
138#define GHOST_INTERN_ATOM(atom) \
140 atom_.atom = XInternAtom(display_, #atom, False); \
165#ifdef WITH_X11_XINPUT
166 atom_.TABLET = XInternAtom(display_, XI_TABLET, False);
169#undef GHOST_INTERN_ATOM_IF_EXISTS
170#undef GHOST_INTERN_ATOM
174 last_release_keycode_ = 0;
175 last_release_time_ = 0;
179 int xkb_opcode, xkb_event, xkb_error;
180 int xkb_major = XkbMajorVersion, xkb_minor = XkbMinorVersion;
182 use_xkb = XkbQueryExtension(
183 display_, &xkb_opcode, &xkb_event, &xkb_error, &xkb_major, &xkb_minor);
185 XkbSetDetectableAutoRepeat(display_,
true,
nullptr);
187 xkb_descr_ = XkbGetMap(display_, 0, XkbUseCoreKbd);
189 XkbGetNames(display_, XkbKeyNamesMask, xkb_descr_);
190 XkbGetControls(display_, XkbPerKeyRepeatMask | XkbRepeatKeysMask, xkb_descr_);
194#ifdef WITH_XWAYLAND_HACK
195 use_xwayland_hack = getenv(
"WAYLAND_DISPLAY") !=
nullptr;
198#ifdef WITH_X11_XINPUT
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;
211# ifdef USE_XINPUT_HOTPLUG
212 if (xinput_version_.present) {
213 XEventClass class_presence;
215 DevicePresence(display_, xi_presence, class_presence);
216 XSelectExtensionEvent(
217 display_, RootWindow(display_, DefaultScreen(display_)), &class_presence, 1);
222 refreshXInputDevices();
228#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
234#ifdef WITH_X11_XINPUT
236 clearXInputDevices();
240 XkbFreeKeyboard(xkb_descr_, XkbAllComponentsMask,
true);
243 XCloseDisplay(display_);
251#ifdef WITH_INPUT_NDOF
262 timespec ts = {0, 0};
263 if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
264 GHOST_ASSERT(
false,
"Could not instantiate monotonic timer!");
280 static uint64_t timestamp_offset = 0;
283 static uint32_t timestamp_prev = 0;
285 static uint32_t timestamp_start = 0;
287 static bool is_time_init =
false;
292 const uint32_t timestamp_wrap_ms = 2000;
293 static uint32_t timestamp_offset_fake = 0;
295 timestamp_offset_fake =
UINT32_MAX - (timestamp + timestamp_wrap_ms);
297 timestamp = uint32_t(timestamp + timestamp_offset_fake);
304 timestamp_offset = current_time;
305 timestamp_start = timestamp;
310 timestamp = uint32_t(timestamp) - timestamp_start;
314 timestamp_prev = timestamp;
317 if (timestamp < timestamp_prev) [[unlikely]] {
319 if (timestamp_prev - timestamp >
UINT32_MAX / 2) [[unlikely]] {
323 timestamp_prev = timestamp;
327 return timestamp_final;
348 width = DisplayWidth(display_, DefaultScreen(display_));
349 height = DisplayHeight(display_, DefaultScreen(display_));
360 const bool exclusive,
361 const bool is_dialog,
410#ifdef WITH_VULKAN_BACKEND
411 case GHOST_kDrawingContextTypeVulkan: {
413 GHOST_kVulkanPlatformX11,
422 if (context->initializeDrawingContext()) {
430#ifdef WITH_OPENGL_BACKEND
431 case GHOST_kDrawingContextTypeOpenGL: {
432 for (
int minor = 6; minor >= 3; --minor) {
434 context_params_offscreen,
437 (GLXFBConfig)
nullptr,
438 GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
442 (context_params_offscreen.
is_debug ? GLX_CONTEXT_DEBUG_BIT_ARB : 0),
444 if (context->initializeDrawingContext()) {
466#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
467static void destroyIMCallback(XIM , XPointer ptr, XPointer )
472 *(XIM *)ptr =
nullptr;
476bool GHOST_SystemX11::openX11_IM()
483 XSetLocaleModifiers(
"");
485 xim_ = XOpenIM(display_,
nullptr, (
char *)GHOST_X11_RES_NAME, (
char *)GHOST_X11_RES_CLASS);
491 destroy.callback = (XIMProc)destroyIMCallback;
492 destroy.client_data = (XPointer)&xim_;
493 XSetIMValues(xim_, XNDestroyCallback, &destroy,
nullptr);
512 vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
513 vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end();
515 for (; win_it != win_end; ++win_it) {
516 GHOST_WindowX11 *window =
static_cast<GHOST_WindowX11 *
>(*win_it);
526 int fd = ConnectionNumber(display);
532 if (maxSleep == -1) {
533 select(fd + 1, &fds,
nullptr,
nullptr,
nullptr);
538 tv.tv_sec = maxSleep / 1000;
539 tv.tv_usec = (maxSleep - tv.tv_sec * 1000) * 1000;
541 select(fd + 1, &fds,
nullptr,
nullptr, &tv);
553 switch (event->type) {
556 data->timestamp =
event->xbutton.time;
559 data->timestamp =
event->xmotion.time;
563 data->timestamp =
event->xkey.time;
566 data->timestamp =
event->xproperty.time;
570 data->timestamp =
event->xcrossing.time;
573 data->timestamp =
event->xselectionclear.time;
582Time GHOST_SystemX11::lastEventTime(Time default_time)
584 init_timestamp_data
data;
585 data.timestamp = default_time;
589 return data.timestamp;
597 bool anyProcessed =
false;
602 if (waitForEvent && dirty_windows_.empty() && !XPending(display_)) {
621 while (XPending(display_)) {
623 XNextEvent(display_, &xevent);
625#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
629 if (
ELEM(xevent.type, FocusIn, KeyPress)) {
630 if (!xim_ && openX11_IM()) {
636 if (window && !window->getX11_XIC() && window->createX11_XIC()) {
638 if (xevent.type == KeyPress) {
642 XSetICFocus(window->getX11_XIC());
649 if (
ELEM(xevent.type, KeyPress, KeyRelease)) {
650 if (xevent.xkey.time != 0) {
651 last_key_time_ = xevent.xkey.time;
656 if (XFilterEvent(&xevent, (
Window)
nullptr) == True) {
663 if (xevent.type == KeyRelease) {
664 last_release_keycode_ = xevent.xkey.keycode;
665 last_release_time_ = xevent.xkey.time;
667 else if (xevent.type == KeyPress) {
668 if ((xevent.xkey.keycode == last_release_keycode_) &&
669 (xevent.xkey.time <= last_release_time_))
675 processEvent(&xevent);
678#ifdef USE_UNITY_WORKAROUND
685 if (xevent.type == FocusIn) {
689 if (window && XPending(display_) >= 2) {
690 XNextEvent(display_, &xevent);
692 if (xevent.type == KeymapNotify) {
697 XPeekEvent(display_, &xev_next);
699 if (
ELEM(xev_next.type, KeyPress, KeyRelease)) {
702 const static KeySym modifiers[] = {
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,
733 if (generateWindowExposeEvents()) {
737#ifdef WITH_INPUT_NDOF
743 }
while (waitForEvent && !anyProcessed);
748#ifdef WITH_X11_XINPUT
749static bool checkTabletProximity(
Display *display, XDevice *device)
756 if (device ==
nullptr) {
763 state = XQueryDeviceState(display, device);
768 XInputClass *cls =
state->data;
770 for (
int loop = 0; loop <
state->num_classes; loop++) {
771 switch (cls->c_class) {
773 XValuatorState *val_state = (XValuatorState *)cls;
778 if ((val_state->mode & 2) == 0) {
779 XFreeDeviceState(
state);
784 cls = (XInputClass *)((
char *)cls + cls->length);
786 XFreeDeviceState(
state);
792void GHOST_SystemX11::processEvent(XEvent *xe)
794 GHOST_WindowX11 *window = findGhostWindow(xe->xany.window);
795 std::unique_ptr<GHOST_Event> g_event =
nullptr;
798 bool is_repeat =
false;
799 if (
ELEM(xe->type, KeyPress, KeyRelease)) {
800 XKeyEvent *xke = &(xe->xkey);
803 bool is_repeat_keycode =
false;
805 if (xkb_descr_ !=
nullptr) {
807 is_repeat_keycode = (
809 (xke->keycode < (XkbPerKeyBitArraySize << 3)) &&
810 bit_is_on(xkb_descr_->ctrls->per_key_repeat, xke->keycode));
814 switch (XLookupKeysym(xke, 0)) {
831 is_repeat_keycode =
true;
836 if (is_repeat_keycode) {
837 if (xe->type == KeyPress) {
838 if (keycode_last_repeat_key_ == xke->keycode) {
841 keycode_last_repeat_key_ = xke->keycode;
844 if (keycode_last_repeat_key_ == xke->keycode) {
845 keycode_last_repeat_key_ =
uint(-1);
850 else if (xe->type == EnterNotify) {
852 keycode_last_repeat_key_ =
uint(-1);
855#ifdef USE_XINPUT_HOTPLUG
857 if (xinput_version_.present) {
858 XEventClass class_presence;
861 DevicePresence(display_, xi_presence, class_presence);
862 (void)class_presence;
864 if (xe->type == xi_presence) {
865 const XDevicePresenceNotifyEvent *notify_event = (
const XDevicePresenceNotifyEvent *)xe;
866 if (
ELEM(notify_event->devchange, DeviceEnabled, DeviceDisabled, DeviceAdded, DeviceRemoved))
868 refreshXInputDevices();
873 vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
874 vector<GHOST_IWindow *>::const_iterator win_end = win_vec.end();
876 for (; win_it != win_end; ++win_it) {
877 GHOST_WindowX11 *window_xinput =
static_cast<GHOST_WindowX11 *
>(*win_it);
878 window_xinput->refreshXInputDevices();
890#ifdef WITH_X11_XINPUT
897 bool any_proximity =
false;
899 for (
const GHOST_TabletX11 &xtablet : xtablets_) {
900 if (checkTabletProximity(xe->xany.display, xtablet.Device)) {
901 any_proximity =
true;
905 if (!any_proximity) {
913 const XExposeEvent &xee = xe->xexpose;
915 if (xee.count == 0) {
927 const XMotionEvent &xme = xe->xmotion;
948 const int32_t subregion_div = 4;
951 (bounds.
l_ + bounds.
r_) / 2,
952 (bounds.
t_ + bounds.
b_) / 2,
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));
975 bounds.
wrapPoint(x_new, y_new, bounds_margin, bounds_axis);
980 if (x_new != xme.x_root || y_new != xme.y_root) {
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;
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;
1001 g_event = std::make_unique<GHOST_EventCursor>(event_ms,
1004 xme.x_root + x_accum,
1005 xme.y_root + y_accum,
1010 g_event = std::make_unique<GHOST_EventCursor>(event_ms,
1022 XKeyEvent *xke = &(xe->xkey);
1023#ifdef WITH_X11_XINPUT
1025 const Time
time = xke->time ? xke->time : last_key_time_;
1027 const Time
time = xke->time;
1032 char *utf8_buf =
nullptr;
1035#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1042 char utf8_array[16 * 6 + 5];
1051#ifdef USE_NON_LATIN_KB_WORKAROUND
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))
1082 key_sym = XLookupKeysym(xke, ShiftMask);
1083 if (!((key_sym >= XK_0) && (key_sym <= XK_9))) {
1084 key_sym = XLookupKeysym(xke, 0);
1088 key_sym = XLookupKeysym(xke, 0);
1091 if (!XLookupString(xke, &ascii, 1, &key_sym_str,
nullptr)) {
1153 if ((xke->keycode >= 10 && xke->keycode < 20) &&
1154 ((key_sym = XLookupKeysym(xke, ShiftMask)) >= XK_0) && (key_sym <= XK_9))
1160 key_sym = XLookupKeysym(xke, 0);
1165 if (!XLookupString(xke, &ascii, 1,
nullptr,
nullptr)) {
1170#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1175 if (xke->type == KeyPress) {
1176 utf8_buf = utf8_array;
1177#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1179 xic = window->getX11_XIC();
1184 if (!(
len = Xutf8LookupString(
1185 xic, xke, utf8_buf,
sizeof(utf8_array) - 5, &key_sym, &status)))
1190 if (status == XBufferOverflow) {
1191 utf8_buf = (
char *)malloc(
len + 5);
1192 len = Xutf8LookupString(xic, xke, utf8_buf,
len, &key_sym, &status);
1195 if (
ELEM(status, XLookupChars, XLookupBoth)) {
1198 if ((utf8_buf[0] < 32 && utf8_buf[0] > 0) || (utf8_buf[0] == 127)) {
1202 else if (status == XLookupKeySym) {
1207 printf(
"Bad keycode lookup. Keysym 0x%x Status: %s\n",
1209 (status == XLookupNone ?
"XLookupNone" :
1210 status == XLookupKeySym ?
"XLookupKeySym" :
1213 printf(
"'%.*s' %p %p\n",
len, utf8_buf, xic, xim_);
1220 if (!utf8_buf[0] && ascii) {
1221 utf8_buf[0] = ascii;
1226 g_event = std::make_unique<GHOST_EventKey>(
1227 event_ms, type, window, gkey, is_repeat, utf8_buf);
1229#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1232 if (xke->type == KeyPress && xic) {
1237 if (
uchar(utf8_buf[i++]) > 0x7f) {
1238 for (; i <
len; ++i) {
1240 if (c < 0x80 || c > 0xbf) {
1252 g_event = std::make_unique<GHOST_EventKey>(
1253 event_ms, type, window, gkey, is_repeat, &utf8_buf[i]);
1257 if (utf8_buf != utf8_array) {
1266 case ButtonRelease: {
1267 const XButtonEvent &xbe = xe->xbutton;
1274 if (xbe.button == Button4) {
1275 if (xbe.type == ButtonPress) {
1276 g_event = std::make_unique<GHOST_EventWheel>(
1281 if (xbe.button == Button5) {
1282 if (xbe.type == ButtonPress) {
1283 g_event = std::make_unique<GHOST_EventWheel>(
1290 if (xbe.button == Button1) {
1293 else if (xbe.button == Button2) {
1296 else if (xbe.button == Button3) {
1302 else if (xbe.button == 6) {
1305 else if (xbe.button == 7) {
1308 else if (xbe.button == 8) {
1311 else if (xbe.button == 9) {
1318 g_event = std::make_unique<GHOST_EventButton>(
1324 case ConfigureNotify: {
1335 const XFocusChangeEvent &xfe = xe->xfocus;
1339 printf(
"X: focus %s for window %d\n", xfe.type == FocusIn ?
"in" :
"out",
int(xfe.window));
1347#if defined(WITH_X11_XINPUT) && defined(X_HAVE_UTF8_STRING)
1348 XIC xic = window->getX11_XIC();
1350 if (xe->type == FocusIn) {
1359 g_event = std::make_unique<GHOST_Event>(
getMilliSeconds(), gtype, window);
1362 case ClientMessage: {
1363 XClientMessageEvent &xcme = xe->xclient;
1365 if (((Atom)xcme.data.l[0]) ==
atom_.WM_DELETE_WINDOW) {
1366 g_event = std::make_unique<GHOST_Event>(
1369 else if (((Atom)xcme.data.l[0]) ==
atom_.WM_TAKE_FOCUS) {
1370 XWindowAttributes attr;
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]);
1398 if (window->getDropTarget()->GHOST_HandleClientMessage(xe) ==
false) {
1413 case GraphicsExpose:
1425 const XCrossingEvent &xce = xe->xcrossing;
1427 if (xce.mode == NotifyNormal) {
1428 g_event = std::make_unique<GHOST_EventCursor>(event_ms,
1438 "X: %s window %d\n", xce.type == EnterNotify ?
"entering" :
"leaving",
int(xce.window));
1441 if (xce.type == EnterNotify) {
1472 case ReparentNotify:
1474 case SelectionRequest: {
1476 XSelectionRequestEvent *xse = &xe->xselectionrequest;
1479 if (xse->property == None) {
1480 xse->property = xse->target;
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;
1494 if (xse->selection == XInternAtom(display_,
"PRIMARY", False)) {
1495 XChangeProperty(display_,
1504 else if (xse->selection == XInternAtom(display_,
"CLIPBOARD", False)) {
1505 XChangeProperty(display_,
1515 else if (xse->target ==
atom_.TARGETS) {
1516 const Atom atom_list[] = {
1518 XChangeProperty(display_,
1524 reinterpret_cast<const uchar *
>(atom_list),
1530 nxe.xselection.property =
None;
1534 XSendEvent(display_, xse->requestor, 0, 0, &nxe);
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) {
1548 const uchar axis_first =
data->first_axis;
1549 const uchar axes_end = axis_first +
data->axes_count;
1563# define AXIS_VALUE_GET(axis, val) \
1564 ((axis_first <= axis && axes_end > axis) && \
1565 ((void)(val = data->axis_data[axis - axis_first]), true))
1567 if (AXIS_VALUE_GET(2, axis_value)) {
1579 if (AXIS_VALUE_GET(3, axis_value)) {
1581 float(xtablet.XtiltLevels);
1583 if (AXIS_VALUE_GET(4, axis_value)) {
1585 float(xtablet.YtiltLevels);
1588# undef AXIS_VALUE_GET
1590 else if (xe->type == xtablet.ProxInEvent) {
1591 const XProximityNotifyEvent *
data = (
const XProximityNotifyEvent *)xe;
1592 if (
data->deviceid != xtablet.ID) {
1598 else if (xe->type == xtablet.ProxOutEvent) {
1629 XImage *
image = XGetImage(
1630 display_, XRootWindow(display_, XDefaultScreen(display_)),
x,
y, 1, 1, AllPlanes, XYPixmap);
1631 if (
image ==
nullptr) {
1634 c.pixel = XGetPixel(
image, 0, 0);
1636 XQueryColor(display_, XDefaultColormap(display_, XDefaultScreen(display_)), &c);
1639 r_color[0] = c.red / 65535.0f;
1640 r_color[1] = c.green / 65535.0f;
1641 r_color[2] = c.blue / 65535.0f;
1650 memset((
void *)keyboard_vector_, 0,
sizeof(keyboard_vector_));
1652 XQueryKeymap(display_, (
char *)keyboard_vector_);
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);
1669 ((keyboard_vector_[shift_l >> 3] >> (shift_l & 7)) & 1) != 0);
1671 ((keyboard_vector_[shift_r >> 3] >> (shift_r & 7)) & 1) != 0);
1674 ((keyboard_vector_[control_l >> 3] >> (control_l & 7)) & 1) != 0);
1676 ((keyboard_vector_[control_r >> 3] >> (control_r & 7)) & 1) != 0);
1683 ((keyboard_vector_[super_r >> 3] >> (super_r & 7)) & 1) != 0);
1686 ((keyboard_vector_[hyper_l >> 3] >> (hyper_l & 7)) & 1) != 0);
1688 ((keyboard_vector_[hyper_r >> 3] >> (hyper_r & 7)) & 1) != 0);
1695 Window root_return, child_return;
1699 if (XQueryPointer(display_,
1700 RootWindow(display_, DefaultScreen(display_)),
1707 &mask_return) == True)
1731 if (XQueryPointer(display,
1732 RootWindow(display, DefaultScreen(display)),
1739 &mask_return) == False)
1765#ifdef WITH_XWAYLAND_HACK
1766 Window child_return = None;
1779#ifdef WITH_XWAYLAND_HACK
1780 if (use_xwayland_hack) {
1781 if (child_return != None) {
1782 XFixesHideCursor(display_, child_return);
1787#if defined(WITH_X11_XINPUT) && defined(USE_X11_XINPUT_WARP)
1788 if ((xinput_version_.present) && (xinput_version_.major_version >= 2)) {
1791 if (XIGetClientPointer(display_, None, &device_id) != False) {
1792 XIWarpPointer(display_, device_id, None, None, 0, 0, 0, 0, relx, rely);
1798 XWarpPointer(display_, None, None, 0, 0, 0, 0, relx, rely);
1801#ifdef WITH_XWAYLAND_HACK
1802 if (use_xwayland_hack) {
1803 if (child_return != None) {
1804 XFixesShowCursor(display_, child_return);
1836 GHOST_ASSERT((bad_wind !=
nullptr),
"addDirtyWindow() nullptr ptr trapped (window)");
1838 dirty_windows_.push_back(bad_wind);
1841bool GHOST_SystemX11::generateWindowExposeEvents()
1845 bool anyProcessed =
false;
1847 for (; w_start != w_end; ++w_start) {
1848 auto g_event = std::make_unique<GHOST_Event>(
1851 (*w_start)->validate();
1855 anyProcessed =
true;
1859 dirty_windows_.clear();
1860 return anyProcessed;
1864 XkbDescPtr xkb_descr,
1865 const KeyCode keycode)
1876#define GXMAP(k, x, y) \
1885 if ((key >= XK_A) && (key <= XK_Z)) {
1888 else if ((key >= XK_a) && (key <= XK_z)) {
1891 else if ((key >= XK_0) && (key <= XK_9)) {
1894 else if ((key >= XK_F1) && (key <= XK_F24)) {
1982#ifdef WITH_XF86KEYSYM
1988# ifdef XF86XK_AudioForward
1993#ifdef WITH_GHOST_DEBUG
1994 printf(
"%s: unknown key: %lu / 0x%lx\n", __func__, key, key);
2006#define MAKE_ID(a, b, c, d) (int(d) << 24 | int(c) << 16 | (b) << 8 | (a))
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]);
2015 case MAKE_ID(
'T',
'L',
'D',
'E'):
2017 case MAKE_ID(
'L',
'S',
'G',
'T'):
2019#ifdef WITH_GHOST_DEBUG
2021 printf(
"%s unhandled keycode: %.*s\n", __func__, XkbKeyNameLength, id_str);
2026 else if (keycode != 0) {
2036#define XCLIB_XCOUT_NONE 0
2037#define XCLIB_XCOUT_SENTCONVSEL 1
2038#define XCLIB_XCOUT_INCR 2
2039#define XCLIB_XCOUT_FALLBACK 3
2040#define XCLIB_XCOUT_FALLBACK_UTF8 4
2041#define XCLIB_XCOUT_FALLBACK_COMP 5
2042#define XCLIB_XCOUT_FALLBACK_TEXT 6
2046 const XEvent *evt, Atom sel, Atom target,
uchar **txt, ulong *
len, uint *context)
const
2051 ulong pty_size, pty_items;
2055 vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
2069 XConvertSelection(display_, sel, target,
atom_.XCLIP_OUT, win, CurrentTime);
2074 if (evt->type != SelectionNotify) {
2078 if (target ==
atom_.UTF8_STRING && evt->xselection.property == None) {
2082 if (target ==
atom_.COMPOUND_TEXT && evt->xselection.property == None) {
2086 if (target ==
atom_.TEXT && evt->xselection.property == None) {
2092 XGetWindowProperty(display_,
2106 if (pty_type ==
atom_.INCR) {
2108 XDeleteProperty(display_, win,
atom_.XCLIP_OUT);
2117 if (pty_format != 8) {
2123 XGetWindowProperty(display_,
2137 XDeleteProperty(display_, win,
atom_.XCLIP_OUT);
2140 ltxt = (
uchar *)malloc(pty_items);
2141 memcpy(ltxt, buffer, pty_items);
2162 if (evt->type != PropertyNotify) {
2167 if (evt->xproperty.state != PropertyNewValue) {
2172 XGetWindowProperty(display_,
2185 if (pty_format != 8) {
2190 XDeleteProperty(display_, win,
atom_.XCLIP_OUT);
2194 if (pty_size == 0) {
2197 XDeleteProperty(display_, win,
atom_.XCLIP_OUT);
2209 XGetWindowProperty(display_,
2229 ltxt = (
uchar *)realloc(ltxt, *
len);
2233 memcpy(<xt[*
len - pty_items], buffer, pty_items);
2239 XDeleteProperty(display_, win,
atom_.XCLIP_OUT);
2248 Atom target =
atom_.UTF8_STRING;
2257 if (selection == True) {
2258 sseln =
atom_.PRIMARY;
2261 sseln =
atom_.CLIPBOARD;
2265 vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
2270 owner = XGetSelectionOwner(display_, sseln);
2272 if (sseln ==
atom_.CLIPBOARD) {
2274 sel_buf = (
char *)malloc(sel_buf_size);
2279 sel_buf = (
char *)malloc(sel_buf_size);
2283 if (owner == None) {
2288 vector<XEvent> restore_events;
2292 bool restore_this_event =
false;
2294 XNextEvent(display_, &evt);
2295 restore_this_event = (evt.type != SelectionNotify);
2301 if (restore_this_event) {
2302 restore_events.push_back(evt);
2308 target =
atom_.STRING;
2314 target =
atom_.COMPOUND_TEXT;
2320 target =
atom_.TEXT;
2334 while (!restore_events.empty()) {
2335 XPutBackEvent(display_, &restore_events.back());
2336 restore_events.pop_back();
2341 char *tmp_data = (
char *)malloc(sel_len + 1);
2342 memcpy(tmp_data, (
char *)sel_buf, sel_len);
2343 tmp_data[sel_len] =
'\0';
2345 if (sseln ==
atom_.STRING) {
2362 vector<GHOST_IWindow *>::const_iterator win_it = win_vec.begin();
2367 if (selection == False) {
2368 XSetSelectionOwner(display_,
atom_.CLIPBOARD, window_, CurrentTime);
2369 owner = XGetSelectionOwner(display_,
atom_.CLIPBOARD);
2374 size_t buffer_size = strlen(buffer) + 1;
2379 XSetSelectionOwner(display_,
atom_.PRIMARY, window_, CurrentTime);
2380 owner = XGetSelectionOwner(display_,
atom_.PRIMARY);
2385 size_t buffer_size = strlen(buffer) + 1;
2390 if (owner != window_) {
2391 fprintf(stderr,
"failed to own primary\n");
2445 XFillRectangle(display,
2453 XFillRectangle(display,
2461 XDrawString(display,
2481static void split(
const char *text,
const char *seps,
char ***
str,
int *count)
2488 data = strdup(text);
2489 for (tok = strtok(data, seps); tok !=
nullptr; tok = strtok(
nullptr, seps)) {
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);
2503 const char *message,
2504 const char *help_label,
2505 const char *continue_label,
2509 char **text_splitted =
nullptr;
2511 split(message,
"\n", &text_splitted, &textLines);
2518 int screen = DefaultScreen(display_);
2519 window = XCreateSimpleWindow(display_,
2520 RootWindow(display_, screen),
2526 BlackPixel(display_, screen),
2527 WhitePixel(display_, screen));
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);
2539 Atom wm_Name = XInternAtom(display_,
"_NET_WM_NAME", False);
2540 Atom utf8Str = XInternAtom(display_,
"UTF8_STRING", False);
2542 Atom winType = XInternAtom(display_,
"_NET_WM_WINDOW_TYPE", False);
2543 Atom typeDialog = XInternAtom(display_,
"_NET_WM_WINDOW_TYPE_DIALOG", False);
2545 XChangeProperty(display_,
2551 (
const uchar *)title,
2552 int(strlen(title)));
2555 display_, window, winType, XA_ATOM, 32, PropModeReplace, (
uchar *)&typeDialog, 1);
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);
2566 GC buttonBorderGC = XCreateGC(display_, window, GCForeground, &buttonBorderGCValues);
2567 GC buttonGC = XCreateGC(display_, window, GCForeground, &buttonGCValues);
2569 XSelectInput(display_, window, ExposureMask | ButtonPressMask | ButtonReleaseMask);
2570 XMapWindow(display_, window);
2572 const bool has_link = link && strlen(link);
2575 XNextEvent(display_, &e);
2576 if (e.type == Expose) {
2577 for (
int i = 0; i < textLines; i++) {
2578 XDrawString(display_,
2580 DefaultGC(display_, screen),
2584 int(strlen(text_splitted[i])));
2586 dialog_data.
drawButton(display_, window, buttonBorderGC, buttonGC, 1, continue_label);
2588 dialog_data.
drawButton(display_, window, buttonBorderGC, buttonGC, 2, help_label);
2591 else if (e.type == ButtonRelease) {
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]",
2608 for (
int i = 0; i < textLines; i++) {
2609 free(text_splitted[i]);
2611 free(text_splitted);
2613 XDestroyWindow(display_, window);
2614 XFreeGC(display_, buttonBorderGC);
2615 XFreeGC(display_, buttonGC);
2634 return system->
pushEvent(std::make_unique<GHOST_EventDragnDrop>(
2635 event_ms, eventType, draggedObjectType, window, mouseX, mouseY, data));
2652 char error_code_str[512];
2654 XGetErrorText(display, event->error_code, error_code_str,
sizeof(error_code_str));
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",
2663 event->request_code,
2678 fprintf(stderr,
"Ignoring Xlib error: error IO\n");
2684#ifdef WITH_X11_XINPUT
2686static bool is_filler_char(
char c)
2688 return isspace(c) ||
ELEM(c,
'_',
'-',
';',
':');
2692static bool match_token(
const char *haystack,
const char *needle)
2695 for (h = haystack; *h;) {
2696 while (*h && is_filler_char(*h)) {
2703 for (n = needle; *n && *h && tolower(*h) == tolower(*n); n++) {
2706 if (!*n && (is_filler_char(*h) || !*h)) {
2710 while (*h && !is_filler_char(*h)) {
2727static GHOST_TTabletMode tablet_mode_from_name(
const char *name,
const char *type)
2730 static const char *tablet_stylus_whitelist[] = {
"stylus",
"wizardpen",
"acecad",
"pen",
nullptr};
2732 static const char *type_blacklist[] = {
"pad",
"cursor",
"touch",
nullptr};
2735 for (i = 0; type_blacklist[i] !=
nullptr; i++) {
2736 if (type && (strcasecmp(type, type_blacklist[i]) == 0)) {
2742 for (i = 0; tablet_stylus_whitelist[i] !=
nullptr; i++) {
2743 if (type && match_token(type, tablet_stylus_whitelist[i])) {
2747 if (type && match_token(type,
"eraser")) {
2750 for (i = 0; tablet_stylus_whitelist[i] !=
nullptr; i++) {
2751 if (name && match_token(name, tablet_stylus_whitelist[i])) {
2755 if (name && match_token(name,
"eraser")) {
2764void GHOST_SystemX11::refreshXInputDevices()
2766 if (xinput_version_.present) {
2768 clearXInputDevices();
2775 XDeviceInfo *device_info = XListInputDevices(display_, &device_count);
2777 for (
int i = 0; i < device_count; ++i) {
2778 char *device_type = device_info[i].type ? XGetAtomName(display_, device_info[i].type) :
2780 GHOST_TTabletMode tablet_mode = tablet_mode_from_name(device_info[i].name, device_type);
2785 XFree((
void *)device_type);
2792 GHOST_TabletX11 xtablet = {tablet_mode};
2793 xtablet.ID = device_info[i].id;
2794 xtablet.Device = XOpenDevice(display_, xtablet.ID);
2796 if (xtablet.Device !=
nullptr) {
2798 XAnyClassPtr ici = device_info[i].inputclassinfo;
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;
2807 if (xvi->num_axes > 3) {
2810 xtablet.XtiltLevels = xvi->axes[3].max_value;
2811 xtablet.YtiltLevels = xvi->axes[4].max_value;
2814 xtablet.XtiltLevels = 0;
2815 xtablet.YtiltLevels = 0;
2822 ici = (XAnyClassPtr)(((
char *)ici) + ici->length);
2826 xtablets_.push_back(xtablet);
2830 XFreeDeviceList(device_info);
2837void GHOST_SystemX11::clearXInputDevices()
2839 for (GHOST_TabletX11 &xtablet : xtablets_) {
2840 if (xtablet.Device) {
2841 XCloseDevice(display_, xtablet.Device);
#define GHOST_OPENGL_GLX_RESET_NOTIFICATION_STRATEGY
#define GHOST_OPENGL_GLX_CONTEXT_FLAGS
#define GHOST_PRINTF(x,...)
#define GHOST_ASSERT(x, info)
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_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 *)
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_kEventWindowClose
@ GHOST_kEventWindowActivate
@ GHOST_kEventWindowUpdate
@ GHOST_kEventWindowDeactivate
@ GHOST_kTabletModeEraser
@ GHOST_kTabletModeStylus
@ GHOST_kCapabilityCursorRGBA
@ GHOST_kCapabilityInputIME
@ GHOST_kCapabilityCursorGenerator
@ GHOST_kCapabilityWindowPath
@ GHOST_kCapabilityClipboardImage
@ GHOST_kCapabilityWindowDecorationStyles
#define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS(gpu_settings)
#define GHOST_CAPABILITY_FLAG_ALL
@ GHOST_kKeyNumpadAsterisk
@ GHOST_kModifierKeyRightControl
@ GHOST_kModifierKeyLeftControl
@ GHOST_kModifierKeyRightHyper
@ GHOST_kModifierKeyRightAlt
@ GHOST_kModifierKeyRightShift
@ GHOST_kModifierKeyLeftAlt
@ GHOST_kModifierKeyLeftShift
@ GHOST_kModifierKeyLeftOS
@ GHOST_kModifierKeyRightOS
@ GHOST_kModifierKeyLeftHyper
#define GHOST_CONTEXT_PARAMS_FROM_GPU_SETTINGS_OFFSCREEN(gpu_settings)
@ GHOST_kButtonMaskButton4
@ GHOST_kButtonMaskButton7
@ GHOST_kButtonMaskButton6
@ GHOST_kButtonMaskButton5
@ GHOST_kButtonMaskMiddle
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
#define MAKE_ID(a, b, c, d)
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
uint button_text_offset_y
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 &)
virtual void wrapPoint(int32_t &x, int32_t &y, int32_t ofs, GHOST_TAxisFlag axis)
virtual int32_t getHeight() const
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 image(slot, qualifiers, format)
ccl_device_inline dual1 len(const ccl_private dual< T > &a)
void free(struct bMotionPath *mpath)
std::string time(const std::tm &date_time, TimeFormat format=TimeFormat::H24)
int size(const AssetLibraryReference *library_reference)
BMesh const char void * data
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
GHOST_TDrawingContextType context_type
GHOST_GPUDevice preferred_device
void set(GHOST_TModifierKey mask, bool down)