Thu, 22 Jan 2015 13:21:57 +0100
Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6
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 #ifdef MOZ_LOGGING
10 #define FORCE_PR_LOG /* Allow logging in the release build */
11 #endif // MOZ_LOGGING
12 #include "prlog.h"
14 #include "WinMouseScrollHandler.h"
15 #include "nsWindow.h"
16 #include "nsWindowDefs.h"
17 #include "KeyboardLayout.h"
18 #include "WinUtils.h"
19 #include "nsGkAtoms.h"
20 #include "nsIDOMWindowUtils.h"
21 #include "nsIDOMWheelEvent.h"
23 #include "mozilla/MiscEvents.h"
24 #include "mozilla/MouseEvents.h"
25 #include "mozilla/Preferences.h"
26 #include "mozilla/WindowsVersion.h"
28 #include <psapi.h>
30 namespace mozilla {
31 namespace widget {
33 #ifdef PR_LOGGING
34 PRLogModuleInfo* gMouseScrollLog = nullptr;
36 static const char* GetBoolName(bool aBool)
37 {
38 return aBool ? "TRUE" : "FALSE";
39 }
41 static void LogKeyStateImpl()
42 {
43 if (!PR_LOG_TEST(gMouseScrollLog, PR_LOG_DEBUG)) {
44 return;
45 }
46 BYTE keyboardState[256];
47 if (::GetKeyboardState(keyboardState)) {
48 for (size_t i = 0; i < ArrayLength(keyboardState); i++) {
49 if (keyboardState[i]) {
50 PR_LOG(gMouseScrollLog, PR_LOG_DEBUG,
51 (" Current key state: keyboardState[0x%02X]=0x%02X (%s)",
52 i, keyboardState[i],
53 ((keyboardState[i] & 0x81) == 0x81) ? "Pressed and Toggled" :
54 (keyboardState[i] & 0x80) ? "Pressed" :
55 (keyboardState[i] & 0x01) ? "Toggled" : "Unknown"));
56 }
57 }
58 } else {
59 PR_LOG(gMouseScrollLog, PR_LOG_DEBUG,
60 ("MouseScroll::Device::Elantech::HandleKeyMessage(): Failed to print "
61 "current keyboard state"));
62 }
63 }
65 #define LOG_KEYSTATE() LogKeyStateImpl()
66 #else // PR_LOGGING
67 #define LOG_KEYSTATE()
68 #endif
70 MouseScrollHandler* MouseScrollHandler::sInstance = nullptr;
72 bool MouseScrollHandler::Device::sFakeScrollableWindowNeeded = false;
74 bool MouseScrollHandler::Device::Elantech::sUseSwipeHack = false;
75 bool MouseScrollHandler::Device::Elantech::sUsePinchHack = false;
76 DWORD MouseScrollHandler::Device::Elantech::sZoomUntil = 0;
78 bool MouseScrollHandler::Device::SetPoint::sMightBeUsing = false;
80 // The duration until timeout of events transaction. The value is 1.5 sec,
81 // it's just a magic number, it was suggested by Logitech's engineer, see
82 // bug 605648 comment 90.
83 #define DEFAULT_TIMEOUT_DURATION 1500
85 /******************************************************************************
86 *
87 * MouseScrollHandler
88 *
89 ******************************************************************************/
91 /* static */
92 POINTS
93 MouseScrollHandler::GetCurrentMessagePos()
94 {
95 if (SynthesizingEvent::IsSynthesizing()) {
96 return sInstance->mSynthesizingEvent->GetCursorPoint();
97 }
98 DWORD pos = ::GetMessagePos();
99 return MAKEPOINTS(pos);
100 }
102 // Get rid of the GetMessagePos() API.
103 #define GetMessagePos()
105 /* static */
106 void
107 MouseScrollHandler::Initialize()
108 {
109 #ifdef PR_LOGGING
110 if (!gMouseScrollLog) {
111 gMouseScrollLog = PR_NewLogModule("MouseScrollHandlerWidgets");
112 }
113 #endif
114 Device::Init();
115 }
117 /* static */
118 void
119 MouseScrollHandler::Shutdown()
120 {
121 delete sInstance;
122 sInstance = nullptr;
123 }
125 /* static */
126 MouseScrollHandler*
127 MouseScrollHandler::GetInstance()
128 {
129 if (!sInstance) {
130 sInstance = new MouseScrollHandler();
131 }
132 return sInstance;
133 }
135 MouseScrollHandler::MouseScrollHandler() :
136 mIsWaitingInternalMessage(false),
137 mSynthesizingEvent(nullptr)
138 {
139 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
140 ("MouseScroll: Creating an instance, this=%p, sInstance=%p",
141 this, sInstance));
142 }
144 MouseScrollHandler::~MouseScrollHandler()
145 {
146 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
147 ("MouseScroll: Destroying an instance, this=%p, sInstance=%p",
148 this, sInstance));
150 delete mSynthesizingEvent;
151 }
153 /* static */
154 bool
155 MouseScrollHandler::NeedsMessage(UINT aMsg)
156 {
157 switch (aMsg) {
158 case WM_SETTINGCHANGE:
159 case WM_MOUSEWHEEL:
160 case WM_MOUSEHWHEEL:
161 case WM_HSCROLL:
162 case WM_VSCROLL:
163 case MOZ_WM_MOUSEVWHEEL:
164 case MOZ_WM_MOUSEHWHEEL:
165 case MOZ_WM_HSCROLL:
166 case MOZ_WM_VSCROLL:
167 case WM_KEYDOWN:
168 case WM_KEYUP:
169 return true;
170 }
171 return false;
172 }
174 /* static */
175 bool
176 MouseScrollHandler::ProcessMessage(nsWindowBase* aWidget, UINT msg,
177 WPARAM wParam, LPARAM lParam,
178 MSGResult& aResult)
179 {
180 Device::Elantech::UpdateZoomUntil();
182 switch (msg) {
183 case WM_SETTINGCHANGE:
184 if (!sInstance) {
185 return false;
186 }
187 if (wParam == SPI_SETWHEELSCROLLLINES ||
188 wParam == SPI_SETWHEELSCROLLCHARS) {
189 sInstance->mSystemSettings.MarkDirty();
190 }
191 return false;
193 case WM_MOUSEWHEEL:
194 case WM_MOUSEHWHEEL:
195 GetInstance()->
196 ProcessNativeMouseWheelMessage(aWidget, msg, wParam, lParam);
197 sInstance->mSynthesizingEvent->NotifyNativeMessageHandlingFinished();
198 // We don't need to call next wndproc for WM_MOUSEWHEEL and
199 // WM_MOUSEHWHEEL. We should consume them always. If the messages
200 // would be handled by our window again, it caused making infinite
201 // message loop.
202 aResult.mConsumed = true;
203 aResult.mResult = (msg != WM_MOUSEHWHEEL);
204 return true;
206 case WM_HSCROLL:
207 case WM_VSCROLL:
208 aResult.mConsumed =
209 GetInstance()->ProcessNativeScrollMessage(aWidget, msg, wParam, lParam);
210 sInstance->mSynthesizingEvent->NotifyNativeMessageHandlingFinished();
211 aResult.mResult = 0;
212 return true;
214 case MOZ_WM_MOUSEVWHEEL:
215 case MOZ_WM_MOUSEHWHEEL:
216 GetInstance()->HandleMouseWheelMessage(aWidget, msg, wParam, lParam);
217 sInstance->mSynthesizingEvent->NotifyInternalMessageHandlingFinished();
218 // Doesn't need to call next wndproc for internal wheel message.
219 aResult.mConsumed = true;
220 return true;
222 case MOZ_WM_HSCROLL:
223 case MOZ_WM_VSCROLL:
224 GetInstance()->
225 HandleScrollMessageAsMouseWheelMessage(aWidget, msg, wParam, lParam);
226 sInstance->mSynthesizingEvent->NotifyInternalMessageHandlingFinished();
227 // Doesn't need to call next wndproc for internal scroll message.
228 aResult.mConsumed = true;
229 return true;
231 case WM_KEYDOWN:
232 case WM_KEYUP:
233 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
234 ("MouseScroll::ProcessMessage(): aWidget=%p, "
235 "msg=%s(0x%04X), wParam=0x%02X, ::GetMessageTime()=%d",
236 aWidget, msg == WM_KEYDOWN ? "WM_KEYDOWN" :
237 msg == WM_KEYUP ? "WM_KEYUP" : "Unknown", msg, wParam,
238 ::GetMessageTime()));
239 LOG_KEYSTATE();
240 if (Device::Elantech::HandleKeyMessage(aWidget, msg, wParam)) {
241 aResult.mResult = 0;
242 aResult.mConsumed = true;
243 return true;
244 }
245 return false;
247 default:
248 return false;
249 }
250 }
252 /* static */
253 nsresult
254 MouseScrollHandler::SynthesizeNativeMouseScrollEvent(nsWindowBase* aWidget,
255 const nsIntPoint& aPoint,
256 uint32_t aNativeMessage,
257 int32_t aDelta,
258 uint32_t aModifierFlags,
259 uint32_t aAdditionalFlags)
260 {
261 bool useFocusedWindow =
262 !(aAdditionalFlags & nsIDOMWindowUtils::MOUSESCROLL_PREFER_WIDGET_AT_POINT);
264 POINT pt;
265 pt.x = aPoint.x;
266 pt.y = aPoint.y;
268 HWND target = useFocusedWindow ? ::WindowFromPoint(pt) : ::GetFocus();
269 NS_ENSURE_TRUE(target, NS_ERROR_FAILURE);
271 WPARAM wParam = 0;
272 LPARAM lParam = 0;
273 switch (aNativeMessage) {
274 case WM_MOUSEWHEEL:
275 case WM_MOUSEHWHEEL: {
276 lParam = MAKELPARAM(pt.x, pt.y);
277 WORD mod = 0;
278 if (aModifierFlags & (nsIWidget::CTRL_L | nsIWidget::CTRL_R)) {
279 mod |= MK_CONTROL;
280 }
281 if (aModifierFlags & (nsIWidget::SHIFT_L | nsIWidget::SHIFT_R)) {
282 mod |= MK_SHIFT;
283 }
284 wParam = MAKEWPARAM(mod, aDelta);
285 break;
286 }
287 case WM_VSCROLL:
288 case WM_HSCROLL:
289 lParam = (aAdditionalFlags &
290 nsIDOMWindowUtils::MOUSESCROLL_WIN_SCROLL_LPARAM_NOT_NULL) ?
291 reinterpret_cast<LPARAM>(target) : 0;
292 wParam = aDelta;
293 break;
294 default:
295 return NS_ERROR_INVALID_ARG;
296 }
298 // Ensure to make the instance.
299 GetInstance();
301 BYTE kbdState[256];
302 memset(kbdState, 0, sizeof(kbdState));
304 nsAutoTArray<KeyPair,10> keySequence;
305 WinUtils::SetupKeyModifiersSequence(&keySequence, aModifierFlags);
307 for (uint32_t i = 0; i < keySequence.Length(); ++i) {
308 uint8_t key = keySequence[i].mGeneral;
309 uint8_t keySpecific = keySequence[i].mSpecific;
310 kbdState[key] = 0x81; // key is down and toggled on if appropriate
311 if (keySpecific) {
312 kbdState[keySpecific] = 0x81;
313 }
314 }
316 if (!sInstance->mSynthesizingEvent) {
317 sInstance->mSynthesizingEvent = new SynthesizingEvent();
318 }
320 POINTS pts;
321 pts.x = static_cast<SHORT>(pt.x);
322 pts.y = static_cast<SHORT>(pt.y);
323 return sInstance->mSynthesizingEvent->
324 Synthesize(pts, target, aNativeMessage, wParam, lParam, kbdState);
325 }
327 /* static */
328 bool
329 MouseScrollHandler::DispatchEvent(nsWindowBase* aWidget,
330 WidgetGUIEvent& aEvent)
331 {
332 // note, in metrofx, this will always return false for now
333 return aWidget->DispatchScrollEvent(&aEvent);
334 }
336 /* static */
337 void
338 MouseScrollHandler::InitEvent(nsWindowBase* aWidget,
339 WidgetGUIEvent& aEvent,
340 nsIntPoint* aPoint)
341 {
342 NS_ENSURE_TRUE_VOID(aWidget);
343 nsIntPoint point;
344 if (aPoint) {
345 point = *aPoint;
346 } else {
347 POINTS pts = GetCurrentMessagePos();
348 POINT pt;
349 pt.x = pts.x;
350 pt.y = pts.y;
351 ::ScreenToClient(aWidget->GetWindowHandle(), &pt);
352 point.x = pt.x;
353 point.y = pt.y;
354 }
355 aWidget->InitEvent(aEvent, &point);
356 }
358 /* static */
359 ModifierKeyState
360 MouseScrollHandler::GetModifierKeyState(UINT aMessage)
361 {
362 ModifierKeyState result;
363 // Assume the Control key is down if the Elantech touchpad has sent the
364 // mis-ordered WM_KEYDOWN/WM_MOUSEWHEEL messages. (See the comment in
365 // MouseScrollHandler::Device::Elantech::HandleKeyMessage().)
366 if ((aMessage == MOZ_WM_MOUSEVWHEEL || aMessage == WM_MOUSEWHEEL) &&
367 !result.IsControl() && Device::Elantech::IsZooming()) {
368 result.Set(MODIFIER_CONTROL);
369 }
370 return result;
371 }
373 POINT
374 MouseScrollHandler::ComputeMessagePos(UINT aMessage,
375 WPARAM aWParam,
376 LPARAM aLParam)
377 {
378 POINT point;
379 if (Device::SetPoint::IsGetMessagePosResponseValid(aMessage,
380 aWParam, aLParam)) {
381 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
382 ("MouseScroll::ComputeMessagePos: Using ::GetCursorPos()"));
383 ::GetCursorPos(&point);
384 } else {
385 POINTS pts = GetCurrentMessagePos();
386 point.x = pts.x;
387 point.y = pts.y;
388 }
389 return point;
390 }
392 void
393 MouseScrollHandler::ProcessNativeMouseWheelMessage(nsWindowBase* aWidget,
394 UINT aMessage,
395 WPARAM aWParam,
396 LPARAM aLParam)
397 {
398 if (SynthesizingEvent::IsSynthesizing()) {
399 mSynthesizingEvent->NativeMessageReceived(aWidget, aMessage,
400 aWParam, aLParam);
401 }
403 POINT point = ComputeMessagePos(aMessage, aWParam, aLParam);
405 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
406 ("MouseScroll::ProcessNativeMouseWheelMessage: aWidget=%p, "
407 "aMessage=%s, wParam=0x%08X, lParam=0x%08X, point: { x=%d, y=%d }",
408 aWidget, aMessage == WM_MOUSEWHEEL ? "WM_MOUSEWHEEL" :
409 aMessage == WM_MOUSEHWHEEL ? "WM_MOUSEHWHEEL" :
410 aMessage == WM_VSCROLL ? "WM_VSCROLL" : "WM_HSCROLL",
411 aWParam, aLParam, point.x, point.y));
412 LOG_KEYSTATE();
414 HWND underCursorWnd = ::WindowFromPoint(point);
415 if (!underCursorWnd) {
416 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
417 ("MouseScroll::ProcessNativeMouseWheelMessage: "
418 "No window is not found under the cursor"));
419 return;
420 }
422 if (Device::Elantech::IsPinchHackNeeded() &&
423 Device::Elantech::IsHelperWindow(underCursorWnd)) {
424 // The Elantech driver places a window right underneath the cursor
425 // when sending a WM_MOUSEWHEEL event to us as part of a pinch-to-zoom
426 // gesture. We detect that here, and search for our window that would
427 // be beneath the cursor if that window wasn't there.
428 underCursorWnd = WinUtils::FindOurWindowAtPoint(point);
429 if (!underCursorWnd) {
430 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
431 ("MouseScroll::ProcessNativeMouseWheelMessage: "
432 "Our window is not found under the Elantech helper window"));
433 return;
434 }
435 }
437 // Handle most cases first. If the window under mouse cursor is our window
438 // except plugin window (MozillaWindowClass), we should handle the message
439 // on the window.
440 if (WinUtils::IsOurProcessWindow(underCursorWnd)) {
441 nsWindowBase* destWindow = WinUtils::GetNSWindowBasePtr(underCursorWnd);
442 if (!destWindow) {
443 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
444 ("MouseScroll::ProcessNativeMouseWheelMessage: "
445 "Found window under the cursor isn't managed by nsWindow..."));
446 HWND wnd = ::GetParent(underCursorWnd);
447 for (; wnd; wnd = ::GetParent(wnd)) {
448 destWindow = WinUtils::GetNSWindowBasePtr(wnd);
449 if (destWindow) {
450 break;
451 }
452 }
453 if (!wnd) {
454 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
455 ("MouseScroll::ProcessNativeMouseWheelMessage: Our window which is "
456 "managed by nsWindow is not found under the cursor"));
457 return;
458 }
459 }
461 MOZ_ASSERT(destWindow, "destWindow must not be NULL");
463 // If the found window is our plugin window, it means that the message
464 // has been handled by the plugin but not consumed. We should handle the
465 // message on its parent window. However, note that the DOM event may
466 // cause accessing the plugin. Therefore, we should unlock the plugin
467 // process by using PostMessage().
468 if (destWindow->WindowType() == eWindowType_plugin) {
469 destWindow = destWindow->GetParentWindowBase(false);
470 if (!destWindow) {
471 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
472 ("MouseScroll::ProcessNativeMouseWheelMessage: "
473 "Our window which is a parent of a plugin window is not found"));
474 return;
475 }
476 }
477 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
478 ("MouseScroll::ProcessNativeMouseWheelMessage: Succeeded, "
479 "Posting internal message to an nsWindow (%p)...",
480 destWindow));
481 mIsWaitingInternalMessage = true;
482 UINT internalMessage = WinUtils::GetInternalMessage(aMessage);
483 ::PostMessage(destWindow->GetWindowHandle(), internalMessage,
484 aWParam, aLParam);
485 return;
486 }
488 // If the window under cursor is not in our process, it means:
489 // 1. The window may be a plugin window (GeckoPluginWindow or its descendant).
490 // 2. The window may be another application's window.
491 HWND pluginWnd = WinUtils::FindOurProcessWindow(underCursorWnd);
492 if (!pluginWnd) {
493 // If there is no plugin window in ancestors of the window under cursor,
494 // the window is for another applications (case 2).
495 // We don't need to handle this message.
496 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
497 ("MouseScroll::ProcessNativeMouseWheelMessage: "
498 "Our window is not found under the cursor"));
499 return;
500 }
502 // If we're a plugin window (MozillaWindowClass) and cursor in this window,
503 // the message shouldn't go to plugin's wndproc again. So, we should handle
504 // it on parent window. However, note that the DOM event may cause accessing
505 // the plugin. Therefore, we should unlock the plugin process by using
506 // PostMessage().
507 if (aWidget->WindowType() == eWindowType_plugin &&
508 aWidget->GetWindowHandle() == pluginWnd) {
509 nsWindowBase* destWindow = aWidget->GetParentWindowBase(false);
510 if (!destWindow) {
511 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
512 ("MouseScroll::ProcessNativeMouseWheelMessage: Our normal window which "
513 "is a parent of this plugin window is not found"));
514 return;
515 }
516 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
517 ("MouseScroll::ProcessNativeMouseWheelMessage: Succeeded, "
518 "Posting internal message to an nsWindow (%p) which is parent of this "
519 "plugin window...",
520 destWindow));
521 mIsWaitingInternalMessage = true;
522 UINT internalMessage = WinUtils::GetInternalMessage(aMessage);
523 ::PostMessage(destWindow->GetWindowHandle(), internalMessage,
524 aWParam, aLParam);
525 return;
526 }
528 // If the window is a part of plugin, we should post the message to it.
529 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
530 ("MouseScroll::ProcessNativeMouseWheelMessage: Succeeded, "
531 "Redirecting the message to a window which is a plugin child window"));
532 ::PostMessage(underCursorWnd, aMessage, aWParam, aLParam);
533 }
535 bool
536 MouseScrollHandler::ProcessNativeScrollMessage(nsWindowBase* aWidget,
537 UINT aMessage,
538 WPARAM aWParam,
539 LPARAM aLParam)
540 {
541 if (aLParam || mUserPrefs.IsScrollMessageHandledAsWheelMessage()) {
542 // Scroll message generated by Thinkpad Trackpoint Driver or similar
543 // Treat as a mousewheel message and scroll appropriately
544 ProcessNativeMouseWheelMessage(aWidget, aMessage, aWParam, aLParam);
545 // Always consume the scroll message if we try to emulate mouse wheel
546 // action.
547 return true;
548 }
550 if (SynthesizingEvent::IsSynthesizing()) {
551 mSynthesizingEvent->NativeMessageReceived(aWidget, aMessage,
552 aWParam, aLParam);
553 }
555 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
556 ("MouseScroll::ProcessNativeScrollMessage: aWidget=%p, "
557 "aMessage=%s, wParam=0x%08X, lParam=0x%08X",
558 aWidget, aMessage == WM_VSCROLL ? "WM_VSCROLL" : "WM_HSCROLL",
559 aWParam, aLParam));
561 // Scroll message generated by external application
562 WidgetContentCommandEvent commandEvent(true, NS_CONTENT_COMMAND_SCROLL,
563 aWidget);
565 commandEvent.mScroll.mIsHorizontal = (aMessage == WM_HSCROLL);
567 switch (LOWORD(aWParam)) {
568 case SB_LINEUP: // SB_LINELEFT
569 commandEvent.mScroll.mUnit =
570 WidgetContentCommandEvent::eCmdScrollUnit_Line;
571 commandEvent.mScroll.mAmount = -1;
572 break;
573 case SB_LINEDOWN: // SB_LINERIGHT
574 commandEvent.mScroll.mUnit =
575 WidgetContentCommandEvent::eCmdScrollUnit_Line;
576 commandEvent.mScroll.mAmount = 1;
577 break;
578 case SB_PAGEUP: // SB_PAGELEFT
579 commandEvent.mScroll.mUnit =
580 WidgetContentCommandEvent::eCmdScrollUnit_Page;
581 commandEvent.mScroll.mAmount = -1;
582 break;
583 case SB_PAGEDOWN: // SB_PAGERIGHT
584 commandEvent.mScroll.mUnit =
585 WidgetContentCommandEvent::eCmdScrollUnit_Page;
586 commandEvent.mScroll.mAmount = 1;
587 break;
588 case SB_TOP: // SB_LEFT
589 commandEvent.mScroll.mUnit =
590 WidgetContentCommandEvent::eCmdScrollUnit_Whole;
591 commandEvent.mScroll.mAmount = -1;
592 break;
593 case SB_BOTTOM: // SB_RIGHT
594 commandEvent.mScroll.mUnit =
595 WidgetContentCommandEvent::eCmdScrollUnit_Whole;
596 commandEvent.mScroll.mAmount = 1;
597 break;
598 default:
599 return false;
600 }
601 // XXX If this is a plugin window, we should dispatch the event from
602 // parent window.
603 DispatchEvent(aWidget, commandEvent);
604 return true;
605 }
607 void
608 MouseScrollHandler::HandleMouseWheelMessage(nsWindowBase* aWidget,
609 UINT aMessage,
610 WPARAM aWParam,
611 LPARAM aLParam)
612 {
613 NS_ABORT_IF_FALSE(
614 (aMessage == MOZ_WM_MOUSEVWHEEL || aMessage == MOZ_WM_MOUSEHWHEEL),
615 "HandleMouseWheelMessage must be called with "
616 "MOZ_WM_MOUSEVWHEEL or MOZ_WM_MOUSEHWHEEL");
618 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
619 ("MouseScroll::HandleMouseWheelMessage: aWidget=%p, "
620 "aMessage=MOZ_WM_MOUSE%sWHEEL, aWParam=0x%08X, aLParam=0x%08X",
621 aWidget, aMessage == MOZ_WM_MOUSEVWHEEL ? "V" : "H",
622 aWParam, aLParam));
624 mIsWaitingInternalMessage = false;
626 EventInfo eventInfo(aWidget, WinUtils::GetNativeMessage(aMessage),
627 aWParam, aLParam);
628 if (!eventInfo.CanDispatchWheelEvent()) {
629 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
630 ("MouseScroll::HandleMouseWheelMessage: Cannot dispatch the events"));
631 mLastEventInfo.ResetTransaction();
632 return;
633 }
635 // Discard the remaining delta if current wheel message and last one are
636 // received by different window or to scroll different direction or
637 // different unit scroll. Furthermore, if the last event was too old.
638 if (!mLastEventInfo.CanContinueTransaction(eventInfo)) {
639 mLastEventInfo.ResetTransaction();
640 }
642 mLastEventInfo.RecordEvent(eventInfo);
644 ModifierKeyState modKeyState = GetModifierKeyState(aMessage);
646 // Grab the widget, it might be destroyed by a DOM event handler.
647 nsRefPtr<nsWindowBase> kungFuDethGrip(aWidget);
649 WidgetWheelEvent wheelEvent(true, NS_WHEEL_WHEEL, aWidget);
650 if (mLastEventInfo.InitWheelEvent(aWidget, wheelEvent, modKeyState)) {
651 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
652 ("MouseScroll::HandleMouseWheelMessage: dispatching "
653 "NS_WHEEL_WHEEL event"));
654 DispatchEvent(aWidget, wheelEvent);
655 if (aWidget->Destroyed()) {
656 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
657 ("MouseScroll::HandleMouseWheelMessage: The window was destroyed "
658 "by NS_WHEEL_WHEEL event"));
659 mLastEventInfo.ResetTransaction();
660 return;
661 }
662 }
663 #ifdef PR_LOGGING
664 else {
665 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
666 ("MouseScroll::HandleMouseWheelMessage: NS_WHEEL_WHEEL event is not "
667 "dispatched"));
668 }
669 #endif
670 }
672 void
673 MouseScrollHandler::HandleScrollMessageAsMouseWheelMessage(nsWindowBase* aWidget,
674 UINT aMessage,
675 WPARAM aWParam,
676 LPARAM aLParam)
677 {
678 NS_ABORT_IF_FALSE(
679 (aMessage == MOZ_WM_VSCROLL || aMessage == MOZ_WM_HSCROLL),
680 "HandleScrollMessageAsMouseWheelMessage must be called with "
681 "MOZ_WM_VSCROLL or MOZ_WM_HSCROLL");
683 mIsWaitingInternalMessage = false;
685 ModifierKeyState modKeyState = GetModifierKeyState(aMessage);
687 WidgetWheelEvent wheelEvent(true, NS_WHEEL_WHEEL, aWidget);
688 double& delta =
689 (aMessage == MOZ_WM_VSCROLL) ? wheelEvent.deltaY : wheelEvent.deltaX;
690 int32_t& lineOrPageDelta =
691 (aMessage == MOZ_WM_VSCROLL) ? wheelEvent.lineOrPageDeltaY :
692 wheelEvent.lineOrPageDeltaX;
694 delta = 1.0;
695 lineOrPageDelta = 1;
697 switch (LOWORD(aWParam)) {
698 case SB_PAGEUP:
699 delta = -1.0;
700 lineOrPageDelta = -1;
701 case SB_PAGEDOWN:
702 wheelEvent.deltaMode = nsIDOMWheelEvent::DOM_DELTA_PAGE;
703 break;
705 case SB_LINEUP:
706 delta = -1.0;
707 lineOrPageDelta = -1;
708 case SB_LINEDOWN:
709 wheelEvent.deltaMode = nsIDOMWheelEvent::DOM_DELTA_LINE;
710 break;
712 default:
713 return;
714 }
715 modKeyState.InitInputEvent(wheelEvent);
716 // XXX Current mouse position may not be same as when the original message
717 // is received. We need to know the actual mouse cursor position when
718 // the original message was received.
719 InitEvent(aWidget, wheelEvent);
721 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
722 ("MouseScroll::HandleScrollMessageAsMouseWheelMessage: aWidget=%p, "
723 "aMessage=MOZ_WM_%sSCROLL, aWParam=0x%08X, aLParam=0x%08X, "
724 "wheelEvent { refPoint: { x: %d, y: %d }, deltaX: %f, deltaY: %f, "
725 "lineOrPageDeltaX: %d, lineOrPageDeltaY: %d, "
726 "isShift: %s, isControl: %s, isAlt: %s, isMeta: %s }",
727 aWidget, (aMessage == MOZ_WM_VSCROLL) ? "V" : "H", aWParam, aLParam,
728 wheelEvent.refPoint.x, wheelEvent.refPoint.y,
729 wheelEvent.deltaX, wheelEvent.deltaY,
730 wheelEvent.lineOrPageDeltaX, wheelEvent.lineOrPageDeltaY,
731 GetBoolName(wheelEvent.IsShift()),
732 GetBoolName(wheelEvent.IsControl()),
733 GetBoolName(wheelEvent.IsAlt()),
734 GetBoolName(wheelEvent.IsMeta())));
736 DispatchEvent(aWidget, wheelEvent);
737 }
739 /******************************************************************************
740 *
741 * EventInfo
742 *
743 ******************************************************************************/
745 MouseScrollHandler::EventInfo::EventInfo(nsWindowBase* aWidget,
746 UINT aMessage,
747 WPARAM aWParam, LPARAM aLParam)
748 {
749 NS_ABORT_IF_FALSE(aMessage == WM_MOUSEWHEEL || aMessage == WM_MOUSEHWHEEL,
750 "EventInfo must be initialized with WM_MOUSEWHEEL or WM_MOUSEHWHEEL");
752 MouseScrollHandler::GetInstance()->mSystemSettings.Init();
754 mIsVertical = (aMessage == WM_MOUSEWHEEL);
755 mIsPage = MouseScrollHandler::sInstance->
756 mSystemSettings.IsPageScroll(mIsVertical);
757 mDelta = (short)HIWORD(aWParam);
758 mWnd = aWidget->GetWindowHandle();
759 mTimeStamp = TimeStamp::Now();
760 }
762 bool
763 MouseScrollHandler::EventInfo::CanDispatchWheelEvent() const
764 {
765 if (!GetScrollAmount()) {
766 // XXX I think that we should dispatch mouse wheel events even if the
767 // operation will not scroll because the wheel operation really happened
768 // and web application may want to handle the event for non-scroll action.
769 return false;
770 }
772 return (mDelta != 0);
773 }
775 int32_t
776 MouseScrollHandler::EventInfo::GetScrollAmount() const
777 {
778 if (mIsPage) {
779 return 1;
780 }
781 return MouseScrollHandler::sInstance->
782 mSystemSettings.GetScrollAmount(mIsVertical);
783 }
785 /******************************************************************************
786 *
787 * LastEventInfo
788 *
789 ******************************************************************************/
791 bool
792 MouseScrollHandler::LastEventInfo::CanContinueTransaction(
793 const EventInfo& aNewEvent)
794 {
795 int32_t timeout = MouseScrollHandler::sInstance->
796 mUserPrefs.GetMouseScrollTransactionTimeout();
797 return !mWnd ||
798 (mWnd == aNewEvent.GetWindowHandle() &&
799 IsPositive() == aNewEvent.IsPositive() &&
800 mIsVertical == aNewEvent.IsVertical() &&
801 mIsPage == aNewEvent.IsPage() &&
802 (timeout < 0 ||
803 TimeStamp::Now() - mTimeStamp <=
804 TimeDuration::FromMilliseconds(timeout)));
805 }
807 void
808 MouseScrollHandler::LastEventInfo::ResetTransaction()
809 {
810 if (!mWnd) {
811 return;
812 }
814 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
815 ("MouseScroll::LastEventInfo::ResetTransaction()"));
817 mWnd = nullptr;
818 mAccumulatedDelta = 0;
819 }
821 void
822 MouseScrollHandler::LastEventInfo::RecordEvent(const EventInfo& aEvent)
823 {
824 mWnd = aEvent.GetWindowHandle();
825 mDelta = aEvent.GetNativeDelta();
826 mIsVertical = aEvent.IsVertical();
827 mIsPage = aEvent.IsPage();
828 mTimeStamp = TimeStamp::Now();
829 }
831 /* static */
832 int32_t
833 MouseScrollHandler::LastEventInfo::RoundDelta(double aDelta)
834 {
835 return (aDelta >= 0) ? (int32_t)floor(aDelta) : (int32_t)ceil(aDelta);
836 }
838 bool
839 MouseScrollHandler::LastEventInfo::InitWheelEvent(
840 nsWindowBase* aWidget,
841 WidgetWheelEvent& aWheelEvent,
842 const ModifierKeyState& aModKeyState)
843 {
844 MOZ_ASSERT(aWheelEvent.message == NS_WHEEL_WHEEL);
846 // XXX Why don't we use lParam value? We should use lParam value because
847 // our internal message is always posted by original message handler.
848 // So, GetMessagePos() may return different cursor position.
849 InitEvent(aWidget, aWheelEvent);
851 aModKeyState.InitInputEvent(aWheelEvent);
853 // Our positive delta value means to bottom or right.
854 // But positive native delta value means to top or right.
855 // Use orienter for computing our delta value with native delta value.
856 int32_t orienter = mIsVertical ? -1 : 1;
858 aWheelEvent.deltaMode = mIsPage ? nsIDOMWheelEvent::DOM_DELTA_PAGE :
859 nsIDOMWheelEvent::DOM_DELTA_LINE;
861 double& delta = mIsVertical ? aWheelEvent.deltaY : aWheelEvent.deltaX;
862 int32_t& lineOrPageDelta = mIsVertical ? aWheelEvent.lineOrPageDeltaY :
863 aWheelEvent.lineOrPageDeltaX;
865 double nativeDeltaPerUnit =
866 mIsPage ? static_cast<double>(WHEEL_DELTA) :
867 static_cast<double>(WHEEL_DELTA) / GetScrollAmount();
869 delta = static_cast<double>(mDelta) * orienter / nativeDeltaPerUnit;
870 mAccumulatedDelta += mDelta;
871 lineOrPageDelta =
872 mAccumulatedDelta * orienter / RoundDelta(nativeDeltaPerUnit);
873 mAccumulatedDelta -=
874 lineOrPageDelta * orienter * RoundDelta(nativeDeltaPerUnit);
876 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
877 ("MouseScroll::LastEventInfo::InitWheelEvent: aWidget=%p, "
878 "aWheelEvent { refPoint: { x: %d, y: %d }, deltaX: %f, deltaY: %f, "
879 "lineOrPageDeltaX: %d, lineOrPageDeltaY: %d, "
880 "isShift: %s, isControl: %s, isAlt: %s, isMeta: %s }, "
881 "mAccumulatedDelta: %d",
882 aWidget, aWheelEvent.refPoint.x, aWheelEvent.refPoint.y,
883 aWheelEvent.deltaX, aWheelEvent.deltaY,
884 aWheelEvent.lineOrPageDeltaX, aWheelEvent.lineOrPageDeltaY,
885 GetBoolName(aWheelEvent.IsShift()),
886 GetBoolName(aWheelEvent.IsControl()),
887 GetBoolName(aWheelEvent.IsAlt()),
888 GetBoolName(aWheelEvent.IsMeta()), mAccumulatedDelta));
890 return (delta != 0);
891 }
893 /******************************************************************************
894 *
895 * SystemSettings
896 *
897 ******************************************************************************/
899 void
900 MouseScrollHandler::SystemSettings::Init()
901 {
902 if (mInitialized) {
903 return;
904 }
906 mInitialized = true;
908 MouseScrollHandler::UserPrefs& userPrefs =
909 MouseScrollHandler::sInstance->mUserPrefs;
911 mScrollLines = userPrefs.GetOverriddenVerticalScrollAmout();
912 if (mScrollLines >= 0) {
913 // overridden by the pref.
914 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
915 ("MouseScroll::SystemSettings::Init(): mScrollLines is overridden by "
916 "the pref: %d",
917 mScrollLines));
918 } else if (!::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0,
919 &mScrollLines, 0)) {
920 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
921 ("MouseScroll::SystemSettings::Init(): ::SystemParametersInfo("
922 "SPI_GETWHEELSCROLLLINES) failed"));
923 mScrollLines = 3;
924 }
926 if (mScrollLines > WHEEL_DELTA) {
927 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
928 ("MouseScroll::SystemSettings::Init(): the result of "
929 "::SystemParametersInfo(SPI_GETWHEELSCROLLLINES) is too large: %d",
930 mScrollLines));
931 // sScrollLines usually equals 3 or 0 (for no scrolling)
932 // However, if sScrollLines > WHEEL_DELTA, we assume that
933 // the mouse driver wants a page scroll. The docs state that
934 // sScrollLines should explicitly equal WHEEL_PAGESCROLL, but
935 // since some mouse drivers use an arbitrary large number instead,
936 // we have to handle that as well.
937 mScrollLines = WHEEL_PAGESCROLL;
938 }
940 mScrollChars = userPrefs.GetOverriddenHorizontalScrollAmout();
941 if (mScrollChars >= 0) {
942 // overridden by the pref.
943 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
944 ("MouseScroll::SystemSettings::Init(): mScrollChars is overridden by "
945 "the pref: %d",
946 mScrollChars));
947 } else if (!::SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0,
948 &mScrollChars, 0)) {
949 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
950 ("MouseScroll::SystemSettings::Init(): ::SystemParametersInfo("
951 "SPI_GETWHEELSCROLLCHARS) failed, %s",
952 IsVistaOrLater() ?
953 "this is unexpected on Vista or later" :
954 "but on XP or earlier, this is not a problem"));
955 mScrollChars = 1;
956 }
958 if (mScrollChars > WHEEL_DELTA) {
959 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
960 ("MouseScroll::SystemSettings::Init(): the result of "
961 "::SystemParametersInfo(SPI_GETWHEELSCROLLCHARS) is too large: %d",
962 mScrollChars));
963 // See the comments for the case mScrollLines > WHEEL_DELTA.
964 mScrollChars = WHEEL_PAGESCROLL;
965 }
967 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
968 ("MouseScroll::SystemSettings::Init(): initialized, "
969 "mScrollLines=%d, mScrollChars=%d",
970 mScrollLines, mScrollChars));
971 }
973 void
974 MouseScrollHandler::SystemSettings::MarkDirty()
975 {
976 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
977 ("MouseScrollHandler::SystemSettings::MarkDirty(): "
978 "Marking SystemSettings dirty"));
979 mInitialized = false;
980 // When system settings are changed, we should reset current transaction.
981 MOZ_ASSERT(sInstance,
982 "Must not be called at initializing MouseScrollHandler");
983 MouseScrollHandler::sInstance->mLastEventInfo.ResetTransaction();
984 }
986 /******************************************************************************
987 *
988 * UserPrefs
989 *
990 ******************************************************************************/
992 MouseScrollHandler::UserPrefs::UserPrefs() :
993 mInitialized(false)
994 {
995 // We need to reset mouse wheel transaction when all of mousewheel related
996 // prefs are changed.
997 DebugOnly<nsresult> rv =
998 Preferences::RegisterCallback(OnChange, "mousewheel.", this);
999 MOZ_ASSERT(NS_SUCCEEDED(rv),
1000 "Failed to register callback for mousewheel.");
1001 }
1003 MouseScrollHandler::UserPrefs::~UserPrefs()
1004 {
1005 DebugOnly<nsresult> rv =
1006 Preferences::UnregisterCallback(OnChange, "mousewheel.", this);
1007 MOZ_ASSERT(NS_SUCCEEDED(rv),
1008 "Failed to unregister callback for mousewheel.");
1009 }
1011 void
1012 MouseScrollHandler::UserPrefs::Init()
1013 {
1014 if (mInitialized) {
1015 return;
1016 }
1018 mInitialized = true;
1020 mScrollMessageHandledAsWheelMessage =
1021 Preferences::GetBool("mousewheel.emulate_at_wm_scroll", false);
1022 mOverriddenVerticalScrollAmount =
1023 Preferences::GetInt("mousewheel.windows.vertical_amount_override", -1);
1024 mOverriddenHorizontalScrollAmount =
1025 Preferences::GetInt("mousewheel.windows.horizontal_amount_override", -1);
1026 mMouseScrollTransactionTimeout =
1027 Preferences::GetInt("mousewheel.windows.transaction.timeout",
1028 DEFAULT_TIMEOUT_DURATION);
1030 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1031 ("MouseScroll::UserPrefs::Init(): initialized, "
1032 "mScrollMessageHandledAsWheelMessage=%s, "
1033 "mOverriddenVerticalScrollAmount=%d, "
1034 "mOverriddenHorizontalScrollAmount=%d, "
1035 "mMouseScrollTransactionTimeout=%d",
1036 GetBoolName(mScrollMessageHandledAsWheelMessage),
1037 mOverriddenVerticalScrollAmount, mOverriddenHorizontalScrollAmount,
1038 mMouseScrollTransactionTimeout));
1039 }
1041 void
1042 MouseScrollHandler::UserPrefs::MarkDirty()
1043 {
1044 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1045 ("MouseScrollHandler::UserPrefs::MarkDirty(): Marking UserPrefs dirty"));
1046 mInitialized = false;
1047 // Some prefs might override system settings, so, we should mark them dirty.
1048 MouseScrollHandler::sInstance->mSystemSettings.MarkDirty();
1049 // When user prefs for mousewheel are changed, we should reset current
1050 // transaction.
1051 MOZ_ASSERT(sInstance,
1052 "Must not be called at initializing MouseScrollHandler");
1053 MouseScrollHandler::sInstance->mLastEventInfo.ResetTransaction();
1054 }
1056 /******************************************************************************
1057 *
1058 * Device
1059 *
1060 ******************************************************************************/
1062 /* static */
1063 bool
1064 MouseScrollHandler::Device::GetWorkaroundPref(const char* aPrefName,
1065 bool aValueIfAutomatic)
1066 {
1067 if (!aPrefName) {
1068 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1069 ("MouseScroll::Device::GetWorkaroundPref(): Failed, aPrefName is NULL"));
1070 return aValueIfAutomatic;
1071 }
1073 int32_t lHackValue = 0;
1074 if (NS_FAILED(Preferences::GetInt(aPrefName, &lHackValue))) {
1075 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1076 ("MouseScroll::Device::GetWorkaroundPref(): Preferences::GetInt() failed,"
1077 " aPrefName=\"%s\", aValueIfAutomatic=%s",
1078 aPrefName, GetBoolName(aValueIfAutomatic)));
1079 return aValueIfAutomatic;
1080 }
1082 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1083 ("MouseScroll::Device::GetWorkaroundPref(): Succeeded, "
1084 "aPrefName=\"%s\", aValueIfAutomatic=%s, lHackValue=%d",
1085 aPrefName, GetBoolName(aValueIfAutomatic), lHackValue));
1087 switch (lHackValue) {
1088 case 0: // disabled
1089 return false;
1090 case 1: // enabled
1091 return true;
1092 default: // -1: autodetect
1093 return aValueIfAutomatic;
1094 }
1095 }
1097 /* static */
1098 void
1099 MouseScrollHandler::Device::Init()
1100 {
1101 // Not supported in metro mode.
1102 if (XRE_GetWindowsEnvironment() == WindowsEnvironmentType_Metro) {
1103 return;
1104 }
1106 sFakeScrollableWindowNeeded =
1107 GetWorkaroundPref("ui.trackpoint_hack.enabled",
1108 (TrackPoint::IsDriverInstalled() ||
1109 UltraNav::IsObsoleteDriverInstalled()));
1111 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1112 ("MouseScroll::Device::Init(): sFakeScrollableWindowNeeded=%s",
1113 GetBoolName(sFakeScrollableWindowNeeded)));
1115 Elantech::Init();
1116 }
1118 /******************************************************************************
1119 *
1120 * Device::Elantech
1121 *
1122 ******************************************************************************/
1124 /* static */
1125 void
1126 MouseScrollHandler::Device::Elantech::Init()
1127 {
1128 int32_t version = GetDriverMajorVersion();
1129 bool needsHack =
1130 Device::GetWorkaroundPref("ui.elantech_gesture_hacks.enabled",
1131 version != 0);
1132 sUseSwipeHack = needsHack && version <= 7;
1133 sUsePinchHack = needsHack && version <= 8;
1135 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1136 ("MouseScroll::Device::Elantech::Init(): version=%d, sUseSwipeHack=%s, "
1137 "sUsePinchHack=%s",
1138 version, GetBoolName(sUseSwipeHack), GetBoolName(sUsePinchHack)));
1139 }
1141 /* static */
1142 int32_t
1143 MouseScrollHandler::Device::Elantech::GetDriverMajorVersion()
1144 {
1145 wchar_t buf[40];
1146 // The driver version is found in one of these two registry keys.
1147 bool foundKey =
1148 WinUtils::GetRegistryKey(HKEY_CURRENT_USER,
1149 L"Software\\Elantech\\MainOption",
1150 L"DriverVersion",
1151 buf, sizeof buf);
1152 if (!foundKey) {
1153 foundKey =
1154 WinUtils::GetRegistryKey(HKEY_CURRENT_USER,
1155 L"Software\\Elantech",
1156 L"DriverVersion",
1157 buf, sizeof buf);
1158 }
1160 if (!foundKey) {
1161 return 0;
1162 }
1164 // Assume that the major version number can be found just after a space
1165 // or at the start of the string.
1166 for (wchar_t* p = buf; *p; p++) {
1167 if (*p >= L'0' && *p <= L'9' && (p == buf || *(p - 1) == L' ')) {
1168 return wcstol(p, nullptr, 10);
1169 }
1170 }
1172 return 0;
1173 }
1175 /* static */
1176 bool
1177 MouseScrollHandler::Device::Elantech::IsHelperWindow(HWND aWnd)
1178 {
1179 // The helper window cannot be distinguished based on its window class, so we
1180 // need to check if it is owned by the helper process, ETDCtrl.exe.
1182 const wchar_t* filenameSuffix = L"\\etdctrl.exe";
1183 const int filenameSuffixLength = 12;
1185 DWORD pid;
1186 ::GetWindowThreadProcessId(aWnd, &pid);
1188 HANDLE hProcess = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1189 if (!hProcess) {
1190 return false;
1191 }
1193 bool result = false;
1194 wchar_t path[256] = {L'\0'};
1195 if (::GetProcessImageFileNameW(hProcess, path, ArrayLength(path))) {
1196 int pathLength = lstrlenW(path);
1197 if (pathLength >= filenameSuffixLength) {
1198 if (lstrcmpiW(path + pathLength - filenameSuffixLength,
1199 filenameSuffix) == 0) {
1200 result = true;
1201 }
1202 }
1203 }
1204 ::CloseHandle(hProcess);
1206 return result;
1207 }
1209 /* static */
1210 bool
1211 MouseScrollHandler::Device::Elantech::HandleKeyMessage(nsWindowBase* aWidget,
1212 UINT aMsg,
1213 WPARAM aWParam)
1214 {
1215 // The Elantech touchpad driver understands three-finger swipe left and
1216 // right gestures, and translates them into Page Up and Page Down key
1217 // events for most applications. For Firefox 3.6, it instead sends
1218 // Alt+Left and Alt+Right to trigger browser back/forward actions. As
1219 // with the Thinkpad Driver hack in nsWindow::Create, the change in
1220 // HWND structure makes Firefox not trigger the driver's heuristics
1221 // any longer.
1222 //
1223 // The Elantech driver actually sends these messages for a three-finger
1224 // swipe right:
1225 //
1226 // WM_KEYDOWN virtual_key = 0xCC or 0xFF (depending on driver version)
1227 // WM_KEYDOWN virtual_key = VK_NEXT
1228 // WM_KEYUP virtual_key = VK_NEXT
1229 // WM_KEYUP virtual_key = 0xCC or 0xFF
1230 //
1231 // so we use the 0xCC or 0xFF key modifier to detect whether the Page Down
1232 // is due to the gesture rather than a regular Page Down keypress. We then
1233 // pretend that we should dispatch "Go Forward" command. Similarly
1234 // for VK_PRIOR and "Go Back" command.
1235 if (sUseSwipeHack &&
1236 (aWParam == VK_NEXT || aWParam == VK_PRIOR) &&
1237 (IS_VK_DOWN(0xFF) || IS_VK_DOWN(0xCC))) {
1238 if (aMsg == WM_KEYDOWN) {
1239 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1240 ("MouseScroll::Device::Elantech::HandleKeyMessage(): Dispatching "
1241 "%s command event",
1242 aWParam == VK_NEXT ? "Forward" : "Back"));
1244 WidgetCommandEvent commandEvent(true, nsGkAtoms::onAppCommand,
1245 (aWParam == VK_NEXT) ? nsGkAtoms::Forward : nsGkAtoms::Back, aWidget);
1246 InitEvent(aWidget, commandEvent);
1247 MouseScrollHandler::DispatchEvent(aWidget, commandEvent);
1248 }
1249 #ifdef PR_LOGGING
1250 else {
1251 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1252 ("MouseScroll::Device::Elantech::HandleKeyMessage(): Consumed"));
1253 }
1254 #endif
1255 return true; // consume the message (doesn't need to dispatch key events)
1256 }
1258 // Version 8 of the Elantech touchpad driver sends these messages for
1259 // zoom gestures:
1260 //
1261 // WM_KEYDOWN virtual_key = 0xCC time = 10
1262 // WM_KEYDOWN virtual_key = VK_CONTROL time = 10
1263 // WM_MOUSEWHEEL time = ::GetTickCount()
1264 // WM_KEYUP virtual_key = VK_CONTROL time = 10
1265 // WM_KEYUP virtual_key = 0xCC time = 10
1266 //
1267 // The result of this is that we process all of the WM_KEYDOWN/WM_KEYUP
1268 // messages first because their timestamps make them appear to have
1269 // been sent before the WM_MOUSEWHEEL message. To work around this,
1270 // we store the current time when we process the WM_KEYUP message and
1271 // assume that any WM_MOUSEWHEEL message with a timestamp before that
1272 // time is one that should be processed as if the Control key was down.
1273 if (sUsePinchHack && aMsg == WM_KEYUP &&
1274 aWParam == VK_CONTROL && ::GetMessageTime() == 10) {
1275 // We look only at the bottom 31 bits of the system tick count since
1276 // GetMessageTime returns a LONG, which is signed, so we want values
1277 // that are more easily comparable.
1278 sZoomUntil = ::GetTickCount() & 0x7FFFFFFF;
1280 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1281 ("MouseScroll::Device::Elantech::HandleKeyMessage(): sZoomUntil=%d",
1282 sZoomUntil));
1283 }
1285 return false;
1286 }
1288 /* static */
1289 void
1290 MouseScrollHandler::Device::Elantech::UpdateZoomUntil()
1291 {
1292 if (!sZoomUntil) {
1293 return;
1294 }
1296 // For the Elantech Touchpad Zoom Gesture Hack, we should check that the
1297 // system time (32-bit milliseconds) hasn't wrapped around. Otherwise we
1298 // might get into the situation where wheel events for the next 50 days of
1299 // system uptime are assumed to be Ctrl+Wheel events. (It is unlikely that
1300 // we would get into that state, because the system would already need to be
1301 // up for 50 days and the Control key message would need to be processed just
1302 // before the system time overflow and the wheel message just after.)
1303 //
1304 // We also take the chance to reset sZoomUntil if we simply have passed that
1305 // time.
1306 LONG msgTime = ::GetMessageTime();
1307 if ((sZoomUntil >= 0x3fffffffu && DWORD(msgTime) < 0x40000000u) ||
1308 (sZoomUntil < DWORD(msgTime))) {
1309 sZoomUntil = 0;
1311 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1312 ("MouseScroll::Device::Elantech::UpdateZoomUntil(): "
1313 "sZoomUntil was reset"));
1314 }
1315 }
1317 /* static */
1318 bool
1319 MouseScrollHandler::Device::Elantech::IsZooming()
1320 {
1321 // Assume the Control key is down if the Elantech touchpad has sent the
1322 // mis-ordered WM_KEYDOWN/WM_MOUSEWHEEL messages. (See the comment in
1323 // OnKeyUp.)
1324 return (sZoomUntil && static_cast<DWORD>(::GetMessageTime()) < sZoomUntil);
1325 }
1327 /******************************************************************************
1328 *
1329 * Device::TrackPoint
1330 *
1331 ******************************************************************************/
1333 /* static */
1334 bool
1335 MouseScrollHandler::Device::TrackPoint::IsDriverInstalled()
1336 {
1337 if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1338 L"Software\\Lenovo\\TrackPoint")) {
1339 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1340 ("MouseScroll::Device::TrackPoint::IsDriverInstalled(): "
1341 "Lenovo's TrackPoint driver is found"));
1342 return true;
1343 }
1345 if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1346 L"Software\\Alps\\Apoint\\TrackPoint")) {
1347 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1348 ("MouseScroll::Device::TrackPoint::IsDriverInstalled(): "
1349 "Alps's TrackPoint driver is found"));
1350 }
1352 return false;
1353 }
1355 /******************************************************************************
1356 *
1357 * Device::UltraNav
1358 *
1359 ******************************************************************************/
1361 /* static */
1362 bool
1363 MouseScrollHandler::Device::UltraNav::IsObsoleteDriverInstalled()
1364 {
1365 if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1366 L"Software\\Lenovo\\UltraNav")) {
1367 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1368 ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1369 "Lenovo's UltraNav driver is found"));
1370 return true;
1371 }
1373 bool installed = false;
1374 if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1375 L"Software\\Synaptics\\SynTPEnh\\UltraNavUSB")) {
1376 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1377 ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1378 "Synaptics's UltraNav (USB) driver is found"));
1379 installed = true;
1380 } else if (WinUtils::HasRegistryKey(HKEY_CURRENT_USER,
1381 L"Software\\Synaptics\\SynTPEnh\\UltraNavPS2")) {
1382 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1383 ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1384 "Synaptics's UltraNav (PS/2) driver is found"));
1385 installed = true;
1386 }
1388 if (!installed) {
1389 return false;
1390 }
1392 wchar_t buf[40];
1393 bool foundKey =
1394 WinUtils::GetRegistryKey(HKEY_LOCAL_MACHINE,
1395 L"Software\\Synaptics\\SynTP\\Install",
1396 L"DriverVersion",
1397 buf, sizeof buf);
1398 if (!foundKey) {
1399 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1400 ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1401 "Failed to get UltraNav driver version"));
1402 return false;
1403 }
1405 int majorVersion = wcstol(buf, nullptr, 10);
1406 int minorVersion = 0;
1407 wchar_t* p = wcschr(buf, L'.');
1408 if (p) {
1409 minorVersion = wcstol(p + 1, nullptr, 10);
1410 }
1411 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1412 ("MouseScroll::Device::UltraNav::IsObsoleteDriverInstalled(): "
1413 "found driver version = %d.%d",
1414 majorVersion, minorVersion));
1415 return majorVersion < 15 || (majorVersion == 15 && minorVersion == 0);
1416 }
1418 /******************************************************************************
1419 *
1420 * Device::SetPoint
1421 *
1422 ******************************************************************************/
1424 /* static */
1425 bool
1426 MouseScrollHandler::Device::SetPoint::IsGetMessagePosResponseValid(
1427 UINT aMessage,
1428 WPARAM aWParam,
1429 LPARAM aLParam)
1430 {
1431 if (aMessage != WM_MOUSEHWHEEL) {
1432 return false;
1433 }
1435 POINTS pts = MouseScrollHandler::GetCurrentMessagePos();
1436 LPARAM messagePos = MAKELPARAM(pts.x, pts.y);
1438 // XXX We should check whether SetPoint is installed or not by registry.
1440 // SetPoint, Logitech (Logicool) mouse driver, (confirmed with 4.82.11 and
1441 // MX-1100) always sets 0 to the lParam of WM_MOUSEHWHEEL. The driver SENDs
1442 // one message at first time, this time, ::GetMessagePos() works fine.
1443 // Then, we will return 0 (0 means we process it) to the message. Then, the
1444 // driver will POST the same messages continuously during the wheel tilted.
1445 // But ::GetMessagePos() API always returns (0, 0) for them, even if the
1446 // actual mouse cursor isn't 0,0. Therefore, we cannot trust the result of
1447 // ::GetMessagePos API if the sender is SetPoint.
1448 if (!sMightBeUsing && !aLParam && aLParam != messagePos &&
1449 ::InSendMessage()) {
1450 sMightBeUsing = true;
1451 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1452 ("MouseScroll::Device::SetPoint::IsGetMessagePosResponseValid(): "
1453 "Might using SetPoint"));
1454 } else if (sMightBeUsing && aLParam != 0 && ::InSendMessage()) {
1455 // The user has changed the mouse from Logitech's to another one (e.g.,
1456 // the user has changed to the touchpad of the notebook.
1457 sMightBeUsing = false;
1458 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1459 ("MouseScroll::Device::SetPoint::IsGetMessagePosResponseValid(): "
1460 "Might stop using SetPoint"));
1461 }
1462 return (sMightBeUsing && !aLParam && !messagePos);
1463 }
1465 /******************************************************************************
1466 *
1467 * SynthesizingEvent
1468 *
1469 ******************************************************************************/
1471 /* static */
1472 bool
1473 MouseScrollHandler::SynthesizingEvent::IsSynthesizing()
1474 {
1475 return MouseScrollHandler::sInstance &&
1476 MouseScrollHandler::sInstance->mSynthesizingEvent &&
1477 MouseScrollHandler::sInstance->mSynthesizingEvent->mStatus !=
1478 NOT_SYNTHESIZING;
1479 }
1481 nsresult
1482 MouseScrollHandler::SynthesizingEvent::Synthesize(const POINTS& aCursorPoint,
1483 HWND aWnd,
1484 UINT aMessage,
1485 WPARAM aWParam,
1486 LPARAM aLParam,
1487 const BYTE (&aKeyStates)[256])
1488 {
1489 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1490 ("MouseScrollHandler::SynthesizingEvent::Synthesize(): aCursorPoint: { "
1491 "x: %d, y: %d }, aWnd=0x%X, aMessage=0x%04X, aWParam=0x%08X, "
1492 "aLParam=0x%08X, IsSynthesized()=%s, mStatus=%s",
1493 aCursorPoint.x, aCursorPoint.y, aWnd, aMessage, aWParam, aLParam,
1494 GetBoolName(IsSynthesizing()), GetStatusName()));
1496 if (IsSynthesizing()) {
1497 return NS_ERROR_NOT_AVAILABLE;
1498 }
1500 ::GetKeyboardState(mOriginalKeyState);
1502 // Note that we cannot use ::SetCursorPos() because it works asynchronously.
1503 // We should SEND the message for reducing the possibility of receiving
1504 // unexpected message which were not sent from here.
1505 mCursorPoint = aCursorPoint;
1507 mWnd = aWnd;
1508 mMessage = aMessage;
1509 mWParam = aWParam;
1510 mLParam = aLParam;
1512 memcpy(mKeyState, aKeyStates, sizeof(mKeyState));
1513 ::SetKeyboardState(mKeyState);
1515 mStatus = SENDING_MESSAGE;
1517 // Don't assume that aWnd is always managed by nsWindow. It might be
1518 // a plugin window.
1519 ::SendMessage(aWnd, aMessage, aWParam, aLParam);
1521 return NS_OK;
1522 }
1524 void
1525 MouseScrollHandler::SynthesizingEvent::NativeMessageReceived(nsWindowBase* aWidget,
1526 UINT aMessage,
1527 WPARAM aWParam,
1528 LPARAM aLParam)
1529 {
1530 if (mStatus == SENDING_MESSAGE && mMessage == aMessage &&
1531 mWParam == aWParam && mLParam == aLParam) {
1532 mStatus = NATIVE_MESSAGE_RECEIVED;
1533 if (aWidget && aWidget->GetWindowHandle() == mWnd) {
1534 return;
1535 }
1536 // If the target window is not ours and received window is our plugin
1537 // window, it comes from child window of the plugin.
1538 if (aWidget && aWidget->WindowType() == eWindowType_plugin &&
1539 !WinUtils::GetNSWindowBasePtr(mWnd)) {
1540 return;
1541 }
1542 // Otherwise, the message may not be sent by us.
1543 }
1545 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1546 ("MouseScrollHandler::SynthesizingEvent::NativeMessageReceived(): "
1547 "aWidget=%p, aWidget->GetWindowHandle()=0x%X, mWnd=0x%X, "
1548 "aMessage=0x%04X, aWParam=0x%08X, aLParam=0x%08X, mStatus=%s",
1549 aWidget, aWidget ? aWidget->GetWindowHandle() : 0, mWnd,
1550 aMessage, aWParam, aLParam, GetStatusName()));
1552 // We failed to receive our sent message, we failed to do the job.
1553 Finish();
1555 return;
1556 }
1558 void
1559 MouseScrollHandler::SynthesizingEvent::NotifyNativeMessageHandlingFinished()
1560 {
1561 if (!IsSynthesizing()) {
1562 return;
1563 }
1565 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1566 ("MouseScrollHandler::SynthesizingEvent::"
1567 "NotifyNativeMessageHandlingFinished(): IsWaitingInternalMessage=%s",
1568 GetBoolName(MouseScrollHandler::IsWaitingInternalMessage())));
1570 if (MouseScrollHandler::IsWaitingInternalMessage()) {
1571 mStatus = INTERNAL_MESSAGE_POSTED;
1572 return;
1573 }
1575 // If the native message handler didn't post our internal message,
1576 // we our job is finished.
1577 // TODO: When we post the message to plugin window, there is remaning job.
1578 Finish();
1579 }
1581 void
1582 MouseScrollHandler::SynthesizingEvent::NotifyInternalMessageHandlingFinished()
1583 {
1584 if (!IsSynthesizing()) {
1585 return;
1586 }
1588 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1589 ("MouseScrollHandler::SynthesizingEvent::"
1590 "NotifyInternalMessageHandlingFinished()"));
1592 Finish();
1593 }
1595 void
1596 MouseScrollHandler::SynthesizingEvent::Finish()
1597 {
1598 if (!IsSynthesizing()) {
1599 return;
1600 }
1602 PR_LOG(gMouseScrollLog, PR_LOG_ALWAYS,
1603 ("MouseScrollHandler::SynthesizingEvent::Finish()"));
1605 // Restore the original key state.
1606 ::SetKeyboardState(mOriginalKeyState);
1608 mStatus = NOT_SYNTHESIZING;
1609 }
1611 } // namespace widget
1612 } // namespace mozilla