Backed out changeset 2450366cf7ca (bug 1891629) for causing win msix mochitest failures
[gecko.git] / widget / windows / nsWindow.cpp
blobac8f44cd9becdc3df59b0c0563549e31f9d0ff49
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sts=2 sw=2 et cin: */
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
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 /*
8 * nsWindow - Native window management and event handling.
10 * nsWindow is organized into a set of major blocks and
11 * block subsections. The layout is as follows:
13 * Includes
14 * Variables
15 * nsIWidget impl.
16 * nsIWidget methods and utilities
17 * nsSwitchToUIThread impl.
18 * nsSwitchToUIThread methods and utilities
19 * Moz events
20 * Event initialization
21 * Event dispatching
22 * Native events
23 * Wndproc(s)
24 * Event processing
25 * OnEvent event handlers
26 * IME management and accessibility
27 * Transparency
28 * Popup hook handling
29 * Misc. utilities
30 * Child window impl.
32 * Search for "BLOCK:" to find major blocks.
33 * Search for "SECTION:" to find specific sections.
35 * Blocks should be split out into separate files if they
36 * become unmanageable.
38 * Notable related sources:
40 * nsWindowDefs.h - Definitions, macros, structs, enums
41 * and general setup.
42 * nsWindowDbg.h/.cpp - Debug related code and directives.
43 * nsWindowGfx.h/.cpp - Graphics and painting.
47 /**************************************************************
48 **************************************************************
50 ** BLOCK: Includes
52 ** Include headers.
54 **************************************************************
55 **************************************************************/
57 #include "gfx2DGlue.h"
58 #include "gfxEnv.h"
59 #include "gfxPlatform.h"
61 #include "mozilla/AppShutdown.h"
62 #include "mozilla/AutoRestore.h"
63 #include "mozilla/Likely.h"
64 #include "mozilla/PreXULSkeletonUI.h"
65 #include "mozilla/Logging.h"
66 #include "mozilla/MathAlgorithms.h"
67 #include "mozilla/MiscEvents.h"
68 #include "mozilla/MouseEvents.h"
69 #include "mozilla/PresShell.h"
70 #include "mozilla/ScopeExit.h"
71 #include "mozilla/StaticPrefs_browser.h"
72 #include "mozilla/SwipeTracker.h"
73 #include "mozilla/TouchEvents.h"
74 #include "mozilla/TimeStamp.h"
76 #include "mozilla/ipc/MessageChannel.h"
77 #include <algorithm>
78 #include <limits>
80 #include "mozilla/widget/WinMessages.h"
81 #include "nsLookAndFeel.h"
82 #include "nsWindow.h"
83 #include "nsWindowTaskbarConcealer.h"
84 #include "nsAppRunner.h"
86 #include <shellapi.h>
87 #include <windows.h>
88 #include <wtsapi32.h>
89 #include <process.h>
90 #include <commctrl.h>
91 #include <dbt.h>
92 #include <unknwn.h>
93 #include <psapi.h>
94 #include <rpc.h>
95 #include <propvarutil.h>
96 #include <propkey.h>
98 #include "mozilla/Logging.h"
99 #include "prtime.h"
100 #include "prenv.h"
102 #include "mozilla/WidgetTraceEvent.h"
103 #include "nsContentUtils.h"
104 #include "nsISupportsPrimitives.h"
105 #include "nsITheme.h"
106 #include "nsIObserverService.h"
107 #include "nsIScreenManager.h"
108 #include "imgIContainer.h"
109 #include "nsIFile.h"
110 #include "nsIRollupListener.h"
111 #include "nsIClipboard.h"
112 #include "WinMouseScrollHandler.h"
113 #include "nsFontMetrics.h"
114 #include "nsIFontEnumerator.h"
115 #include "nsFont.h"
116 #include "nsRect.h"
117 #include "nsThreadUtils.h"
118 #include "nsNativeCharsetUtils.h"
119 #include "nsGkAtoms.h"
120 #include "nsCRT.h"
121 #include "nsAppDirectoryServiceDefs.h"
122 #include "nsWidgetsCID.h"
123 #include "nsTHashtable.h"
124 #include "nsHashKeys.h"
125 #include "nsString.h"
126 #include "mozilla/Components.h"
127 #include "nsNativeThemeWin.h"
128 #include "nsXULPopupManager.h"
129 #include "nsWindowsDllInterceptor.h"
130 #include "nsLayoutUtils.h"
131 #include "nsView.h"
132 #include "nsWindowGfx.h"
133 #include "gfxWindowsPlatform.h"
134 #include "gfxDWriteFonts.h"
135 #include "nsPrintfCString.h"
136 #include "mozilla/Preferences.h"
137 #include "SystemTimeConverter.h"
138 #include "WinTaskbar.h"
139 #include "WidgetUtils.h"
140 #include "WinWindowOcclusionTracker.h"
141 #include "nsIWidgetListener.h"
142 #include "mozilla/dom/Document.h"
143 #include "mozilla/dom/MouseEventBinding.h"
144 #include "mozilla/dom/Touch.h"
145 #include "mozilla/gfx/2D.h"
146 #include "mozilla/gfx/GPUProcessManager.h"
147 #include "mozilla/intl/LocaleService.h"
148 #include "mozilla/layers/WebRenderLayerManager.h"
149 #include "mozilla/WindowsVersion.h"
150 #include "mozilla/TextEvents.h" // For WidgetKeyboardEvent
151 #include "mozilla/TextEventDispatcherListener.h"
152 #include "mozilla/widget/nsAutoRollup.h"
153 #include "mozilla/widget/PlatformWidgetTypes.h"
154 #include "mozilla/widget/Screen.h"
155 #include "nsStyleConsts.h"
156 #include "nsBidiKeyboard.h"
157 #include "nsStyleConsts.h"
158 #include "gfxConfig.h"
159 #include "InProcessWinCompositorWidget.h"
160 #include "InputDeviceUtils.h"
161 #include "ScreenHelperWin.h"
162 #include "mozilla/StaticPrefs_apz.h"
163 #include "mozilla/StaticPrefs_dom.h"
164 #include "mozilla/StaticPrefs_gfx.h"
165 #include "mozilla/StaticPrefs_layout.h"
166 #include "mozilla/StaticPrefs_ui.h"
167 #include "mozilla/StaticPrefs_widget.h"
168 #include "nsNativeAppSupportWin.h"
169 #include "mozilla/browser/NimbusFeatures.h"
171 #include "nsIGfxInfo.h"
172 #include "nsUXThemeConstants.h"
173 #include "KeyboardLayout.h"
174 #include "nsNativeDragTarget.h"
175 #include <mmsystem.h> // needed for WIN32_LEAN_AND_MEAN
176 #include <zmouse.h>
177 #include <richedit.h>
179 #ifdef ACCESSIBILITY
180 # ifdef DEBUG
181 # include "mozilla/a11y/Logging.h"
182 # endif
183 # include "mozilla/a11y/Compatibility.h"
184 # include "oleidl.h"
185 # include <uiautomation.h>
186 # include <winuser.h>
187 # include "nsAccessibilityService.h"
188 # include "mozilla/a11y/DocAccessible.h"
189 # include "mozilla/a11y/LazyInstantiator.h"
190 # include "mozilla/a11y/Platform.h"
191 # include "mozilla/StaticPrefs_accessibility.h"
192 # if !defined(WINABLEAPI)
193 # include <winable.h>
194 # endif // !defined(WINABLEAPI)
195 #endif
197 #include "WindowsUIUtils.h"
199 #include "nsWindowDefs.h"
201 #include "nsCrashOnException.h"
203 #include "nsIContent.h"
205 #include "mozilla/BackgroundHangMonitor.h"
206 #include "WinIMEHandler.h"
208 #include "npapi.h"
210 #include <d3d11.h>
212 // ERROR from wingdi.h (below) gets undefined by some code.
213 // #define ERROR 0
214 // #define RGN_ERROR ERROR
215 #define ERROR 0
217 #if !defined(SM_CONVERTIBLESLATEMODE)
218 # define SM_CONVERTIBLESLATEMODE 0x2003
219 #endif
221 #include "mozilla/gfx/DeviceManagerDx.h"
222 #include "mozilla/layers/APZInputBridge.h"
223 #include "mozilla/layers/InputAPZContext.h"
224 #include "mozilla/layers/KnowsCompositor.h"
225 #include "InputData.h"
227 #include "mozilla/TaskController.h"
228 #include "mozilla/Telemetry.h"
229 #include "mozilla/webrender/WebRenderAPI.h"
230 #include "mozilla/layers/IAPZCTreeManager.h"
232 #include "DirectManipulationOwner.h"
234 using namespace mozilla;
235 using namespace mozilla::dom;
236 using namespace mozilla::gfx;
237 using namespace mozilla::layers;
238 using namespace mozilla::widget;
239 using namespace mozilla::plugins;
241 /**************************************************************
242 **************************************************************
244 ** BLOCK: Variables
246 ** nsWindow Class static initializations and global variables.
248 **************************************************************
249 **************************************************************/
251 /**************************************************************
253 * SECTION: nsWindow statics
255 **************************************************************/
256 static const wchar_t kUser32LibName[] = L"user32.dll";
258 uint32_t nsWindow::sInstanceCount = 0;
259 bool nsWindow::sIsOleInitialized = false;
260 nsIWidget::Cursor nsWindow::sCurrentCursor = {};
261 nsWindow* nsWindow::sCurrentWindow = nullptr;
262 bool nsWindow::sJustGotDeactivate = false;
263 bool nsWindow::sJustGotActivate = false;
264 bool nsWindow::sIsInMouseCapture = false;
266 // Urgent-message reentrancy depth for the static `WindowProc` callback.
268 // Three unfortunate facts collide:
270 // 𝛼) Some messages must be processed promptly. If not, Windows will leave the
271 // receiving window in an intermediate, and potentially unusable, state until
272 // the WindowProc invocation that is handling it returns.
274 // 𝛽) Some messages have indefinitely long processing time. These are mostly
275 // messages which may cause us to enter a nested modal loop (via
276 // `SpinEventLoopUntil` or similar).
278 // 𝛾) Sometimes, messages skip the queue entirely. Our `WindowProc` may be
279 // reentrantly reinvoked from the kernel while we're blocking _on_ the
280 // kernel, even briefly, during processing of other messages. (Relevant
281 // search term: `KeUserModeCallback`.)
283 // The nightmare scenario, then, is that during processing of an 𝛼-message, we
284 // briefly become blocked (e.g., by calling `::SendMessageW()`), and the kernel
285 // takes that opportunity to use 𝛾 to hand us a 𝛽-message. (Concretely, see
286 // bug 1842170.)
288 // There is little we can do to prevent the first half of this scenario. 𝛼) and
289 // 𝛾) are effectively immutable facts of Windows, and we sometimes legitimately
290 // need to make blocking calls to process 𝛼-messages. (We may not even be aware
291 // that we're making such calls, if they're undocumented implementation details
292 // of another API.)
294 // In an ideal world, WindowProc would always return promptly (or at least in
295 // bounded time), and 𝛽-messages would not _per se_ exist; long-running modal
296 // states would instead be implemented in async fashion. In practice, that's far
297 // easier said than done -- replacing existing uses of `SpinEventLoopUntil` _et
298 // al._ with asynchronous mechanisms is a collection of mostly-unrelated cross-
299 // cutting architectural tasks, each of potentially unbounded scope. For now,
300 // and for the foreseeable future, we're stuck with them.
302 // We therefore simply punt. More specifically: if a known 𝛽-message jumps the
303 // queue to come in while we're in the middle of processing a known 𝛼-message,
304 // we:
305 // * properly queue the message for processing later;
306 // * respond to the 𝛽-message as though we actually had processed it; and
307 // * just hope that it can wait until we get around to it.
309 // The word "known" requires a bit of justification. There is no canonical set
310 // of 𝛼-messages, nor is the set of 𝛽-messages fixed (or even demarcable). We
311 // can't safely assume that all messages are 𝛼-messages, as that could cause
312 // 𝛽-messages to be arbitrarily and surprisingly delayed whenever any nested
313 // event loop is active. We also can't assume all messages are 𝛽-messages,
314 // since one 𝛼-message jumping the queue while processing another 𝛼-message is
315 // part of normal and required operation for windowed Windows applications.
317 // So we simply add messages to those sets as we identify them. (Or, preferably,
318 // rework the 𝛽-message's handling to make it no longer 𝛽. But see above.)
320 // ---
322 // The actual value of `sDepth` is the number of active invocations of
323 // `WindowProc` that are processing known 𝛼-messages.
324 size_t nsWindow::WndProcUrgentInvocation::sDepth = 0;
326 // Hook Data Members for Dropdowns. sProcessHook Tells the
327 // hook methods whether they should be processing the hook
328 // messages.
329 HHOOK nsWindow::sMsgFilterHook = nullptr;
330 HHOOK nsWindow::sCallProcHook = nullptr;
331 HHOOK nsWindow::sCallMouseHook = nullptr;
332 bool nsWindow::sProcessHook = false;
333 UINT nsWindow::sRollupMsgId = 0;
334 HWND nsWindow::sRollupMsgWnd = nullptr;
335 UINT nsWindow::sHookTimerId = 0;
337 // Used to prevent dispatching mouse events that do not originate from user
338 // input.
339 POINT nsWindow::sLastMouseMovePoint = {0};
341 bool nsWindow::sIsRestoringSession = false;
343 bool nsWindow::sTouchInjectInitialized = false;
344 InjectTouchInputPtr nsWindow::sInjectTouchFuncPtr;
346 static SystemTimeConverter<DWORD>& TimeConverter() {
347 static SystemTimeConverter<DWORD> timeConverterSingleton;
348 return timeConverterSingleton;
351 // Global event hook for window cloaking. Never deregistered.
352 // - `Nothing` if not yet set.
353 // - `Some(nullptr)` if no attempt should be made to set it.
354 static mozilla::Maybe<HWINEVENTHOOK> sWinCloakEventHook = Nothing();
355 static mozilla::LazyLogModule sCloakingLog("DWMCloaking");
357 namespace mozilla {
359 class CurrentWindowsTimeGetter {
360 public:
361 explicit CurrentWindowsTimeGetter(HWND aWnd) : mWnd(aWnd) {}
363 DWORD GetCurrentTime() const { return ::GetTickCount(); }
365 void GetTimeAsyncForPossibleBackwardsSkew(const TimeStamp& aNow) {
366 DWORD currentTime = GetCurrentTime();
367 if (sBackwardsSkewStamp && currentTime == sLastPostTime) {
368 // There's already one inflight with this timestamp. Don't
369 // send a duplicate.
370 return;
372 sBackwardsSkewStamp = Some(aNow);
373 sLastPostTime = currentTime;
374 static_assert(sizeof(WPARAM) >= sizeof(DWORD),
375 "Can't fit a DWORD in a WPARAM");
376 ::PostMessage(mWnd, MOZ_WM_SKEWFIX, sLastPostTime, 0);
379 static bool GetAndClearBackwardsSkewStamp(DWORD aPostTime,
380 TimeStamp* aOutSkewStamp) {
381 if (aPostTime != sLastPostTime) {
382 // The SKEWFIX message is stale; we've sent a new one since then.
383 // Ignore this one.
384 return false;
386 MOZ_ASSERT(sBackwardsSkewStamp);
387 *aOutSkewStamp = sBackwardsSkewStamp.value();
388 sBackwardsSkewStamp = Nothing();
389 return true;
392 private:
393 static Maybe<TimeStamp> sBackwardsSkewStamp;
394 static DWORD sLastPostTime;
395 HWND mWnd;
398 Maybe<TimeStamp> CurrentWindowsTimeGetter::sBackwardsSkewStamp;
399 DWORD CurrentWindowsTimeGetter::sLastPostTime = 0;
401 } // namespace mozilla
403 /**************************************************************
405 * SECTION: globals variables
407 **************************************************************/
409 static const char* sScreenManagerContractID =
410 "@mozilla.org/gfx/screenmanager;1";
412 extern mozilla::LazyLogModule gWindowsLog;
414 static NS_DEFINE_CID(kCClipboardCID, NS_CLIPBOARD_CID);
416 // General purpose user32.dll hook object
417 static WindowsDllInterceptor sUser32Intercept;
419 // When the client area is extended out into the default window frame area,
420 // this is the minimum amount of space along the edge of resizable windows
421 // we will always display a resize cursor in, regardless of the underlying
422 // content.
423 static const int32_t kResizableBorderMinSize = 3;
425 // Getting this object from the window server can be expensive. Keep it
426 // around, also get it off the main thread. (See bug 1640852)
427 StaticRefPtr<IVirtualDesktopManager> gVirtualDesktopManager;
428 static bool gInitializedVirtualDesktopManager = false;
430 // We should never really try to accelerate windows bigger than this. In some
431 // cases this might lead to no D3D9 acceleration where we could have had it
432 // but D3D9 does not reliably report when it supports bigger windows. 8192
433 // is as safe as we can get, we know at least D3D10 hardware always supports
434 // this, other hardware we expect to report correctly in D3D9.
435 #define MAX_ACCELERATED_DIMENSION 8192
437 // On window open (as well as after), Windows has an unfortunate habit of
438 // sending rather a lot of WM_NCHITTEST messages. Because we have to do point
439 // to DOM target conversions for these, we cache responses for a given
440 // coordinate this many milliseconds:
441 #define HITTEST_CACHE_LIFETIME_MS 50
443 #if defined(ACCESSIBILITY)
445 namespace mozilla {
448 * Windows touchscreen code works by setting a global WH_GETMESSAGE hook and
449 * injecting tiptsf.dll. The touchscreen process then posts registered messages
450 * to our main thread. The tiptsf hook picks up those registered messages and
451 * uses them as commands, some of which call into UIA, which then calls into
452 * MSAA, which then sends WM_GETOBJECT to us.
454 * We can get ahead of this by installing our own thread-local WH_GETMESSAGE
455 * hook. Since thread-local hooks are called ahead of global hooks, we will
456 * see these registered messages before tiptsf does. At this point we can then
457 * raise a flag that blocks a11y before invoking CallNextHookEx which will then
458 * invoke the global tiptsf hook. Then when we see WM_GETOBJECT, we check the
459 * flag by calling TIPMessageHandler::IsA11yBlocked().
461 * For Windows 8, we also hook tiptsf!ProcessCaretEvents, which is an a11y hook
462 * function that also calls into UIA.
464 class TIPMessageHandler {
465 public:
466 ~TIPMessageHandler() {
467 if (mHook) {
468 ::UnhookWindowsHookEx(mHook);
472 static void Initialize() {
473 if (sInstance) {
474 return;
477 sInstance = new TIPMessageHandler();
478 ClearOnShutdown(&sInstance);
481 static bool IsA11yBlocked() {
482 if (!sInstance) {
483 return false;
486 return sInstance->mA11yBlockCount > 0;
489 private:
490 TIPMessageHandler() : mHook(nullptr), mA11yBlockCount(0) {
491 MOZ_ASSERT(NS_IsMainThread());
493 // Registered messages used by tiptsf
494 mMessages[0] = ::RegisterWindowMessage(L"ImmersiveFocusNotification");
495 mMessages[1] = ::RegisterWindowMessage(L"TipCloseMenus");
496 mMessages[2] = ::RegisterWindowMessage(L"TabletInputPanelOpening");
497 mMessages[3] = ::RegisterWindowMessage(L"IHM Pen or Touch Event noticed");
498 mMessages[4] = ::RegisterWindowMessage(L"ProgrammabilityCaretVisibility");
499 mMessages[5] = ::RegisterWindowMessage(L"CaretTrackingUpdateIPHidden");
500 mMessages[6] = ::RegisterWindowMessage(L"CaretTrackingUpdateIPInfo");
502 mHook = ::SetWindowsHookEx(WH_GETMESSAGE, &TIPHook, nullptr,
503 ::GetCurrentThreadId());
504 MOZ_ASSERT(mHook);
506 if (!sSendMessageTimeoutWStub) {
507 sUser32Intercept.Init("user32.dll");
508 DebugOnly<bool> hooked = sSendMessageTimeoutWStub.Set(
509 sUser32Intercept, "SendMessageTimeoutW", &SendMessageTimeoutWHook);
510 MOZ_ASSERT(hooked);
514 class MOZ_RAII A11yInstantiationBlocker {
515 public:
516 A11yInstantiationBlocker() {
517 if (!TIPMessageHandler::sInstance) {
518 return;
520 ++TIPMessageHandler::sInstance->mA11yBlockCount;
523 ~A11yInstantiationBlocker() {
524 if (!TIPMessageHandler::sInstance) {
525 return;
527 MOZ_ASSERT(TIPMessageHandler::sInstance->mA11yBlockCount > 0);
528 --TIPMessageHandler::sInstance->mA11yBlockCount;
532 friend class A11yInstantiationBlocker;
534 static LRESULT CALLBACK TIPHook(int aCode, WPARAM aWParam, LPARAM aLParam) {
535 if (aCode < 0 || !sInstance) {
536 return ::CallNextHookEx(nullptr, aCode, aWParam, aLParam);
539 MSG* msg = reinterpret_cast<MSG*>(aLParam);
540 UINT& msgCode = msg->message;
542 for (uint32_t i = 0; i < ArrayLength(sInstance->mMessages); ++i) {
543 if (msgCode == sInstance->mMessages[i]) {
544 A11yInstantiationBlocker block;
545 return ::CallNextHookEx(nullptr, aCode, aWParam, aLParam);
549 return ::CallNextHookEx(nullptr, aCode, aWParam, aLParam);
552 static LRESULT WINAPI SendMessageTimeoutWHook(HWND aHwnd, UINT aMsgCode,
553 WPARAM aWParam, LPARAM aLParam,
554 UINT aFlags, UINT aTimeout,
555 PDWORD_PTR aMsgResult) {
556 // We don't want to handle this unless the message is a WM_GETOBJECT that we
557 // want to block, and the aHwnd is a nsWindow that belongs to the current
558 // (i.e., main) thread.
559 if (!aMsgResult || aMsgCode != WM_GETOBJECT ||
560 static_cast<LONG>(aLParam) != OBJID_CLIENT || !::NS_IsMainThread() ||
561 !WinUtils::GetNSWindowPtr(aHwnd) || !IsA11yBlocked()) {
562 return sSendMessageTimeoutWStub(aHwnd, aMsgCode, aWParam, aLParam, aFlags,
563 aTimeout, aMsgResult);
566 // In this case we want to fake the result that would happen if we had
567 // decided not to handle WM_GETOBJECT in our WndProc. We hand the message
568 // off to DefWindowProc to accomplish this.
569 *aMsgResult = static_cast<DWORD_PTR>(
570 ::DefWindowProcW(aHwnd, aMsgCode, aWParam, aLParam));
572 return static_cast<LRESULT>(TRUE);
575 static WindowsDllInterceptor::FuncHookType<decltype(&SendMessageTimeoutW)>
576 sSendMessageTimeoutWStub;
577 static StaticAutoPtr<TIPMessageHandler> sInstance;
579 HHOOK mHook;
580 UINT mMessages[7];
581 uint32_t mA11yBlockCount;
584 WindowsDllInterceptor::FuncHookType<decltype(&SendMessageTimeoutW)>
585 TIPMessageHandler::sSendMessageTimeoutWStub;
586 StaticAutoPtr<TIPMessageHandler> TIPMessageHandler::sInstance;
588 } // namespace mozilla
590 #endif // defined(ACCESSIBILITY)
592 namespace mozilla {
594 // This task will get the VirtualDesktopManager from the generic thread pool
595 // since doing this on the main thread on startup causes performance issues.
597 // See bug 1640852.
599 // This should be fine and should not require any locking, as when the main
600 // thread will access it, if it races with this function it will either find
601 // it to be null or to have a valid value.
602 class InitializeVirtualDesktopManagerTask : public Task {
603 public:
604 InitializeVirtualDesktopManagerTask()
605 : Task(Kind::OffMainThreadOnly, kDefaultPriorityValue) {}
607 #ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
608 bool GetName(nsACString& aName) override {
609 aName.AssignLiteral("InitializeVirtualDesktopManagerTask");
610 return true;
612 #endif
614 virtual TaskResult Run() override {
615 RefPtr<IVirtualDesktopManager> desktopManager;
616 HRESULT hr = ::CoCreateInstance(
617 CLSID_VirtualDesktopManager, NULL, CLSCTX_INPROC_SERVER,
618 __uuidof(IVirtualDesktopManager), getter_AddRefs(desktopManager));
619 if (FAILED(hr)) {
620 return TaskResult::Complete;
623 gVirtualDesktopManager = desktopManager;
624 return TaskResult::Complete;
628 // Ground-truth query: does Windows claim the window is cloaked right now?
629 static bool IsCloaked(HWND hwnd) {
630 DWORD cloakedState;
631 HRESULT hr = ::DwmGetWindowAttribute(hwnd, DWMWA_CLOAKED, &cloakedState,
632 sizeof(cloakedState));
634 if (FAILED(hr)) {
635 MOZ_LOG(sCloakingLog, LogLevel::Warning,
636 ("failed (%08lX) to query cloaking state for HWND %p", hr, hwnd));
637 return false;
640 return cloakedState != 0;
643 } // namespace mozilla
645 /**************************************************************
646 **************************************************************
648 ** BLOCK: nsIWidget impl.
650 ** nsIWidget interface implementation, broken down into
651 ** sections.
653 **************************************************************
654 **************************************************************/
656 /**************************************************************
658 * SECTION: nsWindow construction and destruction
660 **************************************************************/
662 nsWindow::nsWindow(bool aIsChildWindow)
663 : nsBaseWidget(BorderStyle::Default),
664 mBrush(::CreateSolidBrush(NSRGB_2_COLOREF(::GetSysColor(COLOR_BTNFACE)))),
665 mFrameState(std::in_place, this),
666 mIsChildWindow(aIsChildWindow),
667 mLastPaintEndTime(TimeStamp::Now()),
668 mCachedHitTestTime(TimeStamp::Now()),
669 mSizeConstraintsScale(GetDefaultScale().scale),
670 mDesktopId("DesktopIdMutex") {
671 MOZ_ASSERT(mWindowType == WindowType::Child);
673 if (!gInitializedVirtualDesktopManager) {
674 TaskController::Get()->AddTask(
675 MakeAndAddRef<InitializeVirtualDesktopManagerTask>());
676 gInitializedVirtualDesktopManager = true;
679 // Global initialization
680 if (!sInstanceCount) {
681 // Global app registration id for Win7 and up. See
682 // WinTaskbar.cpp for details.
683 // MSIX packages explicitly do not support setting the appid from within
684 // the app, as it is set in the package manifest instead.
685 if (!WinUtils::HasPackageIdentity()) {
686 mozilla::widget::WinTaskbar::RegisterAppUserModelID();
688 if (!StaticPrefs::ui_key_layout_load_when_first_needed()) {
689 KeyboardLayout::GetInstance()->OnLayoutChange(::GetKeyboardLayout(0));
691 #if defined(ACCESSIBILITY)
692 mozilla::TIPMessageHandler::Initialize();
693 #endif // defined(ACCESSIBILITY)
694 if (SUCCEEDED(::OleInitialize(nullptr))) {
695 sIsOleInitialized = true;
697 NS_ASSERTION(sIsOleInitialized, "***** OLE is not initialized!\n");
698 MouseScrollHandler::Initialize();
699 // Init theme data
700 nsUXThemeData::UpdateNativeThemeInfo();
701 RedirectedKeyDownMessageManager::Forget();
702 } // !sInstanceCount
704 sInstanceCount++;
707 nsWindow::~nsWindow() {
708 mInDtor = true;
710 // If the widget was released without calling Destroy() then the native window
711 // still exists, and we need to destroy it. Destroy() will early-return if it
712 // was already called. In any case it is important to call it before
713 // destroying mPresentLock (cf. 1156182).
714 Destroy();
716 // Free app icon resources. This must happen after `OnDestroy` (see bug
717 // 708033).
718 if (mIconSmall) ::DestroyIcon(mIconSmall);
720 if (mIconBig) ::DestroyIcon(mIconBig);
722 sInstanceCount--;
724 // Global shutdown
725 if (sInstanceCount == 0) {
726 IMEHandler::Terminate();
727 sCurrentCursor = {};
728 if (sIsOleInitialized) {
729 ::OleFlushClipboard();
730 ::OleUninitialize();
731 sIsOleInitialized = false;
735 NS_IF_RELEASE(mNativeDragTarget);
738 /**************************************************************
740 * SECTION: nsIWidget::Create, nsIWidget::Destroy
742 * Creating and destroying windows for this widget.
744 **************************************************************/
746 // Allow Derived classes to modify the height that is passed
747 // when the window is created or resized.
748 int32_t nsWindow::GetHeight(int32_t aProposedHeight) { return aProposedHeight; }
750 void nsWindow::SendAnAPZEvent(InputData& aEvent) {
751 LRESULT popupHandlingResult;
752 if (DealWithPopups(mWnd, MOZ_WM_DMANIP, 0, 0, &popupHandlingResult)) {
753 // We need to consume the event after using it to roll up the popup(s).
754 return;
757 if (mSwipeTracker && aEvent.mInputType == PANGESTURE_INPUT) {
758 // Give the swipe tracker a first pass at the event. If a new pan gesture
759 // has been started since the beginning of the swipe, the swipe tracker
760 // will know to ignore the event.
761 nsEventStatus status =
762 mSwipeTracker->ProcessEvent(aEvent.AsPanGestureInput());
763 if (status == nsEventStatus_eConsumeNoDefault) {
764 return;
768 APZEventResult result;
769 if (mAPZC) {
770 result = mAPZC->InputBridge()->ReceiveInputEvent(aEvent);
772 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
773 return;
776 MOZ_ASSERT(aEvent.mInputType == PANGESTURE_INPUT ||
777 aEvent.mInputType == PINCHGESTURE_INPUT);
779 if (aEvent.mInputType == PANGESTURE_INPUT) {
780 PanGestureInput& panInput = aEvent.AsPanGestureInput();
781 WidgetWheelEvent event = panInput.ToWidgetEvent(this);
782 if (!mAPZC) {
783 if (MayStartSwipeForNonAPZ(panInput)) {
784 return;
786 } else {
787 event = MayStartSwipeForAPZ(panInput, result);
790 ProcessUntransformedAPZEvent(&event, result);
792 return;
795 PinchGestureInput& pinchInput = aEvent.AsPinchGestureInput();
796 WidgetWheelEvent event = pinchInput.ToWidgetEvent(this);
797 ProcessUntransformedAPZEvent(&event, result);
800 void nsWindow::RecreateDirectManipulationIfNeeded() {
801 DestroyDirectManipulation();
803 if (mWindowType != WindowType::TopLevel && mWindowType != WindowType::Popup) {
804 return;
807 if (!(StaticPrefs::apz_allow_zooming() ||
808 StaticPrefs::apz_windows_use_direct_manipulation()) ||
809 StaticPrefs::apz_windows_force_disable_direct_manipulation()) {
810 return;
813 mDmOwner = MakeUnique<DirectManipulationOwner>(this);
815 LayoutDeviceIntRect bounds(mBounds.X(), mBounds.Y(), mBounds.Width(),
816 GetHeight(mBounds.Height()));
817 mDmOwner->Init(bounds);
820 void nsWindow::ResizeDirectManipulationViewport() {
821 if (mDmOwner) {
822 LayoutDeviceIntRect bounds(mBounds.X(), mBounds.Y(), mBounds.Width(),
823 GetHeight(mBounds.Height()));
824 mDmOwner->ResizeViewport(bounds);
828 void nsWindow::DestroyDirectManipulation() {
829 if (mDmOwner) {
830 mDmOwner->Destroy();
831 mDmOwner.reset();
835 // Create the proper widget
836 nsresult nsWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
837 const LayoutDeviceIntRect& aRect,
838 widget::InitData* aInitData) {
839 // Historical note: there was once some belief and/or intent that nsWindows
840 // could be created on arbitrary threads, and this may still be reflected in
841 // some comments.
842 MOZ_ASSERT(NS_IsMainThread());
844 widget::InitData defaultInitData;
845 if (!aInitData) aInitData = &defaultInitData;
847 nsIWidget* baseParent =
848 aInitData->mWindowType == WindowType::Dialog ||
849 aInitData->mWindowType == WindowType::TopLevel ||
850 aInitData->mWindowType == WindowType::Invisible
851 ? nullptr
852 : aParent;
854 mIsTopWidgetWindow = (nullptr == baseParent);
855 mBounds = aRect;
857 // Ensure that the toolkit is created.
858 nsToolkit::GetToolkit();
860 BaseCreate(baseParent, aInitData);
862 HWND parent;
863 if (aParent) { // has a nsIWidget parent
864 parent = aParent ? (HWND)aParent->GetNativeData(NS_NATIVE_WINDOW) : nullptr;
865 mParent = aParent;
866 } else { // has a nsNative parent
867 parent = (HWND)aNativeParent;
868 mParent =
869 aNativeParent ? WinUtils::GetNSWindowPtr((HWND)aNativeParent) : nullptr;
872 mIsRTL = aInitData->mRTL;
873 mOpeningAnimationSuppressed = aInitData->mIsAnimationSuppressed;
874 mAlwaysOnTop = aInitData->mAlwaysOnTop;
875 mIsAlert = aInitData->mIsAlert;
876 mResizable = aInitData->mResizable;
878 DWORD style = WindowStyle();
879 DWORD extendedStyle = WindowExStyle();
881 if (mWindowType == WindowType::Popup) {
882 if (!aParent) {
883 parent = nullptr;
885 } else if (mWindowType == WindowType::Invisible) {
886 // Make sure CreateWindowEx succeeds at creating a toplevel window
887 style &= ~0x40000000; // WS_CHILDWINDOW
888 } else {
889 // See if the caller wants to explictly set clip children and clip siblings
890 if (aInitData->mClipChildren) {
891 style |= WS_CLIPCHILDREN;
892 } else {
893 style &= ~WS_CLIPCHILDREN;
895 if (aInitData->mClipSiblings) {
896 style |= WS_CLIPSIBLINGS;
900 const wchar_t* className = ChooseWindowClass(mWindowType);
902 // Take specific actions when creating the first top-level window
903 static bool sFirstTopLevelWindowCreated = false;
904 if (aInitData->mWindowType == WindowType::TopLevel && !aParent &&
905 !sFirstTopLevelWindowCreated) {
906 sFirstTopLevelWindowCreated = true;
907 mWnd = ConsumePreXULSkeletonUIHandle();
908 auto skeletonUIError = GetPreXULSkeletonUIErrorReason();
909 if (skeletonUIError) {
910 nsAutoString errorString(
911 GetPreXULSkeletonUIErrorString(skeletonUIError.value()));
912 Telemetry::ScalarSet(
913 Telemetry::ScalarID::STARTUP_SKELETON_UI_DISABLED_REASON,
914 errorString);
916 if (mWnd) {
917 MOZ_ASSERT(style == kPreXULSkeletonUIWindowStyle,
918 "The skeleton UI window style should match the expected "
919 "style for the first window created");
920 MOZ_ASSERT(extendedStyle == kPreXULSkeletonUIWindowStyleEx,
921 "The skeleton UI window extended style should match the "
922 "expected extended style for the first window created");
923 MOZ_ASSERT(
924 ::GetWindowThreadProcessId(mWnd, nullptr) == ::GetCurrentThreadId(),
925 "The skeleton UI window should be created on the same thread as "
926 "other windows");
927 mIsShowingPreXULSkeletonUI = true;
929 // If we successfully consumed the pre-XUL skeleton UI, just update
930 // our internal state to match what is currently being displayed.
931 mIsVisible = true;
932 mIsCloaked = mozilla::IsCloaked(mWnd);
933 mFrameState->ConsumePreXULSkeletonState(WasPreXULSkeletonUIMaximized());
935 // These match the margins set in browser-tabsintitlebar.js with
936 // default prefs on Windows. Bug 1673092 tracks lining this up with
937 // that more correctly instead of hard-coding it.
938 SetNonClientMargins(LayoutDeviceIntMargin(0, 2, 2, 2));
940 // Reset the WNDPROC for this window and its whole class, as we had
941 // to use our own WNDPROC when creating the the skeleton UI window.
942 ::SetWindowLongPtrW(mWnd, GWLP_WNDPROC,
943 reinterpret_cast<LONG_PTR>(
944 WinUtils::NonClientDpiScalingDefWindowProcW));
945 ::SetClassLongPtrW(mWnd, GCLP_WNDPROC,
946 reinterpret_cast<LONG_PTR>(
947 WinUtils::NonClientDpiScalingDefWindowProcW));
951 if (!mWnd) {
952 mWnd =
953 ::CreateWindowExW(extendedStyle, className, L"", style, aRect.X(),
954 aRect.Y(), aRect.Width(), GetHeight(aRect.Height()),
955 parent, nullptr, nsToolkit::mDllInstance, nullptr);
958 if (!mWnd) {
959 NS_WARNING("nsWindow CreateWindowEx failed.");
960 return NS_ERROR_FAILURE;
963 if (!sWinCloakEventHook) {
964 MOZ_LOG(sCloakingLog, LogLevel::Info, ("Registering cloaking event hook"));
966 // C++03 lambda approximation until P2173R1 is available (-std=c++2b)
967 struct StdcallLambda {
968 static void CALLBACK OnCloakUncloakHook(HWINEVENTHOOK hWinEventHook,
969 DWORD event, HWND hwnd,
970 LONG idObject, LONG idChild,
971 DWORD idEventThread,
972 DWORD dwmsEventTime) {
973 const bool isCloaked = event == EVENT_OBJECT_CLOAKED ? true : false;
974 nsWindow::OnCloakEvent(hwnd, isCloaked);
978 const HWINEVENTHOOK hook = ::SetWinEventHook(
979 EVENT_OBJECT_CLOAKED, EVENT_OBJECT_UNCLOAKED, HMODULE(nullptr),
980 &StdcallLambda::OnCloakUncloakHook, ::GetCurrentProcessId(),
981 ::GetCurrentThreadId(), WINEVENT_OUTOFCONTEXT);
982 sWinCloakEventHook = Some(hook);
984 if (!hook) {
985 const DWORD err = ::GetLastError();
986 MOZ_LOG(sCloakingLog, LogLevel::Error,
987 ("Failed to register cloaking event hook! GLE = %lu (0x%lX)", err,
988 err));
992 if (aInitData->mIsPrivate) {
993 if (NimbusFeatures::GetBool("majorRelease2022"_ns,
994 "feltPrivacyWindowSeparation"_ns, true) &&
995 // Although permanent Private Browsing mode is indeed Private Browsing,
996 // we choose to make it look like regular Firefox in terms of the icon
997 // it uses (which also means we shouldn't use the Private Browsing
998 // AUMID).
999 !StaticPrefs::browser_privatebrowsing_autostart()) {
1000 RefPtr<IPropertyStore> pPropStore;
1001 if (!FAILED(SHGetPropertyStoreForWindow(mWnd, IID_IPropertyStore,
1002 getter_AddRefs(pPropStore)))) {
1003 PROPVARIANT pv;
1004 nsAutoString aumid;
1005 // make sure we're using the private browsing AUMID so that taskbar
1006 // grouping works properly
1007 Unused << NS_WARN_IF(
1008 !mozilla::widget::WinTaskbar::GenerateAppUserModelID(aumid, true));
1009 if (!FAILED(InitPropVariantFromString(aumid.get(), &pv))) {
1010 if (!FAILED(pPropStore->SetValue(PKEY_AppUserModel_ID, pv))) {
1011 pPropStore->Commit();
1014 PropVariantClear(&pv);
1017 HICON icon = ::LoadIconW(::GetModuleHandleW(nullptr),
1018 MAKEINTRESOURCEW(IDI_PBMODE));
1019 SetBigIcon(icon);
1020 SetSmallIcon(icon);
1024 mDeviceNotifyHandle = InputDeviceUtils::RegisterNotification(mWnd);
1026 // If mDefaultScale is set before mWnd has been set, it will have the scale of
1027 // the primary monitor, rather than the monitor that the window is actually
1028 // on. For non-popup windows this gets corrected by the WM_DPICHANGED message
1029 // which resets mDefaultScale, but for popup windows we don't reset
1030 // mDefaultScale on that message. In order to ensure that popup windows
1031 // spawned on a non-primary monitor end up with the correct scale, we reset
1032 // mDefaultScale here so that it gets recomputed using the correct monitor now
1033 // that we have a mWnd.
1034 mDefaultScale = -1.0;
1036 if (mIsRTL) {
1037 DWORD dwAttribute = TRUE;
1038 DwmSetWindowAttribute(mWnd, DWMWA_NONCLIENT_RTL_LAYOUT, &dwAttribute,
1039 sizeof dwAttribute);
1042 UpdateDarkModeToolbar();
1044 if (mOpeningAnimationSuppressed) {
1045 SuppressAnimation(true);
1048 if (mAlwaysOnTop) {
1049 ::SetWindowPos(mWnd, HWND_TOPMOST, 0, 0, 0, 0,
1050 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
1053 if (mWindowType != WindowType::Invisible &&
1054 MouseScrollHandler::Device::IsFakeScrollableWindowNeeded()) {
1055 // Ugly Thinkpad Driver Hack (Bugs 507222 and 594977)
1057 // We create two zero-sized windows as descendants of the top-level window,
1058 // like so:
1060 // Top-level window (MozillaWindowClass)
1061 // FAKETRACKPOINTSCROLLCONTAINER (MozillaWindowClass)
1062 // FAKETRACKPOINTSCROLLABLE (MozillaWindowClass)
1064 // We need to have the middle window, otherwise the Trackpoint driver
1065 // will fail to deliver scroll messages. WM_MOUSEWHEEL messages are
1066 // sent to the FAKETRACKPOINTSCROLLABLE, which then propagate up the
1067 // window hierarchy until they are handled by nsWindow::WindowProc.
1068 // WM_HSCROLL messages are also sent to the FAKETRACKPOINTSCROLLABLE,
1069 // but these do not propagate automatically, so we have the window
1070 // procedure pretend that they were dispatched to the top-level window
1071 // instead.
1073 // The FAKETRACKPOINTSCROLLABLE needs to have the specific window styles it
1074 // is given below so that it catches the Trackpoint driver's heuristics.
1075 HWND scrollContainerWnd = ::CreateWindowW(
1076 className, L"FAKETRACKPOINTSCROLLCONTAINER", WS_CHILD | WS_VISIBLE, 0,
1077 0, 0, 0, mWnd, nullptr, nsToolkit::mDllInstance, nullptr);
1078 HWND scrollableWnd = ::CreateWindowW(
1079 className, L"FAKETRACKPOINTSCROLLABLE",
1080 WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_TABSTOP | 0x30, 0, 0, 0, 0,
1081 scrollContainerWnd, nullptr, nsToolkit::mDllInstance, nullptr);
1083 // Give the FAKETRACKPOINTSCROLLABLE window a specific ID so that
1084 // WindowProcInternal can distinguish it from the top-level window
1085 // easily.
1086 ::SetWindowLongPtrW(scrollableWnd, GWLP_ID, eFakeTrackPointScrollableID);
1088 // Make FAKETRACKPOINTSCROLLABLE use nsWindow::WindowProc, and store the
1089 // old window procedure in its "user data".
1090 WNDPROC oldWndProc = (WNDPROC)::SetWindowLongPtrW(
1091 scrollableWnd, GWLP_WNDPROC, (LONG_PTR)nsWindow::WindowProc);
1092 ::SetWindowLongPtrW(scrollableWnd, GWLP_USERDATA, (LONG_PTR)oldWndProc);
1095 // We will start receiving native events after associating with our native
1096 // window. We will also become the output of WinUtils::GetNSWindowPtr for that
1097 // window.
1098 if (!AssociateWithNativeWindow()) {
1099 return NS_ERROR_FAILURE;
1102 // Starting with Windows XP, a process always runs within a terminal services
1103 // session. In order to play nicely with RDP, fast user switching, and the
1104 // lock screen, we should be handling WM_WTSSESSION_CHANGE. We must register
1105 // our HWND in order to receive this message.
1106 DebugOnly<BOOL> wtsRegistered =
1107 ::WTSRegisterSessionNotification(mWnd, NOTIFY_FOR_THIS_SESSION);
1108 NS_ASSERTION(wtsRegistered, "WTSRegisterSessionNotification failed!\n");
1110 mDefaultIMC.Init(this);
1111 IMEHandler::InitInputContext(this, mInputContext);
1113 static bool a11yPrimed = false;
1114 if (!a11yPrimed && mWindowType == WindowType::TopLevel) {
1115 a11yPrimed = true;
1116 if (Preferences::GetInt("accessibility.force_disabled", 0) == -1) {
1117 ::PostMessage(mWnd, MOZ_WM_STARTA11Y, 0, 0);
1121 RecreateDirectManipulationIfNeeded();
1123 return NS_OK;
1126 void nsWindow::LocalesChanged() {
1127 bool isRTL = intl::LocaleService::GetInstance()->IsAppLocaleRTL();
1128 if (mIsRTL != isRTL) {
1129 DWORD dwAttribute = isRTL;
1130 DwmSetWindowAttribute(mWnd, DWMWA_NONCLIENT_RTL_LAYOUT, &dwAttribute,
1131 sizeof dwAttribute);
1132 mIsRTL = isRTL;
1136 // Close this nsWindow
1137 void nsWindow::Destroy() {
1138 // WM_DESTROY has already fired, avoid calling it twice
1139 if (mOnDestroyCalled) return;
1141 // Don't destroy windows that have file pickers open, we'll tear these down
1142 // later once the picker is closed.
1143 mDestroyCalled = true;
1144 if (mPickerDisplayCount) return;
1146 // During the destruction of all of our children, make sure we don't get
1147 // deleted.
1148 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
1150 DestroyDirectManipulation();
1153 * On windows the LayerManagerOGL destructor wants the widget to be around for
1154 * cleanup. It also would like to have the HWND intact, so we nullptr it here.
1156 DestroyLayerManager();
1158 InputDeviceUtils::UnregisterNotification(mDeviceNotifyHandle);
1159 mDeviceNotifyHandle = nullptr;
1161 // The DestroyWindow function destroys the specified window. The function
1162 // sends WM_DESTROY and WM_NCDESTROY messages to the window to deactivate it
1163 // and remove the keyboard focus from it. The function also destroys the
1164 // window's menu, flushes the thread message queue, destroys timers, removes
1165 // clipboard ownership, and breaks the clipboard viewer chain (if the window
1166 // is at the top of the viewer chain).
1168 // If the specified window is a parent or owner window, DestroyWindow
1169 // automatically destroys the associated child or owned windows when it
1170 // destroys the parent or owner window. The function first destroys child or
1171 // owned windows, and then it destroys the parent or owner window.
1172 VERIFY(::DestroyWindow(mWnd));
1174 // Our windows can be subclassed which may prevent us receiving WM_DESTROY. If
1175 // OnDestroy() didn't get called, call it now.
1176 if (false == mOnDestroyCalled) {
1177 MSGResult msgResult;
1178 mWindowHook.Notify(mWnd, WM_DESTROY, 0, 0, msgResult);
1179 OnDestroy();
1183 /**************************************************************
1185 * SECTION: Window class utilities
1187 * Utilities for calculating the proper window class name for
1188 * Create window.
1190 **************************************************************/
1192 /* static */
1193 const wchar_t* nsWindow::RegisterWindowClass(const wchar_t* aClassName,
1194 UINT aExtraStyle, LPWSTR aIconID) {
1195 WNDCLASSW wc;
1196 if (::GetClassInfoW(nsToolkit::mDllInstance, aClassName, &wc)) {
1197 // already registered
1198 return aClassName;
1201 wc.style = CS_DBLCLKS | aExtraStyle;
1202 wc.lpfnWndProc = WinUtils::NonClientDpiScalingDefWindowProcW;
1203 wc.cbClsExtra = 0;
1204 wc.cbWndExtra = 0;
1205 wc.hInstance = nsToolkit::mDllInstance;
1206 wc.hIcon =
1207 aIconID ? ::LoadIconW(::GetModuleHandleW(nullptr), aIconID) : nullptr;
1208 wc.hCursor = nullptr;
1209 wc.hbrBackground = nullptr;
1210 wc.lpszMenuName = nullptr;
1211 wc.lpszClassName = aClassName;
1213 if (!::RegisterClassW(&wc)) {
1214 // For older versions of Win32 (i.e., not XP), the registration may
1215 // fail with aExtraStyle, so we have to re-register without it.
1216 wc.style = CS_DBLCLKS;
1217 ::RegisterClassW(&wc);
1219 return aClassName;
1222 static LPWSTR const gStockApplicationIcon = MAKEINTRESOURCEW(32512);
1224 /* static */
1225 const wchar_t* nsWindow::ChooseWindowClass(WindowType aWindowType) {
1226 const wchar_t* className = [aWindowType] {
1227 switch (aWindowType) {
1228 case WindowType::Invisible:
1229 return kClassNameHidden;
1230 case WindowType::Dialog:
1231 return kClassNameDialog;
1232 case WindowType::Popup:
1233 return kClassNameDropShadow;
1234 default:
1235 return GetMainWindowClass();
1237 }();
1238 return RegisterWindowClass(className, 0, gStockApplicationIcon);
1241 /**************************************************************
1243 * SECTION: Window styles utilities
1245 * Return the proper windows styles and extended styles.
1247 **************************************************************/
1249 const DWORD kTitlebarItemsWindowStyles =
1250 WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
1251 const DWORD kAllBorderStyles =
1252 kTitlebarItemsWindowStyles | WS_THICKFRAME | WS_DLGFRAME;
1254 static DWORD WindowStylesRemovedForBorderStyle(BorderStyle aStyle) {
1255 if (aStyle == BorderStyle::Default || aStyle == BorderStyle::All) {
1256 return 0;
1258 if (aStyle == BorderStyle::None) {
1259 return kAllBorderStyles;
1261 DWORD toRemove = 0;
1262 if (!(aStyle & BorderStyle::Border)) {
1263 toRemove |= WS_BORDER;
1265 if (!(aStyle & BorderStyle::Title)) {
1266 toRemove |= WS_DLGFRAME;
1268 if (!(aStyle & (BorderStyle::Menu | BorderStyle::Close))) {
1269 // Looks like getting rid of the system menu also does away with the close
1270 // box. So, we only get rid of the system menu and the close box if you
1271 // want neither. How does the Windows "Dialog" window class get just
1272 // closebox and no sysmenu? Who knows.
1273 toRemove |= WS_SYSMENU;
1275 if (!(aStyle & BorderStyle::ResizeH)) {
1276 toRemove |= WS_THICKFRAME;
1278 if (!(aStyle & BorderStyle::Minimize)) {
1279 toRemove |= WS_MINIMIZEBOX;
1281 if (!(aStyle & BorderStyle::Maximize)) {
1282 toRemove |= WS_MAXIMIZEBOX;
1284 return toRemove;
1287 // Return nsWindow styles
1288 DWORD nsWindow::WindowStyle() {
1289 DWORD style;
1290 switch (mWindowType) {
1291 case WindowType::Child:
1292 style = WS_OVERLAPPED;
1293 break;
1295 case WindowType::Dialog:
1296 style = WS_OVERLAPPED | WS_BORDER | WS_DLGFRAME | WS_SYSMENU | DS_3DLOOK |
1297 DS_MODALFRAME | WS_CLIPCHILDREN;
1298 if (mBorderStyle != BorderStyle::Default) {
1299 style |= WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX;
1301 break;
1303 case WindowType::Popup:
1304 style = WS_OVERLAPPED | WS_POPUP;
1305 break;
1307 default:
1308 NS_ERROR("unknown border style");
1309 [[fallthrough]];
1311 case WindowType::TopLevel:
1312 case WindowType::Invisible:
1313 style = WS_OVERLAPPED | WS_CLIPCHILDREN | WS_DLGFRAME | WS_BORDER |
1314 WS_THICKFRAME | kTitlebarItemsWindowStyles;
1315 break;
1318 style &= ~WindowStylesRemovedForBorderStyle(mBorderStyle);
1320 if (mIsChildWindow) {
1321 style |= WS_CLIPCHILDREN;
1322 if (!(style & WS_POPUP)) {
1323 style |= WS_CHILD; // WS_POPUP and WS_CHILD are mutually exclusive.
1327 VERIFY_WINDOW_STYLE(style);
1328 return style;
1331 // Return nsWindow extended styles
1332 DWORD nsWindow::WindowExStyle() {
1333 switch (mWindowType) {
1334 case WindowType::Child:
1335 return 0;
1336 case WindowType::Popup: {
1337 DWORD extendedStyle = WS_EX_TOOLWINDOW;
1338 if (mPopupLevel == PopupLevel::Top) {
1339 extendedStyle |= WS_EX_TOPMOST;
1341 return extendedStyle;
1343 case WindowType::Dialog:
1344 case WindowType::TopLevel:
1345 case WindowType::Invisible:
1346 break;
1348 if (mIsAlert) {
1349 MOZ_ASSERT(mWindowType == WindowType::Dialog,
1350 "Expect alert windows to have type=dialog");
1351 return WS_EX_TOOLWINDOW | WS_EX_TOPMOST;
1353 return WS_EX_WINDOWEDGE;
1356 /**************************************************************
1358 * SECTION: Native window association utilities
1360 * Used in Create and Destroy. A nsWindow can associate with its
1361 * underlying native window mWnd. Once a native window is
1362 * associated with a nsWindow, its native events will be handled
1363 * by the static member function nsWindow::WindowProc. Moreover,
1364 * the association will be registered in the WinUtils association
1365 * list, that is, calling WinUtils::GetNSWindowPtr on the native
1366 * window will return the associated nsWindow. This is used in
1367 * nsWindow::WindowProc to correctly dispatch native events to
1368 * the handler methods defined in nsWindow, even though it is a
1369 * static member function.
1371 * After dissociation, the native events of the native window will
1372 * no longer be handled by nsWindow::WindowProc, and will thus not
1373 * be dispatched to the nsWindow native event handler methods.
1374 * Moreover, the association will no longer be registered in the
1375 * WinUtils association list, so calling WinUtils::GetNSWindowPtr
1376 * on the native window will return nullptr.
1378 **************************************************************/
1380 bool nsWindow::AssociateWithNativeWindow() {
1381 if (!mWnd || !IsWindow(mWnd)) {
1382 NS_ERROR("Invalid window handle");
1383 return false;
1386 // Connect the this pointer to the native window handle.
1387 // This should be done before SetWindowLongPtrW, because nsWindow::WindowProc
1388 // uses WinUtils::GetNSWindowPtr internally.
1389 WinUtils::SetNSWindowPtr(mWnd, this);
1391 ::SetLastError(ERROR_SUCCESS);
1392 const auto prevWndProc = reinterpret_cast<WNDPROC>(::SetWindowLongPtrW(
1393 mWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(nsWindow::WindowProc)));
1394 if (!prevWndProc && GetLastError() != ERROR_SUCCESS) {
1395 NS_ERROR("Failure in SetWindowLongPtrW");
1396 WinUtils::SetNSWindowPtr(mWnd, nullptr);
1397 return false;
1400 mPrevWndProc.emplace(prevWndProc);
1401 return true;
1404 void nsWindow::DissociateFromNativeWindow() {
1405 if (!mWnd || !IsWindow(mWnd) || mPrevWndProc.isNothing()) {
1406 return;
1409 DebugOnly<WNDPROC> wndProcBeforeDissociate =
1410 reinterpret_cast<WNDPROC>(::SetWindowLongPtrW(
1411 mWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(*mPrevWndProc)));
1412 NS_ASSERTION(wndProcBeforeDissociate == nsWindow::WindowProc,
1413 "Unstacked an unexpected native window procedure");
1415 WinUtils::SetNSWindowPtr(mWnd, nullptr);
1416 mPrevWndProc.reset();
1419 /**************************************************************
1421 * SECTION: nsIWidget::SetParent, nsIWidget::GetParent
1423 * Set or clear the parent widgets using window properties, and
1424 * handles calculating native parent handles.
1426 **************************************************************/
1428 // Get and set parent widgets
1429 void nsWindow::SetParent(nsIWidget* aNewParent) {
1430 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
1431 nsIWidget* parent = GetParent();
1432 if (parent) {
1433 parent->RemoveChild(this);
1436 mParent = aNewParent;
1438 if (aNewParent) {
1439 ReparentNativeWidget(aNewParent);
1440 aNewParent->AddChild(this);
1441 return;
1443 if (mWnd) {
1444 // If we have no parent, SetParent should return the desktop.
1445 VERIFY(::SetParent(mWnd, nullptr));
1446 RecreateDirectManipulationIfNeeded();
1450 void nsWindow::ReparentNativeWidget(nsIWidget* aNewParent) {
1451 MOZ_ASSERT(aNewParent, "null widget");
1453 mParent = aNewParent;
1454 if (mWindowType == WindowType::Popup) {
1455 return;
1457 HWND newParent = (HWND)aNewParent->GetNativeData(NS_NATIVE_WINDOW);
1458 NS_ASSERTION(newParent, "Parent widget has a null native window handle");
1459 if (newParent && mWnd) {
1460 ::SetParent(mWnd, newParent);
1461 RecreateDirectManipulationIfNeeded();
1465 nsIWidget* nsWindow::GetParent(void) {
1466 if (mIsTopWidgetWindow) {
1467 return nullptr;
1469 if (mInDtor || mOnDestroyCalled) {
1470 return nullptr;
1472 return mParent;
1475 static int32_t RoundDown(double aDouble) {
1476 return aDouble > 0 ? static_cast<int32_t>(floor(aDouble))
1477 : static_cast<int32_t>(ceil(aDouble));
1480 float nsWindow::GetDPI() {
1481 float dpi = 96.0f;
1482 nsCOMPtr<nsIScreen> screen = GetWidgetScreen();
1483 if (screen) {
1484 screen->GetDpi(&dpi);
1486 return dpi;
1489 double nsWindow::GetDefaultScaleInternal() {
1490 if (mDefaultScale <= 0.0) {
1491 mDefaultScale = WinUtils::LogToPhysFactor(mWnd);
1493 return mDefaultScale;
1496 int32_t nsWindow::LogToPhys(double aValue) {
1497 return WinUtils::LogToPhys(
1498 ::MonitorFromWindow(mWnd, MONITOR_DEFAULTTOPRIMARY), aValue);
1501 nsWindow* nsWindow::GetParentWindow(bool aIncludeOwner) {
1502 return static_cast<nsWindow*>(GetParentWindowBase(aIncludeOwner));
1505 nsWindow* nsWindow::GetParentWindowBase(bool aIncludeOwner) {
1506 if (mIsTopWidgetWindow) {
1507 // Must use a flag instead of mWindowType to tell if the window is the
1508 // owned by the topmost widget, because a child window can be embedded
1509 // inside a HWND which is not associated with a nsIWidget.
1510 return nullptr;
1513 // If this widget has already been destroyed, pretend we have no parent.
1514 // This corresponds to code in Destroy which removes the destroyed
1515 // widget from its parent's child list.
1516 if (mInDtor || mOnDestroyCalled) return nullptr;
1518 // aIncludeOwner set to true implies walking the parent chain to retrieve the
1519 // root owner. aIncludeOwner set to false implies the search will stop at the
1520 // true parent (default).
1521 nsWindow* widget = nullptr;
1522 if (mWnd) {
1523 HWND parent = nullptr;
1524 if (aIncludeOwner)
1525 parent = ::GetParent(mWnd);
1526 else
1527 parent = ::GetAncestor(mWnd, GA_PARENT);
1529 if (parent) {
1530 widget = WinUtils::GetNSWindowPtr(parent);
1531 if (widget) {
1532 // If the widget is in the process of being destroyed then
1533 // do NOT return it
1534 if (widget->mInDtor) {
1535 widget = nullptr;
1541 return widget;
1544 /**************************************************************
1546 * SECTION: nsIWidget::Show
1548 * Hide or show this component.
1550 **************************************************************/
1552 void nsWindow::Show(bool bState) {
1553 if (bState && mIsShowingPreXULSkeletonUI) {
1554 // The first time we decide to actually show the window is when we decide
1555 // that we've taken over the window from the skeleton UI, and we should
1556 // no longer treat resizes / moves specially.
1557 mIsShowingPreXULSkeletonUI = false;
1558 #if defined(ACCESSIBILITY)
1559 // If our HWND has focus and the a11y engine hasn't started yet, fire a
1560 // focus win event. Windows already did this when the skeleton UI appeared,
1561 // but a11y wouldn't have been able to start at that point even if a client
1562 // responded. Firing this now gives clients the chance to respond with
1563 // WM_GETOBJECT, which will trigger the a11y engine. We don't want to do
1564 // this if the a11y engine has already started because it has probably
1565 // already fired focus on a descendant.
1566 if (::GetFocus() == mWnd && !GetAccService()) {
1567 ::NotifyWinEvent(EVENT_OBJECT_FOCUS, mWnd, OBJID_CLIENT, CHILDID_SELF);
1569 #endif // defined(ACCESSIBILITY)
1572 if (mWindowType == WindowType::Popup) {
1573 MOZ_ASSERT(ChooseWindowClass(mWindowType) == kClassNameDropShadow);
1574 // WS_EX_COMPOSITED conflicts with the WS_EX_LAYERED style and causes
1575 // some popup menus to become invisible.
1576 LONG_PTR exStyle = ::GetWindowLongPtrW(mWnd, GWL_EXSTYLE);
1577 if (exStyle & WS_EX_LAYERED) {
1578 ::SetWindowLongPtrW(mWnd, GWL_EXSTYLE, exStyle & ~WS_EX_COMPOSITED);
1582 bool syncInvalidate = false;
1584 bool wasVisible = mIsVisible;
1585 // Set the status now so that anyone asking during ShowWindow or
1586 // SetWindowPos would get the correct answer.
1587 mIsVisible = bState;
1589 if (mWnd) {
1590 if (bState) {
1591 if (!wasVisible && mWindowType == WindowType::TopLevel) {
1592 // speed up the initial paint after show for
1593 // top level windows:
1594 syncInvalidate = true;
1596 // Set the cursor before showing the window to avoid the default wait
1597 // cursor.
1598 SetCursor(Cursor{eCursor_standard});
1600 switch (mFrameState->GetSizeMode()) {
1601 case nsSizeMode_Fullscreen:
1602 ::ShowWindow(mWnd, SW_SHOW);
1603 break;
1604 case nsSizeMode_Maximized:
1605 ::ShowWindow(mWnd, SW_SHOWMAXIMIZED);
1606 break;
1607 case nsSizeMode_Minimized:
1608 ::ShowWindow(mWnd, SW_SHOWMINIMIZED);
1609 break;
1610 default:
1611 if (CanTakeFocus() && !mAlwaysOnTop) {
1612 ::ShowWindow(mWnd, SW_SHOWNORMAL);
1613 } else {
1614 ::ShowWindow(mWnd, SW_SHOWNOACTIVATE);
1615 // Don't flicker the window if we're restoring session
1616 if (!sIsRestoringSession) {
1617 Unused << GetAttention(2);
1620 break;
1622 } else {
1623 DWORD flags = SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW;
1624 if (wasVisible) {
1625 flags |= SWP_NOZORDER;
1627 if (mAlwaysOnTop || mIsAlert) {
1628 flags |= SWP_NOACTIVATE;
1631 if (mWindowType == WindowType::Popup) {
1632 // ensure popups are the topmost of the TOPMOST
1633 // layer. Remember not to set the SWP_NOZORDER
1634 // flag as that might allow the taskbar to overlap
1635 // the popup.
1636 flags |= SWP_NOACTIVATE;
1637 HWND owner = ::GetWindow(mWnd, GW_OWNER);
1638 if (owner) {
1639 // PopupLevel::Top popups should be above all else. All other
1640 // types should be placed in front of their owner, without
1641 // changing the owner's z-level relative to other windows.
1642 if (mPopupLevel != PopupLevel::Top) {
1643 ::SetWindowPos(mWnd, owner, 0, 0, 0, 0, flags);
1644 ::SetWindowPos(owner, mWnd, 0, 0, 0, 0,
1645 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
1646 } else {
1647 ::SetWindowPos(mWnd, HWND_TOP, 0, 0, 0, 0, flags);
1649 } else {
1650 ::SetWindowPos(mWnd, HWND_TOPMOST, 0, 0, 0, 0, flags);
1652 } else {
1653 if (mWindowType == WindowType::Dialog && !CanTakeFocus())
1654 flags |= SWP_NOACTIVATE;
1656 ::SetWindowPos(mWnd, HWND_TOP, 0, 0, 0, 0, flags);
1659 } else {
1660 // Clear contents to avoid ghosting of old content if we display
1661 // this window again.
1662 if (wasVisible && mTransparencyMode == TransparencyMode::Transparent) {
1663 if (mCompositorWidgetDelegate) {
1664 mCompositorWidgetDelegate->ClearTransparentWindow();
1667 if (mWindowType != WindowType::Dialog) {
1668 ::ShowWindow(mWnd, SW_HIDE);
1669 } else {
1670 ::SetWindowPos(mWnd, 0, 0, 0, 0, 0,
1671 SWP_HIDEWINDOW | SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER |
1672 SWP_NOACTIVATE);
1677 if (!wasVisible && bState) {
1678 Invalidate();
1679 if (syncInvalidate && !mInDtor && !mOnDestroyCalled) {
1680 ::UpdateWindow(mWnd);
1684 if (mOpeningAnimationSuppressed) {
1685 SuppressAnimation(false);
1689 /**************************************************************
1691 * SECTION: nsIWidget::IsVisible
1693 * Returns the visibility state.
1695 **************************************************************/
1697 // Return true if the component is visible, false otherwise.
1699 // This does not take cloaking into account.
1700 bool nsWindow::IsVisible() const { return mIsVisible; }
1702 /**************************************************************
1704 * SECTION: Touch and APZ-related functions
1706 **************************************************************/
1708 void nsWindow::RegisterTouchWindow() {
1709 mTouchWindow = true;
1710 ::RegisterTouchWindow(mWnd, TWF_WANTPALM);
1711 ::EnumChildWindows(mWnd, nsWindow::RegisterTouchForDescendants, 0);
1714 BOOL CALLBACK nsWindow::RegisterTouchForDescendants(HWND aWnd, LPARAM aMsg) {
1715 nsWindow* win = WinUtils::GetNSWindowPtr(aWnd);
1716 if (win) {
1717 ::RegisterTouchWindow(aWnd, TWF_WANTPALM);
1719 return TRUE;
1722 void nsWindow::LockAspectRatio(bool aShouldLock) {
1723 if (aShouldLock) {
1724 mAspectRatio = (float)mBounds.Width() / (float)mBounds.Height();
1725 } else {
1726 mAspectRatio = 0.0;
1730 /**************************************************************
1732 * SECTION: nsIWidget::SetInputRegion
1734 * Sets whether the window should ignore mouse events.
1736 **************************************************************/
1737 void nsWindow::SetInputRegion(const InputRegion& aInputRegion) {
1738 mInputRegion = aInputRegion;
1741 /**************************************************************
1743 * SECTION: nsIWidget::Move, nsIWidget::Resize, nsIWidget::Size
1745 * Repositioning and sizing a window.
1747 **************************************************************/
1749 void nsWindow::SetSizeConstraints(const SizeConstraints& aConstraints) {
1750 SizeConstraints c = aConstraints;
1752 if (mWindowType != WindowType::Popup && mResizable) {
1753 c.mMinSize.width =
1754 std::max(int32_t(::GetSystemMetrics(SM_CXMINTRACK)), c.mMinSize.width);
1755 c.mMinSize.height =
1756 std::max(int32_t(::GetSystemMetrics(SM_CYMINTRACK)), c.mMinSize.height);
1759 if (mMaxTextureSize > 0) {
1760 // We can't make ThebesLayers bigger than this anyway.. no point it letting
1761 // a window grow bigger as we won't be able to draw content there in
1762 // general.
1763 c.mMaxSize.width = std::min(c.mMaxSize.width, mMaxTextureSize);
1764 c.mMaxSize.height = std::min(c.mMaxSize.height, mMaxTextureSize);
1767 mSizeConstraintsScale = GetDefaultScale().scale;
1769 nsBaseWidget::SetSizeConstraints(c);
1772 const SizeConstraints nsWindow::GetSizeConstraints() {
1773 double scale = GetDefaultScale().scale;
1774 if (mSizeConstraintsScale == scale || mSizeConstraintsScale == 0.0) {
1775 return mSizeConstraints;
1777 scale /= mSizeConstraintsScale;
1778 SizeConstraints c = mSizeConstraints;
1779 if (c.mMinSize.width != NS_MAXSIZE) {
1780 c.mMinSize.width = NSToIntRound(c.mMinSize.width * scale);
1782 if (c.mMinSize.height != NS_MAXSIZE) {
1783 c.mMinSize.height = NSToIntRound(c.mMinSize.height * scale);
1785 if (c.mMaxSize.width != NS_MAXSIZE) {
1786 c.mMaxSize.width = NSToIntRound(c.mMaxSize.width * scale);
1788 if (c.mMaxSize.height != NS_MAXSIZE) {
1789 c.mMaxSize.height = NSToIntRound(c.mMaxSize.height * scale);
1791 return c;
1794 // Move this component
1795 void nsWindow::Move(double aX, double aY) {
1796 if (mWindowType == WindowType::TopLevel ||
1797 mWindowType == WindowType::Dialog) {
1798 SetSizeMode(nsSizeMode_Normal);
1801 // for top-level windows only, convert coordinates from desktop pixels
1802 // (the "parent" coordinate space) to the window's device pixel space
1803 double scale =
1804 BoundsUseDesktopPixels() ? GetDesktopToDeviceScale().scale : 1.0;
1805 int32_t x = NSToIntRound(aX * scale);
1806 int32_t y = NSToIntRound(aY * scale);
1808 // Check to see if window needs to be moved first
1809 // to avoid a costly call to SetWindowPos. This check
1810 // can not be moved to the calling code in nsView, because
1811 // some platforms do not position child windows correctly
1813 // Only perform this check for non-popup windows, since the positioning can
1814 // in fact change even when the x/y do not. We always need to perform the
1815 // check. See bug #97805 for details.
1816 if (mWindowType != WindowType::Popup && mBounds.IsEqualXY(x, y)) {
1817 // Nothing to do, since it is already positioned correctly.
1818 return;
1821 mBounds.MoveTo(x, y);
1823 if (mWnd) {
1824 #ifdef DEBUG
1825 // complain if a window is moved offscreen (legal, but potentially
1826 // worrisome)
1827 if (mIsTopWidgetWindow) { // only a problem for top-level windows
1828 // Make sure this window is actually on the screen before we move it
1829 // XXX: Needs multiple monitor support
1830 HDC dc = ::GetDC(mWnd);
1831 if (dc) {
1832 if (::GetDeviceCaps(dc, TECHNOLOGY) == DT_RASDISPLAY) {
1833 RECT workArea;
1834 ::SystemParametersInfo(SPI_GETWORKAREA, 0, &workArea, 0);
1835 // no annoying assertions. just mention the issue.
1836 if (x < 0 || x >= workArea.right || y < 0 || y >= workArea.bottom) {
1837 MOZ_LOG(gWindowsLog, LogLevel::Info,
1838 ("window moved to offscreen position\n"));
1841 ::ReleaseDC(mWnd, dc);
1844 #endif
1846 // Normally, when the skeleton UI is disabled, we resize+move the window
1847 // before showing it in order to ensure that it restores to the correct
1848 // position when the user un-maximizes it. However, when we are using the
1849 // skeleton UI, this results in the skeleton UI window being moved around
1850 // undesirably before being locked back into the maximized position. To
1851 // avoid this, we simply set the placement to restore to via
1852 // SetWindowPlacement. It's a little bit more of a dance, though, since we
1853 // need to convert the workspace coords that SetWindowPlacement uses to the
1854 // screen space coordinates we normally use with SetWindowPos.
1855 if (mIsShowingPreXULSkeletonUI && WasPreXULSkeletonUIMaximized()) {
1856 WINDOWPLACEMENT pl = {sizeof(WINDOWPLACEMENT)};
1857 VERIFY(::GetWindowPlacement(mWnd, &pl));
1859 HMONITOR monitor = ::MonitorFromWindow(mWnd, MONITOR_DEFAULTTONULL);
1860 if (NS_WARN_IF(!monitor)) {
1861 return;
1863 MONITORINFO mi = {sizeof(MONITORINFO)};
1864 VERIFY(::GetMonitorInfo(monitor, &mi));
1866 int32_t deltaX =
1867 x + mi.rcWork.left - mi.rcMonitor.left - pl.rcNormalPosition.left;
1868 int32_t deltaY =
1869 y + mi.rcWork.top - mi.rcMonitor.top - pl.rcNormalPosition.top;
1870 pl.rcNormalPosition.left += deltaX;
1871 pl.rcNormalPosition.right += deltaX;
1872 pl.rcNormalPosition.top += deltaY;
1873 pl.rcNormalPosition.bottom += deltaY;
1874 VERIFY(::SetWindowPlacement(mWnd, &pl));
1875 } else {
1876 UINT flags = SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOSIZE;
1877 double oldScale = mDefaultScale;
1878 mResizeState = IN_SIZEMOVE;
1879 VERIFY(::SetWindowPos(mWnd, nullptr, x, y, 0, 0, flags));
1880 mResizeState = NOT_RESIZING;
1881 if (WinUtils::LogToPhysFactor(mWnd) != oldScale) {
1882 ChangedDPI();
1886 ResizeDirectManipulationViewport();
1890 // Resize this component
1891 void nsWindow::Resize(double aWidth, double aHeight, bool aRepaint) {
1892 // for top-level windows only, convert coordinates from desktop pixels
1893 // (the "parent" coordinate space) to the window's device pixel space
1894 double scale =
1895 BoundsUseDesktopPixels() ? GetDesktopToDeviceScale().scale : 1.0;
1896 int32_t width = NSToIntRound(aWidth * scale);
1897 int32_t height = NSToIntRound(aHeight * scale);
1899 NS_ASSERTION((width >= 0), "Negative width passed to nsWindow::Resize");
1900 NS_ASSERTION((height >= 0), "Negative height passed to nsWindow::Resize");
1901 if (width < 0 || height < 0) {
1902 gfxCriticalNoteOnce << "Negative passed to Resize(" << width << ", "
1903 << height << ") repaint: " << aRepaint;
1906 ConstrainSize(&width, &height);
1908 // Avoid unnecessary resizing calls
1909 if (mBounds.IsEqualSize(width, height)) {
1910 if (aRepaint) {
1911 Invalidate();
1913 return;
1916 // Set cached value for lightweight and printing
1917 bool wasLocking = mAspectRatio != 0.0;
1918 mBounds.SizeTo(width, height);
1919 if (wasLocking) {
1920 LockAspectRatio(true); // This causes us to refresh the mAspectRatio value
1923 if (mWnd) {
1924 // Refer to the comment above a similar check in nsWindow::Move
1925 if (mIsShowingPreXULSkeletonUI && WasPreXULSkeletonUIMaximized()) {
1926 WINDOWPLACEMENT pl = {sizeof(WINDOWPLACEMENT)};
1927 VERIFY(::GetWindowPlacement(mWnd, &pl));
1928 pl.rcNormalPosition.right = pl.rcNormalPosition.left + width;
1929 pl.rcNormalPosition.bottom = pl.rcNormalPosition.top + GetHeight(height);
1930 mResizeState = RESIZING;
1931 VERIFY(::SetWindowPlacement(mWnd, &pl));
1932 mResizeState = NOT_RESIZING;
1933 } else {
1934 UINT flags = SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE;
1936 if (!aRepaint) {
1937 flags |= SWP_NOREDRAW;
1940 double oldScale = mDefaultScale;
1941 mResizeState = RESIZING;
1942 VERIFY(
1943 ::SetWindowPos(mWnd, nullptr, 0, 0, width, GetHeight(height), flags));
1945 mResizeState = NOT_RESIZING;
1946 if (WinUtils::LogToPhysFactor(mWnd) != oldScale) {
1947 ChangedDPI();
1951 ResizeDirectManipulationViewport();
1954 if (aRepaint) Invalidate();
1957 // Resize this component
1958 void nsWindow::Resize(double aX, double aY, double aWidth, double aHeight,
1959 bool aRepaint) {
1960 // for top-level windows only, convert coordinates from desktop pixels
1961 // (the "parent" coordinate space) to the window's device pixel space
1962 double scale =
1963 BoundsUseDesktopPixels() ? GetDesktopToDeviceScale().scale : 1.0;
1964 int32_t x = NSToIntRound(aX * scale);
1965 int32_t y = NSToIntRound(aY * scale);
1966 int32_t width = NSToIntRound(aWidth * scale);
1967 int32_t height = NSToIntRound(aHeight * scale);
1969 NS_ASSERTION((width >= 0), "Negative width passed to nsWindow::Resize");
1970 NS_ASSERTION((height >= 0), "Negative height passed to nsWindow::Resize");
1971 if (width < 0 || height < 0) {
1972 gfxCriticalNoteOnce << "Negative passed to Resize(" << x << " ," << y
1973 << ", " << width << ", " << height
1974 << ") repaint: " << aRepaint;
1977 ConstrainSize(&width, &height);
1979 // Avoid unnecessary resizing calls
1980 if (mBounds.IsEqualRect(x, y, width, height)) {
1981 if (aRepaint) {
1982 Invalidate();
1984 return;
1987 // Set cached value for lightweight and printing
1988 mBounds.SetRect(x, y, width, height);
1990 if (mWnd) {
1991 // Refer to the comment above a similar check in nsWindow::Move
1992 if (mIsShowingPreXULSkeletonUI && WasPreXULSkeletonUIMaximized()) {
1993 WINDOWPLACEMENT pl = {sizeof(WINDOWPLACEMENT)};
1994 VERIFY(::GetWindowPlacement(mWnd, &pl));
1996 HMONITOR monitor = ::MonitorFromWindow(mWnd, MONITOR_DEFAULTTONULL);
1997 if (NS_WARN_IF(!monitor)) {
1998 return;
2000 MONITORINFO mi = {sizeof(MONITORINFO)};
2001 VERIFY(::GetMonitorInfo(monitor, &mi));
2003 int32_t deltaX =
2004 x + mi.rcWork.left - mi.rcMonitor.left - pl.rcNormalPosition.left;
2005 int32_t deltaY =
2006 y + mi.rcWork.top - mi.rcMonitor.top - pl.rcNormalPosition.top;
2007 pl.rcNormalPosition.left += deltaX;
2008 pl.rcNormalPosition.right = pl.rcNormalPosition.left + width;
2009 pl.rcNormalPosition.top += deltaY;
2010 pl.rcNormalPosition.bottom = pl.rcNormalPosition.top + GetHeight(height);
2011 VERIFY(::SetWindowPlacement(mWnd, &pl));
2012 } else {
2013 UINT flags = SWP_NOZORDER | SWP_NOACTIVATE;
2014 if (!aRepaint) {
2015 flags |= SWP_NOREDRAW;
2018 double oldScale = mDefaultScale;
2019 mResizeState = RESIZING;
2020 VERIFY(
2021 ::SetWindowPos(mWnd, nullptr, x, y, width, GetHeight(height), flags));
2022 mResizeState = NOT_RESIZING;
2023 if (WinUtils::LogToPhysFactor(mWnd) != oldScale) {
2024 ChangedDPI();
2027 if (mTransitionWnd) {
2028 // If we have a fullscreen transition window, we need to make
2029 // it topmost again, otherwise the taskbar may be raised by
2030 // the system unexpectedly when we leave fullscreen state.
2031 ::SetWindowPos(mTransitionWnd, HWND_TOPMOST, 0, 0, 0, 0,
2032 SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
2036 ResizeDirectManipulationViewport();
2039 if (aRepaint) Invalidate();
2042 /**************************************************************
2044 * SECTION: Window Z-order and state.
2046 * nsIWidget::PlaceBehind, nsIWidget::SetSizeMode,
2047 * nsIWidget::ConstrainPosition
2049 * Z-order, positioning, restore, minimize, and maximize.
2051 **************************************************************/
2053 // Position the window behind the given window
2054 void nsWindow::PlaceBehind(nsTopLevelWidgetZPlacement aPlacement,
2055 nsIWidget* aWidget, bool aActivate) {
2056 HWND behind = HWND_TOP;
2057 if (aPlacement == eZPlacementBottom)
2058 behind = HWND_BOTTOM;
2059 else if (aPlacement == eZPlacementBelow && aWidget)
2060 behind = (HWND)aWidget->GetNativeData(NS_NATIVE_WINDOW);
2061 UINT flags = SWP_NOMOVE | SWP_NOREPOSITION | SWP_NOSIZE;
2062 if (!aActivate) flags |= SWP_NOACTIVATE;
2064 if (!CanTakeFocus() && behind == HWND_TOP) {
2065 // Can't place the window to top so place it behind the foreground window
2066 // (as long as it is not topmost)
2067 HWND wndAfter = ::GetForegroundWindow();
2068 if (!wndAfter)
2069 behind = HWND_BOTTOM;
2070 else if (!(GetWindowLongPtrW(wndAfter, GWL_EXSTYLE) & WS_EX_TOPMOST))
2071 behind = wndAfter;
2072 flags |= SWP_NOACTIVATE;
2075 ::SetWindowPos(mWnd, behind, 0, 0, 0, 0, flags);
2078 static UINT GetCurrentShowCmd(HWND aWnd) {
2079 WINDOWPLACEMENT pl;
2080 pl.length = sizeof(pl);
2081 ::GetWindowPlacement(aWnd, &pl);
2082 return pl.showCmd;
2085 // Maximize, minimize or restore the window.
2086 void nsWindow::SetSizeMode(nsSizeMode aMode) {
2087 // If we are still displaying a maximized pre-XUL skeleton UI, ignore the
2088 // noise of sizemode changes. Once we have "shown" the window for the first
2089 // time (called nsWindow::Show(true), even though the window is already
2090 // technically displayed), we will again accept sizemode changes.
2091 if (mIsShowingPreXULSkeletonUI && WasPreXULSkeletonUIMaximized()) {
2092 return;
2095 mFrameState->EnsureSizeMode(aMode);
2098 nsSizeMode nsWindow::SizeMode() { return mFrameState->GetSizeMode(); }
2100 void DoGetWorkspaceID(HWND aWnd, nsAString* aWorkspaceID) {
2101 RefPtr<IVirtualDesktopManager> desktopManager = gVirtualDesktopManager;
2102 if (!desktopManager || !aWnd) {
2103 return;
2106 GUID desktop;
2107 HRESULT hr = desktopManager->GetWindowDesktopId(aWnd, &desktop);
2108 if (FAILED(hr)) {
2109 return;
2112 RPC_WSTR workspaceIDStr = nullptr;
2113 if (UuidToStringW(&desktop, &workspaceIDStr) == RPC_S_OK) {
2114 aWorkspaceID->Assign((wchar_t*)workspaceIDStr);
2115 RpcStringFreeW(&workspaceIDStr);
2119 void nsWindow::GetWorkspaceID(nsAString& workspaceID) {
2120 // If we have a value cached, use that, but also make sure it is
2121 // scheduled to be updated. If we don't yet have a value, get
2122 // one synchronously.
2123 auto desktop = mDesktopId.Lock();
2124 if (desktop->mID.IsEmpty()) {
2125 DoGetWorkspaceID(mWnd, &desktop->mID);
2126 desktop->mUpdateIsQueued = false;
2127 } else {
2128 AsyncUpdateWorkspaceID(*desktop);
2131 workspaceID = desktop->mID;
2134 void nsWindow::AsyncUpdateWorkspaceID(Desktop& aDesktop) {
2135 struct UpdateWorkspaceIdTask : public Task {
2136 explicit UpdateWorkspaceIdTask(nsWindow* aSelf)
2137 : Task(Kind::OffMainThreadOnly, EventQueuePriority::Normal),
2138 mSelf(aSelf) {}
2140 TaskResult Run() override {
2141 auto desktop = mSelf->mDesktopId.Lock();
2142 if (desktop->mUpdateIsQueued) {
2143 DoGetWorkspaceID(mSelf->mWnd, &desktop->mID);
2144 desktop->mUpdateIsQueued = false;
2146 return TaskResult::Complete;
2149 #ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
2150 bool GetName(nsACString& aName) override {
2151 aName.AssignLiteral("UpdateWorkspaceIdTask");
2152 return true;
2154 #endif
2156 RefPtr<nsWindow> mSelf;
2159 if (aDesktop.mUpdateIsQueued) {
2160 return;
2163 aDesktop.mUpdateIsQueued = true;
2164 TaskController::Get()->AddTask(MakeAndAddRef<UpdateWorkspaceIdTask>(this));
2167 void nsWindow::MoveToWorkspace(const nsAString& workspaceID) {
2168 RefPtr<IVirtualDesktopManager> desktopManager = gVirtualDesktopManager;
2169 if (!desktopManager) {
2170 return;
2173 GUID desktop;
2174 const nsString flat = PromiseFlatString(workspaceID);
2175 RPC_WSTR workspaceIDStr = reinterpret_cast<RPC_WSTR>((wchar_t*)flat.get());
2176 if (UuidFromStringW(workspaceIDStr, &desktop) == RPC_S_OK) {
2177 if (SUCCEEDED(desktopManager->MoveWindowToDesktop(mWnd, desktop))) {
2178 auto desktop = mDesktopId.Lock();
2179 desktop->mID = workspaceID;
2184 void nsWindow::SuppressAnimation(bool aSuppress) {
2185 DWORD dwAttribute = aSuppress ? TRUE : FALSE;
2186 DwmSetWindowAttribute(mWnd, DWMWA_TRANSITIONS_FORCEDISABLED, &dwAttribute,
2187 sizeof dwAttribute);
2190 // Constrain a potential move to fit onscreen
2191 // Position (aX, aY) is specified in Windows screen (logical) pixels,
2192 // except when using per-monitor DPI, in which case it's device pixels.
2193 void nsWindow::ConstrainPosition(DesktopIntPoint& aPoint) {
2194 if (!mIsTopWidgetWindow) // only a problem for top-level windows
2195 return;
2197 double dpiScale = GetDesktopToDeviceScale().scale;
2199 // We need to use the window size in the kind of pixels used for window-
2200 // manipulation APIs.
2201 int32_t logWidth =
2202 std::max<int32_t>(NSToIntRound(mBounds.Width() / dpiScale), 1);
2203 int32_t logHeight =
2204 std::max<int32_t>(NSToIntRound(mBounds.Height() / dpiScale), 1);
2206 /* get our playing field. use the current screen, or failing that
2207 for any reason, use device caps for the default screen. */
2208 RECT screenRect;
2210 nsCOMPtr<nsIScreenManager> screenmgr =
2211 do_GetService(sScreenManagerContractID);
2212 if (!screenmgr) {
2213 return;
2215 nsCOMPtr<nsIScreen> screen;
2216 int32_t left, top, width, height;
2218 screenmgr->ScreenForRect(aPoint.x, aPoint.y, logWidth, logHeight,
2219 getter_AddRefs(screen));
2220 if (mFrameState->GetSizeMode() != nsSizeMode_Fullscreen) {
2221 // For normalized windows, use the desktop work area.
2222 nsresult rv = screen->GetAvailRectDisplayPix(&left, &top, &width, &height);
2223 if (NS_FAILED(rv)) {
2224 return;
2226 } else {
2227 // For full screen windows, use the desktop.
2228 nsresult rv = screen->GetRectDisplayPix(&left, &top, &width, &height);
2229 if (NS_FAILED(rv)) {
2230 return;
2233 screenRect.left = left;
2234 screenRect.right = left + width;
2235 screenRect.top = top;
2236 screenRect.bottom = top + height;
2238 if (aPoint.x < screenRect.left)
2239 aPoint.x = screenRect.left;
2240 else if (aPoint.x >= screenRect.right - logWidth)
2241 aPoint.x = screenRect.right - logWidth;
2243 if (aPoint.y < screenRect.top)
2244 aPoint.y = screenRect.top;
2245 else if (aPoint.y >= screenRect.bottom - logHeight)
2246 aPoint.y = screenRect.bottom - logHeight;
2249 /**************************************************************
2251 * SECTION: nsIWidget::Enable, nsIWidget::IsEnabled
2253 * Enabling and disabling the widget.
2255 **************************************************************/
2257 // Enable/disable this component
2258 void nsWindow::Enable(bool bState) {
2259 if (mWnd) {
2260 ::EnableWindow(mWnd, bState);
2264 // Return the current enable state
2265 bool nsWindow::IsEnabled() const {
2266 return !mWnd || (::IsWindowEnabled(mWnd) &&
2267 ::IsWindowEnabled(::GetAncestor(mWnd, GA_ROOT)));
2270 /**************************************************************
2272 * SECTION: nsIWidget::SetFocus
2274 * Give the focus to this widget.
2276 **************************************************************/
2278 void nsWindow::SetFocus(Raise aRaise, mozilla::dom::CallerType aCallerType) {
2279 if (mWnd) {
2280 #ifdef WINSTATE_DEBUG_OUTPUT
2281 if (mWnd == WinUtils::GetTopLevelHWND(mWnd)) {
2282 MOZ_LOG(gWindowsLog, LogLevel::Info,
2283 ("*** SetFocus: [ top] raise=%d\n", aRaise == Raise::Yes));
2284 } else {
2285 MOZ_LOG(gWindowsLog, LogLevel::Info,
2286 ("*** SetFocus: [child] raise=%d\n", aRaise == Raise::Yes));
2288 #endif
2289 // Uniconify, if necessary
2290 HWND toplevelWnd = WinUtils::GetTopLevelHWND(mWnd);
2291 if (aRaise == Raise::Yes && ::IsIconic(toplevelWnd)) {
2292 ::ShowWindow(toplevelWnd, SW_RESTORE);
2294 ::SetFocus(mWnd);
2298 /**************************************************************
2300 * SECTION: Bounds
2302 * GetBounds, GetClientBounds, GetScreenBounds,
2303 * GetRestoredBounds, GetClientOffset, SetNonClientMargins
2305 * Bound calculations.
2307 **************************************************************/
2309 // Return the window's full dimensions in screen coordinates.
2310 // If the window has a parent, converts the origin to an offset
2311 // of the parent's screen origin.
2312 LayoutDeviceIntRect nsWindow::GetBounds() {
2313 if (!mWnd) {
2314 return mBounds;
2317 RECT r;
2318 VERIFY(::GetWindowRect(mWnd, &r));
2320 LayoutDeviceIntRect rect;
2322 // assign size
2323 rect.SizeTo(r.right - r.left, r.bottom - r.top);
2325 // popup window bounds' are in screen coordinates, not relative to parent
2326 // window
2327 if (mWindowType == WindowType::Popup) {
2328 rect.MoveTo(r.left, r.top);
2329 return rect;
2332 // chrome on parent:
2333 // ___ 5,5 (chrome start)
2334 // | ____ 10,10 (client start)
2335 // | | ____ 20,20 (child start)
2336 // | | |
2337 // 20,20 - 5,5 = 15,15 (??)
2338 // minus GetClientOffset:
2339 // 15,15 - 5,5 = 10,10
2341 // no chrome on parent:
2342 // ______ 10,10 (win start)
2343 // | ____ 20,20 (child start)
2344 // | |
2345 // 20,20 - 10,10 = 10,10
2347 // walking the chain:
2348 // ___ 5,5 (chrome start)
2349 // | ___ 10,10 (client start)
2350 // | | ___ 20,20 (child start)
2351 // | | | __ 30,30 (child start)
2352 // | | | |
2353 // 30,30 - 20,20 = 10,10 (offset from second child to first)
2354 // 20,20 - 5,5 = 15,15 + 10,10 = 25,25 (??)
2355 // minus GetClientOffset:
2356 // 25,25 - 5,5 = 20,20 (offset from second child to parent client)
2358 // convert coordinates if parent exists
2359 HWND parent = ::GetParent(mWnd);
2360 if (parent) {
2361 RECT pr;
2362 VERIFY(::GetWindowRect(parent, &pr));
2363 r.left -= pr.left;
2364 r.top -= pr.top;
2365 // adjust for chrome
2366 nsWindow* pWidget = static_cast<nsWindow*>(GetParent());
2367 if (pWidget && pWidget->IsTopLevelWidget()) {
2368 LayoutDeviceIntPoint clientOffset = pWidget->GetClientOffset();
2369 r.left -= clientOffset.x;
2370 r.top -= clientOffset.y;
2373 rect.MoveTo(r.left, r.top);
2374 if (mCompositorSession &&
2375 !wr::WindowSizeSanityCheck(rect.width, rect.height)) {
2376 gfxCriticalNoteOnce << "Invalid size" << rect << " size mode "
2377 << mFrameState->GetSizeMode();
2380 return rect;
2383 // Get this component dimension
2384 LayoutDeviceIntRect nsWindow::GetClientBounds() {
2385 if (!mWnd) {
2386 return LayoutDeviceIntRect(0, 0, 0, 0);
2389 RECT r;
2390 if (!::GetClientRect(mWnd, &r)) {
2391 MOZ_ASSERT_UNREACHABLE("unexpected to be called");
2392 gfxCriticalNoteOnce << "GetClientRect failed " << ::GetLastError();
2393 return mBounds;
2396 LayoutDeviceIntRect bounds = GetBounds();
2397 LayoutDeviceIntRect rect;
2398 rect.MoveTo(bounds.TopLeft() + GetClientOffset());
2399 rect.SizeTo(r.right - r.left, r.bottom - r.top);
2400 return rect;
2403 // Like GetBounds, but don't offset by the parent
2404 LayoutDeviceIntRect nsWindow::GetScreenBounds() {
2405 if (!mWnd) {
2406 return mBounds;
2409 RECT r;
2410 VERIFY(::GetWindowRect(mWnd, &r));
2412 return LayoutDeviceIntRect(r.left, r.top, r.right - r.left, r.bottom - r.top);
2415 nsresult nsWindow::GetRestoredBounds(LayoutDeviceIntRect& aRect) {
2416 if (SizeMode() == nsSizeMode_Normal) {
2417 aRect = GetScreenBounds();
2418 return NS_OK;
2420 if (!mWnd) {
2421 return NS_ERROR_FAILURE;
2424 WINDOWPLACEMENT pl = {sizeof(WINDOWPLACEMENT)};
2425 VERIFY(::GetWindowPlacement(mWnd, &pl));
2426 const RECT& r = pl.rcNormalPosition;
2428 HMONITOR monitor = ::MonitorFromWindow(mWnd, MONITOR_DEFAULTTONULL);
2429 if (!monitor) {
2430 return NS_ERROR_FAILURE;
2432 MONITORINFO mi = {sizeof(MONITORINFO)};
2433 VERIFY(::GetMonitorInfo(monitor, &mi));
2435 aRect.SetRect(r.left, r.top, r.right - r.left, r.bottom - r.top);
2436 aRect.MoveBy(mi.rcWork.left - mi.rcMonitor.left,
2437 mi.rcWork.top - mi.rcMonitor.top);
2438 return NS_OK;
2441 // Return the x,y offset of the client area from the origin of the window. If
2442 // the window is borderless returns (0,0).
2443 LayoutDeviceIntPoint nsWindow::GetClientOffset() {
2444 if (!mWnd) {
2445 return LayoutDeviceIntPoint(0, 0);
2448 RECT r1;
2449 GetWindowRect(mWnd, &r1);
2450 LayoutDeviceIntPoint pt = WidgetToScreenOffset();
2451 return LayoutDeviceIntPoint(pt.x - LayoutDeviceIntCoord(r1.left),
2452 pt.y - LayoutDeviceIntCoord(r1.top));
2455 void nsWindow::ResetLayout() {
2456 // This will trigger a frame changed event, triggering
2457 // nc calc size and a sizemode gecko event.
2458 SetWindowPos(mWnd, 0, 0, 0, 0, 0,
2459 SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOMOVE |
2460 SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER);
2462 // If hidden, just send the frame changed event for now.
2463 if (!mIsVisible) {
2464 return;
2467 // Send a gecko size event to trigger reflow.
2468 RECT clientRc = {0};
2469 GetClientRect(mWnd, &clientRc);
2470 OnResize(WinUtils::ToIntRect(clientRc).Size());
2472 // Invalidate and update
2473 Invalidate();
2476 #define DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 19
2477 #define DWMWA_USE_IMMERSIVE_DARK_MODE 20
2479 void nsWindow::UpdateDarkModeToolbar() {
2480 PreferenceSheet::EnsureInitialized();
2481 BOOL dark = PreferenceSheet::ColorSchemeForChrome() == ColorScheme::Dark;
2482 DwmSetWindowAttribute(mWnd, DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1, &dark,
2483 sizeof dark);
2484 DwmSetWindowAttribute(mWnd, DWMWA_USE_IMMERSIVE_DARK_MODE, &dark,
2485 sizeof dark);
2488 LayoutDeviceIntMargin nsWindow::NormalWindowNonClientOffset() const {
2489 LayoutDeviceIntMargin nonClientOffset;
2491 // We're dealing with a "normal" window (not maximized, minimized, or
2492 // fullscreen), so process `mNonClientMargins` and set `mNonClientOffset`
2493 // accordingly.
2495 // Setting `mNonClientOffset` to 0 has the effect of leaving the default
2496 // frame intact. Setting it to a value greater than 0 reduces the frame
2497 // size by that amount.
2499 if (mNonClientMargins.top > 0) {
2500 nonClientOffset.top = std::min(mCaptionHeight, mNonClientMargins.top);
2501 } else if (mNonClientMargins.top == 0) {
2502 nonClientOffset.top = mCaptionHeight;
2503 } else {
2504 nonClientOffset.top = 0;
2507 if (mNonClientMargins.bottom > 0) {
2508 nonClientOffset.bottom =
2509 std::min(mVertResizeMargin, mNonClientMargins.bottom);
2510 } else if (mNonClientMargins.bottom == 0) {
2511 nonClientOffset.bottom = mVertResizeMargin;
2512 } else {
2513 nonClientOffset.bottom = 0;
2516 if (mNonClientMargins.left > 0) {
2517 nonClientOffset.left = std::min(mHorResizeMargin, mNonClientMargins.left);
2518 } else if (mNonClientMargins.left == 0) {
2519 nonClientOffset.left = mHorResizeMargin;
2520 } else {
2521 nonClientOffset.left = 0;
2524 if (mNonClientMargins.right > 0) {
2525 nonClientOffset.right = std::min(mHorResizeMargin, mNonClientMargins.right);
2526 } else if (mNonClientMargins.right == 0) {
2527 nonClientOffset.right = mHorResizeMargin;
2528 } else {
2529 nonClientOffset.right = 0;
2531 return nonClientOffset;
2535 * Called when the window layout changes: full screen mode transitions,
2536 * theme changes, and composition changes. Calculates the new non-client
2537 * margins and fires off a frame changed event, which triggers an nc calc
2538 * size windows event, kicking the changes in.
2540 * The offsets calculated here are based on the value of `mNonClientMargins`
2541 * which is specified in the "chromemargins" attribute of the window. For
2542 * each margin, the value specified has the following meaning:
2543 * -1 - leave the default frame in place
2544 * 0 - remove the frame
2545 * >0 - frame size equals min(0, (default frame size - margin value))
2547 * This function calculates and populates `mNonClientOffset`.
2548 * In our processing of `WM_NCCALCSIZE`, the frame size will be calculated
2549 * as (default frame size - offset). For example, if the left frame should
2550 * be 1 pixel narrower than the default frame size, `mNonClientOffset.left`
2551 * will equal 1.
2553 * For maximized, fullscreen, and minimized windows, the values stored in
2554 * `mNonClientMargins` are ignored, and special processing takes place.
2556 * For non-glass windows, we only allow frames to be their default size
2557 * or removed entirely.
2559 bool nsWindow::UpdateNonClientMargins(bool aReflowWindow) {
2560 if (!mCustomNonClient) {
2561 return false;
2564 const nsSizeMode sizeMode = mFrameState->GetSizeMode();
2566 bool hasCaption =
2567 bool(mBorderStyle & (BorderStyle::All | BorderStyle::Title |
2568 BorderStyle::Menu | BorderStyle::Default));
2570 float dpi = GetDPI();
2572 // mCaptionHeight is the default size of the NC area at
2573 // the top of the window. If the window has a caption,
2574 // the size is calculated as the sum of:
2575 // SM_CYFRAME - The thickness of the sizing border
2576 // around a resizable window
2577 // SM_CXPADDEDBORDER - The amount of border padding
2578 // for captioned windows
2579 // SM_CYCAPTION - The height of the caption area
2581 // If the window does not have a caption, mCaptionHeight will be equal to
2582 // `WinUtils::GetSystemMetricsForDpi(SM_CYFRAME, dpi)`
2583 mCaptionHeight =
2584 WinUtils::GetSystemMetricsForDpi(SM_CYFRAME, dpi) +
2585 (hasCaption ? WinUtils::GetSystemMetricsForDpi(SM_CYCAPTION, dpi) +
2586 WinUtils::GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi)
2587 : 0);
2588 if (!mUseResizeMarginOverrides) {
2589 // mHorResizeMargin is the size of the default NC areas on the
2590 // left and right sides of our window. It is calculated as
2591 // the sum of:
2592 // SM_CXFRAME - The thickness of the sizing border
2593 // SM_CXPADDEDBORDER - The amount of border padding
2594 // for captioned windows
2596 // If the window does not have a caption, mHorResizeMargin will be equal to
2597 // `WinUtils::GetSystemMetricsForDpi(SM_CXFRAME, dpi)`
2598 mHorResizeMargin =
2599 WinUtils::GetSystemMetricsForDpi(SM_CXFRAME, dpi) +
2600 (hasCaption ? WinUtils::GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi)
2601 : 0);
2603 // mVertResizeMargin is the size of the default NC area at the
2604 // bottom of the window. It is calculated as the sum of:
2605 // SM_CYFRAME - The thickness of the sizing border
2606 // SM_CXPADDEDBORDER - The amount of border padding
2607 // for captioned windows.
2609 // If the window does not have a caption, mVertResizeMargin will be equal to
2610 // `WinUtils::GetSystemMetricsForDpi(SM_CYFRAME, dpi)`
2611 mVertResizeMargin =
2612 WinUtils::GetSystemMetricsForDpi(SM_CYFRAME, dpi) +
2613 (hasCaption ? WinUtils::GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi)
2614 : 0);
2617 if (sizeMode == nsSizeMode_Minimized) {
2618 // Use default frame size for minimized windows
2619 mNonClientOffset.top = 0;
2620 mNonClientOffset.left = 0;
2621 mNonClientOffset.right = 0;
2622 mNonClientOffset.bottom = 0;
2623 } else if (sizeMode == nsSizeMode_Fullscreen) {
2624 // Remove the default frame from the top of our fullscreen window. This
2625 // makes the whole caption part of our client area, allowing us to draw
2626 // in the whole caption area. Additionally remove the default frame from
2627 // the left, right, and bottom.
2628 mNonClientOffset.top = mCaptionHeight;
2629 mNonClientOffset.bottom = mVertResizeMargin;
2630 mNonClientOffset.left = mHorResizeMargin;
2631 mNonClientOffset.right = mHorResizeMargin;
2632 } else if (sizeMode == nsSizeMode_Maximized) {
2633 // We make the entire frame part of the client area. We leave the default
2634 // frame sizes for left, right and bottom since Windows will automagically
2635 // position the edges "offscreen" for maximized windows.
2636 int verticalResize =
2637 WinUtils::GetSystemMetricsForDpi(SM_CYFRAME, dpi) +
2638 (hasCaption ? WinUtils::GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi)
2639 : 0);
2641 mNonClientOffset.top = mCaptionHeight - verticalResize;
2642 mNonClientOffset.bottom = 0;
2643 mNonClientOffset.left = 0;
2644 mNonClientOffset.right = 0;
2646 mozilla::Maybe<UINT> maybeEdge = GetHiddenTaskbarEdge();
2647 if (maybeEdge) {
2648 auto edge = maybeEdge.value();
2649 if (ABE_LEFT == edge) {
2650 mNonClientOffset.left -= kHiddenTaskbarSize;
2651 } else if (ABE_RIGHT == edge) {
2652 mNonClientOffset.right -= kHiddenTaskbarSize;
2653 } else if (ABE_BOTTOM == edge || ABE_TOP == edge) {
2654 mNonClientOffset.bottom -= kHiddenTaskbarSize;
2657 // When we are drawing the non-client region, we need
2658 // to clear the portion of the NC region that is exposed by the
2659 // hidden taskbar. As above, we clear the bottom of the NC region
2660 // when the taskbar is at the top of the screen.
2661 UINT clearEdge = (edge == ABE_TOP) ? ABE_BOTTOM : edge;
2662 mClearNCEdge = Some(clearEdge);
2664 } else {
2665 mNonClientOffset = NormalWindowNonClientOffset();
2668 if (aReflowWindow) {
2669 // Force a reflow of content based on the new client
2670 // dimensions.
2671 ResetLayout();
2674 return true;
2677 nsresult nsWindow::SetNonClientMargins(const LayoutDeviceIntMargin& margins) {
2678 if (!mIsTopWidgetWindow || mBorderStyle == BorderStyle::None) {
2679 return NS_ERROR_INVALID_ARG;
2682 if (mHideChrome) {
2683 mFutureMarginsOnceChromeShows = margins;
2684 mFutureMarginsToUse = true;
2685 return NS_OK;
2687 mFutureMarginsToUse = false;
2689 // Request for a reset
2690 if (margins.top == -1 && margins.left == -1 && margins.right == -1 &&
2691 margins.bottom == -1) {
2692 mCustomNonClient = false;
2693 mNonClientMargins = margins;
2694 // Force a reflow of content based on the new client
2695 // dimensions.
2696 ResetLayout();
2697 return NS_OK;
2700 if (margins.top < -1 || margins.bottom < -1 || margins.left < -1 ||
2701 margins.right < -1) {
2702 return NS_ERROR_INVALID_ARG;
2705 mNonClientMargins = margins;
2706 mCustomNonClient = true;
2707 if (!UpdateNonClientMargins()) {
2708 NS_WARNING("UpdateNonClientMargins failed!");
2709 return NS_OK;
2712 return NS_OK;
2715 void nsWindow::SetResizeMargin(mozilla::LayoutDeviceIntCoord aResizeMargin) {
2716 mUseResizeMarginOverrides = true;
2717 mHorResizeMargin = aResizeMargin;
2718 mVertResizeMargin = aResizeMargin;
2719 UpdateNonClientMargins();
2722 void nsWindow::InvalidateNonClientRegion() {
2723 // +-+-----------------------+-+
2724 // | | app non-client chrome | |
2725 // | +-----------------------+ |
2726 // | | app client chrome | | }
2727 // | +-----------------------+ | }
2728 // | | app content | | } area we don't want to invalidate
2729 // | +-----------------------+ | }
2730 // | | app client chrome | | }
2731 // | +-----------------------+ |
2732 // +---------------------------+ <
2733 // ^ ^ windows non-client chrome
2734 // client area = app *
2735 RECT rect;
2736 GetWindowRect(mWnd, &rect);
2737 MapWindowPoints(nullptr, mWnd, (LPPOINT)&rect, 2);
2738 HRGN winRgn = CreateRectRgnIndirect(&rect);
2740 // Subtract app client chrome and app content leaving
2741 // windows non-client chrome and app non-client chrome
2742 // in winRgn.
2743 GetWindowRect(mWnd, &rect);
2744 rect.top += mCaptionHeight;
2745 rect.right -= mHorResizeMargin;
2746 rect.bottom -= mVertResizeMargin;
2747 rect.left += mHorResizeMargin;
2748 MapWindowPoints(nullptr, mWnd, (LPPOINT)&rect, 2);
2749 HRGN clientRgn = CreateRectRgnIndirect(&rect);
2750 CombineRgn(winRgn, winRgn, clientRgn, RGN_DIFF);
2751 DeleteObject(clientRgn);
2753 // triggers ncpaint and paint events for the two areas
2754 RedrawWindow(mWnd, nullptr, winRgn, RDW_FRAME | RDW_INVALIDATE);
2755 DeleteObject(winRgn);
2758 /**************************************************************
2760 * SECTION: nsIWidget::SetBackgroundColor
2762 * Sets the window background paint color.
2764 **************************************************************/
2766 void nsWindow::SetBackgroundColor(const nscolor& aColor) {
2767 if (mBrush) ::DeleteObject(mBrush);
2769 mBrush = ::CreateSolidBrush(NSRGB_2_COLOREF(aColor));
2770 if (mWnd != nullptr) {
2771 ::SetClassLongPtrW(mWnd, GCLP_HBRBACKGROUND, (LONG_PTR)mBrush);
2775 /**************************************************************
2777 * SECTION: nsIWidget::SetCursor
2779 * SetCursor and related utilities for manging cursor state.
2781 **************************************************************/
2783 // Set this component cursor
2784 static HCURSOR CursorFor(nsCursor aCursor) {
2785 switch (aCursor) {
2786 case eCursor_select:
2787 return ::LoadCursor(nullptr, IDC_IBEAM);
2788 case eCursor_wait:
2789 return ::LoadCursor(nullptr, IDC_WAIT);
2790 case eCursor_hyperlink:
2791 return ::LoadCursor(nullptr, IDC_HAND);
2792 case eCursor_standard:
2793 case eCursor_context_menu: // XXX See bug 258960.
2794 return ::LoadCursor(nullptr, IDC_ARROW);
2796 case eCursor_n_resize:
2797 case eCursor_s_resize:
2798 return ::LoadCursor(nullptr, IDC_SIZENS);
2800 case eCursor_w_resize:
2801 case eCursor_e_resize:
2802 return ::LoadCursor(nullptr, IDC_SIZEWE);
2804 case eCursor_nw_resize:
2805 case eCursor_se_resize:
2806 return ::LoadCursor(nullptr, IDC_SIZENWSE);
2808 case eCursor_ne_resize:
2809 case eCursor_sw_resize:
2810 return ::LoadCursor(nullptr, IDC_SIZENESW);
2812 case eCursor_crosshair:
2813 return ::LoadCursor(nullptr, IDC_CROSS);
2815 case eCursor_move:
2816 return ::LoadCursor(nullptr, IDC_SIZEALL);
2818 case eCursor_help:
2819 return ::LoadCursor(nullptr, IDC_HELP);
2821 case eCursor_copy: // CSS3
2822 return ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_COPY));
2824 case eCursor_alias:
2825 return ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_ALIAS));
2827 case eCursor_cell:
2828 return ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_CELL));
2829 case eCursor_grab:
2830 return ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_GRAB));
2832 case eCursor_grabbing:
2833 return ::LoadCursor(nsToolkit::mDllInstance,
2834 MAKEINTRESOURCE(IDC_GRABBING));
2836 case eCursor_spinning:
2837 return ::LoadCursor(nullptr, IDC_APPSTARTING);
2839 case eCursor_zoom_in:
2840 return ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_ZOOMIN));
2842 case eCursor_zoom_out:
2843 return ::LoadCursor(nsToolkit::mDllInstance,
2844 MAKEINTRESOURCE(IDC_ZOOMOUT));
2846 case eCursor_not_allowed:
2847 case eCursor_no_drop:
2848 return ::LoadCursor(nullptr, IDC_NO);
2850 case eCursor_col_resize:
2851 return ::LoadCursor(nsToolkit::mDllInstance,
2852 MAKEINTRESOURCE(IDC_COLRESIZE));
2854 case eCursor_row_resize:
2855 return ::LoadCursor(nsToolkit::mDllInstance,
2856 MAKEINTRESOURCE(IDC_ROWRESIZE));
2858 case eCursor_vertical_text:
2859 return ::LoadCursor(nsToolkit::mDllInstance,
2860 MAKEINTRESOURCE(IDC_VERTICALTEXT));
2862 case eCursor_all_scroll:
2863 // XXX not 100% appropriate perhaps
2864 return ::LoadCursor(nullptr, IDC_SIZEALL);
2866 case eCursor_nesw_resize:
2867 return ::LoadCursor(nullptr, IDC_SIZENESW);
2869 case eCursor_nwse_resize:
2870 return ::LoadCursor(nullptr, IDC_SIZENWSE);
2872 case eCursor_ns_resize:
2873 return ::LoadCursor(nullptr, IDC_SIZENS);
2875 case eCursor_ew_resize:
2876 return ::LoadCursor(nullptr, IDC_SIZEWE);
2878 case eCursor_none:
2879 return ::LoadCursor(nsToolkit::mDllInstance, MAKEINTRESOURCE(IDC_NONE));
2881 default:
2882 NS_ERROR("Invalid cursor type");
2883 return nullptr;
2887 static HCURSOR CursorForImage(const nsIWidget::Cursor& aCursor,
2888 CSSToLayoutDeviceScale aScale) {
2889 if (!aCursor.IsCustom()) {
2890 return nullptr;
2893 nsIntSize size = nsIWidget::CustomCursorSize(aCursor);
2895 // Reject cursors greater than 128 pixels in either direction, to prevent
2896 // spoofing.
2897 // XXX ideally we should rescale. Also, we could modify the API to
2898 // allow trusted content to set larger cursors.
2899 if (size.width > 128 || size.height > 128) {
2900 return nullptr;
2903 LayoutDeviceIntSize layoutSize =
2904 RoundedToInt(CSSIntSize(size.width, size.height) * aScale);
2905 LayoutDeviceIntPoint hotspot =
2906 RoundedToInt(CSSIntPoint(aCursor.mHotspotX, aCursor.mHotspotY) * aScale);
2907 HCURSOR cursor;
2908 nsresult rv = nsWindowGfx::CreateIcon(aCursor.mContainer, true, hotspot,
2909 layoutSize, &cursor);
2910 if (NS_FAILED(rv)) {
2911 return nullptr;
2914 return cursor;
2917 void nsWindow::SetCursor(const Cursor& aCursor) {
2918 static HCURSOR sCurrentHCursor = nullptr;
2919 static bool sCurrentHCursorIsCustom = false;
2921 mCursor = aCursor;
2923 if (sCurrentCursor == aCursor && sCurrentHCursor && !mUpdateCursor) {
2924 // Cursors in windows are global, so even if our mUpdateCursor flag is
2925 // false we always need to make sure the Windows cursor is up-to-date,
2926 // since stuff like native drag and drop / resizers code can mutate it
2927 // outside of this method.
2928 ::SetCursor(sCurrentHCursor);
2929 return;
2932 mUpdateCursor = false;
2934 if (sCurrentHCursorIsCustom) {
2935 ::DestroyIcon(sCurrentHCursor);
2937 sCurrentHCursor = nullptr;
2938 sCurrentHCursorIsCustom = false;
2939 sCurrentCursor = aCursor;
2941 HCURSOR cursor = nullptr;
2942 if (mCustomCursorAllowed) {
2943 cursor = CursorForImage(aCursor, GetDefaultScale());
2945 bool custom = false;
2946 if (cursor) {
2947 custom = true;
2948 } else {
2949 cursor = CursorFor(aCursor.mDefaultCursor);
2952 if (!cursor) {
2953 return;
2956 sCurrentHCursor = cursor;
2957 sCurrentHCursorIsCustom = custom;
2958 ::SetCursor(cursor);
2961 /**************************************************************
2963 * SECTION: nsIWidget::Get/SetTransparencyMode
2965 * Manage the transparency mode of the window containing this
2966 * widget. Only works for popup and dialog windows when the
2967 * Desktop Window Manager compositor is not enabled.
2969 **************************************************************/
2971 TransparencyMode nsWindow::GetTransparencyMode() {
2972 return GetTopLevelWindow(true)->GetWindowTranslucencyInner();
2975 void nsWindow::SetTransparencyMode(TransparencyMode aMode) {
2976 nsWindow* window = GetTopLevelWindow(true);
2977 MOZ_ASSERT(window);
2979 if (!window || window->DestroyCalled()) {
2980 return;
2983 window->SetWindowTranslucencyInner(aMode);
2986 /**************************************************************
2988 * SECTION: nsIWidget::UpdateWindowDraggingRegion
2990 * For setting the draggable titlebar region from CSS
2991 * with -moz-window-dragging: drag.
2993 **************************************************************/
2995 void nsWindow::UpdateWindowDraggingRegion(
2996 const LayoutDeviceIntRegion& aRegion) {
2997 mDraggableRegion = aRegion;
3000 /**************************************************************
3002 * SECTION: nsIWidget::HideWindowChrome
3004 * Show or hide window chrome.
3006 **************************************************************/
3008 void nsWindow::HideWindowChrome(bool aShouldHide) {
3009 HWND hwnd = WinUtils::GetTopLevelHWND(mWnd, true);
3010 if (!WinUtils::GetNSWindowPtr(hwnd)) {
3011 NS_WARNING("Trying to hide window decorations in an embedded context");
3012 return;
3015 if (mHideChrome == aShouldHide) return;
3017 // Data manipulation: styles + ex-styles, and bitmasking operations thereupon.
3018 struct Styles {
3019 LONG_PTR style, ex;
3020 constexpr Styles operator|(Styles const& that) const {
3021 return Styles{.style = style | that.style, .ex = ex | that.ex};
3023 constexpr Styles operator&(Styles const& that) const {
3024 return Styles{.style = style & that.style, .ex = ex & that.ex};
3026 constexpr Styles operator~() const {
3027 return Styles{.style = ~style, .ex = ~ex};
3030 // Compute a style-set which matches `zero` where the bits of `this` are 0
3031 // and `one` where the bits of `this` are 1.
3032 constexpr Styles merge(Styles zero, Styles one) const {
3033 Styles const& mask = *this;
3034 return (~mask & zero) | (mask & one);
3037 // The dual of `merge`, above: returns a pair [zero, one] satisfying
3038 // `a.merge(a.split(b)...) == b`. (Or its equivalent in valid C++.)
3039 constexpr std::tuple<Styles, Styles> split(Styles data) const {
3040 Styles const& mask = *this;
3041 return {~mask & data, mask & data};
3045 // Get styles from an HWND.
3046 constexpr auto const GetStyles = [](HWND hwnd) {
3047 return Styles{.style = ::GetWindowLongPtrW(hwnd, GWL_STYLE),
3048 .ex = ::GetWindowLongPtrW(hwnd, GWL_EXSTYLE)};
3050 constexpr auto const SetStyles = [](HWND hwnd, Styles styles) {
3051 VERIFY_WINDOW_STYLE(styles.style);
3052 ::SetWindowLongPtrW(hwnd, GWL_STYLE, styles.style);
3053 ::SetWindowLongPtrW(hwnd, GWL_EXSTYLE, styles.ex);
3056 // Get styles from *this.
3057 auto const GetCachedStyles = [&]() {
3058 return mOldStyles.map([](auto const& m) {
3059 return Styles{.style = m.style, .ex = m.exStyle};
3062 auto const SetCachedStyles = [&](Styles styles) {
3063 using WStyles = nsWindow::WindowStyles;
3064 mOldStyles = Some(WStyles{.style = styles.style, .exStyle = styles.ex});
3067 // The mask describing the "chrome" which this function is supposed to remove
3068 // (or restore, as the case may be). Other style-flags will be left untouched.
3069 constexpr static const Styles kChromeMask{
3070 .style = WS_CAPTION | WS_THICKFRAME,
3071 .ex = WS_EX_DLGMODALFRAME | WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE |
3072 WS_EX_STATICEDGE};
3074 // The desired style-flagset for fullscreen windows. (This happens to be all
3075 // zeroes, but we don't need to rely on that.)
3076 constexpr static const Styles kFullscreenChrome{.style = 0, .ex = 0};
3078 auto const [chromeless, currentChrome] = kChromeMask.split(GetStyles(hwnd));
3079 Styles newChrome{}, oldChrome{};
3081 mHideChrome = aShouldHide;
3082 if (aShouldHide) {
3083 newChrome = kFullscreenChrome;
3084 oldChrome = currentChrome;
3085 } else {
3086 // if there's nothing to "restore" it to, just use what's there now
3087 oldChrome = GetCachedStyles().refOr(currentChrome);
3088 newChrome = oldChrome;
3089 if (mFutureMarginsToUse) {
3090 SetNonClientMargins(mFutureMarginsOnceChromeShows);
3094 SetCachedStyles(oldChrome);
3095 SetStyles(hwnd, kChromeMask.merge(chromeless, newChrome));
3098 /**************************************************************
3100 * SECTION: nsWindow::Invalidate
3102 * Invalidate an area of the client for painting.
3104 **************************************************************/
3106 // Invalidate this component visible area
3107 void nsWindow::Invalidate(bool aEraseBackground, bool aUpdateNCArea,
3108 bool aIncludeChildren) {
3109 if (!mWnd) {
3110 return;
3113 #ifdef WIDGET_DEBUG_OUTPUT
3114 debug_DumpInvalidate(stdout, this, nullptr, "noname", (int32_t)mWnd);
3115 #endif // WIDGET_DEBUG_OUTPUT
3117 DWORD flags = RDW_INVALIDATE;
3118 if (aEraseBackground) {
3119 flags |= RDW_ERASE;
3121 if (aUpdateNCArea) {
3122 flags |= RDW_FRAME;
3124 if (aIncludeChildren) {
3125 flags |= RDW_ALLCHILDREN;
3128 VERIFY(::RedrawWindow(mWnd, nullptr, nullptr, flags));
3131 // Invalidate this component visible area
3132 void nsWindow::Invalidate(const LayoutDeviceIntRect& aRect) {
3133 if (mWnd) {
3134 #ifdef WIDGET_DEBUG_OUTPUT
3135 debug_DumpInvalidate(stdout, this, &aRect, "noname", (int32_t)mWnd);
3136 #endif // WIDGET_DEBUG_OUTPUT
3138 RECT rect;
3140 rect.left = aRect.X();
3141 rect.top = aRect.Y();
3142 rect.right = aRect.XMost();
3143 rect.bottom = aRect.YMost();
3145 VERIFY(::InvalidateRect(mWnd, &rect, FALSE));
3149 static LRESULT CALLBACK FullscreenTransitionWindowProc(HWND hWnd, UINT uMsg,
3150 WPARAM wParam,
3151 LPARAM lParam) {
3152 switch (uMsg) {
3153 case WM_FULLSCREEN_TRANSITION_BEFORE:
3154 case WM_FULLSCREEN_TRANSITION_AFTER: {
3155 DWORD duration = (DWORD)lParam;
3156 DWORD flags = AW_BLEND;
3157 if (uMsg == WM_FULLSCREEN_TRANSITION_AFTER) {
3158 flags |= AW_HIDE;
3160 ::AnimateWindow(hWnd, duration, flags);
3161 // The message sender should have added ref for us.
3162 NS_DispatchToMainThread(
3163 already_AddRefed<nsIRunnable>((nsIRunnable*)wParam));
3164 break;
3166 case WM_DESTROY:
3167 ::PostQuitMessage(0);
3168 break;
3169 default:
3170 return ::DefWindowProcW(hWnd, uMsg, wParam, lParam);
3172 return 0;
3175 struct FullscreenTransitionInitData {
3176 LayoutDeviceIntRect mBounds;
3177 HANDLE mSemaphore;
3178 HANDLE mThread;
3179 HWND mWnd;
3181 FullscreenTransitionInitData()
3182 : mSemaphore(nullptr), mThread(nullptr), mWnd(nullptr) {}
3184 ~FullscreenTransitionInitData() {
3185 if (mSemaphore) {
3186 ::CloseHandle(mSemaphore);
3188 if (mThread) {
3189 ::CloseHandle(mThread);
3194 static DWORD WINAPI FullscreenTransitionThreadProc(LPVOID lpParam) {
3195 // Initialize window class
3196 static bool sInitialized = false;
3197 if (!sInitialized) {
3198 WNDCLASSW wc = {};
3199 wc.lpfnWndProc = ::FullscreenTransitionWindowProc;
3200 wc.hInstance = nsToolkit::mDllInstance;
3201 wc.hbrBackground = ::CreateSolidBrush(RGB(0, 0, 0));
3202 wc.lpszClassName = kClassNameTransition;
3203 ::RegisterClassW(&wc);
3204 sInitialized = true;
3207 auto data = static_cast<FullscreenTransitionInitData*>(lpParam);
3208 HWND wnd = ::CreateWindowW(kClassNameTransition, L"", 0, 0, 0, 0, 0, nullptr,
3209 nullptr, nsToolkit::mDllInstance, nullptr);
3210 if (!wnd) {
3211 ::ReleaseSemaphore(data->mSemaphore, 1, nullptr);
3212 return 0;
3215 // Since AnimateWindow blocks the thread of the transition window,
3216 // we need to hide the cursor for that window, otherwise the system
3217 // would show the busy pointer to the user.
3218 ::ShowCursor(false);
3219 ::SetWindowLongW(wnd, GWL_STYLE, 0);
3220 ::SetWindowLongW(
3221 wnd, GWL_EXSTYLE,
3222 WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE);
3223 ::SetWindowPos(wnd, HWND_TOPMOST, data->mBounds.X(), data->mBounds.Y(),
3224 data->mBounds.Width(), data->mBounds.Height(), 0);
3225 data->mWnd = wnd;
3226 ::ReleaseSemaphore(data->mSemaphore, 1, nullptr);
3227 // The initialization data may no longer be valid
3228 // after we release the semaphore.
3229 data = nullptr;
3231 MSG msg;
3232 while (::GetMessageW(&msg, nullptr, 0, 0)) {
3233 ::TranslateMessage(&msg);
3234 ::DispatchMessage(&msg);
3236 ::ShowCursor(true);
3237 ::DestroyWindow(wnd);
3238 return 0;
3241 class FullscreenTransitionData final : public nsISupports {
3242 public:
3243 NS_DECL_ISUPPORTS
3245 explicit FullscreenTransitionData(HWND aWnd) : mWnd(aWnd) {
3246 MOZ_ASSERT(NS_IsMainThread(),
3247 "FullscreenTransitionData "
3248 "should be constructed in the main thread");
3251 const HWND mWnd;
3253 private:
3254 ~FullscreenTransitionData() {
3255 MOZ_ASSERT(NS_IsMainThread(),
3256 "FullscreenTransitionData "
3257 "should be deconstructed in the main thread");
3258 ::PostMessageW(mWnd, WM_DESTROY, 0, 0);
3262 NS_IMPL_ISUPPORTS0(FullscreenTransitionData)
3264 /* virtual */
3265 bool nsWindow::PrepareForFullscreenTransition(nsISupports** aData) {
3266 FullscreenTransitionInitData initData;
3267 nsCOMPtr<nsIScreen> screen = GetWidgetScreen();
3268 const DesktopIntRect rect = screen->GetRectDisplayPix();
3269 MOZ_ASSERT(BoundsUseDesktopPixels(),
3270 "Should only be called on top-level window");
3271 initData.mBounds =
3272 LayoutDeviceIntRect::Round(rect * GetDesktopToDeviceScale());
3274 // Create a semaphore for synchronizing the window handle which will
3275 // be created by the transition thread and used by the main thread for
3276 // posting the transition messages.
3277 initData.mSemaphore = ::CreateSemaphore(nullptr, 0, 1, nullptr);
3278 if (initData.mSemaphore) {
3279 initData.mThread = ::CreateThread(
3280 nullptr, 0, FullscreenTransitionThreadProc, &initData, 0, nullptr);
3281 if (initData.mThread) {
3282 ::WaitForSingleObject(initData.mSemaphore, INFINITE);
3285 if (!initData.mWnd) {
3286 return false;
3289 mTransitionWnd = initData.mWnd;
3291 auto data = new FullscreenTransitionData(initData.mWnd);
3292 *aData = data;
3293 NS_ADDREF(data);
3294 return true;
3297 /* virtual */
3298 void nsWindow::PerformFullscreenTransition(FullscreenTransitionStage aStage,
3299 uint16_t aDuration,
3300 nsISupports* aData,
3301 nsIRunnable* aCallback) {
3302 auto data = static_cast<FullscreenTransitionData*>(aData);
3303 nsCOMPtr<nsIRunnable> callback = aCallback;
3304 UINT msg = aStage == eBeforeFullscreenToggle ? WM_FULLSCREEN_TRANSITION_BEFORE
3305 : WM_FULLSCREEN_TRANSITION_AFTER;
3306 WPARAM wparam = (WPARAM)callback.forget().take();
3307 ::PostMessage(data->mWnd, msg, wparam, (LPARAM)aDuration);
3310 /* virtual */
3311 void nsWindow::CleanupFullscreenTransition() {
3312 MOZ_ASSERT(NS_IsMainThread(),
3313 "CleanupFullscreenTransition "
3314 "should only run on the main thread");
3316 mTransitionWnd = nullptr;
3319 void nsWindow::TryDwmResizeHack() {
3320 // The "DWM resize hack", aka the "fullscreen resize hack", is a workaround
3321 // for DWM's occasional and not-entirely-predictable failure to update its
3322 // internal state when the client area of a window changes without changing
3323 // the window size. The effect of this is that DWM will clip the content of
3324 // the window to its former client area.
3326 // It is not known under what circumstances the bug will trigger. Windows 11
3327 // is known to be required, but many Windows 11 machines do not exhibit the
3328 // issue. Even machines that _do_ exhibit it will sometimes not do so when
3329 // apparently-irrelevant changes are made to the configuration. (See bug
3330 // 1763981.)
3332 // The bug is triggered by Firefox when a maximized window (which has window
3333 // decorations) becomes fullscreen (which doesn't). To work around this, if we
3334 // think it may occur, we "flicker-resize" the relevant window -- that is, we
3335 // reduce its height by 1px, then restore it. This causes DWM to acquire the
3336 // new client-area metrics.
3338 // Note that, in particular, this bug will not occur when using a separate
3339 // compositor window, as our compositor windows never have any nonclient area.
3341 // This is admittedly a sledgehammer where a screwdriver should suffice.
3343 // ---------------------------------------------------------------------------
3345 // Regardless of preferences or heuristics, only apply the hack if this is the
3346 // first time we've entered fullscreen across the entire Firefox session.
3347 // (Subsequent transitions to fullscreen, even with different windows, don't
3348 // appear to induce the bug.)
3350 // (main thread only; `atomic` not needed)
3351 static bool sIsFirstFullscreenEntry = true;
3352 bool isFirstFullscreenEntry = sIsFirstFullscreenEntry;
3353 sIsFirstFullscreenEntry = false;
3354 if (MOZ_LIKELY(!isFirstFullscreenEntry)) {
3355 return;
3357 MOZ_LOG(gWindowsLog, LogLevel::Verbose,
3358 ("%s: first fullscreen entry", __PRETTY_FUNCTION__));
3361 // Check whether to try to apply the DWM resize hack, based on the override
3362 // pref and/or some internal heuristics.
3364 const auto hackApplicationHeuristics = [&]() -> bool {
3365 // The bug has only been seen under Windows 11. (At time of writing, this
3366 // is the latest version of Windows.)
3367 if (!IsWin11OrLater()) {
3368 return false;
3371 KnowsCompositor const* const kc = mWindowRenderer->AsKnowsCompositor();
3372 // This should never happen...
3373 MOZ_ASSERT(kc);
3374 // ... so if it does, we are in uncharted territory: don't apply the hack.
3375 if (!kc) {
3376 return false;
3379 // The bug doesn't occur when we're using a separate compositor window
3380 // (since the compositor window always comprises exactly its client area,
3381 // with no non-client border).
3382 if (kc->GetUseCompositorWnd()) {
3383 return false;
3386 // Otherwise, apply the hack.
3387 return true;
3390 // Figure out whether or not we should perform the hack, and -- arguably
3391 // more importantly -- log that decision.
3392 bool const shouldApplyHack = [&]() {
3393 enum Reason : bool { Pref, Heuristics };
3394 auto const msg = [&](bool decision, Reason reason) -> bool {
3395 MOZ_LOG(gWindowsLog, LogLevel::Verbose,
3396 ("%s %s per %s", decision ? "applying" : "skipping",
3397 "DWM resize hack", reason == Pref ? "pref" : "heuristics"));
3398 return decision;
3400 switch (StaticPrefs::widget_windows_apply_dwm_resize_hack()) {
3401 case 0:
3402 return msg(false, Pref);
3403 case 1:
3404 return msg(true, Pref);
3405 default: // treat all other values as `auto`
3406 return msg(hackApplicationHeuristics(), Heuristics);
3408 }();
3410 if (!shouldApplyHack) {
3411 return;
3415 // The DWM bug is believed to involve a race condition: some users have
3416 // reported that setting a custom theme or adding unused command-line
3417 // parameters sometimes causes the bug to vanish.
3419 // Out of an abundance of caution, we therefore apply the hack in a later
3420 // event, rather than inline.
3421 NS_DispatchToMainThread(NS_NewRunnableFunction(
3422 "nsWindow::TryFullscreenResizeHack", [self = RefPtr(this)]() {
3423 HWND const hwnd = self->GetWindowHandle();
3425 if (self->mFrameState->GetSizeMode() != nsSizeMode_Fullscreen) {
3426 MOZ_LOG(gWindowsLog, mozilla::LogLevel::Info,
3427 ("DWM resize hack: window no longer fullscreen; aborting"));
3428 return;
3431 RECT origRect;
3432 if (!::GetWindowRect(hwnd, &origRect)) {
3433 MOZ_LOG(gWindowsLog, mozilla::LogLevel::Error,
3434 ("DWM resize hack: could not get window size?!"));
3435 return;
3437 LONG const x = origRect.left;
3438 LONG const y = origRect.top;
3439 LONG const width = origRect.right - origRect.left;
3440 LONG const height = origRect.bottom - origRect.top;
3442 MOZ_DIAGNOSTIC_ASSERT(!self->mIsPerformingDwmFlushHack);
3443 auto const onExit =
3444 MakeScopeExit([&, oldVal = self->mIsPerformingDwmFlushHack]() {
3445 self->mIsPerformingDwmFlushHack = oldVal;
3447 self->mIsPerformingDwmFlushHack = true;
3449 MOZ_LOG(gWindowsLog, LogLevel::Debug,
3450 ("beginning DWM resize hack for HWND %08" PRIXPTR,
3451 uintptr_t(hwnd)));
3452 ::MoveWindow(hwnd, x, y, width, height - 1, FALSE);
3453 ::MoveWindow(hwnd, x, y, width, height, TRUE);
3454 MOZ_LOG(gWindowsLog, LogLevel::Debug,
3455 ("concluded DWM resize hack for HWND %08" PRIXPTR,
3456 uintptr_t(hwnd)));
3457 }));
3460 void nsWindow::OnFullscreenChanged(nsSizeMode aOldSizeMode, bool aFullScreen) {
3461 MOZ_ASSERT((aOldSizeMode != nsSizeMode_Fullscreen) == aFullScreen);
3463 // HACK: Potentially flicker-resize the window, to force DWM to get the right
3464 // client-area information.
3465 if (aFullScreen) {
3466 TryDwmResizeHack();
3469 // Hide chrome and reposition window. Note this will also cache dimensions for
3470 // restoration, so it should only be called once per fullscreen request.
3472 // Don't do this when minimized, since our bounds make no sense then, nor when
3473 // coming back from that state.
3474 const bool toOrFromMinimized =
3475 mFrameState->GetSizeMode() == nsSizeMode_Minimized ||
3476 aOldSizeMode == nsSizeMode_Minimized;
3477 if (!toOrFromMinimized) {
3478 InfallibleMakeFullScreen(aFullScreen);
3481 // Possibly notify the taskbar that we have changed our fullscreen mode.
3482 TaskbarConcealer::OnFullscreenChanged(this, aFullScreen);
3485 nsresult nsWindow::MakeFullScreen(bool aFullScreen) {
3486 mFrameState->EnsureFullscreenMode(aFullScreen);
3487 return NS_OK;
3490 /**************************************************************
3492 * SECTION: Native data storage
3494 * nsIWidget::GetNativeData
3495 * nsIWidget::FreeNativeData
3497 * Set or clear native data based on a constant.
3499 **************************************************************/
3501 // Return some native data according to aDataType
3502 void* nsWindow::GetNativeData(uint32_t aDataType) {
3503 switch (aDataType) {
3504 case NS_NATIVE_WIDGET:
3505 case NS_NATIVE_WINDOW:
3506 case NS_NATIVE_WINDOW_WEBRTC_DEVICE_ID:
3507 return (void*)mWnd;
3508 case NS_NATIVE_GRAPHIC:
3509 MOZ_ASSERT_UNREACHABLE("Not supported on Windows:");
3510 return nullptr;
3511 case NS_RAW_NATIVE_IME_CONTEXT: {
3512 void* pseudoIMEContext = GetPseudoIMEContext();
3513 if (pseudoIMEContext) {
3514 return pseudoIMEContext;
3516 [[fallthrough]];
3518 case NS_NATIVE_TSF_THREAD_MGR:
3519 case NS_NATIVE_TSF_CATEGORY_MGR:
3520 case NS_NATIVE_TSF_DISPLAY_ATTR_MGR:
3521 return IMEHandler::GetNativeData(this, aDataType);
3523 default:
3524 break;
3527 return nullptr;
3530 // Free some native data according to aDataType
3531 void nsWindow::FreeNativeData(void* data, uint32_t aDataType) {
3532 switch (aDataType) {
3533 case NS_NATIVE_GRAPHIC:
3534 case NS_NATIVE_WIDGET:
3535 case NS_NATIVE_WINDOW:
3536 break;
3537 default:
3538 break;
3542 /**************************************************************
3544 * SECTION: nsIWidget::SetTitle
3546 * Set the main windows title text.
3548 **************************************************************/
3550 nsresult nsWindow::SetTitle(const nsAString& aTitle) {
3551 const nsString& strTitle = PromiseFlatString(aTitle);
3552 AutoRestore<bool> sendingText(mSendingSetText);
3553 mSendingSetText = true;
3554 ::SendMessageW(mWnd, WM_SETTEXT, (WPARAM)0, (LPARAM)(LPCWSTR)strTitle.get());
3555 return NS_OK;
3558 /**************************************************************
3560 * SECTION: nsIWidget::SetIcon
3562 * Set the main windows icon.
3564 **************************************************************/
3566 void nsWindow::SetBigIcon(HICON aIcon) {
3567 HICON icon =
3568 (HICON)::SendMessageW(mWnd, WM_SETICON, (WPARAM)ICON_BIG, (LPARAM)aIcon);
3569 if (icon) {
3570 ::DestroyIcon(icon);
3573 mIconBig = aIcon;
3576 void nsWindow::SetSmallIcon(HICON aIcon) {
3577 HICON icon = (HICON)::SendMessageW(mWnd, WM_SETICON, (WPARAM)ICON_SMALL,
3578 (LPARAM)aIcon);
3579 if (icon) {
3580 ::DestroyIcon(icon);
3583 mIconSmall = aIcon;
3586 void nsWindow::SetIcon(const nsAString& aIconSpec) {
3587 // Assume the given string is a local identifier for an icon file.
3589 nsCOMPtr<nsIFile> iconFile;
3590 ResolveIconName(aIconSpec, u".ico"_ns, getter_AddRefs(iconFile));
3591 if (!iconFile) return;
3593 nsAutoString iconPath;
3594 iconFile->GetPath(iconPath);
3596 // XXX this should use MZLU (see bug 239279)
3598 ::SetLastError(0);
3600 HICON bigIcon =
3601 (HICON)::LoadImageW(nullptr, (LPCWSTR)iconPath.get(), IMAGE_ICON,
3602 ::GetSystemMetrics(SM_CXICON),
3603 ::GetSystemMetrics(SM_CYICON), LR_LOADFROMFILE);
3604 HICON smallIcon =
3605 (HICON)::LoadImageW(nullptr, (LPCWSTR)iconPath.get(), IMAGE_ICON,
3606 ::GetSystemMetrics(SM_CXSMICON),
3607 ::GetSystemMetrics(SM_CYSMICON), LR_LOADFROMFILE);
3609 if (bigIcon) {
3610 SetBigIcon(bigIcon);
3612 #ifdef DEBUG_SetIcon
3613 else {
3614 NS_LossyConvertUTF16toASCII cPath(iconPath);
3615 MOZ_LOG(gWindowsLog, LogLevel::Info,
3616 ("\nIcon load error; icon=%s, rc=0x%08X\n\n", cPath.get(),
3617 ::GetLastError()));
3619 #endif
3620 if (smallIcon) {
3621 SetSmallIcon(smallIcon);
3623 #ifdef DEBUG_SetIcon
3624 else {
3625 NS_LossyConvertUTF16toASCII cPath(iconPath);
3626 MOZ_LOG(gWindowsLog, LogLevel::Info,
3627 ("\nSmall icon load error; icon=%s, rc=0x%08X\n\n", cPath.get(),
3628 ::GetLastError()));
3630 #endif
3633 void nsWindow::SetBigIconNoData() {
3634 HICON bigIcon =
3635 ::LoadIconW(::GetModuleHandleW(nullptr), gStockApplicationIcon);
3636 SetBigIcon(bigIcon);
3639 void nsWindow::SetSmallIconNoData() {
3640 HICON smallIcon =
3641 ::LoadIconW(::GetModuleHandleW(nullptr), gStockApplicationIcon);
3642 SetSmallIcon(smallIcon);
3645 /**************************************************************
3647 * SECTION: nsIWidget::WidgetToScreenOffset
3649 * Return this widget's origin in screen coordinates.
3651 **************************************************************/
3653 LayoutDeviceIntPoint nsWindow::WidgetToScreenOffset() {
3654 POINT point;
3655 point.x = 0;
3656 point.y = 0;
3657 ::ClientToScreen(mWnd, &point);
3658 return LayoutDeviceIntPoint(point.x, point.y);
3661 LayoutDeviceIntMargin nsWindow::ClientToWindowMargin() {
3662 if (mWindowType == WindowType::Popup) {
3663 return {};
3666 if (mCustomNonClient) {
3667 return NonClientSizeMargin(NormalWindowNonClientOffset());
3670 // Just use a dummy 200x200 at (200, 200) client rect as the rect.
3671 RECT clientRect;
3672 clientRect.left = 200;
3673 clientRect.top = 200;
3674 clientRect.right = 400;
3675 clientRect.bottom = 400;
3677 auto ToRect = [](const RECT& aRect) -> LayoutDeviceIntRect {
3678 return {aRect.left, aRect.top, aRect.right - aRect.left,
3679 aRect.bottom - aRect.top};
3682 RECT windowRect = clientRect;
3683 ::AdjustWindowRectEx(&windowRect, WindowStyle(), false, WindowExStyle());
3685 return ToRect(windowRect) - ToRect(clientRect);
3688 /**************************************************************
3690 * SECTION: nsIWidget::EnableDragDrop
3692 * Enables/Disables drag and drop of files on this widget.
3694 **************************************************************/
3696 void nsWindow::EnableDragDrop(bool aEnable) {
3697 if (!mWnd) {
3698 // Return early if the window already closed
3699 return;
3702 if (aEnable) {
3703 if (!mNativeDragTarget) {
3704 mNativeDragTarget = new nsNativeDragTarget(this);
3705 mNativeDragTarget->AddRef();
3706 ::RegisterDragDrop(mWnd, (LPDROPTARGET)mNativeDragTarget);
3708 } else {
3709 if (mWnd && mNativeDragTarget) {
3710 ::RevokeDragDrop(mWnd);
3711 mNativeDragTarget->DragCancel();
3712 NS_RELEASE(mNativeDragTarget);
3717 /**************************************************************
3719 * SECTION: nsIWidget::CaptureMouse
3721 * Enables/Disables system mouse capture.
3723 **************************************************************/
3725 void nsWindow::CaptureMouse(bool aCapture) {
3726 TRACKMOUSEEVENT mTrack;
3727 mTrack.cbSize = sizeof(TRACKMOUSEEVENT);
3728 mTrack.dwHoverTime = 0;
3729 mTrack.hwndTrack = mWnd;
3730 if (aCapture) {
3731 mTrack.dwFlags = TME_CANCEL | TME_LEAVE;
3732 ::SetCapture(mWnd);
3733 } else {
3734 mTrack.dwFlags = TME_LEAVE;
3735 ::ReleaseCapture();
3737 sIsInMouseCapture = aCapture;
3738 TrackMouseEvent(&mTrack);
3741 /**************************************************************
3743 * SECTION: nsIWidget::CaptureRollupEvents
3745 * Dealing with event rollup on destroy for popups. Enables &
3746 * Disables system capture of any and all events that would
3747 * cause a dropdown to be rolled up.
3749 **************************************************************/
3751 void nsWindow::CaptureRollupEvents(bool aDoCapture) {
3752 if (aDoCapture) {
3753 if (!sMsgFilterHook && !sCallProcHook && !sCallMouseHook) {
3754 RegisterSpecialDropdownHooks();
3756 sProcessHook = true;
3757 } else {
3758 sProcessHook = false;
3759 UnregisterSpecialDropdownHooks();
3763 /**************************************************************
3765 * SECTION: nsIWidget::GetAttention
3767 * Bring this window to the user's attention.
3769 **************************************************************/
3771 // Draw user's attention to this window until it comes to foreground.
3772 nsresult nsWindow::GetAttention(int32_t aCycleCount) {
3773 // Got window?
3774 if (!mWnd) return NS_ERROR_NOT_INITIALIZED;
3776 HWND flashWnd = WinUtils::GetTopLevelHWND(mWnd, false, false);
3777 HWND fgWnd = ::GetForegroundWindow();
3778 // Don't flash if the flash count is 0 or if the foreground window is our
3779 // window handle or that of our owned-most window.
3780 if (aCycleCount == 0 || flashWnd == fgWnd ||
3781 flashWnd == WinUtils::GetTopLevelHWND(fgWnd, false, false)) {
3782 return NS_OK;
3785 DWORD defaultCycleCount = 0;
3786 ::SystemParametersInfo(SPI_GETFOREGROUNDFLASHCOUNT, 0, &defaultCycleCount, 0);
3788 FLASHWINFO flashInfo = {sizeof(FLASHWINFO), flashWnd, FLASHW_ALL,
3789 aCycleCount > 0 ? aCycleCount : defaultCycleCount, 0};
3790 ::FlashWindowEx(&flashInfo);
3792 return NS_OK;
3795 void nsWindow::StopFlashing() {
3796 HWND flashWnd = mWnd;
3797 while (HWND ownerWnd = ::GetWindow(flashWnd, GW_OWNER)) {
3798 flashWnd = ownerWnd;
3801 FLASHWINFO flashInfo = {sizeof(FLASHWINFO), flashWnd, FLASHW_STOP, 0, 0};
3802 ::FlashWindowEx(&flashInfo);
3805 /**************************************************************
3807 * SECTION: nsIWidget::HasPendingInputEvent
3809 * Ask whether there user input events pending. All input events are
3810 * included, including those not targeted at this nsIwidget instance.
3812 **************************************************************/
3814 bool nsWindow::HasPendingInputEvent() {
3815 // If there is pending input or the user is currently
3816 // moving the window then return true.
3817 // Note: When the user is moving the window WIN32 spins
3818 // a separate event loop and input events are not
3819 // reported to the application.
3820 if (HIWORD(GetQueueStatus(QS_INPUT))) return true;
3821 GUITHREADINFO guiInfo;
3822 guiInfo.cbSize = sizeof(GUITHREADINFO);
3823 if (!GetGUIThreadInfo(GetCurrentThreadId(), &guiInfo)) return false;
3824 return GUI_INMOVESIZE == (guiInfo.flags & GUI_INMOVESIZE);
3827 /**************************************************************
3829 * SECTION: nsIWidget::GetWindowRenderer
3831 * Get the window renderer associated with this widget.
3833 **************************************************************/
3835 WindowRenderer* nsWindow::GetWindowRenderer() {
3836 if (mWindowRenderer) {
3837 return mWindowRenderer;
3840 if (!mLocalesChangedObserver) {
3841 mLocalesChangedObserver = new LocalesChangedObserver(this);
3844 // Try OMTC first.
3845 if (!mWindowRenderer && ShouldUseOffMainThreadCompositing()) {
3846 gfxWindowsPlatform::GetPlatform()->UpdateRenderMode();
3847 CreateCompositor();
3850 if (!mWindowRenderer) {
3851 MOZ_ASSERT(!mCompositorSession && !mCompositorBridgeChild);
3852 MOZ_ASSERT(!mCompositorWidgetDelegate);
3854 // Ensure we have a widget proxy even if we're not using the compositor,
3855 // since all our transparent window handling lives there.
3856 WinCompositorWidgetInitData initData(
3857 reinterpret_cast<uintptr_t>(mWnd),
3858 reinterpret_cast<uintptr_t>(static_cast<nsIWidget*>(this)),
3859 mTransparencyMode, mFrameState->GetSizeMode());
3860 // If we're not using the compositor, the options don't actually matter.
3861 CompositorOptions options(false, false);
3862 mBasicLayersSurface =
3863 new InProcessWinCompositorWidget(initData, options, this);
3864 mCompositorWidgetDelegate = mBasicLayersSurface;
3865 mWindowRenderer = CreateFallbackRenderer();
3868 NS_ASSERTION(mWindowRenderer, "Couldn't provide a valid window renderer.");
3870 if (mWindowRenderer) {
3871 // Update the size constraints now that the layer manager has been
3872 // created.
3873 KnowsCompositor* knowsCompositor = mWindowRenderer->AsKnowsCompositor();
3874 if (knowsCompositor) {
3875 SizeConstraints c = mSizeConstraints;
3876 mMaxTextureSize = knowsCompositor->GetMaxTextureSize();
3877 c.mMaxSize.width = std::min(c.mMaxSize.width, mMaxTextureSize);
3878 c.mMaxSize.height = std::min(c.mMaxSize.height, mMaxTextureSize);
3879 nsBaseWidget::SetSizeConstraints(c);
3883 return mWindowRenderer;
3886 /**************************************************************
3888 * SECTION: nsBaseWidget::SetCompositorWidgetDelegate
3890 * Called to connect the nsWindow to the delegate providing
3891 * platform compositing API access.
3893 **************************************************************/
3895 void nsWindow::SetCompositorWidgetDelegate(CompositorWidgetDelegate* delegate) {
3896 if (delegate) {
3897 mCompositorWidgetDelegate = delegate->AsPlatformSpecificDelegate();
3898 MOZ_ASSERT(mCompositorWidgetDelegate,
3899 "nsWindow::SetCompositorWidgetDelegate called with a "
3900 "non-PlatformCompositorWidgetDelegate");
3901 } else {
3902 mCompositorWidgetDelegate = nullptr;
3906 /**************************************************************
3908 * SECTION: nsIWidget::OnDefaultButtonLoaded
3910 * Called after the dialog is loaded and it has a default button.
3912 **************************************************************/
3914 nsresult nsWindow::OnDefaultButtonLoaded(
3915 const LayoutDeviceIntRect& aButtonRect) {
3916 if (aButtonRect.IsEmpty()) return NS_OK;
3918 // Don't snap when we are not active.
3919 HWND activeWnd = ::GetActiveWindow();
3920 if (activeWnd != ::GetForegroundWindow() ||
3921 WinUtils::GetTopLevelHWND(mWnd, true) !=
3922 WinUtils::GetTopLevelHWND(activeWnd, true)) {
3923 return NS_OK;
3926 bool isAlwaysSnapCursor =
3927 Preferences::GetBool("ui.cursor_snapping.always_enabled", false);
3929 if (!isAlwaysSnapCursor) {
3930 BOOL snapDefaultButton;
3931 if (!::SystemParametersInfo(SPI_GETSNAPTODEFBUTTON, 0, &snapDefaultButton,
3932 0) ||
3933 !snapDefaultButton)
3934 return NS_OK;
3937 LayoutDeviceIntRect widgetRect = GetScreenBounds();
3938 LayoutDeviceIntRect buttonRect(aButtonRect + widgetRect.TopLeft());
3940 LayoutDeviceIntPoint centerOfButton(buttonRect.X() + buttonRect.Width() / 2,
3941 buttonRect.Y() + buttonRect.Height() / 2);
3942 // The center of the button can be outside of the widget.
3943 // E.g., it could be hidden by scrolling.
3944 if (!widgetRect.Contains(centerOfButton)) {
3945 return NS_OK;
3948 if (!::SetCursorPos(centerOfButton.x, centerOfButton.y)) {
3949 NS_ERROR("SetCursorPos failed");
3950 return NS_ERROR_FAILURE;
3952 return NS_OK;
3955 uint32_t nsWindow::GetMaxTouchPoints() const {
3956 return WinUtils::GetMaxTouchPoints();
3959 void nsWindow::SetWindowClass(const nsAString& xulWinType,
3960 const nsAString& xulWinClass,
3961 const nsAString& xulWinName) {
3962 mIsEarlyBlankWindow = xulWinType.EqualsLiteral("navigator:blank");
3965 /**************************************************************
3966 **************************************************************
3968 ** BLOCK: Moz Events
3970 ** Moz GUI event management.
3972 **************************************************************
3973 **************************************************************/
3975 /**************************************************************
3977 * SECTION: Mozilla event initialization
3979 * Helpers for initializing moz events.
3981 **************************************************************/
3983 // Event initialization
3984 void nsWindow::InitEvent(WidgetGUIEvent& event, LayoutDeviceIntPoint* aPoint) {
3985 if (nullptr == aPoint) { // use the point from the event
3986 // get the message position in client coordinates
3987 if (mWnd != nullptr) {
3988 DWORD pos = ::GetMessagePos();
3989 POINT cpos;
3991 cpos.x = GET_X_LPARAM(pos);
3992 cpos.y = GET_Y_LPARAM(pos);
3994 ::ScreenToClient(mWnd, &cpos);
3995 event.mRefPoint = LayoutDeviceIntPoint(cpos.x, cpos.y);
3996 } else {
3997 event.mRefPoint = LayoutDeviceIntPoint(0, 0);
3999 } else {
4000 // use the point override if provided
4001 event.mRefPoint = *aPoint;
4004 event.AssignEventTime(CurrentMessageWidgetEventTime());
4007 WidgetEventTime nsWindow::CurrentMessageWidgetEventTime() const {
4008 LONG messageTime = ::GetMessageTime();
4009 return WidgetEventTime(GetMessageTimeStamp(messageTime));
4012 /**************************************************************
4014 * SECTION: Moz event dispatch helpers
4016 * Helpers for dispatching different types of moz events.
4018 **************************************************************/
4020 // Main event dispatch. Invokes callback and ProcessEvent method on
4021 // Event Listener object. Part of nsIWidget.
4022 nsresult nsWindow::DispatchEvent(WidgetGUIEvent* event,
4023 nsEventStatus& aStatus) {
4024 #ifdef WIDGET_DEBUG_OUTPUT
4025 debug_DumpEvent(stdout, event->mWidget, event, "something", (int32_t)mWnd);
4026 #endif // WIDGET_DEBUG_OUTPUT
4028 aStatus = nsEventStatus_eIgnore;
4030 // Top level windows can have a view attached which requires events be sent
4031 // to the underlying base window and the view. Added when we combined the
4032 // base chrome window with the main content child for nc client area (title
4033 // bar) rendering.
4034 if (mAttachedWidgetListener) {
4035 aStatus = mAttachedWidgetListener->HandleEvent(event, mUseAttachedEvents);
4036 } else if (mWidgetListener) {
4037 aStatus = mWidgetListener->HandleEvent(event, mUseAttachedEvents);
4040 // the window can be destroyed during processing of seemingly innocuous events
4041 // like, say, mousedowns due to the magic of scripting. mousedowns will return
4042 // nsEventStatus_eIgnore, which causes problems with the deleted window.
4043 // therefore:
4044 if (mOnDestroyCalled) aStatus = nsEventStatus_eConsumeNoDefault;
4045 return NS_OK;
4048 bool nsWindow::DispatchStandardEvent(EventMessage aMsg) {
4049 WidgetGUIEvent event(true, aMsg, this);
4050 InitEvent(event);
4052 bool result = DispatchWindowEvent(event);
4053 return result;
4056 bool nsWindow::DispatchKeyboardEvent(WidgetKeyboardEvent* event) {
4057 nsEventStatus status = DispatchInputEvent(event).mContentStatus;
4058 return ConvertStatus(status);
4061 bool nsWindow::DispatchContentCommandEvent(WidgetContentCommandEvent* aEvent) {
4062 nsEventStatus status;
4063 DispatchEvent(aEvent, status);
4064 return ConvertStatus(status);
4067 bool nsWindow::DispatchWheelEvent(WidgetWheelEvent* aEvent) {
4068 nsEventStatus status =
4069 DispatchInputEvent(aEvent->AsInputEvent()).mContentStatus;
4070 return ConvertStatus(status);
4073 // Recursively dispatch synchronous paints for nsIWidget
4074 // descendants with invalidated rectangles.
4075 BOOL CALLBACK nsWindow::DispatchStarvedPaints(HWND aWnd, LPARAM aMsg) {
4076 LONG_PTR proc = ::GetWindowLongPtrW(aWnd, GWLP_WNDPROC);
4077 if (proc == (LONG_PTR)&nsWindow::WindowProc) {
4078 // its one of our windows so check to see if it has a
4079 // invalidated rect. If it does. Dispatch a synchronous
4080 // paint.
4081 if (GetUpdateRect(aWnd, nullptr, FALSE)) VERIFY(::UpdateWindow(aWnd));
4083 return TRUE;
4086 // Check for pending paints and dispatch any pending paint
4087 // messages for any nsIWidget which is a descendant of the
4088 // top-level window that *this* window is embedded within.
4090 // Note: We do not dispatch pending paint messages for non
4091 // nsIWidget managed windows.
4092 void nsWindow::DispatchPendingEvents() {
4093 // We need to ensure that reflow events do not get starved.
4094 // At the same time, we don't want to recurse through here
4095 // as that would prevent us from dispatching starved paints.
4096 static int recursionBlocker = 0;
4097 if (recursionBlocker++ == 0) {
4098 NS_ProcessPendingEvents(nullptr, PR_MillisecondsToInterval(100));
4099 --recursionBlocker;
4102 // Quickly check to see if there are any paint events pending,
4103 // but only dispatch them if it has been long enough since the
4104 // last paint completed.
4105 if (::GetQueueStatus(QS_PAINT) &&
4106 ((TimeStamp::Now() - mLastPaintEndTime).ToMilliseconds() >= 50)) {
4107 // Find the top level window.
4108 HWND topWnd = WinUtils::GetTopLevelHWND(mWnd);
4110 // Dispatch pending paints for topWnd and all its descendant windows.
4111 // Note: EnumChildWindows enumerates all descendant windows not just
4112 // the children (but not the window itself).
4113 nsWindow::DispatchStarvedPaints(topWnd, 0);
4114 ::EnumChildWindows(topWnd, nsWindow::DispatchStarvedPaints, 0);
4118 void nsWindow::DispatchCustomEvent(const nsString& eventName) {
4119 if (Document* doc = GetDocument()) {
4120 if (nsPIDOMWindowOuter* win = doc->GetWindow()) {
4121 win->DispatchCustomEvent(eventName, ChromeOnlyDispatch::eYes);
4126 bool nsWindow::TouchEventShouldStartDrag(EventMessage aEventMessage,
4127 LayoutDeviceIntPoint aEventPoint) {
4128 // Allow users to start dragging by double-tapping.
4129 if (aEventMessage == eMouseDoubleClick) {
4130 return true;
4133 // In chrome UI, allow touchdownstartsdrag attributes
4134 // to cause any touchdown event to trigger a drag.
4135 if (aEventMessage == eMouseDown) {
4136 WidgetMouseEvent hittest(true, eMouseHitTest, this,
4137 WidgetMouseEvent::eReal);
4138 hittest.mRefPoint = aEventPoint;
4139 hittest.mIgnoreRootScrollFrame = true;
4140 hittest.mInputSource = MouseEvent_Binding::MOZ_SOURCE_TOUCH;
4141 DispatchInputEvent(&hittest);
4143 if (EventTarget* target = hittest.GetDOMEventTarget()) {
4144 if (nsIContent* content = nsIContent::FromEventTarget(target)) {
4145 // Check if the element or any parent element has the
4146 // attribute we're looking for.
4147 for (Element* element = content->GetAsElementOrParentElement(); element;
4148 element = element->GetParentElement()) {
4149 nsAutoString startDrag;
4150 element->GetAttribute(u"touchdownstartsdrag"_ns, startDrag);
4151 if (!startDrag.IsEmpty()) {
4152 return true;
4159 return false;
4162 // Deal with all sort of mouse event
4163 bool nsWindow::DispatchMouseEvent(EventMessage aEventMessage, WPARAM wParam,
4164 LPARAM lParam, bool aIsContextMenuKey,
4165 int16_t aButton, uint16_t aInputSource,
4166 WinPointerInfo* aPointerInfo,
4167 bool aIgnoreAPZ) {
4168 ContextMenuPreventer contextMenuPreventer(this);
4169 bool result = false;
4171 UserActivity();
4173 if (!mWidgetListener) {
4174 return result;
4177 LayoutDeviceIntPoint eventPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
4178 LayoutDeviceIntPoint mpScreen = eventPoint + WidgetToScreenOffset();
4180 // Suppress mouse moves caused by widget creation. Make sure to do this early
4181 // so that we update sLastMouseMovePoint even for touch-induced mousemove
4182 // events.
4183 if (aEventMessage == eMouseMove) {
4184 if ((sLastMouseMovePoint.x == mpScreen.x.value) &&
4185 (sLastMouseMovePoint.y == mpScreen.y.value)) {
4186 return result;
4188 sLastMouseMovePoint.x = mpScreen.x;
4189 sLastMouseMovePoint.y = mpScreen.y;
4192 if (!aIgnoreAPZ && WinUtils::GetIsMouseFromTouch(aEventMessage)) {
4193 if (mTouchWindow) {
4194 // If mTouchWindow is true, then we must have APZ enabled and be
4195 // feeding it raw touch events. In that case we only want to
4196 // send touch-generated mouse events to content if they should
4197 // start a touch-based drag-and-drop gesture, such as on
4198 // double-tapping or when tapping elements marked with the
4199 // touchdownstartsdrag attribute in chrome UI.
4200 MOZ_ASSERT(mAPZC);
4201 if (TouchEventShouldStartDrag(aEventMessage, eventPoint)) {
4202 aEventMessage = eMouseTouchDrag;
4203 } else {
4204 return result;
4209 uint32_t pointerId =
4210 aPointerInfo ? aPointerInfo->pointerId : MOUSE_POINTERID();
4212 switch (aEventMessage) {
4213 case eMouseDown:
4214 CaptureMouse(true);
4215 break;
4217 // eMouseMove and eMouseExitFromWidget are here because we need to make
4218 // sure capture flag isn't left on after a drag where we wouldn't see a
4219 // button up message (see bug 324131).
4220 case eMouseUp:
4221 case eMouseMove:
4222 case eMouseExitFromWidget:
4223 if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)) &&
4224 sIsInMouseCapture)
4225 CaptureMouse(false);
4226 break;
4228 default:
4229 break;
4231 } // switch
4233 WidgetMouseEvent event(true, aEventMessage, this, WidgetMouseEvent::eReal,
4234 aIsContextMenuKey ? WidgetMouseEvent::eContextMenuKey
4235 : WidgetMouseEvent::eNormal);
4236 if (aEventMessage == eContextMenu && aIsContextMenuKey) {
4237 LayoutDeviceIntPoint zero(0, 0);
4238 InitEvent(event, &zero);
4239 } else {
4240 InitEvent(event, &eventPoint);
4243 ModifierKeyState modifierKeyState;
4244 modifierKeyState.InitInputEvent(event);
4246 // eContextMenu with Shift state is special. It won't fire "contextmenu"
4247 // event in the web content for blocking web content to prevent its default.
4248 // However, Shift+F10 is a standard shortcut key on Windows. Therefore,
4249 // this should not block web page to prevent its default. I.e., it should
4250 // behave same as ContextMenu key without Shift key.
4251 // XXX Should we allow to block web page to prevent its default with
4252 // Ctrl+Shift+F10 or Alt+Shift+F10 instead?
4253 if (aEventMessage == eContextMenu && aIsContextMenuKey && event.IsShift() &&
4254 NativeKey::LastKeyOrCharMSG().message == WM_SYSKEYDOWN &&
4255 NativeKey::LastKeyOrCharMSG().wParam == VK_F10) {
4256 event.mModifiers &= ~MODIFIER_SHIFT;
4259 event.mButton = aButton;
4260 event.mInputSource = aInputSource;
4261 if (aPointerInfo) {
4262 // Mouse events from Windows WM_POINTER*. Fill more information in
4263 // WidgetMouseEvent.
4264 event.AssignPointerHelperData(*aPointerInfo);
4265 event.mPressure = aPointerInfo->mPressure;
4266 event.mButtons = aPointerInfo->mButtons;
4267 } else {
4268 // If we get here the mouse events must be from non-touch sources, so
4269 // convert it to pointer events as well
4270 event.convertToPointer = true;
4271 event.pointerId = pointerId;
4274 // Static variables used to distinguish simple-, double- and triple-clicks.
4275 static POINT sLastMousePoint = {0};
4276 static LONG sLastMouseDownTime = 0L;
4277 static LONG sLastClickCount = 0L;
4278 static BYTE sLastMouseButton = 0;
4280 bool insideMovementThreshold =
4281 (DeprecatedAbs(sLastMousePoint.x - eventPoint.x.value) <
4282 (short)::GetSystemMetrics(SM_CXDOUBLECLK)) &&
4283 (DeprecatedAbs(sLastMousePoint.y - eventPoint.y.value) <
4284 (short)::GetSystemMetrics(SM_CYDOUBLECLK));
4286 BYTE eventButton;
4287 switch (aButton) {
4288 case MouseButton::ePrimary:
4289 eventButton = VK_LBUTTON;
4290 break;
4291 case MouseButton::eMiddle:
4292 eventButton = VK_MBUTTON;
4293 break;
4294 case MouseButton::eSecondary:
4295 eventButton = VK_RBUTTON;
4296 break;
4297 default:
4298 eventButton = 0;
4299 break;
4302 // Doubleclicks are used to set the click count, then changed to mousedowns
4303 // We're going to time double-clicks from mouse *up* to next mouse *down*
4304 LONG curMsgTime = ::GetMessageTime();
4306 switch (aEventMessage) {
4307 case eMouseDoubleClick:
4308 event.mMessage = eMouseDown;
4309 event.mButton = aButton;
4310 sLastClickCount = 2;
4311 sLastMouseDownTime = curMsgTime;
4312 break;
4313 case eMouseUp:
4314 // remember when this happened for the next mouse down
4315 sLastMousePoint.x = eventPoint.x;
4316 sLastMousePoint.y = eventPoint.y;
4317 sLastMouseButton = eventButton;
4318 break;
4319 case eMouseDown:
4320 // now look to see if we want to convert this to a double- or triple-click
4321 if (((curMsgTime - sLastMouseDownTime) < (LONG)::GetDoubleClickTime()) &&
4322 insideMovementThreshold && eventButton == sLastMouseButton) {
4323 sLastClickCount++;
4324 } else {
4325 // reset the click count, to count *this* click
4326 sLastClickCount = 1;
4328 // Set last Click time on MouseDown only
4329 sLastMouseDownTime = curMsgTime;
4330 break;
4331 case eMouseMove:
4332 if (!insideMovementThreshold) {
4333 sLastClickCount = 0;
4335 break;
4336 case eMouseExitFromWidget:
4337 event.mExitFrom =
4338 Some(IsTopLevelMouseExit(mWnd) ? WidgetMouseEvent::ePlatformTopLevel
4339 : WidgetMouseEvent::ePlatformChild);
4340 break;
4341 default:
4342 break;
4344 event.mClickCount = sLastClickCount;
4346 #ifdef NS_DEBUG_XX
4347 MOZ_LOG(gWindowsLog, LogLevel::Info,
4348 ("Msg Time: %d Click Count: %d\n", curMsgTime, event.mClickCount));
4349 #endif
4351 // call the event callback
4352 if (mWidgetListener) {
4353 if (aEventMessage == eMouseMove) {
4354 LayoutDeviceIntRect rect = GetBounds();
4355 rect.MoveTo(0, 0);
4357 if (rect.Contains(event.mRefPoint)) {
4358 if (sCurrentWindow == nullptr || sCurrentWindow != this) {
4359 if ((nullptr != sCurrentWindow) && (!sCurrentWindow->mInDtor)) {
4360 LPARAM pos = sCurrentWindow->lParamToClient(lParamToScreen(lParam));
4361 sCurrentWindow->DispatchMouseEvent(
4362 eMouseExitFromWidget, wParam, pos, false, MouseButton::ePrimary,
4363 aInputSource, aPointerInfo);
4365 sCurrentWindow = this;
4366 if (!mInDtor) {
4367 LPARAM pos = sCurrentWindow->lParamToClient(lParamToScreen(lParam));
4368 sCurrentWindow->DispatchMouseEvent(
4369 eMouseEnterIntoWidget, wParam, pos, false,
4370 MouseButton::ePrimary, aInputSource, aPointerInfo);
4374 } else if (aEventMessage == eMouseExitFromWidget) {
4375 if (sCurrentWindow == this) {
4376 sCurrentWindow = nullptr;
4380 nsIWidget::ContentAndAPZEventStatus eventStatus =
4381 DispatchInputEvent(&event);
4382 contextMenuPreventer.Update(event, eventStatus);
4383 return ConvertStatus(eventStatus.mContentStatus);
4386 return result;
4389 HWND nsWindow::GetTopLevelForFocus(HWND aCurWnd) {
4390 // retrieve the toplevel window or dialogue
4391 HWND toplevelWnd = nullptr;
4392 while (aCurWnd) {
4393 toplevelWnd = aCurWnd;
4394 nsWindow* win = WinUtils::GetNSWindowPtr(aCurWnd);
4395 if (win) {
4396 if (win->mWindowType == WindowType::TopLevel ||
4397 win->mWindowType == WindowType::Dialog) {
4398 break;
4402 aCurWnd = ::GetParent(aCurWnd); // Parent or owner (if has no parent)
4404 return toplevelWnd;
4407 void nsWindow::DispatchFocusToTopLevelWindow(bool aIsActivate) {
4408 if (aIsActivate && mPickerDisplayCount) {
4409 // We disable the root window when a picker opens. See PickerOpen. When the
4410 // picker closes (but before PickerClosed is called), our window will get
4411 // focus, but it will still be disabled. This confuses the focus system.
4412 // Therefore, we ignore this focus and explicitly call this function once
4413 // we re-enable the window. Rarely, the picker seems to re-enable our root
4414 // window before we do, but for simplicity, we always ignore focus before
4415 // the final call to PickerClosed. See bug 1883568 for further details.
4416 return;
4419 if (aIsActivate) {
4420 sJustGotActivate = false;
4422 sJustGotDeactivate = false;
4423 mLastKillFocusWindow = nullptr;
4425 HWND toplevelWnd = GetTopLevelForFocus(mWnd);
4427 if (toplevelWnd) {
4428 nsWindow* win = WinUtils::GetNSWindowPtr(toplevelWnd);
4429 if (win && win->mWidgetListener) {
4430 if (aIsActivate) {
4431 win->mWidgetListener->WindowActivated();
4432 } else {
4433 win->mWidgetListener->WindowDeactivated();
4439 HWND nsWindow::WindowAtMouse() {
4440 DWORD pos = ::GetMessagePos();
4441 POINT mp;
4442 mp.x = GET_X_LPARAM(pos);
4443 mp.y = GET_Y_LPARAM(pos);
4444 return ::WindowFromPoint(mp);
4447 bool nsWindow::IsTopLevelMouseExit(HWND aWnd) {
4448 HWND mouseWnd = WindowAtMouse();
4450 // WinUtils::GetTopLevelHWND() will return a HWND for the window frame
4451 // (which includes the non-client area). If the mouse has moved into
4452 // the non-client area, we should treat it as a top-level exit.
4453 HWND mouseTopLevel = WinUtils::GetTopLevelHWND(mouseWnd);
4454 if (mouseWnd == mouseTopLevel) return true;
4456 return WinUtils::GetTopLevelHWND(aWnd) != mouseTopLevel;
4459 /**************************************************************
4461 * SECTION: IPC
4463 * IPC related helpers.
4465 **************************************************************/
4467 // static
4468 bool nsWindow::IsAsyncResponseEvent(UINT aMsg, LRESULT& aResult) {
4469 switch (aMsg) {
4470 case WM_SETFOCUS:
4471 case WM_KILLFOCUS:
4472 case WM_ENABLE:
4473 case WM_WINDOWPOSCHANGING:
4474 case WM_WINDOWPOSCHANGED:
4475 case WM_PARENTNOTIFY:
4476 case WM_ACTIVATEAPP:
4477 case WM_NCACTIVATE:
4478 case WM_ACTIVATE:
4479 case WM_CHILDACTIVATE:
4480 case WM_IME_SETCONTEXT:
4481 case WM_IME_NOTIFY:
4482 case WM_SHOWWINDOW:
4483 case WM_CANCELMODE:
4484 case WM_MOUSEACTIVATE:
4485 case WM_CONTEXTMENU:
4486 aResult = 0;
4487 return true;
4489 case WM_SETTINGCHANGE:
4490 case WM_SETCURSOR:
4491 return false;
4494 #ifdef DEBUG
4495 char szBuf[200];
4496 sprintf(szBuf,
4497 "An unhandled ISMEX_SEND message was received during spin loop! (%X)",
4498 aMsg);
4499 NS_WARNING(szBuf);
4500 #endif
4502 return false;
4505 void nsWindow::IPCWindowProcHandler(UINT& msg, WPARAM& wParam, LPARAM& lParam) {
4506 MOZ_ASSERT_IF(
4507 msg != WM_GETOBJECT,
4508 !mozilla::ipc::MessageChannel::IsPumpingMessages() ||
4509 mozilla::ipc::SuppressedNeuteringRegion::IsNeuteringSuppressed());
4511 // Modal UI being displayed in windowless plugins.
4512 if (mozilla::ipc::MessageChannel::IsSpinLoopActive() &&
4513 (InSendMessageEx(nullptr) & (ISMEX_REPLIED | ISMEX_SEND)) == ISMEX_SEND) {
4514 LRESULT res;
4515 if (IsAsyncResponseEvent(msg, res)) {
4516 ReplyMessage(res);
4518 return;
4521 // Handle certain sync plugin events sent to the parent which
4522 // trigger ipc calls that result in deadlocks.
4524 DWORD dwResult = 0;
4525 bool handled = false;
4527 switch (msg) {
4528 // Windowless flash sending WM_ACTIVATE events to the main window
4529 // via calls to ShowWindow.
4530 case WM_ACTIVATE:
4531 if (lParam != 0 && LOWORD(wParam) == WA_ACTIVE &&
4532 IsWindow((HWND)lParam)) {
4533 // Check for Adobe Reader X sync activate message from their
4534 // helper window and ignore. Fixes an annoying focus problem.
4535 if ((InSendMessageEx(nullptr) & (ISMEX_REPLIED | ISMEX_SEND)) ==
4536 ISMEX_SEND) {
4537 wchar_t szClass[10];
4538 HWND focusWnd = (HWND)lParam;
4539 if (IsWindowVisible(focusWnd) &&
4540 GetClassNameW(focusWnd, szClass,
4541 sizeof(szClass) / sizeof(char16_t)) &&
4542 !wcscmp(szClass, L"Edit") &&
4543 !WinUtils::IsOurProcessWindow(focusWnd)) {
4544 break;
4547 handled = true;
4549 break;
4550 // Plugins taking or losing focus triggering focus app messages.
4551 case WM_SETFOCUS:
4552 case WM_KILLFOCUS:
4553 // Windowed plugins that pass sys key events to defwndproc generate
4554 // WM_SYSCOMMAND events to the main window.
4555 case WM_SYSCOMMAND:
4556 // Windowed plugins that fire context menu selection events to parent
4557 // windows.
4558 case WM_CONTEXTMENU:
4559 // IME events fired as a result of synchronous focus changes
4560 case WM_IME_SETCONTEXT:
4561 handled = true;
4562 break;
4565 if (handled &&
4566 (InSendMessageEx(nullptr) & (ISMEX_REPLIED | ISMEX_SEND)) == ISMEX_SEND) {
4567 ReplyMessage(dwResult);
4571 /**************************************************************
4572 **************************************************************
4574 ** BLOCK: Native events
4576 ** Main Windows message handlers and OnXXX handlers for
4577 ** Windows event handling.
4579 **************************************************************
4580 **************************************************************/
4582 /**************************************************************
4584 * SECTION: Wind proc.
4586 * The main Windows event procedures and associated
4587 * message processing methods.
4589 **************************************************************/
4591 static bool DisplaySystemMenu(HWND hWnd, nsSizeMode sizeMode, bool isRtl,
4592 int32_t x, int32_t y) {
4593 HMENU hMenu = GetSystemMenu(hWnd, FALSE);
4594 if (hMenu) {
4595 MENUITEMINFO mii;
4596 mii.cbSize = sizeof(MENUITEMINFO);
4597 mii.fMask = MIIM_STATE;
4598 mii.fType = 0;
4600 // update the options
4601 mii.fState = MF_ENABLED;
4602 SetMenuItemInfo(hMenu, SC_RESTORE, FALSE, &mii);
4603 SetMenuItemInfo(hMenu, SC_SIZE, FALSE, &mii);
4604 SetMenuItemInfo(hMenu, SC_MOVE, FALSE, &mii);
4605 SetMenuItemInfo(hMenu, SC_MAXIMIZE, FALSE, &mii);
4606 SetMenuItemInfo(hMenu, SC_MINIMIZE, FALSE, &mii);
4608 mii.fState = MF_GRAYED;
4609 switch (sizeMode) {
4610 case nsSizeMode_Fullscreen:
4611 // intentional fall through
4612 case nsSizeMode_Maximized:
4613 SetMenuItemInfo(hMenu, SC_SIZE, FALSE, &mii);
4614 SetMenuItemInfo(hMenu, SC_MOVE, FALSE, &mii);
4615 SetMenuItemInfo(hMenu, SC_MAXIMIZE, FALSE, &mii);
4616 break;
4617 case nsSizeMode_Minimized:
4618 SetMenuItemInfo(hMenu, SC_MINIMIZE, FALSE, &mii);
4619 break;
4620 case nsSizeMode_Normal:
4621 SetMenuItemInfo(hMenu, SC_RESTORE, FALSE, &mii);
4622 break;
4623 case nsSizeMode_Invalid:
4624 NS_ASSERTION(false, "Did the argument come from invalid IPC?");
4625 break;
4626 default:
4627 MOZ_ASSERT_UNREACHABLE("Unhnalded nsSizeMode value detected");
4628 break;
4630 LPARAM cmd = TrackPopupMenu(
4631 hMenu,
4632 (TPM_LEFTBUTTON | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_TOPALIGN |
4633 (isRtl ? TPM_RIGHTALIGN : TPM_LEFTALIGN)),
4634 x, y, 0, hWnd, nullptr);
4635 if (cmd) {
4636 PostMessage(hWnd, WM_SYSCOMMAND, cmd, 0);
4637 return true;
4640 return false;
4643 // The WndProc procedure for all nsWindows in this toolkit. This merely catches
4644 // SEH exceptions and passes the real work to WindowProcInternal. See bug 587406
4645 // and http://msdn.microsoft.com/en-us/library/ms633573%28VS.85%29.aspx
4646 LRESULT CALLBACK nsWindow::WindowProc(HWND hWnd, UINT msg, WPARAM wParam,
4647 LPARAM lParam) {
4648 mozilla::ipc::CancelCPOWs();
4650 BackgroundHangMonitor().NotifyActivity();
4652 return mozilla::CallWindowProcCrashProtected(WindowProcInternal, hWnd, msg,
4653 wParam, lParam);
4656 LRESULT CALLBACK nsWindow::WindowProcInternal(HWND hWnd, UINT msg,
4657 WPARAM wParam, LPARAM lParam) {
4658 if (::GetWindowLongPtrW(hWnd, GWLP_ID) == eFakeTrackPointScrollableID) {
4659 // This message was sent to the FAKETRACKPOINTSCROLLABLE.
4660 if (msg == WM_HSCROLL) {
4661 // Route WM_HSCROLL messages to the main window.
4662 hWnd = ::GetParent(::GetParent(hWnd));
4663 } else {
4664 // Handle all other messages with its original window procedure.
4665 WNDPROC prevWindowProc = (WNDPROC)::GetWindowLongPtr(hWnd, GWLP_USERDATA);
4666 return ::CallWindowProcW(prevWindowProc, hWnd, msg, wParam, lParam);
4670 if (msg == MOZ_WM_TRACE) {
4671 // This is a tracer event for measuring event loop latency.
4672 // See WidgetTraceEvent.cpp for more details.
4673 mozilla::SignalTracerThread();
4674 return 0;
4677 // Get the window which caused the event and ask it to process the message
4678 nsWindow* targetWindow = WinUtils::GetNSWindowPtr(hWnd);
4679 NS_ASSERTION(targetWindow, "nsWindow* is null!");
4680 if (!targetWindow) return ::DefWindowProcW(hWnd, msg, wParam, lParam);
4682 // Hold the window for the life of this method, in case it gets
4683 // destroyed during processing, unless we're in the dtor already.
4684 nsCOMPtr<nsIWidget> kungFuDeathGrip;
4685 if (!targetWindow->mInDtor) kungFuDeathGrip = targetWindow;
4687 targetWindow->IPCWindowProcHandler(msg, wParam, lParam);
4689 // Create this here so that we store the last rolled up popup until after
4690 // the event has been processed.
4691 nsAutoRollup autoRollup;
4693 LRESULT popupHandlingResult;
4694 if (DealWithPopups(hWnd, msg, wParam, lParam, &popupHandlingResult))
4695 return popupHandlingResult;
4697 // Call ProcessMessage
4698 LRESULT retValue;
4699 if (targetWindow->ProcessMessage(msg, wParam, lParam, &retValue)) {
4700 return retValue;
4703 LRESULT res = ::CallWindowProcW(targetWindow->GetPrevWindowProc(), hWnd, msg,
4704 wParam, lParam);
4706 return res;
4709 const char16_t* GetQuitType() {
4710 if (Preferences::GetBool(PREF_WIN_REGISTER_APPLICATION_RESTART, false)) {
4711 DWORD cchCmdLine = 0;
4712 HRESULT rc = ::GetApplicationRestartSettings(::GetCurrentProcess(), nullptr,
4713 &cchCmdLine, nullptr);
4714 if (rc == S_OK) {
4715 return u"os-restart";
4718 return nullptr;
4721 bool nsWindow::ExternalHandlerProcessMessage(UINT aMessage, WPARAM& aWParam,
4722 LPARAM& aLParam,
4723 MSGResult& aResult) {
4724 if (mWindowHook.Notify(mWnd, aMessage, aWParam, aLParam, aResult)) {
4725 return true;
4728 if (IMEHandler::ProcessMessage(this, aMessage, aWParam, aLParam, aResult)) {
4729 return true;
4732 if (MouseScrollHandler::ProcessMessage(this, aMessage, aWParam, aLParam,
4733 aResult)) {
4734 return true;
4737 return false;
4740 // The main windows message processing method. Wraps ProcessMessageInternal so
4741 // we can log aRetValue.
4742 bool nsWindow::ProcessMessage(UINT msg, WPARAM& wParam, LPARAM& lParam,
4743 LRESULT* aRetValue) {
4744 // For some events we might change the parameter values, so log
4745 // before and after we process them.
4746 NativeEventLogger eventLogger("nsWindow", mWnd, msg, wParam, lParam);
4747 bool result = ProcessMessageInternal(msg, wParam, lParam, aRetValue);
4748 eventLogger.SetResult(*aRetValue, result);
4750 return result;
4753 // The main windows message processing method. Called by ProcessMessage.
4754 bool nsWindow::ProcessMessageInternal(UINT msg, WPARAM& wParam, LPARAM& lParam,
4755 LRESULT* aRetValue) {
4756 MSGResult msgResult(aRetValue);
4757 if (ExternalHandlerProcessMessage(msg, wParam, lParam, msgResult)) {
4758 return (msgResult.mConsumed || !mWnd);
4761 bool result = false; // call the default nsWindow proc
4762 *aRetValue = 0;
4764 // The DWM resize hack (see bug 1763981) causes us to process a number of
4765 // messages, notably including some WM_WINDOWPOSCHANG{ING,ED} messages which
4766 // would ordinarily result in a whole lot of internal state being updated.
4768 // Since we're supposed to end in the same state we started in (and since the
4769 // content shouldn't know about any of this nonsense), just discard any
4770 // messages synchronously dispatched from within the hack.
4771 if (MOZ_UNLIKELY(mIsPerformingDwmFlushHack)) {
4772 return true;
4775 // Glass hit testing w/custom transparent margins.
4777 // FIXME(emilio): is this needed? We deal with titlebar buttons non-natively
4778 // now.
4779 LRESULT dwmHitResult;
4780 if (mCustomNonClient &&
4781 DwmDefWindowProc(mWnd, msg, wParam, lParam, &dwmHitResult)) {
4782 *aRetValue = dwmHitResult;
4783 return true;
4786 // The preference whether to use a different keyboard layout for each
4787 // window is cached, and updating it will not take effect until the
4788 // next restart. We read the preference here and not upon WM_ACTIVATE to make
4789 // sure that this behavior is consistent. Otherwise, if the user changed the
4790 // preference before having ever lowered the window, the preference would take
4791 // effect immediately.
4792 static const bool sSwitchKeyboardLayout =
4793 Preferences::GetBool("intl.keyboard.per_window_layout", false);
4794 AppShutdownReason shutdownReason = AppShutdownReason::Unknown;
4796 // (Large blocks of code should be broken out into OnEvent handlers.)
4797 switch (msg) {
4798 // WM_QUERYENDSESSION must be handled by all windows.
4799 // Otherwise Windows thinks the window can just be killed at will.
4800 case WM_QUERYENDSESSION: {
4801 // Ask around if it's ok to quit.
4802 nsCOMPtr<nsIObserverService> obsServ =
4803 mozilla::services::GetObserverService();
4804 nsCOMPtr<nsISupportsPRBool> cancelQuitWrapper =
4805 do_CreateInstance(NS_SUPPORTS_PRBOOL_CONTRACTID);
4806 cancelQuitWrapper->SetData(false);
4808 const char16_t* quitType = GetQuitType();
4809 obsServ->NotifyObservers(cancelQuitWrapper, "quit-application-requested",
4810 quitType);
4812 bool shouldCancelQuit;
4813 cancelQuitWrapper->GetData(&shouldCancelQuit);
4814 *aRetValue = !shouldCancelQuit;
4815 result = true;
4816 } break;
4818 case MOZ_WM_STARTA11Y:
4819 #if defined(ACCESSIBILITY)
4820 Unused << GetAccessible();
4821 result = true;
4822 #else
4823 result = false;
4824 #endif
4825 break;
4827 case WM_ENDSESSION: {
4828 // For WM_ENDSESSION, wParam indicates whether we need to shutdown
4829 // (TRUE) or not (FALSE).
4830 if (!wParam) {
4831 result = true;
4832 break;
4834 // According to WM_ENDSESSION lParam documentation:
4835 // 0 -> OS shutdown or restart (no way to distinguish)
4836 // ENDSESSION_LOGOFF -> User is logging off
4837 // ENDSESSION_CLOSEAPP -> Application must shutdown
4838 // ENDSESSION_CRITICAL -> Application is forced to shutdown
4839 // The difference of the last two is not very clear.
4840 if (lParam == 0) {
4841 shutdownReason = AppShutdownReason::OSShutdown;
4842 } else if (lParam & ENDSESSION_LOGOFF) {
4843 shutdownReason = AppShutdownReason::OSSessionEnd;
4844 } else if (lParam & (ENDSESSION_CLOSEAPP | ENDSESSION_CRITICAL)) {
4845 shutdownReason = AppShutdownReason::OSForceClose;
4846 } else {
4847 MOZ_DIAGNOSTIC_ASSERT(false,
4848 "Received WM_ENDSESSION with unknown flags.");
4849 shutdownReason = AppShutdownReason::OSForceClose;
4852 [[fallthrough]];
4853 case MOZ_WM_APP_QUIT: {
4854 if (shutdownReason == AppShutdownReason::Unknown) {
4855 // TODO: We do not expect that these days anybody sends us
4856 // MOZ_WM_APP_QUIT, see bug 1827807.
4857 shutdownReason = AppShutdownReason::WinUnexpectedMozQuit;
4859 // Let's fake a shutdown sequence without actually closing windows etc.
4860 // to avoid Windows killing us in the middle. A proper shutdown would
4861 // require having a chance to pump some messages. Unfortunately
4862 // Windows won't let us do that. Bug 212316.
4863 nsCOMPtr<nsIObserverService> obsServ =
4864 mozilla::services::GetObserverService();
4865 const char16_t* syncShutdown = u"syncShutdown";
4866 const char16_t* quitType = GetQuitType();
4868 AppShutdown::Init(AppShutdownMode::Normal, 0, shutdownReason);
4870 obsServ->NotifyObservers(nullptr, "quit-application-granted",
4871 syncShutdown);
4872 obsServ->NotifyObservers(nullptr, "quit-application-forced", nullptr);
4874 AppShutdown::OnShutdownConfirmed();
4876 AppShutdown::AdvanceShutdownPhase(ShutdownPhase::AppShutdownConfirmed,
4877 quitType);
4878 AppShutdown::AdvanceShutdownPhase(ShutdownPhase::AppShutdownNetTeardown,
4879 nullptr);
4880 AppShutdown::AdvanceShutdownPhase(ShutdownPhase::AppShutdownTeardown,
4881 nullptr);
4882 AppShutdown::AdvanceShutdownPhase(ShutdownPhase::AppShutdown, nullptr);
4883 AppShutdown::AdvanceShutdownPhase(ShutdownPhase::AppShutdownQM, nullptr);
4884 AppShutdown::AdvanceShutdownPhase(ShutdownPhase::AppShutdownTelemetry,
4885 nullptr);
4887 AppShutdown::DoImmediateExit();
4888 MOZ_ASSERT_UNREACHABLE("Our process was supposed to exit.");
4889 } break;
4891 case WM_SYSCOLORCHANGE:
4892 // No need to invalidate layout for system color changes, but we need to
4893 // invalidate style.
4894 NotifyThemeChanged(widget::ThemeChangeKind::Style);
4895 break;
4897 case WM_THEMECHANGED: {
4898 // Update non-client margin offsets
4899 UpdateNonClientMargins();
4900 nsUXThemeData::UpdateNativeThemeInfo();
4902 // We assume pretty much everything could've changed here.
4903 NotifyThemeChanged(widget::ThemeChangeKind::StyleAndLayout);
4905 UpdateDarkModeToolbar();
4907 // Invalidate the window so that the repaint will
4908 // pick up the new theme.
4909 Invalidate(true, true, true);
4910 } break;
4912 case WM_WTSSESSION_CHANGE: {
4913 switch (wParam) {
4914 case WTS_CONSOLE_CONNECT:
4915 case WTS_REMOTE_CONNECT:
4916 case WTS_SESSION_UNLOCK:
4917 // When a session becomes visible, we should invalidate.
4918 Invalidate(true, true, true);
4919 break;
4920 default:
4921 break;
4923 } break;
4925 case WM_FONTCHANGE: {
4926 // We only handle this message for the hidden window,
4927 // as we only need to update the (global) font list once
4928 // for any given change, not once per window!
4929 if (mWindowType != WindowType::Invisible) {
4930 break;
4933 // update the global font list
4934 gfxPlatform::GetPlatform()->UpdateFontList();
4935 } break;
4937 case WM_SETTINGCHANGE: {
4938 if (wParam == SPI_SETCLIENTAREAANIMATION ||
4939 wParam == SPI_SETKEYBOARDDELAY || wParam == SPI_SETMOUSEVANISH ||
4940 wParam == MOZ_SPI_SETCURSORSIZE) {
4941 // These need to update LookAndFeel cached values.
4942 // They affect reduced motion settings / caret blink count / show
4943 // pointer while typing / tooltip offset, so no need to invalidate style
4944 // / layout.
4945 NotifyThemeChanged(widget::ThemeChangeKind::MediaQueriesOnly);
4946 break;
4948 if (wParam == SPI_SETFONTSMOOTHING ||
4949 wParam == SPI_SETFONTSMOOTHINGTYPE) {
4950 gfxDWriteFont::UpdateSystemTextVars();
4951 break;
4953 if (wParam == SPI_SETWORKAREA) {
4954 // NB: We also refresh screens on WM_DISPLAYCHANGE but the rcWork
4955 // values are sometimes wrong at that point. This message then
4956 // arrives soon afterward, when we can get the right rcWork values.
4957 ScreenHelperWin::RefreshScreens();
4958 break;
4960 if (auto lParamString = reinterpret_cast<const wchar_t*>(lParam)) {
4961 if (!wcscmp(lParamString, L"ImmersiveColorSet")) {
4962 // This affects system colors (-moz-win-accentcolor), so gotta pass
4963 // the style flag.
4964 NotifyThemeChanged(widget::ThemeChangeKind::Style);
4965 break;
4968 // UserInteractionMode, ConvertibleSlateMode, SystemDockMode may cause
4969 // @media(pointer) queries to change, which layout needs to know about
4971 // (WM_SETTINGCHANGE will be sent to all top-level windows, so we
4972 // only respond to the hidden top-level window to avoid hammering
4973 // layout with a bunch of NotifyThemeChanged() calls)
4975 if (mWindowType == WindowType::Invisible) {
4976 if (!wcscmp(lParamString, L"UserInteractionMode") ||
4977 !wcscmp(lParamString, L"ConvertibleSlateMode") ||
4978 !wcscmp(lParamString, L"SystemDockMode")) {
4979 NotifyThemeChanged(widget::ThemeChangeKind::MediaQueriesOnly);
4980 WindowsUIUtils::UpdateInTabletMode();
4984 } break;
4986 case WM_DEVICECHANGE: {
4987 if (wParam == DBT_DEVICEARRIVAL || wParam == DBT_DEVICEREMOVECOMPLETE) {
4988 DEV_BROADCAST_HDR* hdr = reinterpret_cast<DEV_BROADCAST_HDR*>(lParam);
4989 // Check dbch_devicetype explicitly since we will get other device types
4990 // (e.g. DBT_DEVTYP_VOLUME) for some reasons even if we specify
4991 // DBT_DEVTYP_DEVICEINTERFACE in the filter for
4992 // RegisterDeviceNotification.
4993 if (hdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
4994 // This can only change media queries (any-hover/any-pointer).
4995 NotifyThemeChanged(widget::ThemeChangeKind::MediaQueriesOnly);
4998 } break;
5000 case WM_NCCALCSIZE: {
5001 // NOTE: the following block is mirrored in PreXULSkeletonUI.cpp, and
5002 // will need to be kept in sync.
5003 if (mCustomNonClient) {
5004 // If `wParam` is `FALSE`, `lParam` points to a `RECT` that contains
5005 // the proposed window rectangle for our window. During our
5006 // processing of the `WM_NCCALCSIZE` message, we are expected to
5007 // modify the `RECT` that `lParam` points to, so that its value upon
5008 // our return is the new client area. We must return 0 if `wParam`
5009 // is `FALSE`.
5011 // If `wParam` is `TRUE`, `lParam` points to a `NCCALCSIZE_PARAMS`
5012 // struct. This struct contains an array of 3 `RECT`s, the first of
5013 // which has the exact same meaning as the `RECT` that is pointed to
5014 // by `lParam` when `wParam` is `FALSE`. The remaining `RECT`s, in
5015 // conjunction with our return value, can
5016 // be used to specify portions of the source and destination window
5017 // rectangles that are valid and should be preserved. We opt not to
5018 // implement an elaborate client-area preservation technique, and
5019 // simply return 0, which means "preserve the entire old client area
5020 // and align it with the upper-left corner of our new client area".
5021 RECT* clientRect =
5022 wParam ? &(reinterpret_cast<NCCALCSIZE_PARAMS*>(lParam))->rgrc[0]
5023 : (reinterpret_cast<RECT*>(lParam));
5024 auto margin = NonClientSizeMargin();
5025 clientRect->top += margin.top;
5026 clientRect->left += margin.left;
5027 clientRect->right -= margin.right;
5028 clientRect->bottom -= margin.bottom;
5029 // Make client rect's width and height more than 0 to
5030 // avoid problems of webrender and angle.
5031 clientRect->right = std::max(clientRect->right, clientRect->left + 1);
5032 clientRect->bottom = std::max(clientRect->bottom, clientRect->top + 1);
5034 result = true;
5035 *aRetValue = 0;
5037 break;
5040 case WM_GETTITLEBARINFOEX: {
5041 if (!mCustomNonClient) {
5042 break;
5044 auto* info = reinterpret_cast<TITLEBARINFOEX*>(lParam);
5045 const LayoutDeviceIntPoint origin = WidgetToScreenOffset();
5046 auto GeckoClientToWinScreenRect =
5047 [&origin](LayoutDeviceIntRect aRect) -> RECT {
5048 aRect.MoveBy(origin);
5049 return {
5050 .left = aRect.x,
5051 .top = aRect.y,
5052 .right = aRect.XMost(),
5053 .bottom = aRect.YMost(),
5056 auto SetButton = [&](size_t aIndex, WindowButtonType aType) {
5057 info->rgrect[aIndex] =
5058 GeckoClientToWinScreenRect(mWindowBtnRect[aType]);
5059 DWORD& state = info->rgstate[aIndex];
5060 if (mWindowBtnRect[aType].IsEmpty()) {
5061 state = STATE_SYSTEM_INVISIBLE;
5062 } else {
5063 state = STATE_SYSTEM_FOCUSABLE;
5066 info->rgrect[0] = info->rcTitleBar =
5067 GeckoClientToWinScreenRect(mDraggableRegion.GetBounds());
5068 info->rgstate[0] = 0;
5069 SetButton(2, WindowButtonType::Minimize);
5070 SetButton(3, WindowButtonType::Maximize);
5071 SetButton(5, WindowButtonType::Close);
5072 // We don't have a help button.
5073 info->rgstate[4] = STATE_SYSTEM_INVISIBLE;
5074 info->rgrect[4] = {0, 0, 0, 0};
5075 result = true;
5076 } break;
5078 case WM_NCHITTEST: {
5079 if (mInputRegion.mFullyTransparent) {
5080 // Treat this window as transparent.
5081 *aRetValue = HTTRANSPARENT;
5082 result = true;
5083 break;
5086 if (mInputRegion.mMargin) {
5087 const LayoutDeviceIntPoint screenPoint(GET_X_LPARAM(lParam),
5088 GET_Y_LPARAM(lParam));
5089 LayoutDeviceIntRect screenRect = GetScreenBounds();
5090 screenRect.Deflate(mInputRegion.mMargin);
5091 if (!screenRect.Contains(screenPoint)) {
5092 *aRetValue = HTTRANSPARENT;
5093 result = true;
5094 break;
5099 * If an nc client area margin has been moved, we are responsible
5100 * for calculating where the resize margins are and returning the
5101 * appropriate set of hit test constants. DwmDefWindowProc (above)
5102 * will handle hit testing on it's command buttons if we are on a
5103 * composited desktop.
5106 if (!mCustomNonClient) {
5107 break;
5110 *aRetValue =
5111 ClientMarginHitTestPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
5112 result = true;
5113 break;
5116 case WM_SETTEXT:
5118 * WM_SETTEXT paints the titlebar area. Avoid this if we have a
5119 * custom titlebar we paint ourselves, or if we're the ones
5120 * sending the message with an updated title
5123 if (mSendingSetText || !mCustomNonClient || mNonClientMargins.top == -1)
5124 break;
5127 // From msdn, the way around this is to disable the visible state
5128 // temporarily. We need the text to be set but we don't want the
5129 // redraw to occur. However, we need to make sure that we don't
5130 // do this at the same time that a Present is happening.
5132 // To do this we take mPresentLock in nsWindow::PreRender and
5133 // if that lock is taken we wait before doing WM_SETTEXT
5134 if (mCompositorWidgetDelegate) {
5135 mCompositorWidgetDelegate->EnterPresentLock();
5137 DWORD style = GetWindowLong(mWnd, GWL_STYLE);
5138 SetWindowLong(mWnd, GWL_STYLE, style & ~WS_VISIBLE);
5139 *aRetValue =
5140 CallWindowProcW(GetPrevWindowProc(), mWnd, msg, wParam, lParam);
5141 SetWindowLong(mWnd, GWL_STYLE, style);
5142 if (mCompositorWidgetDelegate) {
5143 mCompositorWidgetDelegate->LeavePresentLock();
5146 return true;
5149 case WM_NCACTIVATE: {
5151 * WM_NCACTIVATE paints nc areas. Avoid this and re-route painting
5152 * through WM_NCPAINT via InvalidateNonClientRegion.
5154 if (!mCustomNonClient) {
5155 break;
5158 // There is a case that rendered result is not kept. Bug 1237617
5159 if (wParam == TRUE && !gfxEnv::MOZ_DISABLE_FORCE_PRESENT()) {
5160 NS_DispatchToMainThread(NewRunnableMethod(
5161 "nsWindow::ForcePresent", this, &nsWindow::ForcePresent));
5164 // let the dwm handle nc painting on glass
5165 // Never allow native painting if we are on fullscreen
5166 if (mFrameState->GetSizeMode() != nsSizeMode_Fullscreen) break;
5168 if (wParam == TRUE) {
5169 // going active
5170 *aRetValue = FALSE; // ignored
5171 result = true;
5172 // invalidate to trigger a paint
5173 InvalidateNonClientRegion();
5174 break;
5175 } else {
5176 // going inactive
5177 *aRetValue = TRUE; // go ahead and deactive
5178 result = true;
5179 // invalidate to trigger a paint
5180 InvalidateNonClientRegion();
5181 break;
5185 case WM_NCPAINT: {
5187 * ClearType changes often don't send a WM_SETTINGCHANGE message. But they
5188 * do seem to always send a WM_NCPAINT message, so let's update on that.
5190 gfxDWriteFont::UpdateSystemTextVars();
5191 } break;
5193 case WM_POWERBROADCAST:
5194 switch (wParam) {
5195 case PBT_APMSUSPEND:
5196 PostSleepWakeNotification(true);
5197 break;
5198 case PBT_APMRESUMEAUTOMATIC:
5199 case PBT_APMRESUMECRITICAL:
5200 case PBT_APMRESUMESUSPEND:
5201 PostSleepWakeNotification(false);
5202 break;
5204 break;
5206 case WM_CLOSE: // close request
5207 if (mWidgetListener) mWidgetListener->RequestWindowClose(this);
5208 result = true; // abort window closure
5209 break;
5211 case WM_DESTROY:
5212 // clean up.
5213 DestroyLayerManager();
5214 OnDestroy();
5215 result = true;
5216 break;
5218 case WM_PAINT:
5219 *aRetValue = (int)OnPaint(0);
5220 result = true;
5221 break;
5223 case WM_HOTKEY:
5224 result = OnHotKey(wParam, lParam);
5225 break;
5227 case WM_SYSCHAR:
5228 case WM_CHAR: {
5229 MSG nativeMsg = WinUtils::InitMSG(msg, wParam, lParam, mWnd);
5230 result = ProcessCharMessage(nativeMsg, nullptr);
5231 DispatchPendingEvents();
5232 } break;
5234 case WM_SYSKEYUP:
5235 case WM_KEYUP: {
5236 MSG nativeMsg = WinUtils::InitMSG(msg, wParam, lParam, mWnd);
5237 nativeMsg.time = ::GetMessageTime();
5238 result = ProcessKeyUpMessage(nativeMsg, nullptr);
5239 DispatchPendingEvents();
5240 } break;
5242 case WM_SYSKEYDOWN:
5243 case WM_KEYDOWN: {
5244 MSG nativeMsg = WinUtils::InitMSG(msg, wParam, lParam, mWnd);
5245 result = ProcessKeyDownMessage(nativeMsg, nullptr);
5246 DispatchPendingEvents();
5247 } break;
5249 // Say we've dealt with erasing the background. (This is actually handled in
5250 // WM_PAINT, where necessary.)
5251 case WM_ERASEBKGND: {
5252 *aRetValue = 1;
5253 result = true;
5254 } break;
5256 case WM_MOUSEMOVE: {
5257 LPARAM lParamScreen = lParamToScreen(lParam);
5258 mSimulatedClientArea = IsSimulatedClientArea(GET_X_LPARAM(lParamScreen),
5259 GET_Y_LPARAM(lParamScreen));
5261 if (!mMousePresent && !sIsInMouseCapture) {
5262 // First MOUSEMOVE over the client area. Ask for MOUSELEAVE
5263 TRACKMOUSEEVENT mTrack;
5264 mTrack.cbSize = sizeof(TRACKMOUSEEVENT);
5265 mTrack.dwFlags = TME_LEAVE;
5266 mTrack.dwHoverTime = 0;
5267 mTrack.hwndTrack = mWnd;
5268 TrackMouseEvent(&mTrack);
5270 mMousePresent = true;
5272 // Suppress dispatch of pending events
5273 // when mouse moves are generated by widget
5274 // creation instead of user input.
5275 POINT mp;
5276 mp.x = GET_X_LPARAM(lParamScreen);
5277 mp.y = GET_Y_LPARAM(lParamScreen);
5278 bool userMovedMouse = false;
5279 if ((sLastMouseMovePoint.x != mp.x) || (sLastMouseMovePoint.y != mp.y)) {
5280 userMovedMouse = true;
5283 if (userMovedMouse) {
5284 result = DispatchMouseEvent(
5285 eMouseMove, wParam, lParam, false, MouseButton::ePrimary,
5286 MOUSE_INPUT_SOURCE(),
5287 mPointerEvents.GetCachedPointerInfo(msg, wParam));
5288 DispatchPendingEvents();
5290 } break;
5292 case WM_NCMOUSEMOVE: {
5293 LPARAM lParamClient = lParamToClient(lParam);
5294 if (IsSimulatedClientArea(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))) {
5295 if (!sIsInMouseCapture) {
5296 TRACKMOUSEEVENT mTrack;
5297 mTrack.cbSize = sizeof(TRACKMOUSEEVENT);
5298 mTrack.dwFlags = TME_LEAVE | TME_NONCLIENT;
5299 mTrack.dwHoverTime = 0;
5300 mTrack.hwndTrack = mWnd;
5301 TrackMouseEvent(&mTrack);
5303 // If we noticed the mouse moving in our draggable region, forward the
5304 // message as a normal WM_MOUSEMOVE.
5305 SendMessage(mWnd, WM_MOUSEMOVE, 0, lParamClient);
5306 } else {
5307 // We've transitioned from a draggable area to somewhere else within
5308 // the non-client area - perhaps one of the edges of the window for
5309 // resizing.
5310 mSimulatedClientArea = false;
5313 if (mMousePresent && !sIsInMouseCapture && !mSimulatedClientArea) {
5314 SendMessage(mWnd, WM_MOUSELEAVE, 0, 0);
5316 } break;
5318 case WM_LBUTTONDOWN: {
5319 result =
5320 DispatchMouseEvent(eMouseDown, wParam, lParam, false,
5321 MouseButton::ePrimary, MOUSE_INPUT_SOURCE(),
5322 mPointerEvents.GetCachedPointerInfo(msg, wParam));
5323 DispatchPendingEvents();
5324 } break;
5326 case WM_LBUTTONUP: {
5327 result =
5328 DispatchMouseEvent(eMouseUp, wParam, lParam, false,
5329 MouseButton::ePrimary, MOUSE_INPUT_SOURCE(),
5330 mPointerEvents.GetCachedPointerInfo(msg, wParam));
5331 DispatchPendingEvents();
5332 } break;
5334 case WM_NCMOUSELEAVE: {
5335 mSimulatedClientArea = false;
5337 if (EventIsInsideWindow(this)) {
5338 // If we're handling WM_NCMOUSELEAVE and the mouse is still over the
5339 // window, then by process of elimination, the mouse has moved from the
5340 // non-client to client area, so no need to fall-through to the
5341 // WM_MOUSELEAVE handler. We also need to re-register for the
5342 // WM_MOUSELEAVE message, since according to the documentation at [1],
5343 // all tracking requested via TrackMouseEvent is cleared once
5344 // WM_NCMOUSELEAVE or WM_MOUSELEAVE fires.
5345 // [1]:
5346 // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-trackmouseevent
5347 TRACKMOUSEEVENT mTrack;
5348 mTrack.cbSize = sizeof(TRACKMOUSEEVENT);
5349 mTrack.dwFlags = TME_LEAVE;
5350 mTrack.dwHoverTime = 0;
5351 mTrack.hwndTrack = mWnd;
5352 TrackMouseEvent(&mTrack);
5353 break;
5355 // We've transitioned from non-client to outside of the window, so
5356 // fall-through to the WM_MOUSELEAVE handler.
5357 [[fallthrough]];
5359 case WM_MOUSELEAVE: {
5360 if (!mMousePresent) break;
5361 if (mSimulatedClientArea) break;
5362 mMousePresent = false;
5364 // Check if the mouse is over the fullscreen transition window, if so
5365 // clear sLastMouseMovePoint. This way the WM_MOUSEMOVE we get after the
5366 // transition window disappears will not be ignored, even if the mouse
5367 // hasn't moved.
5368 if (mTransitionWnd && WindowAtMouse() == mTransitionWnd) {
5369 sLastMouseMovePoint = {0};
5372 // We need to check mouse button states and put them in for
5373 // wParam.
5374 WPARAM mouseState = (GetKeyState(VK_LBUTTON) ? MK_LBUTTON : 0) |
5375 (GetKeyState(VK_MBUTTON) ? MK_MBUTTON : 0) |
5376 (GetKeyState(VK_RBUTTON) ? MK_RBUTTON : 0);
5377 // Synthesize an event position because we don't get one from
5378 // WM_MOUSELEAVE.
5379 LPARAM pos = lParamToClient(::GetMessagePos());
5380 DispatchMouseEvent(eMouseExitFromWidget, mouseState, pos, false,
5381 MouseButton::ePrimary, MOUSE_INPUT_SOURCE());
5382 } break;
5384 case WM_CONTEXTMENU: {
5385 // If the context menu is brought up by a touch long-press, then
5386 // the APZ code is responsible for dealing with this, so we don't
5387 // need to do anything.
5388 if (mTouchWindow &&
5389 MOUSE_INPUT_SOURCE() == MouseEvent_Binding::MOZ_SOURCE_TOUCH) {
5390 MOZ_ASSERT(mAPZC); // since mTouchWindow is true, APZ must be enabled
5391 result = true;
5392 break;
5395 // If this WM_CONTEXTMENU is triggered by a mouse's secondary button up
5396 // event in overscroll gutter, we shouldn't open context menu.
5397 if (MOUSE_INPUT_SOURCE() == MouseEvent_Binding::MOZ_SOURCE_MOUSE &&
5398 mNeedsToPreventContextMenu) {
5399 result = true;
5400 break;
5403 // if the context menu is brought up from the keyboard, |lParam|
5404 // will be -1.
5405 LPARAM pos;
5406 bool contextMenukey = false;
5407 if (lParam == -1) {
5408 contextMenukey = true;
5409 pos = lParamToClient(GetMessagePos());
5410 } else {
5411 pos = lParamToClient(lParam);
5414 result = DispatchMouseEvent(
5415 eContextMenu, wParam, pos, contextMenukey,
5416 contextMenukey ? MouseButton::ePrimary : MouseButton::eSecondary,
5417 MOUSE_INPUT_SOURCE());
5418 if (lParam != -1 && !result && mCustomNonClient &&
5419 mDraggableRegion.Contains(GET_X_LPARAM(pos), GET_Y_LPARAM(pos))) {
5420 // Blank area hit, throw up the system menu.
5421 DisplaySystemMenu(mWnd, mFrameState->GetSizeMode(), mIsRTL,
5422 GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
5423 result = true;
5425 } break;
5427 case WM_POINTERLEAVE:
5428 case WM_POINTERDOWN:
5429 case WM_POINTERUP:
5430 case WM_POINTERUPDATE:
5431 result = OnPointerEvents(msg, wParam, lParam);
5432 if (result) {
5433 DispatchPendingEvents();
5435 break;
5437 case DM_POINTERHITTEST:
5438 if (mDmOwner) {
5439 UINT contactId = GET_POINTERID_WPARAM(wParam);
5440 POINTER_INPUT_TYPE pointerType;
5441 if (mPointerEvents.GetPointerType(contactId, &pointerType) &&
5442 pointerType == PT_TOUCHPAD) {
5443 mDmOwner->SetContact(contactId);
5446 break;
5448 case WM_LBUTTONDBLCLK:
5449 result = DispatchMouseEvent(eMouseDoubleClick, wParam, lParam, false,
5450 MouseButton::ePrimary, MOUSE_INPUT_SOURCE());
5451 DispatchPendingEvents();
5452 break;
5454 case WM_MBUTTONDOWN:
5455 result = DispatchMouseEvent(eMouseDown, wParam, lParam, false,
5456 MouseButton::eMiddle, MOUSE_INPUT_SOURCE());
5457 DispatchPendingEvents();
5458 break;
5460 case WM_MBUTTONUP:
5461 result = DispatchMouseEvent(eMouseUp, wParam, lParam, false,
5462 MouseButton::eMiddle, MOUSE_INPUT_SOURCE());
5463 DispatchPendingEvents();
5464 break;
5466 case WM_MBUTTONDBLCLK:
5467 result = DispatchMouseEvent(eMouseDoubleClick, wParam, lParam, false,
5468 MouseButton::eMiddle, MOUSE_INPUT_SOURCE());
5469 DispatchPendingEvents();
5470 break;
5472 case WM_NCMBUTTONDOWN:
5473 result = DispatchMouseEvent(eMouseDown, 0, lParamToClient(lParam), false,
5474 MouseButton::eMiddle, MOUSE_INPUT_SOURCE());
5475 DispatchPendingEvents();
5476 break;
5478 case WM_NCMBUTTONUP:
5479 result = DispatchMouseEvent(eMouseUp, 0, lParamToClient(lParam), false,
5480 MouseButton::eMiddle, MOUSE_INPUT_SOURCE());
5481 DispatchPendingEvents();
5482 break;
5484 case WM_NCMBUTTONDBLCLK:
5485 result =
5486 DispatchMouseEvent(eMouseDoubleClick, 0, lParamToClient(lParam),
5487 false, MouseButton::eMiddle, MOUSE_INPUT_SOURCE());
5488 DispatchPendingEvents();
5489 break;
5491 case WM_RBUTTONDOWN:
5492 result =
5493 DispatchMouseEvent(eMouseDown, wParam, lParam, false,
5494 MouseButton::eSecondary, MOUSE_INPUT_SOURCE(),
5495 mPointerEvents.GetCachedPointerInfo(msg, wParam));
5496 DispatchPendingEvents();
5497 break;
5499 case WM_RBUTTONUP:
5500 result =
5501 DispatchMouseEvent(eMouseUp, wParam, lParam, false,
5502 MouseButton::eSecondary, MOUSE_INPUT_SOURCE(),
5503 mPointerEvents.GetCachedPointerInfo(msg, wParam));
5504 DispatchPendingEvents();
5505 break;
5507 case WM_RBUTTONDBLCLK:
5508 result =
5509 DispatchMouseEvent(eMouseDoubleClick, wParam, lParam, false,
5510 MouseButton::eSecondary, MOUSE_INPUT_SOURCE());
5511 DispatchPendingEvents();
5512 break;
5514 case WM_NCRBUTTONDOWN:
5515 result =
5516 DispatchMouseEvent(eMouseDown, 0, lParamToClient(lParam), false,
5517 MouseButton::eSecondary, MOUSE_INPUT_SOURCE());
5518 DispatchPendingEvents();
5519 break;
5521 case WM_NCRBUTTONUP:
5522 result =
5523 DispatchMouseEvent(eMouseUp, 0, lParamToClient(lParam), false,
5524 MouseButton::eSecondary, MOUSE_INPUT_SOURCE());
5525 DispatchPendingEvents();
5526 break;
5528 case WM_NCRBUTTONDBLCLK:
5529 result = DispatchMouseEvent(eMouseDoubleClick, 0, lParamToClient(lParam),
5530 false, MouseButton::eSecondary,
5531 MOUSE_INPUT_SOURCE());
5532 DispatchPendingEvents();
5533 break;
5535 // Windows doesn't provide to customize the behavior of 4th nor 5th button
5536 // of mouse. If 5-button mouse works with standard mouse deriver of
5537 // Windows, users cannot disable 4th button (browser back) nor 5th button
5538 // (browser forward). We should allow to do it with our prefs since we can
5539 // prevent Windows to generate WM_APPCOMMAND message if WM_XBUTTONUP
5540 // messages are not sent to DefWindowProc.
5541 case WM_XBUTTONDOWN:
5542 case WM_XBUTTONUP:
5543 case WM_NCXBUTTONDOWN:
5544 case WM_NCXBUTTONUP:
5545 *aRetValue = TRUE;
5546 switch (GET_XBUTTON_WPARAM(wParam)) {
5547 case XBUTTON1:
5548 result = !Preferences::GetBool("mousebutton.4th.enabled", true);
5549 break;
5550 case XBUTTON2:
5551 result = !Preferences::GetBool("mousebutton.5th.enabled", true);
5552 break;
5553 default:
5554 break;
5556 break;
5558 case WM_SIZING: {
5559 if (mAspectRatio > 0) {
5560 LPRECT rect = (LPRECT)lParam;
5561 int32_t newWidth, newHeight;
5563 // The following conditions and switch statement borrow heavily from the
5564 // Chromium source code from
5565 // https://chromium.googlesource.com/chromium/src/+/456d6e533cfb4531995e0ef52c279d4b5aa8a352/ui/views/window/window_resize_utils.cc#45
5566 if (wParam == WMSZ_LEFT || wParam == WMSZ_RIGHT ||
5567 wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT) {
5568 newWidth = rect->right - rect->left;
5569 newHeight = newWidth / mAspectRatio;
5570 if (newHeight < mSizeConstraints.mMinSize.height) {
5571 newHeight = mSizeConstraints.mMinSize.height;
5572 newWidth = newHeight * mAspectRatio;
5573 } else if (newHeight > mSizeConstraints.mMaxSize.height) {
5574 newHeight = mSizeConstraints.mMaxSize.height;
5575 newWidth = newHeight * mAspectRatio;
5577 } else {
5578 newHeight = rect->bottom - rect->top;
5579 newWidth = newHeight * mAspectRatio;
5580 if (newWidth < mSizeConstraints.mMinSize.width) {
5581 newWidth = mSizeConstraints.mMinSize.width;
5582 newHeight = newWidth / mAspectRatio;
5583 } else if (newWidth > mSizeConstraints.mMaxSize.width) {
5584 newWidth = mSizeConstraints.mMaxSize.width;
5585 newHeight = newWidth / mAspectRatio;
5589 switch (wParam) {
5590 case WMSZ_RIGHT:
5591 case WMSZ_BOTTOM:
5592 rect->right = newWidth + rect->left;
5593 rect->bottom = rect->top + newHeight;
5594 break;
5595 case WMSZ_TOP:
5596 rect->right = newWidth + rect->left;
5597 rect->top = rect->bottom - newHeight;
5598 break;
5599 case WMSZ_LEFT:
5600 case WMSZ_TOPLEFT:
5601 rect->left = rect->right - newWidth;
5602 rect->top = rect->bottom - newHeight;
5603 break;
5604 case WMSZ_TOPRIGHT:
5605 rect->right = rect->left + newWidth;
5606 rect->top = rect->bottom - newHeight;
5607 break;
5608 case WMSZ_BOTTOMLEFT:
5609 rect->left = rect->right - newWidth;
5610 rect->bottom = rect->top + newHeight;
5611 break;
5612 case WMSZ_BOTTOMRIGHT:
5613 rect->right = rect->left + newWidth;
5614 rect->bottom = rect->top + newHeight;
5615 break;
5619 // When we get WM_ENTERSIZEMOVE we don't know yet if we're in a live
5620 // resize or move event. Instead we wait for first VM_SIZING message
5621 // within a ENTERSIZEMOVE to consider this a live resize event.
5622 if (mResizeState == IN_SIZEMOVE) {
5623 mResizeState = RESIZING;
5624 NotifyLiveResizeStarted();
5626 break;
5629 case WM_MOVING:
5630 FinishLiveResizing(MOVING);
5631 if (WinUtils::IsPerMonitorDPIAware()) {
5632 // Sometimes, we appear to miss a WM_DPICHANGED message while moving
5633 // a window around. Therefore, call ChangedDPI and ResetLayout here
5634 // if it appears that the window's scaling is not what we expect.
5635 // This causes the prescontext and appshell window management code to
5636 // check the appUnitsPerDevPixel value and current widget size, and
5637 // refresh them if necessary. If nothing has changed, these calls will
5638 // return without actually triggering any extra reflow or painting.
5639 if (WinUtils::LogToPhysFactor(mWnd) != mDefaultScale) {
5640 ChangedDPI();
5641 ResetLayout();
5642 if (mWidgetListener) {
5643 mWidgetListener->UIResolutionChanged();
5647 break;
5649 case WM_ENTERSIZEMOVE: {
5650 if (mResizeState == NOT_RESIZING) {
5651 mResizeState = IN_SIZEMOVE;
5653 break;
5656 case WM_EXITSIZEMOVE: {
5657 FinishLiveResizing(NOT_RESIZING);
5659 if (!sIsInMouseCapture) {
5660 NotifySizeMoveDone();
5663 // Windows spins a separate hidden event loop when moving a window so we
5664 // don't hear mouse events during this time and WM_EXITSIZEMOVE is fired
5665 // when the hidden event loop exits. We set mDraggingWindowWithMouse to
5666 // true in WM_NCLBUTTONDOWN when we started moving the window with the
5667 // mouse so we know that if mDraggingWindowWithMouse is true, we can send
5668 // a mouse up event.
5669 if (mDraggingWindowWithMouse) {
5670 mDraggingWindowWithMouse = false;
5671 result = DispatchMouseEvent(
5672 eMouseUp, wParam, lParam, false, MouseButton::ePrimary,
5673 MOUSE_INPUT_SOURCE(),
5674 mPointerEvents.GetCachedPointerInfo(msg, wParam));
5677 break;
5680 case WM_DISPLAYCHANGE: {
5681 ScreenHelperWin::RefreshScreens();
5682 if (mWidgetListener) {
5683 mWidgetListener->UIResolutionChanged();
5685 break;
5688 case WM_NCLBUTTONDBLCLK:
5689 DispatchMouseEvent(eMouseDoubleClick, 0, lParamToClient(lParam), false,
5690 MouseButton::ePrimary, MOUSE_INPUT_SOURCE());
5691 result = DispatchMouseEvent(eMouseUp, 0, lParamToClient(lParam), false,
5692 MouseButton::ePrimary, MOUSE_INPUT_SOURCE());
5693 DispatchPendingEvents();
5694 break;
5696 case WM_NCLBUTTONDOWN: {
5697 // Dispatch a custom event when this happens in the draggable region, so
5698 // that non-popup-based panels can react to it. This doesn't send an
5699 // actual mousedown event because that would break dragging or interfere
5700 // with other mousedown handling in the caption area.
5701 if (ClientMarginHitTestPoint(GET_X_LPARAM(lParam),
5702 GET_Y_LPARAM(lParam)) == HTCAPTION) {
5703 DispatchCustomEvent(u"draggableregionleftmousedown"_ns);
5704 mDraggingWindowWithMouse = true;
5707 if (IsWindowButton(wParam) && mCustomNonClient) {
5708 DispatchMouseEvent(eMouseDown, wParamFromGlobalMouseState(),
5709 lParamToClient(lParam), false, MouseButton::ePrimary,
5710 MOUSE_INPUT_SOURCE(), nullptr, true);
5711 DispatchPendingEvents();
5712 result = true;
5714 break;
5717 case WM_APPCOMMAND: {
5718 MSG nativeMsg = WinUtils::InitMSG(msg, wParam, lParam, mWnd);
5719 result = HandleAppCommandMsg(nativeMsg, aRetValue);
5720 break;
5723 // The WM_ACTIVATE event is fired when a window is raised or lowered,
5724 // and the loword of wParam specifies which. But we don't want to tell
5725 // the focus system about this until the WM_SETFOCUS or WM_KILLFOCUS
5726 // events are fired. Instead, set either the sJustGotActivate or
5727 // gJustGotDeactivate flags and activate/deactivate once the focus
5728 // events arrive.
5729 case WM_ACTIVATE: {
5730 int32_t fActive = LOWORD(wParam);
5731 if (mWidgetListener) {
5732 if (WA_INACTIVE == fActive) {
5733 // when minimizing a window, the deactivation and focus events will
5734 // be fired in the reverse order. Instead, just deactivate right away.
5735 // This can also happen when a modal system dialog is opened, so check
5736 // if the last window to receive the WM_KILLFOCUS message was this one
5737 // or a child of this one.
5738 if (HIWORD(wParam) ||
5739 (mLastKillFocusWindow &&
5740 (GetTopLevelForFocus(mLastKillFocusWindow) == mWnd))) {
5741 DispatchFocusToTopLevelWindow(false);
5742 } else {
5743 sJustGotDeactivate = true;
5745 if (mIsTopWidgetWindow) {
5746 mLastKeyboardLayout = KeyboardLayout::GetLayout();
5748 } else {
5749 StopFlashing();
5751 sJustGotActivate = true;
5752 WidgetMouseEvent event(true, eMouseActivate, this,
5753 WidgetMouseEvent::eReal);
5754 InitEvent(event);
5755 ModifierKeyState modifierKeyState;
5756 modifierKeyState.InitInputEvent(event);
5757 DispatchInputEvent(&event);
5758 if (sSwitchKeyboardLayout && mLastKeyboardLayout)
5759 ActivateKeyboardLayout(mLastKeyboardLayout, 0);
5761 #ifdef ACCESSIBILITY
5762 a11y::LazyInstantiator::ResetUiaDetectionCache();
5763 #endif
5766 } break;
5768 case WM_ACTIVATEAPP: {
5769 // Bug 1851991: Sometimes this can be called before gfxPlatform::Init
5770 // when a window is created very early. In that case we just forego
5771 // setting this and accept the GPU process might briefly run at a lower
5772 // priority.
5773 if (GPUProcessManager::Get()) {
5774 GPUProcessManager::Get()->SetAppInForeground(wParam);
5776 } break;
5778 case WM_MOUSEACTIVATE:
5779 // A popup with a parent owner should not be activated when clicked but
5780 // should still allow the mouse event to be fired, so the return value
5781 // is set to MA_NOACTIVATE. But if the owner isn't the frontmost window,
5782 // just use default processing so that the window is activated.
5783 if (IsPopup() && IsOwnerForegroundWindow()) {
5784 *aRetValue = MA_NOACTIVATE;
5785 result = true;
5787 break;
5789 case WM_WINDOWPOSCHANGING: {
5790 LPWINDOWPOS info = (LPWINDOWPOS)lParam;
5791 OnWindowPosChanging(info);
5792 result = true;
5793 } break;
5795 // Workaround for race condition in explorer.exe.
5796 case MOZ_WM_FULLSCREEN_STATE_UPDATE: {
5797 TaskbarConcealer::OnAsyncStateUpdateRequest(mWnd);
5798 result = true;
5799 } break;
5801 case WM_GETMINMAXINFO: {
5802 MINMAXINFO* mmi = (MINMAXINFO*)lParam;
5803 // Set the constraints. The minimum size should also be constrained to the
5804 // default window maximum size so that it fits on screen.
5805 mmi->ptMinTrackSize.x =
5806 std::min((int32_t)mmi->ptMaxTrackSize.x,
5807 std::max((int32_t)mmi->ptMinTrackSize.x,
5808 mSizeConstraints.mMinSize.width));
5809 mmi->ptMinTrackSize.y =
5810 std::min((int32_t)mmi->ptMaxTrackSize.y,
5811 std::max((int32_t)mmi->ptMinTrackSize.y,
5812 mSizeConstraints.mMinSize.height));
5813 mmi->ptMaxTrackSize.x = std::min((int32_t)mmi->ptMaxTrackSize.x,
5814 mSizeConstraints.mMaxSize.width);
5815 mmi->ptMaxTrackSize.y = std::min((int32_t)mmi->ptMaxTrackSize.y,
5816 mSizeConstraints.mMaxSize.height);
5817 } break;
5819 case WM_SETFOCUS: {
5820 WndProcUrgentInvocation::Marker _marker;
5822 // If previous focused window isn't ours, it must have received the
5823 // redirected message. So, we should forget it.
5824 if (!WinUtils::IsOurProcessWindow(HWND(wParam))) {
5825 RedirectedKeyDownMessageManager::Forget();
5827 if (sJustGotActivate) {
5828 DispatchFocusToTopLevelWindow(true);
5830 TaskbarConcealer::OnFocusAcquired(this);
5831 } break;
5833 case WM_KILLFOCUS:
5834 if (sJustGotDeactivate) {
5835 DispatchFocusToTopLevelWindow(false);
5836 } else {
5837 mLastKillFocusWindow = mWnd;
5839 break;
5841 case WM_WINDOWPOSCHANGED: {
5842 WINDOWPOS* wp = (LPWINDOWPOS)lParam;
5843 OnWindowPosChanged(wp);
5844 TaskbarConcealer::OnWindowPosChanged(this);
5845 result = true;
5846 } break;
5848 case WM_INPUTLANGCHANGEREQUEST:
5849 *aRetValue = TRUE;
5850 result = false;
5851 break;
5853 case WM_INPUTLANGCHANGE:
5854 KeyboardLayout::GetInstance()->OnLayoutChange(
5855 reinterpret_cast<HKL>(lParam));
5856 nsBidiKeyboard::OnLayoutChange();
5857 result = false; // always pass to child window
5858 break;
5860 case WM_DESTROYCLIPBOARD: {
5861 nsIClipboard* clipboard;
5862 nsresult rv = CallGetService(kCClipboardCID, &clipboard);
5863 if (NS_SUCCEEDED(rv)) {
5864 clipboard->EmptyClipboard(nsIClipboard::kGlobalClipboard);
5865 NS_RELEASE(clipboard);
5867 } break;
5869 #ifdef ACCESSIBILITY
5870 case WM_GETOBJECT: {
5871 *aRetValue = 0;
5872 // Do explicit casting to make it working on 64bit systems (see bug 649236
5873 // for details).
5874 int32_t objId = static_cast<DWORD>(lParam);
5875 if (objId == OBJID_CLIENT) { // oleacc.dll will be loaded dynamically
5876 RefPtr<IAccessible> root(
5877 a11y::LazyInstantiator::GetRootAccessible(mWnd));
5878 if (root) {
5879 *aRetValue = LresultFromObject(IID_IAccessible, wParam, root);
5880 a11y::LazyInstantiator::EnableBlindAggregation(mWnd);
5881 result = true;
5883 } else if (objId == UiaRootObjectId &&
5884 StaticPrefs::accessibility_uia_enable()) {
5885 if (a11y::LocalAccessible* acc = GetAccessible()) {
5886 RefPtr<IAccessible> ia;
5887 acc->GetNativeInterface(getter_AddRefs(ia));
5888 MOZ_ASSERT(ia);
5889 RefPtr<IRawElementProviderSimple> uia;
5890 ia->QueryInterface(IID_IRawElementProviderSimple,
5891 getter_AddRefs(uia));
5892 if (uia) {
5893 *aRetValue = UiaReturnRawElementProvider(mWnd, wParam, lParam, uia);
5894 result = true;
5898 } break;
5899 #endif
5901 case WM_SYSCOMMAND: {
5902 WPARAM const filteredWParam = (wParam & 0xFFF0);
5904 // SC_CLOSE may trigger a synchronous confirmation prompt. If we're in the
5905 // middle of something important, put off responding to it.
5906 if (filteredWParam == SC_CLOSE && WndProcUrgentInvocation::IsActive()) {
5907 ::PostMessageW(mWnd, msg, wParam, lParam);
5908 result = true;
5909 break;
5912 if (mFrameState->GetSizeMode() == nsSizeMode_Fullscreen &&
5913 filteredWParam == SC_RESTORE &&
5914 GetCurrentShowCmd(mWnd) != SW_SHOWMINIMIZED) {
5915 mFrameState->EnsureFullscreenMode(false);
5916 result = true;
5919 // Handle the system menu manually when we're in full screen mode
5920 // so we can set the appropriate options.
5921 if (filteredWParam == SC_KEYMENU && lParam == VK_SPACE &&
5922 mFrameState->GetSizeMode() == nsSizeMode_Fullscreen) {
5923 DisplaySystemMenu(mWnd, mFrameState->GetSizeMode(), mIsRTL,
5924 MOZ_SYSCONTEXT_X_POS, MOZ_SYSCONTEXT_Y_POS);
5925 result = true;
5927 } break;
5929 case WM_DPICHANGED: {
5930 LPRECT rect = (LPRECT)lParam;
5931 OnDPIChanged(rect->left, rect->top, rect->right - rect->left,
5932 rect->bottom - rect->top);
5933 break;
5936 /* Gesture support events */
5937 case WM_TABLET_QUERYSYSTEMGESTURESTATUS:
5938 // According to MS samples, this must be handled to enable
5939 // rotational support in multi-touch drivers.
5940 result = true;
5941 *aRetValue = TABLET_ROTATE_GESTURE_ENABLE;
5942 break;
5944 case WM_TOUCH:
5945 result = OnTouch(wParam, lParam);
5946 if (result) {
5947 *aRetValue = 0;
5949 break;
5951 case WM_GESTURE:
5952 result = OnGesture(wParam, lParam);
5953 break;
5955 case WM_GESTURENOTIFY: {
5956 if (mWindowType != WindowType::Invisible) {
5957 // A GestureNotify event is dispatched to decide which single-finger
5958 // panning direction should be active (including none) and if pan
5959 // feedback should be displayed. Java and plugin windows can make their
5960 // own calls.
5962 GESTURENOTIFYSTRUCT* gestureinfo = (GESTURENOTIFYSTRUCT*)lParam;
5963 nsPointWin touchPoint;
5964 touchPoint = gestureinfo->ptsLocation;
5965 touchPoint.ScreenToClient(mWnd);
5966 WidgetGestureNotifyEvent gestureNotifyEvent(true, eGestureNotify, this);
5967 gestureNotifyEvent.mRefPoint =
5968 LayoutDeviceIntPoint::FromUnknownPoint(touchPoint);
5969 nsEventStatus status;
5970 DispatchEvent(&gestureNotifyEvent, status);
5971 mDisplayPanFeedback = gestureNotifyEvent.mDisplayPanFeedback;
5972 if (!mTouchWindow)
5973 mGesture.SetWinGestureSupport(mWnd, gestureNotifyEvent.mPanDirection);
5975 result = false; // should always bubble to DefWindowProc
5976 } break;
5978 case WM_CLEAR: {
5979 WidgetContentCommandEvent command(true, eContentCommandDelete, this);
5980 DispatchWindowEvent(command);
5981 result = true;
5982 } break;
5984 case WM_CUT: {
5985 WidgetContentCommandEvent command(true, eContentCommandCut, this);
5986 DispatchWindowEvent(command);
5987 result = true;
5988 } break;
5990 case WM_COPY: {
5991 WidgetContentCommandEvent command(true, eContentCommandCopy, this);
5992 DispatchWindowEvent(command);
5993 result = true;
5994 } break;
5996 case WM_PASTE: {
5997 WidgetContentCommandEvent command(true, eContentCommandPaste, this);
5998 DispatchWindowEvent(command);
5999 result = true;
6000 } break;
6002 case EM_UNDO: {
6003 WidgetContentCommandEvent command(true, eContentCommandUndo, this);
6004 DispatchWindowEvent(command);
6005 *aRetValue = (LRESULT)(command.mSucceeded && command.mIsEnabled);
6006 result = true;
6007 } break;
6009 case EM_REDO: {
6010 WidgetContentCommandEvent command(true, eContentCommandRedo, this);
6011 DispatchWindowEvent(command);
6012 *aRetValue = (LRESULT)(command.mSucceeded && command.mIsEnabled);
6013 result = true;
6014 } break;
6016 case EM_CANPASTE: {
6017 // Support EM_CANPASTE message only when wParam isn't specified or
6018 // is plain text format.
6019 if (wParam == 0 || wParam == CF_TEXT || wParam == CF_UNICODETEXT) {
6020 WidgetContentCommandEvent command(true, eContentCommandPaste, this,
6021 true);
6022 DispatchWindowEvent(command);
6023 *aRetValue = (LRESULT)(command.mSucceeded && command.mIsEnabled);
6024 result = true;
6026 } break;
6028 case EM_CANUNDO: {
6029 WidgetContentCommandEvent command(true, eContentCommandUndo, this, true);
6030 DispatchWindowEvent(command);
6031 *aRetValue = (LRESULT)(command.mSucceeded && command.mIsEnabled);
6032 result = true;
6033 } break;
6035 case EM_CANREDO: {
6036 WidgetContentCommandEvent command(true, eContentCommandRedo, this, true);
6037 DispatchWindowEvent(command);
6038 *aRetValue = (LRESULT)(command.mSucceeded && command.mIsEnabled);
6039 result = true;
6040 } break;
6042 case MOZ_WM_SKEWFIX: {
6043 TimeStamp skewStamp;
6044 if (CurrentWindowsTimeGetter::GetAndClearBackwardsSkewStamp(wParam,
6045 &skewStamp)) {
6046 TimeConverter().CompensateForBackwardsSkew(::GetMessageTime(),
6047 skewStamp);
6049 } break;
6051 default: {
6052 if (msg == nsAppShell::GetTaskbarButtonCreatedMessage()) {
6053 SetHasTaskbarIconBeenCreated();
6055 } break;
6058 //*aRetValue = result;
6059 if (mWnd) {
6060 return result;
6061 } else {
6062 // Events which caused mWnd destruction and aren't consumed
6063 // will crash during the Windows default processing.
6064 return true;
6068 void nsWindow::FinishLiveResizing(ResizeState aNewState) {
6069 if (mResizeState == RESIZING) {
6070 NotifyLiveResizeStopped();
6072 mResizeState = aNewState;
6073 ForcePresent();
6076 /**************************************************************
6078 * SECTION: Event processing helpers
6080 * Special processing for certain event types and
6081 * synthesized events.
6083 **************************************************************/
6085 LayoutDeviceIntMargin nsWindow::NonClientSizeMargin(
6086 const LayoutDeviceIntMargin& aNonClientOffset) const {
6087 return LayoutDeviceIntMargin(mCaptionHeight - aNonClientOffset.top,
6088 mHorResizeMargin - aNonClientOffset.right,
6089 mVertResizeMargin - aNonClientOffset.bottom,
6090 mHorResizeMargin - aNonClientOffset.left);
6093 int32_t nsWindow::ClientMarginHitTestPoint(int32_t aX, int32_t aY) {
6094 const nsSizeMode sizeMode = mFrameState->GetSizeMode();
6095 if (sizeMode == nsSizeMode_Minimized || sizeMode == nsSizeMode_Fullscreen) {
6096 return HTCLIENT;
6099 // Calculations are done in screen coords
6100 const LayoutDeviceIntRect winRect = GetScreenBounds();
6101 const LayoutDeviceIntPoint point(aX, aY);
6103 // hit return constants:
6104 // HTBORDER - non-resizable border
6105 // HTBOTTOM, HTLEFT, HTRIGHT, HTTOP - resizable border
6106 // HTBOTTOMLEFT, HTBOTTOMRIGHT - resizable corner
6107 // HTTOPLEFT, HTTOPRIGHT - resizable corner
6108 // HTCAPTION - general title bar area
6109 // HTCLIENT - area considered the client
6110 // HTCLOSE - hovering over the close button
6111 // HTMAXBUTTON - maximize button
6112 // HTMINBUTTON - minimize button
6114 int32_t testResult = HTCLIENT;
6115 const bool isResizable =
6116 sizeMode != nsSizeMode_Maximized &&
6117 (mBorderStyle &
6118 (BorderStyle::All | BorderStyle::ResizeH | BorderStyle::Default));
6120 LayoutDeviceIntMargin nonClientSizeMargin = NonClientSizeMargin();
6122 // Ensure being accessible to borders of window. Even if contents are in
6123 // this area, the area must behave as border.
6124 nonClientSizeMargin.EnsureAtLeast(
6125 LayoutDeviceIntMargin(kResizableBorderMinSize, kResizableBorderMinSize,
6126 kResizableBorderMinSize, kResizableBorderMinSize));
6128 LayoutDeviceIntRect clientRect = winRect;
6129 clientRect.Deflate(nonClientSizeMargin);
6131 const bool allowContentOverride =
6132 sizeMode == nsSizeMode_Maximized || clientRect.Contains(point);
6134 // The border size. If there is no content under mouse cursor, the border
6135 // size should be larger than the values in system settings. Otherwise,
6136 // contents under the mouse cursor should be able to override the behavior.
6137 // E.g., user must expect that Firefox button always opens the popup menu
6138 // even when the user clicks on the above edge of it.
6139 LayoutDeviceIntMargin borderSize = nonClientSizeMargin;
6140 borderSize.EnsureAtLeast(
6141 LayoutDeviceIntMargin(mVertResizeMargin, mHorResizeMargin,
6142 mVertResizeMargin, mHorResizeMargin));
6144 bool top = false;
6145 bool bottom = false;
6146 bool left = false;
6147 bool right = false;
6149 if (point.y >= winRect.y && point.y < winRect.y + borderSize.top) {
6150 top = true;
6151 } else if (point.y <= winRect.YMost() &&
6152 point.y > winRect.YMost() - borderSize.bottom) {
6153 bottom = true;
6156 // (the 2x case here doubles the resize area for corners)
6157 int multiplier = (top || bottom) ? 2 : 1;
6158 if (point.x >= winRect.x &&
6159 point.x < winRect.x + (multiplier * borderSize.left)) {
6160 left = true;
6161 } else if (point.x <= winRect.XMost() &&
6162 point.x > winRect.XMost() - (multiplier * borderSize.right)) {
6163 right = true;
6166 bool inResizeRegion = false;
6167 if (isResizable) {
6168 if (top) {
6169 testResult = HTTOP;
6170 if (left) {
6171 testResult = HTTOPLEFT;
6172 } else if (right) {
6173 testResult = HTTOPRIGHT;
6175 } else if (bottom) {
6176 testResult = HTBOTTOM;
6177 if (left) {
6178 testResult = HTBOTTOMLEFT;
6179 } else if (right) {
6180 testResult = HTBOTTOMRIGHT;
6182 } else {
6183 if (left) {
6184 testResult = HTLEFT;
6186 if (right) {
6187 testResult = HTRIGHT;
6190 inResizeRegion = (testResult != HTCLIENT);
6191 } else {
6192 if (top) {
6193 testResult = HTCAPTION;
6194 } else if (bottom || left || right) {
6195 testResult = HTBORDER;
6199 if (!sIsInMouseCapture && allowContentOverride) {
6201 POINT pt = {aX, aY};
6202 ::ScreenToClient(mWnd, &pt);
6204 if (pt.x == mCachedHitTestPoint.x.value &&
6205 pt.y == mCachedHitTestPoint.y.value &&
6206 TimeStamp::Now() - mCachedHitTestTime <
6207 TimeDuration::FromMilliseconds(HITTEST_CACHE_LIFETIME_MS)) {
6208 return mCachedHitTestResult;
6211 mCachedHitTestPoint = {pt.x, pt.y};
6212 mCachedHitTestTime = TimeStamp::Now();
6215 auto pt = mCachedHitTestPoint;
6217 if (mWindowBtnRect[WindowButtonType::Minimize].Contains(pt)) {
6218 testResult = HTMINBUTTON;
6219 } else if (mWindowBtnRect[WindowButtonType::Maximize].Contains(pt)) {
6220 #ifdef ACCESSIBILITY
6221 a11y::Compatibility::SuppressA11yForSnapLayouts();
6222 #endif
6223 testResult = HTMAXBUTTON;
6224 } else if (mWindowBtnRect[WindowButtonType::Close].Contains(pt)) {
6225 testResult = HTCLOSE;
6226 } else if (!inResizeRegion) {
6227 // If we're in the resize region, avoid overriding that with either a
6228 // drag or a client result; resize takes priority over either (but not
6229 // over the window controls, which is why we check this after those).
6230 if (mDraggableRegion.Contains(pt)) {
6231 testResult = HTCAPTION;
6232 } else {
6233 testResult = HTCLIENT;
6237 mCachedHitTestResult = testResult;
6240 return testResult;
6243 bool nsWindow::IsSimulatedClientArea(int32_t screenX, int32_t screenY) {
6244 int32_t testResult = ClientMarginHitTestPoint(screenX, screenY);
6245 return testResult == HTCAPTION || IsWindowButton(testResult);
6248 bool nsWindow::IsWindowButton(int32_t hitTestResult) {
6249 return hitTestResult == HTMINBUTTON || hitTestResult == HTMAXBUTTON ||
6250 hitTestResult == HTCLOSE;
6253 TimeStamp nsWindow::GetMessageTimeStamp(LONG aEventTime) const {
6254 CurrentWindowsTimeGetter getCurrentTime(mWnd);
6255 return TimeConverter().GetTimeStampFromSystemTime(aEventTime, getCurrentTime);
6258 void nsWindow::PostSleepWakeNotification(const bool aIsSleepMode) {
6259 // Retain the previous mode that was notified to observers
6260 static bool sWasSleepMode = false;
6262 // Only notify observers if mode changed
6263 if (aIsSleepMode == sWasSleepMode) return;
6265 sWasSleepMode = aIsSleepMode;
6267 nsCOMPtr<nsIObserverService> observerService =
6268 mozilla::services::GetObserverService();
6269 if (observerService)
6270 observerService->NotifyObservers(nullptr,
6271 aIsSleepMode
6272 ? NS_WIDGET_SLEEP_OBSERVER_TOPIC
6273 : NS_WIDGET_WAKE_OBSERVER_TOPIC,
6274 nullptr);
6277 LRESULT nsWindow::ProcessCharMessage(const MSG& aMsg, bool* aEventDispatched) {
6278 if (IMEHandler::IsComposingOn(this)) {
6279 IMEHandler::NotifyIME(this, REQUEST_TO_COMMIT_COMPOSITION);
6281 // These must be checked here too as a lone WM_CHAR could be received
6282 // if a child window didn't handle it (for example Alt+Space in a content
6283 // window)
6284 ModifierKeyState modKeyState;
6285 NativeKey nativeKey(this, aMsg, modKeyState);
6286 return static_cast<LRESULT>(nativeKey.HandleCharMessage(aEventDispatched));
6289 LRESULT nsWindow::ProcessKeyUpMessage(const MSG& aMsg, bool* aEventDispatched) {
6290 ModifierKeyState modKeyState;
6291 NativeKey nativeKey(this, aMsg, modKeyState);
6292 bool result = nativeKey.HandleKeyUpMessage(aEventDispatched);
6293 if (aMsg.wParam == VK_F10) {
6294 // Bug 1382199: Windows default behavior will trigger the System menu bar
6295 // when F10 is released. Among other things, this causes the System menu bar
6296 // to appear when a web page overrides the contextmenu event. We *never*
6297 // want this default behavior, so eat this key (never pass it to Windows).
6298 return true;
6300 return result;
6303 LRESULT nsWindow::ProcessKeyDownMessage(const MSG& aMsg,
6304 bool* aEventDispatched) {
6305 // If this method doesn't call NativeKey::HandleKeyDownMessage(), this method
6306 // must clean up the redirected message information itself. For more
6307 // information, see above comment of
6308 // RedirectedKeyDownMessageManager::AutoFlusher class definition in
6309 // KeyboardLayout.h.
6310 RedirectedKeyDownMessageManager::AutoFlusher redirectedMsgFlusher(this, aMsg);
6312 ModifierKeyState modKeyState;
6314 NativeKey nativeKey(this, aMsg, modKeyState);
6315 LRESULT result =
6316 static_cast<LRESULT>(nativeKey.HandleKeyDownMessage(aEventDispatched));
6317 // HandleKeyDownMessage cleaned up the redirected message information
6318 // itself, so, we should do nothing.
6319 redirectedMsgFlusher.Cancel();
6321 if (aMsg.wParam == VK_MENU ||
6322 (aMsg.wParam == VK_F10 && !modKeyState.IsShift())) {
6323 // We need to let Windows handle this keypress,
6324 // by returning false, if there's a native menu
6325 // bar somewhere in our containing window hierarchy.
6326 // Otherwise we handle the keypress and don't pass
6327 // it on to Windows, by returning true.
6328 bool hasNativeMenu = false;
6329 HWND hWnd = mWnd;
6330 while (hWnd) {
6331 if (::GetMenu(hWnd)) {
6332 hasNativeMenu = true;
6333 break;
6335 hWnd = ::GetParent(hWnd);
6337 result = !hasNativeMenu;
6340 return result;
6343 nsresult nsWindow::SynthesizeNativeKeyEvent(
6344 int32_t aNativeKeyboardLayout, int32_t aNativeKeyCode,
6345 uint32_t aModifierFlags, const nsAString& aCharacters,
6346 const nsAString& aUnmodifiedCharacters, nsIObserver* aObserver) {
6347 AutoObserverNotifier notifier(aObserver, "keyevent");
6349 KeyboardLayout* keyboardLayout = KeyboardLayout::GetInstance();
6350 return keyboardLayout->SynthesizeNativeKeyEvent(
6351 this, aNativeKeyboardLayout, aNativeKeyCode, aModifierFlags, aCharacters,
6352 aUnmodifiedCharacters);
6355 nsresult nsWindow::SynthesizeNativeMouseEvent(
6356 LayoutDeviceIntPoint aPoint, NativeMouseMessage aNativeMessage,
6357 MouseButton aButton, nsIWidget::Modifiers aModifierFlags,
6358 nsIObserver* aObserver) {
6359 AutoObserverNotifier notifier(aObserver, "mouseevent");
6361 INPUT input;
6362 memset(&input, 0, sizeof(input));
6364 // TODO (bug 1693240):
6365 // Now, we synthesize native mouse events asynchronously since we want to
6366 // synthesize the event on the front window at the point. However, Windows
6367 // does not provide a way to set modifier only while a mouse message is
6368 // being handled, and MOUSEEVENTF_MOVE may be coalesced by Windows. So, we
6369 // need a trick for handling it.
6371 switch (aNativeMessage) {
6372 case NativeMouseMessage::Move:
6373 input.mi.dwFlags = MOUSEEVENTF_MOVE;
6374 // Reset sLastMouseMovePoint so that even if we're moving the mouse
6375 // to the position it's already at, we still dispatch a mousemove
6376 // event, because the callers of this function expect that.
6377 sLastMouseMovePoint = {0};
6378 break;
6379 case NativeMouseMessage::ButtonDown:
6380 case NativeMouseMessage::ButtonUp: {
6381 const bool isDown = aNativeMessage == NativeMouseMessage::ButtonDown;
6382 switch (aButton) {
6383 case MouseButton::ePrimary:
6384 input.mi.dwFlags = isDown ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP;
6385 break;
6386 case MouseButton::eMiddle:
6387 input.mi.dwFlags =
6388 isDown ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_MIDDLEUP;
6389 break;
6390 case MouseButton::eSecondary:
6391 input.mi.dwFlags =
6392 isDown ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP;
6393 break;
6394 case MouseButton::eX1:
6395 input.mi.dwFlags = isDown ? MOUSEEVENTF_XDOWN : MOUSEEVENTF_XUP;
6396 input.mi.mouseData = XBUTTON1;
6397 break;
6398 case MouseButton::eX2:
6399 input.mi.dwFlags = isDown ? MOUSEEVENTF_XDOWN : MOUSEEVENTF_XUP;
6400 input.mi.mouseData = XBUTTON2;
6401 break;
6402 default:
6403 return NS_ERROR_INVALID_ARG;
6405 break;
6407 case NativeMouseMessage::EnterWindow:
6408 case NativeMouseMessage::LeaveWindow:
6409 MOZ_ASSERT_UNREACHABLE("Non supported mouse event on Windows");
6410 return NS_ERROR_INVALID_ARG;
6413 input.type = INPUT_MOUSE;
6414 ::SetCursorPos(aPoint.x, aPoint.y);
6415 ::SendInput(1, &input, sizeof(INPUT));
6417 return NS_OK;
6420 nsresult nsWindow::SynthesizeNativeMouseScrollEvent(
6421 LayoutDeviceIntPoint aPoint, uint32_t aNativeMessage, double aDeltaX,
6422 double aDeltaY, double aDeltaZ, uint32_t aModifierFlags,
6423 uint32_t aAdditionalFlags, nsIObserver* aObserver) {
6424 AutoObserverNotifier notifier(aObserver, "mousescrollevent");
6425 return MouseScrollHandler::SynthesizeNativeMouseScrollEvent(
6426 this, aPoint, aNativeMessage,
6427 (aNativeMessage == WM_MOUSEWHEEL || aNativeMessage == WM_VSCROLL)
6428 ? static_cast<int32_t>(aDeltaY)
6429 : static_cast<int32_t>(aDeltaX),
6430 aModifierFlags, aAdditionalFlags);
6433 nsresult nsWindow::SynthesizeNativeTouchpadPan(TouchpadGesturePhase aEventPhase,
6434 LayoutDeviceIntPoint aPoint,
6435 double aDeltaX, double aDeltaY,
6436 int32_t aModifierFlags,
6437 nsIObserver* aObserver) {
6438 AutoObserverNotifier notifier(aObserver, "touchpadpanevent");
6439 DirectManipulationOwner::SynthesizeNativeTouchpadPan(
6440 this, aEventPhase, aPoint, aDeltaX, aDeltaY, aModifierFlags);
6441 return NS_OK;
6444 static void MaybeLogPosChanged(HWND aWnd, WINDOWPOS* wp) {
6445 #ifdef WINSTATE_DEBUG_OUTPUT
6446 if (aWnd == WinUtils::GetTopLevelHWND(aWnd)) {
6447 MOZ_LOG(gWindowsLog, LogLevel::Info, ("*** OnWindowPosChanged: [ top] "));
6448 } else {
6449 MOZ_LOG(gWindowsLog, LogLevel::Info, ("*** OnWindowPosChanged: [child] "));
6451 MOZ_LOG(gWindowsLog, LogLevel::Info, ("WINDOWPOS flags:"));
6452 if (wp->flags & SWP_FRAMECHANGED) {
6453 MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_FRAMECHANGED "));
6455 if (wp->flags & SWP_SHOWWINDOW) {
6456 MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_SHOWWINDOW "));
6458 if (wp->flags & SWP_NOSIZE) {
6459 MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_NOSIZE "));
6461 if (wp->flags & SWP_HIDEWINDOW) {
6462 MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_HIDEWINDOW "));
6464 if (wp->flags & SWP_NOZORDER) {
6465 MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_NOZORDER "));
6467 if (wp->flags & SWP_NOACTIVATE) {
6468 MOZ_LOG(gWindowsLog, LogLevel::Info, ("SWP_NOACTIVATE "));
6470 MOZ_LOG(gWindowsLog, LogLevel::Info, ("\n"));
6471 #endif
6474 /**************************************************************
6476 * SECTION: OnXXX message handlers
6478 * For message handlers that need to be broken out or
6479 * implemented in specific platform code.
6481 **************************************************************/
6483 void nsWindow::OnWindowPosChanged(WINDOWPOS* wp) {
6484 if (!wp) {
6485 return;
6488 MaybeLogPosChanged(mWnd, wp);
6490 // Handle window size mode changes
6491 if (wp->flags & SWP_FRAMECHANGED) {
6492 // Bug 566135 - Windows theme code calls show window on SW_SHOWMINIMIZED
6493 // windows when fullscreen games disable desktop composition. If we're
6494 // minimized and not being activated, ignore the event and let windows
6495 // handle it.
6496 if (mFrameState->GetSizeMode() == nsSizeMode_Minimized &&
6497 (wp->flags & SWP_NOACTIVATE)) {
6498 return;
6501 mFrameState->OnFrameChanged();
6503 if (mFrameState->GetSizeMode() == nsSizeMode_Minimized) {
6504 // Skip window size change events below on minimization.
6505 return;
6509 // Notify visibility change when window is activated.
6510 if (!(wp->flags & SWP_NOACTIVATE) && NeedsToTrackWindowOcclusionState()) {
6511 WinWindowOcclusionTracker::Get()->OnWindowVisibilityChanged(
6512 this, mFrameState->GetSizeMode() != nsSizeMode_Minimized);
6515 // Handle window position changes
6516 if (!(wp->flags & SWP_NOMOVE)) {
6517 mBounds.MoveTo(wp->x, wp->y);
6518 NotifyWindowMoved(wp->x, wp->y);
6521 // Handle window size changes
6522 if (!(wp->flags & SWP_NOSIZE)) {
6523 RECT r;
6524 int32_t newWidth, newHeight;
6526 ::GetWindowRect(mWnd, &r);
6528 newWidth = r.right - r.left;
6529 newHeight = r.bottom - r.top;
6531 if (newWidth > mLastSize.width) {
6532 RECT drect;
6534 // getting wider
6535 drect.left = wp->x + mLastSize.width;
6536 drect.top = wp->y;
6537 drect.right = drect.left + (newWidth - mLastSize.width);
6538 drect.bottom = drect.top + newHeight;
6540 ::RedrawWindow(mWnd, &drect, nullptr,
6541 RDW_INVALIDATE | RDW_NOERASE | RDW_NOINTERNALPAINT |
6542 RDW_ERASENOW | RDW_ALLCHILDREN);
6544 if (newHeight > mLastSize.height) {
6545 RECT drect;
6547 // getting taller
6548 drect.left = wp->x;
6549 drect.top = wp->y + mLastSize.height;
6550 drect.right = drect.left + newWidth;
6551 drect.bottom = drect.top + (newHeight - mLastSize.height);
6553 ::RedrawWindow(mWnd, &drect, nullptr,
6554 RDW_INVALIDATE | RDW_NOERASE | RDW_NOINTERNALPAINT |
6555 RDW_ERASENOW | RDW_ALLCHILDREN);
6558 mBounds.SizeTo(newWidth, newHeight);
6559 mLastSize.width = newWidth;
6560 mLastSize.height = newHeight;
6562 #ifdef WINSTATE_DEBUG_OUTPUT
6563 MOZ_LOG(gWindowsLog, LogLevel::Info,
6564 ("*** Resize window: %d x %d x %d x %d\n", wp->x, wp->y, newWidth,
6565 newHeight));
6566 #endif
6568 if (mAspectRatio > 0) {
6569 // It's possible (via Windows Aero Snap) that the size of the window
6570 // has changed such that it violates the aspect ratio constraint. If so,
6571 // queue up an event to enforce the aspect ratio constraint and repaint.
6572 // When resized with Windows Aero Snap, we are in the NOT_RESIZING state.
6573 float newAspectRatio = (float)newWidth / newHeight;
6574 if (mResizeState == NOT_RESIZING && mAspectRatio != newAspectRatio) {
6575 // Hold a reference to self alive and pass it into the lambda to make
6576 // sure this nsIWidget stays alive long enough to run this function.
6577 nsCOMPtr<nsIWidget> self(this);
6578 NS_DispatchToMainThread(NS_NewRunnableFunction(
6579 "EnforceAspectRatio", [self, this, newWidth]() -> void {
6580 if (mWnd) {
6581 Resize(newWidth, newWidth / mAspectRatio, true);
6583 }));
6587 // If a maximized window is resized, recalculate the non-client margins.
6588 if (mFrameState->GetSizeMode() == nsSizeMode_Maximized) {
6589 if (UpdateNonClientMargins(true)) {
6590 // gecko resize event already sent by UpdateNonClientMargins.
6591 return;
6596 // Notify the widget listener for size change of client area for gecko
6597 // events. This needs to be done when either window size is changed,
6598 // or window frame is changed. They may not happen together.
6599 // However, we don't invoke that for popup when window frame changes,
6600 // because popups may trigger frame change before size change via
6601 // {Set,Clear}ThemeRegion they invoke in Resize. That would make the
6602 // code below call OnResize with a wrong client size first, which can
6603 // lead to flickerling for some popups.
6604 if (!(wp->flags & SWP_NOSIZE) ||
6605 ((wp->flags & SWP_FRAMECHANGED) && !IsPopup())) {
6606 RECT r;
6607 LayoutDeviceIntSize clientSize;
6608 if (::GetClientRect(mWnd, &r)) {
6609 clientSize = WinUtils::ToIntRect(r).Size();
6610 } else {
6611 clientSize = mBounds.Size();
6613 // Send a gecko resize event
6614 OnResize(clientSize);
6618 void nsWindow::OnWindowPosChanging(WINDOWPOS* info) {
6619 // Update non-client margins if the frame size is changing, and let the
6620 // browser know we are changing size modes, so alternative css can kick in.
6621 // If we're going into fullscreen mode, ignore this, since it'll reset
6622 // margins to normal mode.
6623 if (info->flags & SWP_FRAMECHANGED && !(info->flags & SWP_NOSIZE)) {
6624 mFrameState->OnFrameChanging();
6627 // Force fullscreen. This works around a bug in Windows 10 1809 where
6628 // using fullscreen when a window is "snapped" causes a spurious resize
6629 // smaller than the full screen, see bug 1482920.
6630 if (mFrameState->GetSizeMode() == nsSizeMode_Fullscreen &&
6631 !(info->flags & SWP_NOMOVE) && !(info->flags & SWP_NOSIZE)) {
6632 nsCOMPtr<nsIScreenManager> screenmgr =
6633 do_GetService(sScreenManagerContractID);
6634 if (screenmgr) {
6635 LayoutDeviceIntRect bounds(info->x, info->y, info->cx, info->cy);
6636 DesktopIntRect deskBounds =
6637 RoundedToInt(bounds / GetDesktopToDeviceScale());
6638 nsCOMPtr<nsIScreen> screen;
6639 screenmgr->ScreenForRect(deskBounds.X(), deskBounds.Y(),
6640 deskBounds.Width(), deskBounds.Height(),
6641 getter_AddRefs(screen));
6643 if (screen) {
6644 auto rect = screen->GetRect();
6645 info->x = rect.x;
6646 info->y = rect.y;
6647 info->cx = rect.width;
6648 info->cy = rect.height;
6653 // enforce local z-order rules
6654 if (!(info->flags & SWP_NOZORDER)) {
6655 HWND hwndAfter = info->hwndInsertAfter;
6657 nsWindow* aboveWindow = 0;
6658 nsWindowZ placement;
6660 if (hwndAfter == HWND_BOTTOM)
6661 placement = nsWindowZBottom;
6662 else if (hwndAfter == HWND_TOP || hwndAfter == HWND_TOPMOST ||
6663 hwndAfter == HWND_NOTOPMOST)
6664 placement = nsWindowZTop;
6665 else {
6666 placement = nsWindowZRelative;
6667 aboveWindow = WinUtils::GetNSWindowPtr(hwndAfter);
6670 if (mWidgetListener) {
6671 nsCOMPtr<nsIWidget> actualBelow = nullptr;
6672 if (mWidgetListener->ZLevelChanged(false, &placement, aboveWindow,
6673 getter_AddRefs(actualBelow))) {
6674 if (placement == nsWindowZBottom)
6675 info->hwndInsertAfter = HWND_BOTTOM;
6676 else if (placement == nsWindowZTop)
6677 info->hwndInsertAfter = HWND_TOP;
6678 else {
6679 info->hwndInsertAfter =
6680 (HWND)actualBelow->GetNativeData(NS_NATIVE_WINDOW);
6685 // prevent rude external programs from making hidden window visible
6686 if (mWindowType == WindowType::Invisible) info->flags &= ~SWP_SHOWWINDOW;
6688 // When waking from sleep or switching out of tablet mode, Windows 10
6689 // Version 1809 will reopen popup windows that should be hidden. Detect
6690 // this case and refuse to show the window.
6691 static bool sDWMUnhidesPopups = IsWin10Sep2018UpdateOrLater();
6692 if (sDWMUnhidesPopups && (info->flags & SWP_SHOWWINDOW) &&
6693 mWindowType == WindowType::Popup && mWidgetListener &&
6694 mWidgetListener->ShouldNotBeVisible()) {
6695 info->flags &= ~SWP_SHOWWINDOW;
6699 void nsWindow::UserActivity() {
6700 // Check if we have the idle service, if not we try to get it.
6701 if (!mIdleService) {
6702 mIdleService = do_GetService("@mozilla.org/widget/useridleservice;1");
6705 // Check that we now have the idle service.
6706 if (mIdleService) {
6707 mIdleService->ResetIdleTimeOut(0);
6711 // Helper function for TouchDeviceNeedsPanGestureConversion(PTOUCHINPUT,
6712 // uint32_t).
6713 static bool TouchDeviceNeedsPanGestureConversion(HANDLE aSource) {
6714 std::string deviceName;
6715 UINT dataSize = 0;
6716 // The first call just queries how long the name string will be.
6717 GetRawInputDeviceInfoA(aSource, RIDI_DEVICENAME, nullptr, &dataSize);
6718 if (!dataSize || dataSize > 0x10000) {
6719 return false;
6721 deviceName.resize(dataSize);
6722 // The second call actually populates the string.
6723 UINT result = GetRawInputDeviceInfoA(aSource, RIDI_DEVICENAME, &deviceName[0],
6724 &dataSize);
6725 if (result == UINT_MAX) {
6726 return false;
6728 // The affected device name is "\\?\VIRTUAL_DIGITIZER", but each backslash
6729 // needs to be escaped with another one.
6730 std::string expectedDeviceName = "\\\\?\\VIRTUAL_DIGITIZER";
6731 // For some reason, the dataSize returned by the first call is double the
6732 // actual length of the device name (as if it were returning the size of a
6733 // wide-character string in bytes) even though we are using the narrow
6734 // version of the API. For the comparison against the expected device name
6735 // to pass, we truncate the buffer to be no longer tha the expected device
6736 // name.
6737 if (deviceName.substr(0, expectedDeviceName.length()) != expectedDeviceName) {
6738 return false;
6741 RID_DEVICE_INFO deviceInfo;
6742 deviceInfo.cbSize = sizeof(deviceInfo);
6743 dataSize = sizeof(deviceInfo);
6744 result =
6745 GetRawInputDeviceInfoA(aSource, RIDI_DEVICEINFO, &deviceInfo, &dataSize);
6746 if (result == UINT_MAX) {
6747 return false;
6749 // The device identifiers that we check for here come from bug 1355162
6750 // comment 1 (see also bug 1511901 comment 35).
6751 return deviceInfo.dwType == RIM_TYPEHID && deviceInfo.hid.dwVendorId == 0 &&
6752 deviceInfo.hid.dwProductId == 0 &&
6753 deviceInfo.hid.dwVersionNumber == 1 &&
6754 deviceInfo.hid.usUsagePage == 13 && deviceInfo.hid.usUsage == 4;
6757 // Determine if the touch device that originated |aOSEvent| needs to have
6758 // touch events representing a two-finger gesture converted to pan
6759 // gesture events.
6760 // We only do this for touch devices with a specific name and identifiers.
6761 static bool TouchDeviceNeedsPanGestureConversion(PTOUCHINPUT aOSEvent,
6762 uint32_t aTouchCount) {
6763 if (!StaticPrefs::apz_windows_check_for_pan_gesture_conversion()) {
6764 return false;
6766 if (aTouchCount == 0) {
6767 return false;
6769 HANDLE source = aOSEvent[0].hSource;
6771 // Cache the result of this computation for each touch device.
6772 // Touch devices are identified by the HANDLE stored in the hSource
6773 // field of TOUCHINPUT.
6774 static std::map<HANDLE, bool> sResultCache;
6775 auto [iter, inserted] = sResultCache.emplace(source, false);
6776 if (inserted) {
6777 iter->second = TouchDeviceNeedsPanGestureConversion(source);
6779 return iter->second;
6782 Maybe<PanGestureInput> nsWindow::ConvertTouchToPanGesture(
6783 const MultiTouchInput& aTouchInput, PTOUCHINPUT aOSEvent) {
6784 // Checks if the touch device that originated the touch event is one
6785 // for which we want to convert the touch events to pang gesture events.
6786 bool shouldConvert = TouchDeviceNeedsPanGestureConversion(
6787 aOSEvent, aTouchInput.mTouches.Length());
6788 if (!shouldConvert) {
6789 return Nothing();
6792 // Only two-finger gestures need conversion.
6793 if (aTouchInput.mTouches.Length() != 2) {
6794 return Nothing();
6797 PanGestureInput::PanGestureType eventType = PanGestureInput::PANGESTURE_PAN;
6798 if (aTouchInput.mType == MultiTouchInput::MULTITOUCH_START) {
6799 eventType = PanGestureInput::PANGESTURE_START;
6800 } else if (aTouchInput.mType == MultiTouchInput::MULTITOUCH_END) {
6801 eventType = PanGestureInput::PANGESTURE_END;
6802 } else if (aTouchInput.mType == MultiTouchInput::MULTITOUCH_CANCEL) {
6803 eventType = PanGestureInput::PANGESTURE_CANCELLED;
6806 // Use the midpoint of the two touches as the start point of the pan gesture.
6807 ScreenPoint focusPoint = (aTouchInput.mTouches[0].mScreenPoint +
6808 aTouchInput.mTouches[1].mScreenPoint) /
6810 // To compute the displacement of the pan gesture, we keep track of the
6811 // location of the previous event.
6812 ScreenPoint displacement = (eventType == PanGestureInput::PANGESTURE_START)
6813 ? ScreenPoint(0, 0)
6814 : (focusPoint - mLastPanGestureFocus);
6815 mLastPanGestureFocus = focusPoint;
6817 // We need to negate the displacement because for a touch event, moving the
6818 // fingers down results in scrolling up, but for a touchpad gesture, we want
6819 // moving the fingers down to result in scrolling down.
6820 PanGestureInput result(eventType, aTouchInput.mTimeStamp, focusPoint,
6821 -displacement, aTouchInput.modifiers);
6822 result.mSimulateMomentum = true;
6824 return Some(result);
6827 // Dispatch an event that originated as an OS touch event.
6828 // Usually, we want to dispatch it as a touch event, but some touchpads
6829 // produce touch events for two-finger scrolling, which need to be converted
6830 // to pan gesture events for correct behaviour.
6831 void nsWindow::DispatchTouchOrPanGestureInput(MultiTouchInput& aTouchInput,
6832 PTOUCHINPUT aOSEvent) {
6833 if (Maybe<PanGestureInput> panInput =
6834 ConvertTouchToPanGesture(aTouchInput, aOSEvent)) {
6835 DispatchPanGestureInput(*panInput);
6836 return;
6839 DispatchTouchInput(aTouchInput);
6842 bool nsWindow::OnTouch(WPARAM wParam, LPARAM lParam) {
6843 uint32_t cInputs = LOWORD(wParam);
6844 PTOUCHINPUT pInputs = new TOUCHINPUT[cInputs];
6846 if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, pInputs,
6847 sizeof(TOUCHINPUT))) {
6848 MultiTouchInput touchInput, touchEndInput;
6850 // Walk across the touch point array processing each contact point.
6851 for (uint32_t i = 0; i < cInputs; i++) {
6852 bool addToEvent = false, addToEndEvent = false;
6854 // N.B.: According with MS documentation
6855 // https://msdn.microsoft.com/en-us/library/windows/desktop/dd317334(v=vs.85).aspx
6856 // TOUCHEVENTF_DOWN cannot be combined with TOUCHEVENTF_MOVE or
6857 // TOUCHEVENTF_UP. Possibly, it means that TOUCHEVENTF_MOVE and
6858 // TOUCHEVENTF_UP can be combined together.
6860 if (pInputs[i].dwFlags & (TOUCHEVENTF_DOWN | TOUCHEVENTF_MOVE)) {
6861 if (touchInput.mTimeStamp.IsNull()) {
6862 // Initialize a touch event to send.
6863 touchInput.mType = MultiTouchInput::MULTITOUCH_MOVE;
6864 touchInput.mTimeStamp = GetMessageTimeStamp(::GetMessageTime());
6865 ModifierKeyState modifierKeyState;
6866 touchInput.modifiers = modifierKeyState.GetModifiers();
6868 // Pres shell expects this event to be a eTouchStart
6869 // if any new contact points have been added since the last event sent.
6870 if (pInputs[i].dwFlags & TOUCHEVENTF_DOWN) {
6871 touchInput.mType = MultiTouchInput::MULTITOUCH_START;
6873 addToEvent = true;
6875 if (pInputs[i].dwFlags & TOUCHEVENTF_UP) {
6876 // Pres shell expects removed contacts points to be delivered in a
6877 // separate eTouchEnd event containing only the contact points that were
6878 // removed.
6879 if (touchEndInput.mTimeStamp.IsNull()) {
6880 // Initialize a touch event to send.
6881 touchEndInput.mType = MultiTouchInput::MULTITOUCH_END;
6882 touchEndInput.mTimeStamp = GetMessageTimeStamp(::GetMessageTime());
6883 ModifierKeyState modifierKeyState;
6884 touchEndInput.modifiers = modifierKeyState.GetModifiers();
6886 addToEndEvent = true;
6888 if (!addToEvent && !addToEndEvent) {
6889 // Filter out spurious Windows events we don't understand, like palm
6890 // contact.
6891 continue;
6894 // Setup the touch point we'll append to the touch event array.
6895 nsPointWin touchPoint;
6896 touchPoint.x = TOUCH_COORD_TO_PIXEL(pInputs[i].x);
6897 touchPoint.y = TOUCH_COORD_TO_PIXEL(pInputs[i].y);
6898 touchPoint.ScreenToClient(mWnd);
6900 // Initialize the touch data.
6901 SingleTouchData touchData(
6902 pInputs[i].dwID, // aIdentifier
6903 ScreenIntPoint::FromUnknownPoint(touchPoint), // aScreenPoint
6904 // The contact area info cannot be trusted even when
6905 // TOUCHINPUTMASKF_CONTACTAREA is set when the input source is pen,
6906 // which somehow violates the API docs. (bug 1710509) Ultimately the
6907 // dwFlags check will become redundant since we want to migrate to
6908 // WM_POINTER for pens. (bug 1707075)
6909 (pInputs[i].dwMask & TOUCHINPUTMASKF_CONTACTAREA) &&
6910 !(pInputs[i].dwFlags & TOUCHEVENTF_PEN)
6911 ? ScreenSize(TOUCH_COORD_TO_PIXEL(pInputs[i].cxContact) / 2,
6912 TOUCH_COORD_TO_PIXEL(pInputs[i].cyContact) / 2)
6913 : ScreenSize(1, 1), // aRadius
6914 0.0f, // aRotationAngle
6915 0.0f); // aForce
6917 // Append touch data to the appropriate event.
6918 if (addToEvent) {
6919 touchInput.mTouches.AppendElement(touchData);
6921 if (addToEndEvent) {
6922 touchEndInput.mTouches.AppendElement(touchData);
6926 // Dispatch touch start and touch move event if we have one.
6927 if (!touchInput.mTimeStamp.IsNull()) {
6928 DispatchTouchOrPanGestureInput(touchInput, pInputs);
6930 // Dispatch touch end event if we have one.
6931 if (!touchEndInput.mTimeStamp.IsNull()) {
6932 DispatchTouchOrPanGestureInput(touchEndInput, pInputs);
6936 delete[] pInputs;
6937 CloseTouchInputHandle((HTOUCHINPUT)lParam);
6938 return true;
6941 // Gesture event processing. Handles WM_GESTURE events.
6942 bool nsWindow::OnGesture(WPARAM wParam, LPARAM lParam) {
6943 // Treatment for pan events which translate into scroll events:
6944 if (mGesture.IsPanEvent(lParam)) {
6945 if (!mGesture.ProcessPanMessage(mWnd, wParam, lParam))
6946 return false; // ignore
6948 nsEventStatus status;
6950 WidgetWheelEvent wheelEvent(true, eWheel, this);
6952 ModifierKeyState modifierKeyState;
6953 modifierKeyState.InitInputEvent(wheelEvent);
6955 wheelEvent.mButton = 0;
6956 wheelEvent.mTimeStamp = GetMessageTimeStamp(::GetMessageTime());
6957 wheelEvent.mInputSource = MouseEvent_Binding::MOZ_SOURCE_TOUCH;
6959 bool endFeedback = true;
6961 if (mGesture.PanDeltaToPixelScroll(wheelEvent)) {
6962 DispatchEvent(&wheelEvent, status);
6965 if (mDisplayPanFeedback) {
6966 mGesture.UpdatePanFeedbackX(
6967 mWnd, DeprecatedAbs(RoundDown(wheelEvent.mOverflowDeltaX)),
6968 endFeedback);
6969 mGesture.UpdatePanFeedbackY(
6970 mWnd, DeprecatedAbs(RoundDown(wheelEvent.mOverflowDeltaY)),
6971 endFeedback);
6972 mGesture.PanFeedbackFinalize(mWnd, endFeedback);
6975 CloseGestureInfoHandle((HGESTUREINFO)lParam);
6977 return true;
6980 // Other gestures translate into simple gesture events:
6981 WidgetSimpleGestureEvent event(true, eVoidEvent, this);
6982 if (!mGesture.ProcessGestureMessage(mWnd, wParam, lParam, event)) {
6983 return false; // fall through to DefWndProc
6986 // Polish up and send off the new event
6987 ModifierKeyState modifierKeyState;
6988 modifierKeyState.InitInputEvent(event);
6989 event.mButton = 0;
6990 event.mTimeStamp = GetMessageTimeStamp(::GetMessageTime());
6991 event.mInputSource = MouseEvent_Binding::MOZ_SOURCE_TOUCH;
6993 nsEventStatus status;
6994 DispatchEvent(&event, status);
6995 if (status == nsEventStatus_eIgnore) {
6996 return false; // Ignored, fall through
6999 // Only close this if we process and return true.
7000 CloseGestureInfoHandle((HGESTUREINFO)lParam);
7002 return true; // Handled
7005 // WM_DESTROY event handler
7006 void nsWindow::OnDestroy() {
7007 mOnDestroyCalled = true;
7009 // If this is a toplevel window, notify the taskbar concealer to clean up any
7010 // relevant state.
7011 if (!mParent) {
7012 TaskbarConcealer::OnWindowDestroyed(mWnd);
7015 // Make sure we don't get destroyed in the process of tearing down.
7016 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
7018 // Dispatch the destroy notification.
7019 if (!mInDtor) NotifyWindowDestroyed();
7021 // Prevent the widget from sending additional events.
7022 mWidgetListener = nullptr;
7023 mAttachedWidgetListener = nullptr;
7025 DestroyDirectManipulation();
7027 if (mWnd == mLastKillFocusWindow) {
7028 mLastKillFocusWindow = nullptr;
7030 // Unregister notifications from terminal services
7031 ::WTSUnRegisterSessionNotification(mWnd);
7033 // We will stop receiving native events after dissociating from our native
7034 // window. We will also disappear from the output of WinUtils::GetNSWindowPtr
7035 // for that window.
7036 DissociateFromNativeWindow();
7038 // Once mWidgetListener is cleared and the subclass is reset, sCurrentWindow
7039 // can be cleared. (It's used in tracking windows for mouse events.)
7040 if (sCurrentWindow == this) sCurrentWindow = nullptr;
7042 // Disconnects us from our parent, will call our GetParent().
7043 nsBaseWidget::Destroy();
7045 // Release references to children, device context, toolkit, and app shell.
7046 nsBaseWidget::OnDestroy();
7048 // Clear our native parent handle.
7049 // XXX Windows will take care of this in the proper order, and
7050 // SetParent(nullptr)'s remove child on the parent already took place in
7051 // nsBaseWidget's Destroy call above.
7052 // SetParent(nullptr);
7053 mParent = nullptr;
7055 // We have to destroy the native drag target before we null out our window
7056 // pointer.
7057 EnableDragDrop(false);
7059 // If we're going away and for some reason we're still the rollup widget,
7060 // rollup and turn off capture.
7061 nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener();
7062 nsCOMPtr<nsIWidget> rollupWidget;
7063 if (rollupListener) {
7064 rollupWidget = rollupListener->GetRollupWidget();
7066 if (this == rollupWidget) {
7067 rollupListener->Rollup({});
7068 CaptureRollupEvents(false);
7071 IMEHandler::OnDestroyWindow(this);
7073 // Free GDI window class objects
7074 if (mBrush) {
7075 VERIFY(::DeleteObject(mBrush));
7076 mBrush = nullptr;
7079 // Destroy any custom cursor resources.
7080 if (mCursor.IsCustom()) {
7081 SetCursor(Cursor{eCursor_standard});
7084 if (mCompositorWidgetDelegate) {
7085 mCompositorWidgetDelegate->OnDestroyWindow();
7087 mBasicLayersSurface = nullptr;
7089 // Finalize panning feedback to possibly restore window displacement
7090 mGesture.PanFeedbackFinalize(mWnd, true);
7092 // Clear the main HWND.
7093 mWnd = nullptr;
7096 // Send a resize message to the listener
7097 bool nsWindow::OnResize(const LayoutDeviceIntSize& aSize) {
7098 if (mCompositorWidgetDelegate &&
7099 !mCompositorWidgetDelegate->OnWindowResize(aSize)) {
7100 return false;
7103 bool result = false;
7104 if (mWidgetListener) {
7105 result = mWidgetListener->WindowResized(this, aSize.width, aSize.height);
7108 // If there is an attached view, inform it as well as the normal widget
7109 // listener.
7110 if (mAttachedWidgetListener) {
7111 return mAttachedWidgetListener->WindowResized(this, aSize.width,
7112 aSize.height);
7115 return result;
7118 void nsWindow::OnSizeModeChange() {
7119 const nsSizeMode mode = mFrameState->GetSizeMode();
7121 MOZ_LOG(gWindowsLog, LogLevel::Info,
7122 ("nsWindow::OnSizeModeChange() sizeMode %d", mode));
7124 if (NeedsToTrackWindowOcclusionState()) {
7125 WinWindowOcclusionTracker::Get()->OnWindowVisibilityChanged(
7126 this, mode != nsSizeMode_Minimized);
7128 wr::DebugFlags flags{0};
7129 flags._0 = gfx::gfxVars::WebRenderDebugFlags();
7130 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
7131 if (debugEnabled && mCompositorWidgetDelegate) {
7132 mCompositorWidgetDelegate->NotifyVisibilityUpdated(mode,
7133 mIsFullyOccluded);
7137 if (mCompositorWidgetDelegate) {
7138 mCompositorWidgetDelegate->OnWindowModeChange(mode);
7141 if (mWidgetListener) {
7142 mWidgetListener->SizeModeChanged(mode);
7146 bool nsWindow::OnHotKey(WPARAM wParam, LPARAM lParam) { return true; }
7148 bool nsWindow::IsPopup() { return mWindowType == WindowType::Popup; }
7150 bool nsWindow::ShouldUseOffMainThreadCompositing() {
7151 if (mWindowType == WindowType::Popup && mPopupType == PopupType::Tooltip) {
7152 return false;
7155 // Content rendering of popup is always done by child window.
7156 // See nsDocumentViewer::ShouldAttachToTopLevel().
7157 if (mWindowType == WindowType::Popup && !mIsChildWindow) {
7158 MOZ_ASSERT(!mParent);
7159 return false;
7162 return nsBaseWidget::ShouldUseOffMainThreadCompositing();
7165 void nsWindow::WindowUsesOMTC() {
7166 ULONG_PTR style = ::GetClassLongPtr(mWnd, GCL_STYLE);
7167 if (!style) {
7168 NS_WARNING("Could not get window class style");
7169 return;
7171 style |= CS_HREDRAW | CS_VREDRAW;
7172 DebugOnly<ULONG_PTR> result = ::SetClassLongPtr(mWnd, GCL_STYLE, style);
7173 NS_WARNING_ASSERTION(result, "Could not reset window class style");
7176 void nsWindow::OnDPIChanged(int32_t x, int32_t y, int32_t width,
7177 int32_t height) {
7178 // Don't try to handle WM_DPICHANGED for popup windows (see bug 1239353);
7179 // they remain tied to their original parent's resolution.
7180 if (mWindowType == WindowType::Popup) {
7181 return;
7183 if (StaticPrefs::layout_css_devPixelsPerPx() > 0.0) {
7184 return;
7186 mDefaultScale = -1.0; // force recomputation of scale factor
7188 if (mResizeState != RESIZING &&
7189 mFrameState->GetSizeMode() == nsSizeMode_Normal) {
7190 // Limit the position (if not in the middle of a drag-move) & size,
7191 // if it would overflow the destination screen
7192 nsCOMPtr<nsIScreenManager> sm = do_GetService(sScreenManagerContractID);
7193 if (sm) {
7194 nsCOMPtr<nsIScreen> screen;
7195 sm->ScreenForRect(x, y, width, height, getter_AddRefs(screen));
7196 if (screen) {
7197 int32_t availLeft, availTop, availWidth, availHeight;
7198 screen->GetAvailRect(&availLeft, &availTop, &availWidth, &availHeight);
7199 if (mResizeState != MOVING) {
7200 x = std::max(x, availLeft);
7201 y = std::max(y, availTop);
7203 width = std::min(width, availWidth);
7204 height = std::min(height, availHeight);
7208 Resize(x, y, width, height, true);
7210 UpdateNonClientMargins();
7211 ChangedDPI();
7212 ResetLayout();
7215 // Callback to generate OnCloakChanged pseudo-events.
7216 /* static */
7217 void nsWindow::OnCloakEvent(HWND aWnd, bool aCloaked) {
7218 MOZ_ASSERT(NS_IsMainThread());
7220 const char* const kEventName = aCloaked ? "CLOAKED" : "UNCLOAKED";
7221 nsWindow* pWin = WinUtils::GetNSWindowPtr(aWnd);
7222 if (!pWin) {
7223 MOZ_LOG(
7224 sCloakingLog, LogLevel::Debug,
7225 ("Received %s event for HWND %p (not an nsWindow)", kEventName, aWnd));
7226 return;
7229 const char* const kWasCloakedStr = pWin->mIsCloaked ? "cloaked" : "uncloaked";
7230 if (mozilla::IsCloaked(aWnd) == pWin->mIsCloaked) {
7231 MOZ_LOG(sCloakingLog, LogLevel::Debug,
7232 ("Received redundant %s event for %s HWND %p; discarding",
7233 kEventName, kWasCloakedStr, aWnd));
7234 return;
7237 MOZ_LOG(
7238 sCloakingLog, LogLevel::Info,
7239 ("Received %s event for %s HWND %p", kEventName, kWasCloakedStr, aWnd));
7241 // Cloaking events like the one we've just received are sent asynchronously.
7242 // Rather than process them one-by-one, we jump the gun a bit and perform
7243 // updates on all newly cloaked/uncloaked nsWindows at once. This also lets us
7244 // batch operations that consider more than one window's state.
7245 struct Item {
7246 nsWindow* win;
7247 bool nowCloaked;
7249 nsTArray<Item> changedWindows;
7251 mozilla::EnumerateThreadWindows([&](HWND hwnd) {
7252 nsWindow* pWin = WinUtils::GetNSWindowPtr(hwnd);
7253 if (!pWin) {
7254 return;
7257 const bool isCloaked = mozilla::IsCloaked(hwnd);
7258 if (isCloaked != pWin->mIsCloaked) {
7259 changedWindows.AppendElement(Item{pWin, isCloaked});
7263 if (changedWindows.IsEmpty()) {
7264 return;
7267 for (const Item& item : changedWindows) {
7268 item.win->OnCloakChanged(item.nowCloaked);
7271 nsWindow::TaskbarConcealer::OnCloakChanged();
7274 void nsWindow::OnCloakChanged(bool aCloaked) {
7275 MOZ_LOG(sCloakingLog, LogLevel::Info,
7276 ("Calling OnCloakChanged(): HWND %p, aCloaked %s", mWnd,
7277 aCloaked ? "true" : "false"));
7278 mIsCloaked = aCloaked;
7281 /**************************************************************
7282 **************************************************************
7284 ** BLOCK: IME management and accessibility
7286 ** Handles managing IME input and accessibility.
7288 **************************************************************
7289 **************************************************************/
7291 void nsWindow::SetInputContext(const InputContext& aContext,
7292 const InputContextAction& aAction) {
7293 InputContext newInputContext = aContext;
7294 IMEHandler::SetInputContext(this, newInputContext, aAction);
7295 mInputContext = newInputContext;
7298 InputContext nsWindow::GetInputContext() {
7299 mInputContext.mIMEState.mOpen = IMEState::CLOSED;
7300 if (WinUtils::IsIMEEnabled(mInputContext) && IMEHandler::GetOpenState(this)) {
7301 mInputContext.mIMEState.mOpen = IMEState::OPEN;
7302 } else {
7303 mInputContext.mIMEState.mOpen = IMEState::CLOSED;
7305 return mInputContext;
7308 TextEventDispatcherListener* nsWindow::GetNativeTextEventDispatcherListener() {
7309 return IMEHandler::GetNativeTextEventDispatcherListener();
7312 #ifdef ACCESSIBILITY
7313 # ifdef DEBUG
7314 # define NS_LOG_WMGETOBJECT(aWnd, aHwnd, aAcc) \
7315 if (a11y::logging::IsEnabled(a11y::logging::ePlatforms)) { \
7316 printf( \
7317 "Get the window:\n {\n HWND: %p, parent HWND: %p, wndobj: " \
7318 "%p,\n", \
7319 aHwnd, ::GetParent(aHwnd), aWnd); \
7320 printf(" acc: %p", aAcc); \
7321 if (aAcc) { \
7322 nsAutoString name; \
7323 aAcc->Name(name); \
7324 printf(", accname: %s", NS_ConvertUTF16toUTF8(name).get()); \
7326 printf("\n }\n"); \
7329 # else
7330 # define NS_LOG_WMGETOBJECT(aWnd, aHwnd, aAcc)
7331 # endif
7333 a11y::LocalAccessible* nsWindow::GetAccessible() {
7334 // If the pref was ePlatformIsDisabled, return null here, disabling a11y.
7335 if (a11y::PlatformDisabledState() == a11y::ePlatformIsDisabled)
7336 return nullptr;
7338 if (mInDtor || mOnDestroyCalled || mWindowType == WindowType::Invisible) {
7339 return nullptr;
7342 // In case of popup window return a popup accessible.
7343 nsView* view = nsView::GetViewFor(this);
7344 if (view) {
7345 nsIFrame* frame = view->GetFrame();
7346 if (frame && nsLayoutUtils::IsPopup(frame)) {
7347 nsAccessibilityService* accService = GetOrCreateAccService();
7348 if (accService) {
7349 a11y::DocAccessible* docAcc =
7350 GetAccService()->GetDocAccessible(frame->PresShell());
7351 if (docAcc) {
7352 NS_LOG_WMGETOBJECT(
7353 this, mWnd,
7354 docAcc->GetAccessibleOrDescendant(frame->GetContent()));
7355 return docAcc->GetAccessibleOrDescendant(frame->GetContent());
7361 // otherwise root document accessible.
7362 NS_LOG_WMGETOBJECT(this, mWnd, GetRootAccessible());
7363 return GetRootAccessible();
7365 #endif
7367 /**************************************************************
7368 **************************************************************
7370 ** BLOCK: Transparency
7372 ** Window transparency helpers.
7374 **************************************************************
7375 **************************************************************/
7377 void nsWindow::SetWindowTranslucencyInner(TransparencyMode aMode) {
7378 if (aMode == mTransparencyMode) {
7379 return;
7382 // stop on dialogs and popups!
7383 HWND hWnd = WinUtils::GetTopLevelHWND(mWnd, true);
7384 nsWindow* parent = WinUtils::GetNSWindowPtr(hWnd);
7386 if (!parent) {
7387 NS_WARNING("Trying to use transparent chrome in an embedded context");
7388 return;
7391 if (parent != this) {
7392 NS_WARNING(
7393 "Setting SetWindowTranslucencyInner on a parent this is not us!");
7396 LONG_PTR style = ::GetWindowLongPtrW(hWnd, GWL_STYLE),
7397 exStyle = ::GetWindowLongPtr(hWnd, GWL_EXSTYLE);
7399 if (parent->mIsVisible) {
7400 style |= WS_VISIBLE;
7401 if (parent->mFrameState->GetSizeMode() == nsSizeMode_Maximized) {
7402 style |= WS_MAXIMIZE;
7403 } else if (parent->mFrameState->GetSizeMode() == nsSizeMode_Minimized) {
7404 style |= WS_MINIMIZE;
7408 if (aMode == TransparencyMode::Transparent) {
7409 exStyle |= WS_EX_LAYERED;
7410 } else {
7411 exStyle &= ~WS_EX_LAYERED;
7414 VERIFY_WINDOW_STYLE(style);
7415 ::SetWindowLongPtrW(hWnd, GWL_STYLE, style);
7416 ::SetWindowLongPtrW(hWnd, GWL_EXSTYLE, exStyle);
7418 mTransparencyMode = aMode;
7420 if (mCompositorWidgetDelegate) {
7421 mCompositorWidgetDelegate->UpdateTransparency(aMode);
7425 /**************************************************************
7426 **************************************************************
7428 ** BLOCK: Popup rollup hooks
7430 ** Deals with CaptureRollup on popup windows.
7432 **************************************************************
7433 **************************************************************/
7435 // Schedules a timer for a window, so we can rollup after processing the hook
7436 // event
7437 void nsWindow::ScheduleHookTimer(HWND aWnd, UINT aMsgId) {
7438 // In some cases multiple hooks may be scheduled
7439 // so ignore any other requests once one timer is scheduled
7440 if (sHookTimerId == 0) {
7441 // Remember the window handle and the message ID to be used later
7442 sRollupMsgId = aMsgId;
7443 sRollupMsgWnd = aWnd;
7444 // Schedule native timer for doing the rollup after
7445 // this event is done being processed
7446 sHookTimerId = ::SetTimer(nullptr, 0, 0, (TIMERPROC)HookTimerForPopups);
7447 NS_ASSERTION(sHookTimerId, "Timer couldn't be created.");
7451 #ifdef POPUP_ROLLUP_DEBUG_OUTPUT
7452 int gLastMsgCode = 0;
7453 extern MSGFEventMsgInfo gMSGFEvents[];
7454 #endif
7456 // Process Menu messages, rollup when popup is clicked.
7457 LRESULT CALLBACK nsWindow::MozSpecialMsgFilter(int code, WPARAM wParam,
7458 LPARAM lParam) {
7459 #ifdef POPUP_ROLLUP_DEBUG_OUTPUT
7460 if (sProcessHook) {
7461 MSG* pMsg = (MSG*)lParam;
7463 int inx = 0;
7464 while (gMSGFEvents[inx].mId != code && gMSGFEvents[inx].mStr != nullptr) {
7465 inx++;
7467 if (code != gLastMsgCode) {
7468 if (gMSGFEvents[inx].mId == code) {
7469 # ifdef DEBUG
7470 MOZ_LOG(gWindowsLog, LogLevel::Info,
7471 ("MozSpecialMessageProc - code: 0x%X - %s hw: %p\n", code,
7472 gMSGFEvents[inx].mStr, pMsg->hwnd));
7473 # endif
7474 } else {
7475 # ifdef DEBUG
7476 MOZ_LOG(gWindowsLog, LogLevel::Info,
7477 ("MozSpecialMessageProc - code: 0x%X - %d hw: %p\n", code,
7478 gMSGFEvents[inx].mId, pMsg->hwnd));
7479 # endif
7481 gLastMsgCode = code;
7483 PrintEvent(pMsg->message, FALSE, FALSE);
7485 #endif // #ifdef POPUP_ROLLUP_DEBUG_OUTPUT
7487 if (sProcessHook && code == MSGF_MENU) {
7488 MSG* pMsg = (MSG*)lParam;
7489 ScheduleHookTimer(pMsg->hwnd, pMsg->message);
7492 return ::CallNextHookEx(sMsgFilterHook, code, wParam, lParam);
7495 // Process all mouse messages. Roll up when a click is in a native window
7496 // that doesn't have an nsIWidget.
7497 LRESULT CALLBACK nsWindow::MozSpecialMouseProc(int code, WPARAM wParam,
7498 LPARAM lParam) {
7499 if (sProcessHook) {
7500 switch (WinUtils::GetNativeMessage(wParam)) {
7501 case WM_LBUTTONDOWN:
7502 case WM_RBUTTONDOWN:
7503 case WM_MBUTTONDOWN:
7504 case WM_MOUSEWHEEL:
7505 case WM_MOUSEHWHEEL: {
7506 MOUSEHOOKSTRUCT* ms = (MOUSEHOOKSTRUCT*)lParam;
7507 nsIWidget* mozWin = WinUtils::GetNSWindowPtr(ms->hwnd);
7508 if (!mozWin) {
7509 ScheduleHookTimer(ms->hwnd, (UINT)wParam);
7511 break;
7515 return ::CallNextHookEx(sCallMouseHook, code, wParam, lParam);
7518 // Process all messages. Roll up when the window is moving, or
7519 // is resizing or when maximized or mininized.
7520 LRESULT CALLBACK nsWindow::MozSpecialWndProc(int code, WPARAM wParam,
7521 LPARAM lParam) {
7522 #ifdef POPUP_ROLLUP_DEBUG_OUTPUT
7523 if (sProcessHook) {
7524 CWPSTRUCT* cwpt = (CWPSTRUCT*)lParam;
7525 PrintEvent(cwpt->message, FALSE, FALSE);
7527 #endif
7529 if (sProcessHook) {
7530 CWPSTRUCT* cwpt = (CWPSTRUCT*)lParam;
7531 if (cwpt->message == WM_MOVING || cwpt->message == WM_SIZING ||
7532 cwpt->message == WM_GETMINMAXINFO) {
7533 ScheduleHookTimer(cwpt->hwnd, (UINT)cwpt->message);
7537 return ::CallNextHookEx(sCallProcHook, code, wParam, lParam);
7540 // Register the special "hooks" for dropdown processing.
7541 void nsWindow::RegisterSpecialDropdownHooks() {
7542 NS_ASSERTION(!sMsgFilterHook, "sMsgFilterHook must be NULL!");
7543 NS_ASSERTION(!sCallProcHook, "sCallProcHook must be NULL!");
7545 DISPLAY_NMM_PRT("***************** Installing Msg Hooks ***************\n");
7547 // Install msg hook for moving the window and resizing
7548 if (!sMsgFilterHook) {
7549 DISPLAY_NMM_PRT("***** Hooking sMsgFilterHook!\n");
7550 sMsgFilterHook = SetWindowsHookEx(WH_MSGFILTER, MozSpecialMsgFilter,
7551 nullptr, GetCurrentThreadId());
7552 #ifdef POPUP_ROLLUP_DEBUG_OUTPUT
7553 if (!sMsgFilterHook) {
7554 MOZ_LOG(gWindowsLog, LogLevel::Info,
7555 ("***** SetWindowsHookEx is NOT installed for WH_MSGFILTER!\n"));
7557 #endif
7560 // Install msg hook for menus
7561 if (!sCallProcHook) {
7562 DISPLAY_NMM_PRT("***** Hooking sCallProcHook!\n");
7563 sCallProcHook = SetWindowsHookEx(WH_CALLWNDPROC, MozSpecialWndProc, nullptr,
7564 GetCurrentThreadId());
7565 #ifdef POPUP_ROLLUP_DEBUG_OUTPUT
7566 if (!sCallProcHook) {
7567 MOZ_LOG(
7568 gWindowsLog, LogLevel::Info,
7569 ("***** SetWindowsHookEx is NOT installed for WH_CALLWNDPROC!\n"));
7571 #endif
7574 // Install msg hook for the mouse
7575 if (!sCallMouseHook) {
7576 DISPLAY_NMM_PRT("***** Hooking sCallMouseHook!\n");
7577 sCallMouseHook = SetWindowsHookEx(WH_MOUSE, MozSpecialMouseProc, nullptr,
7578 GetCurrentThreadId());
7579 #ifdef POPUP_ROLLUP_DEBUG_OUTPUT
7580 if (!sCallMouseHook) {
7581 MOZ_LOG(gWindowsLog, LogLevel::Info,
7582 ("***** SetWindowsHookEx is NOT installed for WH_MOUSE!\n"));
7584 #endif
7588 // Unhook special message hooks for dropdowns.
7589 void nsWindow::UnregisterSpecialDropdownHooks() {
7590 DISPLAY_NMM_PRT(
7591 "***************** De-installing Msg Hooks ***************\n");
7593 if (sCallProcHook) {
7594 DISPLAY_NMM_PRT("***** Unhooking sCallProcHook!\n");
7595 if (!::UnhookWindowsHookEx(sCallProcHook)) {
7596 DISPLAY_NMM_PRT("***** UnhookWindowsHookEx failed for sCallProcHook!\n");
7598 sCallProcHook = nullptr;
7601 if (sMsgFilterHook) {
7602 DISPLAY_NMM_PRT("***** Unhooking sMsgFilterHook!\n");
7603 if (!::UnhookWindowsHookEx(sMsgFilterHook)) {
7604 DISPLAY_NMM_PRT("***** UnhookWindowsHookEx failed for sMsgFilterHook!\n");
7606 sMsgFilterHook = nullptr;
7609 if (sCallMouseHook) {
7610 DISPLAY_NMM_PRT("***** Unhooking sCallMouseHook!\n");
7611 if (!::UnhookWindowsHookEx(sCallMouseHook)) {
7612 DISPLAY_NMM_PRT("***** UnhookWindowsHookEx failed for sCallMouseHook!\n");
7614 sCallMouseHook = nullptr;
7618 // This timer is designed to only fire one time at most each time a "hook"
7619 // function is used to rollup the dropdown. In some cases, the timer may be
7620 // scheduled from the hook, but that hook event or a subsequent event may roll
7621 // up the dropdown before this timer function is executed.
7623 // For example, if an MFC control takes focus, the combobox will lose focus and
7624 // rollup before this function fires.
7625 VOID CALLBACK nsWindow::HookTimerForPopups(HWND hwnd, UINT uMsg, UINT idEvent,
7626 DWORD dwTime) {
7627 if (sHookTimerId != 0) {
7628 // if the window is nullptr then we need to use the ID to kill the timer
7629 DebugOnly<BOOL> status = ::KillTimer(nullptr, sHookTimerId);
7630 NS_ASSERTION(status, "Hook Timer was not killed.");
7631 sHookTimerId = 0;
7634 if (sRollupMsgId != 0) {
7635 // Note: DealWithPopups does the check to make sure that the rollup widget
7636 // is set.
7637 LRESULT popupHandlingResult;
7638 nsAutoRollup autoRollup;
7639 DealWithPopups(sRollupMsgWnd, sRollupMsgId, 0, 0, &popupHandlingResult);
7640 sRollupMsgId = 0;
7641 sRollupMsgWnd = nullptr;
7645 static bool IsDifferentThreadWindow(HWND aWnd) {
7646 return ::GetCurrentThreadId() != ::GetWindowThreadProcessId(aWnd, nullptr);
7649 // static
7650 bool nsWindow::EventIsInsideWindow(nsWindow* aWindow,
7651 Maybe<POINT> aEventPoint) {
7652 RECT r;
7653 ::GetWindowRect(aWindow->mWnd, &r);
7654 POINT mp;
7655 if (aEventPoint) {
7656 mp = *aEventPoint;
7657 } else {
7658 DWORD pos = ::GetMessagePos();
7659 mp.x = GET_X_LPARAM(pos);
7660 mp.y = GET_Y_LPARAM(pos);
7663 auto margin = aWindow->mInputRegion.mMargin;
7664 if (margin > 0) {
7665 r.top += margin;
7666 r.bottom -= margin;
7667 r.left += margin;
7668 r.right -= margin;
7671 // was the event inside this window?
7672 return static_cast<bool>(::PtInRect(&r, mp));
7675 // static
7676 bool nsWindow::GetPopupsToRollup(nsIRollupListener* aRollupListener,
7677 uint32_t* aPopupsToRollup,
7678 Maybe<POINT> aEventPoint) {
7679 // If we're dealing with menus, we probably have submenus and we don't want
7680 // to rollup some of them if the click is in a parent menu of the current
7681 // submenu.
7682 *aPopupsToRollup = UINT32_MAX;
7683 AutoTArray<nsIWidget*, 5> widgetChain;
7684 uint32_t sameTypeCount = aRollupListener->GetSubmenuWidgetChain(&widgetChain);
7685 for (uint32_t i = 0; i < widgetChain.Length(); ++i) {
7686 nsIWidget* widget = widgetChain[i];
7687 if (EventIsInsideWindow(static_cast<nsWindow*>(widget), aEventPoint)) {
7688 // Don't roll up if the mouse event occurred within a menu of the
7689 // same type. If the mouse event occurred in a menu higher than that,
7690 // roll up, but pass the number of popups to Rollup so that only those
7691 // of the same type close up.
7692 if (i < sameTypeCount) {
7693 return false;
7696 *aPopupsToRollup = sameTypeCount;
7697 break;
7700 return true;
7703 // static
7704 bool nsWindow::NeedsToHandleNCActivateDelayed(HWND aWnd) {
7705 // While popup is open, popup window might be activated by other application.
7706 // At this time, we need to take back focus to the previous window but it
7707 // causes flickering its nonclient area because WM_NCACTIVATE comes before
7708 // WM_ACTIVATE and we cannot know which window will take focus at receiving
7709 // WM_NCACTIVATE. Therefore, we need a hack for preventing the flickerling.
7711 // If non-popup window receives WM_NCACTIVATE at deactivating, default
7712 // wndproc shouldn't handle it as deactivating. Instead, at receiving
7713 // WM_ACTIVIATE after that, WM_NCACTIVATE should be sent again manually.
7714 // This returns true if the window needs to handle WM_NCACTIVATE later.
7716 nsWindow* window = WinUtils::GetNSWindowPtr(aWnd);
7717 return window && !window->IsPopup();
7720 static bool IsTouchSupportEnabled(HWND aWnd) {
7721 nsWindow* topWindow =
7722 WinUtils::GetNSWindowPtr(WinUtils::GetTopLevelHWND(aWnd, true));
7723 return topWindow ? topWindow->IsTouchWindow() : false;
7726 static Maybe<POINT> GetSingleTouch(WPARAM wParam, LPARAM lParam) {
7727 Maybe<POINT> ret;
7728 uint32_t cInputs = LOWORD(wParam);
7729 if (cInputs != 1) {
7730 return ret;
7732 TOUCHINPUT input;
7733 if (GetTouchInputInfo((HTOUCHINPUT)lParam, cInputs, &input,
7734 sizeof(TOUCHINPUT))) {
7735 ret.emplace();
7736 ret->x = TOUCH_COORD_TO_PIXEL(input.x);
7737 ret->y = TOUCH_COORD_TO_PIXEL(input.y);
7739 // Note that we don't call CloseTouchInputHandle here because we need
7740 // to read the touch input info again in OnTouch later.
7741 return ret;
7744 // static
7745 bool nsWindow::DealWithPopups(HWND aWnd, UINT aMessage, WPARAM aWParam,
7746 LPARAM aLParam, LRESULT* aResult) {
7747 NS_ASSERTION(aResult, "Bad outResult");
7749 // XXX Why do we use the return value of WM_MOUSEACTIVATE for all messages?
7750 *aResult = MA_NOACTIVATE;
7752 if (!::IsWindowVisible(aWnd)) {
7753 return false;
7756 if (MOZ_UNLIKELY(aMessage == WM_KILLFOCUS)) {
7757 // NOTE: We deal with this here rather than on the switch below because we
7758 // want to do this even if there are no menus to rollup (tooltips don't set
7759 // the rollup listener etc).
7760 if (RefPtr pm = nsXULPopupManager::GetInstance()) {
7761 pm->RollupTooltips();
7765 nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener();
7766 NS_ENSURE_TRUE(rollupListener, false);
7768 nsCOMPtr<nsIWidget> popup = rollupListener->GetRollupWidget();
7769 if (!popup) {
7770 return false;
7773 static bool sSendingNCACTIVATE = false;
7774 static bool sPendingNCACTIVATE = false;
7775 uint32_t popupsToRollup = UINT32_MAX;
7777 bool consumeRollupEvent = false;
7778 Maybe<POINT> touchPoint; // In screen coords.
7780 // If we rollup with animations but get occluded right away, we might not
7781 // advance the refresh driver enough for the animation to finish.
7782 auto allowAnimations = nsIRollupListener::AllowAnimations::Yes;
7783 nsWindow* popupWindow = static_cast<nsWindow*>(popup.get());
7784 UINT nativeMessage = WinUtils::GetNativeMessage(aMessage);
7785 switch (nativeMessage) {
7786 case WM_TOUCH:
7787 if (!IsTouchSupportEnabled(aWnd)) {
7788 // If APZ is disabled, don't allow touch inputs to dismiss popups. The
7789 // compatibility mouse events will do it instead.
7790 return false;
7792 touchPoint = GetSingleTouch(aWParam, aLParam);
7793 if (!touchPoint) {
7794 return false;
7796 [[fallthrough]];
7797 case WM_LBUTTONDOWN:
7798 case WM_RBUTTONDOWN:
7799 case WM_MBUTTONDOWN:
7800 case WM_NCLBUTTONDOWN:
7801 case WM_NCRBUTTONDOWN:
7802 case WM_NCMBUTTONDOWN:
7803 if (nativeMessage != WM_TOUCH && IsTouchSupportEnabled(aWnd) &&
7804 MOUSE_INPUT_SOURCE() == MouseEvent_Binding::MOZ_SOURCE_TOUCH) {
7805 // If any of these mouse events are really compatibility events that
7806 // Windows is sending for touch inputs, then don't allow them to dismiss
7807 // popups when APZ is enabled (instead we do the dismissing as part of
7808 // WM_TOUCH handling which is more correct).
7809 // If we don't do this, then when the user lifts their finger after a
7810 // long-press, the WM_RBUTTONDOWN compatibility event that Windows sends
7811 // us will dismiss the contextmenu popup that we displayed as part of
7812 // handling the long-tap-up.
7813 return false;
7815 if (!EventIsInsideWindow(popupWindow, touchPoint) &&
7816 GetPopupsToRollup(rollupListener, &popupsToRollup, touchPoint)) {
7817 break;
7819 return false;
7820 case WM_POINTERDOWN: {
7821 WinPointerEvents pointerEvents;
7822 if (!pointerEvents.ShouldRollupOnPointerEvent(nativeMessage, aWParam)) {
7823 return false;
7825 POINT pt;
7826 pt.x = GET_X_LPARAM(aLParam);
7827 pt.y = GET_Y_LPARAM(aLParam);
7828 if (!GetPopupsToRollup(rollupListener, &popupsToRollup, Some(pt))) {
7829 return false;
7831 if (EventIsInsideWindow(popupWindow, Some(pt))) {
7832 // Don't roll up if the event is inside the popup window.
7833 return false;
7835 } break;
7836 case MOZ_WM_DMANIP: {
7837 POINT pt;
7838 ::GetCursorPos(&pt);
7839 if (!GetPopupsToRollup(rollupListener, &popupsToRollup, Some(pt))) {
7840 return false;
7842 if (EventIsInsideWindow(popupWindow, Some(pt))) {
7843 // Don't roll up if the event is inside the popup window
7844 return false;
7846 } break;
7847 case WM_MOUSEWHEEL:
7848 case WM_MOUSEHWHEEL:
7849 // We need to check if the popup thinks that it should cause closing
7850 // itself when mouse wheel events are fired outside the rollup widget.
7851 if (!EventIsInsideWindow(popupWindow)) {
7852 // Check if we should consume this event even if we don't roll-up:
7853 consumeRollupEvent = rollupListener->ShouldConsumeOnMouseWheelEvent();
7854 *aResult = MA_ACTIVATE;
7855 if (rollupListener->ShouldRollupOnMouseWheelEvent() &&
7856 GetPopupsToRollup(rollupListener, &popupsToRollup)) {
7857 break;
7860 return consumeRollupEvent;
7862 case WM_ACTIVATEAPP:
7863 allowAnimations = nsIRollupListener::AllowAnimations::No;
7864 break;
7866 case WM_ACTIVATE: {
7867 WndProcUrgentInvocation::Marker _marker;
7869 // NOTE: Don't handle WA_INACTIVE for preventing popup taking focus
7870 // because we cannot distinguish it's caused by mouse or not.
7871 if (LOWORD(aWParam) == WA_ACTIVE && aLParam) {
7872 nsWindow* window = WinUtils::GetNSWindowPtr(aWnd);
7873 if (window && (window->IsPopup() || window->mIsAlert)) {
7874 // Cancel notifying widget listeners of deactivating the previous
7875 // active window (see WM_KILLFOCUS case in ProcessMessage()).
7876 sJustGotDeactivate = false;
7877 // Reactivate the window later.
7878 ::PostMessageW(aWnd, MOZ_WM_REACTIVATE, aWParam, aLParam);
7879 return true;
7881 // Don't rollup the popup when focus moves back to the parent window
7882 // from a popup because such case is caused by strange mouse drivers.
7883 nsWindow* prevWindow =
7884 WinUtils::GetNSWindowPtr(reinterpret_cast<HWND>(aLParam));
7885 if (prevWindow && prevWindow->IsPopup()) {
7886 // Consume this message here since previous window must not have
7887 // been inactivated since we've already stopped accepting the
7888 // inactivation below.
7889 return true;
7891 } else if (LOWORD(aWParam) == WA_INACTIVE) {
7892 nsWindow* activeWindow =
7893 WinUtils::GetNSWindowPtr(reinterpret_cast<HWND>(aLParam));
7894 if (sPendingNCACTIVATE && NeedsToHandleNCActivateDelayed(aWnd)) {
7895 // If focus moves to non-popup widget or focusable popup, the window
7896 // needs to update its nonclient area.
7897 if (!activeWindow || !activeWindow->IsPopup()) {
7898 sSendingNCACTIVATE = true;
7899 ::SendMessageW(aWnd, WM_NCACTIVATE, false, 0);
7900 sSendingNCACTIVATE = false;
7902 sPendingNCACTIVATE = false;
7904 // If focus moves from/to popup, we don't need to rollup the popup
7905 // because such case is caused by strange mouse drivers. And in
7906 // such case, we should consume the message here since we need to
7907 // hide this odd focus move from our content. (If we didn't consume
7908 // the message here, ProcessMessage() will notify widget listener of
7909 // inactivation and that causes unnecessary reflow for supporting
7910 // -moz-window-inactive pseudo class.
7911 if (activeWindow) {
7912 if (activeWindow->IsPopup()) {
7913 return true;
7915 nsWindow* deactiveWindow = WinUtils::GetNSWindowPtr(aWnd);
7916 if (deactiveWindow && deactiveWindow->IsPopup()) {
7917 return true;
7920 } else if (LOWORD(aWParam) == WA_CLICKACTIVE) {
7921 // If the WM_ACTIVATE message is caused by a click in a popup,
7922 // we should not rollup any popups.
7923 nsWindow* window = WinUtils::GetNSWindowPtr(aWnd);
7924 if ((window && window->IsPopup()) ||
7925 !GetPopupsToRollup(rollupListener, &popupsToRollup)) {
7926 return false;
7929 allowAnimations = nsIRollupListener::AllowAnimations::No;
7930 } break;
7932 case MOZ_WM_REACTIVATE:
7933 // The previous active window should take back focus.
7934 if (::IsWindow(reinterpret_cast<HWND>(aLParam))) {
7935 // FYI: Even without this API call, you see expected result (e.g., the
7936 // owner window of the popup keeps active without flickering
7937 // the non-client area). And also this causes initializing
7938 // TSF and it causes using CPU time a lot. However, even if we
7939 // consume WM_ACTIVE messages, native focus change has already
7940 // been occurred. I.e., a popup window is active now. Therefore,
7941 // you'll see some odd behavior if we don't reactivate the owner
7942 // window here. For example, if you do:
7943 // 1. Turn wheel on a bookmark panel.
7944 // 2. Turn wheel on another window.
7945 // then, you'll see that the another window becomes active but the
7946 // owner window of the bookmark panel looks still active and the
7947 // bookmark panel keeps open. The reason is that the first wheel
7948 // operation gives focus to the bookmark panel. Therefore, when
7949 // the next operation gives focus to the another window, previous
7950 // focus window is the bookmark panel (i.e., a popup window).
7951 // So, in this case, our hack around here prevents to inactivate
7952 // the owner window and roll up the bookmark panel.
7953 ::SetForegroundWindow(reinterpret_cast<HWND>(aLParam));
7955 return true;
7957 case WM_NCACTIVATE:
7958 if (!aWParam && !sSendingNCACTIVATE &&
7959 NeedsToHandleNCActivateDelayed(aWnd)) {
7960 // Don't just consume WM_NCACTIVATE. It doesn't handle only the
7961 // nonclient area state change.
7962 ::DefWindowProcW(aWnd, aMessage, TRUE, aLParam);
7963 // Accept the deactivating because it's necessary to receive following
7964 // WM_ACTIVATE.
7965 *aResult = TRUE;
7966 sPendingNCACTIVATE = true;
7967 return true;
7969 return false;
7971 case WM_MOUSEACTIVATE:
7972 if (!EventIsInsideWindow(popupWindow) &&
7973 GetPopupsToRollup(rollupListener, &popupsToRollup)) {
7974 // WM_MOUSEACTIVATE may be caused by moving the mouse (e.g., X-mouse
7975 // of TweakUI is enabled. Then, check if the popup should be rolled up
7976 // with rollup listener. If not, just consume the message.
7977 if (HIWORD(aLParam) == WM_MOUSEMOVE &&
7978 !rollupListener->ShouldRollupOnMouseActivate()) {
7979 return true;
7981 // Otherwise, it should be handled by wndproc.
7982 return false;
7985 // Prevent the click inside the popup from causing a change in window
7986 // activation. Since the popup is shown non-activated, we need to eat any
7987 // requests to activate the window while it is displayed. Windows will
7988 // automatically activate the popup on the mousedown otherwise.
7989 return true;
7991 case WM_SHOWWINDOW:
7992 // If the window is being minimized, close popups.
7993 if (aLParam == SW_PARENTCLOSING) {
7994 allowAnimations = nsIRollupListener::AllowAnimations::No;
7995 break;
7997 return false;
7999 case WM_KILLFOCUS:
8000 // If focus moves to other window created in different process/thread,
8001 // e.g., a plugin window, popups should be rolled up.
8002 if (IsDifferentThreadWindow(reinterpret_cast<HWND>(aWParam))) {
8003 allowAnimations = nsIRollupListener::AllowAnimations::No;
8004 break;
8006 return false;
8008 case WM_MOVING:
8009 case WM_MENUSELECT:
8010 break;
8012 default:
8013 return false;
8016 // Only need to deal with the last rollup for left mouse down events.
8017 NS_ASSERTION(!nsAutoRollup::GetLastRollup(), "last rollup is null");
8019 nsIRollupListener::RollupOptions rollupOptions{
8020 popupsToRollup,
8021 nsIRollupListener::FlushViews::Yes,
8022 /* mPoint = */ nullptr,
8023 allowAnimations,
8026 if (nativeMessage == WM_TOUCH || nativeMessage == WM_LBUTTONDOWN ||
8027 nativeMessage == WM_POINTERDOWN) {
8028 LayoutDeviceIntPoint pos;
8029 if (nativeMessage == WM_TOUCH) {
8030 pos.x = touchPoint->x;
8031 pos.y = touchPoint->y;
8032 } else {
8033 POINT pt;
8034 pt.x = GET_X_LPARAM(aLParam);
8035 pt.y = GET_Y_LPARAM(aLParam);
8036 // POINTERDOWN is already in screen coords.
8037 if (nativeMessage == WM_LBUTTONDOWN) {
8038 ::ClientToScreen(aWnd, &pt);
8040 pos = LayoutDeviceIntPoint(pt.x, pt.y);
8043 rollupOptions.mPoint = &pos;
8044 nsIContent* lastRollup = nullptr;
8045 consumeRollupEvent = rollupListener->Rollup(rollupOptions, &lastRollup);
8046 nsAutoRollup::SetLastRollup(lastRollup);
8047 } else {
8048 consumeRollupEvent = rollupListener->Rollup(rollupOptions);
8051 // Tell hook to stop processing messages
8052 sProcessHook = false;
8053 sRollupMsgId = 0;
8054 sRollupMsgWnd = nullptr;
8056 // If we are NOT supposed to be consuming events, let it go through
8057 if (consumeRollupEvent && nativeMessage != WM_RBUTTONDOWN) {
8058 *aResult = MA_ACTIVATE;
8059 return true;
8062 return false;
8065 /**************************************************************
8066 **************************************************************
8068 ** BLOCK: Misc. utility methods and functions.
8070 ** General use.
8072 **************************************************************
8073 **************************************************************/
8075 // Note that the result of GetTopLevelWindow method can be different from the
8076 // result of WinUtils::GetTopLevelHWND(). The result can be non-floating
8077 // window. Because our top level window may be contained in another window
8078 // which is not managed by us.
8079 nsWindow* nsWindow::GetTopLevelWindow(bool aStopOnDialogOrPopup) {
8080 nsWindow* curWindow = this;
8082 while (true) {
8083 if (aStopOnDialogOrPopup) {
8084 switch (curWindow->mWindowType) {
8085 case WindowType::Dialog:
8086 case WindowType::Popup:
8087 return curWindow;
8088 default:
8089 break;
8093 // Retrieve the top level parent or owner window
8094 nsWindow* parentWindow = curWindow->GetParentWindow(true);
8096 if (!parentWindow) return curWindow;
8098 curWindow = parentWindow;
8102 // Set a flag if hwnd is a (non-popup) visible window from this process,
8103 // and bail out of the enumeration. Otherwise leave the flag unmodified
8104 // and continue the enumeration.
8105 // lParam must be a bool* pointing at the flag to be set.
8106 static BOOL CALLBACK EnumVisibleWindowsProc(HWND hwnd, LPARAM lParam) {
8107 DWORD pid;
8108 ::GetWindowThreadProcessId(hwnd, &pid);
8109 if (pid == ::GetCurrentProcessId() && ::IsWindowVisible(hwnd)) {
8110 // Don't count popups as visible windows, since they don't take focus,
8111 // in case we only have a popup visible (see bug 1554490 where the gfx
8112 // test window is an offscreen popup).
8113 nsWindow* window = WinUtils::GetNSWindowPtr(hwnd);
8114 if (!window || !window->IsPopup()) {
8115 bool* windowsVisible = reinterpret_cast<bool*>(lParam);
8116 *windowsVisible = true;
8117 return FALSE;
8120 return TRUE;
8123 // Determine if it would be ok to activate a window, taking focus.
8124 // We want to avoid stealing focus from another app (bug 225305).
8125 bool nsWindow::CanTakeFocus() {
8126 HWND fgWnd = ::GetForegroundWindow();
8127 if (!fgWnd) {
8128 // There is no foreground window, so don't worry about stealing focus.
8129 return true;
8131 // We can take focus if the current foreground window is already from
8132 // this process.
8133 DWORD pid;
8134 ::GetWindowThreadProcessId(fgWnd, &pid);
8135 if (pid == ::GetCurrentProcessId()) {
8136 return true;
8139 bool windowsVisible = false;
8140 ::EnumWindows(EnumVisibleWindowsProc,
8141 reinterpret_cast<LPARAM>(&windowsVisible));
8143 if (!windowsVisible) {
8144 // We're probably creating our first visible window, allow that to
8145 // take focus.
8146 return true;
8148 return false;
8151 /* static */ const wchar_t* nsWindow::GetMainWindowClass() {
8152 static const wchar_t* sMainWindowClass = nullptr;
8153 if (!sMainWindowClass) {
8154 nsAutoString className;
8155 Preferences::GetString("ui.window_class_override", className);
8156 if (!className.IsEmpty()) {
8157 sMainWindowClass = wcsdup(className.get());
8158 } else {
8159 sMainWindowClass = kClassNameGeneral;
8162 return sMainWindowClass;
8165 LPARAM nsWindow::lParamToScreen(LPARAM lParam) {
8166 POINT pt;
8167 pt.x = GET_X_LPARAM(lParam);
8168 pt.y = GET_Y_LPARAM(lParam);
8169 ::ClientToScreen(mWnd, &pt);
8170 return MAKELPARAM(pt.x, pt.y);
8173 LPARAM nsWindow::lParamToClient(LPARAM lParam) {
8174 POINT pt;
8175 pt.x = GET_X_LPARAM(lParam);
8176 pt.y = GET_Y_LPARAM(lParam);
8177 ::ScreenToClient(mWnd, &pt);
8178 return MAKELPARAM(pt.x, pt.y);
8181 WPARAM nsWindow::wParamFromGlobalMouseState() {
8182 WPARAM result = 0;
8184 if (!!::GetKeyState(VK_CONTROL)) {
8185 result |= MK_CONTROL;
8188 if (!!::GetKeyState(VK_SHIFT)) {
8189 result |= MK_SHIFT;
8192 if (!!::GetKeyState(VK_LBUTTON)) {
8193 result |= MK_LBUTTON;
8196 if (!!::GetKeyState(VK_MBUTTON)) {
8197 result |= MK_MBUTTON;
8200 if (!!::GetKeyState(VK_RBUTTON)) {
8201 result |= MK_RBUTTON;
8204 if (!!::GetKeyState(VK_XBUTTON1)) {
8205 result |= MK_XBUTTON1;
8208 if (!!::GetKeyState(VK_XBUTTON2)) {
8209 result |= MK_XBUTTON2;
8212 return result;
8215 // WORKAROUND FOR UNDOCUMENTED BEHAVIOR: `IFileDialog::Show` disables the
8216 // top-level ancestor of its provided owner-window. If the modal window's
8217 // container process crashes, it will never get a chance to undo that.
8219 // For simplicity's sake we simply unconditionally perform both the disabling
8220 // and reenabling here, synchronously, on the main thread, rather than leaving
8221 // it to happen in our asynchronously-operated IFileDialog.
8223 void nsWindow::PickerOpen() {
8224 AssertIsOnMainThread();
8226 // Disable the root-level window synchronously before any file-dialogs get a
8227 // chance to fight over doing it asynchronously.
8228 if (!mPickerDisplayCount) {
8229 ::EnableWindow(::GetAncestor(GetWindowHandle(), GA_ROOT), FALSE);
8232 mPickerDisplayCount++;
8235 void nsWindow::PickerClosed() {
8236 AssertIsOnMainThread();
8237 NS_ASSERTION(mPickerDisplayCount > 0, "mPickerDisplayCount out of sync!");
8238 if (!mPickerDisplayCount) return;
8239 mPickerDisplayCount--;
8241 // Once all the file-dialogs are gone, reenable the root-level window.
8242 if (!mPickerDisplayCount) {
8243 ::EnableWindow(::GetAncestor(GetWindowHandle(), GA_ROOT), TRUE);
8244 DispatchFocusToTopLevelWindow(true);
8247 if (!mPickerDisplayCount && mDestroyCalled) {
8248 Destroy();
8252 bool nsWindow::WidgetTypeSupportsAcceleration() {
8253 // We don't currently support using an accelerated layer manager with
8254 // transparent windows so don't even try. I'm also not sure if we even
8255 // want to support this case. See bug 593471.
8257 // Windows' support for transparent accelerated surfaces isn't great.
8258 // Some possible approaches:
8259 // - Readback the data and update it using
8260 // UpdateLayeredWindow/UpdateLayeredWindowIndirect
8261 // This is what WPF does. See
8262 // CD3DDeviceLevel1::PresentWithGDI/CD3DSwapChainWithSwDC in WpfGfx. The
8263 // rationale for not using IDirect3DSurface9::GetDC is explained here:
8264 // https://web.archive.org/web/20160521191104/https://blogs.msdn.microsoft.com/dwayneneed/2008/09/08/transparent-windows-in-wpf/
8265 // - Use D3D11_RESOURCE_MISC_GDI_COMPATIBLE, IDXGISurface1::GetDC(),
8266 // and UpdateLayeredWindowIndirect.
8267 // This is suggested here:
8268 // https://docs.microsoft.com/en-us/archive/msdn-magazine/2009/december/windows-with-c-layered-windows-with-direct2d
8269 // but might have the same problem that IDirect3DSurface9::GetDC has.
8270 // - Creating the window with the WS_EX_NOREDIRECTIONBITMAP flag and use
8271 // DirectComposition.
8272 // Not supported on Win7.
8273 // - Using DwmExtendFrameIntoClientArea with negative margins and something
8274 // to turn off the glass effect.
8275 // This doesn't work when the DWM is not running (Win7)
8277 // Also see bug 1150376, D3D11 composition can cause issues on some devices
8278 // on Windows 7 where presentation fails randomly for windows with drop
8279 // shadows.
8280 return mTransparencyMode != TransparencyMode::Transparent &&
8281 !(IsPopup() && DeviceManagerDx::Get()->IsWARP());
8284 bool nsWindow::DispatchTouchEventFromWMPointer(
8285 UINT msg, LPARAM aLParam, const WinPointerInfo& aPointerInfo,
8286 mozilla::MouseButton aButton) {
8287 MultiTouchInput::MultiTouchType touchType;
8288 switch (msg) {
8289 case WM_POINTERDOWN:
8290 touchType = MultiTouchInput::MULTITOUCH_START;
8291 break;
8292 case WM_POINTERUPDATE:
8293 if (aPointerInfo.mPressure == 0) {
8294 return false; // hover
8296 touchType = MultiTouchInput::MULTITOUCH_MOVE;
8297 break;
8298 case WM_POINTERUP:
8299 touchType = MultiTouchInput::MULTITOUCH_END;
8300 break;
8301 default:
8302 return false;
8305 nsPointWin touchPoint;
8306 touchPoint.x = GET_X_LPARAM(aLParam);
8307 touchPoint.y = GET_Y_LPARAM(aLParam);
8308 touchPoint.ScreenToClient(mWnd);
8310 SingleTouchData touchData(static_cast<int32_t>(aPointerInfo.pointerId),
8311 ScreenIntPoint::FromUnknownPoint(touchPoint),
8312 ScreenSize(1, 1), // pixel size radius for pen
8313 0.0f, // no radius rotation
8314 aPointerInfo.mPressure);
8315 touchData.mTiltX = aPointerInfo.tiltX;
8316 touchData.mTiltY = aPointerInfo.tiltY;
8317 touchData.mTwist = aPointerInfo.twist;
8319 MultiTouchInput touchInput;
8320 touchInput.mType = touchType;
8321 touchInput.mTimeStamp = GetMessageTimeStamp(::GetMessageTime());
8322 touchInput.mTouches.AppendElement(touchData);
8323 touchInput.mButton = aButton;
8324 touchInput.mButtons = aPointerInfo.mButtons;
8326 // POINTER_INFO.dwKeyStates can't be used as it only supports Shift and Ctrl
8327 ModifierKeyState modifierKeyState;
8328 touchInput.modifiers = modifierKeyState.GetModifiers();
8330 DispatchTouchInput(touchInput, MouseEvent_Binding::MOZ_SOURCE_PEN);
8331 return true;
8334 static MouseButton PenFlagsToMouseButton(PEN_FLAGS aPenFlags) {
8335 // Theoretically flags can be set together but they do not
8336 if (aPenFlags & PEN_FLAG_BARREL) {
8337 return MouseButton::eSecondary;
8339 if (aPenFlags & PEN_FLAG_ERASER) {
8340 return MouseButton::eEraser;
8342 return MouseButton::ePrimary;
8345 bool nsWindow::OnPointerEvents(UINT msg, WPARAM aWParam, LPARAM aLParam) {
8346 if (!mAPZC) {
8347 // APZ is not available on context menu. Follow the behavior of touch input
8348 // which fallbacks to WM_LBUTTON* and WM_GESTURE, to keep consistency.
8349 return false;
8351 if (!mPointerEvents.ShouldHandleWinPointerMessages(msg, aWParam)) {
8352 return false;
8354 if (!mPointerEvents.ShouldFirePointerEventByWinPointerMessages()) {
8355 // We have to handle WM_POINTER* to fetch and cache pen related information
8356 // and fire WidgetMouseEvent with the cached information the WM_*BUTTONDOWN
8357 // handler. This is because Windows doesn't support ::DoDragDrop in the
8358 // touch or pen message handlers.
8359 mPointerEvents.ConvertAndCachePointerInfo(msg, aWParam);
8360 // Don't consume the Windows WM_POINTER* messages
8361 return false;
8364 uint32_t pointerId = mPointerEvents.GetPointerId(aWParam);
8365 POINTER_PEN_INFO penInfo{};
8366 if (!mPointerEvents.GetPointerPenInfo(pointerId, &penInfo)) {
8367 return false;
8370 // When dispatching mouse events with pen, there may be some
8371 // WM_POINTERUPDATE messages between WM_POINTERDOWN and WM_POINTERUP with
8372 // small movements. Those events will reset sLastMousePoint and reset
8373 // sLastClickCount. To prevent that, we keep the last pen down position
8374 // and compare it with the subsequent WM_POINTERUPDATE. If the movement is
8375 // smaller than GetSystemMetrics(SM_CXDRAG), then we suppress firing
8376 // eMouseMove for WM_POINTERUPDATE.
8377 static POINT sLastPointerDownPoint = {0};
8379 // We don't support chorded buttons for pen. Keep the button at
8380 // WM_POINTERDOWN.
8381 static mozilla::MouseButton sLastPenDownButton = MouseButton::ePrimary;
8382 static bool sPointerDown = false;
8384 EventMessage message;
8385 mozilla::MouseButton button = MouseButton::ePrimary;
8386 switch (msg) {
8387 case WM_POINTERDOWN: {
8388 LayoutDeviceIntPoint eventPoint(GET_X_LPARAM(aLParam),
8389 GET_Y_LPARAM(aLParam));
8390 sLastPointerDownPoint.x = eventPoint.x;
8391 sLastPointerDownPoint.y = eventPoint.y;
8392 message = eMouseDown;
8393 button = PenFlagsToMouseButton(penInfo.penFlags);
8394 sLastPenDownButton = button;
8395 sPointerDown = true;
8396 } break;
8397 case WM_POINTERUP:
8398 message = eMouseUp;
8399 MOZ_ASSERT(sPointerDown, "receive WM_POINTERUP w/o WM_POINTERDOWN");
8400 button = sPointerDown ? sLastPenDownButton : MouseButton::ePrimary;
8401 sPointerDown = false;
8402 break;
8403 case WM_POINTERUPDATE:
8404 message = eMouseMove;
8405 if (sPointerDown) {
8406 LayoutDeviceIntPoint eventPoint(GET_X_LPARAM(aLParam),
8407 GET_Y_LPARAM(aLParam));
8408 int32_t movementX = sLastPointerDownPoint.x > eventPoint.x
8409 ? sLastPointerDownPoint.x - eventPoint.x.value
8410 : eventPoint.x.value - sLastPointerDownPoint.x;
8411 int32_t movementY = sLastPointerDownPoint.y > eventPoint.y
8412 ? sLastPointerDownPoint.y - eventPoint.y.value
8413 : eventPoint.y.value - sLastPointerDownPoint.y;
8414 bool insideMovementThreshold =
8415 movementX < (int32_t)::GetSystemMetrics(SM_CXDRAG) &&
8416 movementY < (int32_t)::GetSystemMetrics(SM_CYDRAG);
8418 if (insideMovementThreshold) {
8419 // Suppress firing eMouseMove for WM_POINTERUPDATE if the movement
8420 // from last WM_POINTERDOWN is smaller than SM_CXDRAG / SM_CYDRAG
8421 return false;
8423 button = sLastPenDownButton;
8425 break;
8426 case WM_POINTERLEAVE:
8427 message = eMouseExitFromWidget;
8428 break;
8429 default:
8430 return false;
8433 // Windows defines the pen pressure is normalized to a range between 0 and
8434 // 1024. Convert it to float.
8435 float pressure = penInfo.pressure ? (float)penInfo.pressure / 1024 : 0;
8436 int16_t buttons = sPointerDown
8437 ? nsContentUtils::GetButtonsFlagForButton(button)
8438 : MouseButtonsFlag::eNoButtons;
8439 WinPointerInfo pointerInfo(pointerId, penInfo.tiltX, penInfo.tiltY, pressure,
8440 buttons);
8441 // Per
8442 // https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-pointer_pen_info,
8443 // the rotation is normalized in a range of 0 to 359.
8444 MOZ_ASSERT(penInfo.rotation <= 359);
8445 pointerInfo.twist = (int32_t)penInfo.rotation;
8447 // Fire touch events but not when the barrel button is pressed.
8448 if (button != MouseButton::eSecondary &&
8449 StaticPrefs::dom_w3c_pointer_events_scroll_by_pen_enabled() &&
8450 DispatchTouchEventFromWMPointer(msg, aLParam, pointerInfo, button)) {
8451 return true;
8454 // The aLParam of WM_POINTER* is the screen location. Convert it to client
8455 // location
8456 LPARAM newLParam = lParamToClient(aLParam);
8457 DispatchMouseEvent(message, aWParam, newLParam, false, button,
8458 MouseEvent_Binding::MOZ_SOURCE_PEN, &pointerInfo);
8460 if (button == MouseButton::eSecondary && message == eMouseUp) {
8461 // Fire eContextMenu manually since consuming WM_POINTER* blocks
8462 // WM_CONTEXTMENU
8463 DispatchMouseEvent(eContextMenu, aWParam, newLParam, false, button,
8464 MouseEvent_Binding::MOZ_SOURCE_PEN, &pointerInfo);
8466 // Consume WM_POINTER* to stop Windows fires WM_*BUTTONDOWN / WM_*BUTTONUP
8467 // WM_MOUSEMOVE.
8468 return true;
8471 void nsWindow::GetCompositorWidgetInitData(
8472 mozilla::widget::CompositorWidgetInitData* aInitData) {
8473 *aInitData = WinCompositorWidgetInitData(
8474 reinterpret_cast<uintptr_t>(mWnd),
8475 reinterpret_cast<uintptr_t>(static_cast<nsIWidget*>(this)),
8476 mTransparencyMode, mFrameState->GetSizeMode());
8479 bool nsWindow::SynchronouslyRepaintOnResize() { return false; }
8481 void nsWindow::MaybeDispatchInitialFocusEvent() {
8482 if (mIsShowingPreXULSkeletonUI && ::GetActiveWindow() == mWnd) {
8483 DispatchFocusToTopLevelWindow(true);
8487 already_AddRefed<nsIWidget> nsIWidget::CreateTopLevelWindow() {
8488 nsCOMPtr<nsIWidget> window = new nsWindow();
8489 return window.forget();
8492 already_AddRefed<nsIWidget> nsIWidget::CreateChildWindow() {
8493 nsCOMPtr<nsIWidget> window = new nsWindow(true);
8494 return window.forget();
8497 // static
8498 bool nsWindow::InitTouchInjection() {
8499 if (!sTouchInjectInitialized) {
8500 // Initialize touch injection on the first call
8501 HMODULE hMod = LoadLibraryW(kUser32LibName);
8502 if (!hMod) {
8503 return false;
8506 InitializeTouchInjectionPtr func =
8507 (InitializeTouchInjectionPtr)GetProcAddress(hMod,
8508 "InitializeTouchInjection");
8509 if (!func) {
8510 WinUtils::Log("InitializeTouchInjection not available.");
8511 return false;
8514 if (!func(TOUCH_INJECT_MAX_POINTS, TOUCH_FEEDBACK_DEFAULT)) {
8515 WinUtils::Log("InitializeTouchInjection failure. GetLastError=%d",
8516 GetLastError());
8517 return false;
8520 sInjectTouchFuncPtr =
8521 (InjectTouchInputPtr)GetProcAddress(hMod, "InjectTouchInput");
8522 if (!sInjectTouchFuncPtr) {
8523 WinUtils::Log("InjectTouchInput not available.");
8524 return false;
8526 sTouchInjectInitialized = true;
8528 return true;
8531 bool nsWindow::InjectTouchPoint(uint32_t aId, LayoutDeviceIntPoint& aPoint,
8532 POINTER_FLAGS aFlags, uint32_t aPressure,
8533 uint32_t aOrientation) {
8534 if (aId > TOUCH_INJECT_MAX_POINTS) {
8535 WinUtils::Log("Pointer ID exceeds maximum. See TOUCH_INJECT_MAX_POINTS.");
8536 return false;
8539 POINTER_TOUCH_INFO info{};
8541 info.touchFlags = TOUCH_FLAG_NONE;
8542 info.touchMask =
8543 TOUCH_MASK_CONTACTAREA | TOUCH_MASK_ORIENTATION | TOUCH_MASK_PRESSURE;
8544 info.pressure = aPressure;
8545 info.orientation = aOrientation;
8547 info.pointerInfo.pointerFlags = aFlags;
8548 info.pointerInfo.pointerType = PT_TOUCH;
8549 info.pointerInfo.pointerId = aId;
8550 info.pointerInfo.ptPixelLocation.x = aPoint.x;
8551 info.pointerInfo.ptPixelLocation.y = aPoint.y;
8553 info.rcContact.top = info.pointerInfo.ptPixelLocation.y - 2;
8554 info.rcContact.bottom = info.pointerInfo.ptPixelLocation.y + 2;
8555 info.rcContact.left = info.pointerInfo.ptPixelLocation.x - 2;
8556 info.rcContact.right = info.pointerInfo.ptPixelLocation.x + 2;
8558 for (int i = 0; i < 3; i++) {
8559 if (sInjectTouchFuncPtr(1, &info)) {
8560 break;
8562 DWORD error = GetLastError();
8563 if (error == ERROR_NOT_READY && i < 2) {
8564 // We sent it too quickly after the previous injection (see bug 1535140
8565 // comment 10). On the first loop iteration we just yield (via Sleep(0))
8566 // and try again. If it happens again on the second loop iteration we
8567 // explicitly Sleep(1) and try again. If that doesn't work either we just
8568 // error out.
8569 ::Sleep(i);
8570 continue;
8572 WinUtils::Log("InjectTouchInput failure. GetLastError=%d", error);
8573 return false;
8575 return true;
8578 void nsWindow::ChangedDPI() {
8579 if (mWidgetListener) {
8580 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
8581 presShell->BackingScaleFactorChanged();
8584 NotifyAPZOfDPIChange();
8587 static Result<POINTER_FLAGS, nsresult> PointerStateToFlag(
8588 nsWindow::TouchPointerState aPointerState, bool isUpdate) {
8589 bool hover = aPointerState & nsWindow::TOUCH_HOVER;
8590 bool contact = aPointerState & nsWindow::TOUCH_CONTACT;
8591 bool remove = aPointerState & nsWindow::TOUCH_REMOVE;
8592 bool cancel = aPointerState & nsWindow::TOUCH_CANCEL;
8594 POINTER_FLAGS flags;
8595 if (isUpdate) {
8596 // We know about this pointer, send an update
8597 flags = POINTER_FLAG_UPDATE;
8598 if (hover) {
8599 flags |= POINTER_FLAG_INRANGE;
8600 } else if (contact) {
8601 flags |= POINTER_FLAG_INCONTACT | POINTER_FLAG_INRANGE;
8602 } else if (remove) {
8603 flags = POINTER_FLAG_UP;
8606 if (cancel) {
8607 flags |= POINTER_FLAG_CANCELED;
8609 } else {
8610 // Missing init state, error out
8611 if (remove || cancel) {
8612 return Err(NS_ERROR_INVALID_ARG);
8615 // Create a new pointer
8616 flags = POINTER_FLAG_INRANGE;
8617 if (contact) {
8618 flags |= POINTER_FLAG_INCONTACT | POINTER_FLAG_DOWN;
8621 return flags;
8624 nsresult nsWindow::SynthesizeNativeTouchPoint(
8625 uint32_t aPointerId, nsIWidget::TouchPointerState aPointerState,
8626 LayoutDeviceIntPoint aPoint, double aPointerPressure,
8627 uint32_t aPointerOrientation, nsIObserver* aObserver) {
8628 AutoObserverNotifier notifier(aObserver, "touchpoint");
8630 if (StaticPrefs::apz_test_fails_with_native_injection() ||
8631 !InitTouchInjection()) {
8632 // If we don't have touch injection from the OS, or if we are running a test
8633 // that cannot properly inject events to satisfy the OS requirements (see
8634 // bug 1313170) we can just fake it and synthesize the events from here.
8635 MOZ_ASSERT(NS_IsMainThread());
8636 if (aPointerState == TOUCH_HOVER) {
8637 return NS_ERROR_UNEXPECTED;
8640 if (!mSynthesizedTouchInput) {
8641 mSynthesizedTouchInput = MakeUnique<MultiTouchInput>();
8644 WidgetEventTime time = CurrentMessageWidgetEventTime();
8645 LayoutDeviceIntPoint pointInWindow = aPoint - WidgetToScreenOffset();
8646 MultiTouchInput inputToDispatch = UpdateSynthesizedTouchState(
8647 mSynthesizedTouchInput.get(), time.mTimeStamp, aPointerId,
8648 aPointerState, pointInWindow, aPointerPressure, aPointerOrientation);
8649 DispatchTouchInput(inputToDispatch);
8650 return NS_OK;
8653 // win api expects a value from 0 to 1024. aPointerPressure is a value
8654 // from 0.0 to 1.0.
8655 uint32_t pressure = (uint32_t)ceil(aPointerPressure * 1024);
8657 // If we already know about this pointer id get it's record
8658 return mActivePointers.WithEntryHandle(aPointerId, [&](auto&& entry) {
8659 POINTER_FLAGS flags;
8660 // Can't use MOZ_TRY_VAR because it confuses WithEntryHandle
8661 auto result = PointerStateToFlag(aPointerState, !!entry);
8662 if (result.isOk()) {
8663 flags = result.unwrap();
8664 } else {
8665 return result.unwrapErr();
8668 if (!entry) {
8669 entry.Insert(MakeUnique<PointerInfo>(aPointerId, aPoint,
8670 PointerInfo::PointerType::TOUCH));
8671 } else {
8672 if (entry.Data()->mType != PointerInfo::PointerType::TOUCH) {
8673 return NS_ERROR_UNEXPECTED;
8675 if (aPointerState & TOUCH_REMOVE) {
8676 // Remove the pointer from our tracking list. This is UniquePtr wrapped,
8677 // so shouldn't leak.
8678 entry.Remove();
8682 return !InjectTouchPoint(aPointerId, aPoint, flags, pressure,
8683 aPointerOrientation)
8684 ? NS_ERROR_UNEXPECTED
8685 : NS_OK;
8689 nsresult nsWindow::ClearNativeTouchSequence(nsIObserver* aObserver) {
8690 AutoObserverNotifier notifier(aObserver, "cleartouch");
8691 if (!sTouchInjectInitialized) {
8692 return NS_OK;
8695 // cancel all input points
8696 for (auto iter = mActivePointers.Iter(); !iter.Done(); iter.Next()) {
8697 auto* info = iter.UserData();
8698 if (info->mType != PointerInfo::PointerType::TOUCH) {
8699 continue;
8701 InjectTouchPoint(info->mPointerId, info->mPosition, POINTER_FLAG_CANCELED);
8702 iter.Remove();
8705 nsBaseWidget::ClearNativeTouchSequence(nullptr);
8707 return NS_OK;
8710 #if !defined(NTDDI_WIN10_RS5) || (NTDDI_VERSION < NTDDI_WIN10_RS5)
8711 static CreateSyntheticPointerDevicePtr CreateSyntheticPointerDevice;
8712 static DestroySyntheticPointerDevicePtr DestroySyntheticPointerDevice;
8713 static InjectSyntheticPointerInputPtr InjectSyntheticPointerInput;
8714 #endif
8715 static HSYNTHETICPOINTERDEVICE sSyntheticPenDevice;
8717 static bool InitPenInjection() {
8718 if (sSyntheticPenDevice) {
8719 return true;
8721 #if !defined(NTDDI_WIN10_RS5) || (NTDDI_VERSION < NTDDI_WIN10_RS5)
8722 HMODULE hMod = LoadLibraryW(kUser32LibName);
8723 if (!hMod) {
8724 return false;
8726 CreateSyntheticPointerDevice =
8727 (CreateSyntheticPointerDevicePtr)GetProcAddress(
8728 hMod, "CreateSyntheticPointerDevice");
8729 if (!CreateSyntheticPointerDevice) {
8730 WinUtils::Log("CreateSyntheticPointerDevice not available.");
8731 return false;
8733 DestroySyntheticPointerDevice =
8734 (DestroySyntheticPointerDevicePtr)GetProcAddress(
8735 hMod, "DestroySyntheticPointerDevice");
8736 if (!DestroySyntheticPointerDevice) {
8737 WinUtils::Log("DestroySyntheticPointerDevice not available.");
8738 return false;
8740 InjectSyntheticPointerInput = (InjectSyntheticPointerInputPtr)GetProcAddress(
8741 hMod, "InjectSyntheticPointerInput");
8742 if (!InjectSyntheticPointerInput) {
8743 WinUtils::Log("InjectSyntheticPointerInput not available.");
8744 return false;
8746 #endif
8747 sSyntheticPenDevice =
8748 CreateSyntheticPointerDevice(PT_PEN, 1, POINTER_FEEDBACK_DEFAULT);
8749 return !!sSyntheticPenDevice;
8752 nsresult nsWindow::SynthesizeNativePenInput(
8753 uint32_t aPointerId, nsIWidget::TouchPointerState aPointerState,
8754 LayoutDeviceIntPoint aPoint, double aPressure, uint32_t aRotation,
8755 int32_t aTiltX, int32_t aTiltY, int32_t aButton, nsIObserver* aObserver) {
8756 AutoObserverNotifier notifier(aObserver, "peninput");
8757 if (!InitPenInjection()) {
8758 return NS_ERROR_UNEXPECTED;
8761 // win api expects a value from 0 to 1024. aPointerPressure is a value
8762 // from 0.0 to 1.0.
8763 uint32_t pressure = (uint32_t)ceil(aPressure * 1024);
8765 // If we already know about this pointer id get it's record
8766 return mActivePointers.WithEntryHandle(aPointerId, [&](auto&& entry) {
8767 POINTER_FLAGS flags;
8768 // Can't use MOZ_TRY_VAR because it confuses WithEntryHandle
8769 auto result = PointerStateToFlag(aPointerState, !!entry);
8770 if (result.isOk()) {
8771 flags = result.unwrap();
8772 } else {
8773 return result.unwrapErr();
8776 if (!entry) {
8777 entry.Insert(MakeUnique<PointerInfo>(aPointerId, aPoint,
8778 PointerInfo::PointerType::PEN));
8779 } else {
8780 if (entry.Data()->mType != PointerInfo::PointerType::PEN) {
8781 return NS_ERROR_UNEXPECTED;
8783 if (aPointerState & TOUCH_REMOVE) {
8784 // Remove the pointer from our tracking list. This is UniquePtr wrapped,
8785 // so shouldn't leak.
8786 entry.Remove();
8790 POINTER_TYPE_INFO info{};
8792 info.type = PT_PEN;
8793 info.penInfo.pointerInfo.pointerType = PT_PEN;
8794 info.penInfo.pointerInfo.pointerFlags = flags;
8795 info.penInfo.pointerInfo.pointerId = aPointerId;
8796 info.penInfo.pointerInfo.ptPixelLocation.x = aPoint.x;
8797 info.penInfo.pointerInfo.ptPixelLocation.y = aPoint.y;
8799 info.penInfo.penFlags = PEN_FLAG_NONE;
8800 // PEN_FLAG_ERASER is not supported this way, unfortunately.
8801 if (aButton == 2) {
8802 info.penInfo.penFlags |= PEN_FLAG_BARREL;
8804 info.penInfo.penMask = PEN_MASK_PRESSURE | PEN_MASK_ROTATION |
8805 PEN_MASK_TILT_X | PEN_MASK_TILT_Y;
8806 info.penInfo.pressure = pressure;
8807 info.penInfo.rotation = aRotation;
8808 info.penInfo.tiltX = aTiltX;
8809 info.penInfo.tiltY = aTiltY;
8811 return InjectSyntheticPointerInput(sSyntheticPenDevice, &info, 1)
8812 ? NS_OK
8813 : NS_ERROR_UNEXPECTED;
8817 bool nsWindow::HandleAppCommandMsg(const MSG& aAppCommandMsg,
8818 LRESULT* aRetValue) {
8819 ModifierKeyState modKeyState;
8820 NativeKey nativeKey(this, aAppCommandMsg, modKeyState);
8821 bool consumed = nativeKey.HandleAppCommandMessage();
8822 *aRetValue = consumed ? 1 : 0;
8823 return consumed;
8826 #ifdef DEBUG
8827 nsresult nsWindow::SetHiDPIMode(bool aHiDPI) {
8828 return WinUtils::SetHiDPIMode(aHiDPI);
8831 nsresult nsWindow::RestoreHiDPIMode() { return WinUtils::RestoreHiDPIMode(); }
8832 #endif
8834 mozilla::Maybe<UINT> nsWindow::GetHiddenTaskbarEdge() {
8835 HMONITOR windowMonitor = ::MonitorFromWindow(mWnd, MONITOR_DEFAULTTONEAREST);
8837 // Check all four sides of our monitor for an appbar. Skip any that aren't
8838 // the system taskbar.
8839 MONITORINFO mi;
8840 mi.cbSize = sizeof(MONITORINFO);
8841 ::GetMonitorInfo(windowMonitor, &mi);
8843 APPBARDATA appBarData;
8844 appBarData.cbSize = sizeof(appBarData);
8845 appBarData.rc = mi.rcMonitor;
8846 const auto kEdges = {ABE_BOTTOM, ABE_TOP, ABE_LEFT, ABE_RIGHT};
8847 for (auto edge : kEdges) {
8848 appBarData.uEdge = edge;
8849 HWND appBarHwnd = (HWND)SHAppBarMessage(ABM_GETAUTOHIDEBAREX, &appBarData);
8850 if (appBarHwnd) {
8851 nsAutoString className;
8852 if (WinUtils::GetClassName(appBarHwnd, className)) {
8853 if (className.Equals(L"Shell_TrayWnd") ||
8854 className.Equals(L"Shell_SecondaryTrayWnd")) {
8855 return Some(edge);
8861 return Nothing();
8864 static nsSizeMode GetSizeModeForWindowFrame(HWND aWnd, bool aFullscreenMode) {
8865 WINDOWPLACEMENT pl;
8866 pl.length = sizeof(pl);
8867 ::GetWindowPlacement(aWnd, &pl);
8869 if (pl.showCmd == SW_SHOWMINIMIZED) {
8870 return nsSizeMode_Minimized;
8871 } else if (aFullscreenMode) {
8872 return nsSizeMode_Fullscreen;
8873 } else if (pl.showCmd == SW_SHOWMAXIMIZED) {
8874 return nsSizeMode_Maximized;
8875 } else {
8876 return nsSizeMode_Normal;
8880 static void ShowWindowWithMode(HWND aWnd, nsSizeMode aMode) {
8881 // This will likely cause a callback to
8882 // nsWindow::FrameState::{OnFrameChanging() and OnFrameChanged()}
8883 switch (aMode) {
8884 case nsSizeMode_Fullscreen:
8885 ::ShowWindow(aWnd, SW_SHOW);
8886 break;
8888 case nsSizeMode_Maximized:
8889 ::ShowWindow(aWnd, SW_MAXIMIZE);
8890 break;
8892 case nsSizeMode_Minimized:
8893 ::ShowWindow(aWnd, SW_MINIMIZE);
8894 break;
8896 default:
8897 // Don't call ::ShowWindow if we're trying to "restore" a window that is
8898 // already in a normal state. Prevents a bug where snapping to one side
8899 // of the screen and then minimizing would cause Windows to forget our
8900 // window's correct restored position/size.
8901 if (GetCurrentShowCmd(aWnd) != SW_SHOWNORMAL) {
8902 ::ShowWindow(aWnd, SW_RESTORE);
8907 nsWindow::FrameState::FrameState(nsWindow* aWindow) : mWindow(aWindow) {}
8909 nsSizeMode nsWindow::FrameState::GetSizeMode() const { return mSizeMode; }
8911 void nsWindow::FrameState::CheckInvariant() const {
8912 MOZ_ASSERT(mSizeMode >= 0 && mSizeMode < nsSizeMode_Invalid);
8913 MOZ_ASSERT(mLastSizeMode >= 0 && mLastSizeMode < nsSizeMode_Invalid);
8914 MOZ_ASSERT(mPreFullscreenSizeMode >= 0 &&
8915 mPreFullscreenSizeMode < nsSizeMode_Invalid);
8916 MOZ_ASSERT(mWindow);
8918 // We should never observe fullscreen sizemode unless fullscreen is enabled
8919 MOZ_ASSERT_IF(mSizeMode == nsSizeMode_Fullscreen, mFullscreenMode);
8920 MOZ_ASSERT_IF(!mFullscreenMode, mSizeMode != nsSizeMode_Fullscreen);
8922 // Something went wrong if we somehow saved fullscreen mode when we are
8923 // changing into fullscreen mode
8924 MOZ_ASSERT(mPreFullscreenSizeMode != nsSizeMode_Fullscreen);
8927 void nsWindow::FrameState::ConsumePreXULSkeletonState(bool aWasMaximized) {
8928 mSizeMode = aWasMaximized ? nsSizeMode_Maximized : nsSizeMode_Normal;
8931 void nsWindow::FrameState::EnsureSizeMode(nsSizeMode aMode,
8932 DoShowWindow aDoShowWindow) {
8933 if (mSizeMode == aMode) {
8934 return;
8937 if (StaticPrefs::widget_windows_fullscreen_remind_taskbar()) {
8938 // If we're unminimizing a window, asynchronously notify the taskbar after
8939 // the message has been processed. This redundant notification works around
8940 // a race condition in explorer.exe. (See bug 1835851, or comments in
8941 // TaskbarConcealer.)
8943 // Note that we notify regardless of `aMode`: unminimizing a non-fullscreen
8944 // window can also affect the correct taskbar state, yet fail to affect the
8945 // current taskbar state.
8946 if (mSizeMode == nsSizeMode_Minimized) {
8947 ::PostMessage(mWindow->mWnd, MOZ_WM_FULLSCREEN_STATE_UPDATE, 0, 0);
8951 if (aMode == nsSizeMode_Fullscreen) {
8952 EnsureFullscreenMode(true, aDoShowWindow);
8953 MOZ_ASSERT(mSizeMode == nsSizeMode_Fullscreen);
8954 } else if (mSizeMode == nsSizeMode_Fullscreen && aMode == nsSizeMode_Normal) {
8955 // If we are in fullscreen mode, minimize should work like normal and
8956 // return us to fullscreen mode when unminimized. Maximize isn't really
8957 // available and won't do anything. "Restore" should do the same thing as
8958 // requesting to end fullscreen.
8959 EnsureFullscreenMode(false, aDoShowWindow);
8960 } else {
8961 SetSizeModeInternal(aMode, aDoShowWindow);
8965 void nsWindow::FrameState::EnsureFullscreenMode(bool aFullScreen,
8966 DoShowWindow aDoShowWindow) {
8967 const bool changed = aFullScreen != mFullscreenMode;
8968 if (changed && aFullScreen) {
8969 // Save the size mode from before fullscreen.
8970 mPreFullscreenSizeMode = mSizeMode;
8972 mFullscreenMode = aFullScreen;
8973 if (changed || aFullScreen) {
8974 // NOTE(emilio): When minimizing a fullscreen window we remain with
8975 // mFullscreenMode = true, but mSizeMode = nsSizeMode_Minimized. We need to
8976 // make sure to call SetSizeModeInternal even if mFullscreenMode didn't
8977 // change, to ensure we actually end up with a fullscreen sizemode when
8978 // restoring a window from that state.
8979 SetSizeModeInternal(
8980 aFullScreen ? nsSizeMode_Fullscreen : mPreFullscreenSizeMode,
8981 aDoShowWindow);
8985 void nsWindow::FrameState::OnFrameChanging() {
8986 const nsSizeMode newSizeMode =
8987 GetSizeModeForWindowFrame(mWindow->mWnd, mFullscreenMode);
8988 EnsureSizeMode(newSizeMode);
8989 mWindow->UpdateNonClientMargins(false);
8992 void nsWindow::FrameState::OnFrameChanged() {
8993 // We don't want to perform the ShowWindow ourselves if we're on the frame
8994 // changed message. Windows has done the frame change for us, and we take care
8995 // of activating as needed. We also don't want to potentially trigger
8996 // more focus / restore. Among other things, this addresses a bug on Win7
8997 // related to window docking. (bug 489258)
8998 const auto newSizeMode =
8999 GetSizeModeForWindowFrame(mWindow->mWnd, mFullscreenMode);
9000 EnsureSizeMode(newSizeMode, DoShowWindow::No);
9002 // If window was restored, activate the window now to get correct attributes.
9003 if (mWindow->mIsVisible && mWindow->IsForegroundWindow() &&
9004 mLastSizeMode == nsSizeMode_Minimized &&
9005 mSizeMode != nsSizeMode_Minimized) {
9006 mWindow->DispatchFocusToTopLevelWindow(true);
9008 mLastSizeMode = mSizeMode;
9011 static void MaybeLogSizeMode(nsSizeMode aMode) {
9012 #ifdef WINSTATE_DEBUG_OUTPUT
9013 MOZ_LOG(gWindowsLog, LogLevel::Info, ("*** SizeMode: %d\n", int(aMode)));
9014 #endif
9017 void nsWindow::FrameState::SetSizeModeInternal(nsSizeMode aMode,
9018 DoShowWindow aDoShowWindow) {
9019 if (mSizeMode == aMode) {
9020 return;
9023 const auto oldSizeMode = mSizeMode;
9024 const bool fullscreenChange =
9025 mSizeMode == nsSizeMode_Fullscreen || aMode == nsSizeMode_Fullscreen;
9026 const bool fullscreen = aMode == nsSizeMode_Fullscreen;
9028 mLastSizeMode = mSizeMode;
9029 mSizeMode = aMode;
9031 MaybeLogSizeMode(mSizeMode);
9033 if (bool(aDoShowWindow) && mWindow->mIsVisible) {
9034 ShowWindowWithMode(mWindow->mWnd, aMode);
9037 mWindow->UpdateNonClientMargins(false);
9039 if (fullscreenChange) {
9040 mWindow->OnFullscreenChanged(oldSizeMode, fullscreen);
9043 mWindow->OnSizeModeChange();
9046 void nsWindow::ContextMenuPreventer::Update(
9047 const WidgetMouseEvent& aEvent,
9048 const nsIWidget::ContentAndAPZEventStatus& aEventStatus) {
9049 mNeedsToPreventContextMenu =
9050 aEvent.mMessage == eMouseUp &&
9051 aEvent.mButton == MouseButton::eSecondary &&
9052 aEvent.mInputSource == MouseEvent_Binding::MOZ_SOURCE_MOUSE &&
9053 aEventStatus.mApzStatus == nsEventStatus_eConsumeNoDefault;