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"
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"
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"
82 # include "nsAccessibilityService.h"
84 #include "gfxConfig.h"
85 #include "gfxUtils.h" // for ToDeviceColor
86 #include "mozilla/layers/CompositorSession.h"
87 #include "VRManagerChild.h"
88 #include "gfxConfig.h"
90 #include "nsViewManager.h"
92 static mozilla::LazyLogModule
sBaseWidgetLog("BaseWidget");
95 # include "nsIObserver.h"
97 static void debug_RegisterPrefCallbacks();
101 #ifdef NOISY_WIDGET_LEAKS
102 static int32_t gNumWidgets
;
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
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
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
),
145 mPopupLevel(PopupLevel::Top
),
146 mPopupType(PopupType::Any
),
147 mHasRemoteContent(false),
149 mUseAttachedEvents(false),
152 mIsFullyOccluded(false),
153 mNeedFastSnaphot(false),
154 mCurrentPanGestureBelongsToSwipe(false),
155 mIsPIPWindow(false) {
156 #ifdef NOISY_WIDGET_LEAKS
158 printf("WIDGETS+ = %d\n", gNumWidgets
);
162 debug_RegisterPrefCallbacks();
165 mShutdownObserver
= new WidgetShutdownObserver(this);
168 NS_IMPL_ISUPPORTS(WidgetShutdownObserver
, nsIObserver
)
170 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget
* aWidget
)
171 : mWidget(aWidget
), mRegistered(false) {
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.
182 WidgetShutdownObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
183 const char16_t
* aData
) {
187 if (!strcmp(aTopic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
)) {
188 RefPtr
<nsBaseWidget
> widget(mWidget
);
190 } else if (!strcmp(aTopic
, "quit-application")) {
191 RefPtr
<nsBaseWidget
> widget(mWidget
);
197 void WidgetShutdownObserver::Register() {
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);
218 void WidgetShutdownObserver::Unregister() {
222 #ifndef MOZ_WIDGET_ANDROID
223 nsCOMPtr
<nsIObserverService
> observerService
=
224 mozilla::services::GetObserverService();
225 if (observerService
) {
226 observerService
->RemoveObserver(this, "quit-application");
230 nsContentUtils::UnregisterShutdownObserver(this);
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) {
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.
251 LocalesChangedObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
252 const char16_t
* aData
) {
256 if (!strcmp(aTopic
, INTL_APP_LOCALES_CHANGED
)) {
257 RefPtr
<nsBaseWidget
> widget(mWidget
);
258 widget
->LocalesChanged();
263 void LocalesChangedObserver::Register() {
268 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
270 obs
->AddObserver(this, INTL_APP_LOCALES_CHANGED
, true);
273 // Locale might be update before registering
274 RefPtr
<nsBaseWidget
> widget(mWidget
);
275 widget
->LocalesChanged();
280 void LocalesChangedObserver::Unregister() {
285 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
287 obs
->RemoveObserver(this, INTL_APP_LOCALES_CHANGED
);
294 void nsBaseWidget::Shutdown() {
295 NotifyLiveResizeStopped();
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();
337 SetCompositorWidgetDelegate(nullptr);
338 mCompositorBridgeChild
= nullptr;
339 mCompositorSession
->Shutdown();
340 mCompositorSession
= nullptr;
344 // This prevents the layer manager from starting a new transaction during
346 void nsBaseWidget::RevokeTransactionIdAllocator() {
347 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
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;
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() {
392 mSwipeTracker
->Destroy();
393 mSwipeTracker
= nullptr;
396 IMEStateManager::WidgetDestroyed(this);
398 FreeLocalesChangedObserver();
399 FreeShutdownObserver();
400 DestroyLayerManager();
402 #ifdef NOISY_WIDGET_LEAKS
404 printf("WIDGETS- = %d\n", gNumWidgets
);
408 //-------------------------------------------------------------------------
412 //-------------------------------------------------------------------------
413 void nsBaseWidget::BaseCreate(nsIWidget
* aParent
, widget::InitData
* 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
;
425 mParent
->AddToChildList(this);
429 void nsIWidget::ClearParent() {
433 nsCOMPtr
<nsIWidget
> kungFuDeathGrip
= this;
434 nsCOMPtr
<nsIWidget
> oldParent
= mParent
;
435 oldParent
->RemoveFromChildList(this);
437 DidClearParent(oldParent
);
440 void nsIWidget::RemoveAllChildren() {
441 while (nsCOMPtr
<nsIWidget
> kid
= mLastChild
) {
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();
469 widget
= nsIWidget::CreateChildWindow();
473 case WidgetType::Headless
:
474 widget
= nsIWidget::CreateHeadlessWidget();
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);
489 if (mNeedFastSnaphot
) {
490 widget
->SetNeedFastSnaphot();
493 if (NS_FAILED(widget
->Create(this, aRect
, &aInitData
))) {
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() {
536 // Just in case our parent is the only ref to us
537 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
538 // disconnect from the parent
540 mParent
->RemoveFromChildList(this);
543 // disconnect from the children
547 nsIWidget
* nsIWidget::GetTopLevelWidget() {
550 if (cur
->IsTopLevelWidget()) {
553 nsIWidget
* parent
= cur
->GetParent();
562 float nsBaseWidget::GetDPI() { return 96.0f
; }
564 void nsBaseWidget::NotifyAPZOfDPIChange() {
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());
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() {
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");
613 mFirstChild
= mLastChild
= aChild
;
615 // append to the list
616 MOZ_ASSERT(mLastChild
);
617 MOZ_ASSERT(!mLastChild
->GetNextSibling());
618 mLastChild
->SetNextSibling(aChild
);
619 aChild
->SetPrevSibling(mLastChild
);
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();
644 prev
->SetNextSibling(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
) {
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;
678 //-------------------------------------------------------------------------
680 // Window transparency methods
682 //-------------------------------------------------------------------------
684 void nsBaseWidget::SetTransparencyMode(TransparencyMode aMode
) {}
686 TransparencyMode
nsBaseWidget::GetTransparencyMode() {
687 return TransparencyMode::Opaque
;
691 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage
,
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
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");
742 HideWindowChrome(aFullScreen
);
743 hasAdjustedOSChrome
= true;
745 const auto adjustChromeOnScopeExit
= MakeScopeExit([&]() {
746 if (hasAdjustedOSChrome
) {
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();
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
)));
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
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);
799 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
800 ("resized to: " MOZ_FORMAT_RECT("%f"),
801 MOZ_SPLAT_RECT(rectAsFloat
)));
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
)));
812 sBaseWidgetLog
, LogLevel::Verbose
,
813 ("(... which, before DPI adjustment, is:" MOZ_FORMAT_RECT("%d") ")",
814 MOZ_SPLAT_RECT(postResizeRectRaw
)));
820 mSavedBounds
= Some(FullscreenSavedState());
822 // save current position
823 mSavedBounds
->windowRect
= GetScreenBounds() / GetDesktopToDeviceScale();
825 nsCOMPtr
<nsIScreen
> screen
= GetWidgetScreen();
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();
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");
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
);
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
));
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
);
923 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
924 nsBaseWidget
* aWidget
, gfxContext
* aTarget
, BufferMode aDoubleBuffering
)
926 WindowRenderer
* renderer
= mWidget
->GetWindowRenderer();
927 if (renderer
->AsFallback()) {
928 mRenderer
= renderer
->AsFallback();
929 mRenderer
->SetTarget(aTarget
, aDoubleBuffering
);
933 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
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()) {
955 // Always use APZ for top-level windows
956 if (mWindowType
== WindowType::TopLevel
|| mWindowType
== WindowType::Child
) {
960 // Never use APZ for tooltips
961 if (mWindowType
== WindowType::Popup
&& mPopupType
== PopupType::Tooltip
) {
965 if (!StaticPrefs::apz_popups_enabled()) {
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
;
979 void nsBaseWidget::CreateCompositor() {
980 LayoutDeviceIntRect rect
= GetBounds();
981 CreateCompositor(rect
.Width(), rect
.Height());
984 void nsIWidget::PauseOrResumeCompositor(bool aPause
) {
985 auto* renderer
= GetRemoteRenderer();
990 renderer
->SendPause();
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());
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
);
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()));
1058 mInitialZoomConstraints
.reset();
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
,
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
,
1129 mAPZEventState
->ProcessMouseEvent(*mouseEvent
, inputBlockId
);
1131 if (postLayerization
) {
1132 postLayerization
->Register();
1139 template <class InputType
, class EventType
>
1140 class DispatchEventOnMainThread
: public Runnable
{
1142 DispatchEventOnMainThread(const InputType
& aInput
, nsBaseWidget
* aWidget
,
1143 const APZEventResult
& aAPZResult
)
1144 : mozilla::Runnable("DispatchEventOnMainThread"),
1147 mAPZResult(aAPZResult
) {}
1149 NS_IMETHOD
Run() override
{
1150 EventType event
= mInput
.ToWidgetEvent(mWidget
);
1151 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1157 nsBaseWidget
* mWidget
;
1158 APZEventResult mAPZResult
;
1162 NS_IMETHODIMP DispatchEventOnMainThread
<MouseInput
, WidgetMouseEvent
>::Run() {
1164 !mInput
.IsPointerEventType(),
1165 "Please use DispatchEventOnMainThread<MouseInput, WidgetPointerEvent>");
1166 WidgetMouseEvent event
= mInput
.ToWidgetEvent
<WidgetMouseEvent
>(mWidget
);
1167 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1172 NS_IMETHODIMP DispatchEventOnMainThread
<MouseInput
, WidgetPointerEvent
>::Run() {
1174 mInput
.IsPointerEventType(),
1175 "Please use DispatchEventOnMainThread<MouseInput, WidgetMouseEvent>");
1176 WidgetPointerEvent event
= mInput
.ToWidgetEvent
<WidgetPointerEvent
>(mWidget
);
1177 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1181 template <class InputType
, class EventType
>
1182 class DispatchInputOnControllerThread
: public Runnable
{
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()),
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
) {
1202 RefPtr
<Runnable
> r
= new DispatchEventOnMainThread
<InputType
, EventType
>(
1203 mInput
, mWidget
, result
);
1204 mMainMessageLoop
->PostTask(r
.forget());
1209 MessageLoop
* mMainMessageLoop
;
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
);
1223 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1225 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1226 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1230 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1231 ProcessUntransformedAPZEvent(&event
, result
);
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());
1243 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1245 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1246 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1250 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1251 ProcessUntransformedAPZEvent(&event
, result
);
1253 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1254 nsEventStatus status
;
1255 DispatchEvent(&event
, status
);
1259 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput
& aInput
) {
1260 MOZ_ASSERT(NS_IsMainThread());
1262 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1263 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1265 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1268 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1269 ProcessUntransformedAPZEvent(&event
, result
);
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());
1283 if (APZThreadUtils::IsControllerThread()) {
1284 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1285 status
.mApzStatus
= result
.GetStatus();
1286 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1289 status
.mContentStatus
= ProcessUntransformedAPZEvent(aEvent
, result
);
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
,
1303 APZThreadUtils::RunOnControllerThread(std::move(r
));
1304 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
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
;
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
;
1324 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1325 RefPtr
<Runnable
> r
=
1326 new DispatchInputOnControllerThread
<MultiTouchInput
,
1327 WidgetTouchEvent
>(*touchEvent
,
1329 APZThreadUtils::RunOnControllerThread(std::move(r
));
1330 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
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
);
1346 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent
* aEvent
) {
1347 MOZ_ASSERT(NS_IsMainThread());
1349 if (APZThreadUtils::IsControllerThread()) {
1350 mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
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
));
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();
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
);
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
)) {
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
);
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());
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);
1464 options
.SetInitiallyPaused(CompositorInitiallyPaused());
1467 RefPtr
<WebRenderLayerManager
> lm
= new WebRenderLayerManager(this);
1469 uint64_t innerWindowId
= 0;
1470 if (Document
* doc
= GetDocument()) {
1471 innerWindowId
= doc
->InnerWindowID();
1475 mCompositorSession
= gpu
->CreateTopLevelCompositor(
1476 this, lm
, GetDefaultScale(), options
, UseExternalCompositingSurface(),
1477 gfx::IntSize(aWidth
, aHeight
), innerWindowId
, &retry
);
1479 if (mCompositorSession
) {
1480 TextureFactoryIdentifier textureFactoryIdentifier
;
1482 lm
->Initialize(mCompositorSession
->GetCompositorBridgeChild(),
1483 wr::AsPipelineId(mCompositorSession
->RootLayerTreeId()),
1484 &textureFactoryIdentifier
, error
);
1485 if (textureFactoryIdentifier
.mParentBackend
!= LayersBackend::LAYERS_WR
) {
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
;
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 "
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
) {
1527 // The controller thread must be configured before the compositor
1528 // session is created, so that the input bridge runs on the right
1530 ConfigureAPZControllerThread();
1532 CompositorOptions options
;
1533 RefPtr
<WebRenderLayerManager
> lm
=
1534 CreateCompositorSession(aWidth
, aHeight
, &options
);
1539 MOZ_ASSERT(mCompositorSession
);
1540 mCompositorBridgeChild
= mCompositorSession
->GetCompositorBridgeChild();
1541 SetCompositorWidgetDelegate(
1542 mCompositorSession
->GetCompositorWidgetDelegate());
1544 if (options
.UseAPZ()) {
1545 mAPZC
= mCompositorSession
->GetAPZCTreeManager();
1546 ConfigureAPZCTreeManager();
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
);
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;
1574 bool getCompositorFromThisWindow
= mWindowType
== WindowType::TopLevel
;
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
1598 // Try to use an async compositor first, if possible
1599 if (ShouldUseOffMainThreadCompositing()) {
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()) {
1622 mWindowRenderer
->AsWebRender()->ClearCachedResources();
1625 void nsBaseWidget::ClearWebrenderAnimationResources() {
1626 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1629 mWindowRenderer
->AsWebRender()->ClearAnimationResources();
1632 bool nsBaseWidget::SetNeedFastSnaphot() {
1633 MOZ_ASSERT(XRE_IsParentProcess());
1634 MOZ_ASSERT(!mCompositorSession
);
1636 if (!XRE_IsParentProcess() || mCompositorSession
) {
1640 mNeedFastSnaphot
= true;
1644 already_AddRefed
<gfx::DrawTarget
> nsBaseWidget::StartRemoteDrawing() {
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();
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
1685 if (point
.x
>= maxX
) {
1688 if (point
.x
< aScreenRect
.x
) {
1689 point
.x
= aScreenRect
.x
;
1692 if (point
.y
>= maxY
) {
1695 if (point
.y
< aScreenRect
.y
) {
1696 point
.y
= aScreenRect
.y
;
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
);
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
,
1733 LayoutDeviceSize layoutSize
= aSize
* GetDesktopToDeviceScale();
1734 Resize(mBounds
.Width() + (layoutSize
.width
- clientBounds
.Width()),
1735 mBounds
.Height() + (layoutSize
.height
- clientBounds
.Height()),
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()) /
1754 Resize(aRect
.X() - desktopOffset
.x
, aRect
.Y() - desktopOffset
.y
,
1755 aRect
.Width() + desktopDelta
.width
,
1756 aRect
.Height() + desktopDelta
.height
, aRepaint
);
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(),
1766 //-------------------------------------------------------------------------
1770 //-------------------------------------------------------------------------
1773 * If the implementation of nsWindow supports borders this method MUST be
1777 LayoutDeviceIntRect
nsBaseWidget::GetClientBounds() { return GetBounds(); }
1780 * If the implementation of nsWindow supports borders this method MUST be
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();
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
) {
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
);
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
) {
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
));
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
);
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
) {
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
) {
1895 if (BoundsUseDesktopPixels()) {
1896 DesktopSize desktopSize
= clampedSize
/ GetDesktopToDeviceScale();
1897 size
= desktopSize
.ToUnknownSize();
1899 size
= gfx::Size(clampedSize
.ToUnknownSize());
1901 Resize(size
.width
, size
.height
, true);
1905 const widget::SizeConstraints
nsBaseWidget::GetSizeConstraints() {
1906 return mSizeConstraints
;
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
));
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
) {
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
) {
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
);
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;
1985 void nsBaseWidget::EnsureTextEventDispatcher() {
1986 if (mTextEventDispatcher
) {
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();
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.
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
) {
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();
2055 return accService
->GetRootDocumentAccessible(
2056 presShell
, nsContentUtils::IsSafeToRunScript());
2062 #endif // ACCESSIBILITY
2064 void nsBaseWidget::StartAsyncScrollbarDrag(
2065 const AsyncDragMetrics
& aDragMetrics
) {
2066 if (!AsyncPanZoomEnabled()) {
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()
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
,
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
,
2122 if (NS_FAILED(rv
)) {
2127 return SynthesizeNativeTouchPoint(pointerId
, TOUCH_REMOVE
, aPoint
, 0, 0,
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,
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
2166 void nsIWidget::OnLongTapTimerCallback(nsITimer
* aTimer
, void* aClosure
) {
2167 auto* self
= static_cast<nsIWidget
*>(aClosure
);
2169 if ((self
->mLongTapTouchPoint
->mStamp
+ self
->mLongTapTouchPoint
->mDuration
) >
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);
2181 AutoObserverNotifier
notifier(self
->mLongTapTouchPoint
->mObserver
,
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
) {
2213 mLongTapTimer
->Cancel();
2214 mLongTapTimer
= nullptr;
2215 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2216 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2217 mLongTapTouchPoint
= nullptr;
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
) {
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
;
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
;
2255 MOZ_ASSERT(aPointerState
== TOUCH_REMOVE
|| aPointerState
== TOUCH_CANCEL
);
2256 // a touch point is being lifted, so remove it from the stored list
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
) {
2283 nsCOMPtr
<nsIAppWindow
> appWindow
= mWidgetListener
->GetAppWindow();
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
,
2320 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== aInputBlockId
) {
2322 PanGestureInput
& startEvent
= mSwipeEventQueue
->queuedEvents
[0];
2323 TrackScrollEventAsSwipe(startEvent
, mSwipeEventQueue
->allowedDirections
,
2325 for (size_t i
= 1; i
< mSwipeEventQueue
->queuedEvents
.Length(); i
++) {
2326 mSwipeTracker
->ProcessEvent(mSwipeEventQueue
->queuedEvents
[i
]);
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
;
2354 new SwipeTracker(*this, aSwipeStartEvent
, aAllowedDirections
, direction
);
2357 mCurrentPanGestureBelongsToSwipe
= true;
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
};
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.
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
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
);
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
);
2441 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput
& aPanInput
) {
2442 // Ignore swipe-to-navigation in PiP window.
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 "
2458 "and it should have consumed this event.");
2462 if (!aPanInput
.MayTriggerSwipe()) {
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.
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
);
2497 LayersId
nsBaseWidget::GetLayersId() const {
2498 return mCompositorSession
? mCompositorSession
->RootLayerTreeId()
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());
2517 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboard() {
2518 if (XRE_IsContentProcess()) {
2519 return CreateBidiKeyboardContentProcess();
2521 return CreateBidiKeyboardInner();
2525 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboardInner() {
2526 // no bidi keyboard implementation
2531 namespace mozilla::widget
{
2533 const char* ToChar(InputContext::Origin aOrigin
) {
2535 case InputContext::ORIGIN_MAIN
:
2536 return "ORIGIN_MAIN";
2537 case InputContext::ORIGIN_CONTENT
:
2538 return "ORIGIN_CONTENT";
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";
2567 return "Unexpected value";
2571 void NativeIMEContext::Init(nsIWidget
* aWidget
) {
2573 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2574 mOriginProcessID
= static_cast<uint64_t>(-1);
2577 if (!XRE_IsContentProcess()) {
2578 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(
2579 aWidget
->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT
));
2580 mOriginProcessID
= 0;
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);
2596 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(aRawNativeIMEContext
);
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");
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
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
2666 mIncludingChangesDuringComposition
= false;
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
) {
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
2687 uint32_t newRemovedEndOffsetInOldText
=
2688 newData
.mRemovedEndOffset
- oldData
.Difference();
2690 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2691 // The new end offset of added text is always the larger offset.
2692 mAddedEndOffset
= newData
.mAddedEndOffset
;
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
) {
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
2711 uint32_t newRemovedEndOffsetInOldText
=
2712 newData
.mRemovedEndOffset
- oldData
.Difference();
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
;
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();
2737 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
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
) {
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
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
2759 uint32_t newRemovedEndOffsetInOldText
=
2760 newData
.mRemovedEndOffset
- oldData
.Difference();
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
;
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
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();
2788 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
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();
2807 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
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
) {
2820 gTestTextChangeEvent
= false;
2822 /****************************************************************************
2824 ****************************************************************************/
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");
2832 mRemovedEndOffset
== 10, // 20 - (20 - 10)
2833 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2835 mAddedEndOffset
== 35,
2836 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
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 "
2847 "with already removed length");
2849 mAddedEndOffset
== 10,
2850 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
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 "
2861 "with already removed length");
2863 mAddedEndOffset
== 10,
2864 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
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");
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");
2877 mAddedEndOffset
== 60,
2878 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
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");
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");
2891 mAddedEndOffset
== 55,
2892 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
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");
2901 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2902 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2905 mAddedEndOffset
== 40,
2906 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
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");
2915 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2916 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2919 mAddedEndOffset
== 33,
2920 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2923 // Removing text and replacing text after first range (not sure if actually
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 "
2932 "without already removed text");
2934 mAddedEndOffset
== 48,
2935 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2938 // Removing text and replacing text after first range (not sure if actually
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 "
2947 "without already removed text");
2949 mAddedEndOffset
== 36,
2950 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2953 /****************************************************************************
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 "
2966 "without already added text length");
2968 mAddedEndOffset
== 54,
2969 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
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 "
2981 "without already added text length");
2983 mAddedEndOffset
== 68,
2984 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2987 // Replacing text around end of replaced text (became shorter) (not sure if
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 "
2996 "without already removed text length");
2998 mAddedEndOffset
== 49,
2999 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
3002 // Replacing text around end of replaced text (became longer) (not sure if
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 "
3011 "without already added text length");
3013 mAddedEndOffset
== 61,
3014 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
3017 /****************************************************************************
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 "
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");
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 "
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");
3049 // Replacing text in replaced text (became shorter) (not sure if actually
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 "
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");
3064 // Replacing text in replaced text (became longer) (not sure if actually
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 "
3073 "without already added text length");
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");
3080 // Replacing text in replaced text (became shorter) (not sure if actually
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");
3087 mRemovedEndOffset
== 48,
3088 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
3090 MOZ_ASSERT(mAddedEndOffset
== 48, // 50 + (47 - 49)
3091 "Test 3-5-3: mAddedEndOffset should be the first end of added "
3093 "removed text length by the new change");
3096 // Replacing text in replaced text (became longer) (not sure if actually
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 "
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 "
3109 "removed text length by the new change");
3112 /****************************************************************************
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 "
3124 "without already added text length");
3126 mAddedEndOffset
== 68,
3127 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3130 // Replacing text around a point in which text was removed (not sure if
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 "
3139 "without already removed text length");
3141 mAddedEndOffset
== 68,
3142 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3145 // Replacing text all replaced text (became shorter) (not sure if actually
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 "
3154 "without already removed text length");
3156 mAddedEndOffset
== 130,
3157 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3160 // Replacing text all replaced text (became longer) (not sure if actually
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 "
3169 "with already added text length");
3171 mAddedEndOffset
== 50,
3172 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3175 /****************************************************************************
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");
3185 mRemovedEndOffset
== 50,
3186 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
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");
3194 // Replacing text around start of replaced text (became shorter) (not sure if
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");
3201 mRemovedEndOffset
== 60,
3202 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3204 MOZ_ASSERT(mAddedEndOffset
== 56, // 58 + (48 - 50)
3205 "Test 5-2-3: mAddedEndOffset should be the first end of added "
3207 "removed text length by the new change");
3210 // Replacing text around start of replaced text (became longer) (not sure if
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");
3217 mRemovedEndOffset
== 60,
3218 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3220 MOZ_ASSERT(mAddedEndOffset
== 66, // 68 + (53 - 55)
3221 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3223 "removed text length by the new change");
3226 // Replacing text around start of replaced text (became shorter) (not sure if
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");
3233 mRemovedEndOffset
== 60,
3234 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
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");
3242 // Replacing text around start of replaced text (became longer) (not sure if
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");
3249 mRemovedEndOffset
== 60,
3250 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
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");
3258 /****************************************************************************
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");
3268 mRemovedEndOffset
== 30,
3269 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
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");
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");
3283 mRemovedEndOffset
== 35,
3284 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
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");
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");
3298 mRemovedEndOffset
== 65,
3299 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3301 MOZ_ASSERT(mAddedEndOffset
== 61, // 70 + (15 - 24)
3302 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3304 "removed text length by the new change");
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");
3313 mRemovedEndOffset
== 65,
3314 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3316 MOZ_ASSERT(mAddedEndOffset
== 82, // 70 + (36 - 24)
3317 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3319 "removed text length by the new change");
3323 #endif // #ifdef DEBUG
3325 } // namespace mozilla::widget
3328 //////////////////////////////////////////////////////////////
3330 // Code to deal with paint and event debug prefs.
3332 //////////////////////////////////////////////////////////////
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
;
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
;
3369 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3372 //////////////////////////////////////////////////////////////
3373 class Debug_PrefObserver final
: public nsIObserver
{
3374 ~Debug_PrefObserver() = default;
3381 NS_IMPL_ISUPPORTS(Debug_PrefObserver
, nsIObserver
)
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
);
3393 //////////////////////////////////////////////////////////////
3394 /* static */ void debug_RegisterPrefCallbacks() {
3395 static bool once
= true;
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);
3410 // Register callbacks for when these change
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;
3424 //////////////////////////////////////////////////////////////
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"))
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 //////////////////////////////////////////////////////////////
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();
3459 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3461 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
, rect
.X(),
3462 rect
.Y(), rect
.Width(), rect
.Height());
3464 fprintf(aFileOut
, "\n");
3466 //////////////////////////////////////////////////////////////
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
);
3481 fprintf(aFileOut
, " rect=%3d,%-3d %3d,%-3d", aRect
->X(), aRect
->Y(),
3482 aRect
->Width(), aRect
->Height());
3484 fprintf(aFileOut
, " rect=%-15s", "none");
3487 fprintf(aFileOut
, "\n");
3489 //////////////////////////////////////////////////////////////