Bug 1829659 - Remove `import.py` because it's not used anymore r=glandium,bwc
[gecko.git] / widget / windows / WinMouseScrollHandler.cpp
blob74cb11256946740fb3886fc88f419acdf50d4186
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "mozilla/DebugOnly.h"
9 #include "mozilla/Logging.h"
11 #include "WinMouseScrollHandler.h"
12 #include "nsWindow.h"
13 #include "nsWindowDefs.h"
14 #include "KeyboardLayout.h"
15 #include "WinUtils.h"
16 #include "nsGkAtoms.h"
17 #include "nsIDOMWindowUtils.h"
19 #include "mozilla/MiscEvents.h"
20 #include "mozilla/MouseEvents.h"
21 #include "mozilla/Preferences.h"
22 #include "mozilla/dom/WheelEventBinding.h"
23 #include "mozilla/StaticPrefs_mousewheel.h"
25 #include <psapi.h>
27 namespace mozilla {
28 namespace widget {
30 LazyLogModule gMouseScrollLog("MouseScrollHandlerWidgets");
32 static const char* GetBoolName(bool aBool) { return aBool ? "TRUE" : "FALSE"; }
34 MouseScrollHandler* MouseScrollHandler::sInstance = nullptr;
36 bool MouseScrollHandler::Device::sFakeScrollableWindowNeeded = false;
38 bool MouseScrollHandler::Device::SynTP::sInitialized = false;
39 int32_t MouseScrollHandler::Device::SynTP::sMajorVersion = 0;
40 int32_t MouseScrollHandler::Device::SynTP::sMinorVersion = -1;
42 bool MouseScrollHandler::Device::Elantech::sUseSwipeHack = false;
43 bool MouseScrollHandler::Device::Elantech::sUsePinchHack = false;
44 DWORD MouseScrollHandler::Device::Elantech::sZoomUntil = 0;
46 bool MouseScrollHandler::Device::Apoint::sInitialized = false;
47 int32_t MouseScrollHandler::Device::Apoint::sMajorVersion = 0;
48 int32_t MouseScrollHandler::Device::Apoint::sMinorVersion = -1;
50 bool MouseScrollHandler::Device::SetPoint::sMightBeUsing = false;
52 // The duration until timeout of events transaction. The value is 1.5 sec,
53 // it's just a magic number, it was suggested by Logitech's engineer, see
54 // bug 605648 comment 90.
55 #define DEFAULT_TIMEOUT_DURATION 1500
57 /******************************************************************************
59 * MouseScrollHandler
61 ******************************************************************************/
63 /* static */
64 POINTS
65 MouseScrollHandler::GetCurrentMessagePos() {
66 if (SynthesizingEvent::IsSynthesizing()) {
67 return sInstance->mSynthesizingEvent->GetCursorPoint();
69 DWORD pos = ::GetMessagePos();
70 return MAKEPOINTS(pos);
73 // Get rid of the GetMessagePos() API.
74 #define GetMessagePos()
76 /* static */
77 void MouseScrollHandler::Initialize() { Device::Init(); }
79 /* static */
80 void MouseScrollHandler::Shutdown() {
81 delete sInstance;
82 sInstance = nullptr;
85 /* static */
86 MouseScrollHandler* MouseScrollHandler::GetInstance() {
87 if (!sInstance) {
88 sInstance = new MouseScrollHandler();
90 return sInstance;
93 MouseScrollHandler::MouseScrollHandler()
94 : mIsWaitingInternalMessage(false), mSynthesizingEvent(nullptr) {
95 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
96 ("MouseScroll: Creating an instance, this=%p, sInstance=%p", this,
97 sInstance));
100 MouseScrollHandler::~MouseScrollHandler() {
101 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
102 ("MouseScroll: Destroying an instance, this=%p, sInstance=%p", this,
103 sInstance));
105 delete mSynthesizingEvent;
108 /* static */
109 void MouseScrollHandler::MaybeLogKeyState() {
110 if (!MOZ_LOG_TEST(gMouseScrollLog, LogLevel::Debug)) {
111 return;
113 BYTE keyboardState[256];
114 if (::GetKeyboardState(keyboardState)) {
115 for (size_t i = 0; i < ArrayLength(keyboardState); i++) {
116 if (keyboardState[i]) {
117 MOZ_LOG(gMouseScrollLog, LogLevel::Debug,
118 (" Current key state: keyboardState[0x%02zX]=0x%02X (%s)", i,
119 keyboardState[i],
120 ((keyboardState[i] & 0x81) == 0x81) ? "Pressed and Toggled"
121 : (keyboardState[i] & 0x80) ? "Pressed"
122 : (keyboardState[i] & 0x01) ? "Toggled"
123 : "Unknown"));
126 } else {
127 MOZ_LOG(
128 gMouseScrollLog, LogLevel::Debug,
129 ("MouseScroll::MaybeLogKeyState(): Failed to print current keyboard "
130 "state"));
134 /* static */
135 bool MouseScrollHandler::NeedsMessage(UINT aMsg) {
136 switch (aMsg) {
137 case WM_SETTINGCHANGE:
138 case WM_MOUSEWHEEL:
139 case WM_MOUSEHWHEEL:
140 case WM_HSCROLL:
141 case WM_VSCROLL:
142 case MOZ_WM_MOUSEVWHEEL:
143 case MOZ_WM_MOUSEHWHEEL:
144 case MOZ_WM_HSCROLL:
145 case MOZ_WM_VSCROLL:
146 case WM_KEYDOWN:
147 case WM_KEYUP:
148 return true;
150 return false;
153 /* static */
154 bool MouseScrollHandler::ProcessMessage(nsWindow* aWidget, UINT msg,
155 WPARAM wParam, LPARAM lParam,
156 MSGResult& aResult) {
157 Device::Elantech::UpdateZoomUntil();
159 switch (msg) {
160 case WM_SETTINGCHANGE:
161 if (!sInstance) {
162 return false;
164 if (wParam == SPI_SETWHEELSCROLLLINES ||
165 wParam == SPI_SETWHEELSCROLLCHARS) {
166 sInstance->mSystemSettings.MarkDirty();
168 return false;
170 case WM_MOUSEWHEEL:
171 case WM_MOUSEHWHEEL:
172 GetInstance()->ProcessNativeMouseWheelMessage(aWidget, msg, wParam,
173 lParam);
174 sInstance->mSynthesizingEvent->NotifyNativeMessageHandlingFinished();
175 // We don't need to call next wndproc for WM_MOUSEWHEEL and
176 // WM_MOUSEHWHEEL. We should consume them always. If the messages
177 // would be handled by our window again, it caused making infinite
178 // message loop.
179 aResult.mConsumed = true;
180 aResult.mResult = (msg != WM_MOUSEHWHEEL);
181 return true;
183 case WM_HSCROLL:
184 case WM_VSCROLL:
185 aResult.mConsumed = GetInstance()->ProcessNativeScrollMessage(
186 aWidget, msg, wParam, lParam);
187 sInstance->mSynthesizingEvent->NotifyNativeMessageHandlingFinished();
188 aResult.mResult = 0;
189 return true;
191 case MOZ_WM_MOUSEVWHEEL:
192 case MOZ_WM_MOUSEHWHEEL:
193 GetInstance()->HandleMouseWheelMessage(aWidget, msg, wParam, lParam);
194 sInstance->mSynthesizingEvent->NotifyInternalMessageHandlingFinished();
195 // Doesn't need to call next wndproc for internal wheel message.
196 aResult.mConsumed = true;
197 return true;
199 case MOZ_WM_HSCROLL:
200 case MOZ_WM_VSCROLL:
201 GetInstance()->HandleScrollMessageAsMouseWheelMessage(aWidget, msg,
202 wParam, lParam);
203 sInstance->mSynthesizingEvent->NotifyInternalMessageHandlingFinished();
204 // Doesn't need to call next wndproc for internal scroll message.
205 aResult.mConsumed = true;
206 return true;
208 case WM_KEYDOWN:
209 case WM_KEYUP:
210 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
211 ("MouseScroll::ProcessMessage(): aWidget=%p, "
212 "msg=%s(0x%04X), wParam=0x%02zX, ::GetMessageTime()=%ld",
213 aWidget,
214 msg == WM_KEYDOWN ? "WM_KEYDOWN"
215 : msg == WM_KEYUP ? "WM_KEYUP"
216 : "Unknown",
217 msg, wParam, ::GetMessageTime()));
218 MaybeLogKeyState();
219 if (Device::Elantech::HandleKeyMessage(aWidget, msg, wParam, lParam)) {
220 aResult.mResult = 0;
221 aResult.mConsumed = true;
222 return true;
224 return false;
226 default:
227 return false;
231 /* static */
232 nsresult MouseScrollHandler::SynthesizeNativeMouseScrollEvent(
233 nsWindow* aWidget, const LayoutDeviceIntPoint& aPoint,
234 uint32_t aNativeMessage, int32_t aDelta, uint32_t aModifierFlags,
235 uint32_t aAdditionalFlags) {
236 bool useFocusedWindow = !(
237 aAdditionalFlags & nsIDOMWindowUtils::MOUSESCROLL_PREFER_WIDGET_AT_POINT);
239 POINT pt;
240 pt.x = aPoint.x;
241 pt.y = aPoint.y;
243 HWND target = useFocusedWindow ? ::WindowFromPoint(pt) : ::GetFocus();
244 NS_ENSURE_TRUE(target, NS_ERROR_FAILURE);
246 WPARAM wParam = 0;
247 LPARAM lParam = 0;
248 switch (aNativeMessage) {
249 case WM_MOUSEWHEEL:
250 case WM_MOUSEHWHEEL: {
251 lParam = MAKELPARAM(pt.x, pt.y);
252 WORD mod = 0;
253 if (aModifierFlags & (nsIWidget::CTRL_L | nsIWidget::CTRL_R)) {
254 mod |= MK_CONTROL;
256 if (aModifierFlags & (nsIWidget::SHIFT_L | nsIWidget::SHIFT_R)) {
257 mod |= MK_SHIFT;
259 wParam = MAKEWPARAM(mod, aDelta);
260 break;
262 case WM_VSCROLL:
263 case WM_HSCROLL:
264 lParam = (aAdditionalFlags &
265 nsIDOMWindowUtils::MOUSESCROLL_WIN_SCROLL_LPARAM_NOT_NULL)
266 ? reinterpret_cast<LPARAM>(target)
267 : 0;
268 wParam = aDelta;
269 break;
270 default:
271 return NS_ERROR_INVALID_ARG;
274 // Ensure to make the instance.
275 GetInstance();
277 BYTE kbdState[256];
278 memset(kbdState, 0, sizeof(kbdState));
280 AutoTArray<KeyPair, 10> keySequence;
281 WinUtils::SetupKeyModifiersSequence(&keySequence, aModifierFlags,
282 aNativeMessage);
284 for (uint32_t i = 0; i < keySequence.Length(); ++i) {
285 uint8_t key = keySequence[i].mGeneral;
286 uint8_t keySpecific = keySequence[i].mSpecific;
287 kbdState[key] = 0x81; // key is down and toggled on if appropriate
288 if (keySpecific) {
289 kbdState[keySpecific] = 0x81;
293 if (!sInstance->mSynthesizingEvent) {
294 sInstance->mSynthesizingEvent = new SynthesizingEvent();
297 POINTS pts;
298 pts.x = static_cast<SHORT>(pt.x);
299 pts.y = static_cast<SHORT>(pt.y);
300 return sInstance->mSynthesizingEvent->Synthesize(pts, target, aNativeMessage,
301 wParam, lParam, kbdState);
304 /* static */
305 void MouseScrollHandler::InitEvent(nsWindow* aWidget, WidgetGUIEvent& aEvent,
306 LPARAM* aPoint) {
307 NS_ENSURE_TRUE_VOID(aWidget);
309 // If a point is provided, use it; otherwise, get current message point or
310 // synthetic point
311 POINTS pointOnScreen;
312 if (aPoint != nullptr) {
313 pointOnScreen = MAKEPOINTS(*aPoint);
314 } else {
315 pointOnScreen = GetCurrentMessagePos();
318 // InitEvent expects the point to be in window coordinates, so translate the
319 // point from screen coordinates.
320 POINT pointOnWindow;
321 POINTSTOPOINT(pointOnWindow, pointOnScreen);
322 ::ScreenToClient(aWidget->GetWindowHandle(), &pointOnWindow);
324 LayoutDeviceIntPoint point;
325 point.x = pointOnWindow.x;
326 point.y = pointOnWindow.y;
328 aWidget->InitEvent(aEvent, &point);
331 /* static */
332 ModifierKeyState MouseScrollHandler::GetModifierKeyState(UINT aMessage) {
333 ModifierKeyState result;
334 // Assume the Control key is down if the Elantech touchpad has sent the
335 // mis-ordered WM_KEYDOWN/WM_MOUSEWHEEL messages. (See the comment in
336 // MouseScrollHandler::Device::Elantech::HandleKeyMessage().)
337 if ((aMessage == MOZ_WM_MOUSEVWHEEL || aMessage == WM_MOUSEWHEEL) &&
338 !result.IsControl() && Device::Elantech::IsZooming()) {
339 // XXX Do we need to unset MODIFIER_SHIFT, MODIFIER_ALT, MODIFIER_OS too?
340 // If one of them are true, the default action becomes not zooming.
341 result.Unset(MODIFIER_ALTGRAPH);
342 result.Set(MODIFIER_CONTROL);
344 return result;
347 POINT
348 MouseScrollHandler::ComputeMessagePos(UINT aMessage, WPARAM aWParam,
349 LPARAM aLParam) {
350 POINT point;
351 if (Device::SetPoint::IsGetMessagePosResponseValid(aMessage, aWParam,
352 aLParam)) {
353 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
354 ("MouseScroll::ComputeMessagePos: Using ::GetCursorPos()"));
355 ::GetCursorPos(&point);
356 } else {
357 POINTS pts = GetCurrentMessagePos();
358 point.x = pts.x;
359 point.y = pts.y;
361 return point;
364 void MouseScrollHandler::ProcessNativeMouseWheelMessage(nsWindow* aWidget,
365 UINT aMessage,
366 WPARAM aWParam,
367 LPARAM aLParam) {
368 if (SynthesizingEvent::IsSynthesizing()) {
369 mSynthesizingEvent->NativeMessageReceived(aWidget, aMessage, aWParam,
370 aLParam);
373 POINT point = ComputeMessagePos(aMessage, aWParam, aLParam);
375 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
376 ("MouseScroll::ProcessNativeMouseWheelMessage: aWidget=%p, "
377 "aMessage=%s, wParam=0x%08zX, lParam=0x%08" PRIXLPTR
378 ", point: { x=%ld, y=%ld }",
379 aWidget,
380 aMessage == WM_MOUSEWHEEL ? "WM_MOUSEWHEEL"
381 : aMessage == WM_MOUSEHWHEEL ? "WM_MOUSEHWHEEL"
382 : aMessage == WM_VSCROLL ? "WM_VSCROLL"
383 : "WM_HSCROLL",
384 aWParam, aLParam, point.x, point.y));
385 MaybeLogKeyState();
387 HWND underCursorWnd = ::WindowFromPoint(point);
388 if (!underCursorWnd) {
389 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
390 ("MouseScroll::ProcessNativeMouseWheelMessage: "
391 "No window is not found under the cursor"));
392 return;
395 if (Device::Elantech::IsPinchHackNeeded() &&
396 Device::Elantech::IsHelperWindow(underCursorWnd)) {
397 // The Elantech driver places a window right underneath the cursor
398 // when sending a WM_MOUSEWHEEL event to us as part of a pinch-to-zoom
399 // gesture. We detect that here, and search for our window that would
400 // be beneath the cursor if that window wasn't there.
401 underCursorWnd = WinUtils::FindOurWindowAtPoint(point);
402 if (!underCursorWnd) {
403 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
404 ("MouseScroll::ProcessNativeMouseWheelMessage: "
405 "Our window is not found under the Elantech helper window"));
406 return;
410 // Handle most cases first. If the window under mouse cursor is our window
411 // except plugin window (MozillaWindowClass), we should handle the message
412 // on the window.
413 if (WinUtils::IsOurProcessWindow(underCursorWnd)) {
414 nsWindow* destWindow = WinUtils::GetNSWindowPtr(underCursorWnd);
415 if (!destWindow) {
416 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
417 ("MouseScroll::ProcessNativeMouseWheelMessage: "
418 "Found window under the cursor isn't managed by nsWindow..."));
419 HWND wnd = ::GetParent(underCursorWnd);
420 for (; wnd; wnd = ::GetParent(wnd)) {
421 destWindow = WinUtils::GetNSWindowPtr(wnd);
422 if (destWindow) {
423 break;
426 if (!wnd) {
427 MOZ_LOG(
428 gMouseScrollLog, LogLevel::Info,
429 ("MouseScroll::ProcessNativeMouseWheelMessage: Our window which is "
430 "managed by nsWindow is not found under the cursor"));
431 return;
435 MOZ_ASSERT(destWindow, "destWindow must not be NULL");
437 // Some odd touchpad utils sets focus to window under the mouse cursor.
438 // this emulates the odd behavior for debug.
439 if (mUserPrefs.ShouldEmulateToMakeWindowUnderCursorForeground() &&
440 (aMessage == WM_MOUSEWHEEL || aMessage == WM_MOUSEHWHEEL) &&
441 ::GetForegroundWindow() != destWindow->GetWindowHandle()) {
442 ::SetForegroundWindow(destWindow->GetWindowHandle());
445 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
446 ("MouseScroll::ProcessNativeMouseWheelMessage: Succeeded, "
447 "Posting internal message to an nsWindow (%p)...",
448 destWindow));
449 mIsWaitingInternalMessage = true;
450 UINT internalMessage = WinUtils::GetInternalMessage(aMessage);
451 ::PostMessage(destWindow->GetWindowHandle(), internalMessage, aWParam,
452 aLParam);
453 return;
456 // If the window under cursor is not in our process, it means:
457 // 1. The window may be a plugin window (GeckoPluginWindow or its descendant).
458 // 2. The window may be another application's window.
459 HWND pluginWnd = WinUtils::FindOurProcessWindow(underCursorWnd);
460 if (!pluginWnd) {
461 // If there is no plugin window in ancestors of the window under cursor,
462 // the window is for another applications (case 2).
463 // We don't need to handle this message.
464 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
465 ("MouseScroll::ProcessNativeMouseWheelMessage: "
466 "Our window is not found under the cursor"));
467 return;
470 // If the window is a part of plugin, we should post the message to it.
471 MOZ_LOG(
472 gMouseScrollLog, LogLevel::Info,
473 ("MouseScroll::ProcessNativeMouseWheelMessage: Succeeded, "
474 "Redirecting the message to a window which is a plugin child window"));
475 ::PostMessage(underCursorWnd, aMessage, aWParam, aLParam);
478 bool MouseScrollHandler::ProcessNativeScrollMessage(nsWindow* aWidget,
479 UINT aMessage,
480 WPARAM aWParam,
481 LPARAM aLParam) {
482 if (aLParam || mUserPrefs.IsScrollMessageHandledAsWheelMessage()) {
483 // Scroll message generated by Thinkpad Trackpoint Driver or similar
484 // Treat as a mousewheel message and scroll appropriately
485 ProcessNativeMouseWheelMessage(aWidget, aMessage, aWParam, aLParam);
486 // Always consume the scroll message if we try to emulate mouse wheel
487 // action.
488 return true;
491 if (SynthesizingEvent::IsSynthesizing()) {
492 mSynthesizingEvent->NativeMessageReceived(aWidget, aMessage, aWParam,
493 aLParam);
496 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
497 ("MouseScroll::ProcessNativeScrollMessage: aWidget=%p, "
498 "aMessage=%s, wParam=0x%08zX, lParam=0x%08" PRIXLPTR,
499 aWidget, aMessage == WM_VSCROLL ? "WM_VSCROLL" : "WM_HSCROLL",
500 aWParam, aLParam));
502 // Scroll message generated by external application
503 WidgetContentCommandEvent commandEvent(true, eContentCommandScroll, aWidget);
504 commandEvent.mScroll.mIsHorizontal = (aMessage == WM_HSCROLL);
506 switch (LOWORD(aWParam)) {
507 case SB_LINEUP: // SB_LINELEFT
508 commandEvent.mScroll.mUnit =
509 WidgetContentCommandEvent::eCmdScrollUnit_Line;
510 commandEvent.mScroll.mAmount = -1;
511 break;
512 case SB_LINEDOWN: // SB_LINERIGHT
513 commandEvent.mScroll.mUnit =
514 WidgetContentCommandEvent::eCmdScrollUnit_Line;
515 commandEvent.mScroll.mAmount = 1;
516 break;
517 case SB_PAGEUP: // SB_PAGELEFT
518 commandEvent.mScroll.mUnit =
519 WidgetContentCommandEvent::eCmdScrollUnit_Page;
520 commandEvent.mScroll.mAmount = -1;
521 break;
522 case SB_PAGEDOWN: // SB_PAGERIGHT
523 commandEvent.mScroll.mUnit =
524 WidgetContentCommandEvent::eCmdScrollUnit_Page;
525 commandEvent.mScroll.mAmount = 1;
526 break;
527 case SB_TOP: // SB_LEFT
528 commandEvent.mScroll.mUnit =
529 WidgetContentCommandEvent::eCmdScrollUnit_Whole;
530 commandEvent.mScroll.mAmount = -1;
531 break;
532 case SB_BOTTOM: // SB_RIGHT
533 commandEvent.mScroll.mUnit =
534 WidgetContentCommandEvent::eCmdScrollUnit_Whole;
535 commandEvent.mScroll.mAmount = 1;
536 break;
537 default:
538 return false;
540 // XXX If this is a plugin window, we should dispatch the event from
541 // parent window.
542 aWidget->DispatchContentCommandEvent(&commandEvent);
543 return true;
546 void MouseScrollHandler::HandleMouseWheelMessage(nsWindow* aWidget,
547 UINT aMessage, WPARAM aWParam,
548 LPARAM aLParam) {
549 MOZ_ASSERT((aMessage == MOZ_WM_MOUSEVWHEEL || aMessage == MOZ_WM_MOUSEHWHEEL),
550 "HandleMouseWheelMessage must be called with "
551 "MOZ_WM_MOUSEVWHEEL or MOZ_WM_MOUSEHWHEEL");
553 MOZ_LOG(
554 gMouseScrollLog, LogLevel::Info,
555 ("MouseScroll::HandleMouseWheelMessage: aWidget=%p, "
556 "aMessage=MOZ_WM_MOUSE%sWHEEL, aWParam=0x%08zX, aLParam=0x%08" PRIXLPTR,
557 aWidget, aMessage == MOZ_WM_MOUSEVWHEEL ? "V" : "H", aWParam, aLParam));
559 mIsWaitingInternalMessage = false;
561 // If it's not allowed to cache system settings, we need to reset the cache
562 // before handling the mouse wheel message.
563 mSystemSettings.TrustedScrollSettingsDriver();
565 EventInfo eventInfo(aWidget, WinUtils::GetNativeMessage(aMessage), aWParam,
566 aLParam);
567 if (!eventInfo.CanDispatchWheelEvent()) {
568 MOZ_LOG(
569 gMouseScrollLog, LogLevel::Info,
570 ("MouseScroll::HandleMouseWheelMessage: Cannot dispatch the events"));
571 mLastEventInfo.ResetTransaction();
572 return;
575 // Discard the remaining delta if current wheel message and last one are
576 // received by different window or to scroll different direction or
577 // different unit scroll. Furthermore, if the last event was too old.
578 if (!mLastEventInfo.CanContinueTransaction(eventInfo)) {
579 mLastEventInfo.ResetTransaction();
582 mLastEventInfo.RecordEvent(eventInfo);
584 ModifierKeyState modKeyState = GetModifierKeyState(aMessage);
586 // Grab the widget, it might be destroyed by a DOM event handler.
587 RefPtr<nsWindow> kungFuDethGrip(aWidget);
589 WidgetWheelEvent wheelEvent(true, eWheel, aWidget);
590 if (mLastEventInfo.InitWheelEvent(aWidget, wheelEvent, modKeyState,
591 aLParam)) {
592 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
593 ("MouseScroll::HandleMouseWheelMessage: dispatching "
594 "eWheel event"));
595 aWidget->DispatchWheelEvent(&wheelEvent);
596 if (aWidget->Destroyed()) {
597 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
598 ("MouseScroll::HandleMouseWheelMessage: The window was destroyed "
599 "by eWheel event"));
600 mLastEventInfo.ResetTransaction();
601 return;
603 } else {
604 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
605 ("MouseScroll::HandleMouseWheelMessage: eWheel event is not "
606 "dispatched"));
610 void MouseScrollHandler::HandleScrollMessageAsMouseWheelMessage(
611 nsWindow* aWidget, UINT aMessage, WPARAM aWParam, LPARAM aLParam) {
612 MOZ_ASSERT((aMessage == MOZ_WM_VSCROLL || aMessage == MOZ_WM_HSCROLL),
613 "HandleScrollMessageAsMouseWheelMessage must be called with "
614 "MOZ_WM_VSCROLL or MOZ_WM_HSCROLL");
616 mIsWaitingInternalMessage = false;
618 ModifierKeyState modKeyState = GetModifierKeyState(aMessage);
620 WidgetWheelEvent wheelEvent(true, eWheel, aWidget);
621 double& delta =
622 (aMessage == MOZ_WM_VSCROLL) ? wheelEvent.mDeltaY : wheelEvent.mDeltaX;
623 int32_t& lineOrPageDelta = (aMessage == MOZ_WM_VSCROLL)
624 ? wheelEvent.mLineOrPageDeltaY
625 : wheelEvent.mLineOrPageDeltaX;
627 delta = 1.0;
628 lineOrPageDelta = 1;
630 switch (LOWORD(aWParam)) {
631 case SB_PAGEUP:
632 delta = -1.0;
633 lineOrPageDelta = -1;
634 [[fallthrough]];
635 case SB_PAGEDOWN:
636 wheelEvent.mDeltaMode = dom::WheelEvent_Binding::DOM_DELTA_PAGE;
637 break;
639 case SB_LINEUP:
640 delta = -1.0;
641 lineOrPageDelta = -1;
642 [[fallthrough]];
643 case SB_LINEDOWN:
644 wheelEvent.mDeltaMode = dom::WheelEvent_Binding::DOM_DELTA_LINE;
645 break;
647 default:
648 return;
650 modKeyState.InitInputEvent(wheelEvent);
652 // Current mouse position may not be same as when the original message
653 // is received. However, this data is not available with the original
654 // message, which is why nullptr is passed in. We need to know the actual
655 // mouse cursor position when the original message was received.
656 InitEvent(aWidget, wheelEvent, nullptr);
658 MOZ_LOG(
659 gMouseScrollLog, LogLevel::Info,
660 ("MouseScroll::HandleScrollMessageAsMouseWheelMessage: aWidget=%p, "
661 "aMessage=MOZ_WM_%sSCROLL, aWParam=0x%08zX, aLParam=0x%08" PRIXLPTR ", "
662 "wheelEvent { mRefPoint: { x: %d, y: %d }, mDeltaX: %f, mDeltaY: %f, "
663 "mLineOrPageDeltaX: %d, mLineOrPageDeltaY: %d, "
664 "isShift: %s, isControl: %s, isAlt: %s, isMeta: %s }",
665 aWidget, (aMessage == MOZ_WM_VSCROLL) ? "V" : "H", aWParam, aLParam,
666 wheelEvent.mRefPoint.x.value, wheelEvent.mRefPoint.y.value,
667 wheelEvent.mDeltaX, wheelEvent.mDeltaY, wheelEvent.mLineOrPageDeltaX,
668 wheelEvent.mLineOrPageDeltaY, GetBoolName(wheelEvent.IsShift()),
669 GetBoolName(wheelEvent.IsControl()), GetBoolName(wheelEvent.IsAlt()),
670 GetBoolName(wheelEvent.IsMeta())));
672 aWidget->DispatchWheelEvent(&wheelEvent);
675 /******************************************************************************
677 * EventInfo
679 ******************************************************************************/
681 MouseScrollHandler::EventInfo::EventInfo(nsWindow* aWidget, UINT aMessage,
682 WPARAM aWParam, LPARAM aLParam) {
683 MOZ_ASSERT(
684 aMessage == WM_MOUSEWHEEL || aMessage == WM_MOUSEHWHEEL,
685 "EventInfo must be initialized with WM_MOUSEWHEEL or WM_MOUSEHWHEEL");
687 MouseScrollHandler::GetInstance()->mSystemSettings.Init();
689 mIsVertical = (aMessage == WM_MOUSEWHEEL);
690 mIsPage =
691 MouseScrollHandler::sInstance->mSystemSettings.IsPageScroll(mIsVertical);
692 mDelta = (short)HIWORD(aWParam);
693 mWnd = aWidget->GetWindowHandle();
694 mTimeStamp = TimeStamp::Now();
697 bool MouseScrollHandler::EventInfo::CanDispatchWheelEvent() const {
698 if (!GetScrollAmount()) {
699 // XXX I think that we should dispatch mouse wheel events even if the
700 // operation will not scroll because the wheel operation really happened
701 // and web application may want to handle the event for non-scroll action.
702 return false;
705 return (mDelta != 0);
708 int32_t MouseScrollHandler::EventInfo::GetScrollAmount() const {
709 if (mIsPage) {
710 return 1;
712 return MouseScrollHandler::sInstance->mSystemSettings.GetScrollAmount(
713 mIsVertical);
716 /******************************************************************************
718 * LastEventInfo
720 ******************************************************************************/
722 bool MouseScrollHandler::LastEventInfo::CanContinueTransaction(
723 const EventInfo& aNewEvent) {
724 int32_t timeout = MouseScrollHandler::sInstance->mUserPrefs
725 .GetMouseScrollTransactionTimeout();
726 return !mWnd ||
727 (mWnd == aNewEvent.GetWindowHandle() &&
728 IsPositive() == aNewEvent.IsPositive() &&
729 mIsVertical == aNewEvent.IsVertical() &&
730 mIsPage == aNewEvent.IsPage() &&
731 (timeout < 0 || TimeStamp::Now() - mTimeStamp <=
732 TimeDuration::FromMilliseconds(timeout)));
735 void MouseScrollHandler::LastEventInfo::ResetTransaction() {
736 if (!mWnd) {
737 return;
740 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
741 ("MouseScroll::LastEventInfo::ResetTransaction()"));
743 mWnd = nullptr;
744 mAccumulatedDelta = 0;
747 void MouseScrollHandler::LastEventInfo::RecordEvent(const EventInfo& aEvent) {
748 mWnd = aEvent.GetWindowHandle();
749 mDelta = aEvent.GetNativeDelta();
750 mIsVertical = aEvent.IsVertical();
751 mIsPage = aEvent.IsPage();
752 mTimeStamp = TimeStamp::Now();
755 /* static */
756 int32_t MouseScrollHandler::LastEventInfo::RoundDelta(double aDelta) {
757 return (aDelta >= 0) ? (int32_t)floor(aDelta) : (int32_t)ceil(aDelta);
760 bool MouseScrollHandler::LastEventInfo::InitWheelEvent(
761 nsWindow* aWidget, WidgetWheelEvent& aWheelEvent,
762 const ModifierKeyState& aModKeyState, LPARAM aLParam) {
763 MOZ_ASSERT(aWheelEvent.mMessage == eWheel);
765 if (StaticPrefs::mousewheel_ignore_cursor_position_in_lparam()) {
766 InitEvent(aWidget, aWheelEvent, nullptr);
767 } else {
768 InitEvent(aWidget, aWheelEvent, &aLParam);
771 aModKeyState.InitInputEvent(aWheelEvent);
773 // Our positive delta value means to bottom or right.
774 // But positive native delta value means to top or right.
775 // Use orienter for computing our delta value with native delta value.
776 int32_t orienter = mIsVertical ? -1 : 1;
778 aWheelEvent.mDeltaMode = mIsPage ? dom::WheelEvent_Binding::DOM_DELTA_PAGE
779 : dom::WheelEvent_Binding::DOM_DELTA_LINE;
781 double ticks = double(mDelta) * orienter / double(WHEEL_DELTA);
782 if (mIsVertical) {
783 aWheelEvent.mWheelTicksY = ticks;
784 } else {
785 aWheelEvent.mWheelTicksX = ticks;
788 double& delta = mIsVertical ? aWheelEvent.mDeltaY : aWheelEvent.mDeltaX;
789 int32_t& lineOrPageDelta = mIsVertical ? aWheelEvent.mLineOrPageDeltaY
790 : aWheelEvent.mLineOrPageDeltaX;
792 double nativeDeltaPerUnit =
793 mIsPage ? double(WHEEL_DELTA) : double(WHEEL_DELTA) / GetScrollAmount();
795 delta = double(mDelta) * orienter / nativeDeltaPerUnit;
796 mAccumulatedDelta += mDelta;
797 lineOrPageDelta =
798 mAccumulatedDelta * orienter / RoundDelta(nativeDeltaPerUnit);
799 mAccumulatedDelta -=
800 lineOrPageDelta * orienter * RoundDelta(nativeDeltaPerUnit);
802 if (aWheelEvent.mDeltaMode != dom::WheelEvent_Binding::DOM_DELTA_LINE) {
803 // If the scroll delta mode isn't per line scroll, we shouldn't allow to
804 // override the system scroll speed setting.
805 aWheelEvent.mAllowToOverrideSystemScrollSpeed = false;
806 } else if (!MouseScrollHandler::sInstance->mSystemSettings
807 .IsOverridingSystemScrollSpeedAllowed()) {
808 // If the system settings are customized by either the user or
809 // the mouse utility, we shouldn't allow to override the system scroll
810 // speed setting.
811 aWheelEvent.mAllowToOverrideSystemScrollSpeed = false;
812 } else {
813 // For suppressing too fast scroll, we should ensure that the maximum
814 // overridden delta value should be less than overridden scroll speed
815 // with default scroll amount.
816 double defaultScrollAmount = mIsVertical
817 ? SystemSettings::DefaultScrollLines()
818 : SystemSettings::DefaultScrollChars();
819 double maxDelta = WidgetWheelEvent::ComputeOverriddenDelta(
820 defaultScrollAmount, mIsVertical);
821 if (maxDelta != defaultScrollAmount) {
822 double overriddenDelta =
823 WidgetWheelEvent::ComputeOverriddenDelta(Abs(delta), mIsVertical);
824 if (overriddenDelta > maxDelta) {
825 // Suppress to fast scroll since overriding system scroll speed with
826 // current delta value causes too big delta value.
827 aWheelEvent.mAllowToOverrideSystemScrollSpeed = false;
832 MOZ_LOG(
833 gMouseScrollLog, LogLevel::Info,
834 ("MouseScroll::LastEventInfo::InitWheelEvent: aWidget=%p, "
835 "aWheelEvent { mRefPoint: { x: %d, y: %d }, mDeltaX: %f, mDeltaY: %f, "
836 "mLineOrPageDeltaX: %d, mLineOrPageDeltaY: %d, "
837 "isShift: %s, isControl: %s, isAlt: %s, isMeta: %s, "
838 "mAllowToOverrideSystemScrollSpeed: %s }, "
839 "mAccumulatedDelta: %d",
840 aWidget, aWheelEvent.mRefPoint.x.value, aWheelEvent.mRefPoint.y.value,
841 aWheelEvent.mDeltaX, aWheelEvent.mDeltaY, aWheelEvent.mLineOrPageDeltaX,
842 aWheelEvent.mLineOrPageDeltaY, GetBoolName(aWheelEvent.IsShift()),
843 GetBoolName(aWheelEvent.IsControl()), GetBoolName(aWheelEvent.IsAlt()),
844 GetBoolName(aWheelEvent.IsMeta()),
845 GetBoolName(aWheelEvent.mAllowToOverrideSystemScrollSpeed),
846 mAccumulatedDelta));
848 return (delta != 0);
851 /******************************************************************************
853 * SystemSettings
855 ******************************************************************************/
857 void MouseScrollHandler::SystemSettings::Init() {
858 if (mInitialized) {
859 return;
862 InitScrollLines();
863 InitScrollChars();
865 mInitialized = true;
867 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
868 ("MouseScroll::SystemSettings::Init(): initialized, "
869 "mScrollLines=%d, mScrollChars=%d",
870 mScrollLines, mScrollChars));
873 bool MouseScrollHandler::SystemSettings::InitScrollLines() {
874 int32_t oldValue = mInitialized ? mScrollLines : 0;
875 mIsReliableScrollLines = false;
876 mScrollLines = MouseScrollHandler::sInstance->mUserPrefs
877 .GetOverriddenVerticalScrollAmout();
878 if (mScrollLines >= 0) {
879 // overridden by the pref.
880 mIsReliableScrollLines = true;
881 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
882 ("MouseScroll::SystemSettings::InitScrollLines(): mScrollLines is "
883 "overridden by the pref: %d",
884 mScrollLines));
885 } else if (!::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &mScrollLines,
886 0)) {
887 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
888 ("MouseScroll::SystemSettings::InitScrollLines(): "
889 "::SystemParametersInfo("
890 "SPI_GETWHEELSCROLLLINES) failed"));
891 mScrollLines = DefaultScrollLines();
894 if (mScrollLines > WHEEL_DELTA) {
895 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
896 ("MouseScroll::SystemSettings::InitScrollLines(): the result of "
897 "::SystemParametersInfo(SPI_GETWHEELSCROLLLINES) is too large: %d",
898 mScrollLines));
899 // sScrollLines usually equals 3 or 0 (for no scrolling)
900 // However, if sScrollLines > WHEEL_DELTA, we assume that
901 // the mouse driver wants a page scroll. The docs state that
902 // sScrollLines should explicitly equal WHEEL_PAGESCROLL, but
903 // since some mouse drivers use an arbitrary large number instead,
904 // we have to handle that as well.
905 mScrollLines = WHEEL_PAGESCROLL;
908 return oldValue != mScrollLines;
911 bool MouseScrollHandler::SystemSettings::InitScrollChars() {
912 int32_t oldValue = mInitialized ? mScrollChars : 0;
913 mIsReliableScrollChars = false;
914 mScrollChars = MouseScrollHandler::sInstance->mUserPrefs
915 .GetOverriddenHorizontalScrollAmout();
916 if (mScrollChars >= 0) {
917 // overridden by the pref.
918 mIsReliableScrollChars = true;
919 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
920 ("MouseScroll::SystemSettings::InitScrollChars(): mScrollChars is "
921 "overridden by the pref: %d",
922 mScrollChars));
923 } else if (!::SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &mScrollChars,
924 0)) {
925 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
926 ("MouseScroll::SystemSettings::InitScrollChars(): "
927 "::SystemParametersInfo("
928 "SPI_GETWHEELSCROLLCHARS) failed, this is unexpected on Vista or "
929 "later"));
930 // XXX Should we use DefaultScrollChars()?
931 mScrollChars = 1;
934 if (mScrollChars > WHEEL_DELTA) {
935 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
936 ("MouseScroll::SystemSettings::InitScrollChars(): the result of "
937 "::SystemParametersInfo(SPI_GETWHEELSCROLLCHARS) is too large: %d",
938 mScrollChars));
939 // See the comments for the case mScrollLines > WHEEL_DELTA.
940 mScrollChars = WHEEL_PAGESCROLL;
943 return oldValue != mScrollChars;
946 void MouseScrollHandler::SystemSettings::MarkDirty() {
947 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
948 ("MouseScrollHandler::SystemSettings::MarkDirty(): "
949 "Marking SystemSettings dirty"));
950 mInitialized = false;
951 // When system settings are changed, we should reset current transaction.
952 MOZ_ASSERT(sInstance,
953 "Must not be called at initializing MouseScrollHandler");
954 MouseScrollHandler::sInstance->mLastEventInfo.ResetTransaction();
957 void MouseScrollHandler::SystemSettings::RefreshCache() {
958 bool isChanged = InitScrollLines();
959 isChanged = InitScrollChars() || isChanged;
960 if (!isChanged) {
961 return;
963 // If the scroll amount is changed, we should reset current transaction.
964 MOZ_ASSERT(sInstance,
965 "Must not be called at initializing MouseScrollHandler");
966 MouseScrollHandler::sInstance->mLastEventInfo.ResetTransaction();
969 void MouseScrollHandler::SystemSettings::TrustedScrollSettingsDriver() {
970 if (!mInitialized) {
971 return;
974 // if the cache is initialized with prefs, we don't need to refresh it.
975 if (mIsReliableScrollLines && mIsReliableScrollChars) {
976 return;
979 MouseScrollHandler::UserPrefs& userPrefs =
980 MouseScrollHandler::sInstance->mUserPrefs;
982 // If system settings cache is disabled, we should always refresh them.
983 if (!userPrefs.IsSystemSettingCacheEnabled()) {
984 RefreshCache();
985 return;
988 // If pref is set to as "always trust the cache", we shouldn't refresh them
989 // in any environments.
990 if (userPrefs.IsSystemSettingCacheForciblyEnabled()) {
991 return;
994 // If SynTP of Synaptics or Apoint of Alps is installed, it may hook
995 // ::SystemParametersInfo() and returns different value from system settings.
996 if (Device::SynTP::IsDriverInstalled() ||
997 Device::Apoint::IsDriverInstalled()) {
998 RefreshCache();
999 return;
1002 // XXX We're not sure about other touchpad drivers...
1005 bool MouseScrollHandler::SystemSettings::
1006 IsOverridingSystemScrollSpeedAllowed() {
1007 return mScrollLines == DefaultScrollLines() &&
1008 mScrollChars == DefaultScrollChars();
1011 /******************************************************************************
1013 * UserPrefs
1015 ******************************************************************************/
1017 MouseScrollHandler::UserPrefs::UserPrefs() : mInitialized(false) {
1018 // We need to reset mouse wheel transaction when all of mousewheel related
1019 // prefs are changed.
1020 DebugOnly<nsresult> rv =
1021 Preferences::RegisterPrefixCallback(OnChange, "mousewheel.", this);
1022 MOZ_ASSERT(NS_SUCCEEDED(rv), "Failed to register callback for mousewheel.");
1025 MouseScrollHandler::UserPrefs::~UserPrefs() {
1026 DebugOnly<nsresult> rv =
1027 Preferences::UnregisterPrefixCallback(OnChange, "mousewheel.", this);
1028 MOZ_ASSERT(NS_SUCCEEDED(rv), "Failed to unregister callback for mousewheel.");
1031 void MouseScrollHandler::UserPrefs::Init() {
1032 if (mInitialized) {
1033 return;
1036 mInitialized = true;
1038 mScrollMessageHandledAsWheelMessage =
1039 Preferences::GetBool("mousewheel.emulate_at_wm_scroll", false);
1040 mEnableSystemSettingCache =
1041 Preferences::GetBool("mousewheel.system_settings_cache.enabled", true);
1042 mForceEnableSystemSettingCache = Preferences::GetBool(
1043 "mousewheel.system_settings_cache.force_enabled", false);
1044 mEmulateToMakeWindowUnderCursorForeground = Preferences::GetBool(
1045 "mousewheel.debug.make_window_under_cursor_foreground", false);
1046 mOverriddenVerticalScrollAmount =
1047 Preferences::GetInt("mousewheel.windows.vertical_amount_override", -1);
1048 mOverriddenHorizontalScrollAmount =
1049 Preferences::GetInt("mousewheel.windows.horizontal_amount_override", -1);
1050 mMouseScrollTransactionTimeout = Preferences::GetInt(
1051 "mousewheel.windows.transaction.timeout", DEFAULT_TIMEOUT_DURATION);
1053 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1054 ("MouseScroll::UserPrefs::Init(): initialized, "
1055 "mScrollMessageHandledAsWheelMessage=%s, "
1056 "mEnableSystemSettingCache=%s, "
1057 "mForceEnableSystemSettingCache=%s, "
1058 "mEmulateToMakeWindowUnderCursorForeground=%s, "
1059 "mOverriddenVerticalScrollAmount=%d, "
1060 "mOverriddenHorizontalScrollAmount=%d, "
1061 "mMouseScrollTransactionTimeout=%d",
1062 GetBoolName(mScrollMessageHandledAsWheelMessage),
1063 GetBoolName(mEnableSystemSettingCache),
1064 GetBoolName(mForceEnableSystemSettingCache),
1065 GetBoolName(mEmulateToMakeWindowUnderCursorForeground),
1066 mOverriddenVerticalScrollAmount, mOverriddenHorizontalScrollAmount,
1067 mMouseScrollTransactionTimeout));
1070 void MouseScrollHandler::UserPrefs::MarkDirty() {
1071 MOZ_LOG(
1072 gMouseScrollLog, LogLevel::Info,
1073 ("MouseScrollHandler::UserPrefs::MarkDirty(): Marking UserPrefs dirty"));
1074 mInitialized = false;
1075 // Some prefs might override system settings, so, we should mark them dirty.
1076 MouseScrollHandler::sInstance->mSystemSettings.MarkDirty();
1077 // When user prefs for mousewheel are changed, we should reset current
1078 // transaction.
1079 MOZ_ASSERT(sInstance,
1080 "Must not be called at initializing MouseScrollHandler");
1081 MouseScrollHandler::sInstance->mLastEventInfo.ResetTransaction();
1084 /******************************************************************************
1086 * Device
1088 ******************************************************************************/
1090 /* static */
1091 bool MouseScrollHandler::Device::GetWorkaroundPref(const char* aPrefName,
1092 bool aValueIfAutomatic) {
1093 if (!aPrefName) {
1094 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1095 ("MouseScroll::Device::GetWorkaroundPref(): Failed, aPrefName is "
1096 "NULL"));
1097 return aValueIfAutomatic;
1100 int32_t lHackValue = 0;
1101 if (NS_FAILED(Preferences::GetInt(aPrefName, &lHackValue))) {
1102 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1103 ("MouseScroll::Device::GetWorkaroundPref(): Preferences::GetInt() "
1104 "failed,"
1105 " aPrefName=\"%s\", aValueIfAutomatic=%s",
1106 aPrefName, GetBoolName(aValueIfAutomatic)));
1107 return aValueIfAutomatic;
1110 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1111 ("MouseScroll::Device::GetWorkaroundPref(): Succeeded, "
1112 "aPrefName=\"%s\", aValueIfAutomatic=%s, lHackValue=%d",
1113 aPrefName, GetBoolName(aValueIfAutomatic), lHackValue));
1115 switch (lHackValue) {
1116 case 0: // disabled
1117 return false;
1118 case 1: // enabled
1119 return true;
1120 default: // -1: autodetect
1121 return aValueIfAutomatic;
1125 /* static */
1126 void MouseScrollHandler::Device::Init() {
1127 // FYI: Thinkpad's TrackPoint is Apoint of Alps and UltraNav is SynTP of
1128 // Synaptics. So, those drivers' information should be initialized
1129 // before calling methods of TrackPoint and UltraNav.
1130 SynTP::Init();
1131 Elantech::Init();
1132 Apoint::Init();
1134 sFakeScrollableWindowNeeded = GetWorkaroundPref(
1135 "ui.trackpoint_hack.enabled", (TrackPoint::IsDriverInstalled() ||
1136 UltraNav::IsObsoleteDriverInstalled()));
1138 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1139 ("MouseScroll::Device::Init(): sFakeScrollableWindowNeeded=%s",
1140 GetBoolName(sFakeScrollableWindowNeeded)));
1143 /******************************************************************************
1145 * Device::SynTP
1147 ******************************************************************************/
1149 /* static */
1150 void MouseScrollHandler::Device::SynTP::Init() {
1151 if (sInitialized) {
1152 return;
1155 sInitialized = true;
1156 sMajorVersion = 0;
1157 sMinorVersion = -1;
1159 wchar_t buf[40];
1160 bool foundKey = WinUtils::GetRegistryKey(
1161 HKEY_LOCAL_MACHINE, L"Software\\Synaptics\\SynTP\\Install",
1162 L"DriverVersion", buf, sizeof buf);
1163 if (!foundKey) {
1164 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1165 ("MouseScroll::Device::SynTP::Init(): "
1166 "SynTP driver is not found"));
1167 return;
1170 sMajorVersion = wcstol(buf, nullptr, 10);
1171 sMinorVersion = 0;
1172 wchar_t* p = wcschr(buf, L'.');
1173 if (p) {
1174 sMinorVersion = wcstol(p + 1, nullptr, 10);
1176 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1177 ("MouseScroll::Device::SynTP::Init(): "
1178 "found driver version = %d.%d",
1179 sMajorVersion, sMinorVersion));
1182 /******************************************************************************
1184 * Device::Elantech
1186 ******************************************************************************/
1188 /* static */
1189 void MouseScrollHandler::Device::Elantech::Init() {
1190 int32_t version = GetDriverMajorVersion();
1191 bool needsHack = Device::GetWorkaroundPref(
1192 "ui.elantech_gesture_hacks.enabled", version != 0);
1193 sUseSwipeHack = needsHack && version <= 7;
1194 sUsePinchHack = needsHack && version <= 8;
1196 MOZ_LOG(
1197 gMouseScrollLog, LogLevel::Info,
1198 ("MouseScroll::Device::Elantech::Init(): version=%d, sUseSwipeHack=%s, "
1199 "sUsePinchHack=%s",
1200 version, GetBoolName(sUseSwipeHack), GetBoolName(sUsePinchHack)));
1203 /* static */
1204 int32_t MouseScrollHandler::Device::Elantech::GetDriverMajorVersion() {
1205 wchar_t buf[40];
1206 // The driver version is found in one of these two registry keys.
1207 bool foundKey = WinUtils::GetRegistryKey(HKEY_CURRENT_USER,
1208 L"Software\\Elantech\\MainOption",
1209 L"DriverVersion", buf, sizeof buf);
1210 if (!foundKey) {
1211 foundKey =
1212 WinUtils::GetRegistryKey(HKEY_CURRENT_USER, L"Software\\Elantech",
1213 L"DriverVersion", buf, sizeof buf);
1216 if (!foundKey) {
1217 return 0;
1220 // Assume that the major version number can be found just after a space
1221 // or at the start of the string.
1222 for (wchar_t* p = buf; *p; p++) {
1223 if (*p >= L'0' && *p <= L'9' && (p == buf || *(p - 1) == L' ')) {
1224 return wcstol(p, nullptr, 10);
1228 return 0;
1231 /* static */
1232 bool MouseScrollHandler::Device::Elantech::IsHelperWindow(HWND aWnd) {
1233 // The helper window cannot be distinguished based on its window class, so we
1234 // need to check if it is owned by the helper process, ETDCtrl.exe.
1236 const wchar_t* filenameSuffix = L"\\etdctrl.exe";
1237 const int filenameSuffixLength = 12;
1239 DWORD pid;
1240 ::GetWindowThreadProcessId(aWnd, &pid);
1242 HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1243 if (!hProcess) {
1244 return false;
1247 bool result = false;
1248 wchar_t path[256] = {L'\0'};
1249 if (::GetProcessImageFileNameW(hProcess, path, ArrayLength(path))) {
1250 int pathLength = lstrlenW(path);
1251 if (pathLength >= filenameSuffixLength) {
1252 if (lstrcmpiW(path + pathLength - filenameSuffixLength, filenameSuffix) ==
1253 0) {
1254 result = true;
1258 ::CloseHandle(hProcess);
1260 return result;
1263 /* static */
1264 bool MouseScrollHandler::Device::Elantech::HandleKeyMessage(nsWindow* aWidget,
1265 UINT aMsg,
1266 WPARAM aWParam,
1267 LPARAM aLParam) {
1268 // The Elantech touchpad driver understands three-finger swipe left and
1269 // right gestures, and translates them into Page Up and Page Down key
1270 // events for most applications. For Firefox 3.6, it instead sends
1271 // Alt+Left and Alt+Right to trigger browser back/forward actions. As
1272 // with the Thinkpad Driver hack in nsWindow::Create, the change in
1273 // HWND structure makes Firefox not trigger the driver's heuristics
1274 // any longer.
1276 // The Elantech driver actually sends these messages for a three-finger
1277 // swipe right:
1279 // WM_KEYDOWN virtual_key = 0xCC or 0xFF ScanCode = 00
1280 // WM_KEYDOWN virtual_key = VK_NEXT ScanCode = 00
1281 // WM_KEYUP virtual_key = VK_NEXT ScanCode = 00
1282 // WM_KEYUP virtual_key = 0xCC or 0xFF ScanCode = 00
1284 // Whether 0xCC or 0xFF is sent is suspected to depend on the driver
1285 // version. 7.0.4.12_14Jul09_WHQL, 7.0.5.10, and 7.0.6.0 generate 0xCC.
1286 // 7.0.4.3 from Asus on EeePC generates 0xFF.
1288 // On some hardware, IS_VK_DOWN(0xFF) returns true even when Elantech
1289 // messages are not involved, meaning that alone is not enough to
1290 // distinguish the gesture from a regular Page Up or Page Down key press.
1291 // The ScanCode is therefore also tested to detect the gesture.
1292 // We then pretend that we should dispatch "Go Forward" command. Similarly
1293 // for VK_PRIOR and "Go Back" command.
1294 if (sUseSwipeHack && (aWParam == VK_NEXT || aWParam == VK_PRIOR) &&
1295 WinUtils::GetScanCode(aLParam) == 0 &&
1296 (IS_VK_DOWN(0xFF) || IS_VK_DOWN(0xCC))) {
1297 if (aMsg == WM_KEYDOWN) {
1298 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1299 ("MouseScroll::Device::Elantech::HandleKeyMessage(): Dispatching "
1300 "%s command event",
1301 aWParam == VK_NEXT ? "Forward" : "Back"));
1303 WidgetCommandEvent appCommandEvent(
1304 true, (aWParam == VK_NEXT) ? nsGkAtoms::Forward : nsGkAtoms::Back,
1305 aWidget);
1307 // In this scenario, the coordinate of the event isn't supplied, so pass
1308 // nullptr as an argument to indicate using the coordinate from the last
1309 // available window message.
1310 InitEvent(aWidget, appCommandEvent, nullptr);
1311 aWidget->DispatchWindowEvent(appCommandEvent);
1312 } else {
1313 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1314 ("MouseScroll::Device::Elantech::HandleKeyMessage(): Consumed"));
1316 return true; // consume the message (doesn't need to dispatch key events)
1319 // Version 8 of the Elantech touchpad driver sends these messages for
1320 // zoom gestures:
1322 // WM_KEYDOWN virtual_key = 0xCC time = 10
1323 // WM_KEYDOWN virtual_key = VK_CONTROL time = 10
1324 // WM_MOUSEWHEEL time = ::GetTickCount()
1325 // WM_KEYUP virtual_key = VK_CONTROL time = 10
1326 // WM_KEYUP virtual_key = 0xCC time = 10
1328 // The result of this is that we process all of the WM_KEYDOWN/WM_KEYUP
1329 // messages first because their timestamps make them appear to have
1330 // been sent before the WM_MOUSEWHEEL message. To work around this,
1331 // we store the current time when we process the WM_KEYUP message and
1332 // assume that any WM_MOUSEWHEEL message with a timestamp before that
1333 // time is one that should be processed as if the Control key was down.
1334 if (sUsePinchHack && aMsg == WM_KEYUP && aWParam == VK_CONTROL &&
1335 ::GetMessageTime() == 10) {
1336 // We look only at the bottom 31 bits of the system tick count since
1337 // GetMessageTime returns a LONG, which is signed, so we want values
1338 // that are more easily comparable.
1339 sZoomUntil = ::GetTickCount() & 0x7FFFFFFF;
1341 MOZ_LOG(
1342 gMouseScrollLog, LogLevel::Info,
1343 ("MouseScroll::Device::Elantech::HandleKeyMessage(): sZoomUntil=%lu",
1344 sZoomUntil));
1347 return false;
1350 /* static */
1351 void MouseScrollHandler::Device::Elantech::UpdateZoomUntil() {
1352 if (!sZoomUntil) {
1353 return;
1356 // For the Elantech Touchpad Zoom Gesture Hack, we should check that the
1357 // system time (32-bit milliseconds) hasn't wrapped around. Otherwise we
1358 // might get into the situation where wheel events for the next 50 days of
1359 // system uptime are assumed to be Ctrl+Wheel events. (It is unlikely that
1360 // we would get into that state, because the system would already need to be
1361 // up for 50 days and the Control key message would need to be processed just
1362 // before the system time overflow and the wheel message just after.)
1364 // We also take the chance to reset sZoomUntil if we simply have passed that
1365 // time.
1366 LONG msgTime = ::GetMessageTime();
1367 if ((sZoomUntil >= 0x3fffffffu && DWORD(msgTime) < 0x40000000u) ||
1368 (sZoomUntil < DWORD(msgTime))) {
1369 sZoomUntil = 0;
1371 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1372 ("MouseScroll::Device::Elantech::UpdateZoomUntil(): "
1373 "sZoomUntil was reset"));
1377 /* static */
1378 bool MouseScrollHandler::Device::Elantech::IsZooming() {
1379 // Assume the Control key is down if the Elantech touchpad has sent the
1380 // mis-ordered WM_KEYDOWN/WM_MOUSEWHEEL messages. (See the comment in
1381 // OnKeyUp.)
1382 return (sZoomUntil && static_cast<DWORD>(::GetMessageTime()) < sZoomUntil);
1385 /******************************************************************************
1387 * Device::Apoint
1389 ******************************************************************************/
1391 /* static */
1392 void MouseScrollHandler::Device::Apoint::Init() {
1393 if (sInitialized) {
1394 return;
1397 sInitialized = true;
1398 sMajorVersion = 0;
1399 sMinorVersion = -1;
1401 wchar_t buf[40];
1402 bool foundKey =
1403 WinUtils::GetRegistryKey(HKEY_LOCAL_MACHINE, L"Software\\Alps\\Apoint",
1404 L"ProductVer", buf, sizeof buf);
1405 if (!foundKey) {
1406 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1407 ("MouseScroll::Device::Apoint::Init(): "
1408 "Apoint driver is not found"));
1409 return;
1412 sMajorVersion = wcstol(buf, nullptr, 10);
1413 sMinorVersion = 0;
1414 wchar_t* p = wcschr(buf, L'.');
1415 if (p) {
1416 sMinorVersion = wcstol(p + 1, nullptr, 10);
1418 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1419 ("MouseScroll::Device::Apoint::Init(): "
1420 "found driver version = %d.%d",
1421 sMajorVersion, sMinorVersion));
1424 /******************************************************************************
1426 * Device::TrackPoint
1428 ******************************************************************************/
1430 /* static */
1431 bool MouseScrollHandler::Device::TrackPoint::IsDriverInstalled() {
1432 if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1433 L"Software\\Lenovo\\TrackPoint")) {
1434 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1435 ("MouseScroll::Device::TrackPoint::IsDriverInstalled(): "
1436 "Lenovo's TrackPoint driver is found"));
1437 return true;
1440 if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1441 L"Software\\Alps\\Apoint\\TrackPoint")) {
1442 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1443 ("MouseScroll::Device::TrackPoint::IsDriverInstalled(): "
1444 "Alps's TrackPoint driver is found"));
1447 return false;
1450 /******************************************************************************
1452 * Device::UltraNav
1454 ******************************************************************************/
1456 /* static */
1457 bool MouseScrollHandler::Device::UltraNav::IsObsoleteDriverInstalled() {
1458 if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1459 L"Software\\Lenovo\\UltraNav")) {
1460 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1461 ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1462 "Lenovo's UltraNav driver is found"));
1463 return true;
1466 bool installed = false;
1467 if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1468 L"Software\\Synaptics\\SynTPEnh\\UltraNavUSB")) {
1469 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1470 ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1471 "Synaptics's UltraNav (USB) driver is found"));
1472 installed = true;
1473 } else if (WinUtils::HasRegistryKey(
1474 HKEY_CURRENT_USER,
1475 L"Software\\Synaptics\\SynTPEnh\\UltraNavPS2")) {
1476 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1477 ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1478 "Synaptics's UltraNav (PS/2) driver is found"));
1479 installed = true;
1482 if (!installed) {
1483 return false;
1486 int32_t majorVersion = Device::SynTP::GetDriverMajorVersion();
1487 if (!majorVersion) {
1488 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1489 ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1490 "Failed to get UltraNav driver version"));
1491 return false;
1493 int32_t minorVersion = Device::SynTP::GetDriverMinorVersion();
1494 return majorVersion < 15 || (majorVersion == 15 && minorVersion == 0);
1497 /******************************************************************************
1499 * Device::SetPoint
1501 ******************************************************************************/
1503 /* static */
1504 bool MouseScrollHandler::Device::SetPoint::IsGetMessagePosResponseValid(
1505 UINT aMessage, WPARAM aWParam, LPARAM aLParam) {
1506 if (aMessage != WM_MOUSEHWHEEL) {
1507 return false;
1510 POINTS pts = MouseScrollHandler::GetCurrentMessagePos();
1511 LPARAM messagePos = MAKELPARAM(pts.x, pts.y);
1513 // XXX We should check whether SetPoint is installed or not by registry.
1515 // SetPoint, Logitech (Logicool) mouse driver, (confirmed with 4.82.11 and
1516 // MX-1100) always sets 0 to the lParam of WM_MOUSEHWHEEL. The driver SENDs
1517 // one message at first time, this time, ::GetMessagePos() works fine.
1518 // Then, we will return 0 (0 means we process it) to the message. Then, the
1519 // driver will POST the same messages continuously during the wheel tilted.
1520 // But ::GetMessagePos() API always returns (0, 0) for them, even if the
1521 // actual mouse cursor isn't 0,0. Therefore, we cannot trust the result of
1522 // ::GetMessagePos API if the sender is SetPoint.
1523 if (!sMightBeUsing && !aLParam && aLParam != messagePos &&
1524 ::InSendMessage()) {
1525 sMightBeUsing = true;
1526 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1527 ("MouseScroll::Device::SetPoint::IsGetMessagePosResponseValid(): "
1528 "Might using SetPoint"));
1529 } else if (sMightBeUsing && aLParam != 0 && ::InSendMessage()) {
1530 // The user has changed the mouse from Logitech's to another one (e.g.,
1531 // the user has changed to the touchpad of the notebook.
1532 sMightBeUsing = false;
1533 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1534 ("MouseScroll::Device::SetPoint::IsGetMessagePosResponseValid(): "
1535 "Might stop using SetPoint"));
1537 return (sMightBeUsing && !aLParam && !messagePos);
1540 /******************************************************************************
1542 * SynthesizingEvent
1544 ******************************************************************************/
1546 /* static */
1547 bool MouseScrollHandler::SynthesizingEvent::IsSynthesizing() {
1548 return MouseScrollHandler::sInstance &&
1549 MouseScrollHandler::sInstance->mSynthesizingEvent &&
1550 MouseScrollHandler::sInstance->mSynthesizingEvent->mStatus !=
1551 NOT_SYNTHESIZING;
1554 nsresult MouseScrollHandler::SynthesizingEvent::Synthesize(
1555 const POINTS& aCursorPoint, HWND aWnd, UINT aMessage, WPARAM aWParam,
1556 LPARAM aLParam, const BYTE (&aKeyStates)[256]) {
1557 MOZ_LOG(
1558 gMouseScrollLog, LogLevel::Info,
1559 ("MouseScrollHandler::SynthesizingEvent::Synthesize(): aCursorPoint: { "
1560 "x: %d, y: %d }, aWnd=0x%p, aMessage=0x%04X, aWParam=0x%08zX, "
1561 "aLParam=0x%08" PRIXLPTR ", IsSynthesized()=%s, mStatus=%s",
1562 aCursorPoint.x, aCursorPoint.y, aWnd, aMessage, aWParam, aLParam,
1563 GetBoolName(IsSynthesizing()), GetStatusName()));
1565 if (IsSynthesizing()) {
1566 return NS_ERROR_NOT_AVAILABLE;
1569 ::GetKeyboardState(mOriginalKeyState);
1571 // Note that we cannot use ::SetCursorPos() because it works asynchronously.
1572 // We should SEND the message for reducing the possibility of receiving
1573 // unexpected message which were not sent from here.
1574 mCursorPoint = aCursorPoint;
1576 mWnd = aWnd;
1577 mMessage = aMessage;
1578 mWParam = aWParam;
1579 mLParam = aLParam;
1581 memcpy(mKeyState, aKeyStates, sizeof(mKeyState));
1582 ::SetKeyboardState(mKeyState);
1584 mStatus = SENDING_MESSAGE;
1586 // Don't assume that aWnd is always managed by nsWindow. It might be
1587 // a plugin window.
1588 ::SendMessage(aWnd, aMessage, aWParam, aLParam);
1590 return NS_OK;
1593 void MouseScrollHandler::SynthesizingEvent::NativeMessageReceived(
1594 nsWindow* aWidget, UINT aMessage, WPARAM aWParam, LPARAM aLParam) {
1595 if (mStatus == SENDING_MESSAGE && mMessage == aMessage &&
1596 mWParam == aWParam && mLParam == aLParam) {
1597 mStatus = NATIVE_MESSAGE_RECEIVED;
1598 if (aWidget && aWidget->GetWindowHandle() == mWnd) {
1599 return;
1601 // Otherwise, the message may not be sent by us.
1604 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1605 ("MouseScrollHandler::SynthesizingEvent::NativeMessageReceived(): "
1606 "aWidget=%p, aWidget->GetWindowHandle()=0x%p, mWnd=0x%p, "
1607 "aMessage=0x%04X, aWParam=0x%08zX, aLParam=0x%08" PRIXLPTR
1608 ", mStatus=%s",
1609 aWidget, aWidget ? aWidget->GetWindowHandle() : nullptr, mWnd,
1610 aMessage, aWParam, aLParam, GetStatusName()));
1612 // We failed to receive our sent message, we failed to do the job.
1613 Finish();
1615 return;
1618 void MouseScrollHandler::SynthesizingEvent::
1619 NotifyNativeMessageHandlingFinished() {
1620 if (!IsSynthesizing()) {
1621 return;
1624 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1625 ("MouseScrollHandler::SynthesizingEvent::"
1626 "NotifyNativeMessageHandlingFinished(): IsWaitingInternalMessage=%s",
1627 GetBoolName(MouseScrollHandler::IsWaitingInternalMessage())));
1629 if (MouseScrollHandler::IsWaitingInternalMessage()) {
1630 mStatus = INTERNAL_MESSAGE_POSTED;
1631 return;
1634 // If the native message handler didn't post our internal message,
1635 // we our job is finished.
1636 // TODO: When we post the message to plugin window, there is remaning job.
1637 Finish();
1640 void MouseScrollHandler::SynthesizingEvent::
1641 NotifyInternalMessageHandlingFinished() {
1642 if (!IsSynthesizing()) {
1643 return;
1646 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1647 ("MouseScrollHandler::SynthesizingEvent::"
1648 "NotifyInternalMessageHandlingFinished()"));
1650 Finish();
1653 void MouseScrollHandler::SynthesizingEvent::Finish() {
1654 if (!IsSynthesizing()) {
1655 return;
1658 MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1659 ("MouseScrollHandler::SynthesizingEvent::Finish()"));
1661 // Restore the original key state.
1662 ::SetKeyboardState(mOriginalKeyState);
1664 mStatus = NOT_SYNTHESIZING;
1667 } // namespace widget
1668 } // namespace mozilla