Bug 1942006 - Upstream a variety of Servo-specific code from Servo's downstream fork...
[gecko.git] / widget / nsBaseWidget.cpp
blob446f3264418d10eb6edf1828c804eb2100069c1b
2 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
3 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
4 /* This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 #include "nsBaseWidget.h"
10 #include <utility>
12 #include "GLConsts.h"
13 #include "InputData.h"
14 #include "LiveResizeListener.h"
15 #include "SwipeTracker.h"
16 #include "TouchEvents.h"
17 #include "X11UndefineNone.h"
18 #include "base/thread.h"
19 #include "mozilla/ArrayUtils.h"
20 #include "mozilla/Attributes.h"
21 #include "mozilla/GlobalKeyListener.h"
22 #include "mozilla/IMEStateManager.h"
23 #include "mozilla/Logging.h"
24 #include "mozilla/MouseEvents.h"
25 #include "mozilla/NativeKeyBindingsType.h"
26 #include "mozilla/Preferences.h"
27 #include "mozilla/PresShell.h"
28 #include "mozilla/ScopeExit.h"
29 #include "mozilla/Sprintf.h"
30 #include "mozilla/StaticPrefs_apz.h"
31 #include "mozilla/StaticPrefs_dom.h"
32 #include "mozilla/StaticPrefs_gfx.h"
33 #include "mozilla/StaticPrefs_layers.h"
34 #include "mozilla/StaticPrefs_layout.h"
35 #include "mozilla/TextEventDispatcher.h"
36 #include "mozilla/TextEventDispatcherListener.h"
37 #include "mozilla/UniquePtr.h"
38 #include "mozilla/Unused.h"
39 #include "mozilla/VsyncDispatcher.h"
40 #include "mozilla/dom/BrowserParent.h"
41 #include "mozilla/dom/ContentChild.h"
42 #include "mozilla/dom/Document.h"
43 #include "mozilla/dom/SimpleGestureEventBinding.h"
44 #include "mozilla/gfx/2D.h"
45 #include "mozilla/gfx/GPUProcessManager.h"
46 #include "mozilla/gfx/gfxVars.h"
47 #include "mozilla/layers/APZCCallbackHelper.h"
48 #include "mozilla/layers/TouchActionHelper.h"
49 #include "mozilla/layers/APZEventState.h"
50 #include "mozilla/layers/APZInputBridge.h"
51 #include "mozilla/layers/APZThreadUtils.h"
52 #include "mozilla/layers/ChromeProcessController.h"
53 #include "mozilla/layers/Compositor.h"
54 #include "mozilla/layers/CompositorBridgeChild.h"
55 #include "mozilla/layers/CompositorBridgeParent.h"
56 #include "mozilla/layers/CompositorOptions.h"
57 #include "mozilla/layers/IAPZCTreeManager.h"
58 #include "mozilla/layers/ImageBridgeChild.h"
59 #include "mozilla/layers/InputAPZContext.h"
60 #include "mozilla/layers/WebRenderLayerManager.h"
61 #include "mozilla/webrender/WebRenderTypes.h"
62 #include "mozilla/widget/ScreenManager.h"
63 #include "nsAppDirectoryServiceDefs.h"
64 #include "nsBaseDragService.h"
65 #include "nsCOMPtr.h"
66 #include "nsContentUtils.h"
67 #include "nsDeviceContext.h"
68 #include "nsGfxCIID.h"
69 #include "nsIAppWindow.h"
70 #include "nsIBaseWindow.h"
71 #include "nsIContent.h"
72 #include "nsIScreenManager.h"
73 #include "nsISimpleEnumerator.h"
74 #include "nsIWidgetListener.h"
75 #include "nsRefPtrHashtable.h"
76 #include "nsServiceManagerUtils.h"
77 #include "nsWidgetsCID.h"
78 #include "nsXULPopupManager.h"
79 #include "prdtoa.h"
80 #include "prenv.h"
81 #ifdef ACCESSIBILITY
82 # include "nsAccessibilityService.h"
83 #endif
84 #include "gfxConfig.h"
85 #include "gfxUtils.h" // for ToDeviceColor
86 #include "mozilla/layers/CompositorSession.h"
87 #include "VRManagerChild.h"
88 #include "gfxConfig.h"
89 #include "nsView.h"
90 #include "nsViewManager.h"
92 static mozilla::LazyLogModule sBaseWidgetLog("BaseWidget");
94 #ifdef DEBUG
95 # include "nsIObserver.h"
97 static void debug_RegisterPrefCallbacks();
99 #endif
101 #ifdef NOISY_WIDGET_LEAKS
102 static int32_t gNumWidgets;
103 #endif
105 using namespace mozilla::dom;
106 using namespace mozilla::layers;
107 using namespace mozilla::ipc;
108 using namespace mozilla::widget;
109 using namespace mozilla;
111 // Async pump timer during injected long touch taps
112 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
113 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
114 int32_t nsIWidget::sPointerIdCounter = 0;
116 // Some statics from nsIWidget.h
117 /*static*/
118 uint64_t AutoObserverNotifier::sObserverId = 0;
119 MOZ_RUNINIT /*static*/ nsTHashMap<uint64_t, nsCOMPtr<nsIObserver>>
120 AutoObserverNotifier::sSavedObservers;
122 // The maximum amount of time to let the EnableDragDrop runnable wait in the
123 // idle queue before timing out and moving it to the regular queue. Value is in
124 // milliseconds.
125 const uint32_t kAsyncDragDropTimeout = 1000;
127 NS_IMPL_ISUPPORTS(nsBaseWidget, nsIWidget, nsISupportsWeakReference)
129 //-------------------------------------------------------------------------
131 // nsBaseWidget constructor
133 //-------------------------------------------------------------------------
135 nsBaseWidget::nsBaseWidget() : nsBaseWidget(BorderStyle::None) {}
137 nsBaseWidget::nsBaseWidget(BorderStyle aBorderStyle)
138 : mWidgetListener(nullptr),
139 mAttachedWidgetListener(nullptr),
140 mPreviouslyAttachedWidgetListener(nullptr),
141 mCompositorVsyncDispatcher(nullptr),
142 mBorderStyle(aBorderStyle),
143 mBounds(0, 0, 0, 0),
144 mIsTiled(false),
145 mPopupLevel(PopupLevel::Top),
146 mPopupType(PopupType::Any),
147 mHasRemoteContent(false),
148 mUpdateCursor(true),
149 mUseAttachedEvents(false),
150 mIMEHasFocus(false),
151 mIMEHasQuit(false),
152 mIsFullyOccluded(false),
153 mNeedFastSnaphot(false),
154 mCurrentPanGestureBelongsToSwipe(false),
155 mIsPIPWindow(false) {
156 #ifdef NOISY_WIDGET_LEAKS
157 gNumWidgets++;
158 printf("WIDGETS+ = %d\n", gNumWidgets);
159 #endif
161 #ifdef DEBUG
162 debug_RegisterPrefCallbacks();
163 #endif
165 mShutdownObserver = new WidgetShutdownObserver(this);
168 NS_IMPL_ISUPPORTS(WidgetShutdownObserver, nsIObserver)
170 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget* aWidget)
171 : mWidget(aWidget), mRegistered(false) {
172 Register();
175 WidgetShutdownObserver::~WidgetShutdownObserver() {
176 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
177 // gets torn down. The observer service and nsBaseWidget have a ref on us
178 // so nsBaseWidget has to call Unregister and then clear its ref.
181 NS_IMETHODIMP
182 WidgetShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
183 const char16_t* aData) {
184 if (!mWidget) {
185 return NS_OK;
187 if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
188 RefPtr<nsBaseWidget> widget(mWidget);
189 widget->Shutdown();
190 } else if (!strcmp(aTopic, "quit-application")) {
191 RefPtr<nsBaseWidget> widget(mWidget);
192 widget->QuitIME();
194 return NS_OK;
197 void WidgetShutdownObserver::Register() {
198 if (!mRegistered) {
199 mRegistered = true;
200 nsContentUtils::RegisterShutdownObserver(this);
202 #ifndef MOZ_WIDGET_ANDROID
203 // The primary purpose of observing quit-application is
204 // to avoid leaking a widget on Windows when nothing else
205 // breaks the circular reference between the widget and
206 // TSFTextStore. However, our Android IME code crashes if
207 // doing this on Android, so let's not do this on Android.
208 // Doing this on Gtk and Mac just in case.
209 nsCOMPtr<nsIObserverService> observerService =
210 mozilla::services::GetObserverService();
211 if (observerService) {
212 observerService->AddObserver(this, "quit-application", false);
214 #endif
218 void WidgetShutdownObserver::Unregister() {
219 if (mRegistered) {
220 mWidget = nullptr;
222 #ifndef MOZ_WIDGET_ANDROID
223 nsCOMPtr<nsIObserverService> observerService =
224 mozilla::services::GetObserverService();
225 if (observerService) {
226 observerService->RemoveObserver(this, "quit-application");
228 #endif
230 nsContentUtils::UnregisterShutdownObserver(this);
231 mRegistered = false;
235 #define INTL_APP_LOCALES_CHANGED "intl:app-locales-changed"
237 NS_IMPL_ISUPPORTS(LocalesChangedObserver, nsIObserver)
239 LocalesChangedObserver::LocalesChangedObserver(nsBaseWidget* aWidget)
240 : mWidget(aWidget), mRegistered(false) {
241 Register();
244 LocalesChangedObserver::~LocalesChangedObserver() {
245 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
246 // gets torn down. The observer service and nsBaseWidget have a ref on us
247 // so nsBaseWidget has to call Unregister and then clear its ref.
250 NS_IMETHODIMP
251 LocalesChangedObserver::Observe(nsISupports* aSubject, const char* aTopic,
252 const char16_t* aData) {
253 if (!mWidget) {
254 return NS_OK;
256 if (!strcmp(aTopic, INTL_APP_LOCALES_CHANGED)) {
257 RefPtr<nsBaseWidget> widget(mWidget);
258 widget->LocalesChanged();
260 return NS_OK;
263 void LocalesChangedObserver::Register() {
264 if (mRegistered) {
265 return;
268 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
269 if (obs) {
270 obs->AddObserver(this, INTL_APP_LOCALES_CHANGED, true);
273 // Locale might be update before registering
274 RefPtr<nsBaseWidget> widget(mWidget);
275 widget->LocalesChanged();
277 mRegistered = true;
280 void LocalesChangedObserver::Unregister() {
281 if (!mRegistered) {
282 return;
285 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
286 if (obs) {
287 obs->RemoveObserver(this, INTL_APP_LOCALES_CHANGED);
290 mWidget = nullptr;
291 mRegistered = false;
294 void nsBaseWidget::Shutdown() {
295 NotifyLiveResizeStopped();
296 DestroyCompositor();
297 FreeLocalesChangedObserver();
298 FreeShutdownObserver();
301 void nsBaseWidget::QuitIME() {
302 IMEStateManager::WidgetOnQuit(this);
303 this->mIMEHasQuit = true;
306 void nsBaseWidget::DestroyCompositor() {
307 RevokeTransactionIdAllocator();
309 // We release this before releasing the compositor, since it may hold the
310 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
311 // trigger a paint, creating a new compositor, and we don't want to re-use
312 // the old vsync dispatcher.
313 if (mCompositorVsyncDispatcher) {
314 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
316 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
317 mCompositorVsyncDispatcher->Shutdown();
318 mCompositorVsyncDispatcher = nullptr;
321 // The compositor shutdown sequence looks like this:
322 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
323 // 2. CompositorBridgeChild synchronously sends WillClose.
324 // 3. CompositorBridgeParent releases some resources (such as the layer
325 // manager, compositor, and widget).
326 // 4. CompositorBridgeChild::Destroy returns.
327 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
328 // compositor thread when the I/O thread closes the IPC channel.
329 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
330 // releases the reference CompositorBridgeParent holds to itself.
332 // When CompositorSession::Shutdown returns, we assume the compositor is gone
333 // or will be gone very soon.
334 if (mCompositorSession) {
335 ReleaseContentController();
336 mAPZC = nullptr;
337 SetCompositorWidgetDelegate(nullptr);
338 mCompositorBridgeChild = nullptr;
339 mCompositorSession->Shutdown();
340 mCompositorSession = nullptr;
344 // This prevents the layer manager from starting a new transaction during
345 // shutdown.
346 void nsBaseWidget::RevokeTransactionIdAllocator() {
347 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
348 return;
350 mWindowRenderer->AsWebRender()->SetTransactionIdAllocator(nullptr);
353 void nsBaseWidget::ReleaseContentController() {
354 if (mRootContentController) {
355 mRootContentController->Destroy();
356 mRootContentController = nullptr;
360 void nsBaseWidget::DestroyLayerManager() {
361 if (mWindowRenderer) {
362 mWindowRenderer->Destroy();
363 mWindowRenderer = nullptr;
365 DestroyCompositor();
368 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
370 void nsBaseWidget::FreeShutdownObserver() {
371 if (mShutdownObserver) {
372 mShutdownObserver->Unregister();
374 mShutdownObserver = nullptr;
377 void nsBaseWidget::FreeLocalesChangedObserver() {
378 if (mLocalesChangedObserver) {
379 mLocalesChangedObserver->Unregister();
381 mLocalesChangedObserver = nullptr;
384 //-------------------------------------------------------------------------
386 // nsBaseWidget destructor
388 //-------------------------------------------------------------------------
390 nsBaseWidget::~nsBaseWidget() {
391 if (mSwipeTracker) {
392 mSwipeTracker->Destroy();
393 mSwipeTracker = nullptr;
396 IMEStateManager::WidgetDestroyed(this);
398 FreeLocalesChangedObserver();
399 FreeShutdownObserver();
400 DestroyLayerManager();
402 #ifdef NOISY_WIDGET_LEAKS
403 gNumWidgets--;
404 printf("WIDGETS- = %d\n", gNumWidgets);
405 #endif
408 //-------------------------------------------------------------------------
410 // Basic create.
412 //-------------------------------------------------------------------------
413 void nsBaseWidget::BaseCreate(nsIWidget* aParent, widget::InitData* aInitData) {
414 if (aInitData) {
415 mWindowType = aInitData->mWindowType;
416 mBorderStyle = aInitData->mBorderStyle;
417 mPopupLevel = aInitData->mPopupLevel;
418 mPopupType = aInitData->mPopupHint;
419 mHasRemoteContent = aInitData->mHasRemoteContent;
420 mIsPIPWindow = aInitData->mPIPWindow;
423 mParent = aParent;
424 if (mParent) {
425 mParent->AddToChildList(this);
429 void nsIWidget::ClearParent() {
430 if (!mParent) {
431 return;
433 nsCOMPtr<nsIWidget> kungFuDeathGrip = this;
434 nsCOMPtr<nsIWidget> oldParent = mParent;
435 oldParent->RemoveFromChildList(this);
436 mParent = nullptr;
437 DidClearParent(oldParent);
440 void nsIWidget::RemoveAllChildren() {
441 while (nsCOMPtr<nsIWidget> kid = mLastChild) {
442 kid->ClearParent();
443 MOZ_ASSERT(kid != mLastChild);
447 //-------------------------------------------------------------------------
449 // Accessor functions to get/set the client data
451 //-------------------------------------------------------------------------
453 nsIWidgetListener* nsBaseWidget::GetWidgetListener() const {
454 return mWidgetListener;
457 void nsBaseWidget::SetWidgetListener(nsIWidgetListener* aWidgetListener) {
458 mWidgetListener = aWidgetListener;
461 already_AddRefed<nsIWidget> nsBaseWidget::CreateChild(
462 const LayoutDeviceIntRect& aRect, widget::InitData& aInitData) {
463 nsCOMPtr<nsIWidget> widget;
464 switch (mWidgetType) {
465 case WidgetType::Native: {
466 if (aInitData.mWindowType == WindowType::Popup) {
467 widget = AllocateChildPopupWidget();
468 } else {
469 widget = nsIWidget::CreateChildWindow();
471 break;
473 case WidgetType::Headless:
474 widget = nsIWidget::CreateHeadlessWidget();
475 break;
476 case WidgetType::Puppet: {
477 // This really only should happen in crashtests that have menupopups.
478 MOZ_ASSERT(aInitData.mWindowType == WindowType::Popup,
479 "Creating non-popup puppet widget?");
480 widget = nsIWidget::CreatePuppetWidget(nullptr);
481 break;
485 if (!widget) {
486 return nullptr;
489 if (mNeedFastSnaphot) {
490 widget->SetNeedFastSnaphot();
493 if (NS_FAILED(widget->Create(this, aRect, &aInitData))) {
494 return nullptr;
497 return widget.forget();
500 // Attach a view to our widget which we'll send events to.
501 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents) {
502 NS_ASSERTION((mWindowType == WindowType::TopLevel ||
503 mWindowType == WindowType::Dialog ||
504 mWindowType == WindowType::Invisible ||
505 mWindowType == WindowType::Child),
506 "Can't attach to window of that type");
508 mUseAttachedEvents = aUseAttachedEvents;
511 nsIWidgetListener* nsBaseWidget::GetAttachedWidgetListener() const {
512 return mAttachedWidgetListener;
515 nsIWidgetListener* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
516 return mPreviouslyAttachedWidgetListener;
519 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
520 nsIWidgetListener* aListener) {
521 mPreviouslyAttachedWidgetListener = aListener;
524 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener* aListener) {
525 mAttachedWidgetListener = aListener;
528 //-------------------------------------------------------------------------
530 // Close this nsBaseWidget
532 //-------------------------------------------------------------------------
533 void nsBaseWidget::Destroy() {
534 DestroyCompositor();
536 // Just in case our parent is the only ref to us
537 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
538 // disconnect from the parent
539 if (mParent) {
540 mParent->RemoveFromChildList(this);
541 mParent = nullptr;
543 // disconnect from the children
544 RemoveAllChildren();
547 nsIWidget* nsIWidget::GetTopLevelWidget() {
548 auto* cur = this;
549 while (true) {
550 if (cur->IsTopLevelWidget()) {
551 break;
553 nsIWidget* parent = cur->GetParent();
554 if (!parent) {
555 break;
557 cur = parent;
559 return cur;
562 float nsBaseWidget::GetDPI() { return 96.0f; }
564 void nsBaseWidget::NotifyAPZOfDPIChange() {
565 if (mAPZC) {
566 mAPZC->SetDPI(GetDPI());
570 CSSToLayoutDeviceScale nsIWidget::GetDefaultScale() {
571 double devPixelsPerCSSPixel = StaticPrefs::layout_css_devPixelsPerPx();
573 if (devPixelsPerCSSPixel <= 0.0) {
574 devPixelsPerCSSPixel = GetDefaultScaleInternal();
577 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel);
580 nsIntSize nsIWidget::CustomCursorSize(const Cursor& aCursor) {
581 MOZ_ASSERT(aCursor.IsCustom());
582 int32_t width = 0;
583 int32_t height = 0;
584 aCursor.mContainer->GetWidth(&width);
585 aCursor.mContainer->GetHeight(&height);
586 aCursor.mResolution.ApplyTo(width, height);
587 return {width, height};
590 LayoutDeviceIntSize nsIWidget::ClientToWindowSizeDifference() {
591 auto margin = ClientToWindowMargin();
592 MOZ_ASSERT(margin.top >= 0, "Window should be bigger than client area");
593 MOZ_ASSERT(margin.left >= 0, "Window should be bigger than client area");
594 MOZ_ASSERT(margin.right >= 0, "Window should be bigger than client area");
595 MOZ_ASSERT(margin.bottom >= 0, "Window should be bigger than client area");
596 return {margin.LeftRight(), margin.TopBottom()};
599 RefPtr<mozilla::VsyncDispatcher> nsIWidget::GetVsyncDispatcher() {
600 return nullptr;
603 //-------------------------------------------------------------------------
605 // Add a child to the list of children
607 //-------------------------------------------------------------------------
608 void nsIWidget::AddToChildList(nsIWidget* aChild) {
609 MOZ_ASSERT(!aChild->GetNextSibling() && !aChild->GetPrevSibling(),
610 "aChild not properly removed from its old child list");
612 if (!mFirstChild) {
613 mFirstChild = mLastChild = aChild;
614 } else {
615 // append to the list
616 MOZ_ASSERT(mLastChild);
617 MOZ_ASSERT(!mLastChild->GetNextSibling());
618 mLastChild->SetNextSibling(aChild);
619 aChild->SetPrevSibling(mLastChild);
620 mLastChild = aChild;
624 //-------------------------------------------------------------------------
626 // Remove a child from the list of children
628 //-------------------------------------------------------------------------
629 void nsIWidget::RemoveFromChildList(nsIWidget* aChild) {
630 MOZ_ASSERT(aChild->GetParent() == this, "Not one of our kids!");
632 if (mLastChild == aChild) {
633 mLastChild = mLastChild->GetPrevSibling();
635 if (mFirstChild == aChild) {
636 mFirstChild = mFirstChild->GetNextSibling();
639 // Now remove from the list. Make sure that we pass ownership of the tail
640 // of the list correctly before we have aChild let go of it.
641 nsIWidget* prev = aChild->GetPrevSibling();
642 nsIWidget* next = aChild->GetNextSibling();
643 if (prev) {
644 prev->SetNextSibling(next);
646 if (next) {
647 next->SetPrevSibling(prev);
650 aChild->SetNextSibling(nullptr);
651 aChild->SetPrevSibling(nullptr);
654 void nsBaseWidget::GetWorkspaceID(nsAString& workspaceID) {
655 workspaceID.Truncate();
658 void nsBaseWidget::MoveToWorkspace(const nsAString& workspaceID) {
659 // Noop.
662 //-------------------------------------------------------------------------
664 // Get this component cursor
666 //-------------------------------------------------------------------------
668 void nsBaseWidget::SetCursor(const Cursor& aCursor) { mCursor = aCursor; }
670 void nsBaseWidget::SetCustomCursorAllowed(bool aIsAllowed) {
671 if (aIsAllowed != mCustomCursorAllowed) {
672 mCustomCursorAllowed = aIsAllowed;
673 mUpdateCursor = true;
674 SetCursor(mCursor);
678 //-------------------------------------------------------------------------
680 // Window transparency methods
682 //-------------------------------------------------------------------------
684 void nsBaseWidget::SetTransparencyMode(TransparencyMode aMode) {}
686 TransparencyMode nsBaseWidget::GetTransparencyMode() {
687 return TransparencyMode::Opaque;
690 /* virtual */
691 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage,
692 uint16_t aDuration,
693 nsISupports* aData,
694 nsIRunnable* aCallback) {
695 MOZ_ASSERT_UNREACHABLE(
696 "Should never call PerformFullscreenTransition on nsBaseWidget");
699 //-------------------------------------------------------------------------
701 // Put the window into full-screen mode
703 //-------------------------------------------------------------------------
704 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen) {
705 #define MOZ_FORMAT_RECT(fmtstr) "[" fmtstr "," fmtstr " " fmtstr "x" fmtstr "]"
706 #define MOZ_SPLAT_RECT(rect) \
707 (rect).X(), (rect).Y(), (rect).Width(), (rect).Height()
709 // Windows which can be made fullscreen are exactly those which are located on
710 // the desktop, rather than being a child of some other window.
711 MOZ_DIAGNOSTIC_ASSERT(BoundsUseDesktopPixels(),
712 "non-desktop windows cannot be made fullscreen");
714 // Ensure that the OS chrome is hidden/shown before we resize and/or exit the
715 // function.
717 // HideWindowChrome() may (depending on platform, implementation details, and
718 // OS-level user preferences) alter the reported size of the window. The
719 // obvious and principled solution is socks-and-shoes:
720 // - On entering fullscreen mode: hide window chrome, then perform resize.
721 // - On leaving fullscreen mode: unperform resize, then show window chrome.
723 // ... unfortunately, HideWindowChrome() requires Resize() to be called
724 // afterwards (see bug 498835), which prevents this from being done in a
725 // straightforward way.
727 // Instead, we always call HideWindowChrome() just before we call Resize().
728 // This at least ensures that our measurements are consistently taken in a
729 // pre-transition state.
731 // ... unfortunately again, coupling HideWindowChrome() to Resize() means that
732 // we have to worry about the possibility of control flows that don't call
733 // Resize() at all. (That shouldn't happen, but it's not trivial to rule out.)
734 // We therefore set up a fallback to fix up the OS chrome if it hasn't been
735 // done at exit time.
736 bool hasAdjustedOSChrome = false;
737 const auto adjustOSChrome = [&]() {
738 if (hasAdjustedOSChrome) {
739 MOZ_ASSERT_UNREACHABLE("window chrome should only be adjusted once");
740 return;
742 HideWindowChrome(aFullScreen);
743 hasAdjustedOSChrome = true;
745 const auto adjustChromeOnScopeExit = MakeScopeExit([&]() {
746 if (hasAdjustedOSChrome) {
747 return;
750 MOZ_LOG(sBaseWidgetLog, LogLevel::Warning,
751 ("window was not resized within InfallibleMakeFullScreen()"));
753 // Hide chrome and "resize" the window to its current size.
754 auto rect = GetBounds();
755 adjustOSChrome();
756 Resize(rect.X(), rect.Y(), rect.Width(), rect.Height(), true);
759 // Attempt to resize to `rect`.
761 // Returns the actual rectangle resized to. (This may differ from `rect`, if
762 // the OS is unhappy with it. See bug 1786226.)
763 const auto doReposition = [&](auto rect) -> void {
764 static_assert(std::is_base_of_v<DesktopPixel,
765 std::remove_reference_t<decltype(rect)>>,
766 "doReposition requires a rectangle using desktop pixels");
768 if (MOZ_LOG_TEST(sBaseWidgetLog, LogLevel::Debug)) {
769 const DesktopRect previousSize =
770 GetScreenBounds() / GetDesktopToDeviceScale();
771 MOZ_LOG(sBaseWidgetLog, LogLevel::Debug,
772 ("before resize: " MOZ_FORMAT_RECT("%f"),
773 MOZ_SPLAT_RECT(previousSize)));
776 adjustOSChrome();
777 Resize(rect.X(), rect.Y(), rect.Width(), rect.Height(), true);
779 if (MOZ_LOG_TEST(sBaseWidgetLog, LogLevel::Warning)) {
780 // `rect` may have any underlying data type; coerce to float to
781 // simplify printf-style logging
782 const gfx::RectTyped<DesktopPixel, float> rectAsFloat{rect};
784 // The OS may have objected to the target position. That's not necessarily
785 // a problem -- it'll happen regularly on Macs with camera notches in the
786 // monitor, for instance (see bug 1786226) -- but it probably deserves to
787 // be called out.
789 // Since there's floating-point math involved, the actual values may be
790 // off by a few ulps -- as an upper bound, perhaps 8 * FLT_EPSILON *
791 // max(MOZ_SPLAT_RECT(rect)) -- but 0.01 should be several orders of
792 // magnitude bigger than that.
794 const auto postResizeRectRaw = GetScreenBounds();
795 const auto postResizeRect = postResizeRectRaw / GetDesktopToDeviceScale();
796 const bool succeeded = postResizeRect.WithinEpsilonOf(rectAsFloat, 0.01);
798 if (succeeded) {
799 MOZ_LOG(sBaseWidgetLog, LogLevel::Debug,
800 ("resized to: " MOZ_FORMAT_RECT("%f"),
801 MOZ_SPLAT_RECT(rectAsFloat)));
802 } else {
803 MOZ_LOG(sBaseWidgetLog, LogLevel::Warning,
804 ("attempted to resize to: " MOZ_FORMAT_RECT("%f"),
805 MOZ_SPLAT_RECT(rectAsFloat)));
806 MOZ_LOG(sBaseWidgetLog, LogLevel::Warning,
807 ("... but ended up at: " MOZ_FORMAT_RECT("%f"),
808 MOZ_SPLAT_RECT(postResizeRect)));
811 MOZ_LOG(
812 sBaseWidgetLog, LogLevel::Verbose,
813 ("(... which, before DPI adjustment, is:" MOZ_FORMAT_RECT("%d") ")",
814 MOZ_SPLAT_RECT(postResizeRectRaw)));
818 if (aFullScreen) {
819 if (!mSavedBounds) {
820 mSavedBounds = Some(FullscreenSavedState());
822 // save current position
823 mSavedBounds->windowRect = GetScreenBounds() / GetDesktopToDeviceScale();
825 nsCOMPtr<nsIScreen> screen = GetWidgetScreen();
826 if (!screen) {
827 return;
830 // Move to fill the screen.
831 doReposition(screen->GetRectDisplayPix());
832 // Save off the new position. (This may differ from GetRectDisplayPix(), if
833 // the OS was unhappy with it. See bug 1786226.)
834 mSavedBounds->screenRect = GetScreenBounds() / GetDesktopToDeviceScale();
835 } else {
836 if (!mSavedBounds) {
837 // This should never happen, at present, since we don't make windows
838 // fullscreen at their creation time; but it's not logically impossible.
839 MOZ_ASSERT(false, "fullscreen window did not have saved position");
840 return;
843 // Figure out where to go from here.
845 // Fortunately, since we're currently fullscreen (and other code should be
846 // handling _keeping_ us fullscreen even after display-layout changes),
847 // there's an obvious choice for which display we should attach to; all we
848 // need to determine is where on that display we should go.
850 const DesktopRect currentWinRect =
851 GetScreenBounds() / GetDesktopToDeviceScale();
853 // Optimization: if where we are is where we were, then where we originally
854 // came from is where we're going to go.
855 if (currentWinRect == DesktopRect(mSavedBounds->screenRect)) {
856 MOZ_LOG(sBaseWidgetLog, LogLevel::Debug,
857 ("no location change detected; returning to saved location"));
858 doReposition(mSavedBounds->windowRect);
859 return;
863 General case: figure out where we're going to go by dividing where we are
864 by where we were, and then multiplying by where we originally came from.
866 Less abstrusely: resize so that we occupy the same proportional position
867 on our current display after leaving fullscreen as we occupied on our
868 previous display before entering fullscreen.
870 (N.B.: We do not clamp. If we were only partially on the old display,
871 we'll be only partially on the new one, too.)
874 MOZ_LOG(sBaseWidgetLog, LogLevel::Debug,
875 ("location change detected; computing new destination"));
877 // splat: convert an arbitrary Rect into a tuple, for syntactic convenience.
878 const auto splat = [](auto rect) {
879 return std::tuple(rect.X(), rect.Y(), rect.Width(), rect.Height());
882 // remap: find the unique affine mapping which transforms `src` to `dst`,
883 // and apply it to `val`.
884 using Range = std::pair<float, float>;
885 const auto remap = [](Range dst, Range src, float val) {
886 // linear interpolation and its inverse: lerp(a, b, invlerp(a, b, t)) == t
887 const auto lerp = [](float lo, float hi, float t) {
888 return lo + t * (hi - lo);
890 const auto invlerp = [](float lo, float hi, float mid) {
891 return (mid - lo) / (hi - lo);
894 const auto [dst_a, dst_b] = dst;
895 const auto [src_a, src_b] = src;
896 return lerp(dst_a, dst_b, invlerp(src_a, src_b, val));
899 // original position
900 const auto [px, py, pw, ph] = splat(mSavedBounds->windowRect);
901 // source desktop rect
902 const auto [sx, sy, sw, sh] = splat(mSavedBounds->screenRect);
903 // target desktop rect
904 const auto [tx, ty, tw, th] = splat(currentWinRect);
906 const float nx = remap({tx, tx + tw}, {sx, sx + sw}, px);
907 const float ny = remap({ty, ty + th}, {sy, sy + sh}, py);
908 const float nw = remap({0, tw}, {0, sw}, pw);
909 const float nh = remap({0, th}, {0, sh}, ph);
911 doReposition(DesktopRect{nx, ny, nw, nh});
914 #undef MOZ_SPLAT_RECT
915 #undef MOZ_FORMAT_RECT
918 nsresult nsBaseWidget::MakeFullScreen(bool aFullScreen) {
919 InfallibleMakeFullScreen(aFullScreen);
920 return NS_OK;
923 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
924 nsBaseWidget* aWidget, gfxContext* aTarget, BufferMode aDoubleBuffering)
925 : mWidget(aWidget) {
926 WindowRenderer* renderer = mWidget->GetWindowRenderer();
927 if (renderer->AsFallback()) {
928 mRenderer = renderer->AsFallback();
929 mRenderer->SetTarget(aTarget, aDoubleBuffering);
933 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
934 if (mRenderer) {
935 mRenderer->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE);
939 bool nsBaseWidget::IsSmallPopup() const {
940 return mWindowType == WindowType::Popup && mPopupType != PopupType::Panel;
943 bool nsBaseWidget::ComputeShouldAccelerate() {
944 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING) &&
945 (WidgetTypeSupportsAcceleration() ||
946 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
949 bool nsBaseWidget::UseAPZ() const {
950 // APZ disabled globally
951 if (!gfxPlatform::AsyncPanZoomEnabled()) {
952 return false;
955 // Always use APZ for top-level windows
956 if (mWindowType == WindowType::TopLevel || mWindowType == WindowType::Child) {
957 return true;
960 // Never use APZ for tooltips
961 if (mWindowType == WindowType::Popup && mPopupType == PopupType::Tooltip) {
962 return false;
965 if (!StaticPrefs::apz_popups_enabled()) {
966 return false;
969 if (HasRemoteContent()) {
970 return mWindowType == WindowType::Dialog ||
971 mWindowType == WindowType::Popup;
972 } else if (StaticPrefs::apz_popups_without_remote_enabled()) {
973 return mWindowType == WindowType::Popup;
976 return false;
979 void nsBaseWidget::CreateCompositor() {
980 LayoutDeviceIntRect rect = GetBounds();
981 CreateCompositor(rect.Width(), rect.Height());
984 void nsIWidget::PauseOrResumeCompositor(bool aPause) {
985 auto* renderer = GetRemoteRenderer();
986 if (!renderer) {
987 return;
989 if (aPause) {
990 renderer->SendPause();
991 } else {
992 renderer->SendResume();
996 already_AddRefed<GeckoContentController>
997 nsBaseWidget::CreateRootContentController() {
998 RefPtr<GeckoContentController> controller =
999 new ChromeProcessController(this, mAPZEventState, mAPZC);
1000 return controller.forget();
1003 void nsBaseWidget::ConfigureAPZCTreeManager() {
1004 MOZ_ASSERT(NS_IsMainThread());
1005 MOZ_ASSERT(mAPZC);
1007 mAPZC->SetDPI(GetDPI());
1009 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
1010 KeyboardMap map = RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
1011 mAPZC->SetKeyboardMap(map);
1014 ContentReceivedInputBlockCallback callback(
1015 [treeManager = RefPtr{mAPZC.get()}](uint64_t aInputBlockId,
1016 bool aPreventDefault) {
1017 MOZ_ASSERT(NS_IsMainThread());
1018 treeManager->ContentReceivedInputBlock(aInputBlockId, aPreventDefault);
1020 mAPZEventState = new APZEventState(this, std::move(callback));
1022 mRootContentController = CreateRootContentController();
1023 if (mRootContentController) {
1024 mCompositorSession->SetContentController(mRootContentController);
1027 // When APZ is enabled, we can actually enable raw touch events because we
1028 // have code that can deal with them properly. If APZ is not enabled, this
1029 // function doesn't get called.
1030 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
1031 RegisterTouchWindow();
1035 void nsBaseWidget::ConfigureAPZControllerThread() {
1036 // By default the controller thread is the main thread.
1037 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
1040 void nsBaseWidget::SetConfirmedTargetAPZC(
1041 uint64_t aInputBlockId,
1042 const nsTArray<ScrollableLayerGuid>& aTargets) const {
1043 mAPZC->SetTargetAPZC(aInputBlockId, aTargets);
1046 void nsBaseWidget::UpdateZoomConstraints(
1047 const uint32_t& aPresShellId, const ScrollableLayerGuid::ViewID& aViewId,
1048 const Maybe<ZoomConstraints>& aConstraints) {
1049 if (!mCompositorSession || !mAPZC) {
1050 MOZ_ASSERT_IF(mInitialZoomConstraints,
1051 mInitialZoomConstraints->mViewID == aViewId);
1052 if (aConstraints) {
1053 // We have some constraints, but the compositor and APZC aren't
1054 // created yet. Save these so we can use them later.
1055 mInitialZoomConstraints = Some(
1056 InitialZoomConstraints(aPresShellId, aViewId, aConstraints.ref()));
1057 } else {
1058 mInitialZoomConstraints.reset();
1060 return;
1062 LayersId layersId = mCompositorSession->RootLayerTreeId();
1063 mAPZC->UpdateZoomConstraints(
1064 ScrollableLayerGuid(layersId, aPresShellId, aViewId), aConstraints);
1067 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC; }
1069 nsEventStatus nsBaseWidget::ProcessUntransformedAPZEvent(
1070 WidgetInputEvent* aEvent, const APZEventResult& aApzResult) {
1071 MOZ_ASSERT(NS_IsMainThread());
1072 ScrollableLayerGuid targetGuid = aApzResult.mTargetGuid;
1073 uint64_t inputBlockId = aApzResult.mInputBlockId;
1074 InputAPZContext context(aApzResult.mTargetGuid, inputBlockId,
1075 aApzResult.GetStatus());
1077 // Make a copy of the original event for the APZCCallbackHelper helpers that
1078 // we call later, because the event passed to DispatchEvent can get mutated in
1079 // ways that we don't want (i.e. touch points can get stripped out).
1080 nsEventStatus status;
1081 UniquePtr<WidgetEvent> original(aEvent->Duplicate());
1082 DispatchEvent(aEvent, status);
1084 if (mAPZC && !InputAPZContext::WasRoutedToChildProcess() &&
1085 !InputAPZContext::WasDropped() && inputBlockId) {
1086 // EventStateManager did not route the event into the child process and
1087 // the event was dispatched in the parent process.
1088 // It's safe to communicate to APZ that the event has been processed.
1089 // Note that here aGuid.mLayersId might be different from
1090 // mCompositorSession->RootLayerTreeId() because the event might have gotten
1091 // hit-tested by APZ to be targeted at a child process, but a parent process
1092 // event listener called preventDefault on it. In that case aGuid.mLayersId
1093 // would still be the layers id for the child process, but the event would
1094 // not have actually gotten routed to the child process. The main-thread
1095 // hit-test result therefore needs to use the parent process layers id.
1096 LayersId rootLayersId = mCompositorSession->RootLayerTreeId();
1098 RefPtr<DisplayportSetListener> postLayerization;
1099 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
1100 nsTArray<TouchBehaviorFlags> allowedTouchBehaviors;
1101 if (touchEvent->mMessage == eTouchStart) {
1102 auto& originalEvent = *original->AsTouchEvent();
1103 MOZ_ASSERT(NS_IsMainThread());
1104 allowedTouchBehaviors = TouchActionHelper::GetAllowedTouchBehavior(
1105 this, GetDocument(), originalEvent);
1106 if (!allowedTouchBehaviors.IsEmpty()) {
1107 mAPZC->SetAllowedTouchBehavior(inputBlockId, allowedTouchBehaviors);
1109 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1110 this, GetDocument(), originalEvent, rootLayersId, inputBlockId);
1112 mAPZEventState->ProcessTouchEvent(*touchEvent, targetGuid, inputBlockId,
1113 aApzResult.GetStatus(), status,
1114 std::move(allowedTouchBehaviors));
1115 } else if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1116 MOZ_ASSERT(wheelEvent->mFlags.mHandledByAPZ);
1117 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1118 this, GetDocument(), *original->AsWheelEvent(), rootLayersId,
1119 inputBlockId);
1120 if (wheelEvent->mCanTriggerSwipe) {
1121 ReportSwipeStarted(inputBlockId, wheelEvent->TriggersSwipe());
1123 mAPZEventState->ProcessWheelEvent(*wheelEvent, inputBlockId);
1124 } else if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1125 MOZ_ASSERT(mouseEvent->mFlags.mHandledByAPZ);
1126 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1127 this, GetDocument(), *original->AsMouseEvent(), rootLayersId,
1128 inputBlockId);
1129 mAPZEventState->ProcessMouseEvent(*mouseEvent, inputBlockId);
1131 if (postLayerization) {
1132 postLayerization->Register();
1136 return status;
1139 template <class InputType, class EventType>
1140 class DispatchEventOnMainThread : public Runnable {
1141 public:
1142 DispatchEventOnMainThread(const InputType& aInput, nsBaseWidget* aWidget,
1143 const APZEventResult& aAPZResult)
1144 : mozilla::Runnable("DispatchEventOnMainThread"),
1145 mInput(aInput),
1146 mWidget(aWidget),
1147 mAPZResult(aAPZResult) {}
1149 NS_IMETHOD Run() override {
1150 EventType event = mInput.ToWidgetEvent(mWidget);
1151 mWidget->ProcessUntransformedAPZEvent(&event, mAPZResult);
1152 return NS_OK;
1155 private:
1156 InputType mInput;
1157 nsBaseWidget* mWidget;
1158 APZEventResult mAPZResult;
1161 template <>
1162 NS_IMETHODIMP DispatchEventOnMainThread<MouseInput, WidgetMouseEvent>::Run() {
1163 MOZ_ASSERT(
1164 !mInput.IsPointerEventType(),
1165 "Please use DispatchEventOnMainThread<MouseInput, WidgetPointerEvent>");
1166 WidgetMouseEvent event = mInput.ToWidgetEvent<WidgetMouseEvent>(mWidget);
1167 mWidget->ProcessUntransformedAPZEvent(&event, mAPZResult);
1168 return NS_OK;
1171 template <>
1172 NS_IMETHODIMP DispatchEventOnMainThread<MouseInput, WidgetPointerEvent>::Run() {
1173 MOZ_ASSERT(
1174 mInput.IsPointerEventType(),
1175 "Please use DispatchEventOnMainThread<MouseInput, WidgetMouseEvent>");
1176 WidgetPointerEvent event = mInput.ToWidgetEvent<WidgetPointerEvent>(mWidget);
1177 mWidget->ProcessUntransformedAPZEvent(&event, mAPZResult);
1178 return NS_OK;
1181 template <class InputType, class EventType>
1182 class DispatchInputOnControllerThread : public Runnable {
1183 public:
1184 enum class APZOnly { Yes, No };
1185 DispatchInputOnControllerThread(const EventType& aEvent,
1186 IAPZCTreeManager* aAPZC,
1187 nsBaseWidget* aWidget,
1188 APZOnly aAPZOnly = APZOnly::No)
1189 : mozilla::Runnable("DispatchInputOnControllerThread"),
1190 mMainMessageLoop(MessageLoop::current()),
1191 mInput(aEvent),
1192 mAPZC(aAPZC),
1193 mWidget(aWidget),
1194 mAPZOnly(aAPZOnly) {}
1196 NS_IMETHOD Run() override {
1197 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(mInput);
1198 if (mAPZOnly == APZOnly::Yes ||
1199 result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1200 return NS_OK;
1202 RefPtr<Runnable> r = new DispatchEventOnMainThread<InputType, EventType>(
1203 mInput, mWidget, result);
1204 mMainMessageLoop->PostTask(r.forget());
1205 return NS_OK;
1208 private:
1209 MessageLoop* mMainMessageLoop;
1210 InputType mInput;
1211 RefPtr<IAPZCTreeManager> mAPZC;
1212 nsBaseWidget* mWidget;
1213 const APZOnly mAPZOnly;
1216 void nsBaseWidget::DispatchTouchInput(MultiTouchInput& aInput,
1217 uint16_t aInputSource) {
1218 MOZ_ASSERT(NS_IsMainThread());
1219 MOZ_ASSERT(aInputSource ==
1220 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH ||
1221 aInputSource == mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN);
1222 if (mAPZC) {
1223 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1225 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1226 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1227 return;
1230 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1231 ProcessUntransformedAPZEvent(&event, result);
1232 } else {
1233 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1235 nsEventStatus status;
1236 DispatchEvent(&event, status);
1240 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput& aInput) {
1241 MOZ_ASSERT(NS_IsMainThread());
1242 if (mAPZC) {
1243 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1245 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1246 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1247 return;
1250 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1251 ProcessUntransformedAPZEvent(&event, result);
1252 } else {
1253 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1254 nsEventStatus status;
1255 DispatchEvent(&event, status);
1259 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput& aInput) {
1260 MOZ_ASSERT(NS_IsMainThread());
1261 if (mAPZC) {
1262 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1263 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1265 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1266 return;
1268 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1269 ProcessUntransformedAPZEvent(&event, result);
1270 } else {
1271 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1272 nsEventStatus status;
1273 DispatchEvent(&event, status);
1277 nsIWidget::ContentAndAPZEventStatus nsBaseWidget::DispatchInputEvent(
1278 WidgetInputEvent* aEvent) {
1279 nsIWidget::ContentAndAPZEventStatus status;
1280 MOZ_ASSERT(NS_IsMainThread());
1282 if (mAPZC) {
1283 if (APZThreadUtils::IsControllerThread()) {
1284 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1285 status.mApzStatus = result.GetStatus();
1286 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1287 return status;
1289 status.mContentStatus = ProcessUntransformedAPZEvent(aEvent, result);
1290 return status;
1292 // Most drag events aren't able to converted to MouseEvent except to
1293 // eDragStart and eDragEnd.
1294 const bool canDispatchToApzc =
1295 !aEvent->AsDragEvent() ||
1296 aEvent->AsDragEvent()->CanConvertToInputData();
1297 if (canDispatchToApzc) {
1298 if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1299 RefPtr<Runnable> r =
1300 new DispatchInputOnControllerThread<ScrollWheelInput,
1301 WidgetWheelEvent>(*wheelEvent,
1302 mAPZC, this);
1303 APZThreadUtils::RunOnControllerThread(std::move(r));
1304 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1305 return status;
1307 if (WidgetPointerEvent* pointerEvent = aEvent->AsPointerEvent()) {
1308 MOZ_ASSERT(aEvent->mMessage == eContextMenu);
1309 RefPtr<Runnable> r =
1310 new DispatchInputOnControllerThread<MouseInput, WidgetPointerEvent>(
1311 *pointerEvent, mAPZC, this);
1312 APZThreadUtils::RunOnControllerThread(std::move(r));
1313 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1314 return status;
1316 if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1317 RefPtr<Runnable> r =
1318 new DispatchInputOnControllerThread<MouseInput, WidgetMouseEvent>(
1319 *mouseEvent, mAPZC, this);
1320 APZThreadUtils::RunOnControllerThread(std::move(r));
1321 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1322 return status;
1324 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
1325 RefPtr<Runnable> r =
1326 new DispatchInputOnControllerThread<MultiTouchInput,
1327 WidgetTouchEvent>(*touchEvent,
1328 mAPZC, this);
1329 APZThreadUtils::RunOnControllerThread(std::move(r));
1330 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1331 return status;
1333 // Allow dispatching keyboard/drag events on Gecko thread
1334 // without sending them to APZ
1336 // FIXME: APZ can handle keyboard events now, we should
1337 // be sending them to APZ here
1338 MOZ_ASSERT(aEvent->AsKeyboardEvent() || aEvent->AsDragEvent());
1342 DispatchEvent(aEvent, status.mContentStatus);
1343 return status;
1346 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent* aEvent) {
1347 MOZ_ASSERT(NS_IsMainThread());
1348 if (mAPZC) {
1349 if (APZThreadUtils::IsControllerThread()) {
1350 mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1351 return;
1354 if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1355 RefPtr<Runnable> r =
1356 new DispatchInputOnControllerThread<MouseInput, WidgetMouseEvent>(
1357 *mouseEvent, mAPZC, this,
1358 DispatchInputOnControllerThread<MouseInput,
1359 WidgetMouseEvent>::APZOnly::Yes);
1360 APZThreadUtils::RunOnControllerThread(std::move(r));
1361 return;
1364 MOZ_ASSERT_UNREACHABLE("Not implemented yet");
1368 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent& event) {
1369 nsEventStatus status;
1370 DispatchEvent(&event, status);
1371 return ConvertStatus(status);
1374 Document* nsBaseWidget::GetDocument() const {
1375 if (mWidgetListener) {
1376 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1377 return presShell->GetDocument();
1380 return nullptr;
1383 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1384 // Parent directly listens to the vsync source whereas
1385 // child process communicate via IPC
1386 // Should be called AFTER gfxPlatform is initialized
1387 if (XRE_IsParentProcess()) {
1388 if (!mCompositorVsyncDispatcherLock) {
1389 mCompositorVsyncDispatcherLock =
1390 MakeUnique<Mutex>("mCompositorVsyncDispatcherLock");
1392 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1393 if (!mCompositorVsyncDispatcher) {
1394 RefPtr<VsyncDispatcher> vsyncDispatcher =
1395 gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
1396 mCompositorVsyncDispatcher =
1397 new CompositorVsyncDispatcher(std::move(vsyncDispatcher));
1402 already_AddRefed<CompositorVsyncDispatcher>
1403 nsBaseWidget::GetCompositorVsyncDispatcher() {
1404 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
1406 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1407 RefPtr<CompositorVsyncDispatcher> dispatcher = mCompositorVsyncDispatcher;
1408 return dispatcher.forget();
1411 already_AddRefed<WebRenderLayerManager> nsBaseWidget::CreateCompositorSession(
1412 int aWidth, int aHeight, CompositorOptions* aOptionsOut) {
1413 MOZ_ASSERT(aOptionsOut);
1415 do {
1416 CreateCompositorVsyncDispatcher();
1418 gfx::GPUProcessManager* gpu = gfx::GPUProcessManager::Get();
1419 // Make sure GPU process is ready for use.
1420 // If it failed to connect to GPU process, GPU process usage is disabled in
1421 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1422 nsresult rv = gpu->EnsureGPUReady();
1423 if (NS_WARN_IF(rv == NS_ERROR_ILLEGAL_DURING_SHUTDOWN)) {
1424 return nullptr;
1427 // If widget type does not supports acceleration, we may be allowed to use
1428 // software WebRender instead.
1429 bool supportsAcceleration = WidgetTypeSupportsAcceleration();
1430 bool enableSWWR = true;
1431 if (supportsAcceleration ||
1432 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1433 enableSWWR = gfx::gfxVars::UseSoftwareWebRender();
1435 bool enableAPZ = UseAPZ();
1436 CompositorOptions options(enableAPZ, enableSWWR);
1438 #ifdef XP_WIN
1439 if (supportsAcceleration) {
1440 options.SetAllowSoftwareWebRenderD3D11(
1441 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1443 if (mNeedFastSnaphot) {
1444 options.SetNeedFastSnaphot(true);
1446 #elif defined(MOZ_WIDGET_ANDROID)
1447 MOZ_ASSERT(supportsAcceleration);
1448 options.SetAllowSoftwareWebRenderOGL(
1449 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1450 #elif defined(MOZ_WIDGET_GTK)
1451 if (supportsAcceleration) {
1452 options.SetAllowSoftwareWebRenderOGL(
1453 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1455 #endif
1457 #ifdef MOZ_WIDGET_ANDROID
1458 // Unconditionally set the compositor as initially paused, as we have not
1459 // yet had a chance to send the compositor surface to the GPU process. We
1460 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1461 // where we will also resume the compositor if required.
1462 options.SetInitiallyPaused(true);
1463 #else
1464 options.SetInitiallyPaused(CompositorInitiallyPaused());
1465 #endif
1467 RefPtr<WebRenderLayerManager> lm = new WebRenderLayerManager(this);
1469 uint64_t innerWindowId = 0;
1470 if (Document* doc = GetDocument()) {
1471 innerWindowId = doc->InnerWindowID();
1474 bool retry = false;
1475 mCompositorSession = gpu->CreateTopLevelCompositor(
1476 this, lm, GetDefaultScale(), options, UseExternalCompositingSurface(),
1477 gfx::IntSize(aWidth, aHeight), innerWindowId, &retry);
1479 if (mCompositorSession) {
1480 TextureFactoryIdentifier textureFactoryIdentifier;
1481 nsCString error;
1482 lm->Initialize(mCompositorSession->GetCompositorBridgeChild(),
1483 wr::AsPipelineId(mCompositorSession->RootLayerTreeId()),
1484 &textureFactoryIdentifier, error);
1485 if (textureFactoryIdentifier.mParentBackend != LayersBackend::LAYERS_WR) {
1486 retry = true;
1487 DestroyCompositor();
1488 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1489 gfx::GPUProcessManager::Get()->DisableWebRender(
1490 wr::WebRenderError::INITIALIZE, error);
1494 // We need to retry in a loop because the act of failing to create the
1495 // compositor can change our state (e.g. disable WebRender).
1496 if (mCompositorSession || !retry) {
1497 *aOptionsOut = options;
1498 return lm.forget();
1500 } while (true);
1503 void nsBaseWidget::CreateCompositor(int aWidth, int aHeight) {
1504 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1505 gfxPlatform::GetPlatform();
1507 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1508 "This function assumes OMTC");
1510 MOZ_ASSERT(!mCompositorSession && !mCompositorBridgeChild,
1511 "Should have properly cleaned up the previous PCompositor pair "
1512 "beforehand");
1514 if (mCompositorBridgeChild) {
1515 mCompositorBridgeChild->Destroy();
1518 // Recreating this is tricky, as we may still have an old and we need
1519 // to make sure it's properly destroyed by calling DestroyCompositor!
1521 // If we've already received a shutdown notification, don't try
1522 // create a new compositor.
1523 if (!mShutdownObserver) {
1524 return;
1527 // The controller thread must be configured before the compositor
1528 // session is created, so that the input bridge runs on the right
1529 // thread.
1530 ConfigureAPZControllerThread();
1532 CompositorOptions options;
1533 RefPtr<WebRenderLayerManager> lm =
1534 CreateCompositorSession(aWidth, aHeight, &options);
1535 if (!lm) {
1536 return;
1539 MOZ_ASSERT(mCompositorSession);
1540 mCompositorBridgeChild = mCompositorSession->GetCompositorBridgeChild();
1541 SetCompositorWidgetDelegate(
1542 mCompositorSession->GetCompositorWidgetDelegate());
1544 if (options.UseAPZ()) {
1545 mAPZC = mCompositorSession->GetAPZCTreeManager();
1546 ConfigureAPZCTreeManager();
1547 } else {
1548 mAPZC = nullptr;
1551 if (mInitialZoomConstraints) {
1552 UpdateZoomConstraints(mInitialZoomConstraints->mPresShellID,
1553 mInitialZoomConstraints->mViewID,
1554 Some(mInitialZoomConstraints->mConstraints));
1555 mInitialZoomConstraints.reset();
1558 TextureFactoryIdentifier textureFactoryIdentifier =
1559 lm->GetTextureFactoryIdentifier();
1560 MOZ_ASSERT(textureFactoryIdentifier.mParentBackend ==
1561 LayersBackend::LAYERS_WR);
1562 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1563 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1565 WindowUsesOMTC();
1567 mWindowRenderer = std::move(lm);
1569 // Only track compositors for top-level windows, since other window types
1570 // may use the basic compositor. Except on the OS X - see bug 1306383
1571 #if defined(XP_MACOSX)
1572 bool getCompositorFromThisWindow = true;
1573 #else
1574 bool getCompositorFromThisWindow = mWindowType == WindowType::TopLevel;
1575 #endif
1577 if (getCompositorFromThisWindow) {
1578 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1579 mWindowRenderer->GetCompositorBackendType());
1583 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession* aSession) {
1584 MOZ_ASSERT(aSession == mCompositorSession);
1585 DestroyLayerManager();
1588 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1589 return gfxPlatform::UsesOffMainThreadCompositing();
1592 WindowRenderer* nsBaseWidget::GetWindowRenderer() {
1593 if (!mWindowRenderer) {
1594 if (!mShutdownObserver) {
1595 // We are shutting down, do not try to re-create a LayerManager
1596 return nullptr;
1598 // Try to use an async compositor first, if possible
1599 if (ShouldUseOffMainThreadCompositing()) {
1600 CreateCompositor();
1603 if (!mWindowRenderer) {
1604 mWindowRenderer = CreateFallbackRenderer();
1607 return mWindowRenderer;
1610 WindowRenderer* nsBaseWidget::CreateFallbackRenderer() {
1611 return new FallbackRenderer;
1614 CompositorBridgeChild* nsBaseWidget::GetRemoteRenderer() {
1615 return mCompositorBridgeChild;
1618 void nsBaseWidget::ClearCachedWebrenderResources() {
1619 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
1620 return;
1622 mWindowRenderer->AsWebRender()->ClearCachedResources();
1625 void nsBaseWidget::ClearWebrenderAnimationResources() {
1626 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
1627 return;
1629 mWindowRenderer->AsWebRender()->ClearAnimationResources();
1632 bool nsBaseWidget::SetNeedFastSnaphot() {
1633 MOZ_ASSERT(XRE_IsParentProcess());
1634 MOZ_ASSERT(!mCompositorSession);
1636 if (!XRE_IsParentProcess() || mCompositorSession) {
1637 return false;
1640 mNeedFastSnaphot = true;
1641 return true;
1644 already_AddRefed<gfx::DrawTarget> nsBaseWidget::StartRemoteDrawing() {
1645 return nullptr;
1648 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA; }
1650 //-------------------------------------------------------------------------
1652 // Destroy the window
1654 //-------------------------------------------------------------------------
1655 void nsBaseWidget::OnDestroy() {
1656 if (mTextEventDispatcher) {
1657 mTextEventDispatcher->OnDestroyWidget();
1658 // Don't release it until this widget actually released because after this
1659 // is called, TextEventDispatcher() may create it again.
1662 // If this widget is being destroyed, let the APZ code know to drop references
1663 // to this widget. Callers of this function all should be holding a deathgrip
1664 // on this widget already.
1665 ReleaseContentController();
1668 /* static */
1669 DesktopIntPoint nsBaseWidget::ConstrainPositionToBounds(
1670 const DesktopIntPoint& aPoint, const DesktopIntSize& aSize,
1671 const DesktopIntRect& aScreenRect) {
1672 DesktopIntPoint point = aPoint;
1674 // The maximum position to which the window can be moved while keeping its
1675 // bottom-right corner within screenRect.
1676 auto const maxX = aScreenRect.XMost() - aSize.Width();
1677 auto const maxY = aScreenRect.YMost() - aSize.Height();
1679 // Note that the conditional-pairs below are not exclusive with each other,
1680 // and cannot be replaced with a simple call to `std::clamp`! If the window
1681 // provided is too large to fit on the screen, they will both fire. Their
1682 // order has been chosen to ensure that the window's top left corner will be
1683 // onscreen.
1685 if (point.x >= maxX) {
1686 point.x = maxX;
1688 if (point.x < aScreenRect.x) {
1689 point.x = aScreenRect.x;
1692 if (point.y >= maxY) {
1693 point.y = maxY;
1695 if (point.y < aScreenRect.y) {
1696 point.y = aScreenRect.y;
1699 return point;
1702 void nsBaseWidget::MoveClient(const DesktopPoint& aOffset) {
1703 LayoutDeviceIntPoint clientOffset(GetClientOffset());
1705 // GetClientOffset returns device pixels; scale back to desktop pixels
1706 // if that's what this widget uses for the Move/Resize APIs
1707 if (BoundsUseDesktopPixels()) {
1708 DesktopPoint desktopOffset = clientOffset / GetDesktopToDeviceScale();
1709 Move(aOffset.x - desktopOffset.x, aOffset.y - desktopOffset.y);
1710 } else {
1711 LayoutDevicePoint layoutOffset = aOffset * GetDesktopToDeviceScale();
1712 Move(layoutOffset.x - LayoutDeviceCoord(clientOffset.x),
1713 layoutOffset.y - LayoutDeviceCoord(clientOffset.y));
1717 void nsBaseWidget::ResizeClient(const DesktopSize& aSize, bool aRepaint) {
1718 NS_ASSERTION((aSize.width >= 0), "Negative width passed to ResizeClient");
1719 NS_ASSERTION((aSize.height >= 0), "Negative height passed to ResizeClient");
1721 LayoutDeviceIntRect clientBounds = GetClientBounds();
1723 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1724 // if that's what this widget uses for the Move/Resize APIs
1725 if (BoundsUseDesktopPixels()) {
1726 DesktopSize desktopDelta =
1727 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1728 clientBounds.Size()) /
1729 GetDesktopToDeviceScale();
1730 Resize(aSize.width + desktopDelta.width, aSize.height + desktopDelta.height,
1731 aRepaint);
1732 } else {
1733 LayoutDeviceSize layoutSize = aSize * GetDesktopToDeviceScale();
1734 Resize(mBounds.Width() + (layoutSize.width - clientBounds.Width()),
1735 mBounds.Height() + (layoutSize.height - clientBounds.Height()),
1736 aRepaint);
1740 void nsBaseWidget::ResizeClient(const DesktopRect& aRect, bool aRepaint) {
1741 NS_ASSERTION((aRect.Width() >= 0), "Negative width passed to ResizeClient");
1742 NS_ASSERTION((aRect.Height() >= 0), "Negative height passed to ResizeClient");
1744 LayoutDeviceIntRect clientBounds = GetClientBounds();
1745 LayoutDeviceIntPoint clientOffset = GetClientOffset();
1746 DesktopToLayoutDeviceScale scale = GetDesktopToDeviceScale();
1748 if (BoundsUseDesktopPixels()) {
1749 DesktopPoint desktopOffset = clientOffset / scale;
1750 DesktopSize desktopDelta =
1751 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1752 clientBounds.Size()) /
1753 scale;
1754 Resize(aRect.X() - desktopOffset.x, aRect.Y() - desktopOffset.y,
1755 aRect.Width() + desktopDelta.width,
1756 aRect.Height() + desktopDelta.height, aRepaint);
1757 } else {
1758 LayoutDeviceRect layoutRect = aRect * scale;
1759 Resize(layoutRect.X() - clientOffset.x, layoutRect.Y() - clientOffset.y,
1760 layoutRect.Width() + mBounds.Width() - clientBounds.Width(),
1761 layoutRect.Height() + mBounds.Height() - clientBounds.Height(),
1762 aRepaint);
1766 //-------------------------------------------------------------------------
1768 // Bounds
1770 //-------------------------------------------------------------------------
1773 * If the implementation of nsWindow supports borders this method MUST be
1774 * overridden
1777 LayoutDeviceIntRect nsBaseWidget::GetClientBounds() { return GetBounds(); }
1780 * If the implementation of nsWindow supports borders this method MUST be
1781 * overridden
1784 LayoutDeviceIntRect nsBaseWidget::GetBounds() { return mBounds; }
1787 * If the implementation of nsWindow uses a local coordinate system within the
1788 *window, this method must be overridden
1791 LayoutDeviceIntRect nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1793 nsresult nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect& aRect) {
1794 if (SizeMode() != nsSizeMode_Normal) {
1795 return NS_ERROR_FAILURE;
1797 aRect = GetScreenBounds();
1798 return NS_OK;
1801 LayoutDeviceIntPoint nsBaseWidget::GetClientOffset() {
1802 return LayoutDeviceIntPoint(0, 0);
1805 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1807 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1809 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect* aResizerRect) {
1810 return false;
1814 * Modifies aFile to point at an icon file with the given name and suffix. The
1815 * suffix may correspond to a file extension with leading '.' if appropriate.
1816 * Returns true if the icon file exists and can be read.
1818 static bool ResolveIconNameHelper(nsIFile* aFile, const nsAString& aIconName,
1819 const nsAString& aIconSuffix) {
1820 aFile->Append(u"icons"_ns);
1821 aFile->Append(u"default"_ns);
1822 aFile->Append(aIconName + aIconSuffix);
1824 bool readable;
1825 return NS_SUCCEEDED(aFile->IsReadable(&readable)) && readable;
1829 * Resolve the given icon name into a local file object. This method is
1830 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1831 * platform specific icon file suffix (e.g., ".ico" under Win32).
1833 * If no file is found matching the given parameters, then null is returned.
1835 void nsBaseWidget::ResolveIconName(const nsAString& aIconName,
1836 const nsAString& aIconSuffix,
1837 nsIFile** aResult) {
1838 *aResult = nullptr;
1840 nsCOMPtr<nsIProperties> dirSvc =
1841 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
1842 if (!dirSvc) return;
1844 // first check auxilary chrome directories
1846 nsCOMPtr<nsISimpleEnumerator> dirs;
1847 dirSvc->Get(NS_APP_CHROME_DIR_LIST, NS_GET_IID(nsISimpleEnumerator),
1848 getter_AddRefs(dirs));
1849 if (dirs) {
1850 bool hasMore;
1851 while (NS_SUCCEEDED(dirs->HasMoreElements(&hasMore)) && hasMore) {
1852 nsCOMPtr<nsISupports> element;
1853 dirs->GetNext(getter_AddRefs(element));
1854 if (!element) continue;
1855 nsCOMPtr<nsIFile> file = do_QueryInterface(element);
1856 if (!file) continue;
1857 if (ResolveIconNameHelper(file, aIconName, aIconSuffix)) {
1858 NS_ADDREF(*aResult = file);
1859 return;
1864 // then check the main app chrome directory
1866 nsCOMPtr<nsIFile> file;
1867 dirSvc->Get(NS_APP_CHROME_DIR, NS_GET_IID(nsIFile), getter_AddRefs(file));
1868 if (file && ResolveIconNameHelper(file, aIconName, aIconSuffix))
1869 NS_ADDREF(*aResult = file);
1872 void nsBaseWidget::SetSizeConstraints(const SizeConstraints& aConstraints) {
1873 mSizeConstraints = aConstraints;
1875 // Popups are constrained during layout, and we don't want to synchronously
1876 // paint from reflow, so bail out... This is not great, but it's no worse than
1877 // what we used to do.
1879 // The right fix here is probably making constraint changes go through the
1880 // view manager and such.
1881 if (mWindowType == WindowType::Popup) {
1882 return;
1885 // If the current size doesn't meet the new constraints, trigger a
1886 // resize to apply it. Note that, we don't want to invoke Resize if
1887 // the new constraints don't affect the current size, because Resize
1888 // implementation on some platforms may touch other geometry even if
1889 // the size don't need to change.
1890 LayoutDeviceIntSize curSize = mBounds.Size();
1891 LayoutDeviceIntSize clampedSize =
1892 Max(aConstraints.mMinSize, Min(aConstraints.mMaxSize, curSize));
1893 if (clampedSize != curSize) {
1894 gfx::Size size;
1895 if (BoundsUseDesktopPixels()) {
1896 DesktopSize desktopSize = clampedSize / GetDesktopToDeviceScale();
1897 size = desktopSize.ToUnknownSize();
1898 } else {
1899 size = gfx::Size(clampedSize.ToUnknownSize());
1901 Resize(size.width, size.height, true);
1905 const widget::SizeConstraints nsBaseWidget::GetSizeConstraints() {
1906 return mSizeConstraints;
1909 // static
1910 nsIRollupListener* nsBaseWidget::GetActiveRollupListener() {
1911 // TODO: Simplify this.
1912 return nsXULPopupManager::GetInstance();
1915 void nsBaseWidget::NotifyWindowDestroyed() {
1916 if (!mWidgetListener) return;
1918 nsCOMPtr<nsIAppWindow> window = mWidgetListener->GetAppWindow();
1919 nsCOMPtr<nsIBaseWindow> appWindow(do_QueryInterface(window));
1920 if (appWindow) {
1921 appWindow->Destroy();
1925 void nsBaseWidget::NotifyWindowMoved(int32_t aX, int32_t aY,
1926 ByMoveToRect aByMoveToRect) {
1927 if (mWidgetListener) {
1928 mWidgetListener->WindowMoved(this, aX, aY, aByMoveToRect);
1931 if (mIMEHasFocus && IMENotificationRequestsRef().WantPositionChanged()) {
1932 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE));
1936 void nsBaseWidget::NotifySizeMoveDone() {
1937 if (!mWidgetListener) {
1938 return;
1940 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1941 presShell->WindowSizeMoveDone();
1945 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind) {
1946 LookAndFeel::NotifyChangedAllWindows(aKind);
1949 nsresult nsBaseWidget::NotifyIME(const IMENotification& aIMENotification) {
1950 if (mIMEHasQuit) {
1951 return NS_OK;
1953 switch (aIMENotification.mMessage) {
1954 case REQUEST_TO_COMMIT_COMPOSITION:
1955 case REQUEST_TO_CANCEL_COMPOSITION:
1956 // We should send request to IME only when there is a TextEventDispatcher
1957 // instance (this means that this widget has dispatched at least one
1958 // composition event or keyboard event) and the it has composition.
1959 // Otherwise, there is nothing to do.
1960 // Note that if current input transaction is for native input events,
1961 // TextEventDispatcher::NotifyIME() will call
1962 // TextEventDispatcherListener::NotifyIME().
1963 if (mTextEventDispatcher && mTextEventDispatcher->IsComposing()) {
1964 return mTextEventDispatcher->NotifyIME(aIMENotification);
1966 return NS_OK;
1967 default: {
1968 if (aIMENotification.mMessage == NOTIFY_IME_OF_FOCUS) {
1969 mIMEHasFocus = true;
1971 EnsureTextEventDispatcher();
1972 // TextEventDispatcher::NotifyIME() will always call
1973 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1974 // input transaction is for synthesized events for automated tests,
1975 // notifications will be sent to native IME.
1976 nsresult rv = mTextEventDispatcher->NotifyIME(aIMENotification);
1977 if (aIMENotification.mMessage == NOTIFY_IME_OF_BLUR) {
1978 mIMEHasFocus = false;
1980 return rv;
1985 void nsBaseWidget::EnsureTextEventDispatcher() {
1986 if (mTextEventDispatcher) {
1987 return;
1989 mTextEventDispatcher = new TextEventDispatcher(this);
1992 nsIWidget::NativeIMEContext nsBaseWidget::GetNativeIMEContext() {
1993 if (mTextEventDispatcher && mTextEventDispatcher->GetPseudoIMEContext()) {
1994 // If we already have a TextEventDispatcher and it's working with
1995 // a TextInputProcessor, we need to return pseudo IME context since
1996 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1997 // on the pseudo IME context in such case.
1998 NativeIMEContext pseudoIMEContext;
1999 pseudoIMEContext.InitWithRawNativeIMEContext(
2000 mTextEventDispatcher->GetPseudoIMEContext());
2001 return pseudoIMEContext;
2003 return NativeIMEContext(this);
2006 nsIWidget::TextEventDispatcher* nsBaseWidget::GetTextEventDispatcher() {
2007 EnsureTextEventDispatcher();
2008 return mTextEventDispatcher;
2011 void* nsBaseWidget::GetPseudoIMEContext() {
2012 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
2013 if (!dispatcher) {
2014 return nullptr;
2016 return dispatcher->GetPseudoIMEContext();
2019 TextEventDispatcherListener*
2020 nsBaseWidget::GetNativeTextEventDispatcherListener() {
2021 // TODO: If all platforms supported use of TextEventDispatcher for handling
2022 // native IME and keyboard events, this method should be removed since
2023 // in such case, this is overridden by all the subclasses.
2024 return nullptr;
2027 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId,
2028 const ScrollableLayerGuid::ViewID& aViewId,
2029 const CSSRect& aRect, const uint32_t& aFlags) {
2030 if (!mCompositorSession || !mAPZC) {
2031 return;
2033 LayersId layerId = mCompositorSession->RootLayerTreeId();
2034 mAPZC->ZoomToRect(ScrollableLayerGuid(layerId, aPresShellId, aViewId),
2035 ZoomTarget{aRect}, aFlags);
2038 #ifdef ACCESSIBILITY
2040 a11y::LocalAccessible* nsBaseWidget::GetRootAccessible() {
2041 NS_ENSURE_TRUE(mWidgetListener, nullptr);
2043 PresShell* presShell = mWidgetListener->GetPresShell();
2044 NS_ENSURE_TRUE(presShell, nullptr);
2046 // If container is null then the presshell is not active. This often happens
2047 // when a preshell is being held onto for fastback.
2048 nsPresContext* presContext = presShell->GetPresContext();
2049 NS_ENSURE_TRUE(presContext->GetContainerWeak(), nullptr);
2051 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
2052 // make sure it's not created at unsafe times.
2053 nsAccessibilityService* accService = GetOrCreateAccService();
2054 if (accService) {
2055 return accService->GetRootDocumentAccessible(
2056 presShell, nsContentUtils::IsSafeToRunScript());
2059 return nullptr;
2062 #endif // ACCESSIBILITY
2064 void nsBaseWidget::StartAsyncScrollbarDrag(
2065 const AsyncDragMetrics& aDragMetrics) {
2066 if (!AsyncPanZoomEnabled()) {
2067 return;
2070 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession);
2072 LayersId layersId = mCompositorSession->RootLayerTreeId();
2073 ScrollableLayerGuid guid(layersId, aDragMetrics.mPresShellId,
2074 aDragMetrics.mViewId);
2076 mAPZC->StartScrollbarDrag(guid, aDragMetrics);
2079 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
2080 const ScrollableLayerGuid& aGuid) {
2081 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2083 return mAPZC->StartAutoscroll(aGuid, aAnchorLocation);
2086 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid& aGuid) {
2087 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2089 mAPZC->StopAutoscroll(aGuid);
2092 LayersId nsBaseWidget::GetRootLayerTreeId() {
2093 return mCompositorSession ? mCompositorSession->RootLayerTreeId()
2094 : LayersId{0};
2097 already_AddRefed<widget::Screen> nsBaseWidget::GetWidgetScreen() {
2098 ScreenManager& screenManager = ScreenManager::GetSingleton();
2099 LayoutDeviceIntRect bounds = GetScreenBounds();
2100 DesktopIntRect deskBounds = RoundedToInt(bounds / GetDesktopToDeviceScale());
2101 return screenManager.ScreenForRect(deskBounds);
2104 mozilla::DesktopToLayoutDeviceScale
2105 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
2106 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
2107 ->GetDesktopToDeviceScale();
2110 nsresult nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint,
2111 bool aLongTap,
2112 nsIObserver* aObserver) {
2113 AutoObserverNotifier notifier(aObserver, "touchtap");
2115 if (sPointerIdCounter > TOUCH_INJECT_MAX_POINTS) {
2116 sPointerIdCounter = 0;
2118 int pointerId = sPointerIdCounter;
2119 sPointerIdCounter++;
2120 nsresult rv = SynthesizeNativeTouchPoint(pointerId, TOUCH_CONTACT, aPoint,
2121 1.0, 90, nullptr);
2122 if (NS_FAILED(rv)) {
2123 return rv;
2126 if (!aLongTap) {
2127 return SynthesizeNativeTouchPoint(pointerId, TOUCH_REMOVE, aPoint, 0, 0,
2128 nullptr);
2131 // initiate a long tap
2132 int elapse = Preferences::GetInt("ui.click_hold_context_menus.delay",
2133 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC);
2134 if (!mLongTapTimer) {
2135 mLongTapTimer = NS_NewTimer();
2136 if (!mLongTapTimer) {
2137 SynthesizeNativeTouchPoint(pointerId, TOUCH_CANCEL, aPoint, 0, 0,
2138 nullptr);
2139 return NS_ERROR_UNEXPECTED;
2141 // Windows requires recuring events, so we set this to a smaller window
2142 // than the pref value.
2143 int timeout = elapse;
2144 if (timeout > TOUCH_INJECT_PUMP_TIMER_MSEC) {
2145 timeout = TOUCH_INJECT_PUMP_TIMER_MSEC;
2147 mLongTapTimer->InitWithNamedFuncCallback(
2148 OnLongTapTimerCallback, this, timeout, nsITimer::TYPE_REPEATING_SLACK,
2149 "nsIWidget::SynthesizeNativeTouchTap");
2152 // If we already have a long tap pending, cancel it. We only allow one long
2153 // tap to be active at a time.
2154 if (mLongTapTouchPoint) {
2155 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
2156 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
2159 mLongTapTouchPoint = MakeUnique<LongTapInfo>(
2160 pointerId, aPoint, TimeDuration::FromMilliseconds(elapse), aObserver);
2161 notifier.SkipNotification(); // we'll do it in the long-tap callback
2162 return NS_OK;
2165 // static
2166 void nsIWidget::OnLongTapTimerCallback(nsITimer* aTimer, void* aClosure) {
2167 auto* self = static_cast<nsIWidget*>(aClosure);
2169 if ((self->mLongTapTouchPoint->mStamp + self->mLongTapTouchPoint->mDuration) >
2170 TimeStamp::Now()) {
2171 #ifdef XP_WIN
2172 // Windows needs us to keep pumping feedback to the digitizer, so update
2173 // the pointer id with the same position.
2174 self->SynthesizeNativeTouchPoint(
2175 self->mLongTapTouchPoint->mPointerId, TOUCH_CONTACT,
2176 self->mLongTapTouchPoint->mPosition, 1.0, 90, nullptr);
2177 #endif
2178 return;
2181 AutoObserverNotifier notifier(self->mLongTapTouchPoint->mObserver,
2182 "touchtap");
2184 // finished, remove the touch point
2185 self->mLongTapTimer->Cancel();
2186 self->mLongTapTimer = nullptr;
2187 self->SynthesizeNativeTouchPoint(
2188 self->mLongTapTouchPoint->mPointerId, TOUCH_REMOVE,
2189 self->mLongTapTouchPoint->mPosition, 0, 0, nullptr);
2190 self->mLongTapTouchPoint = nullptr;
2193 float nsIWidget::GetFallbackDPI() {
2194 RefPtr<const Screen> primaryScreen =
2195 ScreenManager::GetSingleton().GetPrimaryScreen();
2196 return primaryScreen->GetDPI();
2199 CSSToLayoutDeviceScale nsIWidget::GetFallbackDefaultScale() {
2200 RefPtr<const Screen> s = ScreenManager::GetSingleton().GetPrimaryScreen();
2201 return s->GetCSSToLayoutDeviceScale(Screen::IncludeOSZoom::No);
2204 nsresult nsIWidget::ClearNativeTouchSequence(nsIObserver* aObserver) {
2205 AutoObserverNotifier notifier(aObserver, "cleartouch");
2207 // XXX This is odd. This is called by the constructor of nsIWidget. However,
2208 // at that point, nsIWidget::mLongTapTimer must be nullptr. Therefore,
2209 // this must do nothing at initializing the instance.
2210 if (!mLongTapTimer) {
2211 return NS_OK;
2213 mLongTapTimer->Cancel();
2214 mLongTapTimer = nullptr;
2215 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
2216 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
2217 mLongTapTouchPoint = nullptr;
2218 return NS_OK;
2221 MultiTouchInput nsBaseWidget::UpdateSynthesizedTouchState(
2222 MultiTouchInput* aState, mozilla::TimeStamp aTimeStamp, uint32_t aPointerId,
2223 TouchPointerState aPointerState, LayoutDeviceIntPoint aPoint,
2224 double aPointerPressure, uint32_t aPointerOrientation) {
2225 ScreenIntPoint pointerScreenPoint = ViewAs<ScreenPixel>(
2226 aPoint, PixelCastJustification::LayoutDeviceIsScreenForBounds);
2228 // We can't dispatch *aState directly because (a) dispatching
2229 // it might inadvertently modify it and (b) in the case of touchend or
2230 // touchcancel events aState will hold the touches that are
2231 // still down whereas the input dispatched needs to hold the removed
2232 // touch(es). We use |inputToDispatch| for this purpose.
2233 MultiTouchInput inputToDispatch;
2234 inputToDispatch.mInputType = MULTITOUCH_INPUT;
2235 inputToDispatch.mTimeStamp = aTimeStamp;
2237 int32_t index = aState->IndexOfTouch((int32_t)aPointerId);
2238 if (aPointerState == TOUCH_CONTACT) {
2239 if (index >= 0) {
2240 // found an existing touch point, update it
2241 SingleTouchData& point = aState->mTouches[index];
2242 point.mScreenPoint = pointerScreenPoint;
2243 point.mRotationAngle = (float)aPointerOrientation;
2244 point.mForce = (float)aPointerPressure;
2245 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_MOVE;
2246 } else {
2247 // new touch point, add it
2248 aState->mTouches.AppendElement(SingleTouchData(
2249 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2250 (float)aPointerOrientation, (float)aPointerPressure));
2251 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_START;
2253 inputToDispatch.mTouches = aState->mTouches;
2254 } else {
2255 MOZ_ASSERT(aPointerState == TOUCH_REMOVE || aPointerState == TOUCH_CANCEL);
2256 // a touch point is being lifted, so remove it from the stored list
2257 if (index >= 0) {
2258 aState->mTouches.RemoveElementAt(index);
2260 inputToDispatch.mType =
2261 (aPointerState == TOUCH_REMOVE ? MultiTouchInput::MULTITOUCH_END
2262 : MultiTouchInput::MULTITOUCH_CANCEL);
2263 inputToDispatch.mTouches.AppendElement(SingleTouchData(
2264 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2265 (float)aPointerOrientation, (float)aPointerPressure));
2268 return inputToDispatch;
2271 void nsBaseWidget::NotifyLiveResizeStarted() {
2272 // If we have mLiveResizeListeners already non-empty, we should notify those
2273 // listeners that the resize stopped before starting anew. In theory this
2274 // should never happen because we shouldn't get nested live resize actions.
2275 NotifyLiveResizeStopped();
2276 MOZ_ASSERT(mLiveResizeListeners.IsEmpty());
2278 // If we can get the active remote tab for the current widget, suppress
2279 // the displayport on it during the live resize.
2280 if (!mWidgetListener) {
2281 return;
2283 nsCOMPtr<nsIAppWindow> appWindow = mWidgetListener->GetAppWindow();
2284 if (!appWindow) {
2285 return;
2287 mLiveResizeListeners = appWindow->GetLiveResizeListeners();
2288 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2289 mLiveResizeListeners[i]->LiveResizeStarted();
2293 void nsBaseWidget::NotifyLiveResizeStopped() {
2294 if (!mLiveResizeListeners.IsEmpty()) {
2295 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2296 mLiveResizeListeners[i]->LiveResizeStopped();
2298 mLiveResizeListeners.Clear();
2302 nsresult nsBaseWidget::AsyncEnableDragDrop(bool aEnable) {
2303 RefPtr<nsBaseWidget> kungFuDeathGrip = this;
2304 return NS_DispatchToCurrentThreadQueue(
2305 NS_NewRunnableFunction(
2306 "AsyncEnableDragDropFn",
2307 [this, aEnable, kungFuDeathGrip]() { EnableDragDrop(aEnable); }),
2308 kAsyncDragDropTimeout, EventQueuePriority::Idle);
2311 void nsBaseWidget::SwipeFinished() {
2312 if (mSwipeTracker) {
2313 mSwipeTracker->Destroy();
2314 mSwipeTracker = nullptr;
2318 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId,
2319 bool aStartSwipe) {
2320 if (mSwipeEventQueue && mSwipeEventQueue->inputBlockId == aInputBlockId) {
2321 if (aStartSwipe) {
2322 PanGestureInput& startEvent = mSwipeEventQueue->queuedEvents[0];
2323 TrackScrollEventAsSwipe(startEvent, mSwipeEventQueue->allowedDirections,
2324 aInputBlockId);
2325 for (size_t i = 1; i < mSwipeEventQueue->queuedEvents.Length(); i++) {
2326 mSwipeTracker->ProcessEvent(mSwipeEventQueue->queuedEvents[i]);
2328 } else if (mAPZC) {
2329 // If the event wasn't start swipe, we need to notify it to APZ.
2330 mAPZC->SetBrowserGestureResponse(aInputBlockId,
2331 BrowserGestureResponse::NotConsumed);
2333 mSwipeEventQueue = nullptr;
2337 void nsBaseWidget::TrackScrollEventAsSwipe(
2338 const mozilla::PanGestureInput& aSwipeStartEvent,
2339 uint32_t aAllowedDirections, uint64_t aInputBlockId) {
2340 // If a swipe is currently being tracked kill it -- it's been interrupted
2341 // by another gesture event.
2342 if (mSwipeTracker) {
2343 mSwipeTracker->CancelSwipe(aSwipeStartEvent.mTimeStamp);
2344 mSwipeTracker->Destroy();
2345 mSwipeTracker = nullptr;
2348 uint32_t direction =
2349 (aSwipeStartEvent.mPanDisplacement.x > 0.0)
2350 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2351 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT;
2353 mSwipeTracker =
2354 new SwipeTracker(*this, aSwipeStartEvent, aAllowedDirections, direction);
2356 if (!mAPZC) {
2357 mCurrentPanGestureBelongsToSwipe = true;
2358 } else {
2359 // Now SwipeTracker has started consuming pan events, notify it to APZ so
2360 // that APZ can discard queued events.
2361 mAPZC->SetBrowserGestureResponse(aInputBlockId,
2362 BrowserGestureResponse::Consumed);
2366 nsBaseWidget::SwipeInfo nsBaseWidget::SendMayStartSwipe(
2367 const mozilla::PanGestureInput& aSwipeStartEvent) {
2368 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
2370 uint32_t direction =
2371 (aSwipeStartEvent.mPanDisplacement.x > 0.0)
2372 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2373 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT;
2375 // We're ready to start the animation. Tell Gecko about it, and at the same
2376 // time ask it if it really wants to start an animation for this event.
2377 // This event also reports back the directions that we can swipe in.
2378 LayoutDeviceIntPoint position = RoundedToInt(aSwipeStartEvent.mPanStartPoint *
2379 ScreenToLayoutDeviceScale(1));
2380 WidgetSimpleGestureEvent geckoEvent = SwipeTracker::CreateSwipeGestureEvent(
2381 eSwipeGestureMayStart, this, position, aSwipeStartEvent.mTimeStamp);
2382 geckoEvent.mDirection = direction;
2383 geckoEvent.mDelta = 0.0;
2384 geckoEvent.mAllowedDirections = 0;
2385 bool shouldStartSwipe =
2386 DispatchWindowEvent(geckoEvent); // event cancelled == swipe should start
2388 SwipeInfo result = {shouldStartSwipe, geckoEvent.mAllowedDirections};
2389 return result;
2392 WidgetWheelEvent nsBaseWidget::MayStartSwipeForAPZ(
2393 const PanGestureInput& aPanInput, const APZEventResult& aApzResult) {
2394 WidgetWheelEvent event = aPanInput.ToWidgetEvent(this);
2396 // Ignore swipe-to-navigation in PiP window.
2397 if (mIsPIPWindow) {
2398 return event;
2401 if (aPanInput.mHandledByAPZ && aPanInput.AllowsSwipe()) {
2402 SwipeInfo swipeInfo = SendMayStartSwipe(aPanInput);
2403 event.mCanTriggerSwipe = swipeInfo.wantsSwipe;
2404 if (swipeInfo.wantsSwipe) {
2405 if (aApzResult.GetStatus() == nsEventStatus_eIgnore) {
2406 // APZ has determined and that scrolling horizontally in the
2407 // requested direction is impossible, so it didn't do any
2408 // scrolling for the event.
2409 // We know now that MayStartSwipe wants a swipe, so we can start
2410 // the swipe now.
2411 TrackScrollEventAsSwipe(aPanInput, swipeInfo.allowedDirections,
2412 aApzResult.mInputBlockId);
2413 } else if (!aApzResult.GetHandledResult() ||
2414 !aApzResult.GetHandledResult()->IsHandledByRoot()) {
2415 // We don't know whether this event can start a swipe, so we need
2416 // to queue up events and wait for a call to ReportSwipeStarted.
2417 // APZ might already have started scrolling in response to the
2418 // event if it knew that it's the right thing to do. In that case
2419 // we'll still get a call to ReportSwipeStarted, and we will
2420 // discard the queued events at that point.
2421 mSwipeEventQueue = MakeUnique<SwipeEventQueue>(
2422 swipeInfo.allowedDirections, aApzResult.mInputBlockId);
2424 } else {
2425 // Inform that the browser gesture didn't use the pan event (pan-start
2426 // precisely), so that APZ can now start using the event for
2427 // scrolling/overscrolling.
2428 mAPZC->SetBrowserGestureResponse(aApzResult.mInputBlockId,
2429 BrowserGestureResponse::NotConsumed);
2433 if (mSwipeEventQueue &&
2434 mSwipeEventQueue->inputBlockId == aApzResult.mInputBlockId) {
2435 mSwipeEventQueue->queuedEvents.AppendElement(aPanInput);
2438 return event;
2441 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput& aPanInput) {
2442 // Ignore swipe-to-navigation in PiP window.
2443 if (mIsPIPWindow) {
2444 return false;
2447 if (aPanInput.mType == PanGestureInput::PANGESTURE_MAYSTART ||
2448 aPanInput.mType == PanGestureInput::PANGESTURE_START) {
2449 mCurrentPanGestureBelongsToSwipe = false;
2451 if (mCurrentPanGestureBelongsToSwipe) {
2452 // Ignore this event. It's a momentum event from a scroll gesture
2453 // that was processed as a swipe, and the swipe animation has
2454 // already finished (so mSwipeTracker is already null).
2455 MOZ_ASSERT(aPanInput.IsMomentum(),
2456 "If the fingers are still on the touchpad, we should still have "
2457 "a SwipeTracker, "
2458 "and it should have consumed this event.");
2459 return true;
2462 if (!aPanInput.MayTriggerSwipe()) {
2463 return false;
2466 SwipeInfo swipeInfo = SendMayStartSwipe(aPanInput);
2468 // We're in the non-APZ case here, but we still want to know whether
2469 // the event was routed to a child process, so we use InputAPZContext
2470 // to get that piece of information.
2471 ScrollableLayerGuid guid;
2472 uint64_t blockId = 0;
2473 InputAPZContext context(guid, blockId, nsEventStatus_eIgnore);
2475 WidgetWheelEvent event = aPanInput.ToWidgetEvent(this);
2476 event.mCanTriggerSwipe = swipeInfo.wantsSwipe;
2477 nsEventStatus status;
2478 DispatchEvent(&event, status);
2479 if (swipeInfo.wantsSwipe) {
2480 if (context.WasRoutedToChildProcess()) {
2481 // We don't know whether this event can start a swipe, so we need
2482 // to queue up events and wait for a call to ReportSwipeStarted.
2483 mSwipeEventQueue =
2484 MakeUnique<SwipeEventQueue>(swipeInfo.allowedDirections, blockId);
2485 } else if (event.TriggersSwipe()) {
2486 TrackScrollEventAsSwipe(aPanInput, swipeInfo.allowedDirections, blockId);
2490 if (mSwipeEventQueue && mSwipeEventQueue->inputBlockId == 0) {
2491 mSwipeEventQueue->queuedEvents.AppendElement(aPanInput);
2494 return true;
2497 LayersId nsBaseWidget::GetLayersId() const {
2498 return mCompositorSession ? mCompositorSession->RootLayerTreeId()
2499 : LayersId{0};
2502 const IMENotificationRequests& nsIWidget::IMENotificationRequestsRef() {
2503 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
2504 return dispatcher->IMENotificationRequestsRef();
2507 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent* aEvent) {}
2509 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType,
2510 const WidgetKeyboardEvent& aEvent,
2511 nsTArray<CommandInt>& aCommands) {
2512 MOZ_ASSERT(aEvent.IsTrusted());
2513 MOZ_ASSERT(aCommands.IsEmpty());
2514 return true;
2517 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboard() {
2518 if (XRE_IsContentProcess()) {
2519 return CreateBidiKeyboardContentProcess();
2521 return CreateBidiKeyboardInner();
2524 #ifdef ANDROID
2525 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboardInner() {
2526 // no bidi keyboard implementation
2527 return nullptr;
2529 #endif
2531 namespace mozilla::widget {
2533 const char* ToChar(InputContext::Origin aOrigin) {
2534 switch (aOrigin) {
2535 case InputContext::ORIGIN_MAIN:
2536 return "ORIGIN_MAIN";
2537 case InputContext::ORIGIN_CONTENT:
2538 return "ORIGIN_CONTENT";
2539 default:
2540 return "Unexpected value";
2544 const char* ToChar(IMEMessage aIMEMessage) {
2545 switch (aIMEMessage) {
2546 case NOTIFY_IME_OF_NOTHING:
2547 return "NOTIFY_IME_OF_NOTHING";
2548 case NOTIFY_IME_OF_FOCUS:
2549 return "NOTIFY_IME_OF_FOCUS";
2550 case NOTIFY_IME_OF_BLUR:
2551 return "NOTIFY_IME_OF_BLUR";
2552 case NOTIFY_IME_OF_SELECTION_CHANGE:
2553 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2554 case NOTIFY_IME_OF_TEXT_CHANGE:
2555 return "NOTIFY_IME_OF_TEXT_CHANGE";
2556 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED:
2557 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2558 case NOTIFY_IME_OF_POSITION_CHANGE:
2559 return "NOTIFY_IME_OF_POSITION_CHANGE";
2560 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
2561 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2562 case REQUEST_TO_COMMIT_COMPOSITION:
2563 return "REQUEST_TO_COMMIT_COMPOSITION";
2564 case REQUEST_TO_CANCEL_COMPOSITION:
2565 return "REQUEST_TO_CANCEL_COMPOSITION";
2566 default:
2567 return "Unexpected value";
2571 void NativeIMEContext::Init(nsIWidget* aWidget) {
2572 if (!aWidget) {
2573 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2574 mOriginProcessID = static_cast<uint64_t>(-1);
2575 return;
2577 if (!XRE_IsContentProcess()) {
2578 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(
2579 aWidget->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT));
2580 mOriginProcessID = 0;
2581 return;
2583 // If this is created in a child process, aWidget is an instance of
2584 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2585 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2586 // native IME context of the parent process.
2587 *this = aWidget->GetNativeIMEContext();
2590 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext) {
2591 if (NS_WARN_IF(!aRawNativeIMEContext)) {
2592 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2593 mOriginProcessID = static_cast<uint64_t>(-1);
2594 return;
2596 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(aRawNativeIMEContext);
2597 mOriginProcessID =
2598 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2601 void IMENotification::TextChangeDataBase::MergeWith(
2602 const IMENotification::TextChangeDataBase& aOther) {
2603 MOZ_ASSERT(aOther.IsValid(), "Merging data must store valid data");
2604 MOZ_ASSERT(aOther.mStartOffset <= aOther.mRemovedEndOffset,
2605 "end of removed text must be same or larger than start");
2606 MOZ_ASSERT(aOther.mStartOffset <= aOther.mAddedEndOffset,
2607 "end of added text must be same or larger than start");
2609 if (!IsValid()) {
2610 *this = aOther;
2611 return;
2614 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2615 // text ranges. I.e., mStartOffset should be the smallest offset of all
2616 // modified text ranges in old text. |mRemovedEndOffset| should be the
2617 // largest end offset in old text of all modified text ranges.
2618 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2619 // I.e., only this is an offset in new text.
2620 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2621 // premodified text was already removed. And some text whose length is
2622 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2623 // this allows IME to mark dirty the modified text range with |mStartOffset|
2624 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2625 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2626 // Additionally, IME can retrieve only the text between |mStartOffset| and
2627 // |mAddedEndOffset| for updating stored text.
2629 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2630 // should be adjusted to be in same text. The |newData.mStartOffset| and
2631 // |newData.mRemovedEndOffset| should be computed as in old text because
2632 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2633 // in the old text but even if some text before the values of the newData
2634 // has already been modified, the values don't include the changes.
2636 // For comparing new and old |mAddedEndOffset| values, they should be
2637 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2638 // computed as in the new text because |mAddedEndOffset| indicates the end
2639 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2640 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2642 const TextChangeDataBase& newData = aOther;
2643 const TextChangeDataBase oldData = *this;
2645 // mCausedOnlyByComposition should be true only when all changes are caused
2646 // by composition.
2647 mCausedOnlyByComposition =
2648 newData.mCausedOnlyByComposition && oldData.mCausedOnlyByComposition;
2650 // mIncludingChangesWithoutComposition should be true if at least one of
2651 // merged changes occurred without composition.
2652 mIncludingChangesWithoutComposition =
2653 newData.mIncludingChangesWithoutComposition ||
2654 oldData.mIncludingChangesWithoutComposition;
2656 // mIncludingChangesDuringComposition should be true when at least one of
2657 // the merged non-composition changes occurred during the latest composition.
2658 if (!newData.mCausedOnlyByComposition &&
2659 !newData.mIncludingChangesDuringComposition) {
2660 MOZ_ASSERT(newData.mIncludingChangesWithoutComposition);
2661 MOZ_ASSERT(mIncludingChangesWithoutComposition);
2662 // If new change is neither caused by composition nor occurred during
2663 // composition, set mIncludingChangesDuringComposition to false because
2664 // IME doesn't want outdated text changes as text change during current
2665 // composition.
2666 mIncludingChangesDuringComposition = false;
2667 } else {
2668 // Otherwise, set mIncludingChangesDuringComposition to true if either
2669 // oldData or newData includes changes during composition.
2670 mIncludingChangesDuringComposition =
2671 newData.mIncludingChangesDuringComposition ||
2672 oldData.mIncludingChangesDuringComposition;
2675 if (newData.mStartOffset >= oldData.mAddedEndOffset) {
2676 // Case 1:
2677 // If new start is after old end offset of added text, it means that text
2678 // after the modified range is modified. Like:
2679 // added range of old change: +----------+
2680 // removed range of new change: +----------+
2681 // So, the old start offset is always the smaller offset.
2682 mStartOffset = oldData.mStartOffset;
2683 // The new end offset of removed text is moved by the old change and we
2684 // need to cancel the move of the old change for comparing the offsets in
2685 // same text because it doesn't make sensce to compare offsets in different
2686 // text.
2687 uint32_t newRemovedEndOffsetInOldText =
2688 newData.mRemovedEndOffset - oldData.Difference();
2689 mRemovedEndOffset =
2690 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2691 // The new end offset of added text is always the larger offset.
2692 mAddedEndOffset = newData.mAddedEndOffset;
2693 return;
2696 if (newData.mStartOffset >= oldData.mStartOffset) {
2697 // If new start is in the modified range, it means that new data changes
2698 // a part or all of the range.
2699 mStartOffset = oldData.mStartOffset;
2700 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2701 // Case 2:
2702 // If new end of removed text is greater than old end of added text, it
2703 // means that all or a part of modified range modified again and text
2704 // after the modified range is also modified. Like:
2705 // added range of old change: +----------+
2706 // removed range of new change: +----------+
2707 // So, the new removed end offset is moved by the old change and we need
2708 // to cancel the move of the old change for comparing the offsets in the
2709 // same text because it doesn't make sense to compare the offsets in
2710 // different text.
2711 uint32_t newRemovedEndOffsetInOldText =
2712 newData.mRemovedEndOffset - oldData.Difference();
2713 mRemovedEndOffset =
2714 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2715 // The old end of added text is replaced by new change. So, it should be
2716 // same as the new start. On the other hand, the new added end offset is
2717 // always same or larger. Therefore, the merged end offset of added
2718 // text should be the new end offset of added text.
2719 mAddedEndOffset = newData.mAddedEndOffset;
2720 return;
2723 // Case 3:
2724 // If new end of removed text is less than old end of added text, it means
2725 // that only a part of the modified range is modified again. Like:
2726 // added range of old change: +------------+
2727 // removed range of new change: +-----+
2728 // So, the new end offset of removed text should be same as the old end
2729 // offset of removed text. Therefore, the merged end offset of removed
2730 // text should be the old text change's |mRemovedEndOffset|.
2731 mRemovedEndOffset = oldData.mRemovedEndOffset;
2732 // The old end of added text is moved by new change. So, we need to cancel
2733 // the move of the new change for comparing the offsets in same text.
2734 uint32_t oldAddedEndOffsetInNewText =
2735 oldData.mAddedEndOffset + newData.Difference();
2736 mAddedEndOffset =
2737 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2738 return;
2741 if (newData.mRemovedEndOffset >= oldData.mStartOffset) {
2742 // If new end of removed text is greater than old start (and new start is
2743 // less than old start), it means that a part of modified range is modified
2744 // again and some new text before the modified range is also modified.
2745 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2746 "new start offset should be less than old one here");
2747 mStartOffset = newData.mStartOffset;
2748 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2749 // Case 4:
2750 // If new end of removed text is greater than old end of added text, it
2751 // means that all modified text and text after the modified range is
2752 // modified. Like:
2753 // added range of old change: +----------+
2754 // removed range of new change: +------------------+
2755 // So, the new end of removed text is moved by the old change. Therefore,
2756 // we need to cancel the move of the old change for comparing the offsets
2757 // in same text because it doesn't make sense to compare the offsets in
2758 // different text.
2759 uint32_t newRemovedEndOffsetInOldText =
2760 newData.mRemovedEndOffset - oldData.Difference();
2761 mRemovedEndOffset =
2762 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2763 // The old end of added text is replaced by new change. So, the old end
2764 // offset of added text is same as new text change's start offset. Then,
2765 // new change's end offset of added text is always same or larger than
2766 // it. Therefore, merged end offset of added text is always the new end
2767 // offset of added text.
2768 mAddedEndOffset = newData.mAddedEndOffset;
2769 return;
2772 // Case 5:
2773 // If new end of removed text is less than old end of added text, it
2774 // means that only a part of the modified range is modified again. Like:
2775 // added range of old change: +----------+
2776 // removed range of new change: +----------+
2777 // So, the new end of removed text should be same as old end of removed
2778 // text for preventing end of removed text to be modified. Therefore,
2779 // merged end offset of removed text is always the old end offset of removed
2780 // text.
2781 mRemovedEndOffset = oldData.mRemovedEndOffset;
2782 // The old end of added text is moved by this change. So, we need to
2783 // cancel the move of the new change for comparing the offsets in same text
2784 // because it doesn't make sense to compare the offsets in different text.
2785 uint32_t oldAddedEndOffsetInNewText =
2786 oldData.mAddedEndOffset + newData.Difference();
2787 mAddedEndOffset =
2788 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2789 return;
2792 // Case 6:
2793 // Otherwise, i.e., both new end of added text and new start are less than
2794 // old start, text before the modified range is modified. Like:
2795 // added range of old change: +----------+
2796 // removed range of new change: +----------+
2797 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2798 "new start offset should be less than old one here");
2799 mStartOffset = newData.mStartOffset;
2800 MOZ_ASSERT(newData.mRemovedEndOffset < oldData.mRemovedEndOffset,
2801 "new removed end offset should be less than old one here");
2802 mRemovedEndOffset = oldData.mRemovedEndOffset;
2803 // The end of added text should be adjusted with the new difference.
2804 uint32_t oldAddedEndOffsetInNewText =
2805 oldData.mAddedEndOffset + newData.Difference();
2806 mAddedEndOffset =
2807 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2810 #ifdef DEBUG
2812 // Let's test the code of merging multiple text change data in debug build
2813 // and crash if one of them fails because this feature is very complex but
2814 // cannot be tested with mochitest.
2815 void IMENotification::TextChangeDataBase::Test() {
2816 static bool gTestTextChangeEvent = true;
2817 if (!gTestTextChangeEvent) {
2818 return;
2820 gTestTextChangeEvent = false;
2822 /****************************************************************************
2823 * Case 1
2824 ****************************************************************************/
2826 // Appending text
2827 MergeWith(TextChangeData(10, 10, 20, false, false));
2828 MergeWith(TextChangeData(20, 20, 35, false, false));
2829 MOZ_ASSERT(mStartOffset == 10,
2830 "Test 1-1-1: mStartOffset should be the first offset");
2831 MOZ_ASSERT(
2832 mRemovedEndOffset == 10, // 20 - (20 - 10)
2833 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2834 MOZ_ASSERT(
2835 mAddedEndOffset == 35,
2836 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2837 Clear();
2839 // Removing text (longer line -> shorter line)
2840 MergeWith(TextChangeData(10, 20, 10, false, false));
2841 MergeWith(TextChangeData(10, 30, 10, false, false));
2842 MOZ_ASSERT(mStartOffset == 10,
2843 "Test 1-2-1: mStartOffset should be the first offset");
2844 MOZ_ASSERT(mRemovedEndOffset == 40, // 30 + (10 - 20)
2845 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2846 "removed text "
2847 "with already removed length");
2848 MOZ_ASSERT(
2849 mAddedEndOffset == 10,
2850 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2851 Clear();
2853 // Removing text (shorter line -> longer line)
2854 MergeWith(TextChangeData(10, 20, 10, false, false));
2855 MergeWith(TextChangeData(10, 15, 10, false, false));
2856 MOZ_ASSERT(mStartOffset == 10,
2857 "Test 1-3-1: mStartOffset should be the first offset");
2858 MOZ_ASSERT(mRemovedEndOffset == 25, // 15 + (10 - 20)
2859 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2860 "removed text "
2861 "with already removed length");
2862 MOZ_ASSERT(
2863 mAddedEndOffset == 10,
2864 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2865 Clear();
2867 // Appending text at different point (not sure if actually occurs)
2868 MergeWith(TextChangeData(10, 10, 20, false, false));
2869 MergeWith(TextChangeData(55, 55, 60, false, false));
2870 MOZ_ASSERT(mStartOffset == 10,
2871 "Test 1-4-1: mStartOffset should be the smallest offset");
2872 MOZ_ASSERT(
2873 mRemovedEndOffset == 45, // 55 - (10 - 20)
2874 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2875 "text without already added length");
2876 MOZ_ASSERT(
2877 mAddedEndOffset == 60,
2878 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2879 Clear();
2881 // Removing text at different point (not sure if actually occurs)
2882 MergeWith(TextChangeData(10, 20, 10, false, false));
2883 MergeWith(TextChangeData(55, 68, 55, false, false));
2884 MOZ_ASSERT(mStartOffset == 10,
2885 "Test 1-5-1: mStartOffset should be the smallest offset");
2886 MOZ_ASSERT(
2887 mRemovedEndOffset == 78, // 68 - (10 - 20)
2888 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2889 "text with already removed length");
2890 MOZ_ASSERT(
2891 mAddedEndOffset == 55,
2892 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2893 Clear();
2895 // Replacing text and append text (becomes longer)
2896 MergeWith(TextChangeData(30, 35, 32, false, false));
2897 MergeWith(TextChangeData(32, 32, 40, false, false));
2898 MOZ_ASSERT(mStartOffset == 30,
2899 "Test 1-6-1: mStartOffset should be the smallest offset");
2900 MOZ_ASSERT(
2901 mRemovedEndOffset == 35, // 32 - (32 - 35)
2902 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2903 "text");
2904 MOZ_ASSERT(
2905 mAddedEndOffset == 40,
2906 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2907 Clear();
2909 // Replacing text and append text (becomes shorter)
2910 MergeWith(TextChangeData(30, 35, 32, false, false));
2911 MergeWith(TextChangeData(32, 32, 33, false, false));
2912 MOZ_ASSERT(mStartOffset == 30,
2913 "Test 1-7-1: mStartOffset should be the smallest offset");
2914 MOZ_ASSERT(
2915 mRemovedEndOffset == 35, // 32 - (32 - 35)
2916 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2917 "text");
2918 MOZ_ASSERT(
2919 mAddedEndOffset == 33,
2920 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2921 Clear();
2923 // Removing text and replacing text after first range (not sure if actually
2924 // occurs)
2925 MergeWith(TextChangeData(30, 35, 30, false, false));
2926 MergeWith(TextChangeData(32, 34, 48, false, false));
2927 MOZ_ASSERT(mStartOffset == 30,
2928 "Test 1-8-1: mStartOffset should be the smallest offset");
2929 MOZ_ASSERT(mRemovedEndOffset == 39, // 34 - (30 - 35)
2930 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2931 "removed text "
2932 "without already removed text");
2933 MOZ_ASSERT(
2934 mAddedEndOffset == 48,
2935 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2936 Clear();
2938 // Removing text and replacing text after first range (not sure if actually
2939 // occurs)
2940 MergeWith(TextChangeData(30, 35, 30, false, false));
2941 MergeWith(TextChangeData(32, 38, 36, false, false));
2942 MOZ_ASSERT(mStartOffset == 30,
2943 "Test 1-9-1: mStartOffset should be the smallest offset");
2944 MOZ_ASSERT(mRemovedEndOffset == 43, // 38 - (30 - 35)
2945 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2946 "removed text "
2947 "without already removed text");
2948 MOZ_ASSERT(
2949 mAddedEndOffset == 36,
2950 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2951 Clear();
2953 /****************************************************************************
2954 * Case 2
2955 ****************************************************************************/
2957 // Replacing text in around end of added text (becomes shorter) (not sure
2958 // if actually occurs)
2959 MergeWith(TextChangeData(50, 50, 55, false, false));
2960 MergeWith(TextChangeData(53, 60, 54, false, false));
2961 MOZ_ASSERT(mStartOffset == 50,
2962 "Test 2-1-1: mStartOffset should be the smallest offset");
2963 MOZ_ASSERT(mRemovedEndOffset == 55, // 60 - (55 - 50)
2964 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2965 "removed text "
2966 "without already added text length");
2967 MOZ_ASSERT(
2968 mAddedEndOffset == 54,
2969 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2970 Clear();
2972 // Replacing text around end of added text (becomes longer) (not sure
2973 // if actually occurs)
2974 MergeWith(TextChangeData(50, 50, 55, false, false));
2975 MergeWith(TextChangeData(54, 62, 68, false, false));
2976 MOZ_ASSERT(mStartOffset == 50,
2977 "Test 2-2-1: mStartOffset should be the smallest offset");
2978 MOZ_ASSERT(mRemovedEndOffset == 57, // 62 - (55 - 50)
2979 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2980 "removed text "
2981 "without already added text length");
2982 MOZ_ASSERT(
2983 mAddedEndOffset == 68,
2984 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2985 Clear();
2987 // Replacing text around end of replaced text (became shorter) (not sure if
2988 // actually occurs)
2989 MergeWith(TextChangeData(36, 48, 45, false, false));
2990 MergeWith(TextChangeData(43, 50, 49, false, false));
2991 MOZ_ASSERT(mStartOffset == 36,
2992 "Test 2-3-1: mStartOffset should be the smallest offset");
2993 MOZ_ASSERT(mRemovedEndOffset == 53, // 50 - (45 - 48)
2994 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2995 "removed text "
2996 "without already removed text length");
2997 MOZ_ASSERT(
2998 mAddedEndOffset == 49,
2999 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
3000 Clear();
3002 // Replacing text around end of replaced text (became longer) (not sure if
3003 // actually occurs)
3004 MergeWith(TextChangeData(36, 52, 53, false, false));
3005 MergeWith(TextChangeData(43, 68, 61, false, false));
3006 MOZ_ASSERT(mStartOffset == 36,
3007 "Test 2-4-1: mStartOffset should be the smallest offset");
3008 MOZ_ASSERT(mRemovedEndOffset == 67, // 68 - (53 - 52)
3009 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
3010 "removed text "
3011 "without already added text length");
3012 MOZ_ASSERT(
3013 mAddedEndOffset == 61,
3014 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
3015 Clear();
3017 /****************************************************************************
3018 * Case 3
3019 ****************************************************************************/
3021 // Appending text in already added text (not sure if actually occurs)
3022 MergeWith(TextChangeData(10, 10, 20, false, false));
3023 MergeWith(TextChangeData(15, 15, 30, false, false));
3024 MOZ_ASSERT(mStartOffset == 10,
3025 "Test 3-1-1: mStartOffset should be the smallest offset");
3026 MOZ_ASSERT(mRemovedEndOffset == 10,
3027 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
3028 "removed text");
3029 MOZ_ASSERT(
3030 mAddedEndOffset == 35, // 20 + (30 - 15)
3031 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
3032 "added text length by the new change");
3033 Clear();
3035 // Replacing text in added text (not sure if actually occurs)
3036 MergeWith(TextChangeData(50, 50, 55, false, false));
3037 MergeWith(TextChangeData(52, 53, 56, false, false));
3038 MOZ_ASSERT(mStartOffset == 50,
3039 "Test 3-2-1: mStartOffset should be the smallest offset");
3040 MOZ_ASSERT(mRemovedEndOffset == 50,
3041 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
3042 "removed text");
3043 MOZ_ASSERT(
3044 mAddedEndOffset == 58, // 55 + (56 - 53)
3045 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
3046 "added text length by the new change");
3047 Clear();
3049 // Replacing text in replaced text (became shorter) (not sure if actually
3050 // occurs)
3051 MergeWith(TextChangeData(36, 48, 45, false, false));
3052 MergeWith(TextChangeData(37, 38, 50, false, false));
3053 MOZ_ASSERT(mStartOffset == 36,
3054 "Test 3-3-1: mStartOffset should be the smallest offset");
3055 MOZ_ASSERT(mRemovedEndOffset == 48,
3056 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
3057 "removed text");
3058 MOZ_ASSERT(
3059 mAddedEndOffset == 57, // 45 + (50 - 38)
3060 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
3061 "added text length by the new change");
3062 Clear();
3064 // Replacing text in replaced text (became longer) (not sure if actually
3065 // occurs)
3066 MergeWith(TextChangeData(32, 48, 53, false, false));
3067 MergeWith(TextChangeData(43, 50, 52, false, false));
3068 MOZ_ASSERT(mStartOffset == 32,
3069 "Test 3-4-1: mStartOffset should be the smallest offset");
3070 MOZ_ASSERT(mRemovedEndOffset == 48,
3071 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
3072 "removed text "
3073 "without already added text length");
3074 MOZ_ASSERT(
3075 mAddedEndOffset == 55, // 53 + (52 - 50)
3076 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
3077 "added text length by the new change");
3078 Clear();
3080 // Replacing text in replaced text (became shorter) (not sure if actually
3081 // occurs)
3082 MergeWith(TextChangeData(36, 48, 50, false, false));
3083 MergeWith(TextChangeData(37, 49, 47, false, false));
3084 MOZ_ASSERT(mStartOffset == 36,
3085 "Test 3-5-1: mStartOffset should be the smallest offset");
3086 MOZ_ASSERT(
3087 mRemovedEndOffset == 48,
3088 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
3089 "text");
3090 MOZ_ASSERT(mAddedEndOffset == 48, // 50 + (47 - 49)
3091 "Test 3-5-3: mAddedEndOffset should be the first end of added "
3092 "text without "
3093 "removed text length by the new change");
3094 Clear();
3096 // Replacing text in replaced text (became longer) (not sure if actually
3097 // occurs)
3098 MergeWith(TextChangeData(32, 48, 53, false, false));
3099 MergeWith(TextChangeData(43, 50, 47, false, false));
3100 MOZ_ASSERT(mStartOffset == 32,
3101 "Test 3-6-1: mStartOffset should be the smallest offset");
3102 MOZ_ASSERT(mRemovedEndOffset == 48,
3103 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
3104 "removed text "
3105 "without already added text length");
3106 MOZ_ASSERT(mAddedEndOffset == 50, // 53 + (47 - 50)
3107 "Test 3-6-3: mAddedEndOffset should be the first end of added "
3108 "text without "
3109 "removed text length by the new change");
3110 Clear();
3112 /****************************************************************************
3113 * Case 4
3114 ****************************************************************************/
3116 // Replacing text all of already append text (not sure if actually occurs)
3117 MergeWith(TextChangeData(50, 50, 55, false, false));
3118 MergeWith(TextChangeData(44, 66, 68, false, false));
3119 MOZ_ASSERT(mStartOffset == 44,
3120 "Test 4-1-1: mStartOffset should be the smallest offset");
3121 MOZ_ASSERT(mRemovedEndOffset == 61, // 66 - (55 - 50)
3122 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
3123 "removed text "
3124 "without already added text length");
3125 MOZ_ASSERT(
3126 mAddedEndOffset == 68,
3127 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3128 Clear();
3130 // Replacing text around a point in which text was removed (not sure if
3131 // actually occurs)
3132 MergeWith(TextChangeData(50, 62, 50, false, false));
3133 MergeWith(TextChangeData(44, 66, 68, false, false));
3134 MOZ_ASSERT(mStartOffset == 44,
3135 "Test 4-2-1: mStartOffset should be the smallest offset");
3136 MOZ_ASSERT(mRemovedEndOffset == 78, // 66 - (50 - 62)
3137 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
3138 "removed text "
3139 "without already removed text length");
3140 MOZ_ASSERT(
3141 mAddedEndOffset == 68,
3142 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3143 Clear();
3145 // Replacing text all replaced text (became shorter) (not sure if actually
3146 // occurs)
3147 MergeWith(TextChangeData(50, 62, 60, false, false));
3148 MergeWith(TextChangeData(49, 128, 130, false, false));
3149 MOZ_ASSERT(mStartOffset == 49,
3150 "Test 4-3-1: mStartOffset should be the smallest offset");
3151 MOZ_ASSERT(mRemovedEndOffset == 130, // 128 - (60 - 62)
3152 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
3153 "removed text "
3154 "without already removed text length");
3155 MOZ_ASSERT(
3156 mAddedEndOffset == 130,
3157 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3158 Clear();
3160 // Replacing text all replaced text (became longer) (not sure if actually
3161 // occurs)
3162 MergeWith(TextChangeData(50, 61, 73, false, false));
3163 MergeWith(TextChangeData(44, 100, 50, false, false));
3164 MOZ_ASSERT(mStartOffset == 44,
3165 "Test 4-4-1: mStartOffset should be the smallest offset");
3166 MOZ_ASSERT(mRemovedEndOffset == 88, // 100 - (73 - 61)
3167 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
3168 "removed text "
3169 "with already added text length");
3170 MOZ_ASSERT(
3171 mAddedEndOffset == 50,
3172 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3173 Clear();
3175 /****************************************************************************
3176 * Case 5
3177 ****************************************************************************/
3179 // Replacing text around start of added text (not sure if actually occurs)
3180 MergeWith(TextChangeData(50, 50, 55, false, false));
3181 MergeWith(TextChangeData(48, 52, 49, false, false));
3182 MOZ_ASSERT(mStartOffset == 48,
3183 "Test 5-1-1: mStartOffset should be the smallest offset");
3184 MOZ_ASSERT(
3185 mRemovedEndOffset == 50,
3186 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
3187 "text");
3188 MOZ_ASSERT(
3189 mAddedEndOffset == 52, // 55 + (52 - 49)
3190 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
3191 "added text length by the new change");
3192 Clear();
3194 // Replacing text around start of replaced text (became shorter) (not sure if
3195 // actually occurs)
3196 MergeWith(TextChangeData(50, 60, 58, false, false));
3197 MergeWith(TextChangeData(43, 50, 48, false, false));
3198 MOZ_ASSERT(mStartOffset == 43,
3199 "Test 5-2-1: mStartOffset should be the smallest offset");
3200 MOZ_ASSERT(
3201 mRemovedEndOffset == 60,
3202 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3203 "text");
3204 MOZ_ASSERT(mAddedEndOffset == 56, // 58 + (48 - 50)
3205 "Test 5-2-3: mAddedEndOffset should be the first end of added "
3206 "text without "
3207 "removed text length by the new change");
3208 Clear();
3210 // Replacing text around start of replaced text (became longer) (not sure if
3211 // actually occurs)
3212 MergeWith(TextChangeData(50, 60, 68, false, false));
3213 MergeWith(TextChangeData(43, 55, 53, false, false));
3214 MOZ_ASSERT(mStartOffset == 43,
3215 "Test 5-3-1: mStartOffset should be the smallest offset");
3216 MOZ_ASSERT(
3217 mRemovedEndOffset == 60,
3218 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3219 "text");
3220 MOZ_ASSERT(mAddedEndOffset == 66, // 68 + (53 - 55)
3221 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3222 "text without "
3223 "removed text length by the new change");
3224 Clear();
3226 // Replacing text around start of replaced text (became shorter) (not sure if
3227 // actually occurs)
3228 MergeWith(TextChangeData(50, 60, 58, false, false));
3229 MergeWith(TextChangeData(43, 50, 128, false, false));
3230 MOZ_ASSERT(mStartOffset == 43,
3231 "Test 5-4-1: mStartOffset should be the smallest offset");
3232 MOZ_ASSERT(
3233 mRemovedEndOffset == 60,
3234 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
3235 "text");
3236 MOZ_ASSERT(
3237 mAddedEndOffset == 136, // 58 + (128 - 50)
3238 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
3239 "added text length by the new change");
3240 Clear();
3242 // Replacing text around start of replaced text (became longer) (not sure if
3243 // actually occurs)
3244 MergeWith(TextChangeData(50, 60, 68, false, false));
3245 MergeWith(TextChangeData(43, 55, 65, false, false));
3246 MOZ_ASSERT(mStartOffset == 43,
3247 "Test 5-5-1: mStartOffset should be the smallest offset");
3248 MOZ_ASSERT(
3249 mRemovedEndOffset == 60,
3250 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
3251 "text");
3252 MOZ_ASSERT(
3253 mAddedEndOffset == 78, // 68 + (65 - 55)
3254 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
3255 "added text length by the new change");
3256 Clear();
3258 /****************************************************************************
3259 * Case 6
3260 ****************************************************************************/
3262 // Appending text before already added text (not sure if actually occurs)
3263 MergeWith(TextChangeData(30, 30, 45, false, false));
3264 MergeWith(TextChangeData(10, 10, 20, false, false));
3265 MOZ_ASSERT(mStartOffset == 10,
3266 "Test 6-1-1: mStartOffset should be the smallest offset");
3267 MOZ_ASSERT(
3268 mRemovedEndOffset == 30,
3269 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3270 "text");
3271 MOZ_ASSERT(
3272 mAddedEndOffset == 55, // 45 + (20 - 10)
3273 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3274 "added text length by the new change");
3275 Clear();
3277 // Removing text before already removed text (not sure if actually occurs)
3278 MergeWith(TextChangeData(30, 35, 30, false, false));
3279 MergeWith(TextChangeData(10, 25, 10, false, false));
3280 MOZ_ASSERT(mStartOffset == 10,
3281 "Test 6-2-1: mStartOffset should be the smallest offset");
3282 MOZ_ASSERT(
3283 mRemovedEndOffset == 35,
3284 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3285 "text");
3286 MOZ_ASSERT(
3287 mAddedEndOffset == 15, // 30 - (25 - 10)
3288 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3289 "removed text length by the new change");
3290 Clear();
3292 // Replacing text before already replaced text (not sure if actually occurs)
3293 MergeWith(TextChangeData(50, 65, 70, false, false));
3294 MergeWith(TextChangeData(13, 24, 15, false, false));
3295 MOZ_ASSERT(mStartOffset == 13,
3296 "Test 6-3-1: mStartOffset should be the smallest offset");
3297 MOZ_ASSERT(
3298 mRemovedEndOffset == 65,
3299 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3300 "text");
3301 MOZ_ASSERT(mAddedEndOffset == 61, // 70 + (15 - 24)
3302 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3303 "text without "
3304 "removed text length by the new change");
3305 Clear();
3307 // Replacing text before already replaced text (not sure if actually occurs)
3308 MergeWith(TextChangeData(50, 65, 70, false, false));
3309 MergeWith(TextChangeData(13, 24, 36, false, false));
3310 MOZ_ASSERT(mStartOffset == 13,
3311 "Test 6-4-1: mStartOffset should be the smallest offset");
3312 MOZ_ASSERT(
3313 mRemovedEndOffset == 65,
3314 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3315 "text");
3316 MOZ_ASSERT(mAddedEndOffset == 82, // 70 + (36 - 24)
3317 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3318 "text without "
3319 "removed text length by the new change");
3320 Clear();
3323 #endif // #ifdef DEBUG
3325 } // namespace mozilla::widget
3327 #ifdef DEBUG
3328 //////////////////////////////////////////////////////////////
3330 // Code to deal with paint and event debug prefs.
3332 //////////////////////////////////////////////////////////////
3333 struct PrefPair {
3334 const char* name;
3335 bool value;
3338 static PrefPair debug_PrefValues[] = {
3339 {"nglayout.debug.crossing_event_dumping", false},
3340 {"nglayout.debug.event_dumping", false},
3341 {"nglayout.debug.invalidate_dumping", false},
3342 {"nglayout.debug.motion_event_dumping", false},
3343 {"nglayout.debug.paint_dumping", false}};
3345 //////////////////////////////////////////////////////////////
3346 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName) {
3347 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3349 for (uint32_t i = 0; i < std::size(debug_PrefValues); i++) {
3350 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3351 return debug_PrefValues[i].value;
3355 return false;
3357 //////////////////////////////////////////////////////////////
3358 static void debug_SetCachedBoolPref(const char* aPrefName, bool aValue) {
3359 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3361 for (uint32_t i = 0; i < std::size(debug_PrefValues); i++) {
3362 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3363 debug_PrefValues[i].value = aValue;
3365 return;
3369 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3372 //////////////////////////////////////////////////////////////
3373 class Debug_PrefObserver final : public nsIObserver {
3374 ~Debug_PrefObserver() = default;
3376 public:
3377 NS_DECL_ISUPPORTS
3378 NS_DECL_NSIOBSERVER
3381 NS_IMPL_ISUPPORTS(Debug_PrefObserver, nsIObserver)
3383 NS_IMETHODIMP
3384 Debug_PrefObserver::Observe(nsISupports* subject, const char* topic,
3385 const char16_t* data) {
3386 NS_ConvertUTF16toUTF8 prefName(data);
3388 bool value = Preferences::GetBool(prefName.get(), false);
3389 debug_SetCachedBoolPref(prefName.get(), value);
3390 return NS_OK;
3393 //////////////////////////////////////////////////////////////
3394 /* static */ void debug_RegisterPrefCallbacks() {
3395 static bool once = true;
3397 if (!once) {
3398 return;
3401 once = false;
3403 nsCOMPtr<nsIObserver> obs(new Debug_PrefObserver());
3404 for (uint32_t i = 0; i < std::size(debug_PrefValues); i++) {
3405 // Initialize the pref values
3406 debug_PrefValues[i].value =
3407 Preferences::GetBool(debug_PrefValues[i].name, false);
3409 if (obs) {
3410 // Register callbacks for when these change
3411 nsCString name;
3412 name.AssignLiteral(debug_PrefValues[i].name,
3413 strlen(debug_PrefValues[i].name));
3414 Preferences::AddStrongObserver(obs, name);
3418 //////////////////////////////////////////////////////////////
3419 static int32_t _GetPrintCount() {
3420 static int32_t sCount = 0;
3422 return ++sCount;
3424 //////////////////////////////////////////////////////////////
3425 /* static */
3426 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut, nsIWidget* aWidget,
3427 WidgetGUIEvent* aGuiEvent,
3428 const char* aWidgetName, int32_t aWindowID) {
3429 if (aGuiEvent->mMessage == eMouseMove) {
3430 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3433 if (aGuiEvent->mMessage == eMouseEnterIntoWidget ||
3434 aGuiEvent->mMessage == eMouseExitFromWidget) {
3435 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3436 return;
3439 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3441 fprintf(aFileOut, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3442 _GetPrintCount(), ToChar(aGuiEvent->mMessage), (void*)aWidget,
3443 aWidgetName, aWindowID, aGuiEvent->mRefPoint.x.value,
3444 aGuiEvent->mRefPoint.y.value);
3446 //////////////////////////////////////////////////////////////
3447 /* static */
3448 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut, nsIWidget* aWidget,
3449 const nsIntRegion& aRegion,
3450 const char* aWidgetName,
3451 int32_t aWindowID) {
3452 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3453 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3455 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3457 nsIntRect rect = aRegion.GetBounds();
3458 fprintf(aFileOut,
3459 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3460 "%3d,%-3d",
3461 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID, rect.X(),
3462 rect.Y(), rect.Width(), rect.Height());
3464 fprintf(aFileOut, "\n");
3466 //////////////////////////////////////////////////////////////
3467 /* static */
3468 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut, nsIWidget* aWidget,
3469 const LayoutDeviceIntRect* aRect,
3470 const char* aWidgetName,
3471 int32_t aWindowID) {
3472 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3474 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3475 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3477 fprintf(aFileOut, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3478 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID);
3480 if (aRect) {
3481 fprintf(aFileOut, " rect=%3d,%-3d %3d,%-3d", aRect->X(), aRect->Y(),
3482 aRect->Width(), aRect->Height());
3483 } else {
3484 fprintf(aFileOut, " rect=%-15s", "none");
3487 fprintf(aFileOut, "\n");
3489 //////////////////////////////////////////////////////////////
3491 #endif // DEBUG