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
qwindowsdirectmanipulation.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 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
10
11#include <QtCore/private/qcomobject_p.h>
12#include <QtCore/private/qsystemerror_p.h>
13#include <QtCore/qbasictimer.h>
14#include <QtCore/qobject.h>
15#include <QtCore/qpointer.h>
16#include <QtGui/qwindow.h>
17#include <QtGui/private/qhighdpiscaling_p.h>
18#include <qpa/qwindowsysteminterface.h>
19
20#include <limits>
21#include <memory>
22#include <utility>
23
24QT_BEGIN_NAMESPACE
25
26using namespace Qt::StringLiterals;
27
28// Direct Manipulation only reports transforms while it is being pumped; 8ms
29// keeps up with a 120Hz display without spinning needlessly.
30static constexpr int updateIntervalMs = 8;
31
32// How long to keep pumping after the last viewport stopped interacting, so
33// that a contact which Direct Manipulation ends up not manipulating at all
34// cannot leave the timer running forever.
35static constexpr int maxIdleUpdates = 25;
36
37// We never display the content Direct Manipulation manipulates, we only read
38// the transform it computes for it, so the viewport rectangle is arbitrary. It
39// does have to cover the whole window, since contacts outside of it are not
40// manipulated, and a generous fixed size saves us from tracking resizes.
41static constexpr LONG viewportSize = 1 << 20;
42
43// Bounds on the accumulated scale within a single gesture. The transform is
44// reset to the identity after every gesture, so these only need to be wide
45// enough that a single pinch never runs into them and gets stuck.
46static constexpr float minimumZoom = 0.01f;
47static constexpr float maximumZoom = 100.0f;
48
49// Qt expects wheel angle deltas in eighths of a degree. Interpret a pixel as a
50// quarter of a degree, as the Cocoa plugin does for trackpads, so that
51// applications reading only angleDelta() scroll by a comparable amount.
52static constexpr int pixelsToDegrees = 2;
53
54// A pinch is the only gesture Direct Manipulation reports a scale for.
55static constexpr int pinchFingerCount = 2;
56
57static const char *statusName(DIRECTMANIPULATION_STATUS status)
58{
59 switch (status) {
60 case DIRECTMANIPULATION_BUILDING: return "Building";
61 case DIRECTMANIPULATION_ENABLED: return "Enabled";
62 case DIRECTMANIPULATION_DISABLED: return "Disabled";
63 case DIRECTMANIPULATION_RUNNING: return "Running";
64 case DIRECTMANIPULATION_INERTIA: return "Inertia";
65 case DIRECTMANIPULATION_READY: return "Ready";
66 case DIRECTMANIPULATION_SUSPENDED: return "Suspended";
67 }
68 return "Unknown";
69}
70
72{
73 return QWindowsContext::instance()->keyMapper()->queryKeyboardModifiers();
74}
75
76static void warnFailure(const char *what, HRESULT hr)
77{
78 qCWarning(lcQpaGestures, "%s: %s", what, qPrintable(QSystemError::windowsComString(hr)));
79}
80
81/*!
82 \internal
83
84 Handles the Direct Manipulation callbacks for a single window and turns the
85 content transforms into Qt events.
86
87 Direct Manipulation reports an absolute transform for the (notional)
88 content of its viewport, so an interaction is a stream of transforms which
89 we differentiate to get per-event deltas. A gesture either pans or zooms,
90 but never both, so whichever of the two deltas changes tells us which one
91 the user is performing.
92*/
96{
97public:
99 : m_dm(dm), m_window(window), m_hwnd(hwnd) {}
100
101 bool init(IDirectManipulationManager *manager);
102 void destroy(IDirectManipulationManager *manager);
103
104 bool setContact(UINT32 pointerId);
105
106 bool isInteracting() const
107 {
108 return m_status == DIRECTMANIPULATION_RUNNING || m_status == DIRECTMANIPULATION_INERTIA;
109 }
110
111 // IDirectManipulationViewportEventHandler
118
119 // IDirectManipulationInteractionEventHandler
122
123private:
125
126 enum class Gesture { None, Scroll, Zoom };
127
128 void deliverScroll(QPointF delta);
129 void deliverZoom(qreal scaleDelta);
130 void endGesture();
131 void endInteraction(IDirectManipulationViewport *viewport);
132 QPoint globalPosition() const { return QWindowsCursor::mousePosition(); }
133 QPoint localPosition(QPoint globalPos) const
134 {
135 return QWindowsGeometryHint::mapFromGlobal(m_hwnd, globalPos);
136 }
137
139 QPointer<QWindow> m_window;
140 const HWND m_hwnd;
141 ComPtr<IDirectManipulationViewport2> m_viewport;
142 DWORD m_eventHandlerCookie = 0;
143 DIRECTMANIPULATION_STATUS m_status = DIRECTMANIPULATION_BUILDING;
144 // Which kind of gesture the deltas of this interaction are being reported
145 // as, decided by the first delta which is not zero.
146 Gesture m_gesture = Gesture::None;
147 // The transform reported by the previous content update, and whether there
148 // has been one since this interaction started.
149 bool m_haveReference = false;
150 float m_referenceScale = 1;
151 QPointF m_referenceTranslation;
152 // Sub-pixel scroll movement which has not been delivered yet, so that slow
153 // dragging is not lost to rounding.
154 QPointF m_pendingScroll;
155};
156
157bool QWindowsDirectManipulationViewport::init(IDirectManipulationManager *manager)
158{
159 HRESULT hr = manager->CreateViewport(nullptr, m_hwnd, IID_PPV_ARGS(&m_viewport));
160 if (FAILED(hr)) {
161 warnFailure("Failed to create a Direct Manipulation viewport", hr);
162 return false;
163 }
164
165 const auto configuration =
166 DIRECTMANIPULATION_CONFIGURATION(DIRECTMANIPULATION_CONFIGURATION_INTERACTION
167 | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_X
168 | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_Y
169 | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_INERTIA
170 | DIRECTMANIPULATION_CONFIGURATION_SCALING
171 | DIRECTMANIPULATION_CONFIGURATION_SCALING_INERTIA);
172 hr = m_viewport->ActivateConfiguration(configuration);
173 if (FAILED(hr)) {
174 warnFailure("Failed to configure a Direct Manipulation viewport", hr);
175 return false;
176 }
177
178 // Without MANUALUPDATE, Direct Manipulation drives itself, but then it
179 // oscillates between running and inertia and never settles back to
180 // DIRECTMANIPULATION_READY, so gestures would never end.
181 hr = m_viewport->SetViewportOptions(DIRECTMANIPULATION_VIEWPORT_OPTIONS_MANUALUPDATE);
182 if (FAILED(hr)) {
183 warnFailure("Failed to set Direct Manipulation viewport options", hr);
184 return false;
185 }
186
187 const RECT rect = { 0, 0, viewportSize, viewportSize };
188 hr = m_viewport->SetViewportRect(&rect);
189 if (FAILED(hr)) {
190 warnFailure("Failed to set a Direct Manipulation viewport rect", hr);
191 return false;
192 }
193
194 ComPtr<IDirectManipulationPrimaryContent> primaryContent;
195 if (SUCCEEDED(m_viewport->GetPrimaryContent(IID_PPV_ARGS(&primaryContent))))
196 primaryContent->SetZoomBoundaries(minimumZoom, maximumZoom);
197
198 hr = m_viewport->AddEventHandler(m_hwnd, this, &m_eventHandlerCookie);
199 if (FAILED(hr)) {
200 warnFailure("Failed to install a Direct Manipulation event handler", hr);
201 return false;
202 }
203
204 hr = m_viewport->Enable();
205 if (FAILED(hr)) {
206 warnFailure("Failed to enable a Direct Manipulation viewport", hr);
207 return false;
208 }
209
210 qCDebug(lcQpaGestures) << "Direct Manipulation enabled for" << m_window.data();
211 return true;
212}
213
214void QWindowsDirectManipulationViewport::destroy(IDirectManipulationManager *manager)
215{
216 if (!m_viewport)
217 return;
218 m_viewport->Stop();
219 if (m_eventHandlerCookie)
220 m_viewport->RemoveEventHandler(m_eventHandlerCookie);
221 m_viewport->Abandon();
222 m_viewport.Reset();
223 manager->Deactivate(m_hwnd);
224}
225
227{
228 if (!m_viewport)
229 return false;
230 const HRESULT hr = m_viewport->SetContact(pointerId);
231 if (FAILED(hr)) {
232 qCDebug(lcQpaGestures, "Direct Manipulation refused contact %u: %s", pointerId,
233 qPrintable(QSystemError::windowsComString(hr)));
234 return false;
235 }
236 // The interaction only produces transforms while Direct Manipulation is
237 // pumped, and the first of them arrive before it reports RUNNING.
238 m_dm->startUpdates();
239 return true;
240}
241
242HRESULT QWindowsDirectManipulationViewport::OnViewportStatusChanged(IDirectManipulationViewport *viewport,
243 DIRECTMANIPULATION_STATUS current,
244 DIRECTMANIPULATION_STATUS previous)
245{
246 qCDebug(lcQpaGestures, "Direct Manipulation status %s -> %s", statusName(previous),
247 statusName(current));
248 m_status = current;
249
250 switch (current) {
251 case DIRECTMANIPULATION_READY:
252 // The interaction, including any inertia, is over. Reset the transform
253 // so that the next one starts from a known scale and translation
254 // instead of accumulating indefinitely.
255 endInteraction(viewport);
256 break;
257 case DIRECTMANIPULATION_ENABLED:
258 case DIRECTMANIPULATION_DISABLED:
259 case DIRECTMANIPULATION_SUSPENDED:
260 endInteraction(nullptr);
261 break;
262 case DIRECTMANIPULATION_RUNNING:
263 case DIRECTMANIPULATION_INERTIA:
264 case DIRECTMANIPULATION_BUILDING:
265 break;
266 }
267 return S_OK;
268}
269
270HRESULT QWindowsDirectManipulationViewport::OnViewportUpdated(IDirectManipulationViewport *)
271{
272 return S_OK;
273}
274
275HRESULT QWindowsDirectManipulationViewport::OnContentUpdated(IDirectManipulationViewport *,
276 IDirectManipulationContent *content)
277{
278 float transform[6];
279 if (FAILED(content->GetContentTransform(transform, 6)))
280 return S_OK;
281
282 // A 3x2 matrix. Direct Manipulation only ever scales uniformly and
283 // translates, so transform[1] and transform[2] are always zero.
284 const float scale = transform[0];
285 const QPointF translation(transform[4], transform[5]);
286
287 if (!m_haveReference) {
288 // The transform is not reliably the identity at the start of an
289 // interaction, so take the first update as the reference to
290 // differentiate the following ones against.
291 m_haveReference = true;
292 m_referenceScale = scale;
293 m_referenceTranslation = translation;
294 return S_OK;
295 }
296
297 const float scaleDelta = scale - m_referenceScale;
298 const QPointF translationDelta = translation - m_referenceTranslation;
299 m_referenceScale = scale;
300 m_referenceTranslation = translation;
301
302 // While zooming, the translation changes as well, because Direct
303 // Manipulation scales the content about the point between the fingers. The
304 // scale is what the user is driving, so let it take precedence.
305 if (scaleDelta != 0)
306 deliverZoom(scaleDelta);
307 else if (!translationDelta.isNull())
308 deliverScroll(translationDelta);
309
310 return S_OK;
311}
312
313HRESULT QWindowsDirectManipulationViewport::OnInteraction(IDirectManipulationViewport2 *,
314 DIRECTMANIPULATION_INTERACTION_TYPE interaction)
315{
316 // The status changes tell us all we need about the lifetime of an
317 // interaction; this is only interesting while debugging.
318 qCDebug(lcQpaGestures, "Direct Manipulation interaction type %d", int(interaction));
319 return S_OK;
320}
321
322void QWindowsDirectManipulationViewport::deliverScroll(QPointF delta)
323{
324 if (m_window.isNull())
325 return;
326
327 if (m_gesture == Gesture::Zoom)
328 endGesture();
329
330 // Direct Manipulation works in physical pixels, QWheelEvent::pixelDelta()
331 // in device independent ones.
332 m_pendingScroll += delta / QHighDpiScaling::factor(m_window.data());
333 const QPoint pixelDelta = m_pendingScroll.toPoint();
334 if (pixelDelta.isNull())
335 return;
336 m_pendingScroll -= QPointF(pixelDelta);
337
338 Qt::ScrollPhase phase = Qt::ScrollUpdate;
339 if (m_gesture != Gesture::Scroll) {
340 m_gesture = Gesture::Scroll;
341 phase = Qt::ScrollBegin;
342 } else if (m_status == DIRECTMANIPULATION_INERTIA) {
343 phase = Qt::ScrollMomentum;
344 }
345
346 const QPoint globalPos = globalPosition();
347 qCDebug(lcQpaGestures) << "scroll" << pixelDelta << "phase" << phase << "to" << m_window.data();
348 QWindowSystemInterface::handleWheelEvent(m_window.data(), ::GetTickCount(),
349 m_dm->device().data(), localPosition(globalPos),
350 globalPos, pixelDelta,
351 pixelDelta * pixelsToDegrees,
352 keyboardModifiers(), phase,
353 Qt::MouseEventSynthesizedBySystem);
354}
355
356void QWindowsDirectManipulationViewport::deliverZoom(qreal scaleDelta)
357{
358 if (m_window.isNull())
359 return;
360
361 if (m_gesture == Gesture::Scroll)
362 endGesture();
363
364 const QPoint globalPos = globalPosition();
365 const QPoint localPos = localPosition(globalPos);
366
367 if (m_gesture != Gesture::Zoom) {
368 m_gesture = Gesture::Zoom;
369 QWindowSystemInterface::handleGestureEvent(m_window.data(), ::GetTickCount(),
370 m_dm->device().data(), Qt::BeginNativeGesture,
371 localPos, globalPos, pinchFingerCount);
372 }
373
374 qCDebug(lcQpaGestures) << "zoom by" << scaleDelta << "to" << m_window.data();
375 QWindowSystemInterface::handleGestureEventWithRealValue(m_window.data(), ::GetTickCount(),
376 m_dm->device().data(),
377 Qt::ZoomNativeGesture, scaleDelta,
378 localPos, globalPos, pinchFingerCount);
379}
380
381void QWindowsDirectManipulationViewport::endGesture()
382{
383 const Gesture gesture = std::exchange(m_gesture, Gesture::None);
384 m_pendingScroll = {};
385
386 if (gesture == Gesture::None || m_window.isNull())
387 return;
388
389 const QPoint globalPos = globalPosition();
390 const QPoint localPos = localPosition(globalPos);
391
392 if (gesture == Gesture::Scroll) {
393 qCDebug(lcQpaGestures) << "scroll ended for" << m_window.data();
394 QWindowSystemInterface::handleWheelEvent(m_window.data(), ::GetTickCount(),
395 m_dm->device().data(), localPos, globalPos,
396 QPoint(), QPoint(),
397 keyboardModifiers(),
398 Qt::ScrollEnd,
399 Qt::MouseEventSynthesizedBySystem);
400 } else {
401 qCDebug(lcQpaGestures) << "zoom ended for" << m_window.data();
402 QWindowSystemInterface::handleGestureEvent(m_window.data(), ::GetTickCount(),
403 m_dm->device().data(), Qt::EndNativeGesture,
404 localPos, globalPos, pinchFingerCount);
405 }
406}
407
408void QWindowsDirectManipulationViewport::endInteraction(IDirectManipulationViewport *viewport)
409{
410 endGesture();
411 m_haveReference = false;
412
413 ComPtr<IDirectManipulationContent> content;
414 if (viewport && SUCCEEDED(viewport->GetPrimaryContent(IID_PPV_ARGS(&content)))) {
415 static constexpr float identity[6] = { 1, 0, 0, 1, 0, 0 };
416 content->SyncContentTransform(identity, 6);
417 }
418}
419
420/*!
421 \internal
422 Pumps Direct Manipulation while an interaction is in progress.
423*/
425{
426public:
427 explicit UpdatePump(QWindowsDirectManipulation *dm) : m_dm(dm) {}
428
429 void start()
430 {
431 if (!m_timer.isActive())
432 m_timer.start(updateIntervalMs, Qt::PreciseTimer, this);
433 }
434 void stop() { m_timer.stop(); }
435
436protected:
437 void timerEvent(QTimerEvent *) override { m_dm->update(); }
438
439private:
441 QBasicTimer m_timer;
442};
443
445{
446 std::unique_ptr<QWindowsDirectManipulation> dm(new QWindowsDirectManipulation);
447 return dm->init() ? dm.release() : nullptr;
448}
449
451{
452 HRESULT hr = CoCreateInstance(CLSID_DirectManipulationManager, nullptr, CLSCTX_INPROC_SERVER,
453 IID_PPV_ARGS(&m_manager));
454 if (FAILED(hr)) {
455 warnFailure("Failed to create the Direct Manipulation manager", hr);
456 return false;
457 }
458
459 hr = m_manager->GetUpdateManager(IID_PPV_ARGS(&m_updateManager));
460 if (FAILED(hr)) {
461 warnFailure("Failed to get the Direct Manipulation update manager", hr);
462 return false;
463 }
464
465 m_pump.reset(new UpdatePump(this));
466 return true;
467}
468
470{
471 for (auto it = m_viewports.cbegin(), end = m_viewports.cend(); it != end; ++it)
472 it.value()->destroy(m_manager.Get());
473 m_viewports.clear();
474}
475
476void QWindowsDirectManipulation::registerWindow(QWindow *window, HWND hwnd)
477{
478 if (m_viewports.contains(hwnd))
479 return;
480
481 // Activating the window is what makes Windows send it DM_POINTERHITTEST.
482 const HRESULT hr = m_manager->Activate(hwnd);
483 if (FAILED(hr)) {
484 warnFailure("Failed to activate Direct Manipulation for a window", hr);
485 return;
486 }
487
488 auto viewport = makeComObject<QWindowsDirectManipulationViewport>(this, window, hwnd);
489 if (!viewport->init(m_manager.Get())) {
490 m_manager->Deactivate(hwnd);
491 return;
492 }
493 m_viewports.insert(hwnd, viewport);
494}
495
497{
498 if (auto viewport = m_viewports.take(hwnd))
499 viewport->destroy(m_manager.Get());
500}
501
503{
504 const UINT32 pointerId = GET_POINTERID_WPARAM(wParam);
505 POINTER_INPUT_TYPE pointerType = PT_POINTER;
506 // Leave touch screens and pens to QWindowsPointerHandler, which turns them
507 // into touch and tablet events; only touchpads are gesture sources here.
508 if (!GetPointerType(pointerId, &pointerType) || pointerType != PT_TOUCHPAD)
509 return false;
510
511 const auto it = m_viewports.constFind(hwnd);
512 return it != m_viewports.cend() && it.value()->setContact(pointerId);
513}
514
516{
517 if (!m_device) {
518 // Direct Manipulation does not tell us which touchpad it is reporting
519 // for, so this stands in for all of them. QInputDevicePrivate::fromId()
520 // looks devices up by system ID alone, so use one which cannot collide
521 // with the small IDs QWindowsPointerHandler hands out.
522 // TODO: report one device per touchpad, with its system-provided name
523 const qint64 systemId = std::numeric_limits<qint64>::max();
524 m_device.reset(new QPointingDevice("touchpad"_L1, systemId,
525 QInputDevice::DeviceType::TouchPad,
526 QPointingDevice::PointerType::Finger,
527 QInputDevice::Capability::Position
528 | QInputDevice::Capability::Scroll,
529 pinchFingerCount, 3));
530 QWindowSystemInterface::registerInputDevice(m_device.data());
531 }
532 return m_device;
533}
534
535void QWindowsDirectManipulation::startUpdates()
536{
537 m_idleUpdates = 0;
538 m_pump->start();
539}
540
541void QWindowsDirectManipulation::update()
542{
543 // Any status change and content transform is reported from within this
544 // call, so the state checked below is up to date.
545 m_updateManager->Update(nullptr);
546
547 if (isInteracting())
548 m_idleUpdates = 0;
549 else if (++m_idleUpdates > maxIdleUpdates)
550 m_pump->stop();
551}
552
553bool QWindowsDirectManipulation::isInteracting() const
554{
555 for (auto it = m_viewports.cbegin(), end = m_viewports.cend(); it != end; ++it) {
556 if (it.value()->isInteracting())
557 return true;
558 }
559 return false;
560}
561
562QT_END_NAMESPACE
\inmodule QtCore\reentrant
Definition qpoint.h:30
Singleton container for all relevant information.
QPlatformKeyMapper * keyMapper() const
static QWindowsContext * instance()
Platform cursor implementation.
static QPoint mousePosition()
bool init(IDirectManipulationManager *manager)
void destroy(IDirectManipulationManager *manager)
~QWindowsDirectManipulationViewport() override=default
QWindowsDirectManipulationViewport(QWindowsDirectManipulation *dm, QWindow *window, HWND hwnd)
void timerEvent(QTimerEvent *) override
This event handler can be reimplemented in a subclass to receive timer events for the object.
void registerWindow(QWindow *window, HWND hwnd)
static QWindowsDirectManipulation * create()
const QPointingDevicePtr & device()
bool handlePointerHitTest(HWND hwnd, WPARAM wParam)
static const char * statusName(DIRECTMANIPULATION_STATUS status)
static Qt::KeyboardModifiers keyboardModifiers()
static constexpr int pixelsToDegrees
static constexpr int maxIdleUpdates
static constexpr int updateIntervalMs
static constexpr float maximumZoom
static constexpr float minimumZoom
static constexpr LONG viewportSize
static constexpr int pinchFingerCount
static void warnFailure(const char *what, HRESULT hr)