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
qwindowspointerhandler.cpp
Go to the documentation of this file.
1// Copyright (C) 2019 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
5#include <QtCore/qt_windows.h>
6
8#if QT_CONFIG(tabletevent)
9# include "qwindowstabletsupport.h"
10#endif
13#include "qwindowswindow.h"
15#include "qwindowsscreen.h"
16
17#include <QtGui/qguiapplication.h>
18#include <QtGui/qscreen.h>
19#include <QtGui/qpointingdevice.h>
20#include <QtGui/qwindow.h>
21#include <QtGui/private/qguiapplication_p.h>
22#include <QtCore/qvarlengtharray.h>
23#include <QtCore/qloggingcategory.h>
24#include <QtCore/qqueue.h>
25#include <QtCore/qset.h>
26
27#include <algorithm>
28
29#include <windowsx.h>
30
31QT_BEGIN_NAMESPACE
32
33enum {
34 QT_PT_POINTER = 1,
35 QT_PT_TOUCH = 2,
36 QT_PT_PEN = 3,
37 QT_PT_MOUSE = 4,
38 QT_PT_TOUCHPAD = 5, // MinGW is missing PT_TOUCHPAD
39};
40
41qint64 QWindowsPointerHandler::m_nextInputDeviceId = 1;
42
43const QPointingDevice *primaryMouse()
44{
45 static QPointer<const QPointingDevice> result;
46 if (!result)
47 result = QPointingDevice::primaryPointingDevice();
48 return result;
49}
50
54
55bool QWindowsPointerHandler::translatePointerEvent(QWindow *window, HWND hwnd, QtWindows::WindowsEventType et, MSG msg, LRESULT *result)
56{
57 *result = 0;
58 const quint32 pointerId = GET_POINTERID_WPARAM(msg.wParam);
59
60 if (!GetPointerType(pointerId, &m_pointerType)) {
61 qWarning() << "GetPointerType() failed:" << qt_error_string();
62 const int id = m_touchInputIDToTouchPointID.value(pointerId, -1);
63 if (id != -1) {
64 m_lastTouchPoints.remove(id);
65 m_touchInputIDToTouchPointID.remove(pointerId);
66 }
67 return false;
68 }
69
70 switch (m_pointerType) {
71 case QT_PT_POINTER:
72 case QT_PT_MOUSE:
73 case QT_PT_TOUCHPAD: {
74 // Let Mouse/TouchPad be handled using legacy messages.
75 return false;
76 }
77 case QT_PT_TOUCH: {
78 quint32 pointerCount = 0;
79 if (!GetPointerFrameTouchInfo(pointerId, &pointerCount, nullptr)) {
80 qWarning() << "GetPointerFrameTouchInfo() failed:" << qt_error_string();
81 return false;
82 }
83 QVarLengthArray<POINTER_TOUCH_INFO, 10> touchInfo(pointerCount);
84 if (!GetPointerFrameTouchInfo(pointerId, &pointerCount, touchInfo.data())) {
85 qWarning() << "GetPointerFrameTouchInfo() failed:" << qt_error_string();
86 return false;
87 }
88
89 if (!pointerCount)
90 return false;
91
92 // The history count is the same for all the touchpoints in touchInfo
93 quint32 historyCount = touchInfo[0].pointerInfo.historyCount;
94 // dispatch any skipped frames if event compression is disabled by the app
95 if (historyCount > 1 && !QCoreApplication::testAttribute(Qt::AA_CompressHighFrequencyEvents)) {
96 touchInfo.resize(pointerCount * historyCount);
97 if (!GetPointerFrameTouchInfoHistory(pointerId,
98 &historyCount,
99 &pointerCount,
100 touchInfo.data())) {
101 qWarning() << "GetPointerFrameTouchInfoHistory() failed:" << qt_error_string();
102 return false;
103 }
104
105 // history frames are returned with the most recent frame first so we iterate backwards
106 bool result = true;
107 for (auto it = touchInfo.rbegin(), end = touchInfo.rend(); it != end; it += pointerCount) {
108 result &= translateTouchEvent(window, hwnd, et, msg,
109 &(*(it + (pointerCount - 1))), pointerCount);
110 }
111 return result;
112 }
113
114 return translateTouchEvent(window, hwnd, et, msg, touchInfo.data(), pointerCount);
115 }
116 case QT_PT_PEN: {
117 POINTER_PEN_INFO penInfo;
118 if (!GetPointerPenInfo(pointerId, &penInfo)) {
119 qWarning() << "GetPointerPenInfo() failed:" << qt_error_string();
120 return false;
121 }
122
123 quint32 historyCount = penInfo.pointerInfo.historyCount;
124 // dispatch any skipped frames if generic or tablet event compression is disabled by the app
125 if (historyCount > 1
126 && (!QCoreApplication::testAttribute(Qt::AA_CompressHighFrequencyEvents)
127 || !QCoreApplication::testAttribute(Qt::AA_CompressTabletEvents))) {
128 QVarLengthArray<POINTER_PEN_INFO, 10> penInfoHistory(historyCount);
129
130 if (!GetPointerPenInfoHistory(pointerId, &historyCount, penInfoHistory.data())) {
131 qWarning() << "GetPointerPenInfoHistory() failed:" << qt_error_string();
132 return false;
133 }
134
135 // history frames are returned with the most recent frame first so we iterate backwards
136 bool result = true;
137 for (auto it = penInfoHistory.rbegin(), end = penInfoHistory.rend(); it != end; ++it) {
138 result &= translatePenEvent(window, hwnd, et, msg, &(*(it)));
139 }
140 return result;
141 }
142
143 return translatePenEvent(window, hwnd, et, msg, &penInfo);
144 }
145 }
146 return false;
147}
148
149namespace {
150struct MouseEvent {
151 QEvent::Type type;
152 Qt::MouseButton button;
153};
154} // namespace
155
156static inline Qt::MouseButton extraButton(WPARAM wParam) // for WM_XBUTTON...
157{
158 return GET_XBUTTON_WPARAM(wParam) == XBUTTON1 ? Qt::BackButton : Qt::ForwardButton;
159}
160
161static inline MouseEvent eventFromMsg(const MSG &msg)
162{
163 switch (msg.message) {
164 case WM_MOUSEMOVE:
165 return {QEvent::MouseMove, Qt::NoButton};
166 case WM_LBUTTONDOWN:
167 return {QEvent::MouseButtonPress, Qt::LeftButton};
168 case WM_LBUTTONUP:
169 return {QEvent::MouseButtonRelease, Qt::LeftButton};
170 case WM_LBUTTONDBLCLK: // Qt QPA does not handle double clicks, send as press
171 return {QEvent::MouseButtonPress, Qt::LeftButton};
172 case WM_MBUTTONDOWN:
173 return {QEvent::MouseButtonPress, Qt::MiddleButton};
174 case WM_MBUTTONUP:
175 return {QEvent::MouseButtonRelease, Qt::MiddleButton};
176 case WM_MBUTTONDBLCLK:
177 return {QEvent::MouseButtonPress, Qt::MiddleButton};
178 case WM_RBUTTONDOWN:
179 return {QEvent::MouseButtonPress, Qt::RightButton};
180 case WM_RBUTTONUP:
181 return {QEvent::MouseButtonRelease, Qt::RightButton};
182 case WM_RBUTTONDBLCLK:
183 return {QEvent::MouseButtonPress, Qt::RightButton};
184 case WM_XBUTTONDOWN:
185 return {QEvent::MouseButtonPress, extraButton(msg.wParam)};
186 case WM_XBUTTONUP:
187 return {QEvent::MouseButtonRelease, extraButton(msg.wParam)};
188 case WM_XBUTTONDBLCLK:
189 return {QEvent::MouseButtonPress, extraButton(msg.wParam)};
190 case WM_NCMOUSEMOVE:
191 return {QEvent::NonClientAreaMouseMove, Qt::NoButton};
192 case WM_NCLBUTTONDOWN:
193 return {QEvent::NonClientAreaMouseButtonPress, Qt::LeftButton};
194 case WM_NCLBUTTONUP:
195 return {QEvent::NonClientAreaMouseButtonRelease, Qt::LeftButton};
196 case WM_NCLBUTTONDBLCLK:
197 return {QEvent::NonClientAreaMouseButtonPress, Qt::LeftButton};
198 case WM_NCMBUTTONDOWN:
199 return {QEvent::NonClientAreaMouseButtonPress, Qt::MiddleButton};
200 case WM_NCMBUTTONUP:
201 return {QEvent::NonClientAreaMouseButtonRelease, Qt::MiddleButton};
202 case WM_NCMBUTTONDBLCLK:
203 return {QEvent::NonClientAreaMouseButtonPress, Qt::MiddleButton};
204 case WM_NCRBUTTONDOWN:
205 return {QEvent::NonClientAreaMouseButtonPress, Qt::RightButton};
206 case WM_NCRBUTTONUP:
207 return {QEvent::NonClientAreaMouseButtonRelease, Qt::RightButton};
208 case WM_NCRBUTTONDBLCLK:
209 return {QEvent::NonClientAreaMouseButtonPress, Qt::RightButton};
210 default: // WM_MOUSELEAVE
211 break;
212 }
213 return {QEvent::None, Qt::NoButton};
214}
215
217{
218 Qt::MouseButtons result = Qt::NoButton;
219 if (keyState & MK_LBUTTON)
220 result |= Qt::LeftButton;
221 if (keyState & MK_RBUTTON)
222 result |= Qt::RightButton;
223 if (keyState & MK_MBUTTON)
224 result |= Qt::MiddleButton;
225 if (keyState & MK_XBUTTON1)
226 result |= Qt::XButton1;
227 if (keyState & MK_XBUTTON2)
228 result |= Qt::XButton2;
229 return result;
230}
231
232Qt::MouseButtons QWindowsPointerHandler::queryMouseButtons()
233{
234 Qt::MouseButtons result = Qt::NoButton;
235 const bool mouseSwapped = GetSystemMetrics(SM_SWAPBUTTON);
236 if (GetAsyncKeyState(VK_LBUTTON) < 0)
237 result |= mouseSwapped ? Qt::RightButton: Qt::LeftButton;
238 if (GetAsyncKeyState(VK_RBUTTON) < 0)
239 result |= mouseSwapped ? Qt::LeftButton : Qt::RightButton;
240 if (GetAsyncKeyState(VK_MBUTTON) < 0)
241 result |= Qt::MiddleButton;
242 if (GetAsyncKeyState(VK_XBUTTON1) < 0)
243 result |= Qt::XButton1;
244 if (GetAsyncKeyState(VK_XBUTTON2) < 0)
245 result |= Qt::XButton2;
246 return result;
247}
248
249static QWindow *getWindowUnderPointer(QWindow *window, QPoint globalPos)
250{
251 QWindowsWindow *platformWindow = static_cast<QWindowsWindow *>(window->handle());
252
253 QWindow *currentWindowUnderPointer = platformWindow->hasMouseCapture() ?
254 QWindowsScreen::windowAt(globalPos, CWP_SKIPINVISIBLE | CWP_SKIPTRANSPARENT) : window;
255
256 while (currentWindowUnderPointer && currentWindowUnderPointer->flags() & Qt::WindowTransparentForInput)
257 currentWindowUnderPointer = currentWindowUnderPointer->parent();
258
259 // QTBUG-44332: When Qt is running at low integrity level and
260 // a Qt Window is parented on a Window of a higher integrity process
261 // using QWindow::fromWinId() (for example, Qt running in a browser plugin)
262 // ChildWindowFromPointEx() may not find the Qt window (failing with ERROR_ACCESS_DENIED)
263 if (!currentWindowUnderPointer) {
264 const QRect clientRect(QPoint(0, 0), window->size());
265 if (clientRect.contains(globalPos))
266 currentWindowUnderPointer = window;
267 }
268 return currentWindowUnderPointer;
269}
270
271static bool trackLeave(HWND hwnd)
272{
273 TRACKMOUSEEVENT tme;
274 tme.cbSize = sizeof(TRACKMOUSEEVENT);
275 tme.dwFlags = TME_LEAVE;
276 tme.hwndTrack = hwnd;
277 tme.dwHoverTime = HOVER_DEFAULT;
278 return TrackMouseEvent(&tme);
279}
280
281static bool isValidWheelReceiver(QWindow *candidate)
282{
283 if (candidate) {
284 const QWindow *toplevel = QWindowsWindow::topLevelOf(candidate);
285 if (toplevel->handle() && toplevel->handle()->isForeignWindow())
286 return true;
287 if (const QWindowsWindow *ww = QWindowsWindow::windowsWindowOf(toplevel))
289 }
290 return false;
291}
292
293QWindowsPointerHandler::QPointingDevicePtr QWindowsPointerHandler::createTouchDevice(bool mouseEmulation)
294{
295 const int digitizers = GetSystemMetrics(SM_DIGITIZER);
296 if (!(digitizers & (NID_INTEGRATED_TOUCH | NID_EXTERNAL_TOUCH)))
297 return nullptr;
298 const int tabletPc = GetSystemMetrics(SM_TABLETPC);
299 const int maxTouchPoints = GetSystemMetrics(SM_MAXIMUMTOUCHES);
300 const QPointingDevice::DeviceType type = (digitizers & NID_INTEGRATED_TOUCH)
301 ? QInputDevice::DeviceType::TouchScreen : QInputDevice::DeviceType::TouchPad;
302 QInputDevice::Capabilities capabilities = QInputDevice::Capability::Position
303 | QInputDevice::Capability::Area
304 | QInputDevice::Capability::NormalizedPosition;
305 if (type != QInputDevice::DeviceType::TouchScreen) {
306 capabilities.setFlag(QInputDevice::Capability::MouseEmulation);
307 capabilities.setFlag(QInputDevice::Capability::Scroll);
308 } else if (mouseEmulation) {
309 capabilities.setFlag(QInputDevice::Capability::MouseEmulation);
310 }
311
312 const int flags = digitizers & ~NID_READY;
313 qCDebug(lcQpaEvents) << "Digitizers:" << Qt::hex << Qt::showbase << flags
314 << "Ready:" << (digitizers & NID_READY) << Qt::dec << Qt::noshowbase
315 << "Tablet PC:" << tabletPc << "Max touch points:" << maxTouchPoints << "Capabilities:" << capabilities;
316
317 const int buttonCount = type == QInputDevice::DeviceType::TouchScreen ? 1 : 3;
318 // TODO: use system-provided name and device ID rather than empty-string and m_nextInputDeviceId
319 const qint64 systemId = m_nextInputDeviceId++ | (qint64(flags << 2));
320 auto d = new QPointingDevice(QString(), systemId, type,
321 QPointingDevice::PointerType::Finger,
322 capabilities, maxTouchPoints, buttonCount,
323 QString(), QPointingDeviceUniqueId::fromNumericId(systemId));
324 return QPointingDevicePtr(d);
325}
326
328{
329 m_lastEventType = QEvent::None;
330 m_lastEventButton = Qt::NoButton;
331}
332
333void QWindowsPointerHandler::handleCaptureRelease(QWindow *window,
334 QWindow *currentWindowUnderPointer,
335 HWND hwnd,
336 QEvent::Type eventType,
337 Qt::MouseButtons mouseButtons)
338{
339 auto *platformWindow = static_cast<QWindowsWindow *>(window->handle());
340
341 // Qt expects the platform plugin to capture the mouse on any button press until release.
342 if (!platformWindow->hasMouseCapture() && eventType == QEvent::MouseButtonPress) {
343
344 platformWindow->setMouseGrabEnabled(true);
345 platformWindow->setFlag(QWindowsWindow::AutoMouseCapture);
346 qCDebug(lcQpaEvents) << "Automatic mouse capture " << window;
347
348 } else if (platformWindow->hasMouseCapture()
349 && platformWindow->testFlag(QWindowsWindow::AutoMouseCapture)
350 && eventType == QEvent::MouseButtonRelease
351 && !mouseButtons) {
352
353 platformWindow->setMouseGrabEnabled(false);
354 qCDebug(lcQpaEvents) << "Releasing automatic mouse capture " << window;
355 }
356
357 // Enter new window: track to generate leave event.
358 // If there is an active capture, only track if the current window is capturing,
359 // so we don't get extra leave when cursor leaves the application.
360 if (window != m_currentWindow &&
361 (!platformWindow->hasMouseCapture() || currentWindowUnderPointer == window)) {
362 trackLeave(hwnd);
363 m_currentWindow = window;
364 }
365}
366
367void QWindowsPointerHandler::handleEnterLeave(QWindow *window,
368 QWindow *currentWindowUnderPointer,
369 QPoint globalPos)
370{
371 auto *platformWindow = static_cast<QWindowsWindow *>(window->handle());
372 const bool hasCapture = platformWindow->hasMouseCapture();
373
374 // No enter or leave events are sent as long as there is an autocapturing window.
375 if (!hasCapture || !platformWindow->testFlag(QWindowsWindow::AutoMouseCapture)) {
376
377 // Leave is needed if:
378 // 1) There is no capture and we move from a window to another window.
379 // Note: Leaving the application entirely is handled in translateMouseEvent(WM_MOUSELEAVE).
380 // 2) There is capture and we move out of the capturing window.
381 // 3) There is a new capture and we were over another window.
382 if ((m_windowUnderPointer && m_windowUnderPointer != currentWindowUnderPointer
383 && (!hasCapture || window == m_windowUnderPointer))
384 || (hasCapture && m_previousCaptureWindow != window && m_windowUnderPointer
385 && m_windowUnderPointer != window)) {
386
387 qCDebug(lcQpaEvents) << "Leaving window " << m_windowUnderPointer;
388 QWindowSystemInterface::handleLeaveEvent(m_windowUnderPointer);
389
390 if (hasCapture && currentWindowUnderPointer != window) {
391 // Clear tracking if capturing and current window is not the capturing window
392 // to avoid leave when mouse actually leaves the application.
393 m_currentWindow = nullptr;
394 // We are not officially in any window, but we need to set some cursor to clear
395 // whatever cursor the left window had, so apply the cursor of the capture window.
396 platformWindow->applyCursor();
397 }
398 }
399
400 // Enter is needed if:
401 // 1) There is no capture and we move to a new window.
402 // 2) There is capture and we move into the capturing window.
403 // 3) The capture just ended and we are over non-capturing window.
404 if ((currentWindowUnderPointer && m_windowUnderPointer != currentWindowUnderPointer
405 && (!hasCapture || currentWindowUnderPointer == window))
406 || (m_previousCaptureWindow && !hasCapture && currentWindowUnderPointer
407 && currentWindowUnderPointer != m_previousCaptureWindow)) {
408
409 QPoint wumLocalPos;
410 if (QWindowsWindow *wumPlatformWindow = QWindowsWindow::windowsWindowOf(currentWindowUnderPointer)) {
411 wumLocalPos = wumPlatformWindow->mapFromGlobal(globalPos);
412 wumPlatformWindow->applyCursor();
413 }
414 qCDebug(lcQpaEvents) << "Entering window " << currentWindowUnderPointer;
415 QWindowSystemInterface::handleEnterEvent(currentWindowUnderPointer, wumLocalPos, globalPos);
416 }
417
418 // We need to track m_windowUnderPointer separately from m_currentWindow, as Windows
419 // mouse tracking will not trigger WM_MOUSELEAVE for leaving window when mouse capture is set.
420 m_windowUnderPointer = currentWindowUnderPointer;
421 }
422
423 m_previousCaptureWindow = hasCapture ? window : nullptr;
424}
425
426void QWindowsPointerHandler::handleWindowActivation(QWindow *window,
427 QEvent::Type eventType)
428{
429 if (eventType != QEvent::MouseButtonPress)
430 return;
431
432 auto *focusWindow = QGuiApplication::focusWindow();
433 if (window->isTopLevel()) {
434 // Windows does not send WM_MOUSEACTIVATE to an already-active top-level,
435 // so if focus currently sits in an embedded descendant (e.g. a native
436 // child window hosted via WindowContainer) we have to activate the
437 // top-level ourselves on mouse press.
438 if (focusWindow && window->isAncestorOf(focusWindow))
439 window->requestActivate();
440 } else if (!window->inherits("QWidgetWindow") && focusWindow != window) {
441 // "Click to focus" for native child windows. Skip QWidgetWindow, which
442 // handles focus at the widget level.
443 window->requestActivate();
444 }
445}
446
447bool QWindowsPointerHandler::translateTouchEvent(QWindow *window, HWND hwnd,
448 QtWindows::WindowsEventType et,
449 MSG msg, PVOID vTouchInfo, quint32 count)
450{
451 Q_UNUSED(hwnd);
452
453 auto *touchInfo = static_cast<POINTER_TOUCH_INFO *>(vTouchInfo);
454
455 if (et & QtWindows::NonClientEventFlag)
456 return false; // Let DefWindowProc() handle Non Client messages.
457
458 if (count < 1)
459 return false;
460
461 if (msg.message == WM_POINTERCAPTURECHANGED) {
462 const auto *keyMapper = QWindowsContext::instance()->keyMapper();
463 QWindowSystemInterface::handleTouchCancelEvent(window, msg.time, m_touchDevice.data(),
464 keyMapper->queryKeyboardModifiers());
465 m_lastTouchPoints.clear();
466 return true;
467 }
468
469 if (msg.message == WM_POINTERLEAVE) {
470 for (quint32 i = 0; i < count; ++i) {
471 const quint32 pointerId = touchInfo[i].pointerInfo.pointerId;
472 int id = m_touchInputIDToTouchPointID.value(pointerId, -1);
473 if (id != -1)
474 m_lastTouchPoints.remove(id);
475 }
476 // Send LeaveEvent to reset hover when the last finger leaves the touch screen (QTBUG-62912)
477 QWindowSystemInterface::handleEnterLeaveEvent(nullptr, window);
478 }
479
480 // Only handle down/up/update, ignore others like WM_POINTERENTER, WM_POINTERLEAVE, etc.
481 if (msg.message > WM_POINTERUP)
482 return false;
483
484 const QScreen *screen = window->screen();
485 if (!screen)
486 screen = QGuiApplication::primaryScreen();
487 if (!screen)
488 return false;
489
490 const QRect screenGeometry = screen->geometry();
491
492 QList<QWindowSystemInterface::TouchPoint> touchPoints;
493
494 if (QWindowsContext::verbose > 1)
495 qCDebug(lcQpaEvents).noquote().nospace() << Qt::showbase
496 << __FUNCTION__
497 << " message=" << Qt::hex << msg.message
498 << " count=" << Qt::dec << count;
499
500 QEventPoint::States allStates;
501 QSet<int> inputIds;
502
503 for (quint32 i = 0; i < count; ++i) {
504 if (QWindowsContext::verbose > 1)
505 qCDebug(lcQpaEvents).noquote().nospace() << Qt::showbase
506 << " TouchPoint id=" << touchInfo[i].pointerInfo.pointerId
507 << " frame=" << touchInfo[i].pointerInfo.frameId
508 << " flags=" << Qt::hex << touchInfo[i].pointerInfo.pointerFlags;
509
510 QWindowSystemInterface::TouchPoint touchPoint;
511 const quint32 pointerId = touchInfo[i].pointerInfo.pointerId;
512 int id = m_touchInputIDToTouchPointID.value(pointerId, -1);
513 if (id == -1) {
514 // Start tracking after fingers touch the screen. Ignore bogus updates after touch is released.
515 if ((touchInfo[i].pointerInfo.pointerFlags & POINTER_FLAG_DOWN) == 0)
516 continue;
517 id = m_touchInputIDToTouchPointID.size();
518 m_touchInputIDToTouchPointID.insert(pointerId, id);
519 }
520 touchPoint.id = id;
521 touchPoint.pressure = (touchInfo[i].touchMask & TOUCH_MASK_PRESSURE) ?
522 touchInfo[i].pressure / 1024.0 : 1.0;
523 if (m_lastTouchPoints.contains(touchPoint.id))
524 touchPoint.normalPosition = m_lastTouchPoints.value(touchPoint.id).normalPosition;
525
526 const QPointF screenPos = QPointF(touchInfo[i].pointerInfo.ptPixelLocation.x,
527 touchInfo[i].pointerInfo.ptPixelLocation.y);
528
529 if (touchInfo[i].touchMask & TOUCH_MASK_CONTACTAREA)
530 touchPoint.area.setSize(QSizeF(touchInfo[i].rcContact.right - touchInfo[i].rcContact.left,
531 touchInfo[i].rcContact.bottom - touchInfo[i].rcContact.top));
532 touchPoint.area.moveCenter(screenPos);
533 QPointF normalPosition = QPointF(screenPos.x() / screenGeometry.width(),
534 screenPos.y() / screenGeometry.height());
535 const bool stationaryTouchPoint = (normalPosition == touchPoint.normalPosition);
536 touchPoint.normalPosition = normalPosition;
537
538 if (touchInfo[i].pointerInfo.pointerFlags & POINTER_FLAG_DOWN) {
539 touchPoint.state = QEventPoint::State::Pressed;
540 m_lastTouchPoints.insert(touchPoint.id, touchPoint);
541 } else if (touchInfo[i].pointerInfo.pointerFlags & POINTER_FLAG_UP) {
542 touchPoint.state = QEventPoint::State::Released;
543 m_lastTouchPoints.remove(touchPoint.id);
544 } else {
545 touchPoint.state = stationaryTouchPoint ? QEventPoint::State::Stationary : QEventPoint::State::Updated;
546 m_lastTouchPoints.insert(touchPoint.id, touchPoint);
547 }
548 allStates |= touchPoint.state;
549
550 touchPoints.append(touchPoint);
551 inputIds.insert(touchPoint.id);
552
553 // Avoid getting repeated messages for this frame if there are multiple pointerIds
554 SkipPointerFrameMessages(touchInfo[i].pointerInfo.pointerId);
555 }
556
557 // Some devices send touches for each finger in a different message/frame, instead of consolidating
558 // them in the same frame as we were expecting. We account for missing unreleased touches here.
559 for (auto tp : std::as_const(m_lastTouchPoints)) {
560 if (!inputIds.contains(tp.id)) {
561 tp.state = QEventPoint::State::Stationary;
562 allStates |= tp.state;
563 touchPoints.append(tp);
564 }
565 }
566
567 if (touchPoints.count() == 0)
568 return false;
569
570 // all touch points released, forget the ids we've seen.
571 if (allStates == QEventPoint::State::Released)
572 m_touchInputIDToTouchPointID.clear();
573
574 const auto *keyMapper = QWindowsContext::instance()->keyMapper();
575 QWindowSystemInterface::handleTouchEvent(window, msg.time, m_touchDevice.data(), touchPoints,
576 keyMapper->queryKeyboardModifiers());
577 return false; // Allow mouse messages to be generated.
578}
579
580#if QT_CONFIG(tabletevent)
581QWindowsPointerHandler::QPointingDevicePtr QWindowsPointerHandler::findTabletDevice(QPointingDevice::PointerType pointerType) const
582{
583 for (const auto &d : m_tabletDevices) {
584 if (d->pointerType() == pointerType)
585 return d;
586 }
587 return {};
588}
589#endif
590
591bool QWindowsPointerHandler::translatePenEvent(QWindow *window, HWND hwnd, QtWindows::WindowsEventType et,
592 MSG msg, PVOID vPenInfo)
593{
594#if QT_CONFIG(tabletevent)
595 if (et & QtWindows::NonClientEventFlag)
596 return false; // Let DefWindowProc() handle Non Client messages.
597
598 auto *penInfo = static_cast<POINTER_PEN_INFO *>(vPenInfo);
599
600 RECT pRect, dRect;
601 if (!GetPointerDeviceRects(penInfo->pointerInfo.sourceDevice, &pRect, &dRect))
602 return false;
603
604 const auto systemId = (qint64)penInfo->pointerInfo.sourceDevice;
605 const QPoint globalPos = QPoint(penInfo->pointerInfo.ptPixelLocation.x, penInfo->pointerInfo.ptPixelLocation.y);
606 const QPoint localPos = QWindowsGeometryHint::mapFromGlobal(hwnd, globalPos);
607 const QPointF hiResGlobalPos = QPointF(dRect.left + qreal(penInfo->pointerInfo.ptHimetricLocation.x - pRect.left)
608 / (pRect.right - pRect.left) * (dRect.right - dRect.left),
609 dRect.top + qreal(penInfo->pointerInfo.ptHimetricLocation.y - pRect.top)
610 / (pRect.bottom - pRect.top) * (dRect.bottom - dRect.top));
611 const bool hasPressure = (penInfo->penMask & PEN_MASK_PRESSURE) != 0;
612 const bool hasRotation = (penInfo->penMask & PEN_MASK_ROTATION) != 0;
613 const qreal pressure = hasPressure ? qreal(penInfo->pressure) / 1024.0 : 0.5;
614 const qreal rotation = hasRotation ? qreal(penInfo->rotation) : 0.0;
615 const qreal tangentialPressure = 0.0;
616 const bool hasTiltX = (penInfo->penMask & PEN_MASK_TILT_X) != 0;
617 const bool hasTiltY = (penInfo->penMask & PEN_MASK_TILT_Y) != 0;
618 const int xTilt = hasTiltX ? penInfo->tiltX : 0;
619 const int yTilt = hasTiltY ? penInfo->tiltY : 0;
620 const int z = 0;
621
622 if (QWindowsContext::verbose > 1)
623 qCDebug(lcQpaEvents).noquote().nospace() << Qt::showbase
624 << __FUNCTION__ << " systemId=" << systemId
625 << " globalPos=" << globalPos << " localPos=" << localPos << " hiResGlobalPos=" << hiResGlobalPos
626 << " message=" << Qt::hex << msg.message
627 << " flags=" << Qt::hex << penInfo->pointerInfo.pointerFlags;
628
629 QPointingDevice::PointerType type;
630 // Since it may be the middle button, so if the checks fail then it should
631 // be set to Middle if it was used.
632 Qt::MouseButtons mouseButtons = queryMouseButtons();
633
634 const bool pointerInContact = IS_POINTER_INCONTACT_WPARAM(msg.wParam);
635 if (pointerInContact)
636 mouseButtons = Qt::LeftButton;
637
638 if (penInfo->penFlags & (PEN_FLAG_ERASER | PEN_FLAG_INVERTED)) {
639 type = QPointingDevice::PointerType::Eraser;
640 } else {
641 type = QPointingDevice::PointerType::Pen;
642 if (pointerInContact && penInfo->penFlags & PEN_FLAG_BARREL)
643 mouseButtons = Qt::RightButton; // Either left or right, not both
644 }
645
646 auto device = findTabletDevice(type);
647 if (device.isNull()) {
648 QInputDevice::Capabilities caps(QInputDevice::Capability::Position
649 | QInputDevice::Capability::MouseEmulation
650 | QInputDevice::Capability::Hover);
651 if (hasPressure)
652 caps |= QInputDevice::Capability::Pressure;
653 if (hasRotation)
654 caps |= QInputDevice::Capability::Rotation;
655 if (hasTiltX)
656 caps |= QInputDevice::Capability::XTilt;
657 if (hasTiltY)
658 caps |= QInputDevice::Capability::YTilt;
659 const qint64 uniqueId = systemId | (qint64(type) << 32L);
660 device.reset(new QPointingDevice(QStringLiteral("wmpointer"),
661 systemId, QInputDevice::DeviceType::Stylus,
662 type, caps, 1, 3, QString(),
663 QPointingDeviceUniqueId::fromNumericId(uniqueId)));
664 QWindowSystemInterface::registerInputDevice(device.data());
665 m_tabletDevices.append(device);
666 }
667
668 const auto uniqueId = device->uniqueId().numericId();
669 m_activeTabletDevice = device;
670
671 switch (msg.message) {
672 case WM_POINTERENTER: {
673 QWindowSystemInterface::handleTabletEnterLeaveProximityEvent(window, msg.time, device.data(), true);
674 m_windowUnderPointer = window;
675 // The local coordinates may fall outside the window.
676 // Wait until the next update to send the enter event.
677 m_needsEnterOnPointerUpdate = true;
678 break;
679 }
680 case WM_POINTERLEAVE:
681 if (m_windowUnderPointer && m_windowUnderPointer == m_currentWindow) {
682 QWindowSystemInterface::handleLeaveEvent(m_windowUnderPointer);
683 m_windowUnderPointer = nullptr;
684 m_currentWindow = nullptr;
685 }
686 QWindowSystemInterface::handleTabletEnterLeaveProximityEvent(window, msg.time, device.data(), false);
687 break;
688 case WM_POINTERDOWN:
689 case WM_POINTERUP:
690 case WM_POINTERUPDATE: {
691 QWindow *target = QGuiApplicationPrivate::tabletDevicePoint(uniqueId).target; // Pass to window that grabbed it.
692 if (!target && m_windowUnderPointer)
693 target = m_windowUnderPointer;
694 if (!target)
695 target = window;
696
697 if (m_needsEnterOnPointerUpdate) {
698 m_needsEnterOnPointerUpdate = false;
699 if (window != m_currentWindow) {
700 // make sure we subscribe to leave events for this window
701 trackLeave(hwnd);
702
703 QWindowSystemInterface::handleEnterEvent(window, localPos, globalPos);
704 m_currentWindow = window;
705 if (QWindowsWindow *wumPlatformWindow = QWindowsWindow::windowsWindowOf(target))
706 wumPlatformWindow->applyCursor();
707 }
708 }
709 const auto *keyMapper = QWindowsContext::instance()->keyMapper();
710 const Qt::KeyboardModifiers keyModifiers = keyMapper->queryKeyboardModifiers();
711
712 QWindowSystemInterface::handleTabletEvent(target, msg.time, device.data(),
713 localPos, hiResGlobalPos, mouseButtons,
714 pressure, xTilt, yTilt, tangentialPressure,
715 rotation, z, keyModifiers);
716 return false; // Allow mouse messages to be generated.
717 }
718 }
719 return true;
720#else
721 Q_UNUSED(window);
722 Q_UNUSED(hwnd);
723 Q_UNUSED(et);
724 Q_UNUSED(msg);
725 Q_UNUSED(vPenInfo);
726 return false;
727#endif
728}
729
731{
732 // For details, see
733 // https://docs.microsoft.com/en-us/windows/desktop/tablet/system-events-and-mouse-messages
734 const LONG_PTR SIGNATURE_MASK = 0xFFFFFF00;
735 const LONG_PTR MI_WP_SIGNATURE = 0xFF515700;
736
737 return ((::GetMessageExtraInfo() & SIGNATURE_MASK) == MI_WP_SIGNATURE);
738}
739
740bool QWindowsPointerHandler::translateMouseWheelEvent(QWindow *window,
741 QWindow *currentWindowUnderPointer,
742 MSG msg,
743 QPoint globalPos,
744 Qt::KeyboardModifiers keyModifiers)
745{
746 QWindow *receiver = currentWindowUnderPointer;
747 if (!isValidWheelReceiver(receiver))
748 receiver = window;
749 if (!isValidWheelReceiver(receiver))
750 return true;
751
752 int delta = GET_WHEEL_DELTA_WPARAM(msg.wParam);
753
754 // Qt horizontal wheel rotation orientation is opposite to the one in WM_MOUSEHWHEEL
755 if (msg.message == WM_MOUSEHWHEEL)
756 delta = -delta;
757
758 const QPoint angleDelta = (msg.message == WM_MOUSEHWHEEL || (keyModifiers & Qt::AltModifier)) ?
759 QPoint(delta, 0) : QPoint(0, delta);
760
761 QPoint localPos = QWindowsGeometryHint::mapFromGlobal(receiver, globalPos);
762
763 QWindowSystemInterface::handleWheelEvent(receiver, msg.time, localPos, globalPos, QPoint(), angleDelta, keyModifiers);
764 return true;
765}
766
767// Process legacy mouse messages here.
769 HWND hwnd,
770 QtWindows::WindowsEventType et,
771 MSG msg,
772 LRESULT *result)
773{
774 *result = 0;
775
776 QPoint localPos;
777 QPoint globalPos;
778 QPoint eventPos(GET_X_LPARAM(msg.lParam), GET_Y_LPARAM(msg.lParam));
779
780 if ((et == QtWindows::MouseWheelEvent) || (et & QtWindows::NonClientEventFlag)) {
781 globalPos = eventPos;
782 localPos = QWindowsGeometryHint::mapFromGlobal(hwnd, eventPos);
783 } else {
784 if (QWindowsBaseWindow::isRtlLayout(hwnd)) {
785 RECT clientArea;
786 GetClientRect(hwnd, &clientArea);
787 eventPos.setX(clientArea.right - eventPos.x());
788 }
789
790 globalPos = QWindowsGeometryHint::mapToGlobal(hwnd, eventPos);
791 auto targetHwnd = hwnd;
792 if (auto *pw = window->handle())
793 targetHwnd = HWND(pw->winId());
794 localPos = targetHwnd == hwnd
795 ? eventPos
796 : QWindowsGeometryHint::mapFromGlobal(targetHwnd, globalPos);
797 }
798
799 const auto *keyMapper = QWindowsContext::instance()->keyMapper();
800 const Qt::KeyboardModifiers keyModifiers = keyMapper->queryKeyboardModifiers();
801 QWindow *currentWindowUnderPointer = getWindowUnderPointer(window, globalPos);
802
803 if (et == QtWindows::MouseWheelEvent)
804 return translateMouseWheelEvent(window, currentWindowUnderPointer, msg, globalPos, keyModifiers);
805
806 // Windows sends a mouse move with no buttons pressed to signal "Enter"
807 // when a window is shown over the cursor. Discard the event and only use
808 // it for generating QEvent::Enter to be consistent with other platforms -
809 // X11 and macOS.
810 bool discardEvent = false;
811 if (msg.message == WM_MOUSEMOVE) {
812 Q_CONSTINIT static QPoint lastMouseMovePos;
813 if (msg.wParam == 0 && (m_windowUnderPointer.isNull() || globalPos == lastMouseMovePos))
814 discardEvent = true;
815 lastMouseMovePos = globalPos;
816 }
817
818 Qt::MouseEventSource source = Qt::MouseEventNotSynthesized;
819 const QPointingDevice *device = primaryMouse();
820
821 // Following the logic of the old mouse handler, only events synthesized
822 // for touch screen are marked as such. On some systems, using the bit 7 of
823 // the extra msg info for checking if synthesized for touch does not work,
824 // so we use the pointer type of the last pointer message.
826 switch (m_pointerType) {
827 case QT_PT_TOUCH:
828 if (QWindowsIntegration::instance()->options() & QWindowsIntegration::DontPassOsMouseEventsSynthesizedFromTouch)
829 return false;
830 source = Qt::MouseEventSynthesizedBySystem;
831 if (!m_touchDevice.isNull())
832 device = m_touchDevice.data();
833 break;
834 case QT_PT_PEN:
835#if QT_CONFIG(tabletevent)
836 qCDebug(lcQpaTablet) << "ignoring synth-mouse event for tablet event from" << device;
837 return false;
838#endif
839 break;
840 }
841 }
842
843 const MouseEvent mouseEvent = eventFromMsg(msg);
844 Qt::MouseButtons mouseButtons;
845
846 if (mouseEvent.type >= QEvent::NonClientAreaMouseMove && mouseEvent.type <= QEvent::NonClientAreaMouseButtonDblClick)
847 mouseButtons = queryMouseButtons();
848 else
849 mouseButtons = mouseButtonsFromKeyState(msg.wParam);
850
851 // When the left/right mouse buttons are pressed over the window title bar
852 // WM_NCLBUTTONDOWN/WM_NCRBUTTONDOWN messages are received. But no UP
853 // messages are received on release, only WM_NCMOUSEMOVE/WM_MOUSEMOVE.
854 // We detect it and generate the missing release events here. (QTBUG-75678)
855 // The last event vars are cleared on QWindowsContext::handleExitSizeMove()
856 // to avoid generating duplicated release events.
857 if (m_lastEventType == QEvent::NonClientAreaMouseButtonPress
858 && (mouseEvent.type == QEvent::NonClientAreaMouseMove || mouseEvent.type == QEvent::MouseMove)
859 && (m_lastEventButton & mouseButtons) == 0) {
860 auto releaseType = mouseEvent.type == QEvent::NonClientAreaMouseMove ?
861 QEvent::NonClientAreaMouseButtonRelease : QEvent::MouseButtonRelease;
862 QWindowSystemInterface::handleMouseEvent(window, msg.time, device, localPos, globalPos, mouseButtons, m_lastEventButton,
863 releaseType, keyModifiers, source);
864 }
865 m_lastEventType = mouseEvent.type;
866 m_lastEventButton = mouseEvent.button;
867
868 if (mouseEvent.type >= QEvent::NonClientAreaMouseMove && mouseEvent.type <= QEvent::NonClientAreaMouseButtonDblClick) {
869 QWindowSystemInterface::handleMouseEvent(window, msg.time, device, localPos, globalPos, mouseButtons,
870 mouseEvent.button, mouseEvent.type, keyModifiers, source);
871 return false; // Allow further event processing
872 }
873
874 if (msg.message == WM_MOUSELEAVE) {
875 if (window == m_currentWindow) {
876 QWindow *leaveTarget = m_windowUnderPointer ? m_windowUnderPointer : m_currentWindow;
877 qCDebug(lcQpaEvents) << "Leaving window " << leaveTarget;
878 QWindowSystemInterface::handleLeaveEvent(leaveTarget);
879 m_windowUnderPointer = nullptr;
880 m_currentWindow = nullptr;
881 }
882 return true;
883 }
884
885 handleWindowActivation(window, mouseEvent.type);
886 handleCaptureRelease(window, currentWindowUnderPointer, hwnd, mouseEvent.type, mouseButtons);
887 handleEnterLeave(window, currentWindowUnderPointer, globalPos);
888
889 if (!discardEvent && mouseEvent.type != QEvent::None) {
890 QWindowSystemInterface::handleMouseEvent(window, msg.time, device, localPos, globalPos, mouseButtons,
891 mouseEvent.button, mouseEvent.type, keyModifiers, source);
892 }
893
894 // QTBUG-48117, force synchronous handling for the extra buttons so that WM_APPCOMMAND
895 // is sent for unhandled WM_XBUTTONDOWN.
896 return (msg.message != WM_XBUTTONUP && msg.message != WM_XBUTTONDOWN && msg.message != WM_XBUTTONDBLCLK)
897 || QWindowSystemInterface::flushWindowSystemEvents();
898}
899
900QT_END_NAMESPACE
\inmodule QtCore\reentrant
Definition qpoint.h:30
Singleton container for all relevant information.
QPlatformKeyMapper * keyMapper() const
static QWindowsContext * instance()
bool translatePointerEvent(QWindow *window, HWND hwnd, QtWindows::WindowsEventType et, MSG msg, LRESULT *result)
bool translateMouseEvent(QWindow *window, HWND hwnd, QtWindows::WindowsEventType et, MSG msg, LRESULT *result)
Windows screen.
static QWindow * windowAt(const QPoint &point, unsigned flags)
Raster or OpenGL Window.
bool testFlag(unsigned f) const
void applyCursor()
Applies to cursor property set on the window to the global cursor.
bool hasMouseCapture() const
WindowsEventType
Enumerations for WM_XX events.
#define WM_POINTERCAPTURECHANGED
#define WM_POINTERLEAVE
#define WM_POINTERUP
static bool isValidWheelReceiver(QWindow *candidate)
static bool trackLeave(HWND hwnd)
static QWindow * getWindowUnderPointer(QWindow *window, QPoint globalPos)
static Qt::MouseButton extraButton(WPARAM wParam)
const QPointingDevice * primaryMouse()
static MouseEvent eventFromMsg(const MSG &msg)
static bool isMouseEventSynthesizedFromPenOrTouch()
static Qt::MouseButtons mouseButtonsFromKeyState(WPARAM keyState)