Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qxcbconnection_xi2.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
6#include "qxcbkeyboard.h"
8#include "qxcbscreen.h"
9#include "qxcbwindow.h"
10#include "QtCore/qmetaobject.h"
11#include "QtCore/qmath.h"
12#include <QtGui/qpointingdevice.h>
13#include <QtGui/private/qpointingdevice_p.h>
14#include <qpa/qwindowsysteminterface_p.h>
15#include <QDebug>
16
17#include <xcb/xinput.h>
18
19#if QT_CONFIG(gestures)
20#define QT_XCB_HAS_TOUCHPAD_GESTURES (XCB_INPUT_MINOR_VERSION >= 4)
21#endif
22
23using namespace Qt::StringLiterals;
24
25using qt_xcb_input_device_event_t = xcb_input_button_press_event_t;
26#if QT_XCB_HAS_TOUCHPAD_GESTURES
27using qt_xcb_input_pinch_event_t = xcb_input_gesture_pinch_begin_event_t;
28using qt_xcb_input_swipe_event_t = xcb_input_gesture_swipe_begin_event_t;
29#endif
30
31namespace {
32
33struct qt_xcb_input_event_mask_t {
34 xcb_input_event_mask_t header;
35 alignas(4) uint8_t mask[8] = {}; // up to 2 units of 4 bytes
36};
37
38} // namespace
39
40static inline void setXcbMask(uint8_t* mask, int bit)
41{
42 // note that XI protocol always uses little endian for masks over the wire
43 mask[bit >> 3] |= 1 << (bit & 7);
44}
45
46void QXcbConnection::xi2SelectStateEvents()
47{
48 // These state events do not depend on a specific X window, but are global
49 // for the X client's (application's) state.
50 qt_xcb_input_event_mask_t xiEventMask;
51 xiEventMask.header.deviceid = XCB_INPUT_DEVICE_ALL;
52 xiEventMask.header.mask_len = 1;
53 setXcbMask(xiEventMask.mask, XCB_INPUT_HIERARCHY);
54 setXcbMask(xiEventMask.mask, XCB_INPUT_DEVICE_CHANGED);
55 setXcbMask(xiEventMask.mask, XCB_INPUT_PROPERTY);
56 xcb_input_xi_select_events(xcb_connection(), rootWindow(), 1, &xiEventMask.header);
57}
58
59void QXcbConnection::xi2SelectDeviceEvents(xcb_window_t window)
60{
61 if (window == rootWindow())
62 return;
63
64 qt_xcb_input_event_mask_t mask;
65
66 setXcbMask(mask.mask, XCB_INPUT_BUTTON_PRESS);
67 setXcbMask(mask.mask, XCB_INPUT_BUTTON_RELEASE);
68 setXcbMask(mask.mask, XCB_INPUT_MOTION);
69 // There is a check for enter/leave events in plain xcb enter/leave event handler,
70 // core enter/leave events will be ignored in this case.
71 setXcbMask(mask.mask, XCB_INPUT_ENTER);
72 setXcbMask(mask.mask, XCB_INPUT_LEAVE);
73 if (isAtLeastXI22()) {
74 setXcbMask(mask.mask, XCB_INPUT_TOUCH_BEGIN);
75 setXcbMask(mask.mask, XCB_INPUT_TOUCH_UPDATE);
76 setXcbMask(mask.mask, XCB_INPUT_TOUCH_END);
77 }
78#if QT_CONFIG(gestures) && QT_XCB_HAS_TOUCHPAD_GESTURES
79 if (isAtLeastXI24()) {
80 setXcbMask(mask.mask, XCB_INPUT_GESTURE_PINCH_BEGIN);
81 setXcbMask(mask.mask, XCB_INPUT_GESTURE_PINCH_UPDATE);
82 setXcbMask(mask.mask, XCB_INPUT_GESTURE_PINCH_END);
83 setXcbMask(mask.mask, XCB_INPUT_GESTURE_SWIPE_BEGIN);
84 setXcbMask(mask.mask, XCB_INPUT_GESTURE_SWIPE_UPDATE);
85 setXcbMask(mask.mask, XCB_INPUT_GESTURE_SWIPE_END);
86 }
87#endif // QT_CONFIG(gestures) && QT_XCB_HAS_TOUCHPAD_GESTURES
88
89 mask.header.deviceid = XCB_INPUT_DEVICE_ALL;
90 mask.header.mask_len = 2;
91 xcb_void_cookie_t cookie =
92 xcb_input_xi_select_events_checked(xcb_connection(), window, 1, &mask.header);
93 xcb_generic_error_t *error = xcb_request_check(xcb_connection(), cookie);
94 if (error) {
95 qCDebug(lcQpaXInput, "failed to select events, window %x, error code %d", window, error->error_code);
96 free(error);
97 } else {
98 QWindowSystemInterfacePrivate::TabletEvent::setPlatformSynthesizesMouse(false);
99 }
100}
101
102static inline qreal fixed3232ToReal(xcb_input_fp3232_t val)
103{
104 return qreal(val.integral) + qreal(val.frac) / (1ULL << 32);
105}
106
107#if QT_CONFIG(tabletevent)
108/*!
109 \internal
110 Find the existing QPointingDevice instance representing a particular tablet or stylus;
111 or create and register a new instance if it was not found.
112
113 An instance can be uniquely identified by its \a devType, \a pointerType and \a uniqueId.
114 The rest of the arguments are necessary to create a new instance.
115
116 If the instance represents a stylus, the instance representing the tablet
117 itself must be given as \a master. Otherwise, \a master must be the xinput
118 master device (core pointer) to which the tablet belongs. It should not be
119 null, because \a master is also the QObject::parent() for memory management.
120
121 Proximity events have incomplete information. So as a side effect, if an
122 existing instance is found, it is updated with the given \a usbId and
123 \a toolId, and the seat ID of \a master, in case those values were only
124 now discovered, or the seat assignment changed (?).
125*/
126static const QPointingDevice *tabletToolInstance(QPointingDevice *master, const QString &tabletName,
127 qint64 id, quint32 usbId, quint32 toolId, qint64 uniqueId,
128 QPointingDevice::PointerType pointerTypeOverride = QPointingDevice::PointerType::Unknown,
129 QPointingDevice::Capabilities capsOverride = QInputDevice::Capability::None)
130{
131 QInputDevice::DeviceType devType = QInputDevice::DeviceType::Stylus;
132 QPointingDevice::PointerType pointerType = QPointingDevice::PointerType::Pen;
133 QPointingDevice::Capabilities caps = QInputDevice::Capability::Position |
134 QInputDevice::Capability::Pressure |
135 QInputDevice::Capability::MouseEmulation |
136 QInputDevice::Capability::Hover |
137 capsOverride;
138 int buttonCount = 3; // the tip, plus two barrel buttons
139 // keep in sync with wacom_intuos_inout() in Linux kernel driver wacom_wac.c
140 // TODO yeah really, there are many more now so this needs updating
141 switch (toolId) {
142 case 0xd12:
143 case 0x912:
144 case 0x112:
145 case 0x913: /* Intuos3 Airbrush */
146 case 0x902: /* Intuos4/5 13HD/24HD Airbrush */
147 case 0x100902: /* Intuos4/5 13HD/24HD Airbrush */
148 devType = QInputDevice::DeviceType::Airbrush;
149 caps.setFlag(QInputDevice::Capability::XTilt);
150 caps.setFlag(QInputDevice::Capability::YTilt);
151 caps.setFlag(QInputDevice::Capability::TangentialPressure);
152 buttonCount = 2;
153 break;
154 case 0x91b: /* Intuos3 Airbrush Eraser */
155 case 0x90a: /* Intuos4/5 13HD/24HD Airbrush Eraser */
156 case 0x10090a: /* Intuos4/5 13HD/24HD Airbrush Eraser */
157 devType = QInputDevice::DeviceType::Airbrush;
158 pointerType = QPointingDevice::PointerType::Eraser;
159 caps.setFlag(QInputDevice::Capability::XTilt);
160 caps.setFlag(QInputDevice::Capability::YTilt);
161 caps.setFlag(QInputDevice::Capability::TangentialPressure);
162 buttonCount = 2;
163 break;
164 case 0x007: /* Mouse 4D and 2D */
165 case 0x09c:
166 case 0x094:
167 // TODO set something to indicate a multi-dimensional capability:
168 // Capability::3D or 4D or QPointingDevice::setMaximumDimensions()?
169 devType = QInputDevice::DeviceType::Mouse;
170 buttonCount = 5; // TODO only if it's a 4D Mouse
171 break;
172 case 0x017: /* Intuos3 2D Mouse */
173 case 0x806: /* Intuos4 Mouse */
174 devType = QInputDevice::DeviceType::Mouse;
175 break;
176 case 0x096: /* Lens cursor */
177 case 0x097: /* Intuos3 Lens cursor */
178 case 0x006: /* Intuos4 Lens cursor */
179 devType = QInputDevice::DeviceType::Puck;
180 break;
181 case 0x885: /* Intuos3 Art Pen (Marker Pen) */
182 case 0x100804: /* Intuos4/5 13HD/24HD Art Pen */
183 caps.setFlag(QInputDevice::Capability::XTilt);
184 caps.setFlag(QInputDevice::Capability::YTilt);
185 caps.setFlag(QInputDevice::Capability::Rotation);
186 buttonCount = 1;
187 break;
188 case 0x10080c: /* Intuos4/5 13HD/24HD Art Pen Eraser */
189 pointerType = QPointingDevice::PointerType::Eraser;
190 caps.setFlag(QInputDevice::Capability::XTilt);
191 caps.setFlag(QInputDevice::Capability::YTilt);
192 caps.setFlag(QInputDevice::Capability::Rotation);
193 buttonCount = 1;
194 break;
195 case 0:
196 pointerType = QPointingDevice::PointerType::Unknown;
197 break;
198 }
199 if (pointerTypeOverride != QPointingDevice::PointerType::Unknown)
200 pointerType = pointerTypeOverride;
201 const QPointingDevice *ret = QPointingDevicePrivate::queryTabletDevice(devType, pointerType,
202 QPointingDeviceUniqueId::fromNumericId(uniqueId),
203 caps, id);
204 if (!ret) {
205 ret = new QPointingDevice(tabletName, id, devType, pointerType, caps, 1, buttonCount,
206 master ? master->seatName() : QString(),
207 QPointingDeviceUniqueId::fromNumericId(uniqueId), master);
208 QWindowSystemInterface::registerInputDevice(ret);
209 }
210 QPointingDevicePrivate *devPriv = QPointingDevicePrivate::get(const_cast<QPointingDevice *>(ret));
211 devPriv->busId = QString::number(usbId, 16);
212 devPriv->toolId = toolId;
213 if (master)
214 devPriv->seatName = master->seatName();
215 return ret;
216}
217
218static const char *toolName(QInputDevice::DeviceType tool) {
219 static const QMetaObject *metaObject = qt_getEnumMetaObject(tool);
220 static const QMetaEnum me = metaObject->enumerator(metaObject->indexOfEnumerator(qt_getEnumName(tool)));
221 return me.valueToKey(int(tool));
222}
223
224static const char *pointerTypeName(QPointingDevice::PointerType ptype) {
225 static const QMetaObject *metaObject = qt_getEnumMetaObject(ptype);
226 static const QMetaEnum me = metaObject->enumerator(metaObject->indexOfEnumerator(qt_getEnumName(ptype)));
227 return me.valueToKey(int(ptype));
228}
229#endif
230
231void QXcbConnection::xi2SetupSlavePointerDevice(void *info, QPointingDevice *master)
232{
233 auto *deviceInfo = reinterpret_cast<xcb_input_xi_device_info_t *>(info);
234#if QT_CONFIG(tabletevent)
235 for (int i = 0; i < m_tabletData.size(); ++i) {
236 if (m_tabletData.at(i).deviceId == deviceInfo->deviceid) {
237 m_tabletData.remove(i);
238 break;
239 }
240 }
241#endif
242 m_touchDevices.remove(deviceInfo->deviceid);
243
244 const QByteArray nameRaw = QByteArray(xcb_input_xi_device_info_name(deviceInfo),
245 xcb_input_xi_device_info_name_length(deviceInfo));
246 const QString name = QString::fromUtf8(nameRaw);
247 m_xiSlavePointerIds.append(deviceInfo->deviceid);
248 qCDebug(lcQpaInputDevices) << "input device " << name << "ID" << deviceInfo->deviceid;
249#if QT_CONFIG(tabletevent)
250 TabletData tabletData;
251#endif
252 QXcbScrollingDevicePrivate *scrollingDeviceP = nullptr;
253 bool used = false;
254 auto scrollingDevice = [&]() {
255 if (!scrollingDeviceP)
256 scrollingDeviceP = new QXcbScrollingDevicePrivate(name, deviceInfo->deviceid,
257 QInputDevice::Capability::Scroll);
258 return scrollingDeviceP;
259 };
260
261 int buttonCount = 32;
262 auto classes_it = xcb_input_xi_device_info_classes_iterator(deviceInfo);
263 for (; classes_it.rem; xcb_input_device_class_next(&classes_it)) {
264 xcb_input_device_class_t *classinfo = classes_it.data;
265 switch (classinfo->type) {
266 case XCB_INPUT_DEVICE_CLASS_TYPE_VALUATOR: {
267 auto *vci = reinterpret_cast<xcb_input_valuator_class_t *>(classinfo);
268 const int valuatorAtom = qatom(vci->label);
269 qCDebug(lcQpaInputDevices) << " has valuator" << atomName(vci->label) << "recognized?" << (valuatorAtom < QXcbAtom::NAtoms);
270#if QT_CONFIG(tabletevent)
271 if (valuatorAtom < QXcbAtom::NAtoms) {
272 TabletData::ValuatorClassInfo info;
273 info.minVal = fixed3232ToReal(vci->min);
274 info.maxVal = fixed3232ToReal(vci->max);
275 info.number = vci->number;
276 tabletData.valuatorInfo[valuatorAtom] = info;
277 }
278#endif // QT_CONFIG(tabletevent)
279 if (valuatorAtom == QXcbAtom::AtomRelHorizScroll || valuatorAtom == QXcbAtom::AtomRelHorizWheel)
280 scrollingDevice()->lastScrollPosition.setX(fixed3232ToReal(vci->value));
281 else if (valuatorAtom == QXcbAtom::AtomRelVertScroll || valuatorAtom == QXcbAtom::AtomRelVertWheel)
282 scrollingDevice()->lastScrollPosition.setY(fixed3232ToReal(vci->value));
283 break;
284 }
285 case XCB_INPUT_DEVICE_CLASS_TYPE_SCROLL: {
286 auto *sci = reinterpret_cast<xcb_input_scroll_class_t *>(classinfo);
287 if (sci->scroll_type == XCB_INPUT_SCROLL_TYPE_VERTICAL) {
288 auto dev = scrollingDevice();
289 dev->orientations.setFlag(Qt::Vertical);
290 dev->verticalIndex = sci->number;
291 dev->verticalIncrement = fixed3232ToReal(sci->increment);
292 } else if (sci->scroll_type == XCB_INPUT_SCROLL_TYPE_HORIZONTAL) {
293 auto dev = scrollingDevice();
294 dev->orientations.setFlag(Qt::Horizontal);
295 dev->horizontalIndex = sci->number;
296 dev->horizontalIncrement = fixed3232ToReal(sci->increment);
297 }
298 break;
299 }
300 case XCB_INPUT_DEVICE_CLASS_TYPE_BUTTON: {
301 auto *bci = reinterpret_cast<xcb_input_button_class_t *>(classinfo);
302 xcb_atom_t *labels = nullptr;
303 if (bci->num_buttons >= 5) {
304 labels = xcb_input_button_class_labels(bci);
305 xcb_atom_t label4 = labels[3];
306 xcb_atom_t label5 = labels[4];
307 // Some drivers have no labels on the wheel buttons, some have no label on just one and some have no label on
308 // button 4 and the wrong one on button 5. So we just check that they are not labelled with unrelated buttons.
309 if ((!label4 || qatom(label4) == QXcbAtom::AtomButtonWheelUp || qatom(label4) == QXcbAtom::AtomButtonWheelDown) &&
310 (!label5 || qatom(label5) == QXcbAtom::AtomButtonWheelUp || qatom(label5) == QXcbAtom::AtomButtonWheelDown))
311 scrollingDevice()->legacyOrientations |= Qt::Vertical;
312 }
313 if (bci->num_buttons >= 7) {
314 xcb_atom_t label6 = labels[5];
315 xcb_atom_t label7 = labels[6];
316 if ((!label6 || qatom(label6) == QXcbAtom::AtomButtonHorizWheelLeft) && (!label7 || qatom(label7) == QXcbAtom::AtomButtonHorizWheelRight))
317 scrollingDevice()->legacyOrientations |= Qt::Horizontal;
318 }
319 buttonCount = bci->num_buttons;
320 qCDebug(lcQpaInputDevices, " has %d buttons", bci->num_buttons);
321 break;
322 }
323 case XCB_INPUT_DEVICE_CLASS_TYPE_KEY:
324 qCDebug(lcQpaInputDevices) << " it's a keyboard";
325 break;
326 case XCB_INPUT_DEVICE_CLASS_TYPE_TOUCH:
327#if QT_CONFIG(gestures) && QT_XCB_HAS_TOUCHPAD_GESTURES
328 case XCB_INPUT_DEVICE_CLASS_TYPE_GESTURE:
329#endif // QT_CONFIG(gestures) && QT_XCB_HAS_TOUCHPAD_GESTURES
330 // will be handled in populateTouchDevices()
331 break;
332 default:
333 qCDebug(lcQpaInputDevices) << " has class" << classinfo->type;
334 break;
335 }
336 }
337 bool isTablet = false;
338#if QT_CONFIG(tabletevent)
339 // If we have found the valuators which we expect a tablet to have, it might be a tablet.
340 if (tabletData.valuatorInfo.contains(QXcbAtom::AtomAbsX) &&
341 tabletData.valuatorInfo.contains(QXcbAtom::AtomAbsY) &&
342 tabletData.valuatorInfo.contains(QXcbAtom::AtomAbsPressure))
343 isTablet = true;
344
345 // But we need to be careful not to take the touch and tablet-button devices as tablets.
346 QByteArray nameLower = nameRaw.toLower();
347 QString dbgType = "UNKNOWN"_L1;
348 if (nameLower.contains("eraser")) {
349 isTablet = true;
350 tabletData.pointerType = QPointingDevice::PointerType::Eraser;
351 dbgType = "eraser"_L1;
352 } else if (nameLower.contains("cursor") && !(nameLower.contains("cursor controls") && nameLower.contains("trackball"))) {
353 isTablet = true;
354 tabletData.pointerType = QPointingDevice::PointerType::Cursor;
355 dbgType = "cursor"_L1;
356 } else if (nameLower.contains("wacom") && nameLower.contains("finger touch")) {
357 isTablet = false;
358 } else if ((nameLower.contains("pen") || nameLower.contains("stylus")) && isTablet) {
359 tabletData.pointerType = QPointingDevice::PointerType::Pen;
360 dbgType = "pen"_L1;
361 } else if (nameLower.contains("wacom") && isTablet && !nameLower.contains("touch")) {
362 // combined device (evdev) rather than separate pen/eraser (wacom driver)
363 tabletData.pointerType = QPointingDevice::PointerType::Pen;
364 dbgType = "pen"_L1;
365 } else if (nameLower.contains("aiptek") /* && device == QXcbAtom::AtomKEYBOARD */) {
366 // some "Genius" tablets
367 isTablet = true;
368 tabletData.pointerType = QPointingDevice::PointerType::Pen;
369 dbgType = "pen"_L1;
370 } else if (nameLower.contains("waltop") && nameLower.contains("tablet")) {
371 // other "Genius" tablets
372 // WALTOP International Corp. Slim Tablet
373 isTablet = true;
374 tabletData.pointerType = QPointingDevice::PointerType::Pen;
375 dbgType = "pen"_L1;
376 } else if (nameLower.contains("uc-logic") && isTablet) {
377 tabletData.pointerType = QPointingDevice::PointerType::Pen;
378 dbgType = "pen"_L1;
379 } else if (nameLower.contains("ugee")) {
380 isTablet = true;
381 tabletData.pointerType = QPointingDevice::PointerType::Pen;
382 dbgType = "pen"_L1;
383 } else {
384 isTablet = false;
385 }
386
387 if (isTablet) {
388 tabletData.deviceId = deviceInfo->deviceid;
389 tabletData.name = name;
390 m_tabletData.append(tabletData);
391 qCDebug(lcQpaInputDevices) << " it's a tablet with pointer type" << dbgType;
392 QPointingDevice::Capabilities capsOverride = QInputDevice::Capability::None;
393 if (tabletData.valuatorInfo.contains(QXcbAtom::AtomAbsTiltX))
394 capsOverride.setFlag(QInputDevice::Capability::XTilt);
395 if (tabletData.valuatorInfo.contains(QXcbAtom::AtomAbsTiltY))
396 capsOverride.setFlag(QInputDevice::Capability::YTilt);
397 // TODO can we get USB ID?
398 Q_ASSERT(deviceInfo->deviceid == tabletData.deviceId);
399 const QPointingDevice *dev = tabletToolInstance(master,
400 tabletData.name, deviceInfo->deviceid, 0, 0, tabletData.serialId,
401 tabletData.pointerType, capsOverride);
402 Q_ASSERT(dev);
403 }
404#endif // QT_CONFIG(tabletevent)
405
406 if (scrollingDeviceP) {
407 // Only use legacy wheel button events when we don't have real scroll valuators.
408 scrollingDeviceP->legacyOrientations &= ~scrollingDeviceP->orientations;
409 qCDebug(lcQpaInputDevices) << " it's a scrolling device";
410 }
411
412 if (!isTablet) {
413 TouchDeviceData *dev = populateTouchDevices(deviceInfo, scrollingDeviceP, &used);
414 if (dev && lcQpaInputDevices().isDebugEnabled()) {
415 if (dev->qtTouchDevice->type() == QInputDevice::DeviceType::TouchScreen)
416 qCDebug(lcQpaInputDevices, " it's a touchscreen with type %d capabilities 0x%X max touch points %d",
417 int(dev->qtTouchDevice->type()), qint32(dev->qtTouchDevice->capabilities()),
418 dev->qtTouchDevice->maximumPoints());
419 else if (dev->qtTouchDevice->type() == QInputDevice::DeviceType::TouchPad)
420 qCDebug(lcQpaInputDevices, " it's a touchpad with type %d capabilities 0x%X max touch points %d size %f x %f",
421 int(dev->qtTouchDevice->type()), qint32(dev->qtTouchDevice->capabilities()),
422 dev->qtTouchDevice->maximumPoints(),
423 dev->size.width(), dev->size.height());
424 }
425 }
426
427 if (!QInputDevicePrivate::fromId(deviceInfo->deviceid)) {
428 qCDebug(lcQpaInputDevices) << " it's a mouse";
429 QInputDevice::Capabilities caps = QInputDevice::Capability::Position | QInputDevice::Capability::Hover;
430 if (scrollingDeviceP) {
431 scrollingDeviceP->capabilities |= caps;
432 scrollingDeviceP->buttonCount = buttonCount;
433 if (master)
434 scrollingDeviceP->seatName = master->seatName();
435 QWindowSystemInterface::registerInputDevice(new QXcbScrollingDevice(*scrollingDeviceP, master));
436 used = true;
437 } else {
438 QWindowSystemInterface::registerInputDevice(new QPointingDevice(
439 name, deviceInfo->deviceid,
440 QInputDevice::DeviceType::Mouse, QPointingDevice::PointerType::Generic,
441 caps, 1, buttonCount, (master ? master->seatName() : QString()), QPointingDeviceUniqueId(), master));
442 }
443 }
444
445 if (!used && scrollingDeviceP) {
446 QXcbScrollingDevice *holder = new QXcbScrollingDevice(*scrollingDeviceP, master);
447 holder->deleteLater();
448 }
449}
450
451/*!
452 Find all X11 input devices at startup, or react to a device hierarchy event,
453 and create/delete the corresponding QInputDevice instances as necessary.
454 Afterwards, we expect QInputDevice::devices() to contain only the
455 Qt-relevant devices that \c {xinput list} reports. The parent of each master
456 device is this QXcbConnection object; the parent of each slave is its master.
457*/
458void QXcbConnection::xi2SetupDevices()
459{
460 m_xiMasterPointerIds.clear();
461
462 auto reply = Q_XCB_REPLY(xcb_input_xi_query_device, xcb_connection(), XCB_INPUT_DEVICE_ALL);
463 if (!reply) {
464 qCDebug(lcQpaInputDevices) << "failed to query devices";
465 return;
466 }
467
468 // Start with all known devices; remove the ones that still exist.
469 // Afterwards, previousDevices will be the list of those that we should delete.
470 QList<const QInputDevice *> previousDevices = QInputDevice::devices();
471 // Return true if the device with the given systemId is new;
472 // otherwise remove it from previousDevices and return false.
473 auto newOrKeep = [&previousDevices](qint64 systemId) {
474 // if nothing is removed from previousDevices, it's a new device
475 return !previousDevices.removeIf([systemId](const QInputDevice *dev) {
476 return dev->systemId() == systemId;
477 });
478 };
479
480 // XInput doesn't provide a way to identify "seats"; but each device has an attachment to another device.
481 // So we make up a seatId: master-keyboard-id << 16 | master-pointer-id.
482
483 auto it = xcb_input_xi_query_device_infos_iterator(reply.get());
484 for (; it.rem; xcb_input_xi_device_info_next(&it)) {
485 xcb_input_xi_device_info_t *deviceInfo = it.data;
486 switch (deviceInfo->type) {
487 case XCB_INPUT_DEVICE_TYPE_MASTER_KEYBOARD: {
488 if (newOrKeep(deviceInfo->deviceid)) {
489 auto dev = new QInputDevice(QString::fromUtf8(xcb_input_xi_device_info_name(deviceInfo),
490 xcb_input_xi_device_info_name_length(deviceInfo)),
491 deviceInfo->deviceid, QInputDevice::DeviceType::Keyboard,
492 QString::number(deviceInfo->deviceid << 16 | deviceInfo->attachment, 16), this);
493 QWindowSystemInterface::registerInputDevice(dev);
494 }
495 } break;
496 case XCB_INPUT_DEVICE_TYPE_MASTER_POINTER: {
497 m_xiMasterPointerIds.append(deviceInfo->deviceid);
498 if (newOrKeep(deviceInfo->deviceid)) {
499 auto dev = new QXcbScrollingDevice(QString::fromUtf8(xcb_input_xi_device_info_name(deviceInfo),
500 xcb_input_xi_device_info_name_length(deviceInfo)),
501 deviceInfo->deviceid,
502 QInputDevice::Capability::Position | QInputDevice::Capability::Scroll | QInputDevice::Capability::Hover,
503 32, QString::number(deviceInfo->attachment << 16 | deviceInfo->deviceid, 16), this);
504 QWindowSystemInterface::registerInputDevice(dev);
505 }
506 continue;
507 } break;
508 default:
509 break;
510 }
511 }
512
513 it = xcb_input_xi_query_device_infos_iterator(reply.get());
514 for (; it.rem; xcb_input_xi_device_info_next(&it)) {
515 xcb_input_xi_device_info_t *deviceInfo = it.data;
516 switch (deviceInfo->type) {
517 case XCB_INPUT_DEVICE_TYPE_MASTER_KEYBOARD:
518 case XCB_INPUT_DEVICE_TYPE_MASTER_POINTER:
519 // already registered
520 break;
521 case XCB_INPUT_DEVICE_TYPE_SLAVE_POINTER: {
522 if (newOrKeep(deviceInfo->deviceid)) {
523 m_xiSlavePointerIds.append(deviceInfo->deviceid);
524 QInputDevice *master = const_cast<QInputDevice *>(QInputDevicePrivate::fromId(deviceInfo->attachment));
525 Q_ASSERT(master);
526 xi2SetupSlavePointerDevice(deviceInfo, qobject_cast<QPointingDevice *>(master));
527 }
528 } break;
529 case XCB_INPUT_DEVICE_TYPE_SLAVE_KEYBOARD: {
530 if (newOrKeep(deviceInfo->deviceid)) {
531 QInputDevice *master = const_cast<QInputDevice *>(QInputDevicePrivate::fromId(deviceInfo->attachment));
532 Q_ASSERT(master);
533 QWindowSystemInterface::registerInputDevice(new QInputDevice(
534 QString::fromUtf8(xcb_input_xi_device_info_name(deviceInfo),
535 xcb_input_xi_device_info_name_length(deviceInfo)), deviceInfo->deviceid,
536 QInputDevice::DeviceType::Keyboard, master->seatName(), master));
537 }
538 } break;
539 case XCB_INPUT_DEVICE_TYPE_FLOATING_SLAVE:
540 break;
541 }
542 }
543
544 // previousDevices is now the list of those that are no longer found
545 qCDebug(lcQpaInputDevices) << "removed" << previousDevices;
546 for (auto it = previousDevices.constBegin(); it != previousDevices.constEnd(); ++it) {
547 const auto id = (*it)->systemId();
548 m_xiSlavePointerIds.removeAll(id);
549 m_touchDevices.remove(id);
550 }
551 // A master is the QObject parent of its slaves, so deleting it deletes them
552 // too. Slaves that X no longer attaches stay in previousDevices (the query
553 // loops above skip XCB_INPUT_DEVICE_TYPE_FLOATING_SLAVE), so deleting the
554 // master would destroy them and qDeleteAll would then delete the same
555 // pointers again, corrupting the heap. Drop the children of removed devices
556 // first; walk backwards so that removeAt() does not invalidate the
557 // iteration.
558 for (qsizetype i = previousDevices.size() - 1; i >= 0; --i) {
559 const auto *parentDevice = qobject_cast<const QInputDevice *>(previousDevices.at(i)->parent());
560 if (parentDevice && previousDevices.contains(parentDevice))
561 previousDevices.removeAt(i);
562 }
563 qDeleteAll(previousDevices);
564
565 if (m_xiMasterPointerIds.size() > 1)
566 qCDebug(lcQpaInputDevices) << "multi-pointer X detected";
567}
568
569QXcbConnection::TouchDeviceData *QXcbConnection::touchDeviceForId(int id)
570{
571 TouchDeviceData *dev = nullptr;
572 if (m_touchDevices.contains(id))
573 dev = &m_touchDevices[id];
574 return dev;
575}
576
577QXcbConnection::TouchDeviceData *QXcbConnection::populateTouchDevices(void *info, QXcbScrollingDevicePrivate *scrollingDeviceP, bool *used)
578{
579 auto *deviceInfo = reinterpret_cast<xcb_input_xi_device_info_t *>(info);
580 QPointingDevice::Capabilities caps;
581 QInputDevice::DeviceType type = QInputDevice::DeviceType::Unknown;
582 int maxTouchPoints = 1;
583 bool isTouchDevice = false;
584 bool hasRelativeCoords = false;
585 TouchDeviceData dev;
586 auto classes_it = xcb_input_xi_device_info_classes_iterator(deviceInfo);
587 for (; classes_it.rem; xcb_input_device_class_next(&classes_it)) {
588 xcb_input_device_class_t *classinfo = classes_it.data;
589 switch (classinfo->type) {
590 case XCB_INPUT_DEVICE_CLASS_TYPE_TOUCH: {
591 auto *tci = reinterpret_cast<xcb_input_touch_class_t *>(classinfo);
592 maxTouchPoints = tci->num_touches;
593 qCDebug(lcQpaInputDevices, " has touch class with mode %d", tci->mode);
594 switch (tci->mode) {
595 case XCB_INPUT_TOUCH_MODE_DEPENDENT:
596 type = QInputDevice::DeviceType::TouchPad;
597 break;
598 case XCB_INPUT_TOUCH_MODE_DIRECT:
599 type = QInputDevice::DeviceType::TouchScreen;
600 break;
601 }
602 break;
603 }
604#if QT_CONFIG(gestures) && QT_XCB_HAS_TOUCHPAD_GESTURES
605 case XCB_INPUT_DEVICE_CLASS_TYPE_GESTURE: {
606 // Note that gesture devices can only be touchpads (i.e. dependent devices in XInput
607 // naming convention). According to XI 2.4, the same device can't have touch and
608 // gesture device classes.
609 auto *gci = reinterpret_cast<xcb_input_gesture_class_t *>(classinfo);
610 maxTouchPoints = gci->num_touches;
611 qCDebug(lcQpaInputDevices, " has gesture class");
612 type = QInputDevice::DeviceType::TouchPad;
613 break;
614 }
615#endif // QT_CONFIG(gestures) && QT_XCB_HAS_TOUCHPAD_GESTURES
616 case XCB_INPUT_DEVICE_CLASS_TYPE_VALUATOR: {
617 auto *vci = reinterpret_cast<xcb_input_valuator_class_t *>(classinfo);
618 const QXcbAtom::Atom valuatorAtom = qatom(vci->label);
619 if (valuatorAtom < QXcbAtom::NAtoms) {
620 TouchDeviceData::ValuatorClassInfo info;
621 info.min = fixed3232ToReal(vci->min);
622 info.max = fixed3232ToReal(vci->max);
623 info.number = vci->number;
624 info.label = valuatorAtom;
625 dev.valuatorInfo.append(info);
626 }
627 // Some devices (mice) report a resolution of 0; they will be excluded later,
628 // for now just prevent a division by zero
629 const int vciResolution = vci->resolution ? vci->resolution : 1;
630 if (valuatorAtom == QXcbAtom::AtomAbsMTPositionX)
631 caps |= QInputDevice::Capability::Position | QInputDevice::Capability::NormalizedPosition;
632 else if (valuatorAtom == QXcbAtom::AtomAbsMTTouchMajor)
633 caps |= QInputDevice::Capability::Area;
634 else if (valuatorAtom == QXcbAtom::AtomAbsMTOrientation)
635 dev.providesTouchOrientation = true;
636 else if (valuatorAtom == QXcbAtom::AtomAbsMTPressure || valuatorAtom == QXcbAtom::AtomAbsPressure)
637 caps |= QInputDevice::Capability::Pressure;
638 else if (valuatorAtom == QXcbAtom::AtomRelX) {
639 hasRelativeCoords = true;
640 dev.size.setWidth((fixed3232ToReal(vci->max) - fixed3232ToReal(vci->min)) * 1000.0 / vciResolution);
641 } else if (valuatorAtom == QXcbAtom::AtomRelY) {
642 hasRelativeCoords = true;
643 dev.size.setHeight((fixed3232ToReal(vci->max) - fixed3232ToReal(vci->min)) * 1000.0 / vciResolution);
644 } else if (valuatorAtom == QXcbAtom::AtomAbsX) {
645 caps |= QInputDevice::Capability::Position;
646 dev.size.setWidth((fixed3232ToReal(vci->max) - fixed3232ToReal(vci->min)) * 1000.0 / vciResolution);
647 } else if (valuatorAtom == QXcbAtom::AtomAbsY) {
648 caps |= QInputDevice::Capability::Position;
649 dev.size.setHeight((fixed3232ToReal(vci->max) - fixed3232ToReal(vci->min)) * 1000.0 / vciResolution);
650 } else if (valuatorAtom == QXcbAtom::AtomRelVertWheel || valuatorAtom == QXcbAtom::AtomRelHorizWheel) {
651 caps |= QInputDevice::Capability::Scroll;
652 }
653 break;
654 }
655 default:
656 break;
657 }
658 }
659 if (type == QInputDevice::DeviceType::Unknown && caps && hasRelativeCoords) {
660 type = QInputDevice::DeviceType::TouchPad;
661 if (dev.size.width() < 10 || dev.size.height() < 10 ||
662 dev.size.width() > 10000 || dev.size.height() > 10000)
663 dev.size = QSizeF(130, 110);
664 }
665 if (!isAtLeastXI22() || type == QInputDevice::DeviceType::TouchPad)
666 caps |= QInputDevice::Capability::MouseEmulation;
667
668 if (type == QInputDevice::DeviceType::TouchScreen || type == QInputDevice::DeviceType::TouchPad) {
669 QInputDevice *master = const_cast<QInputDevice *>(QInputDevicePrivate::fromId(deviceInfo->attachment));
670 Q_ASSERT(master);
671 if (scrollingDeviceP) {
672 // valuators were already discovered in QXcbConnection::xi2SetupSlavePointerDevice, so just finish initialization
673 scrollingDeviceP->deviceType = type;
674 scrollingDeviceP->pointerType = QPointingDevice::PointerType::Finger;
675 scrollingDeviceP->capabilities |= caps;
676 scrollingDeviceP->maximumTouchPoints = maxTouchPoints;
677 scrollingDeviceP->buttonCount = 3;
678 scrollingDeviceP->seatName = master->seatName();
679 dev.qtTouchDevice = new QXcbScrollingDevice(*scrollingDeviceP, master);
680 if (Q_UNLIKELY(!caps.testFlag(QInputDevice::Capability::Scroll)))
681 qCDebug(lcQpaInputDevices) << "unexpectedly missing RelVert/HorizWheel atoms for touchpad with scroll capability" << dev.qtTouchDevice;
682 *used = true;
683 } else {
684 dev.qtTouchDevice = new QPointingDevice(QString::fromUtf8(xcb_input_xi_device_info_name(deviceInfo),
685 xcb_input_xi_device_info_name_length(deviceInfo)),
686 deviceInfo->deviceid,
687 type, QPointingDevice::PointerType::Finger, caps, maxTouchPoints, 0,
688 master->seatName(), QPointingDeviceUniqueId(), master);
689 }
690 if (caps != 0)
691 QWindowSystemInterface::registerInputDevice(dev.qtTouchDevice);
692 m_touchDevices[deviceInfo->deviceid] = dev;
693 isTouchDevice = true;
694 }
695
696 return isTouchDevice ? &m_touchDevices[deviceInfo->deviceid] : nullptr;
697}
698
699static inline qreal fixed1616ToReal(xcb_input_fp1616_t val)
700{
701 return qreal(val) / 0x10000;
702}
703
704void QXcbConnection::xi2HandleEvent(xcb_ge_event_t *event)
705{
706 auto *xiEvent = reinterpret_cast<qt_xcb_input_device_event_t *>(event);
707 setTime(xiEvent->time);
708 if (m_xiSlavePointerIds.contains(xiEvent->deviceid) && xiEvent->event_type != XCB_INPUT_PROPERTY) {
709 if (!m_duringSystemMoveResize)
710 return;
711 if (xiEvent->event == XCB_NONE)
712 return;
713
714 if (xiEvent->event_type == XCB_INPUT_BUTTON_RELEASE
715 && xiEvent->detail == XCB_BUTTON_INDEX_1 ) {
716 abortSystemMoveResize(xiEvent->event);
717 } else if (xiEvent->event_type == XCB_INPUT_TOUCH_END) {
718 abortSystemMoveResize(xiEvent->event);
719 return;
720 } else {
721 return;
722 }
723 }
724 int sourceDeviceId = xiEvent->deviceid; // may be the master id
725 qt_xcb_input_device_event_t *xiDeviceEvent = nullptr;
726 xcb_input_enter_event_t *xiEnterEvent = nullptr;
727 QXcbWindowEventListener *eventListener = nullptr;
728
729 switch (xiEvent->event_type) {
730 case XCB_INPUT_BUTTON_PRESS:
731 case XCB_INPUT_BUTTON_RELEASE:
732 case XCB_INPUT_MOTION:
733 case XCB_INPUT_TOUCH_BEGIN:
734 case XCB_INPUT_TOUCH_UPDATE:
735 case XCB_INPUT_TOUCH_END:
736 {
737 xiDeviceEvent = xiEvent;
738 eventListener = windowEventListenerFromId(xiDeviceEvent->event);
739 sourceDeviceId = xiDeviceEvent->sourceid; // use the actual device id instead of the master
740 break;
741 }
742#if QT_CONFIG(gestures) && QT_XCB_HAS_TOUCHPAD_GESTURES
743 case XCB_INPUT_GESTURE_PINCH_BEGIN:
744 case XCB_INPUT_GESTURE_PINCH_UPDATE:
745 case XCB_INPUT_GESTURE_PINCH_END:
746 xi2HandleGesturePinchEvent(event);
747 return;
748 case XCB_INPUT_GESTURE_SWIPE_BEGIN:
749 case XCB_INPUT_GESTURE_SWIPE_UPDATE:
750 case XCB_INPUT_GESTURE_SWIPE_END:
751 xi2HandleGestureSwipeEvent(event);
752 return;
753#endif // QT_CONFIG(gestures) && QT_XCB_HAS_TOUCHPAD_GESTURES
754 case XCB_INPUT_ENTER:
755 case XCB_INPUT_LEAVE: {
756 xiEnterEvent = reinterpret_cast<xcb_input_enter_event_t *>(event);
757 eventListener = windowEventListenerFromId(xiEnterEvent->event);
758 sourceDeviceId = xiEnterEvent->sourceid; // use the actual device id instead of the master
759 break;
760 }
761 case XCB_INPUT_HIERARCHY:
762 xi2HandleHierarchyEvent(event);
763 return;
764 case XCB_INPUT_DEVICE_CHANGED:
765 xi2HandleDeviceChangedEvent(event);
766 return;
767 default:
768 break;
769 }
770
771 if (eventListener) {
772 if (eventListener->handleNativeEvent(reinterpret_cast<xcb_generic_event_t *>(event)))
773 return;
774 }
775
776#if QT_CONFIG(tabletevent)
777 if (!xiEnterEvent) {
778 // TODO we need the UID here; tabletDataForDevice doesn't have enough to go on (?)
779 QXcbConnection::TabletData *tablet = tabletDataForDevice(sourceDeviceId);
780 if (tablet && xi2HandleTabletEvent(event, tablet))
781 return;
782 }
783#endif // QT_CONFIG(tabletevent)
784
785 if (auto device = QPointingDevicePrivate::pointingDeviceById(sourceDeviceId))
786 xi2HandleScrollEvent(event, device);
787 else
788 qCDebug(lcQpaXInputEvents) << "scroll event from unregistered device" << sourceDeviceId;
789
790 if (xiDeviceEvent) {
791 switch (xiDeviceEvent->event_type) {
792 case XCB_INPUT_BUTTON_PRESS:
793 case XCB_INPUT_BUTTON_RELEASE:
794 case XCB_INPUT_MOTION:
795 if (eventListener && !(xiDeviceEvent->flags & XCB_INPUT_POINTER_EVENT_FLAGS_POINTER_EMULATED))
796 eventListener->handleXIMouseEvent(event);
797 break;
798
799 case XCB_INPUT_TOUCH_BEGIN:
800 case XCB_INPUT_TOUCH_UPDATE:
801 case XCB_INPUT_TOUCH_END:
802 if (Q_UNLIKELY(lcQpaXInputEvents().isDebugEnabled()))
803 qCDebug(lcQpaXInputEvents, "XI2 touch event type %d seq %d detail %d pos %6.1f, %6.1f root pos %6.1f, %6.1f on window %x",
804 event->event_type, xiDeviceEvent->sequence, xiDeviceEvent->detail,
805 fixed1616ToReal(xiDeviceEvent->event_x), fixed1616ToReal(xiDeviceEvent->event_y),
806 fixed1616ToReal(xiDeviceEvent->root_x), fixed1616ToReal(xiDeviceEvent->root_y),xiDeviceEvent->event);
807 if (QXcbWindow *platformWindow = platformWindowFromId(xiDeviceEvent->event)) {
808 xi2ProcessTouch(xiDeviceEvent, platformWindow);
809 } else { // When the window cannot be matched, delete it from touchPoints
810 if (TouchDeviceData *dev = touchDeviceForId(xiDeviceEvent->sourceid))
811 dev->touchPoints.remove((xiDeviceEvent->detail % INT_MAX));
812 }
813 break;
814 }
815 } else if (xiEnterEvent && eventListener) {
816 switch (xiEnterEvent->event_type) {
817 case XCB_INPUT_ENTER:
818 case XCB_INPUT_LEAVE:
819 eventListener->handleXIEnterLeave(event);
820 break;
821 }
822 }
823}
824
825bool QXcbConnection::isTouchScreen(int id)
826{
827 auto device = touchDeviceForId(id);
828 return device && device->qtTouchDevice->type() == QInputDevice::DeviceType::TouchScreen;
829}
830
831void QXcbConnection::xi2ProcessTouch(void *xiDevEvent, QXcbWindow *platformWindow)
832{
833 auto *xiDeviceEvent = reinterpret_cast<xcb_input_touch_begin_event_t *>(xiDevEvent);
834 TouchDeviceData *dev = touchDeviceForId(xiDeviceEvent->sourceid);
835 if (!dev) {
836 qCDebug(lcQpaXInputEvents) << "didn't find the dev for given sourceid - " << xiDeviceEvent->sourceid
837 << ", try to repopulate xi2 devices";
838 xi2SetupDevices();
839 dev = touchDeviceForId(xiDeviceEvent->sourceid);
840 if (!dev) {
841 qCDebug(lcQpaXInputEvents) << "still can't find the dev for it, give up.";
842 return;
843 }
844 }
845 const bool firstTouch = dev->touchPoints.isEmpty();
846 if (xiDeviceEvent->event_type == XCB_INPUT_TOUCH_BEGIN) {
847 QWindowSystemInterface::TouchPoint tp;
848 tp.id = xiDeviceEvent->detail % INT_MAX;
849 tp.state = QEventPoint::State::Pressed;
850 tp.pressure = -1.0;
851 dev->touchPoints[tp.id] = tp;
852 }
853 QWindowSystemInterface::TouchPoint &touchPoint = dev->touchPoints[xiDeviceEvent->detail];
854 QXcbScreen* screen = platformWindow->xcbScreen();
855 qreal x = fixed1616ToReal(xiDeviceEvent->root_x);
856 qreal y = fixed1616ToReal(xiDeviceEvent->root_y);
857 qreal nx = -1.0, ny = -1.0;
858 qreal w = 0.0, h = 0.0;
859 bool majorAxisIsY = touchPoint.area.height() > touchPoint.area.width();
860 for (const TouchDeviceData::ValuatorClassInfo &vci : std::as_const(dev->valuatorInfo)) {
861 double value;
862 if (!xi2GetValuatorValueIfSet(xiDeviceEvent, vci.number, &value))
863 continue;
864 if (Q_UNLIKELY(lcQpaXInputEvents().isDebugEnabled()))
865 qCDebug(lcQpaXInputEvents, " valuator %20s value %lf from range %lf -> %lf",
866 atomName(atom(vci.label)).constData(), value, vci.min, vci.max);
867 if (value > vci.max)
868 value = vci.max;
869 if (value < vci.min)
870 value = vci.min;
871 qreal valuatorNormalized = (value - vci.min) / (vci.max - vci.min);
872 if (vci.label == QXcbAtom::AtomRelX) {
873 nx = valuatorNormalized;
874 } else if (vci.label == QXcbAtom::AtomRelY) {
875 ny = valuatorNormalized;
876 } else if (vci.label == QXcbAtom::AtomAbsX) {
877 nx = valuatorNormalized;
878 } else if (vci.label == QXcbAtom::AtomAbsY) {
879 ny = valuatorNormalized;
880 } else if (vci.label == QXcbAtom::AtomAbsMTPositionX) {
881 nx = valuatorNormalized;
882 } else if (vci.label == QXcbAtom::AtomAbsMTPositionY) {
883 ny = valuatorNormalized;
884 } else if (vci.label == QXcbAtom::AtomAbsMTTouchMajor) {
885 const qreal sw = screen->geometry().width();
886 const qreal sh = screen->geometry().height();
887 w = valuatorNormalized * qHypot(sw, sh);
888 } else if (vci.label == QXcbAtom::AtomAbsMTTouchMinor) {
889 const qreal sw = screen->geometry().width();
890 const qreal sh = screen->geometry().height();
891 h = valuatorNormalized * qHypot(sw, sh);
892 } else if (vci.label == QXcbAtom::AtomAbsMTOrientation) {
893 // Find the closest axis.
894 // 0 corresponds to the Y axis, vci.max to the X axis.
895 // Flipping over the Y axis and rotating by 180 degrees
896 // don't change the result, so normalize value to range
897 // [0, vci.max] first.
898 value = qAbs(value);
899 while (value > vci.max)
900 value -= 2 * vci.max;
901 value = qAbs(value);
902 majorAxisIsY = value < vci.max - value;
903 } else if (vci.label == QXcbAtom::AtomAbsMTPressure || vci.label == QXcbAtom::AtomAbsPressure) {
904 touchPoint.pressure = valuatorNormalized;
905 }
906
907 }
908 // If any value was not updated, use the last-known value.
909 if (nx == -1.0) {
910 x = touchPoint.area.center().x();
911 nx = x / screen->geometry().width();
912 }
913 if (ny == -1.0) {
914 y = touchPoint.area.center().y();
915 ny = y / screen->geometry().height();
916 }
917 if (xiDeviceEvent->event_type != XCB_INPUT_TOUCH_END) {
918 if (!dev->providesTouchOrientation) {
919 if (w == 0.0)
920 w = touchPoint.area.width();
921 h = w;
922 } else {
923 if (w == 0.0)
924 w = qMax(touchPoint.area.width(), touchPoint.area.height());
925 if (h == 0.0)
926 h = qMin(touchPoint.area.width(), touchPoint.area.height());
927 if (majorAxisIsY)
928 qSwap(w, h);
929 }
930 }
931
932 switch (xiDeviceEvent->event_type) {
933 case XCB_INPUT_TOUCH_BEGIN:
934 if (firstTouch) {
935 dev->firstPressedPosition = QPointF(x, y);
936 dev->firstPressedNormalPosition = QPointF(nx, ny);
937 }
938 dev->pointPressedPosition.insert(touchPoint.id, QPointF(x, y));
939
940 // Touches must be accepted when we are grabbing touch events. Otherwise the entire sequence
941 // will get replayed when the grab ends.
942 if (m_xiGrab) {
943 xcb_input_xi_allow_events(xcb_connection(), XCB_CURRENT_TIME, xiDeviceEvent->deviceid,
944 XCB_INPUT_EVENT_MODE_ACCEPT_TOUCH,
945 xiDeviceEvent->detail, xiDeviceEvent->event);
946 }
947 break;
948 case XCB_INPUT_TOUCH_UPDATE:
949 if (dev->qtTouchDevice->type() == QInputDevice::DeviceType::TouchPad && dev->pointPressedPosition.value(touchPoint.id) == QPointF(x, y)) {
950 qreal dx = (nx - dev->firstPressedNormalPosition.x()) *
951 dev->size.width() * screen->geometry().width() / screen->physicalSize().width();
952 qreal dy = (ny - dev->firstPressedNormalPosition.y()) *
953 dev->size.height() * screen->geometry().height() / screen->physicalSize().height();
954 x = dev->firstPressedPosition.x() + dx;
955 y = dev->firstPressedPosition.y() + dy;
956 touchPoint.state = QEventPoint::State::Updated;
957 } else if (touchPoint.area.center() != QPoint(x, y)) {
958 touchPoint.state = QEventPoint::State::Updated;
959 if (dev->qtTouchDevice->type() == QInputDevice::DeviceType::TouchPad)
960 dev->pointPressedPosition[touchPoint.id] = QPointF(x, y);
961 }
962
963 if (dev->qtTouchDevice->type() == QInputDevice::DeviceType::TouchScreen &&
964 xiDeviceEvent->event == m_startSystemMoveResizeInfo.window &&
965 xiDeviceEvent->sourceid == m_startSystemMoveResizeInfo.deviceid &&
966 xiDeviceEvent->detail == m_startSystemMoveResizeInfo.pointid) {
967 QXcbWindow *window = platformWindowFromId(m_startSystemMoveResizeInfo.window);
968 if (window) {
969 xcb_input_xi_allow_events(xcb_connection(), XCB_CURRENT_TIME, xiDeviceEvent->deviceid,
970 XCB_INPUT_EVENT_MODE_REJECT_TOUCH,
971 xiDeviceEvent->detail, xiDeviceEvent->event);
972 window->doStartSystemMoveResize(QPoint(x, y), m_startSystemMoveResizeInfo.edges);
973 m_startSystemMoveResizeInfo.window = XCB_NONE;
974 }
975 }
976 break;
977 case XCB_INPUT_TOUCH_END:
978 touchPoint.state = QEventPoint::State::Released;
979 if (dev->qtTouchDevice->type() == QInputDevice::DeviceType::TouchPad && dev->pointPressedPosition.value(touchPoint.id) == QPointF(x, y)) {
980 qreal dx = (nx - dev->firstPressedNormalPosition.x()) *
981 dev->size.width() * screen->geometry().width() / screen->physicalSize().width();
982 qreal dy = (ny - dev->firstPressedNormalPosition.y()) *
983 dev->size.width() * screen->geometry().width() / screen->physicalSize().width();
984 x = dev->firstPressedPosition.x() + dx;
985 y = dev->firstPressedPosition.y() + dy;
986 }
987 dev->pointPressedPosition.remove(touchPoint.id);
988 }
989 touchPoint.area = QRectF(x - w/2, y - h/2, w, h);
990 touchPoint.normalPosition = QPointF(nx, ny);
991
992 if (Q_UNLIKELY(lcQpaXInputEvents().isDebugEnabled()))
993 qCDebug(lcQpaXInputEvents) << " touchpoint " << touchPoint.id << " state " << touchPoint.state << " pos norm " << touchPoint.normalPosition <<
994 " area " << touchPoint.area << " pressure " << touchPoint.pressure;
995 Qt::KeyboardModifiers modifiers = keyboard()->translateModifiers(xiDeviceEvent->mods.effective);
996 QWindowSystemInterface::handleTouchEvent(platformWindow->window(), xiDeviceEvent->time, dev->qtTouchDevice, dev->touchPoints.values(), modifiers);
997 if (touchPoint.state == QEventPoint::State::Released)
998 // If a touchpoint was released, we can forget it, because the ID won't be reused.
999 dev->touchPoints.remove(touchPoint.id);
1000 else
1001 // Make sure that we don't send TouchPointPressed/Moved in more than one QTouchEvent
1002 // with this touch point if the next XI2 event is about a different touch point.
1003 touchPoint.state = QEventPoint::State::Stationary;
1004}
1005
1006bool QXcbConnection::startSystemMoveResizeForTouch(xcb_window_t window, int edges)
1007{
1008 QHash<int, TouchDeviceData>::const_iterator devIt = m_touchDevices.constBegin();
1009 for (; devIt != m_touchDevices.constEnd(); ++devIt) {
1010 TouchDeviceData deviceData = devIt.value();
1011 if (deviceData.qtTouchDevice->type() == QInputDevice::DeviceType::TouchScreen) {
1012 auto pointIt = deviceData.touchPoints.constBegin();
1013 for (; pointIt != deviceData.touchPoints.constEnd(); ++pointIt) {
1014 QEventPoint::State state = pointIt.value().state;
1015 if (state == QEventPoint::State::Updated || state == QEventPoint::State::Pressed || state == QEventPoint::State::Stationary) {
1016 m_startSystemMoveResizeInfo.window = window;
1017 m_startSystemMoveResizeInfo.deviceid = devIt.key();
1018 m_startSystemMoveResizeInfo.pointid = pointIt.key();
1019 m_startSystemMoveResizeInfo.edges = edges;
1020 setDuringSystemMoveResize(true);
1021 qCDebug(lcQpaInputDevices) << "triggered system move or resize from touch";
1022 return true;
1023 }
1024 }
1025 }
1026 }
1027 return false;
1028}
1029
1030void QXcbConnection::abortSystemMoveResize(xcb_window_t window)
1031{
1032 qCDebug(lcQpaInputDevices) << "sending client message NET_WM_MOVERESIZE_CANCEL to window: " << window;
1033 m_startSystemMoveResizeInfo.window = XCB_NONE;
1034
1035 const xcb_atom_t moveResize = connection()->atom(QXcbAtom::Atom_NET_WM_MOVERESIZE);
1036 xcb_client_message_event_t xev;
1037 xev.response_type = XCB_CLIENT_MESSAGE;
1038 xev.type = moveResize;
1039 xev.sequence = 0;
1040 xev.window = window;
1041 xev.format = 32;
1042 xev.data.data32[0] = 0;
1043 xev.data.data32[1] = 0;
1044 xev.data.data32[2] = 11; // _NET_WM_MOVERESIZE_CANCEL
1045 xev.data.data32[3] = 0;
1046 xev.data.data32[4] = 0;
1047 xcb_send_event(xcb_connection(), false, primaryScreen()->root(),
1048 XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT | XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY,
1049 (const char *)&xev);
1050
1051 m_duringSystemMoveResize = false;
1052}
1053
1054bool QXcbConnection::isDuringSystemMoveResize() const
1055{
1056 return m_duringSystemMoveResize;
1057}
1058
1059void QXcbConnection::setDuringSystemMoveResize(bool during)
1060{
1061 m_duringSystemMoveResize = during;
1062}
1063
1064bool QXcbConnection::xi2SetMouseGrabEnabled(xcb_window_t w, bool grab)
1065{
1066 bool ok = false;
1067
1068 if (grab) { // grab
1069 uint8_t mask[8] = {};
1070 setXcbMask(mask, XCB_INPUT_BUTTON_PRESS);
1071 setXcbMask(mask, XCB_INPUT_BUTTON_RELEASE);
1072 setXcbMask(mask, XCB_INPUT_MOTION);
1073 setXcbMask(mask, XCB_INPUT_ENTER);
1074 setXcbMask(mask, XCB_INPUT_LEAVE);
1075 if (isAtLeastXI22()) {
1076 setXcbMask(mask, XCB_INPUT_TOUCH_BEGIN);
1077 setXcbMask(mask, XCB_INPUT_TOUCH_UPDATE);
1078 setXcbMask(mask, XCB_INPUT_TOUCH_END);
1079 }
1080#if QT_CONFIG(gestures) && QT_XCB_HAS_TOUCHPAD_GESTURES
1081 if (isAtLeastXI24()) {
1082 setXcbMask(mask, XCB_INPUT_GESTURE_PINCH_BEGIN);
1083 setXcbMask(mask, XCB_INPUT_GESTURE_PINCH_UPDATE);
1084 setXcbMask(mask, XCB_INPUT_GESTURE_PINCH_END);
1085 setXcbMask(mask, XCB_INPUT_GESTURE_SWIPE_BEGIN);
1086 setXcbMask(mask, XCB_INPUT_GESTURE_SWIPE_UPDATE);
1087 setXcbMask(mask, XCB_INPUT_GESTURE_SWIPE_END);
1088 }
1089#endif // QT_CONFIG(gestures) && QT_XCB_HAS_TOUCHPAD_GESTURES
1090
1091 for (int id : std::as_const(m_xiMasterPointerIds)) {
1092 xcb_generic_error_t *error = nullptr;
1093 auto cookie = xcb_input_xi_grab_device(xcb_connection(), w, XCB_CURRENT_TIME, XCB_CURSOR_NONE, id,
1094 XCB_INPUT_GRAB_MODE_22_ASYNC, XCB_INPUT_GRAB_MODE_22_ASYNC,
1095 false, 2, reinterpret_cast<uint32_t *>(mask));
1096 auto *reply = xcb_input_xi_grab_device_reply(xcb_connection(), cookie, &error);
1097 if (error) {
1098 qCDebug(lcQpaXInput, "failed to grab events for device %d on window %x"
1099 "(error code %d)", id, w, error->error_code);
1100 free(error);
1101 } else {
1102 // Managed to grab at least one of master pointers, that should be enough
1103 // to properly dismiss windows that rely on mouse grabbing.
1104 ok = true;
1105 }
1106 free(reply);
1107 }
1108 } else { // ungrab
1109 for (int id : std::as_const(m_xiMasterPointerIds)) {
1110 auto cookie = xcb_input_xi_ungrab_device_checked(xcb_connection(), XCB_CURRENT_TIME, id);
1111 xcb_generic_error_t *error = xcb_request_check(xcb_connection(), cookie);
1112 if (error) {
1113 qCDebug(lcQpaXInput, "XIUngrabDevice failed - id: %d (error code %d)", id, error->error_code);
1114 free(error);
1115 }
1116 }
1117 // XIUngrabDevice does not seem to wait for a reply from X server (similar to
1118 // xcb_ungrab_pointer). Ungrabbing won't fail, unless NoSuchExtension error
1119 // has occurred due to a programming error somewhere else in the stack. That
1120 // would mean that things will crash soon anyway.
1121 ok = true;
1122 }
1123
1124 if (ok)
1125 m_xiGrab = grab;
1126
1127 return ok;
1128}
1129
1130void QXcbConnection::xi2HandleHierarchyEvent(void *event)
1131{
1132 auto *xiEvent = reinterpret_cast<xcb_input_hierarchy_event_t *>(event);
1133 // We care about hotplugged devices (slaves) and master devices.
1134 // We don't report anything for DEVICE_ENABLED or DEVICE_DISABLED
1135 // (but often that goes with adding or removal anyway).
1136 // We don't react to SLAVE_ATTACHED or SLAVE_DETACHED either.
1137 if (xiEvent->flags & (XCB_INPUT_HIERARCHY_MASK_MASTER_ADDED |
1138 XCB_INPUT_HIERARCHY_MASK_MASTER_REMOVED |
1139 XCB_INPUT_HIERARCHY_MASK_SLAVE_REMOVED |
1140 XCB_INPUT_HIERARCHY_MASK_SLAVE_ADDED))
1141 xi2SetupDevices();
1142}
1143
1144#if QT_XCB_HAS_TOUCHPAD_GESTURES
1145void QXcbConnection::xi2HandleGesturePinchEvent(void *event)
1146{
1147 auto *xiEvent = reinterpret_cast<qt_xcb_input_pinch_event_t *>(event);
1148
1149 if (Q_UNLIKELY(lcQpaXInputEvents().isDebugEnabled())) {
1150 qCDebug(lcQpaXInputEvents, "XI2 gesture event type %d seq %d fingers %d pos %6.1f, "
1151 "%6.1f root pos %6.1f, %6.1f delta_angle %6.1f scale %6.1f on window %x",
1152 xiEvent->event_type, xiEvent->sequence, xiEvent->detail,
1153 fixed1616ToReal(xiEvent->event_x), fixed1616ToReal(xiEvent->event_y),
1154 fixed1616ToReal(xiEvent->root_x), fixed1616ToReal(xiEvent->root_y),
1155 fixed1616ToReal(xiEvent->delta_angle), fixed1616ToReal(xiEvent->scale),
1156 xiEvent->event);
1157 }
1158 QXcbWindow *platformWindow = platformWindowFromId(xiEvent->event);
1159 if (!platformWindow)
1160 return;
1161
1162 setTime(xiEvent->time);
1163
1164 TouchDeviceData *dev = touchDeviceForId(xiEvent->sourceid);
1165 Q_ASSERT(dev);
1166
1167 uint32_t fingerCount = xiEvent->detail;
1168
1169 switch (xiEvent->event_type) {
1170 case XCB_INPUT_GESTURE_PINCH_BEGIN:
1171 // Gestures must be accepted when we are grabbing gesture events. Otherwise the entire
1172 // sequence will get replayed when the grab ends.
1173 if (m_xiGrab) {
1174 xcb_input_xi_allow_events(xcb_connection(), XCB_CURRENT_TIME, xiEvent->deviceid,
1175 XCB_INPUT_EVENT_MODE_ASYNC_DEVICE, 0, xiEvent->event);
1176 }
1177 m_lastPinchScale = 1.0;
1178 QWindowSystemInterface::handleGestureEvent(platformWindow->window(), xiEvent->time,
1179 dev->qtTouchDevice,
1180 Qt::BeginNativeGesture,
1181 platformWindow->lastPointerPosition(),
1182 platformWindow->lastPointerGlobalPosition(),
1183 fingerCount);
1184 break;
1185
1186 case XCB_INPUT_GESTURE_PINCH_UPDATE: {
1187 qreal rotationDelta = fixed1616ToReal(xiEvent->delta_angle);
1188 qreal scale = fixed1616ToReal(xiEvent->scale);
1189 qreal scaleDelta = scale - m_lastPinchScale;
1190 m_lastPinchScale = scale;
1191
1192 QPointF delta = QPointF(fixed1616ToReal(xiEvent->delta_x),
1193 fixed1616ToReal(xiEvent->delta_y));
1194
1195 if (!delta.isNull()) {
1196 QWindowSystemInterface::handleGestureEventWithValueAndDelta(
1197 platformWindow->window(), xiEvent->time, dev->qtTouchDevice,
1198 Qt::PanNativeGesture, 0, delta,
1199 platformWindow->lastPointerPosition(),
1200 platformWindow->lastPointerGlobalPosition(),
1201 fingerCount);
1202 }
1203 if (rotationDelta != 0) {
1204 QWindowSystemInterface::handleGestureEventWithRealValue(
1205 platformWindow->window(), xiEvent->time, dev->qtTouchDevice,
1206 Qt::RotateNativeGesture,
1207 rotationDelta,
1208 platformWindow->lastPointerPosition(),
1209 platformWindow->lastPointerGlobalPosition(),
1210 fingerCount);
1211 }
1212 if (scaleDelta != 0) {
1213 QWindowSystemInterface::handleGestureEventWithRealValue(
1214 platformWindow->window(), xiEvent->time, dev->qtTouchDevice,
1215 Qt::ZoomNativeGesture,
1216 scaleDelta,
1217 platformWindow->lastPointerPosition(),
1218 platformWindow->lastPointerGlobalPosition(),
1219 fingerCount);
1220 }
1221 break;
1222 }
1223 case XCB_INPUT_GESTURE_PINCH_END:
1224 QWindowSystemInterface::handleGestureEvent(platformWindow->window(), xiEvent->time,
1225 dev->qtTouchDevice,
1226 Qt::EndNativeGesture,
1227 platformWindow->lastPointerPosition(),
1228 platformWindow->lastPointerGlobalPosition(),
1229 fingerCount);
1230 break;
1231 }
1232}
1233
1234void QXcbConnection::xi2HandleGestureSwipeEvent(void *event)
1235{
1236 auto *xiEvent = reinterpret_cast<qt_xcb_input_swipe_event_t *>(event);
1237
1238 if (Q_UNLIKELY(lcQpaXInputEvents().isDebugEnabled())) {
1239 qCDebug(lcQpaXInputEvents, "XI2 gesture event type %d seq %d detail %d pos %6.1f, %6.1f root pos %6.1f, %6.1f on window %x",
1240 xiEvent->event_type, xiEvent->sequence, xiEvent->detail,
1241 fixed1616ToReal(xiEvent->event_x), fixed1616ToReal(xiEvent->event_y),
1242 fixed1616ToReal(xiEvent->root_x), fixed1616ToReal(xiEvent->root_y),
1243 xiEvent->event);
1244 }
1245 QXcbWindow *platformWindow = platformWindowFromId(xiEvent->event);
1246 if (!platformWindow)
1247 return;
1248
1249 setTime(xiEvent->time);
1250
1251 TouchDeviceData *dev = touchDeviceForId(xiEvent->sourceid);
1252 Q_ASSERT(dev);
1253
1254 uint32_t fingerCount = xiEvent->detail;
1255
1256 switch (xiEvent->event_type) {
1257 case XCB_INPUT_GESTURE_SWIPE_BEGIN:
1258 // Gestures must be accepted when we are grabbing gesture events. Otherwise the entire
1259 // sequence will get replayed when the grab ends.
1260 if (m_xiGrab) {
1261 xcb_input_xi_allow_events(xcb_connection(), XCB_CURRENT_TIME, xiEvent->deviceid,
1262 XCB_INPUT_EVENT_MODE_ASYNC_DEVICE, 0, xiEvent->event);
1263 }
1264 QWindowSystemInterface::handleGestureEvent(platformWindow->window(), xiEvent->time,
1265 dev->qtTouchDevice,
1266 Qt::BeginNativeGesture,
1267 platformWindow->lastPointerPosition(),
1268 platformWindow->lastPointerGlobalPosition(),
1269 fingerCount);
1270 break;
1271 case XCB_INPUT_GESTURE_SWIPE_UPDATE: {
1272 QPointF delta = QPointF(fixed1616ToReal(xiEvent->delta_x),
1273 fixed1616ToReal(xiEvent->delta_y));
1274
1275 if (xiEvent->delta_x != 0 || xiEvent->delta_y != 0) {
1276 QWindowSystemInterface::handleGestureEventWithValueAndDelta(
1277 platformWindow->window(), xiEvent->time, dev->qtTouchDevice,
1278 Qt::PanNativeGesture, 0, delta,
1279 platformWindow->lastPointerPosition(),
1280 platformWindow->lastPointerGlobalPosition(),
1281 fingerCount);
1282 }
1283 break;
1284 }
1285 case XCB_INPUT_GESTURE_SWIPE_END:
1286 QWindowSystemInterface::handleGestureEvent(platformWindow->window(), xiEvent->time,
1287 dev->qtTouchDevice,
1288 Qt::EndNativeGesture,
1289 platformWindow->lastPointerPosition(),
1290 platformWindow->lastPointerGlobalPosition(),
1291 fingerCount);
1292 break;
1293 }
1294}
1295
1296#else // QT_XCB_HAS_TOUCHPAD_GESTURES
1297void QXcbConnection::xi2HandleGesturePinchEvent(void*) {}
1298void QXcbConnection::xi2HandleGestureSwipeEvent(void*) {}
1299#endif
1300
1301void QXcbConnection::xi2HandleDeviceChangedEvent(void *event)
1302{
1303 auto *xiEvent = reinterpret_cast<xcb_input_device_changed_event_t *>(event);
1304 switch (xiEvent->reason) {
1305 case XCB_INPUT_CHANGE_REASON_DEVICE_CHANGE: {
1306 // Don't call xi2SetupSlavePointerDevice() again for an already-known device, and never for a master.
1307 if (m_xiMasterPointerIds.contains(xiEvent->deviceid) || m_xiSlavePointerIds.contains(xiEvent->deviceid))
1308 return;
1309 auto reply = Q_XCB_REPLY(xcb_input_xi_query_device, xcb_connection(), xiEvent->sourceid);
1310 if (!reply || reply->num_infos <= 0)
1311 return;
1312 auto it = xcb_input_xi_query_device_infos_iterator(reply.get());
1313 xi2SetupSlavePointerDevice(it.data);
1314 break;
1315 }
1316 case XCB_INPUT_CHANGE_REASON_SLAVE_SWITCH: {
1317 if (auto *scrollingDevice = scrollingDeviceForId(xiEvent->sourceid))
1318 xi2UpdateScrollingDevice(scrollingDevice);
1319 break;
1320 }
1321 default:
1322 qCDebug(lcQpaXInputEvents, "unknown device-changed-event (device %d)", xiEvent->sourceid);
1323 break;
1324 }
1325}
1326
1327void QXcbConnection::xi2UpdateScrollingDevice(QInputDevice *dev)
1328{
1329 QXcbScrollingDevice *scrollDev = qobject_cast<QXcbScrollingDevice *>(dev);
1330 if (!scrollDev || !scrollDev->capabilities().testFlag(QInputDevice::Capability::Scroll))
1331 return;
1332 QXcbScrollingDevicePrivate *scrollingDevice = QXcbScrollingDevice::get(scrollDev);
1333
1334 auto reply = Q_XCB_REPLY(xcb_input_xi_query_device, xcb_connection(), scrollingDevice->systemId);
1335 if (!reply || reply->num_infos <= 0) {
1336 qCDebug(lcQpaInputDevices, "scrolling device %lld no longer present", scrollingDevice->systemId);
1337 return;
1338 }
1339 QPointF lastScrollPosition;
1340 if (lcQpaXInputEvents().isDebugEnabled())
1341 lastScrollPosition = scrollingDevice->lastScrollPosition;
1342
1343 xcb_input_xi_device_info_t *deviceInfo = xcb_input_xi_query_device_infos_iterator(reply.get()).data;
1344 auto classes_it = xcb_input_xi_device_info_classes_iterator(deviceInfo);
1345 for (; classes_it.rem; xcb_input_device_class_next(&classes_it)) {
1346 xcb_input_device_class_t *classInfo = classes_it.data;
1347 if (classInfo->type == XCB_INPUT_DEVICE_CLASS_TYPE_VALUATOR) {
1348 auto *vci = reinterpret_cast<xcb_input_valuator_class_t *>(classInfo);
1349 const int valuatorAtom = qatom(vci->label);
1350 if (valuatorAtom == QXcbAtom::AtomRelHorizScroll || valuatorAtom == QXcbAtom::AtomRelHorizWheel)
1351 scrollingDevice->lastScrollPosition.setX(fixed3232ToReal(vci->value));
1352 else if (valuatorAtom == QXcbAtom::AtomRelVertScroll || valuatorAtom == QXcbAtom::AtomRelVertWheel)
1353 scrollingDevice->lastScrollPosition.setY(fixed3232ToReal(vci->value));
1354 }
1355 }
1356 if (Q_UNLIKELY(lcQpaXInputEvents().isDebugEnabled() && lastScrollPosition != scrollingDevice->lastScrollPosition))
1357 qCDebug(lcQpaXInputEvents, "scrolling device %lld moved from (%f, %f) to (%f, %f)", scrollingDevice->systemId,
1358 lastScrollPosition.x(), lastScrollPosition.y(),
1359 scrollingDevice->lastScrollPosition.x(),
1360 scrollingDevice->lastScrollPosition.y());
1361}
1362
1363void QXcbConnection::xi2UpdateScrollingDevices()
1364{
1365 const auto &devices = QInputDevice::devices();
1366 for (const QInputDevice *dev : devices) {
1367 if (dev->capabilities().testFlag(QInputDevice::Capability::Scroll))
1368 xi2UpdateScrollingDevice(const_cast<QInputDevice *>(dev));
1369 }
1370}
1371
1372QXcbScrollingDevice *QXcbConnection::scrollingDeviceForId(int id)
1373{
1374 const QPointingDevice *dev = QPointingDevicePrivate::pointingDeviceById(id);
1375 if (!dev|| !dev->capabilities().testFlag(QInputDevice::Capability::Scroll))
1376 return nullptr;
1377 return qobject_cast<QXcbScrollingDevice *>(const_cast<QPointingDevice *>(dev));
1378}
1379
1380void QXcbConnection::xi2HandleScrollEvent(void *event, const QPointingDevice *dev)
1381{
1382 auto *xiDeviceEvent = reinterpret_cast<qt_xcb_input_device_event_t *>(event);
1383
1384 const QXcbScrollingDevice *scrollDev = qobject_cast<const QXcbScrollingDevice *>(dev);
1385 if (!scrollDev || !scrollDev->capabilities().testFlag(QInputDevice::Capability::Scroll))
1386 return;
1387 const QXcbScrollingDevicePrivate *scrollingDevice = QXcbScrollingDevice::get(scrollDev);
1388
1389 if (xiDeviceEvent->event_type == XCB_INPUT_MOTION && scrollingDevice->orientations) {
1390 if (QXcbWindow *platformWindow = platformWindowFromId(xiDeviceEvent->event)) {
1391 QPoint rawDelta;
1392 QPoint angleDelta;
1393 double value;
1394 if (scrollingDevice->orientations & Qt::Vertical) {
1395 if (xi2GetValuatorValueIfSet(xiDeviceEvent, scrollingDevice->verticalIndex, &value)) {
1396 double delta = scrollingDevice->lastScrollPosition.y() - value;
1397 scrollingDevice->lastScrollPosition.setY(value);
1398 angleDelta.setY((delta / scrollingDevice->verticalIncrement) * 120);
1399 // With most drivers the increment is 1 for wheels.
1400 // For libinput it is hardcoded to a useless 15.
1401 // For a proper touchpad driver it should be in the same order of magnitude as 120
1402 if (scrollingDevice->verticalIncrement > 15)
1403 rawDelta.setY(delta);
1404 else if (scrollingDevice->verticalIncrement < -15)
1405 rawDelta.setY(-delta);
1406 }
1407 }
1408 if (scrollingDevice->orientations & Qt::Horizontal) {
1409 if (xi2GetValuatorValueIfSet(xiDeviceEvent, scrollingDevice->horizontalIndex, &value)) {
1410 double delta = scrollingDevice->lastScrollPosition.x() - value;
1411 scrollingDevice->lastScrollPosition.setX(value);
1412 angleDelta.setX((delta / scrollingDevice->horizontalIncrement) * 120);
1413 // See comment under vertical
1414 if (scrollingDevice->horizontalIncrement > 15)
1415 rawDelta.setX(delta);
1416 else if (scrollingDevice->horizontalIncrement < -15)
1417 rawDelta.setX(-delta);
1418 }
1419 }
1420 if (!angleDelta.isNull()) {
1421 QPoint local(fixed1616ToReal(xiDeviceEvent->event_x), fixed1616ToReal(xiDeviceEvent->event_y));
1422 QPoint global(fixed1616ToReal(xiDeviceEvent->root_x), fixed1616ToReal(xiDeviceEvent->root_y));
1423 Qt::KeyboardModifiers modifiers = keyboard()->translateModifiers(xiDeviceEvent->mods.effective);
1424 if (modifiers & Qt::AltModifier) {
1425 angleDelta = angleDelta.transposed();
1426 rawDelta = rawDelta.transposed();
1427 }
1428 qCDebug(lcQpaXInputEvents) << "scroll wheel from device" << scrollingDevice->systemId
1429 << "@ window pos" << local << "delta px" << rawDelta << "angle" << angleDelta;
1430 QWindowSystemInterface::handleWheelEvent(platformWindow->window(), xiDeviceEvent->time, dev,
1431 local, global, rawDelta, angleDelta, modifiers);
1432 }
1433 }
1434 } else if (xiDeviceEvent->event_type == XCB_INPUT_BUTTON_RELEASE && scrollingDevice->legacyOrientations) {
1435 if (QXcbWindow *platformWindow = platformWindowFromId(xiDeviceEvent->event)) {
1436 QPoint angleDelta;
1437 if (scrollingDevice->legacyOrientations & Qt::Vertical) {
1438 if (xiDeviceEvent->detail == 4)
1439 angleDelta.setY(120);
1440 else if (xiDeviceEvent->detail == 5)
1441 angleDelta.setY(-120);
1442 }
1443 if (scrollingDevice->legacyOrientations & Qt::Horizontal) {
1444 if (xiDeviceEvent->detail == 6)
1445 angleDelta.setX(120);
1446 else if (xiDeviceEvent->detail == 7)
1447 angleDelta.setX(-120);
1448 }
1449 if (!angleDelta.isNull()) {
1450 QPoint local(fixed1616ToReal(xiDeviceEvent->event_x), fixed1616ToReal(xiDeviceEvent->event_y));
1451 QPoint global(fixed1616ToReal(xiDeviceEvent->root_x), fixed1616ToReal(xiDeviceEvent->root_y));
1452 Qt::KeyboardModifiers modifiers = keyboard()->translateModifiers(xiDeviceEvent->mods.effective);
1453 if (modifiers & Qt::AltModifier)
1454 angleDelta = angleDelta.transposed();
1455 qCDebug(lcQpaXInputEvents) << "scroll wheel (button" << xiDeviceEvent->detail << ") @ window pos" << local << "delta angle" << angleDelta;
1456 QWindowSystemInterface::handleWheelEvent(platformWindow->window(), xiDeviceEvent->time, dev,
1457 local, global, QPoint(), angleDelta, modifiers);
1458 }
1459 }
1460 }
1461}
1462
1463static int xi2ValuatorOffset(const unsigned char *maskPtr, int maskLen, int number)
1464{
1465 int offset = 0;
1466 for (int i = 0; i < maskLen; i++) {
1467 if (number < 8) {
1468 if ((maskPtr[i] & (1 << number)) == 0)
1469 return -1;
1470 }
1471 for (int j = 0; j < 8; j++) {
1472 if (j == number)
1473 return offset;
1474 if (maskPtr[i] & (1 << j))
1475 offset++;
1476 }
1477 number -= 8;
1478 }
1479 return -1;
1480}
1481
1482bool QXcbConnection::xi2GetValuatorValueIfSet(const void *event, int valuatorNum, double *value)
1483{
1484 auto *xideviceevent = static_cast<const qt_xcb_input_device_event_t *>(event);
1485 auto *buttonsMaskAddr = reinterpret_cast<const unsigned char *>(&xideviceevent[1]);
1486 auto *valuatorsMaskAddr = buttonsMaskAddr + xideviceevent->buttons_len * 4;
1487 auto *valuatorsValuesAddr = reinterpret_cast<const xcb_input_fp3232_t *>(valuatorsMaskAddr + xideviceevent->valuators_len * 4);
1488
1489 int valuatorOffset = xi2ValuatorOffset(valuatorsMaskAddr, xideviceevent->valuators_len, valuatorNum);
1490 if (valuatorOffset < 0)
1491 return false;
1492
1493 *value = valuatorsValuesAddr[valuatorOffset].integral;
1494 *value += ((double)valuatorsValuesAddr[valuatorOffset].frac / (1 << 16) / (1 << 16));
1495 return true;
1496}
1497
1498Qt::MouseButton QXcbConnection::xiToQtMouseButton(uint32_t b)
1499{
1500 switch (b) {
1501 case 1: return Qt::LeftButton;
1502 case 2: return Qt::MiddleButton;
1503 case 3: return Qt::RightButton;
1504 // 4-7 are for scrolling
1505 default: break;
1506 }
1507 if (b >= 8 && b <= Qt::MaxMouseButton)
1508 return static_cast<Qt::MouseButton>(Qt::BackButton << (b - 8));
1509 return Qt::NoButton;
1510}
1511
1512#if QT_CONFIG(tabletevent)
1513bool QXcbConnection::xi2HandleTabletEvent(const void *event, TabletData *tabletData)
1514{
1515 bool handled = true;
1516 const auto *xiDeviceEvent = reinterpret_cast<const qt_xcb_input_device_event_t *>(event);
1517
1518 switch (xiDeviceEvent->event_type) {
1519 case XCB_INPUT_BUTTON_PRESS: {
1520 Qt::MouseButton b = xiToQtMouseButton(xiDeviceEvent->detail);
1521 tabletData->buttons |= b;
1522 xi2ReportTabletEvent(event, tabletData);
1523 break;
1524 }
1525 case XCB_INPUT_BUTTON_RELEASE: {
1526 Qt::MouseButton b = xiToQtMouseButton(xiDeviceEvent->detail);
1527 tabletData->buttons ^= b;
1528 xi2ReportTabletEvent(event, tabletData);
1529 break;
1530 }
1531 case XCB_INPUT_MOTION:
1532 xi2ReportTabletEvent(event, tabletData);
1533 break;
1534 case XCB_INPUT_PROPERTY: {
1535 // This is the wacom driver's way of reporting tool proximity.
1536 // The evdev driver doesn't do it this way.
1537 const auto *ev = reinterpret_cast<const xcb_input_property_event_t *>(event);
1538 if (ev->what == XCB_INPUT_PROPERTY_FLAG_MODIFIED) {
1539 if (ev->property == atom(QXcbAtom::AtomWacomSerialIDs)) {
1540 enum WacomSerialIndex {
1541 _WACSER_USB_ID = 0,
1542 _WACSER_LAST_TOOL_SERIAL,
1543 _WACSER_LAST_TOOL_ID,
1544 _WACSER_TOOL_SERIAL,
1545 _WACSER_TOOL_ID,
1546 _WACSER_COUNT
1547 };
1548
1549 auto reply = Q_XCB_REPLY(xcb_input_xi_get_property, xcb_connection(), tabletData->deviceId, 0,
1550 ev->property, XCB_GET_PROPERTY_TYPE_ANY, 0, 100);
1551 if (reply) {
1552 if (reply->type == atom(QXcbAtom::AtomINTEGER) && reply->format == 32 && reply->num_items == _WACSER_COUNT) {
1553 quint32 *ptr = reinterpret_cast<quint32 *>(xcb_input_xi_get_property_items(reply.get()));
1554 quint32 tool = ptr[_WACSER_TOOL_ID];
1555 // Workaround for http://sourceforge.net/p/linuxwacom/bugs/246/
1556 // e.g. on Thinkpad Helix, tool ID will be 0 and serial will be 1
1557 if (!tool && ptr[_WACSER_TOOL_SERIAL])
1558 tool = ptr[_WACSER_TOOL_SERIAL];
1559
1560 QWindow *win = nullptr; // TODO QTBUG-111400 get the position somehow, then the window
1561 // The property change event informs us which tool is in proximity or which one left proximity.
1562 if (tool) {
1563 const QPointingDevice *dev = tabletToolInstance(nullptr, tabletData->name,
1564 tabletData->deviceId, ptr[_WACSER_USB_ID], tool,
1565 qint64(ptr[_WACSER_TOOL_SERIAL])); // TODO look up the master
1566 tabletData->inProximity = true;
1567 tabletData->tool = dev->type();
1568 tabletData->serialId = qint64(ptr[_WACSER_TOOL_SERIAL]);
1569 QWindowSystemInterface::handleTabletEnterLeaveProximityEvent(win, ev->time, dev, true); // enter
1570 } else {
1571 tool = ptr[_WACSER_LAST_TOOL_ID];
1572 // Workaround for http://sourceforge.net/p/linuxwacom/bugs/246/
1573 // e.g. on Thinkpad Helix, tool ID will be 0 and serial will be 1
1574 if (!tool)
1575 tool = ptr[_WACSER_LAST_TOOL_SERIAL];
1576 auto *dev = qobject_cast<const QPointingDevice *>(QInputDevicePrivate::fromId(tabletData->deviceId));
1577 Q_ASSERT(dev);
1578 tabletData->tool = dev->type();
1579 tabletData->inProximity = false;
1580 tabletData->serialId = qint64(ptr[_WACSER_LAST_TOOL_SERIAL]);
1581 QWindowSystemInterface::handleTabletEnterLeaveProximityEvent(win, ev->time, dev, false); // leave
1582 }
1583 // TODO maybe have a hash of tabletData->deviceId to device data so we can
1584 // look up the tablet name here, and distinguish multiple tablets
1585 qCDebug(lcQpaInputDevices, "XI2 proximity change on tablet %d %s (USB %x): last tool: %x id %x current tool: %x id %x %s",
1586 tabletData->deviceId, qPrintable(tabletData->name), ptr[_WACSER_USB_ID],
1587 ptr[_WACSER_LAST_TOOL_SERIAL], ptr[_WACSER_LAST_TOOL_ID],
1588 ptr[_WACSER_TOOL_SERIAL], ptr[_WACSER_TOOL_ID], toolName(tabletData->tool));
1589 }
1590 }
1591 }
1592 }
1593 break;
1594 }
1595 default:
1596 handled = false;
1597 break;
1598 }
1599
1600 return handled;
1601}
1602
1603static inline qreal scaleOneValuator(qreal normValue, qreal screenMin, qreal screenSize)
1604{
1605 return screenMin + normValue * screenSize;
1606}
1607
1608// TODO QPointingDevice not TabletData
1609void QXcbConnection::xi2ReportTabletEvent(const void *event, TabletData *tabletData)
1610{
1611 auto *ev = reinterpret_cast<const qt_xcb_input_device_event_t *>(event);
1612 QXcbWindow *xcbWindow = platformWindowFromId(ev->event);
1613 if (!xcbWindow)
1614 return;
1615 QWindow *window = xcbWindow->window();
1616 const Qt::KeyboardModifiers modifiers = keyboard()->translateModifiers(ev->mods.effective);
1617 QPointF local(fixed1616ToReal(ev->event_x), fixed1616ToReal(ev->event_y));
1618 QPointF global(fixed1616ToReal(ev->root_x), fixed1616ToReal(ev->root_y));
1619 double pressure = 0, rotation = 0, tangentialPressure = 0;
1620 qreal xTilt = 0, yTilt = 0;
1621 static const bool useValuators = !qEnvironmentVariableIsSet("QT_XCB_TABLET_LEGACY_COORDINATES");
1622 const QPointingDevice *dev = QPointingDevicePrivate::tabletDevice(QInputDevice::DeviceType(tabletData->tool),
1623 QPointingDevice::PointerType(tabletData->pointerType),
1624 QPointingDeviceUniqueId::fromNumericId(tabletData->serialId));
1625
1626 // Valuators' values are relative to the physical size of the current virtual
1627 // screen. Therefore we cannot use QScreen/QWindow geometry and should use
1628 // QPlatformWindow/QPlatformScreen instead.
1629 QRect physicalScreenArea;
1630 if (Q_LIKELY(useValuators)) {
1631 const QList<QPlatformScreen *> siblings = window->screen()->handle()->virtualSiblings();
1632 for (const QPlatformScreen *screen : siblings)
1633 physicalScreenArea |= screen->geometry();
1634 }
1635
1636 for (QHash<int, TabletData::ValuatorClassInfo>::iterator it = tabletData->valuatorInfo.begin(),
1637 ite = tabletData->valuatorInfo.end(); it != ite; ++it) {
1638 int valuator = it.key();
1639 TabletData::ValuatorClassInfo &classInfo(it.value());
1640 xi2GetValuatorValueIfSet(event, classInfo.number, &classInfo.curVal);
1641 double normalizedValue = (classInfo.curVal - classInfo.minVal) / (classInfo.maxVal - classInfo.minVal);
1642 switch (valuator) {
1643 case QXcbAtom::AtomAbsX:
1644 if (Q_LIKELY(useValuators)) {
1645 const qreal value = scaleOneValuator(normalizedValue, physicalScreenArea.x(), physicalScreenArea.width());
1646 global.setX(value);
1647 local.setX(xcbWindow->mapFromGlobalF(global).x());
1648 }
1649 break;
1650 case QXcbAtom::AtomAbsY:
1651 if (Q_LIKELY(useValuators)) {
1652 qreal value = scaleOneValuator(normalizedValue, physicalScreenArea.y(), physicalScreenArea.height());
1653 global.setY(value);
1654 local.setY(xcbWindow->mapFromGlobalF(global).y());
1655 }
1656 break;
1657 case QXcbAtom::AtomAbsPressure:
1658 pressure = normalizedValue;
1659 break;
1660 case QXcbAtom::AtomAbsTiltX:
1661 xTilt = classInfo.curVal;
1662 break;
1663 case QXcbAtom::AtomAbsTiltY:
1664 yTilt = classInfo.curVal;
1665 break;
1666 case QXcbAtom::AtomAbsWheel:
1667 switch (tabletData->tool) {
1668 case QInputDevice::DeviceType::Airbrush:
1669 tangentialPressure = normalizedValue * 2.0 - 1.0; // Convert 0..1 range to -1..+1 range
1670 break;
1671 case QInputDevice::DeviceType::Stylus:
1672 if (dev->capabilities().testFlag(QInputDevice::Capability::Rotation))
1673 rotation = normalizedValue * 360.0 - 180.0; // Convert 0..1 range to -180..+180 degrees
1674 break;
1675 default: // Other types of styli do not use this valuator
1676 break;
1677 }
1678 break;
1679 default:
1680 break;
1681 }
1682 }
1683
1684 if (Q_UNLIKELY(lcQpaXInputEvents().isDebugEnabled()))
1685 qCDebug(lcQpaXInputEvents, "XI2 event on tablet %d with tool %s %llx type %s seq %d detail %d time %d "
1686 "pos %6.1f, %6.1f root pos %6.1f, %6.1f buttons 0x%x pressure %4.2lf tilt %4.2lf, %4.2lf rotation %6.2lf modifiers 0x%x",
1687 tabletData->deviceId, toolName(tabletData->tool), tabletData->serialId, pointerTypeName(tabletData->pointerType),
1688 ev->sequence, ev->detail, ev->time,
1689 local.x(), local.y(), global.x(), global.y(),
1690 (int)tabletData->buttons, pressure, xTilt, yTilt, rotation, (int)modifiers);
1691
1692 QWindowSystemInterface::handleTabletEvent(window, ev->time, dev, local, global,
1693 tabletData->buttons, pressure,
1694 xTilt, yTilt, tangentialPressure,
1695 rotation, 0, modifiers);
1696}
1697
1698QXcbConnection::TabletData *QXcbConnection::tabletDataForDevice(int id)
1699{
1700 for (int i = 0; i < m_tabletData.size(); ++i) {
1701 if (m_tabletData.at(i).deviceId == id)
1702 return &m_tabletData[i];
1703 }
1704 return nullptr;
1705}
1706
1707#endif // QT_CONFIG(tabletevent)
#define Q_XCB_REPLY(call,...)
static int xi2ValuatorOffset(const unsigned char *maskPtr, int maskLen, int number)
static void setXcbMask(uint8_t *mask, int bit)
static qreal fixed1616ToReal(xcb_input_fp1616_t val)
xcb_input_button_press_event_t qt_xcb_input_device_event_t
static qreal fixed3232ToReal(xcb_input_fp3232_t val)