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/. */
6 
7 #include "mozilla/DebugOnly.h"
8 
9 #include "mozilla/Logging.h"
10 
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"
18 
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"
24 
25 #include <psapi.h>
26 
27 namespace mozilla {
28 namespace widget {
29 
30 LazyLogModule gMouseScrollLog("MouseScrollHandlerWidgets");
31 
GetBoolName(bool aBool)32 static const char* GetBoolName(bool aBool) { return aBool ? "TRUE" : "FALSE"; }
33 
34 MouseScrollHandler* MouseScrollHandler::sInstance = nullptr;
35 
36 bool MouseScrollHandler::Device::sFakeScrollableWindowNeeded = false;
37 
38 bool MouseScrollHandler::Device::SynTP::sInitialized = false;
39 int32_t MouseScrollHandler::Device::SynTP::sMajorVersion = 0;
40 int32_t MouseScrollHandler::Device::SynTP::sMinorVersion = -1;
41 
42 bool MouseScrollHandler::Device::Elantech::sUseSwipeHack = false;
43 bool MouseScrollHandler::Device::Elantech::sUsePinchHack = false;
44 DWORD MouseScrollHandler::Device::Elantech::sZoomUntil = 0;
45 
46 bool MouseScrollHandler::Device::Apoint::sInitialized = false;
47 int32_t MouseScrollHandler::Device::Apoint::sMajorVersion = 0;
48 int32_t MouseScrollHandler::Device::Apoint::sMinorVersion = -1;
49 
50 bool MouseScrollHandler::Device::SetPoint::sMightBeUsing = false;
51 
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
56 
57 /******************************************************************************
58  *
59  * MouseScrollHandler
60  *
61  ******************************************************************************/
62 
63 /* static */
64 POINTS
GetCurrentMessagePos()65 MouseScrollHandler::GetCurrentMessagePos() {
66   if (SynthesizingEvent::IsSynthesizing()) {
67     return sInstance->mSynthesizingEvent->GetCursorPoint();
68   }
69   DWORD pos = ::GetMessagePos();
70   return MAKEPOINTS(pos);
71 }
72 
73 // Get rid of the GetMessagePos() API.
74 #define GetMessagePos()
75 
76 /* static */
Initialize()77 void MouseScrollHandler::Initialize() { Device::Init(); }
78 
79 /* static */
Shutdown()80 void MouseScrollHandler::Shutdown() {
81   delete sInstance;
82   sInstance = nullptr;
83 }
84 
85 /* static */
GetInstance()86 MouseScrollHandler* MouseScrollHandler::GetInstance() {
87   if (!sInstance) {
88     sInstance = new MouseScrollHandler();
89   }
90   return sInstance;
91 }
92 
MouseScrollHandler()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));
98 }
99 
~MouseScrollHandler()100 MouseScrollHandler::~MouseScrollHandler() {
101   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
102           ("MouseScroll: Destroying an instance, this=%p, sInstance=%p", this,
103            sInstance));
104 
105   delete mSynthesizingEvent;
106 }
107 
108 /* static */
MaybeLogKeyState()109 void MouseScrollHandler::MaybeLogKeyState() {
110   if (!MOZ_LOG_TEST(gMouseScrollLog, LogLevel::Debug)) {
111     return;
112   }
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%02X]=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"));
124       }
125     }
126   } else {
127     MOZ_LOG(
128         gMouseScrollLog, LogLevel::Debug,
129         ("MouseScroll::MaybeLogKeyState(): Failed to print current keyboard "
130          "state"));
131   }
132 }
133 
134 /* static */
NeedsMessage(UINT aMsg)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;
149   }
150   return false;
151 }
152 
153 /* static */
ProcessMessage(nsWindowBase * aWidget,UINT msg,WPARAM wParam,LPARAM lParam,MSGResult & aResult)154 bool MouseScrollHandler::ProcessMessage(nsWindowBase* aWidget, UINT msg,
155                                         WPARAM wParam, LPARAM lParam,
156                                         MSGResult& aResult) {
157   Device::Elantech::UpdateZoomUntil();
158 
159   switch (msg) {
160     case WM_SETTINGCHANGE:
161       if (!sInstance) {
162         return false;
163       }
164       if (wParam == SPI_SETWHEELSCROLLLINES ||
165           wParam == SPI_SETWHEELSCROLLCHARS) {
166         sInstance->mSystemSettings.MarkDirty();
167       }
168       return false;
169 
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;
182 
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;
190 
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;
198 
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;
207 
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%02X, ::GetMessageTime()=%d",
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;
223       }
224       return false;
225 
226     default:
227       return false;
228   }
229 }
230 
231 /* static */
SynthesizeNativeMouseScrollEvent(nsWindowBase * aWidget,const LayoutDeviceIntPoint & aPoint,uint32_t aNativeMessage,int32_t aDelta,uint32_t aModifierFlags,uint32_t aAdditionalFlags)232 nsresult MouseScrollHandler::SynthesizeNativeMouseScrollEvent(
233     nsWindowBase* 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);
238 
239   POINT pt;
240   pt.x = aPoint.x;
241   pt.y = aPoint.y;
242 
243   HWND target = useFocusedWindow ? ::WindowFromPoint(pt) : ::GetFocus();
244   NS_ENSURE_TRUE(target, NS_ERROR_FAILURE);
245 
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;
255       }
256       if (aModifierFlags & (nsIWidget::SHIFT_L | nsIWidget::SHIFT_R)) {
257         mod |= MK_SHIFT;
258       }
259       wParam = MAKEWPARAM(mod, aDelta);
260       break;
261     }
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;
272   }
273 
274   // Ensure to make the instance.
275   GetInstance();
276 
277   BYTE kbdState[256];
278   memset(kbdState, 0, sizeof(kbdState));
279 
280   AutoTArray<KeyPair, 10> keySequence;
281   WinUtils::SetupKeyModifiersSequence(&keySequence, aModifierFlags,
282                                       aNativeMessage);
283 
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;
290     }
291   }
292 
293   if (!sInstance->mSynthesizingEvent) {
294     sInstance->mSynthesizingEvent = new SynthesizingEvent();
295   }
296 
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);
302 }
303 
304 /* static */
InitEvent(nsWindowBase * aWidget,WidgetGUIEvent & aEvent,LPARAM * aPoint)305 void MouseScrollHandler::InitEvent(nsWindowBase* aWidget,
306                                    WidgetGUIEvent& aEvent, LPARAM* aPoint) {
307   NS_ENSURE_TRUE_VOID(aWidget);
308 
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();
316   }
317 
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);
323 
324   LayoutDeviceIntPoint point;
325   point.x = pointOnWindow.x;
326   point.y = pointOnWindow.y;
327 
328   aWidget->InitEvent(aEvent, &point);
329 }
330 
331 /* static */
GetModifierKeyState(UINT aMessage)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);
343   }
344   return result;
345 }
346 
347 POINT
ComputeMessagePos(UINT aMessage,WPARAM aWParam,LPARAM aLParam)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;
360   }
361   return point;
362 }
363 
ProcessNativeMouseWheelMessage(nsWindowBase * aWidget,UINT aMessage,WPARAM aWParam,LPARAM aLParam)364 void MouseScrollHandler::ProcessNativeMouseWheelMessage(nsWindowBase* aWidget,
365                                                         UINT aMessage,
366                                                         WPARAM aWParam,
367                                                         LPARAM aLParam) {
368   if (SynthesizingEvent::IsSynthesizing()) {
369     mSynthesizingEvent->NativeMessageReceived(aWidget, aMessage, aWParam,
370                                               aLParam);
371   }
372 
373   POINT point = ComputeMessagePos(aMessage, aWParam, aLParam);
374 
375   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
376           ("MouseScroll::ProcessNativeMouseWheelMessage: aWidget=%p, "
377            "aMessage=%s, wParam=0x%08X, lParam=0x%08X, point: { x=%d, y=%d }",
378            aWidget,
379            aMessage == WM_MOUSEWHEEL    ? "WM_MOUSEWHEEL"
380            : aMessage == WM_MOUSEHWHEEL ? "WM_MOUSEHWHEEL"
381            : aMessage == WM_VSCROLL     ? "WM_VSCROLL"
382                                         : "WM_HSCROLL",
383            aWParam, aLParam, point.x, point.y));
384   MaybeLogKeyState();
385 
386   HWND underCursorWnd = ::WindowFromPoint(point);
387   if (!underCursorWnd) {
388     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
389             ("MouseScroll::ProcessNativeMouseWheelMessage: "
390              "No window is not found under the cursor"));
391     return;
392   }
393 
394   if (Device::Elantech::IsPinchHackNeeded() &&
395       Device::Elantech::IsHelperWindow(underCursorWnd)) {
396     // The Elantech driver places a window right underneath the cursor
397     // when sending a WM_MOUSEWHEEL event to us as part of a pinch-to-zoom
398     // gesture.  We detect that here, and search for our window that would
399     // be beneath the cursor if that window wasn't there.
400     underCursorWnd = WinUtils::FindOurWindowAtPoint(point);
401     if (!underCursorWnd) {
402       MOZ_LOG(gMouseScrollLog, LogLevel::Info,
403               ("MouseScroll::ProcessNativeMouseWheelMessage: "
404                "Our window is not found under the Elantech helper window"));
405       return;
406     }
407   }
408 
409   // Handle most cases first.  If the window under mouse cursor is our window
410   // except plugin window (MozillaWindowClass), we should handle the message
411   // on the window.
412   if (WinUtils::IsOurProcessWindow(underCursorWnd)) {
413     nsWindowBase* destWindow = WinUtils::GetNSWindowBasePtr(underCursorWnd);
414     if (!destWindow) {
415       MOZ_LOG(gMouseScrollLog, LogLevel::Info,
416               ("MouseScroll::ProcessNativeMouseWheelMessage: "
417                "Found window under the cursor isn't managed by nsWindow..."));
418       HWND wnd = ::GetParent(underCursorWnd);
419       for (; wnd; wnd = ::GetParent(wnd)) {
420         destWindow = WinUtils::GetNSWindowBasePtr(wnd);
421         if (destWindow) {
422           break;
423         }
424       }
425       if (!wnd) {
426         MOZ_LOG(
427             gMouseScrollLog, LogLevel::Info,
428             ("MouseScroll::ProcessNativeMouseWheelMessage: Our window which is "
429              "managed by nsWindow is not found under the cursor"));
430         return;
431       }
432     }
433 
434     MOZ_ASSERT(destWindow, "destWindow must not be NULL");
435 
436     // Some odd touchpad utils sets focus to window under the mouse cursor.
437     // this emulates the odd behavior for debug.
438     if (mUserPrefs.ShouldEmulateToMakeWindowUnderCursorForeground() &&
439         (aMessage == WM_MOUSEWHEEL || aMessage == WM_MOUSEHWHEEL) &&
440         ::GetForegroundWindow() != destWindow->GetWindowHandle()) {
441       ::SetForegroundWindow(destWindow->GetWindowHandle());
442     }
443 
444     // If the found window is our plugin window, it means that the message
445     // has been handled by the plugin but not consumed.  We should handle the
446     // message on its parent window.  However, note that the DOM event may
447     // cause accessing the plugin.  Therefore, we should unlock the plugin
448     // process by using PostMessage().
449     if (destWindow->IsPlugin()) {
450       destWindow = destWindow->GetParentWindowBase(false);
451       if (!destWindow) {
452         MOZ_LOG(
453             gMouseScrollLog, LogLevel::Info,
454             ("MouseScroll::ProcessNativeMouseWheelMessage: "
455              "Our window which is a parent of a plugin window is not found"));
456         return;
457       }
458     }
459     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
460             ("MouseScroll::ProcessNativeMouseWheelMessage: Succeeded, "
461              "Posting internal message to an nsWindow (%p)...",
462              destWindow));
463     mIsWaitingInternalMessage = true;
464     UINT internalMessage = WinUtils::GetInternalMessage(aMessage);
465     ::PostMessage(destWindow->GetWindowHandle(), internalMessage, aWParam,
466                   aLParam);
467     return;
468   }
469 
470   // If the window under cursor is not in our process, it means:
471   // 1. The window may be a plugin window (GeckoPluginWindow or its descendant).
472   // 2. The window may be another application's window.
473   HWND pluginWnd = WinUtils::FindOurProcessWindow(underCursorWnd);
474   if (!pluginWnd) {
475     // If there is no plugin window in ancestors of the window under cursor,
476     // the window is for another applications (case 2).
477     // We don't need to handle this message.
478     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
479             ("MouseScroll::ProcessNativeMouseWheelMessage: "
480              "Our window is not found under the cursor"));
481     return;
482   }
483 
484   // If we're a plugin window (MozillaWindowClass) and cursor in this window,
485   // the message shouldn't go to plugin's wndproc again.  So, we should handle
486   // it on parent window.  However, note that the DOM event may cause accessing
487   // the plugin.  Therefore, we should unlock the plugin process by using
488   // PostMessage().
489   if (aWidget->IsPlugin() && aWidget->GetWindowHandle() == pluginWnd) {
490     nsWindowBase* destWindow = aWidget->GetParentWindowBase(false);
491     if (!destWindow) {
492       MOZ_LOG(gMouseScrollLog, LogLevel::Info,
493               ("MouseScroll::ProcessNativeMouseWheelMessage: Our normal window "
494                "which "
495                "is a parent of this plugin window is not found"));
496       return;
497     }
498     MOZ_LOG(
499         gMouseScrollLog, LogLevel::Info,
500         ("MouseScroll::ProcessNativeMouseWheelMessage: Succeeded, "
501          "Posting internal message to an nsWindow (%p) which is parent of this "
502          "plugin window...",
503          destWindow));
504     mIsWaitingInternalMessage = true;
505     UINT internalMessage = WinUtils::GetInternalMessage(aMessage);
506     ::PostMessage(destWindow->GetWindowHandle(), internalMessage, aWParam,
507                   aLParam);
508     return;
509   }
510 
511   // If the window is a part of plugin, we should post the message to it.
512   MOZ_LOG(
513       gMouseScrollLog, LogLevel::Info,
514       ("MouseScroll::ProcessNativeMouseWheelMessage: Succeeded, "
515        "Redirecting the message to a window which is a plugin child window"));
516   ::PostMessage(underCursorWnd, aMessage, aWParam, aLParam);
517 }
518 
ProcessNativeScrollMessage(nsWindowBase * aWidget,UINT aMessage,WPARAM aWParam,LPARAM aLParam)519 bool MouseScrollHandler::ProcessNativeScrollMessage(nsWindowBase* aWidget,
520                                                     UINT aMessage,
521                                                     WPARAM aWParam,
522                                                     LPARAM aLParam) {
523   if (aLParam || mUserPrefs.IsScrollMessageHandledAsWheelMessage()) {
524     // Scroll message generated by Thinkpad Trackpoint Driver or similar
525     // Treat as a mousewheel message and scroll appropriately
526     ProcessNativeMouseWheelMessage(aWidget, aMessage, aWParam, aLParam);
527     // Always consume the scroll message if we try to emulate mouse wheel
528     // action.
529     return true;
530   }
531 
532   if (SynthesizingEvent::IsSynthesizing()) {
533     mSynthesizingEvent->NativeMessageReceived(aWidget, aMessage, aWParam,
534                                               aLParam);
535   }
536 
537   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
538           ("MouseScroll::ProcessNativeScrollMessage: aWidget=%p, "
539            "aMessage=%s, wParam=0x%08X, lParam=0x%08X",
540            aWidget, aMessage == WM_VSCROLL ? "WM_VSCROLL" : "WM_HSCROLL",
541            aWParam, aLParam));
542 
543   // Scroll message generated by external application
544   WidgetContentCommandEvent commandEvent(true, eContentCommandScroll, aWidget);
545   commandEvent.mScroll.mIsHorizontal = (aMessage == WM_HSCROLL);
546 
547   switch (LOWORD(aWParam)) {
548     case SB_LINEUP:  // SB_LINELEFT
549       commandEvent.mScroll.mUnit =
550           WidgetContentCommandEvent::eCmdScrollUnit_Line;
551       commandEvent.mScroll.mAmount = -1;
552       break;
553     case SB_LINEDOWN:  // SB_LINERIGHT
554       commandEvent.mScroll.mUnit =
555           WidgetContentCommandEvent::eCmdScrollUnit_Line;
556       commandEvent.mScroll.mAmount = 1;
557       break;
558     case SB_PAGEUP:  // SB_PAGELEFT
559       commandEvent.mScroll.mUnit =
560           WidgetContentCommandEvent::eCmdScrollUnit_Page;
561       commandEvent.mScroll.mAmount = -1;
562       break;
563     case SB_PAGEDOWN:  // SB_PAGERIGHT
564       commandEvent.mScroll.mUnit =
565           WidgetContentCommandEvent::eCmdScrollUnit_Page;
566       commandEvent.mScroll.mAmount = 1;
567       break;
568     case SB_TOP:  // SB_LEFT
569       commandEvent.mScroll.mUnit =
570           WidgetContentCommandEvent::eCmdScrollUnit_Whole;
571       commandEvent.mScroll.mAmount = -1;
572       break;
573     case SB_BOTTOM:  // SB_RIGHT
574       commandEvent.mScroll.mUnit =
575           WidgetContentCommandEvent::eCmdScrollUnit_Whole;
576       commandEvent.mScroll.mAmount = 1;
577       break;
578     default:
579       return false;
580   }
581   // XXX If this is a plugin window, we should dispatch the event from
582   //     parent window.
583   aWidget->DispatchContentCommandEvent(&commandEvent);
584   return true;
585 }
586 
HandleMouseWheelMessage(nsWindowBase * aWidget,UINT aMessage,WPARAM aWParam,LPARAM aLParam)587 void MouseScrollHandler::HandleMouseWheelMessage(nsWindowBase* aWidget,
588                                                  UINT aMessage, WPARAM aWParam,
589                                                  LPARAM aLParam) {
590   MOZ_ASSERT((aMessage == MOZ_WM_MOUSEVWHEEL || aMessage == MOZ_WM_MOUSEHWHEEL),
591              "HandleMouseWheelMessage must be called with "
592              "MOZ_WM_MOUSEVWHEEL or MOZ_WM_MOUSEHWHEEL");
593 
594   MOZ_LOG(
595       gMouseScrollLog, LogLevel::Info,
596       ("MouseScroll::HandleMouseWheelMessage: aWidget=%p, "
597        "aMessage=MOZ_WM_MOUSE%sWHEEL, aWParam=0x%08X, aLParam=0x%08X",
598        aWidget, aMessage == MOZ_WM_MOUSEVWHEEL ? "V" : "H", aWParam, aLParam));
599 
600   mIsWaitingInternalMessage = false;
601 
602   // If it's not allowed to cache system settings, we need to reset the cache
603   // before handling the mouse wheel message.
604   mSystemSettings.TrustedScrollSettingsDriver();
605 
606   EventInfo eventInfo(aWidget, WinUtils::GetNativeMessage(aMessage), aWParam,
607                       aLParam);
608   if (!eventInfo.CanDispatchWheelEvent()) {
609     MOZ_LOG(
610         gMouseScrollLog, LogLevel::Info,
611         ("MouseScroll::HandleMouseWheelMessage: Cannot dispatch the events"));
612     mLastEventInfo.ResetTransaction();
613     return;
614   }
615 
616   // Discard the remaining delta if current wheel message and last one are
617   // received by different window or to scroll different direction or
618   // different unit scroll.  Furthermore, if the last event was too old.
619   if (!mLastEventInfo.CanContinueTransaction(eventInfo)) {
620     mLastEventInfo.ResetTransaction();
621   }
622 
623   mLastEventInfo.RecordEvent(eventInfo);
624 
625   ModifierKeyState modKeyState = GetModifierKeyState(aMessage);
626 
627   // Grab the widget, it might be destroyed by a DOM event handler.
628   RefPtr<nsWindowBase> kungFuDethGrip(aWidget);
629 
630   WidgetWheelEvent wheelEvent(true, eWheel, aWidget);
631   if (mLastEventInfo.InitWheelEvent(aWidget, wheelEvent, modKeyState,
632                                     aLParam)) {
633     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
634             ("MouseScroll::HandleMouseWheelMessage: dispatching "
635              "eWheel event"));
636     aWidget->DispatchWheelEvent(&wheelEvent);
637     if (aWidget->Destroyed()) {
638       MOZ_LOG(gMouseScrollLog, LogLevel::Info,
639               ("MouseScroll::HandleMouseWheelMessage: The window was destroyed "
640                "by eWheel event"));
641       mLastEventInfo.ResetTransaction();
642       return;
643     }
644   } else {
645     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
646             ("MouseScroll::HandleMouseWheelMessage: eWheel event is not "
647              "dispatched"));
648   }
649 }
650 
HandleScrollMessageAsMouseWheelMessage(nsWindowBase * aWidget,UINT aMessage,WPARAM aWParam,LPARAM aLParam)651 void MouseScrollHandler::HandleScrollMessageAsMouseWheelMessage(
652     nsWindowBase* aWidget, UINT aMessage, WPARAM aWParam, LPARAM aLParam) {
653   MOZ_ASSERT((aMessage == MOZ_WM_VSCROLL || aMessage == MOZ_WM_HSCROLL),
654              "HandleScrollMessageAsMouseWheelMessage must be called with "
655              "MOZ_WM_VSCROLL or MOZ_WM_HSCROLL");
656 
657   mIsWaitingInternalMessage = false;
658 
659   ModifierKeyState modKeyState = GetModifierKeyState(aMessage);
660 
661   WidgetWheelEvent wheelEvent(true, eWheel, aWidget);
662   double& delta =
663       (aMessage == MOZ_WM_VSCROLL) ? wheelEvent.mDeltaY : wheelEvent.mDeltaX;
664   int32_t& lineOrPageDelta = (aMessage == MOZ_WM_VSCROLL)
665                                  ? wheelEvent.mLineOrPageDeltaY
666                                  : wheelEvent.mLineOrPageDeltaX;
667 
668   delta = 1.0;
669   lineOrPageDelta = 1;
670 
671   switch (LOWORD(aWParam)) {
672     case SB_PAGEUP:
673       delta = -1.0;
674       lineOrPageDelta = -1;
675     case SB_PAGEDOWN:
676       wheelEvent.mDeltaMode = dom::WheelEvent_Binding::DOM_DELTA_PAGE;
677       break;
678 
679     case SB_LINEUP:
680       delta = -1.0;
681       lineOrPageDelta = -1;
682     case SB_LINEDOWN:
683       wheelEvent.mDeltaMode = dom::WheelEvent_Binding::DOM_DELTA_LINE;
684       break;
685 
686     default:
687       return;
688   }
689   modKeyState.InitInputEvent(wheelEvent);
690 
691   // Current mouse position may not be same as when the original message
692   // is received. However, this data is not available with the original
693   // message, which is why nullptr is passed in. We need to know the actual
694   // mouse cursor position when the original message was received.
695   InitEvent(aWidget, wheelEvent, nullptr);
696 
697   MOZ_LOG(
698       gMouseScrollLog, LogLevel::Info,
699       ("MouseScroll::HandleScrollMessageAsMouseWheelMessage: aWidget=%p, "
700        "aMessage=MOZ_WM_%sSCROLL, aWParam=0x%08X, aLParam=0x%08X, "
701        "wheelEvent { mRefPoint: { x: %d, y: %d }, mDeltaX: %f, mDeltaY: %f, "
702        "mLineOrPageDeltaX: %d, mLineOrPageDeltaY: %d, "
703        "isShift: %s, isControl: %s, isAlt: %s, isMeta: %s }",
704        aWidget, (aMessage == MOZ_WM_VSCROLL) ? "V" : "H", aWParam, aLParam,
705        wheelEvent.mRefPoint.x, wheelEvent.mRefPoint.y, wheelEvent.mDeltaX,
706        wheelEvent.mDeltaY, wheelEvent.mLineOrPageDeltaX,
707        wheelEvent.mLineOrPageDeltaY, GetBoolName(wheelEvent.IsShift()),
708        GetBoolName(wheelEvent.IsControl()), GetBoolName(wheelEvent.IsAlt()),
709        GetBoolName(wheelEvent.IsMeta())));
710 
711   aWidget->DispatchWheelEvent(&wheelEvent);
712 }
713 
714 /******************************************************************************
715  *
716  * EventInfo
717  *
718  ******************************************************************************/
719 
EventInfo(nsWindowBase * aWidget,UINT aMessage,WPARAM aWParam,LPARAM aLParam)720 MouseScrollHandler::EventInfo::EventInfo(nsWindowBase* aWidget, UINT aMessage,
721                                          WPARAM aWParam, LPARAM aLParam) {
722   MOZ_ASSERT(
723       aMessage == WM_MOUSEWHEEL || aMessage == WM_MOUSEHWHEEL,
724       "EventInfo must be initialized with WM_MOUSEWHEEL or WM_MOUSEHWHEEL");
725 
726   MouseScrollHandler::GetInstance()->mSystemSettings.Init();
727 
728   mIsVertical = (aMessage == WM_MOUSEWHEEL);
729   mIsPage =
730       MouseScrollHandler::sInstance->mSystemSettings.IsPageScroll(mIsVertical);
731   mDelta = (short)HIWORD(aWParam);
732   mWnd = aWidget->GetWindowHandle();
733   mTimeStamp = TimeStamp::Now();
734 }
735 
CanDispatchWheelEvent() const736 bool MouseScrollHandler::EventInfo::CanDispatchWheelEvent() const {
737   if (!GetScrollAmount()) {
738     // XXX I think that we should dispatch mouse wheel events even if the
739     // operation will not scroll because the wheel operation really happened
740     // and web application may want to handle the event for non-scroll action.
741     return false;
742   }
743 
744   return (mDelta != 0);
745 }
746 
GetScrollAmount() const747 int32_t MouseScrollHandler::EventInfo::GetScrollAmount() const {
748   if (mIsPage) {
749     return 1;
750   }
751   return MouseScrollHandler::sInstance->mSystemSettings.GetScrollAmount(
752       mIsVertical);
753 }
754 
755 /******************************************************************************
756  *
757  * LastEventInfo
758  *
759  ******************************************************************************/
760 
CanContinueTransaction(const EventInfo & aNewEvent)761 bool MouseScrollHandler::LastEventInfo::CanContinueTransaction(
762     const EventInfo& aNewEvent) {
763   int32_t timeout = MouseScrollHandler::sInstance->mUserPrefs
764                         .GetMouseScrollTransactionTimeout();
765   return !mWnd ||
766          (mWnd == aNewEvent.GetWindowHandle() &&
767           IsPositive() == aNewEvent.IsPositive() &&
768           mIsVertical == aNewEvent.IsVertical() &&
769           mIsPage == aNewEvent.IsPage() &&
770           (timeout < 0 || TimeStamp::Now() - mTimeStamp <=
771                               TimeDuration::FromMilliseconds(timeout)));
772 }
773 
ResetTransaction()774 void MouseScrollHandler::LastEventInfo::ResetTransaction() {
775   if (!mWnd) {
776     return;
777   }
778 
779   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
780           ("MouseScroll::LastEventInfo::ResetTransaction()"));
781 
782   mWnd = nullptr;
783   mAccumulatedDelta = 0;
784 }
785 
RecordEvent(const EventInfo & aEvent)786 void MouseScrollHandler::LastEventInfo::RecordEvent(const EventInfo& aEvent) {
787   mWnd = aEvent.GetWindowHandle();
788   mDelta = aEvent.GetNativeDelta();
789   mIsVertical = aEvent.IsVertical();
790   mIsPage = aEvent.IsPage();
791   mTimeStamp = TimeStamp::Now();
792 }
793 
794 /* static */
RoundDelta(double aDelta)795 int32_t MouseScrollHandler::LastEventInfo::RoundDelta(double aDelta) {
796   return (aDelta >= 0) ? (int32_t)floor(aDelta) : (int32_t)ceil(aDelta);
797 }
798 
InitWheelEvent(nsWindowBase * aWidget,WidgetWheelEvent & aWheelEvent,const ModifierKeyState & aModKeyState,LPARAM aLParam)799 bool MouseScrollHandler::LastEventInfo::InitWheelEvent(
800     nsWindowBase* aWidget, WidgetWheelEvent& aWheelEvent,
801     const ModifierKeyState& aModKeyState, LPARAM aLParam) {
802   MOZ_ASSERT(aWheelEvent.mMessage == eWheel);
803 
804   if (StaticPrefs::mousewheel_ignore_cursor_position_in_lparam()) {
805     InitEvent(aWidget, aWheelEvent, nullptr);
806   } else {
807     InitEvent(aWidget, aWheelEvent, &aLParam);
808   }
809 
810   aModKeyState.InitInputEvent(aWheelEvent);
811 
812   // Our positive delta value means to bottom or right.
813   // But positive native delta value means to top or right.
814   // Use orienter for computing our delta value with native delta value.
815   int32_t orienter = mIsVertical ? -1 : 1;
816 
817   aWheelEvent.mDeltaMode = mIsPage ? dom::WheelEvent_Binding::DOM_DELTA_PAGE
818                                    : dom::WheelEvent_Binding::DOM_DELTA_LINE;
819 
820   double ticks = double(mDelta) * orienter / double(WHEEL_DELTA);
821   if (mIsVertical) {
822     aWheelEvent.mWheelTicksY = ticks;
823   } else {
824     aWheelEvent.mWheelTicksX = ticks;
825   }
826 
827   double& delta = mIsVertical ? aWheelEvent.mDeltaY : aWheelEvent.mDeltaX;
828   int32_t& lineOrPageDelta = mIsVertical ? aWheelEvent.mLineOrPageDeltaY
829                                          : aWheelEvent.mLineOrPageDeltaX;
830 
831   double nativeDeltaPerUnit =
832       mIsPage ? double(WHEEL_DELTA) : double(WHEEL_DELTA) / GetScrollAmount();
833 
834   delta = double(mDelta) * orienter / nativeDeltaPerUnit;
835   mAccumulatedDelta += mDelta;
836   lineOrPageDelta =
837       mAccumulatedDelta * orienter / RoundDelta(nativeDeltaPerUnit);
838   mAccumulatedDelta -=
839       lineOrPageDelta * orienter * RoundDelta(nativeDeltaPerUnit);
840 
841   if (aWheelEvent.mDeltaMode != dom::WheelEvent_Binding::DOM_DELTA_LINE) {
842     // If the scroll delta mode isn't per line scroll, we shouldn't allow to
843     // override the system scroll speed setting.
844     aWheelEvent.mAllowToOverrideSystemScrollSpeed = false;
845   } else if (!MouseScrollHandler::sInstance->mSystemSettings
846                   .IsOverridingSystemScrollSpeedAllowed()) {
847     // If the system settings are customized by either the user or
848     // the mouse utility, we shouldn't allow to override the system scroll
849     // speed setting.
850     aWheelEvent.mAllowToOverrideSystemScrollSpeed = false;
851   } else {
852     // For suppressing too fast scroll, we should ensure that the maximum
853     // overridden delta value should be less than overridden scroll speed
854     // with default scroll amount.
855     double defaultScrollAmount = mIsVertical
856                                      ? SystemSettings::DefaultScrollLines()
857                                      : SystemSettings::DefaultScrollChars();
858     double maxDelta = WidgetWheelEvent::ComputeOverriddenDelta(
859         defaultScrollAmount, mIsVertical);
860     if (maxDelta != defaultScrollAmount) {
861       double overriddenDelta =
862           WidgetWheelEvent::ComputeOverriddenDelta(Abs(delta), mIsVertical);
863       if (overriddenDelta > maxDelta) {
864         // Suppress to fast scroll since overriding system scroll speed with
865         // current delta value causes too big delta value.
866         aWheelEvent.mAllowToOverrideSystemScrollSpeed = false;
867       }
868     }
869   }
870 
871   MOZ_LOG(
872       gMouseScrollLog, LogLevel::Info,
873       ("MouseScroll::LastEventInfo::InitWheelEvent: aWidget=%p, "
874        "aWheelEvent { mRefPoint: { x: %d, y: %d }, mDeltaX: %f, mDeltaY: %f, "
875        "mLineOrPageDeltaX: %d, mLineOrPageDeltaY: %d, "
876        "isShift: %s, isControl: %s, isAlt: %s, isMeta: %s, "
877        "mAllowToOverrideSystemScrollSpeed: %s }, "
878        "mAccumulatedDelta: %d",
879        aWidget, aWheelEvent.mRefPoint.x, aWheelEvent.mRefPoint.y,
880        aWheelEvent.mDeltaX, aWheelEvent.mDeltaY, aWheelEvent.mLineOrPageDeltaX,
881        aWheelEvent.mLineOrPageDeltaY, GetBoolName(aWheelEvent.IsShift()),
882        GetBoolName(aWheelEvent.IsControl()), GetBoolName(aWheelEvent.IsAlt()),
883        GetBoolName(aWheelEvent.IsMeta()),
884        GetBoolName(aWheelEvent.mAllowToOverrideSystemScrollSpeed),
885        mAccumulatedDelta));
886 
887   return (delta != 0);
888 }
889 
890 /******************************************************************************
891  *
892  * SystemSettings
893  *
894  ******************************************************************************/
895 
Init()896 void MouseScrollHandler::SystemSettings::Init() {
897   if (mInitialized) {
898     return;
899   }
900 
901   InitScrollLines();
902   InitScrollChars();
903 
904   mInitialized = true;
905 
906   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
907           ("MouseScroll::SystemSettings::Init(): initialized, "
908            "mScrollLines=%d, mScrollChars=%d",
909            mScrollLines, mScrollChars));
910 }
911 
InitScrollLines()912 bool MouseScrollHandler::SystemSettings::InitScrollLines() {
913   int32_t oldValue = mInitialized ? mScrollLines : 0;
914   mIsReliableScrollLines = false;
915   mScrollLines = MouseScrollHandler::sInstance->mUserPrefs
916                      .GetOverriddenVerticalScrollAmout();
917   if (mScrollLines >= 0) {
918     // overridden by the pref.
919     mIsReliableScrollLines = true;
920     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
921             ("MouseScroll::SystemSettings::InitScrollLines(): mScrollLines is "
922              "overridden by the pref: %d",
923              mScrollLines));
924   } else if (!::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &mScrollLines,
925                                      0)) {
926     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
927             ("MouseScroll::SystemSettings::InitScrollLines(): "
928              "::SystemParametersInfo("
929              "SPI_GETWHEELSCROLLLINES) failed"));
930     mScrollLines = DefaultScrollLines();
931   }
932 
933   if (mScrollLines > WHEEL_DELTA) {
934     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
935             ("MouseScroll::SystemSettings::InitScrollLines(): the result of "
936              "::SystemParametersInfo(SPI_GETWHEELSCROLLLINES) is too large: %d",
937              mScrollLines));
938     // sScrollLines usually equals 3 or 0 (for no scrolling)
939     // However, if sScrollLines > WHEEL_DELTA, we assume that
940     // the mouse driver wants a page scroll.  The docs state that
941     // sScrollLines should explicitly equal WHEEL_PAGESCROLL, but
942     // since some mouse drivers use an arbitrary large number instead,
943     // we have to handle that as well.
944     mScrollLines = WHEEL_PAGESCROLL;
945   }
946 
947   return oldValue != mScrollLines;
948 }
949 
InitScrollChars()950 bool MouseScrollHandler::SystemSettings::InitScrollChars() {
951   int32_t oldValue = mInitialized ? mScrollChars : 0;
952   mIsReliableScrollChars = false;
953   mScrollChars = MouseScrollHandler::sInstance->mUserPrefs
954                      .GetOverriddenHorizontalScrollAmout();
955   if (mScrollChars >= 0) {
956     // overridden by the pref.
957     mIsReliableScrollChars = true;
958     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
959             ("MouseScroll::SystemSettings::InitScrollChars(): mScrollChars is "
960              "overridden by the pref: %d",
961              mScrollChars));
962   } else if (!::SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &mScrollChars,
963                                      0)) {
964     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
965             ("MouseScroll::SystemSettings::InitScrollChars(): "
966              "::SystemParametersInfo("
967              "SPI_GETWHEELSCROLLCHARS) failed, this is unexpected on Vista or "
968              "later"));
969     // XXX Should we use DefaultScrollChars()?
970     mScrollChars = 1;
971   }
972 
973   if (mScrollChars > WHEEL_DELTA) {
974     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
975             ("MouseScroll::SystemSettings::InitScrollChars(): the result of "
976              "::SystemParametersInfo(SPI_GETWHEELSCROLLCHARS) is too large: %d",
977              mScrollChars));
978     // See the comments for the case mScrollLines > WHEEL_DELTA.
979     mScrollChars = WHEEL_PAGESCROLL;
980   }
981 
982   return oldValue != mScrollChars;
983 }
984 
MarkDirty()985 void MouseScrollHandler::SystemSettings::MarkDirty() {
986   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
987           ("MouseScrollHandler::SystemSettings::MarkDirty(): "
988            "Marking SystemSettings dirty"));
989   mInitialized = false;
990   // When system settings are changed, we should reset current transaction.
991   MOZ_ASSERT(sInstance,
992              "Must not be called at initializing MouseScrollHandler");
993   MouseScrollHandler::sInstance->mLastEventInfo.ResetTransaction();
994 }
995 
RefreshCache()996 void MouseScrollHandler::SystemSettings::RefreshCache() {
997   bool isChanged = InitScrollLines();
998   isChanged = InitScrollChars() || isChanged;
999   if (!isChanged) {
1000     return;
1001   }
1002   // If the scroll amount is changed, we should reset current transaction.
1003   MOZ_ASSERT(sInstance,
1004              "Must not be called at initializing MouseScrollHandler");
1005   MouseScrollHandler::sInstance->mLastEventInfo.ResetTransaction();
1006 }
1007 
TrustedScrollSettingsDriver()1008 void MouseScrollHandler::SystemSettings::TrustedScrollSettingsDriver() {
1009   if (!mInitialized) {
1010     return;
1011   }
1012 
1013   // if the cache is initialized with prefs, we don't need to refresh it.
1014   if (mIsReliableScrollLines && mIsReliableScrollChars) {
1015     return;
1016   }
1017 
1018   MouseScrollHandler::UserPrefs& userPrefs =
1019       MouseScrollHandler::sInstance->mUserPrefs;
1020 
1021   // If system settings cache is disabled, we should always refresh them.
1022   if (!userPrefs.IsSystemSettingCacheEnabled()) {
1023     RefreshCache();
1024     return;
1025   }
1026 
1027   // If pref is set to as "always trust the cache", we shouldn't refresh them
1028   // in any environments.
1029   if (userPrefs.IsSystemSettingCacheForciblyEnabled()) {
1030     return;
1031   }
1032 
1033   // If SynTP of Synaptics or Apoint of Alps is installed, it may hook
1034   // ::SystemParametersInfo() and returns different value from system settings.
1035   if (Device::SynTP::IsDriverInstalled() ||
1036       Device::Apoint::IsDriverInstalled()) {
1037     RefreshCache();
1038     return;
1039   }
1040 
1041   // XXX We're not sure about other touchpad drivers...
1042 }
1043 
1044 bool MouseScrollHandler::SystemSettings::
IsOverridingSystemScrollSpeedAllowed()1045     IsOverridingSystemScrollSpeedAllowed() {
1046   return mScrollLines == DefaultScrollLines() &&
1047          mScrollChars == DefaultScrollChars();
1048 }
1049 
1050 /******************************************************************************
1051  *
1052  * UserPrefs
1053  *
1054  ******************************************************************************/
1055 
UserPrefs()1056 MouseScrollHandler::UserPrefs::UserPrefs() : mInitialized(false) {
1057   // We need to reset mouse wheel transaction when all of mousewheel related
1058   // prefs are changed.
1059   DebugOnly<nsresult> rv =
1060       Preferences::RegisterPrefixCallback(OnChange, "mousewheel.", this);
1061   MOZ_ASSERT(NS_SUCCEEDED(rv), "Failed to register callback for mousewheel.");
1062 }
1063 
~UserPrefs()1064 MouseScrollHandler::UserPrefs::~UserPrefs() {
1065   DebugOnly<nsresult> rv =
1066       Preferences::UnregisterPrefixCallback(OnChange, "mousewheel.", this);
1067   MOZ_ASSERT(NS_SUCCEEDED(rv), "Failed to unregister callback for mousewheel.");
1068 }
1069 
Init()1070 void MouseScrollHandler::UserPrefs::Init() {
1071   if (mInitialized) {
1072     return;
1073   }
1074 
1075   mInitialized = true;
1076 
1077   mScrollMessageHandledAsWheelMessage =
1078       Preferences::GetBool("mousewheel.emulate_at_wm_scroll", false);
1079   mEnableSystemSettingCache =
1080       Preferences::GetBool("mousewheel.system_settings_cache.enabled", true);
1081   mForceEnableSystemSettingCache = Preferences::GetBool(
1082       "mousewheel.system_settings_cache.force_enabled", false);
1083   mEmulateToMakeWindowUnderCursorForeground = Preferences::GetBool(
1084       "mousewheel.debug.make_window_under_cursor_foreground", false);
1085   mOverriddenVerticalScrollAmount =
1086       Preferences::GetInt("mousewheel.windows.vertical_amount_override", -1);
1087   mOverriddenHorizontalScrollAmount =
1088       Preferences::GetInt("mousewheel.windows.horizontal_amount_override", -1);
1089   mMouseScrollTransactionTimeout = Preferences::GetInt(
1090       "mousewheel.windows.transaction.timeout", DEFAULT_TIMEOUT_DURATION);
1091 
1092   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1093           ("MouseScroll::UserPrefs::Init(): initialized, "
1094            "mScrollMessageHandledAsWheelMessage=%s, "
1095            "mEnableSystemSettingCache=%s, "
1096            "mForceEnableSystemSettingCache=%s, "
1097            "mEmulateToMakeWindowUnderCursorForeground=%s, "
1098            "mOverriddenVerticalScrollAmount=%d, "
1099            "mOverriddenHorizontalScrollAmount=%d, "
1100            "mMouseScrollTransactionTimeout=%d",
1101            GetBoolName(mScrollMessageHandledAsWheelMessage),
1102            GetBoolName(mEnableSystemSettingCache),
1103            GetBoolName(mForceEnableSystemSettingCache),
1104            GetBoolName(mEmulateToMakeWindowUnderCursorForeground),
1105            mOverriddenVerticalScrollAmount, mOverriddenHorizontalScrollAmount,
1106            mMouseScrollTransactionTimeout));
1107 }
1108 
MarkDirty()1109 void MouseScrollHandler::UserPrefs::MarkDirty() {
1110   MOZ_LOG(
1111       gMouseScrollLog, LogLevel::Info,
1112       ("MouseScrollHandler::UserPrefs::MarkDirty(): Marking UserPrefs dirty"));
1113   mInitialized = false;
1114   // Some prefs might override system settings, so, we should mark them dirty.
1115   MouseScrollHandler::sInstance->mSystemSettings.MarkDirty();
1116   // When user prefs for mousewheel are changed, we should reset current
1117   // transaction.
1118   MOZ_ASSERT(sInstance,
1119              "Must not be called at initializing MouseScrollHandler");
1120   MouseScrollHandler::sInstance->mLastEventInfo.ResetTransaction();
1121 }
1122 
1123 /******************************************************************************
1124  *
1125  * Device
1126  *
1127  ******************************************************************************/
1128 
1129 /* static */
GetWorkaroundPref(const char * aPrefName,bool aValueIfAutomatic)1130 bool MouseScrollHandler::Device::GetWorkaroundPref(const char* aPrefName,
1131                                                    bool aValueIfAutomatic) {
1132   if (!aPrefName) {
1133     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1134             ("MouseScroll::Device::GetWorkaroundPref(): Failed, aPrefName is "
1135              "NULL"));
1136     return aValueIfAutomatic;
1137   }
1138 
1139   int32_t lHackValue = 0;
1140   if (NS_FAILED(Preferences::GetInt(aPrefName, &lHackValue))) {
1141     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1142             ("MouseScroll::Device::GetWorkaroundPref(): Preferences::GetInt() "
1143              "failed,"
1144              " aPrefName=\"%s\", aValueIfAutomatic=%s",
1145              aPrefName, GetBoolName(aValueIfAutomatic)));
1146     return aValueIfAutomatic;
1147   }
1148 
1149   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1150           ("MouseScroll::Device::GetWorkaroundPref(): Succeeded, "
1151            "aPrefName=\"%s\", aValueIfAutomatic=%s, lHackValue=%d",
1152            aPrefName, GetBoolName(aValueIfAutomatic), lHackValue));
1153 
1154   switch (lHackValue) {
1155     case 0:  // disabled
1156       return false;
1157     case 1:  // enabled
1158       return true;
1159     default:  // -1: autodetect
1160       return aValueIfAutomatic;
1161   }
1162 }
1163 
1164 /* static */
Init()1165 void MouseScrollHandler::Device::Init() {
1166   // FYI: Thinkpad's TrackPoint is Apoint of Alps and UltraNav is SynTP of
1167   //      Synaptics.  So, those drivers' information should be initialized
1168   //      before calling methods of TrackPoint and UltraNav.
1169   SynTP::Init();
1170   Elantech::Init();
1171   Apoint::Init();
1172 
1173   sFakeScrollableWindowNeeded = GetWorkaroundPref(
1174       "ui.trackpoint_hack.enabled", (TrackPoint::IsDriverInstalled() ||
1175                                      UltraNav::IsObsoleteDriverInstalled()));
1176 
1177   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1178           ("MouseScroll::Device::Init(): sFakeScrollableWindowNeeded=%s",
1179            GetBoolName(sFakeScrollableWindowNeeded)));
1180 }
1181 
1182 /******************************************************************************
1183  *
1184  * Device::SynTP
1185  *
1186  ******************************************************************************/
1187 
1188 /* static */
Init()1189 void MouseScrollHandler::Device::SynTP::Init() {
1190   if (sInitialized) {
1191     return;
1192   }
1193 
1194   sInitialized = true;
1195   sMajorVersion = 0;
1196   sMinorVersion = -1;
1197 
1198   wchar_t buf[40];
1199   bool foundKey = WinUtils::GetRegistryKey(
1200       HKEY_LOCAL_MACHINE, L"Software\\Synaptics\\SynTP\\Install",
1201       L"DriverVersion", buf, sizeof buf);
1202   if (!foundKey) {
1203     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1204             ("MouseScroll::Device::SynTP::Init(): "
1205              "SynTP driver is not found"));
1206     return;
1207   }
1208 
1209   sMajorVersion = wcstol(buf, nullptr, 10);
1210   sMinorVersion = 0;
1211   wchar_t* p = wcschr(buf, L'.');
1212   if (p) {
1213     sMinorVersion = wcstol(p + 1, nullptr, 10);
1214   }
1215   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1216           ("MouseScroll::Device::SynTP::Init(): "
1217            "found driver version = %d.%d",
1218            sMajorVersion, sMinorVersion));
1219 }
1220 
1221 /******************************************************************************
1222  *
1223  * Device::Elantech
1224  *
1225  ******************************************************************************/
1226 
1227 /* static */
Init()1228 void MouseScrollHandler::Device::Elantech::Init() {
1229   int32_t version = GetDriverMajorVersion();
1230   bool needsHack = Device::GetWorkaroundPref(
1231       "ui.elantech_gesture_hacks.enabled", version != 0);
1232   sUseSwipeHack = needsHack && version <= 7;
1233   sUsePinchHack = needsHack && version <= 8;
1234 
1235   MOZ_LOG(
1236       gMouseScrollLog, LogLevel::Info,
1237       ("MouseScroll::Device::Elantech::Init(): version=%d, sUseSwipeHack=%s, "
1238        "sUsePinchHack=%s",
1239        version, GetBoolName(sUseSwipeHack), GetBoolName(sUsePinchHack)));
1240 }
1241 
1242 /* static */
GetDriverMajorVersion()1243 int32_t MouseScrollHandler::Device::Elantech::GetDriverMajorVersion() {
1244   wchar_t buf[40];
1245   // The driver version is found in one of these two registry keys.
1246   bool foundKey = WinUtils::GetRegistryKey(HKEY_CURRENT_USER,
1247                                            L"Software\\Elantech\\MainOption",
1248                                            L"DriverVersion", buf, sizeof buf);
1249   if (!foundKey) {
1250     foundKey =
1251         WinUtils::GetRegistryKey(HKEY_CURRENT_USER, L"Software\\Elantech",
1252                                  L"DriverVersion", buf, sizeof buf);
1253   }
1254 
1255   if (!foundKey) {
1256     return 0;
1257   }
1258 
1259   // Assume that the major version number can be found just after a space
1260   // or at the start of the string.
1261   for (wchar_t* p = buf; *p; p++) {
1262     if (*p >= L'0' && *p <= L'9' && (p == buf || *(p - 1) == L' ')) {
1263       return wcstol(p, nullptr, 10);
1264     }
1265   }
1266 
1267   return 0;
1268 }
1269 
1270 /* static */
IsHelperWindow(HWND aWnd)1271 bool MouseScrollHandler::Device::Elantech::IsHelperWindow(HWND aWnd) {
1272   // The helper window cannot be distinguished based on its window class, so we
1273   // need to check if it is owned by the helper process, ETDCtrl.exe.
1274 
1275   const wchar_t* filenameSuffix = L"\\etdctrl.exe";
1276   const int filenameSuffixLength = 12;
1277 
1278   DWORD pid;
1279   ::GetWindowThreadProcessId(aWnd, &pid);
1280 
1281   HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1282   if (!hProcess) {
1283     return false;
1284   }
1285 
1286   bool result = false;
1287   wchar_t path[256] = {L'\0'};
1288   if (::GetProcessImageFileNameW(hProcess, path, ArrayLength(path))) {
1289     int pathLength = lstrlenW(path);
1290     if (pathLength >= filenameSuffixLength) {
1291       if (lstrcmpiW(path + pathLength - filenameSuffixLength, filenameSuffix) ==
1292           0) {
1293         result = true;
1294       }
1295     }
1296   }
1297   ::CloseHandle(hProcess);
1298 
1299   return result;
1300 }
1301 
1302 /* static */
HandleKeyMessage(nsWindowBase * aWidget,UINT aMsg,WPARAM aWParam,LPARAM aLParam)1303 bool MouseScrollHandler::Device::Elantech::HandleKeyMessage(
1304     nsWindowBase* aWidget, UINT aMsg, WPARAM aWParam, LPARAM aLParam) {
1305   // The Elantech touchpad driver understands three-finger swipe left and
1306   // right gestures, and translates them into Page Up and Page Down key
1307   // events for most applications.  For Firefox 3.6, it instead sends
1308   // Alt+Left and Alt+Right to trigger browser back/forward actions.  As
1309   // with the Thinkpad Driver hack in nsWindow::Create, the change in
1310   // HWND structure makes Firefox not trigger the driver's heuristics
1311   // any longer.
1312   //
1313   // The Elantech driver actually sends these messages for a three-finger
1314   // swipe right:
1315   //
1316   //   WM_KEYDOWN virtual_key = 0xCC or 0xFF ScanCode = 00
1317   //   WM_KEYDOWN virtual_key = VK_NEXT      ScanCode = 00
1318   //   WM_KEYUP   virtual_key = VK_NEXT      ScanCode = 00
1319   //   WM_KEYUP   virtual_key = 0xCC or 0xFF ScanCode = 00
1320   //
1321   // Whether 0xCC or 0xFF is sent is suspected to depend on the driver
1322   // version.  7.0.4.12_14Jul09_WHQL, 7.0.5.10, and 7.0.6.0 generate 0xCC.
1323   // 7.0.4.3 from Asus on EeePC generates 0xFF.
1324   //
1325   // On some hardware, IS_VK_DOWN(0xFF) returns true even when Elantech
1326   // messages are not involved, meaning that alone is not enough to
1327   // distinguish the gesture from a regular Page Up or Page Down key press.
1328   // The ScanCode is therefore also tested to detect the gesture.
1329   // We then pretend that we should dispatch "Go Forward" command.  Similarly
1330   // for VK_PRIOR and "Go Back" command.
1331   if (sUseSwipeHack && (aWParam == VK_NEXT || aWParam == VK_PRIOR) &&
1332       WinUtils::GetScanCode(aLParam) == 0 &&
1333       (IS_VK_DOWN(0xFF) || IS_VK_DOWN(0xCC))) {
1334     if (aMsg == WM_KEYDOWN) {
1335       MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1336               ("MouseScroll::Device::Elantech::HandleKeyMessage(): Dispatching "
1337                "%s command event",
1338                aWParam == VK_NEXT ? "Forward" : "Back"));
1339 
1340       WidgetCommandEvent appCommandEvent(
1341           true, (aWParam == VK_NEXT) ? nsGkAtoms::Forward : nsGkAtoms::Back,
1342           aWidget);
1343 
1344       // In this scenario, the coordinate of the event isn't supplied, so pass
1345       // nullptr as an argument to indicate using the coordinate from the last
1346       // available window message.
1347       InitEvent(aWidget, appCommandEvent, nullptr);
1348       aWidget->DispatchWindowEvent(&appCommandEvent);
1349     } else {
1350       MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1351               ("MouseScroll::Device::Elantech::HandleKeyMessage(): Consumed"));
1352     }
1353     return true;  // consume the message (doesn't need to dispatch key events)
1354   }
1355 
1356   // Version 8 of the Elantech touchpad driver sends these messages for
1357   // zoom gestures:
1358   //
1359   //   WM_KEYDOWN    virtual_key = 0xCC        time = 10
1360   //   WM_KEYDOWN    virtual_key = VK_CONTROL  time = 10
1361   //   WM_MOUSEWHEEL                           time = ::GetTickCount()
1362   //   WM_KEYUP      virtual_key = VK_CONTROL  time = 10
1363   //   WM_KEYUP      virtual_key = 0xCC        time = 10
1364   //
1365   // The result of this is that we process all of the WM_KEYDOWN/WM_KEYUP
1366   // messages first because their timestamps make them appear to have
1367   // been sent before the WM_MOUSEWHEEL message.  To work around this,
1368   // we store the current time when we process the WM_KEYUP message and
1369   // assume that any WM_MOUSEWHEEL message with a timestamp before that
1370   // time is one that should be processed as if the Control key was down.
1371   if (sUsePinchHack && aMsg == WM_KEYUP && aWParam == VK_CONTROL &&
1372       ::GetMessageTime() == 10) {
1373     // We look only at the bottom 31 bits of the system tick count since
1374     // GetMessageTime returns a LONG, which is signed, so we want values
1375     // that are more easily comparable.
1376     sZoomUntil = ::GetTickCount() & 0x7FFFFFFF;
1377 
1378     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1379             ("MouseScroll::Device::Elantech::HandleKeyMessage(): sZoomUntil=%d",
1380              sZoomUntil));
1381   }
1382 
1383   return false;
1384 }
1385 
1386 /* static */
UpdateZoomUntil()1387 void MouseScrollHandler::Device::Elantech::UpdateZoomUntil() {
1388   if (!sZoomUntil) {
1389     return;
1390   }
1391 
1392   // For the Elantech Touchpad Zoom Gesture Hack, we should check that the
1393   // system time (32-bit milliseconds) hasn't wrapped around.  Otherwise we
1394   // might get into the situation where wheel events for the next 50 days of
1395   // system uptime are assumed to be Ctrl+Wheel events.  (It is unlikely that
1396   // we would get into that state, because the system would already need to be
1397   // up for 50 days and the Control key message would need to be processed just
1398   // before the system time overflow and the wheel message just after.)
1399   //
1400   // We also take the chance to reset sZoomUntil if we simply have passed that
1401   // time.
1402   LONG msgTime = ::GetMessageTime();
1403   if ((sZoomUntil >= 0x3fffffffu && DWORD(msgTime) < 0x40000000u) ||
1404       (sZoomUntil < DWORD(msgTime))) {
1405     sZoomUntil = 0;
1406 
1407     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1408             ("MouseScroll::Device::Elantech::UpdateZoomUntil(): "
1409              "sZoomUntil was reset"));
1410   }
1411 }
1412 
1413 /* static */
IsZooming()1414 bool MouseScrollHandler::Device::Elantech::IsZooming() {
1415   // Assume the Control key is down if the Elantech touchpad has sent the
1416   // mis-ordered WM_KEYDOWN/WM_MOUSEWHEEL messages.  (See the comment in
1417   // OnKeyUp.)
1418   return (sZoomUntil && static_cast<DWORD>(::GetMessageTime()) < sZoomUntil);
1419 }
1420 
1421 /******************************************************************************
1422  *
1423  * Device::Apoint
1424  *
1425  ******************************************************************************/
1426 
1427 /* static */
Init()1428 void MouseScrollHandler::Device::Apoint::Init() {
1429   if (sInitialized) {
1430     return;
1431   }
1432 
1433   sInitialized = true;
1434   sMajorVersion = 0;
1435   sMinorVersion = -1;
1436 
1437   wchar_t buf[40];
1438   bool foundKey =
1439       WinUtils::GetRegistryKey(HKEY_LOCAL_MACHINE, L"Software\\Alps\\Apoint",
1440                                L"ProductVer", buf, sizeof buf);
1441   if (!foundKey) {
1442     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1443             ("MouseScroll::Device::Apoint::Init(): "
1444              "Apoint driver is not found"));
1445     return;
1446   }
1447 
1448   sMajorVersion = wcstol(buf, nullptr, 10);
1449   sMinorVersion = 0;
1450   wchar_t* p = wcschr(buf, L'.');
1451   if (p) {
1452     sMinorVersion = wcstol(p + 1, nullptr, 10);
1453   }
1454   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1455           ("MouseScroll::Device::Apoint::Init(): "
1456            "found driver version = %d.%d",
1457            sMajorVersion, sMinorVersion));
1458 }
1459 
1460 /******************************************************************************
1461  *
1462  * Device::TrackPoint
1463  *
1464  ******************************************************************************/
1465 
1466 /* static */
IsDriverInstalled()1467 bool MouseScrollHandler::Device::TrackPoint::IsDriverInstalled() {
1468   if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1469                                L"Software\\Lenovo\\TrackPoint")) {
1470     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1471             ("MouseScroll::Device::TrackPoint::IsDriverInstalled(): "
1472              "Lenovo's TrackPoint driver is found"));
1473     return true;
1474   }
1475 
1476   if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1477                                L"Software\\Alps\\Apoint\\TrackPoint")) {
1478     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1479             ("MouseScroll::Device::TrackPoint::IsDriverInstalled(): "
1480              "Alps's TrackPoint driver is found"));
1481   }
1482 
1483   return false;
1484 }
1485 
1486 /******************************************************************************
1487  *
1488  * Device::UltraNav
1489  *
1490  ******************************************************************************/
1491 
1492 /* static */
IsObsoleteDriverInstalled()1493 bool MouseScrollHandler::Device::UltraNav::IsObsoleteDriverInstalled() {
1494   if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1495                                L"Software\\Lenovo\\UltraNav")) {
1496     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1497             ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1498              "Lenovo's UltraNav driver is found"));
1499     return true;
1500   }
1501 
1502   bool installed = false;
1503   if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1504                                L"Software\\Synaptics\\SynTPEnh\\UltraNavUSB")) {
1505     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1506             ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1507              "Synaptics's UltraNav (USB) driver is found"));
1508     installed = true;
1509   } else if (WinUtils::HasRegistryKey(
1510                  HKEY_CURRENT_USER,
1511                  L"Software\\Synaptics\\SynTPEnh\\UltraNavPS2")) {
1512     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1513             ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1514              "Synaptics's UltraNav (PS/2) driver is found"));
1515     installed = true;
1516   }
1517 
1518   if (!installed) {
1519     return false;
1520   }
1521 
1522   int32_t majorVersion = Device::SynTP::GetDriverMajorVersion();
1523   if (!majorVersion) {
1524     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1525             ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1526              "Failed to get UltraNav driver version"));
1527     return false;
1528   }
1529   int32_t minorVersion = Device::SynTP::GetDriverMinorVersion();
1530   return majorVersion < 15 || (majorVersion == 15 && minorVersion == 0);
1531 }
1532 
1533 /******************************************************************************
1534  *
1535  * Device::SetPoint
1536  *
1537  ******************************************************************************/
1538 
1539 /* static */
IsGetMessagePosResponseValid(UINT aMessage,WPARAM aWParam,LPARAM aLParam)1540 bool MouseScrollHandler::Device::SetPoint::IsGetMessagePosResponseValid(
1541     UINT aMessage, WPARAM aWParam, LPARAM aLParam) {
1542   if (aMessage != WM_MOUSEHWHEEL) {
1543     return false;
1544   }
1545 
1546   POINTS pts = MouseScrollHandler::GetCurrentMessagePos();
1547   LPARAM messagePos = MAKELPARAM(pts.x, pts.y);
1548 
1549   // XXX We should check whether SetPoint is installed or not by registry.
1550 
1551   // SetPoint, Logitech (Logicool) mouse driver, (confirmed with 4.82.11 and
1552   // MX-1100) always sets 0 to the lParam of WM_MOUSEHWHEEL.  The driver SENDs
1553   // one message at first time, this time, ::GetMessagePos() works fine.
1554   // Then, we will return 0 (0 means we process it) to the message. Then, the
1555   // driver will POST the same messages continuously during the wheel tilted.
1556   // But ::GetMessagePos() API always returns (0, 0) for them, even if the
1557   // actual mouse cursor isn't 0,0.  Therefore, we cannot trust the result of
1558   // ::GetMessagePos API if the sender is SetPoint.
1559   if (!sMightBeUsing && !aLParam && aLParam != messagePos &&
1560       ::InSendMessage()) {
1561     sMightBeUsing = true;
1562     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1563             ("MouseScroll::Device::SetPoint::IsGetMessagePosResponseValid(): "
1564              "Might using SetPoint"));
1565   } else if (sMightBeUsing && aLParam != 0 && ::InSendMessage()) {
1566     // The user has changed the mouse from Logitech's to another one (e.g.,
1567     // the user has changed to the touchpad of the notebook.
1568     sMightBeUsing = false;
1569     MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1570             ("MouseScroll::Device::SetPoint::IsGetMessagePosResponseValid(): "
1571              "Might stop using SetPoint"));
1572   }
1573   return (sMightBeUsing && !aLParam && !messagePos);
1574 }
1575 
1576 /******************************************************************************
1577  *
1578  * SynthesizingEvent
1579  *
1580  ******************************************************************************/
1581 
1582 /* static */
IsSynthesizing()1583 bool MouseScrollHandler::SynthesizingEvent::IsSynthesizing() {
1584   return MouseScrollHandler::sInstance &&
1585          MouseScrollHandler::sInstance->mSynthesizingEvent &&
1586          MouseScrollHandler::sInstance->mSynthesizingEvent->mStatus !=
1587              NOT_SYNTHESIZING;
1588 }
1589 
Synthesize(const POINTS & aCursorPoint,HWND aWnd,UINT aMessage,WPARAM aWParam,LPARAM aLParam,const BYTE (& aKeyStates)[256])1590 nsresult MouseScrollHandler::SynthesizingEvent::Synthesize(
1591     const POINTS& aCursorPoint, HWND aWnd, UINT aMessage, WPARAM aWParam,
1592     LPARAM aLParam, const BYTE (&aKeyStates)[256]) {
1593   MOZ_LOG(
1594       gMouseScrollLog, LogLevel::Info,
1595       ("MouseScrollHandler::SynthesizingEvent::Synthesize(): aCursorPoint: { "
1596        "x: %d, y: %d }, aWnd=0x%X, aMessage=0x%04X, aWParam=0x%08X, "
1597        "aLParam=0x%08X, IsSynthesized()=%s, mStatus=%s",
1598        aCursorPoint.x, aCursorPoint.y, aWnd, aMessage, aWParam, aLParam,
1599        GetBoolName(IsSynthesizing()), GetStatusName()));
1600 
1601   if (IsSynthesizing()) {
1602     return NS_ERROR_NOT_AVAILABLE;
1603   }
1604 
1605   ::GetKeyboardState(mOriginalKeyState);
1606 
1607   // Note that we cannot use ::SetCursorPos() because it works asynchronously.
1608   // We should SEND the message for reducing the possibility of receiving
1609   // unexpected message which were not sent from here.
1610   mCursorPoint = aCursorPoint;
1611 
1612   mWnd = aWnd;
1613   mMessage = aMessage;
1614   mWParam = aWParam;
1615   mLParam = aLParam;
1616 
1617   memcpy(mKeyState, aKeyStates, sizeof(mKeyState));
1618   ::SetKeyboardState(mKeyState);
1619 
1620   mStatus = SENDING_MESSAGE;
1621 
1622   // Don't assume that aWnd is always managed by nsWindow.  It might be
1623   // a plugin window.
1624   ::SendMessage(aWnd, aMessage, aWParam, aLParam);
1625 
1626   return NS_OK;
1627 }
1628 
NativeMessageReceived(nsWindowBase * aWidget,UINT aMessage,WPARAM aWParam,LPARAM aLParam)1629 void MouseScrollHandler::SynthesizingEvent::NativeMessageReceived(
1630     nsWindowBase* aWidget, UINT aMessage, WPARAM aWParam, LPARAM aLParam) {
1631   if (mStatus == SENDING_MESSAGE && mMessage == aMessage &&
1632       mWParam == aWParam && mLParam == aLParam) {
1633     mStatus = NATIVE_MESSAGE_RECEIVED;
1634     if (aWidget && aWidget->GetWindowHandle() == mWnd) {
1635       return;
1636     }
1637     // If the target window is not ours and received window is our plugin
1638     // window, it comes from child window of the plugin.
1639     if (aWidget && aWidget->IsPlugin() && !WinUtils::GetNSWindowBasePtr(mWnd)) {
1640       return;
1641     }
1642     // Otherwise, the message may not be sent by us.
1643   }
1644 
1645   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1646           ("MouseScrollHandler::SynthesizingEvent::NativeMessageReceived(): "
1647            "aWidget=%p, aWidget->GetWindowHandle()=0x%X, mWnd=0x%X, "
1648            "aMessage=0x%04X, aWParam=0x%08X, aLParam=0x%08X, mStatus=%s",
1649            aWidget, aWidget ? aWidget->GetWindowHandle() : 0, mWnd, aMessage,
1650            aWParam, aLParam, GetStatusName()));
1651 
1652   // We failed to receive our sent message, we failed to do the job.
1653   Finish();
1654 
1655   return;
1656 }
1657 
1658 void MouseScrollHandler::SynthesizingEvent::
NotifyNativeMessageHandlingFinished()1659     NotifyNativeMessageHandlingFinished() {
1660   if (!IsSynthesizing()) {
1661     return;
1662   }
1663 
1664   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1665           ("MouseScrollHandler::SynthesizingEvent::"
1666            "NotifyNativeMessageHandlingFinished(): IsWaitingInternalMessage=%s",
1667            GetBoolName(MouseScrollHandler::IsWaitingInternalMessage())));
1668 
1669   if (MouseScrollHandler::IsWaitingInternalMessage()) {
1670     mStatus = INTERNAL_MESSAGE_POSTED;
1671     return;
1672   }
1673 
1674   // If the native message handler didn't post our internal message,
1675   // we our job is finished.
1676   // TODO: When we post the message to plugin window, there is remaning job.
1677   Finish();
1678 }
1679 
1680 void MouseScrollHandler::SynthesizingEvent::
NotifyInternalMessageHandlingFinished()1681     NotifyInternalMessageHandlingFinished() {
1682   if (!IsSynthesizing()) {
1683     return;
1684   }
1685 
1686   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1687           ("MouseScrollHandler::SynthesizingEvent::"
1688            "NotifyInternalMessageHandlingFinished()"));
1689 
1690   Finish();
1691 }
1692 
Finish()1693 void MouseScrollHandler::SynthesizingEvent::Finish() {
1694   if (!IsSynthesizing()) {
1695     return;
1696   }
1697 
1698   MOZ_LOG(gMouseScrollLog, LogLevel::Info,
1699           ("MouseScrollHandler::SynthesizingEvent::Finish()"));
1700 
1701   // Restore the original key state.
1702   ::SetKeyboardState(mOriginalKeyState);
1703 
1704   mStatus = NOT_SYNTHESIZING;
1705 }
1706 
1707 }  // namespace widget
1708 }  // namespace mozilla
1709