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"
65 #include "nsContentUtils.h"
66 #include "nsDeviceContext.h"
67 #include "nsGfxCIID.h"
68 #include "nsIAppWindow.h"
69 #include "nsIBaseWindow.h"
70 #include "nsIContent.h"
71 #include "nsIScreenManager.h"
72 #include "nsISimpleEnumerator.h"
73 #include "nsIWidgetListener.h"
74 #include "nsRefPtrHashtable.h"
75 #include "nsServiceManagerUtils.h"
76 #include "nsWidgetsCID.h"
77 #include "nsXULPopupManager.h"
81 # include "nsAccessibilityService.h"
83 #include "gfxConfig.h"
84 #include "gfxUtils.h" // for ToDeviceColor
85 #include "mozilla/layers/CompositorSession.h"
86 #include "VRManagerChild.h"
87 #include "gfxConfig.h"
89 #include "nsViewManager.h"
91 static mozilla::LazyLogModule
sBaseWidgetLog("BaseWidget");
94 # include "nsIObserver.h"
96 static void debug_RegisterPrefCallbacks();
100 #ifdef NOISY_WIDGET_LEAKS
101 static int32_t gNumWidgets
;
104 using namespace mozilla::dom
;
105 using namespace mozilla::layers
;
106 using namespace mozilla::ipc
;
107 using namespace mozilla::widget
;
108 using namespace mozilla
;
110 // Async pump timer during injected long touch taps
111 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
112 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
113 int32_t nsIWidget::sPointerIdCounter
= 0;
115 // Some statics from nsIWidget.h
117 uint64_t AutoObserverNotifier::sObserverId
= 0;
118 /*static*/ nsTHashMap
<uint64_t, nsCOMPtr
<nsIObserver
>>
119 AutoObserverNotifier::sSavedObservers
;
121 // The maximum amount of time to let the EnableDragDrop runnable wait in the
122 // idle queue before timing out and moving it to the regular queue. Value is in
124 const uint32_t kAsyncDragDropTimeout
= 1000;
126 NS_IMPL_ISUPPORTS(nsBaseWidget
, nsIWidget
, nsISupportsWeakReference
)
128 //-------------------------------------------------------------------------
130 // nsBaseWidget constructor
132 //-------------------------------------------------------------------------
134 nsBaseWidget::nsBaseWidget() : nsBaseWidget(BorderStyle::None
) {}
136 nsBaseWidget::nsBaseWidget(BorderStyle aBorderStyle
)
137 : mWidgetListener(nullptr),
138 mAttachedWidgetListener(nullptr),
139 mPreviouslyAttachedWidgetListener(nullptr),
140 mCompositorVsyncDispatcher(nullptr),
141 mBorderStyle(aBorderStyle
),
144 mPopupLevel(PopupLevel::Top
),
145 mPopupType(PopupType::Any
),
146 mHasRemoteContent(false),
148 mUseAttachedEvents(false),
151 mIsFullyOccluded(false),
152 mNeedFastSnaphot(false),
153 mCurrentPanGestureBelongsToSwipe(false),
154 mIsPIPWindow(false) {
155 #ifdef NOISY_WIDGET_LEAKS
157 printf("WIDGETS+ = %d\n", gNumWidgets
);
161 debug_RegisterPrefCallbacks();
164 mShutdownObserver
= new WidgetShutdownObserver(this);
167 NS_IMPL_ISUPPORTS(WidgetShutdownObserver
, nsIObserver
)
169 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget
* aWidget
)
170 : mWidget(aWidget
), mRegistered(false) {
174 WidgetShutdownObserver::~WidgetShutdownObserver() {
175 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
176 // gets torn down. The observer service and nsBaseWidget have a ref on us
177 // so nsBaseWidget has to call Unregister and then clear its ref.
181 WidgetShutdownObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
182 const char16_t
* aData
) {
186 if (!strcmp(aTopic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
)) {
187 RefPtr
<nsBaseWidget
> widget(mWidget
);
189 } else if (!strcmp(aTopic
, "quit-application")) {
190 RefPtr
<nsBaseWidget
> widget(mWidget
);
196 void WidgetShutdownObserver::Register() {
199 nsContentUtils::RegisterShutdownObserver(this);
201 #ifndef MOZ_WIDGET_ANDROID
202 // The primary purpose of observing quit-application is
203 // to avoid leaking a widget on Windows when nothing else
204 // breaks the circular reference between the widget and
205 // TSFTextStore. However, our Android IME code crashes if
206 // doing this on Android, so let's not do this on Android.
207 // Doing this on Gtk and Mac just in case.
208 nsCOMPtr
<nsIObserverService
> observerService
=
209 mozilla::services::GetObserverService();
210 if (observerService
) {
211 observerService
->AddObserver(this, "quit-application", false);
217 void WidgetShutdownObserver::Unregister() {
221 #ifndef MOZ_WIDGET_ANDROID
222 nsCOMPtr
<nsIObserverService
> observerService
=
223 mozilla::services::GetObserverService();
224 if (observerService
) {
225 observerService
->RemoveObserver(this, "quit-application");
229 nsContentUtils::UnregisterShutdownObserver(this);
234 #define INTL_APP_LOCALES_CHANGED "intl:app-locales-changed"
236 NS_IMPL_ISUPPORTS(LocalesChangedObserver
, nsIObserver
)
238 LocalesChangedObserver::LocalesChangedObserver(nsBaseWidget
* aWidget
)
239 : mWidget(aWidget
), mRegistered(false) {
243 LocalesChangedObserver::~LocalesChangedObserver() {
244 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
245 // gets torn down. The observer service and nsBaseWidget have a ref on us
246 // so nsBaseWidget has to call Unregister and then clear its ref.
250 LocalesChangedObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
251 const char16_t
* aData
) {
255 if (!strcmp(aTopic
, INTL_APP_LOCALES_CHANGED
)) {
256 RefPtr
<nsBaseWidget
> widget(mWidget
);
257 widget
->LocalesChanged();
262 void LocalesChangedObserver::Register() {
267 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
269 obs
->AddObserver(this, INTL_APP_LOCALES_CHANGED
, true);
272 // Locale might be update before registering
273 RefPtr
<nsBaseWidget
> widget(mWidget
);
274 widget
->LocalesChanged();
279 void LocalesChangedObserver::Unregister() {
284 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
286 obs
->RemoveObserver(this, INTL_APP_LOCALES_CHANGED
);
293 void nsBaseWidget::Shutdown() {
294 NotifyLiveResizeStopped();
296 FreeLocalesChangedObserver();
297 FreeShutdownObserver();
300 void nsBaseWidget::QuitIME() {
301 IMEStateManager::WidgetOnQuit(this);
302 this->mIMEHasQuit
= true;
305 void nsBaseWidget::DestroyCompositor() {
306 RevokeTransactionIdAllocator();
308 // We release this before releasing the compositor, since it may hold the
309 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
310 // trigger a paint, creating a new compositor, and we don't want to re-use
311 // the old vsync dispatcher.
312 if (mCompositorVsyncDispatcher
) {
313 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
315 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
316 mCompositorVsyncDispatcher
->Shutdown();
317 mCompositorVsyncDispatcher
= nullptr;
320 // The compositor shutdown sequence looks like this:
321 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
322 // 2. CompositorBridgeChild synchronously sends WillClose.
323 // 3. CompositorBridgeParent releases some resources (such as the layer
324 // manager, compositor, and widget).
325 // 4. CompositorBridgeChild::Destroy returns.
326 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
327 // compositor thread when the I/O thread closes the IPC channel.
328 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
329 // releases the reference CompositorBridgeParent holds to itself.
331 // When CompositorSession::Shutdown returns, we assume the compositor is gone
332 // or will be gone very soon.
333 if (mCompositorSession
) {
334 ReleaseContentController();
336 SetCompositorWidgetDelegate(nullptr);
337 mCompositorBridgeChild
= nullptr;
338 mCompositorSession
->Shutdown();
339 mCompositorSession
= nullptr;
343 // This prevents the layer manager from starting a new transaction during
345 void nsBaseWidget::RevokeTransactionIdAllocator() {
346 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
349 mWindowRenderer
->AsWebRender()->SetTransactionIdAllocator(nullptr);
352 void nsBaseWidget::ReleaseContentController() {
353 if (mRootContentController
) {
354 mRootContentController
->Destroy();
355 mRootContentController
= nullptr;
359 void nsBaseWidget::DestroyLayerManager() {
360 if (mWindowRenderer
) {
361 mWindowRenderer
->Destroy();
362 mWindowRenderer
= nullptr;
367 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
369 void nsBaseWidget::FreeShutdownObserver() {
370 if (mShutdownObserver
) {
371 mShutdownObserver
->Unregister();
373 mShutdownObserver
= nullptr;
376 void nsBaseWidget::FreeLocalesChangedObserver() {
377 if (mLocalesChangedObserver
) {
378 mLocalesChangedObserver
->Unregister();
380 mLocalesChangedObserver
= nullptr;
383 //-------------------------------------------------------------------------
385 // nsBaseWidget destructor
387 //-------------------------------------------------------------------------
389 nsBaseWidget::~nsBaseWidget() {
391 mSwipeTracker
->Destroy();
392 mSwipeTracker
= nullptr;
395 IMEStateManager::WidgetDestroyed(this);
397 FreeLocalesChangedObserver();
398 FreeShutdownObserver();
399 DestroyLayerManager();
401 #ifdef NOISY_WIDGET_LEAKS
403 printf("WIDGETS- = %d\n", gNumWidgets
);
407 //-------------------------------------------------------------------------
411 //-------------------------------------------------------------------------
412 void nsBaseWidget::BaseCreate(nsIWidget
* aParent
, widget::InitData
* aInitData
) {
414 mWindowType
= aInitData
->mWindowType
;
415 mBorderStyle
= aInitData
->mBorderStyle
;
416 mPopupLevel
= aInitData
->mPopupLevel
;
417 mPopupType
= aInitData
->mPopupHint
;
418 mHasRemoteContent
= aInitData
->mHasRemoteContent
;
419 mIsPIPWindow
= aInitData
->mPIPWindow
;
423 aParent
->AddChild(this);
427 //-------------------------------------------------------------------------
429 // Accessor functions to get/set the client data
431 //-------------------------------------------------------------------------
433 nsIWidgetListener
* nsBaseWidget::GetWidgetListener() const {
434 return mWidgetListener
;
437 void nsBaseWidget::SetWidgetListener(nsIWidgetListener
* aWidgetListener
) {
438 mWidgetListener
= aWidgetListener
;
441 already_AddRefed
<nsIWidget
> nsBaseWidget::CreateChild(
442 const LayoutDeviceIntRect
& aRect
, widget::InitData
* aInitData
,
443 bool aForceUseIWidgetParent
) {
444 nsIWidget
* parent
= this;
445 nsNativeWidget nativeParent
= nullptr;
447 if (!aForceUseIWidgetParent
) {
448 // Use only either parent or nativeParent, not both, to match
449 // existing code. Eventually Create() should be divested of its
450 // nativeWidget parameter.
451 nativeParent
= parent
? parent
->GetNativeData(NS_NATIVE_WIDGET
) : nullptr;
452 parent
= nativeParent
? nullptr : parent
;
453 MOZ_ASSERT(!parent
|| !nativeParent
, "messed up logic");
456 nsCOMPtr
<nsIWidget
> widget
;
457 if (aInitData
&& aInitData
->mWindowType
== WindowType::Popup
) {
458 widget
= AllocateChildPopupWidget();
460 widget
= nsIWidget::CreateChildWindow();
463 if (widget
&& mNeedFastSnaphot
) {
464 widget
->SetNeedFastSnaphot();
468 NS_SUCCEEDED(widget
->Create(parent
, nativeParent
, aRect
, aInitData
))) {
469 return widget
.forget();
475 // Attach a view to our widget which we'll send events to.
476 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents
) {
477 NS_ASSERTION((mWindowType
== WindowType::TopLevel
||
478 mWindowType
== WindowType::Dialog
||
479 mWindowType
== WindowType::Invisible
||
480 mWindowType
== WindowType::Child
),
481 "Can't attach to window of that type");
483 mUseAttachedEvents
= aUseAttachedEvents
;
486 nsIWidgetListener
* nsBaseWidget::GetAttachedWidgetListener() const {
487 return mAttachedWidgetListener
;
490 nsIWidgetListener
* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
491 return mPreviouslyAttachedWidgetListener
;
494 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
495 nsIWidgetListener
* aListener
) {
496 mPreviouslyAttachedWidgetListener
= aListener
;
499 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener
* aListener
) {
500 mAttachedWidgetListener
= aListener
;
503 //-------------------------------------------------------------------------
505 // Close this nsBaseWidget
507 //-------------------------------------------------------------------------
508 void nsBaseWidget::Destroy() {
511 // Just in case our parent is the only ref to us
512 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
513 // disconnect from the parent
514 nsIWidget
* parent
= GetParent();
516 parent
->RemoveChild(this);
520 //-------------------------------------------------------------------------
522 // Get this nsBaseWidget parent
524 //-------------------------------------------------------------------------
525 nsIWidget
* nsBaseWidget::GetParent(void) { return nullptr; }
527 //-------------------------------------------------------------------------
529 // Get this nsBaseWidget top level widget
531 //-------------------------------------------------------------------------
532 nsIWidget
* nsBaseWidget::GetTopLevelWidget() {
533 nsIWidget
*topLevelWidget
= nullptr, *widget
= this;
535 topLevelWidget
= widget
;
536 widget
= widget
->GetParent();
538 return topLevelWidget
;
541 //-------------------------------------------------------------------------
543 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
545 //-------------------------------------------------------------------------
546 nsIWidget
* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
548 float nsBaseWidget::GetDPI() { return 96.0f
; }
550 CSSToLayoutDeviceScale
nsIWidget::GetDefaultScale() {
551 double devPixelsPerCSSPixel
= StaticPrefs::layout_css_devPixelsPerPx();
553 if (devPixelsPerCSSPixel
<= 0.0) {
554 devPixelsPerCSSPixel
= GetDefaultScaleInternal();
557 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel
);
560 nsIntSize
nsIWidget::CustomCursorSize(const Cursor
& aCursor
) {
561 MOZ_ASSERT(aCursor
.IsCustom());
564 aCursor
.mContainer
->GetWidth(&width
);
565 aCursor
.mContainer
->GetHeight(&height
);
566 aCursor
.mResolution
.ApplyTo(width
, height
);
567 return {width
, height
};
570 LayoutDeviceIntSize
nsIWidget::ClientToWindowSizeDifference() {
571 auto margin
= ClientToWindowMargin();
572 MOZ_ASSERT(margin
.top
>= 0, "Window should be bigger than client area");
573 MOZ_ASSERT(margin
.left
>= 0, "Window should be bigger than client area");
574 MOZ_ASSERT(margin
.right
>= 0, "Window should be bigger than client area");
575 MOZ_ASSERT(margin
.bottom
>= 0, "Window should be bigger than client area");
576 return {margin
.LeftRight(), margin
.TopBottom()};
579 RefPtr
<mozilla::VsyncDispatcher
> nsIWidget::GetVsyncDispatcher() {
583 //-------------------------------------------------------------------------
585 // Add a child to the list of children
587 //-------------------------------------------------------------------------
588 void nsBaseWidget::AddChild(nsIWidget
* aChild
) {
589 MOZ_ASSERT(!aChild
->GetNextSibling() && !aChild
->GetPrevSibling(),
590 "aChild not properly removed from its old child list");
593 mFirstChild
= mLastChild
= aChild
;
595 // append to the list
596 MOZ_ASSERT(mLastChild
);
597 MOZ_ASSERT(!mLastChild
->GetNextSibling());
598 mLastChild
->SetNextSibling(aChild
);
599 aChild
->SetPrevSibling(mLastChild
);
604 //-------------------------------------------------------------------------
606 // Remove a child from the list of children
608 //-------------------------------------------------------------------------
609 void nsBaseWidget::RemoveChild(nsIWidget
* aChild
) {
612 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
613 // null and we'll just have to do without this assertion.
614 nsIWidget
* parent
= aChild
->GetParent();
615 NS_ASSERTION(!parent
|| parent
== this, "Not one of our kids!");
617 MOZ_RELEASE_ASSERT(aChild
->GetParent() == this, "Not one of our kids!");
621 if (mLastChild
== aChild
) {
622 mLastChild
= mLastChild
->GetPrevSibling();
624 if (mFirstChild
== aChild
) {
625 mFirstChild
= mFirstChild
->GetNextSibling();
628 // Now remove from the list. Make sure that we pass ownership of the tail
629 // of the list correctly before we have aChild let go of it.
630 nsIWidget
* prev
= aChild
->GetPrevSibling();
631 nsIWidget
* next
= aChild
->GetNextSibling();
633 prev
->SetNextSibling(next
);
636 next
->SetPrevSibling(prev
);
639 aChild
->SetNextSibling(nullptr);
640 aChild
->SetPrevSibling(nullptr);
643 //-------------------------------------------------------------------------
645 // Sets widget's position within its parent's child list.
647 //-------------------------------------------------------------------------
648 void nsBaseWidget::SetZIndex(int32_t aZIndex
) {
649 // Hold a ref to ourselves just in case, since we're going to remove
651 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
655 // reorder this child in its parent's list.
656 auto* parent
= static_cast<nsBaseWidget
*>(GetParent());
658 parent
->RemoveChild(this);
659 // Scope sib outside the for loop so we can check it afterward
660 nsIWidget
* sib
= parent
->GetFirstChild();
661 for (; sib
; sib
= sib
->GetNextSibling()) {
662 int32_t childZIndex
= GetZIndex();
663 if (aZIndex
< childZIndex
) {
664 // Insert ourselves before sib
665 nsIWidget
* prev
= sib
->GetPrevSibling();
668 sib
->SetPrevSibling(this);
670 prev
->SetNextSibling(this);
672 NS_ASSERTION(sib
== parent
->mFirstChild
, "Broken child list");
673 // We've taken ownership of sib, so it's safe to have parent let
675 parent
->mFirstChild
= this;
677 PlaceBehind(eZPlacementBelow
, sib
, false);
681 // were we added to the list?
683 parent
->AddChild(this);
688 void nsBaseWidget::GetWorkspaceID(nsAString
& workspaceID
) {
689 workspaceID
.Truncate();
692 void nsBaseWidget::MoveToWorkspace(const nsAString
& workspaceID
) {
696 //-------------------------------------------------------------------------
698 // Get this component cursor
700 //-------------------------------------------------------------------------
702 void nsBaseWidget::SetCursor(const Cursor
& aCursor
) { mCursor
= aCursor
; }
704 void nsBaseWidget::SetCustomCursorAllowed(bool aIsAllowed
) {
705 if (aIsAllowed
!= mCustomCursorAllowed
) {
706 mCustomCursorAllowed
= aIsAllowed
;
707 mUpdateCursor
= true;
712 //-------------------------------------------------------------------------
714 // Window transparency methods
716 //-------------------------------------------------------------------------
718 void nsBaseWidget::SetTransparencyMode(TransparencyMode aMode
) {}
720 TransparencyMode
nsBaseWidget::GetTransparencyMode() {
721 return TransparencyMode::Opaque
;
725 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage
,
728 nsIRunnable
* aCallback
) {
729 MOZ_ASSERT_UNREACHABLE(
730 "Should never call PerformFullscreenTransition on nsBaseWidget");
733 //-------------------------------------------------------------------------
735 // Put the window into full-screen mode
737 //-------------------------------------------------------------------------
738 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen
) {
739 #define MOZ_FORMAT_RECT(fmtstr) "[" fmtstr "," fmtstr " " fmtstr "x" fmtstr "]"
740 #define MOZ_SPLAT_RECT(rect) \
741 (rect).X(), (rect).Y(), (rect).Width(), (rect).Height()
743 // Windows which can be made fullscreen are exactly those which are located on
744 // the desktop, rather than being a child of some other window.
745 MOZ_DIAGNOSTIC_ASSERT(BoundsUseDesktopPixels(),
746 "non-desktop windows cannot be made fullscreen");
748 // Ensure that the OS chrome is hidden/shown before we resize and/or exit the
751 // HideWindowChrome() may (depending on platform, implementation details, and
752 // OS-level user preferences) alter the reported size of the window. The
753 // obvious and principled solution is socks-and-shoes:
754 // - On entering fullscreen mode: hide window chrome, then perform resize.
755 // - On leaving fullscreen mode: unperform resize, then show window chrome.
757 // ... unfortunately, HideWindowChrome() requires Resize() to be called
758 // afterwards (see bug 498835), which prevents this from being done in a
759 // straightforward way.
761 // Instead, we always call HideWindowChrome() just before we call Resize().
762 // This at least ensures that our measurements are consistently taken in a
763 // pre-transition state.
765 // ... unfortunately again, coupling HideWindowChrome() to Resize() means that
766 // we have to worry about the possibility of control flows that don't call
767 // Resize() at all. (That shouldn't happen, but it's not trivial to rule out.)
768 // We therefore set up a fallback to fix up the OS chrome if it hasn't been
769 // done at exit time.
770 bool hasAdjustedOSChrome
= false;
771 const auto adjustOSChrome
= [&]() {
772 if (hasAdjustedOSChrome
) {
773 MOZ_ASSERT_UNREACHABLE("window chrome should only be adjusted once");
776 HideWindowChrome(aFullScreen
);
777 hasAdjustedOSChrome
= true;
779 const auto adjustChromeOnScopeExit
= MakeScopeExit([&]() {
780 if (hasAdjustedOSChrome
) {
784 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
785 ("window was not resized within InfallibleMakeFullScreen()"));
787 // Hide chrome and "resize" the window to its current size.
788 auto rect
= GetBounds();
790 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
793 // Attempt to resize to `rect`.
795 // Returns the actual rectangle resized to. (This may differ from `rect`, if
796 // the OS is unhappy with it. See bug 1786226.)
797 const auto doReposition
= [&](auto rect
) -> void {
798 static_assert(std::is_base_of_v
<DesktopPixel
,
799 std::remove_reference_t
<decltype(rect
)>>,
800 "doReposition requires a rectangle using desktop pixels");
802 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Debug
)) {
803 const DesktopRect previousSize
=
804 GetScreenBounds() / GetDesktopToDeviceScale();
805 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
806 ("before resize: " MOZ_FORMAT_RECT("%f"),
807 MOZ_SPLAT_RECT(previousSize
)));
811 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
813 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Warning
)) {
814 // `rect` may have any underlying data type; coerce to float to
815 // simplify printf-style logging
816 const gfx::RectTyped
<DesktopPixel
, float> rectAsFloat
{rect
};
818 // The OS may have objected to the target position. That's not necessarily
819 // a problem -- it'll happen regularly on Macs with camera notches in the
820 // monitor, for instance (see bug 1786226) -- but it probably deserves to
823 // Since there's floating-point math involved, the actual values may be
824 // off by a few ulps -- as an upper bound, perhaps 8 * FLT_EPSILON *
825 // max(MOZ_SPLAT_RECT(rect)) -- but 0.01 should be several orders of
826 // magnitude bigger than that.
828 const auto postResizeRectRaw
= GetScreenBounds();
829 const auto postResizeRect
= postResizeRectRaw
/ GetDesktopToDeviceScale();
830 const bool succeeded
= postResizeRect
.WithinEpsilonOf(rectAsFloat
, 0.01);
833 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
834 ("resized to: " MOZ_FORMAT_RECT("%f"),
835 MOZ_SPLAT_RECT(rectAsFloat
)));
837 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
838 ("attempted to resize to: " MOZ_FORMAT_RECT("%f"),
839 MOZ_SPLAT_RECT(rectAsFloat
)));
840 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
841 ("... but ended up at: " MOZ_FORMAT_RECT("%f"),
842 MOZ_SPLAT_RECT(postResizeRect
)));
846 sBaseWidgetLog
, LogLevel::Verbose
,
847 ("(... which, before DPI adjustment, is:" MOZ_FORMAT_RECT("%d") ")",
848 MOZ_SPLAT_RECT(postResizeRectRaw
)));
854 mSavedBounds
= Some(FullscreenSavedState());
856 // save current position
857 mSavedBounds
->windowRect
= GetScreenBounds() / GetDesktopToDeviceScale();
859 nsCOMPtr
<nsIScreen
> screen
= GetWidgetScreen();
864 // Move to fill the screen.
865 doReposition(screen
->GetRectDisplayPix());
866 // Save off the new position. (This may differ from GetRectDisplayPix(), if
867 // the OS was unhappy with it. See bug 1786226.)
868 mSavedBounds
->screenRect
= GetScreenBounds() / GetDesktopToDeviceScale();
871 // This should never happen, at present, since we don't make windows
872 // fullscreen at their creation time; but it's not logically impossible.
873 MOZ_ASSERT(false, "fullscreen window did not have saved position");
877 // Figure out where to go from here.
879 // Fortunately, since we're currently fullscreen (and other code should be
880 // handling _keeping_ us fullscreen even after display-layout changes),
881 // there's an obvious choice for which display we should attach to; all we
882 // need to determine is where on that display we should go.
884 const DesktopRect currentWinRect
=
885 GetScreenBounds() / GetDesktopToDeviceScale();
887 // Optimization: if where we are is where we were, then where we originally
888 // came from is where we're going to go.
889 if (currentWinRect
== DesktopRect(mSavedBounds
->screenRect
)) {
890 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
891 ("no location change detected; returning to saved location"));
892 doReposition(mSavedBounds
->windowRect
);
897 General case: figure out where we're going to go by dividing where we are
898 by where we were, and then multiplying by where we originally came from.
900 Less abstrusely: resize so that we occupy the same proportional position
901 on our current display after leaving fullscreen as we occupied on our
902 previous display before entering fullscreen.
904 (N.B.: We do not clamp. If we were only partially on the old display,
905 we'll be only partially on the new one, too.)
908 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
909 ("location change detected; computing new destination"));
911 // splat: convert an arbitrary Rect into a tuple, for syntactic convenience.
912 const auto splat
= [](auto rect
) {
913 return std::tuple(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height());
916 // remap: find the unique affine mapping which transforms `src` to `dst`,
917 // and apply it to `val`.
918 using Range
= std::pair
<float, float>;
919 const auto remap
= [](Range dst
, Range src
, float val
) {
920 // linear interpolation and its inverse: lerp(a, b, invlerp(a, b, t)) == t
921 const auto lerp
= [](float lo
, float hi
, float t
) {
922 return lo
+ t
* (hi
- lo
);
924 const auto invlerp
= [](float lo
, float hi
, float mid
) {
925 return (mid
- lo
) / (hi
- lo
);
928 const auto [dst_a
, dst_b
] = dst
;
929 const auto [src_a
, src_b
] = src
;
930 return lerp(dst_a
, dst_b
, invlerp(src_a
, src_b
, val
));
934 const auto [px
, py
, pw
, ph
] = splat(mSavedBounds
->windowRect
);
935 // source desktop rect
936 const auto [sx
, sy
, sw
, sh
] = splat(mSavedBounds
->screenRect
);
937 // target desktop rect
938 const auto [tx
, ty
, tw
, th
] = splat(currentWinRect
);
940 const float nx
= remap({tx
, tx
+ tw
}, {sx
, sx
+ sw
}, px
);
941 const float ny
= remap({ty
, ty
+ th
}, {sy
, sy
+ sh
}, py
);
942 const float nw
= remap({0, tw
}, {0, sw
}, pw
);
943 const float nh
= remap({0, th
}, {0, sh
}, ph
);
945 doReposition(DesktopRect
{nx
, ny
, nw
, nh
});
948 #undef MOZ_SPLAT_RECT
949 #undef MOZ_FORMAT_RECT
952 nsresult
nsBaseWidget::MakeFullScreen(bool aFullScreen
) {
953 InfallibleMakeFullScreen(aFullScreen
);
957 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
958 nsBaseWidget
* aWidget
, gfxContext
* aTarget
, BufferMode aDoubleBuffering
)
960 WindowRenderer
* renderer
= mWidget
->GetWindowRenderer();
961 if (renderer
->AsFallback()) {
962 mRenderer
= renderer
->AsFallback();
963 mRenderer
->SetTarget(aTarget
, aDoubleBuffering
);
967 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
969 mRenderer
->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE
);
973 bool nsBaseWidget::IsSmallPopup() const {
974 return mWindowType
== WindowType::Popup
&& mPopupType
!= PopupType::Panel
;
977 bool nsBaseWidget::ComputeShouldAccelerate() {
978 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING
) &&
979 (WidgetTypeSupportsAcceleration() ||
980 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
983 bool nsBaseWidget::UseAPZ() {
984 return (gfxPlatform::AsyncPanZoomEnabled() &&
985 (mWindowType
== WindowType::TopLevel
||
986 mWindowType
== WindowType::Child
||
987 ((mWindowType
== WindowType::Popup
||
988 mWindowType
== WindowType::Dialog
) &&
989 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
992 void nsBaseWidget::CreateCompositor() {
993 LayoutDeviceIntRect rect
= GetBounds();
994 CreateCompositor(rect
.Width(), rect
.Height());
997 void nsIWidget::PauseOrResumeCompositor(bool aPause
) {
998 auto* renderer
= GetRemoteRenderer();
1003 renderer
->SendPause();
1005 renderer
->SendResume();
1009 already_AddRefed
<GeckoContentController
>
1010 nsBaseWidget::CreateRootContentController() {
1011 RefPtr
<GeckoContentController
> controller
=
1012 new ChromeProcessController(this, mAPZEventState
, mAPZC
);
1013 return controller
.forget();
1016 void nsBaseWidget::ConfigureAPZCTreeManager() {
1017 MOZ_ASSERT(NS_IsMainThread());
1020 mAPZC
->SetDPI(GetDPI());
1022 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
1023 KeyboardMap map
= RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
1024 mAPZC
->SetKeyboardMap(map
);
1027 ContentReceivedInputBlockCallback
callback(
1028 [treeManager
= RefPtr
{mAPZC
.get()}](uint64_t aInputBlockId
,
1029 bool aPreventDefault
) {
1030 MOZ_ASSERT(NS_IsMainThread());
1031 treeManager
->ContentReceivedInputBlock(aInputBlockId
, aPreventDefault
);
1033 mAPZEventState
= new APZEventState(this, std::move(callback
));
1035 mRootContentController
= CreateRootContentController();
1036 if (mRootContentController
) {
1037 mCompositorSession
->SetContentController(mRootContentController
);
1040 // When APZ is enabled, we can actually enable raw touch events because we
1041 // have code that can deal with them properly. If APZ is not enabled, this
1042 // function doesn't get called.
1043 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
1044 RegisterTouchWindow();
1048 void nsBaseWidget::ConfigureAPZControllerThread() {
1049 // By default the controller thread is the main thread.
1050 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
1053 void nsBaseWidget::SetConfirmedTargetAPZC(
1054 uint64_t aInputBlockId
,
1055 const nsTArray
<ScrollableLayerGuid
>& aTargets
) const {
1056 mAPZC
->SetTargetAPZC(aInputBlockId
, aTargets
);
1059 void nsBaseWidget::UpdateZoomConstraints(
1060 const uint32_t& aPresShellId
, const ScrollableLayerGuid::ViewID
& aViewId
,
1061 const Maybe
<ZoomConstraints
>& aConstraints
) {
1062 if (!mCompositorSession
|| !mAPZC
) {
1063 MOZ_ASSERT_IF(mInitialZoomConstraints
,
1064 mInitialZoomConstraints
->mViewID
== aViewId
);
1066 // We have some constraints, but the compositor and APZC aren't
1067 // created yet. Save these so we can use them later.
1068 mInitialZoomConstraints
= Some(
1069 InitialZoomConstraints(aPresShellId
, aViewId
, aConstraints
.ref()));
1071 mInitialZoomConstraints
.reset();
1075 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1076 mAPZC
->UpdateZoomConstraints(
1077 ScrollableLayerGuid(layersId
, aPresShellId
, aViewId
), aConstraints
);
1080 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC
; }
1082 nsEventStatus
nsBaseWidget::ProcessUntransformedAPZEvent(
1083 WidgetInputEvent
* aEvent
, const APZEventResult
& aApzResult
) {
1084 MOZ_ASSERT(NS_IsMainThread());
1085 ScrollableLayerGuid targetGuid
= aApzResult
.mTargetGuid
;
1086 uint64_t inputBlockId
= aApzResult
.mInputBlockId
;
1087 InputAPZContext
context(aApzResult
.mTargetGuid
, inputBlockId
,
1088 aApzResult
.GetStatus());
1090 // Make a copy of the original event for the APZCCallbackHelper helpers that
1091 // we call later, because the event passed to DispatchEvent can get mutated in
1092 // ways that we don't want (i.e. touch points can get stripped out).
1093 nsEventStatus status
;
1094 UniquePtr
<WidgetEvent
> original(aEvent
->Duplicate());
1095 DispatchEvent(aEvent
, status
);
1097 if (mAPZC
&& !InputAPZContext::WasRoutedToChildProcess() &&
1098 !InputAPZContext::WasDropped() && inputBlockId
) {
1099 // EventStateManager did not route the event into the child process and
1100 // the event was dispatched in the parent process.
1101 // It's safe to communicate to APZ that the event has been processed.
1102 // Note that here aGuid.mLayersId might be different from
1103 // mCompositorSession->RootLayerTreeId() because the event might have gotten
1104 // hit-tested by APZ to be targeted at a child process, but a parent process
1105 // event listener called preventDefault on it. In that case aGuid.mLayersId
1106 // would still be the layers id for the child process, but the event would
1107 // not have actually gotten routed to the child process. The main-thread
1108 // hit-test result therefore needs to use the parent process layers id.
1109 LayersId rootLayersId
= mCompositorSession
->RootLayerTreeId();
1111 RefPtr
<DisplayportSetListener
> postLayerization
;
1112 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1113 nsTArray
<TouchBehaviorFlags
> allowedTouchBehaviors
;
1114 if (touchEvent
->mMessage
== eTouchStart
) {
1115 auto& originalEvent
= *original
->AsTouchEvent();
1116 MOZ_ASSERT(NS_IsMainThread());
1117 allowedTouchBehaviors
= TouchActionHelper::GetAllowedTouchBehavior(
1118 this, GetDocument(), originalEvent
);
1119 if (!allowedTouchBehaviors
.IsEmpty()) {
1120 mAPZC
->SetAllowedTouchBehavior(inputBlockId
, allowedTouchBehaviors
);
1122 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1123 this, GetDocument(), originalEvent
, rootLayersId
, inputBlockId
);
1125 mAPZEventState
->ProcessTouchEvent(*touchEvent
, targetGuid
, inputBlockId
,
1126 aApzResult
.GetStatus(), status
,
1127 std::move(allowedTouchBehaviors
));
1128 } else if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1129 MOZ_ASSERT(wheelEvent
->mFlags
.mHandledByAPZ
);
1130 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1131 this, GetDocument(), *original
->AsWheelEvent(), rootLayersId
,
1133 if (wheelEvent
->mCanTriggerSwipe
) {
1134 ReportSwipeStarted(inputBlockId
, wheelEvent
->TriggersSwipe());
1136 mAPZEventState
->ProcessWheelEvent(*wheelEvent
, inputBlockId
);
1137 } else if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1138 MOZ_ASSERT(mouseEvent
->mFlags
.mHandledByAPZ
);
1139 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1140 this, GetDocument(), *original
->AsMouseEvent(), rootLayersId
,
1142 mAPZEventState
->ProcessMouseEvent(*mouseEvent
, inputBlockId
);
1144 if (postLayerization
) {
1145 postLayerization
->Register();
1152 template <class InputType
, class EventType
>
1153 class DispatchEventOnMainThread
: public Runnable
{
1155 DispatchEventOnMainThread(const InputType
& aInput
, nsBaseWidget
* aWidget
,
1156 const APZEventResult
& aAPZResult
)
1157 : mozilla::Runnable("DispatchEventOnMainThread"),
1160 mAPZResult(aAPZResult
) {}
1162 NS_IMETHOD
Run() override
{
1163 EventType event
= mInput
.ToWidgetEvent(mWidget
);
1164 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1170 nsBaseWidget
* mWidget
;
1171 APZEventResult mAPZResult
;
1174 template <class InputType
, class EventType
>
1175 class DispatchInputOnControllerThread
: public Runnable
{
1177 enum class APZOnly
{ Yes
, No
};
1178 DispatchInputOnControllerThread(const EventType
& aEvent
,
1179 IAPZCTreeManager
* aAPZC
,
1180 nsBaseWidget
* aWidget
,
1181 APZOnly aAPZOnly
= APZOnly::No
)
1182 : mozilla::Runnable("DispatchInputOnControllerThread"),
1183 mMainMessageLoop(MessageLoop::current()),
1187 mAPZOnly(aAPZOnly
) {}
1189 NS_IMETHOD
Run() override
{
1190 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(mInput
);
1191 if (mAPZOnly
== APZOnly::Yes
||
1192 result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1195 RefPtr
<Runnable
> r
= new DispatchEventOnMainThread
<InputType
, EventType
>(
1196 mInput
, mWidget
, result
);
1197 mMainMessageLoop
->PostTask(r
.forget());
1202 MessageLoop
* mMainMessageLoop
;
1204 RefPtr
<IAPZCTreeManager
> mAPZC
;
1205 nsBaseWidget
* mWidget
;
1206 const APZOnly mAPZOnly
;
1209 void nsBaseWidget::DispatchTouchInput(MultiTouchInput
& aInput
,
1210 uint16_t aInputSource
) {
1211 MOZ_ASSERT(NS_IsMainThread());
1212 MOZ_ASSERT(aInputSource
==
1213 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH
||
1214 aInputSource
== mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN
);
1216 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1218 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1219 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1223 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1224 ProcessUntransformedAPZEvent(&event
, result
);
1226 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1228 nsEventStatus status
;
1229 DispatchEvent(&event
, status
);
1233 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput
& aInput
) {
1234 MOZ_ASSERT(NS_IsMainThread());
1236 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1238 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1239 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1243 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1244 ProcessUntransformedAPZEvent(&event
, result
);
1246 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1247 nsEventStatus status
;
1248 DispatchEvent(&event
, status
);
1252 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput
& aInput
) {
1253 MOZ_ASSERT(NS_IsMainThread());
1255 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1256 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1258 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1261 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1262 ProcessUntransformedAPZEvent(&event
, result
);
1264 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1265 nsEventStatus status
;
1266 DispatchEvent(&event
, status
);
1270 nsIWidget::ContentAndAPZEventStatus
nsBaseWidget::DispatchInputEvent(
1271 WidgetInputEvent
* aEvent
) {
1272 nsIWidget::ContentAndAPZEventStatus status
;
1273 MOZ_ASSERT(NS_IsMainThread());
1276 if (APZThreadUtils::IsControllerThread()) {
1277 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1278 status
.mApzStatus
= result
.GetStatus();
1279 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1282 status
.mContentStatus
= ProcessUntransformedAPZEvent(aEvent
, result
);
1285 // Most drag events aren't able to converted to MouseEvent except to
1286 // eDragStart and eDragEnd.
1287 const bool canDispatchToApzc
=
1288 !aEvent
->AsDragEvent() ||
1289 aEvent
->AsDragEvent()->CanConvertToInputData();
1290 if (canDispatchToApzc
) {
1291 if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1292 RefPtr
<Runnable
> r
=
1293 new DispatchInputOnControllerThread
<ScrollWheelInput
,
1294 WidgetWheelEvent
>(*wheelEvent
,
1296 APZThreadUtils::RunOnControllerThread(std::move(r
));
1297 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1300 if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1301 RefPtr
<Runnable
> r
=
1302 new DispatchInputOnControllerThread
<MouseInput
, WidgetMouseEvent
>(
1303 *mouseEvent
, mAPZC
, this);
1304 APZThreadUtils::RunOnControllerThread(std::move(r
));
1305 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1308 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1309 RefPtr
<Runnable
> r
=
1310 new DispatchInputOnControllerThread
<MultiTouchInput
,
1311 WidgetTouchEvent
>(*touchEvent
,
1313 APZThreadUtils::RunOnControllerThread(std::move(r
));
1314 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1317 // Allow dispatching keyboard/drag events on Gecko thread
1318 // without sending them to APZ
1320 // FIXME: APZ can handle keyboard events now, we should
1321 // be sending them to APZ here
1322 MOZ_ASSERT(aEvent
->AsKeyboardEvent() || aEvent
->AsDragEvent());
1326 DispatchEvent(aEvent
, status
.mContentStatus
);
1330 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent
* aEvent
) {
1331 MOZ_ASSERT(NS_IsMainThread());
1333 if (APZThreadUtils::IsControllerThread()) {
1334 mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1338 if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1339 RefPtr
<Runnable
> r
=
1340 new DispatchInputOnControllerThread
<MouseInput
, WidgetMouseEvent
>(
1341 *mouseEvent
, mAPZC
, this,
1342 DispatchInputOnControllerThread
<MouseInput
,
1343 WidgetMouseEvent
>::APZOnly::Yes
);
1344 APZThreadUtils::RunOnControllerThread(std::move(r
));
1348 MOZ_ASSERT_UNREACHABLE("Not implemented yet");
1352 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent
& event
) {
1353 nsEventStatus status
;
1354 DispatchEvent(&event
, status
);
1355 return ConvertStatus(status
);
1358 Document
* nsBaseWidget::GetDocument() const {
1359 if (mWidgetListener
) {
1360 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1361 return presShell
->GetDocument();
1367 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1368 // Parent directly listens to the vsync source whereas
1369 // child process communicate via IPC
1370 // Should be called AFTER gfxPlatform is initialized
1371 if (XRE_IsParentProcess()) {
1372 if (!mCompositorVsyncDispatcherLock
) {
1373 mCompositorVsyncDispatcherLock
=
1374 MakeUnique
<Mutex
>("mCompositorVsyncDispatcherLock");
1376 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1377 if (!mCompositorVsyncDispatcher
) {
1378 RefPtr
<VsyncDispatcher
> vsyncDispatcher
=
1379 gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
1380 mCompositorVsyncDispatcher
=
1381 new CompositorVsyncDispatcher(std::move(vsyncDispatcher
));
1386 already_AddRefed
<CompositorVsyncDispatcher
>
1387 nsBaseWidget::GetCompositorVsyncDispatcher() {
1388 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
1390 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1391 RefPtr
<CompositorVsyncDispatcher
> dispatcher
= mCompositorVsyncDispatcher
;
1392 return dispatcher
.forget();
1395 already_AddRefed
<WebRenderLayerManager
> nsBaseWidget::CreateCompositorSession(
1396 int aWidth
, int aHeight
, CompositorOptions
* aOptionsOut
) {
1397 MOZ_ASSERT(aOptionsOut
);
1400 CreateCompositorVsyncDispatcher();
1402 gfx::GPUProcessManager
* gpu
= gfx::GPUProcessManager::Get();
1403 // Make sure GPU process is ready for use.
1404 // If it failed to connect to GPU process, GPU process usage is disabled in
1405 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1406 nsresult rv
= gpu
->EnsureGPUReady();
1407 if (NS_WARN_IF(rv
== NS_ERROR_ILLEGAL_DURING_SHUTDOWN
)) {
1411 // If widget type does not supports acceleration, we may be allowed to use
1412 // software WebRender instead.
1413 bool supportsAcceleration
= WidgetTypeSupportsAcceleration();
1414 bool enableSWWR
= true;
1415 if (supportsAcceleration
||
1416 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1417 enableSWWR
= gfx::gfxVars::UseSoftwareWebRender();
1419 bool enableAPZ
= UseAPZ();
1420 CompositorOptions
options(enableAPZ
, enableSWWR
);
1423 if (supportsAcceleration
) {
1424 options
.SetAllowSoftwareWebRenderD3D11(
1425 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1427 if (mNeedFastSnaphot
) {
1428 options
.SetNeedFastSnaphot(true);
1430 #elif defined(MOZ_WIDGET_ANDROID)
1431 MOZ_ASSERT(supportsAcceleration
);
1432 options
.SetAllowSoftwareWebRenderOGL(
1433 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1434 #elif defined(MOZ_WIDGET_GTK)
1435 if (supportsAcceleration
) {
1436 options
.SetAllowSoftwareWebRenderOGL(
1437 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1441 #ifdef MOZ_WIDGET_ANDROID
1442 // Unconditionally set the compositor as initially paused, as we have not
1443 // yet had a chance to send the compositor surface to the GPU process. We
1444 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1445 // where we will also resume the compositor if required.
1446 options
.SetInitiallyPaused(true);
1448 options
.SetInitiallyPaused(CompositorInitiallyPaused());
1451 RefPtr
<WebRenderLayerManager
> lm
= new WebRenderLayerManager(this);
1453 uint64_t innerWindowId
= 0;
1454 if (Document
* doc
= GetDocument()) {
1455 innerWindowId
= doc
->InnerWindowID();
1459 mCompositorSession
= gpu
->CreateTopLevelCompositor(
1460 this, lm
, GetDefaultScale(), options
, UseExternalCompositingSurface(),
1461 gfx::IntSize(aWidth
, aHeight
), innerWindowId
, &retry
);
1463 if (mCompositorSession
) {
1464 TextureFactoryIdentifier textureFactoryIdentifier
;
1466 lm
->Initialize(mCompositorSession
->GetCompositorBridgeChild(),
1467 wr::AsPipelineId(mCompositorSession
->RootLayerTreeId()),
1468 &textureFactoryIdentifier
, error
);
1469 if (textureFactoryIdentifier
.mParentBackend
!= LayersBackend::LAYERS_WR
) {
1471 DestroyCompositor();
1472 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1473 gfx::GPUProcessManager::Get()->DisableWebRender(
1474 wr::WebRenderError::INITIALIZE
, error
);
1478 // We need to retry in a loop because the act of failing to create the
1479 // compositor can change our state (e.g. disable WebRender).
1480 if (mCompositorSession
|| !retry
) {
1481 *aOptionsOut
= options
;
1487 void nsBaseWidget::CreateCompositor(int aWidth
, int aHeight
) {
1488 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1489 gfxPlatform::GetPlatform();
1491 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1492 "This function assumes OMTC");
1494 MOZ_ASSERT(!mCompositorSession
&& !mCompositorBridgeChild
,
1495 "Should have properly cleaned up the previous PCompositor pair "
1498 if (mCompositorBridgeChild
) {
1499 mCompositorBridgeChild
->Destroy();
1502 // Recreating this is tricky, as we may still have an old and we need
1503 // to make sure it's properly destroyed by calling DestroyCompositor!
1505 // If we've already received a shutdown notification, don't try
1506 // create a new compositor.
1507 if (!mShutdownObserver
) {
1511 // The controller thread must be configured before the compositor
1512 // session is created, so that the input bridge runs on the right
1514 ConfigureAPZControllerThread();
1516 CompositorOptions options
;
1517 RefPtr
<WebRenderLayerManager
> lm
=
1518 CreateCompositorSession(aWidth
, aHeight
, &options
);
1523 MOZ_ASSERT(mCompositorSession
);
1524 mCompositorBridgeChild
= mCompositorSession
->GetCompositorBridgeChild();
1525 SetCompositorWidgetDelegate(
1526 mCompositorSession
->GetCompositorWidgetDelegate());
1528 if (options
.UseAPZ()) {
1529 mAPZC
= mCompositorSession
->GetAPZCTreeManager();
1530 ConfigureAPZCTreeManager();
1535 if (mInitialZoomConstraints
) {
1536 UpdateZoomConstraints(mInitialZoomConstraints
->mPresShellID
,
1537 mInitialZoomConstraints
->mViewID
,
1538 Some(mInitialZoomConstraints
->mConstraints
));
1539 mInitialZoomConstraints
.reset();
1542 TextureFactoryIdentifier textureFactoryIdentifier
=
1543 lm
->GetTextureFactoryIdentifier();
1544 MOZ_ASSERT(textureFactoryIdentifier
.mParentBackend
==
1545 LayersBackend::LAYERS_WR
);
1546 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier
);
1547 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier
);
1551 mWindowRenderer
= std::move(lm
);
1553 // Only track compositors for top-level windows, since other window types
1554 // may use the basic compositor. Except on the OS X - see bug 1306383
1555 #if defined(XP_MACOSX)
1556 bool getCompositorFromThisWindow
= true;
1558 bool getCompositorFromThisWindow
= mWindowType
== WindowType::TopLevel
;
1561 if (getCompositorFromThisWindow
) {
1562 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1563 mWindowRenderer
->GetCompositorBackendType());
1567 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession
* aSession
) {
1568 MOZ_ASSERT(aSession
== mCompositorSession
);
1569 DestroyLayerManager();
1572 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1573 return gfxPlatform::UsesOffMainThreadCompositing();
1576 WindowRenderer
* nsBaseWidget::GetWindowRenderer() {
1577 if (!mWindowRenderer
) {
1578 if (!mShutdownObserver
) {
1579 // We are shutting down, do not try to re-create a LayerManager
1582 // Try to use an async compositor first, if possible
1583 if (ShouldUseOffMainThreadCompositing()) {
1587 if (!mWindowRenderer
) {
1588 mWindowRenderer
= CreateFallbackRenderer();
1591 return mWindowRenderer
;
1594 WindowRenderer
* nsBaseWidget::CreateFallbackRenderer() {
1595 return new FallbackRenderer
;
1598 CompositorBridgeChild
* nsBaseWidget::GetRemoteRenderer() {
1599 return mCompositorBridgeChild
;
1602 void nsBaseWidget::ClearCachedWebrenderResources() {
1603 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1606 mWindowRenderer
->AsWebRender()->ClearCachedResources();
1609 void nsBaseWidget::ClearWebrenderAnimationResources() {
1610 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1613 mWindowRenderer
->AsWebRender()->ClearAnimationResources();
1616 bool nsBaseWidget::SetNeedFastSnaphot() {
1617 MOZ_ASSERT(XRE_IsParentProcess());
1618 MOZ_ASSERT(!mCompositorSession
);
1620 if (!XRE_IsParentProcess() || mCompositorSession
) {
1624 mNeedFastSnaphot
= true;
1628 already_AddRefed
<gfx::DrawTarget
> nsBaseWidget::StartRemoteDrawing() {
1632 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA
; }
1634 //-------------------------------------------------------------------------
1636 // Destroy the window
1638 //-------------------------------------------------------------------------
1639 void nsBaseWidget::OnDestroy() {
1640 if (mTextEventDispatcher
) {
1641 mTextEventDispatcher
->OnDestroyWidget();
1642 // Don't release it until this widget actually released because after this
1643 // is called, TextEventDispatcher() may create it again.
1646 // If this widget is being destroyed, let the APZ code know to drop references
1647 // to this widget. Callers of this function all should be holding a deathgrip
1648 // on this widget already.
1649 ReleaseContentController();
1652 void nsBaseWidget::MoveClient(const DesktopPoint
& aOffset
) {
1653 LayoutDeviceIntPoint
clientOffset(GetClientOffset());
1655 // GetClientOffset returns device pixels; scale back to desktop pixels
1656 // if that's what this widget uses for the Move/Resize APIs
1657 if (BoundsUseDesktopPixels()) {
1658 DesktopPoint desktopOffset
= clientOffset
/ GetDesktopToDeviceScale();
1659 Move(aOffset
.x
- desktopOffset
.x
, aOffset
.y
- desktopOffset
.y
);
1661 LayoutDevicePoint layoutOffset
= aOffset
* GetDesktopToDeviceScale();
1662 Move(layoutOffset
.x
- LayoutDeviceCoord(clientOffset
.x
),
1663 layoutOffset
.y
- LayoutDeviceCoord(clientOffset
.y
));
1667 void nsBaseWidget::ResizeClient(const DesktopSize
& aSize
, bool aRepaint
) {
1668 NS_ASSERTION((aSize
.width
>= 0), "Negative width passed to ResizeClient");
1669 NS_ASSERTION((aSize
.height
>= 0), "Negative height passed to ResizeClient");
1671 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1673 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1674 // if that's what this widget uses for the Move/Resize APIs
1675 if (BoundsUseDesktopPixels()) {
1676 DesktopSize desktopDelta
=
1677 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1678 clientBounds
.Size()) /
1679 GetDesktopToDeviceScale();
1680 Resize(aSize
.width
+ desktopDelta
.width
, aSize
.height
+ desktopDelta
.height
,
1683 LayoutDeviceSize layoutSize
= aSize
* GetDesktopToDeviceScale();
1684 Resize(mBounds
.Width() + (layoutSize
.width
- clientBounds
.Width()),
1685 mBounds
.Height() + (layoutSize
.height
- clientBounds
.Height()),
1690 void nsBaseWidget::ResizeClient(const DesktopRect
& aRect
, bool aRepaint
) {
1691 NS_ASSERTION((aRect
.Width() >= 0), "Negative width passed to ResizeClient");
1692 NS_ASSERTION((aRect
.Height() >= 0), "Negative height passed to ResizeClient");
1694 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1695 LayoutDeviceIntPoint clientOffset
= GetClientOffset();
1696 DesktopToLayoutDeviceScale scale
= GetDesktopToDeviceScale();
1698 if (BoundsUseDesktopPixels()) {
1699 DesktopPoint desktopOffset
= clientOffset
/ scale
;
1700 DesktopSize desktopDelta
=
1701 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1702 clientBounds
.Size()) /
1704 Resize(aRect
.X() - desktopOffset
.x
, aRect
.Y() - desktopOffset
.y
,
1705 aRect
.Width() + desktopDelta
.width
,
1706 aRect
.Height() + desktopDelta
.height
, aRepaint
);
1708 LayoutDeviceRect layoutRect
= aRect
* scale
;
1709 Resize(layoutRect
.X() - clientOffset
.x
, layoutRect
.Y() - clientOffset
.y
,
1710 layoutRect
.Width() + mBounds
.Width() - clientBounds
.Width(),
1711 layoutRect
.Height() + mBounds
.Height() - clientBounds
.Height(),
1716 //-------------------------------------------------------------------------
1720 //-------------------------------------------------------------------------
1723 * If the implementation of nsWindow supports borders this method MUST be
1727 LayoutDeviceIntRect
nsBaseWidget::GetClientBounds() { return GetBounds(); }
1730 * If the implementation of nsWindow supports borders this method MUST be
1734 LayoutDeviceIntRect
nsBaseWidget::GetBounds() { return mBounds
; }
1737 * If the implementation of nsWindow uses a local coordinate system within the
1738 *window, this method must be overridden
1741 LayoutDeviceIntRect
nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1743 nsresult
nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect
& aRect
) {
1744 if (SizeMode() != nsSizeMode_Normal
) {
1745 return NS_ERROR_FAILURE
;
1747 aRect
= GetScreenBounds();
1751 LayoutDeviceIntPoint
nsBaseWidget::GetClientOffset() {
1752 return LayoutDeviceIntPoint(0, 0);
1755 nsresult
nsBaseWidget::SetNonClientMargins(const LayoutDeviceIntMargin
&) {
1756 return NS_ERROR_NOT_IMPLEMENTED
;
1759 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin
) {}
1761 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1763 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1765 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect
* aResizerRect
) {
1770 * Modifies aFile to point at an icon file with the given name and suffix. The
1771 * suffix may correspond to a file extension with leading '.' if appropriate.
1772 * Returns true if the icon file exists and can be read.
1774 static bool ResolveIconNameHelper(nsIFile
* aFile
, const nsAString
& aIconName
,
1775 const nsAString
& aIconSuffix
) {
1776 aFile
->Append(u
"icons"_ns
);
1777 aFile
->Append(u
"default"_ns
);
1778 aFile
->Append(aIconName
+ aIconSuffix
);
1781 return NS_SUCCEEDED(aFile
->IsReadable(&readable
)) && readable
;
1785 * Resolve the given icon name into a local file object. This method is
1786 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1787 * platform specific icon file suffix (e.g., ".ico" under Win32).
1789 * If no file is found matching the given parameters, then null is returned.
1791 void nsBaseWidget::ResolveIconName(const nsAString
& aIconName
,
1792 const nsAString
& aIconSuffix
,
1793 nsIFile
** aResult
) {
1796 nsCOMPtr
<nsIProperties
> dirSvc
=
1797 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID
);
1798 if (!dirSvc
) return;
1800 // first check auxilary chrome directories
1802 nsCOMPtr
<nsISimpleEnumerator
> dirs
;
1803 dirSvc
->Get(NS_APP_CHROME_DIR_LIST
, NS_GET_IID(nsISimpleEnumerator
),
1804 getter_AddRefs(dirs
));
1807 while (NS_SUCCEEDED(dirs
->HasMoreElements(&hasMore
)) && hasMore
) {
1808 nsCOMPtr
<nsISupports
> element
;
1809 dirs
->GetNext(getter_AddRefs(element
));
1810 if (!element
) continue;
1811 nsCOMPtr
<nsIFile
> file
= do_QueryInterface(element
);
1812 if (!file
) continue;
1813 if (ResolveIconNameHelper(file
, aIconName
, aIconSuffix
)) {
1814 NS_ADDREF(*aResult
= file
);
1820 // then check the main app chrome directory
1822 nsCOMPtr
<nsIFile
> file
;
1823 dirSvc
->Get(NS_APP_CHROME_DIR
, NS_GET_IID(nsIFile
), getter_AddRefs(file
));
1824 if (file
&& ResolveIconNameHelper(file
, aIconName
, aIconSuffix
))
1825 NS_ADDREF(*aResult
= file
);
1828 void nsBaseWidget::SetSizeConstraints(const SizeConstraints
& aConstraints
) {
1829 mSizeConstraints
= aConstraints
;
1831 // Popups are constrained during layout, and we don't want to synchronously
1832 // paint from reflow, so bail out... This is not great, but it's no worse than
1833 // what we used to do.
1835 // The right fix here is probably making constraint changes go through the
1836 // view manager and such.
1837 if (mWindowType
== WindowType::Popup
) {
1841 // If the current size doesn't meet the new constraints, trigger a
1842 // resize to apply it. Note that, we don't want to invoke Resize if
1843 // the new constraints don't affect the current size, because Resize
1844 // implementation on some platforms may touch other geometry even if
1845 // the size don't need to change.
1846 LayoutDeviceIntSize curSize
= mBounds
.Size();
1847 LayoutDeviceIntSize clampedSize
=
1848 Max(aConstraints
.mMinSize
, Min(aConstraints
.mMaxSize
, curSize
));
1849 if (clampedSize
!= curSize
) {
1851 if (BoundsUseDesktopPixels()) {
1852 DesktopSize desktopSize
= clampedSize
/ GetDesktopToDeviceScale();
1853 size
= desktopSize
.ToUnknownSize();
1855 size
= gfx::Size(clampedSize
.ToUnknownSize());
1857 Resize(size
.width
, size
.height
, true);
1861 const widget::SizeConstraints
nsBaseWidget::GetSizeConstraints() {
1862 return mSizeConstraints
;
1866 nsIRollupListener
* nsBaseWidget::GetActiveRollupListener() {
1867 // TODO: Simplify this.
1868 return nsXULPopupManager::GetInstance();
1871 void nsBaseWidget::NotifyWindowDestroyed() {
1872 if (!mWidgetListener
) return;
1874 nsCOMPtr
<nsIAppWindow
> window
= mWidgetListener
->GetAppWindow();
1875 nsCOMPtr
<nsIBaseWindow
> appWindow(do_QueryInterface(window
));
1877 appWindow
->Destroy();
1881 void nsBaseWidget::NotifyWindowMoved(int32_t aX
, int32_t aY
,
1882 ByMoveToRect aByMoveToRect
) {
1883 if (mWidgetListener
) {
1884 mWidgetListener
->WindowMoved(this, aX
, aY
, aByMoveToRect
);
1887 if (mIMEHasFocus
&& IMENotificationRequestsRef().WantPositionChanged()) {
1888 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE
));
1892 void nsBaseWidget::NotifySizeMoveDone() {
1893 if (!mWidgetListener
) {
1896 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1897 presShell
->WindowSizeMoveDone();
1901 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind
) {
1902 LookAndFeel::NotifyChangedAllWindows(aKind
);
1905 nsresult
nsBaseWidget::NotifyIME(const IMENotification
& aIMENotification
) {
1909 switch (aIMENotification
.mMessage
) {
1910 case REQUEST_TO_COMMIT_COMPOSITION
:
1911 case REQUEST_TO_CANCEL_COMPOSITION
:
1912 // We should send request to IME only when there is a TextEventDispatcher
1913 // instance (this means that this widget has dispatched at least one
1914 // composition event or keyboard event) and the it has composition.
1915 // Otherwise, there is nothing to do.
1916 // Note that if current input transaction is for native input events,
1917 // TextEventDispatcher::NotifyIME() will call
1918 // TextEventDispatcherListener::NotifyIME().
1919 if (mTextEventDispatcher
&& mTextEventDispatcher
->IsComposing()) {
1920 return mTextEventDispatcher
->NotifyIME(aIMENotification
);
1924 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_FOCUS
) {
1925 mIMEHasFocus
= true;
1927 EnsureTextEventDispatcher();
1928 // TextEventDispatcher::NotifyIME() will always call
1929 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1930 // input transaction is for synthesized events for automated tests,
1931 // notifications will be sent to native IME.
1932 nsresult rv
= mTextEventDispatcher
->NotifyIME(aIMENotification
);
1933 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_BLUR
) {
1934 mIMEHasFocus
= false;
1941 void nsBaseWidget::EnsureTextEventDispatcher() {
1942 if (mTextEventDispatcher
) {
1945 mTextEventDispatcher
= new TextEventDispatcher(this);
1948 nsIWidget::NativeIMEContext
nsBaseWidget::GetNativeIMEContext() {
1949 if (mTextEventDispatcher
&& mTextEventDispatcher
->GetPseudoIMEContext()) {
1950 // If we already have a TextEventDispatcher and it's working with
1951 // a TextInputProcessor, we need to return pseudo IME context since
1952 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1953 // on the pseudo IME context in such case.
1954 NativeIMEContext pseudoIMEContext
;
1955 pseudoIMEContext
.InitWithRawNativeIMEContext(
1956 mTextEventDispatcher
->GetPseudoIMEContext());
1957 return pseudoIMEContext
;
1959 return NativeIMEContext(this);
1962 nsIWidget::TextEventDispatcher
* nsBaseWidget::GetTextEventDispatcher() {
1963 EnsureTextEventDispatcher();
1964 return mTextEventDispatcher
;
1967 void* nsBaseWidget::GetPseudoIMEContext() {
1968 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
1972 return dispatcher
->GetPseudoIMEContext();
1975 TextEventDispatcherListener
*
1976 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1977 // TODO: If all platforms supported use of TextEventDispatcher for handling
1978 // native IME and keyboard events, this method should be removed since
1979 // in such case, this is overridden by all the subclasses.
1983 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId
,
1984 const ScrollableLayerGuid::ViewID
& aViewId
,
1985 const CSSRect
& aRect
, const uint32_t& aFlags
) {
1986 if (!mCompositorSession
|| !mAPZC
) {
1989 LayersId layerId
= mCompositorSession
->RootLayerTreeId();
1990 mAPZC
->ZoomToRect(ScrollableLayerGuid(layerId
, aPresShellId
, aViewId
),
1991 ZoomTarget
{aRect
}, aFlags
);
1994 #ifdef ACCESSIBILITY
1996 a11y::LocalAccessible
* nsBaseWidget::GetRootAccessible() {
1997 NS_ENSURE_TRUE(mWidgetListener
, nullptr);
1999 PresShell
* presShell
= mWidgetListener
->GetPresShell();
2000 NS_ENSURE_TRUE(presShell
, nullptr);
2002 // If container is null then the presshell is not active. This often happens
2003 // when a preshell is being held onto for fastback.
2004 nsPresContext
* presContext
= presShell
->GetPresContext();
2005 NS_ENSURE_TRUE(presContext
->GetContainerWeak(), nullptr);
2007 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
2008 // make sure it's not created at unsafe times.
2009 nsAccessibilityService
* accService
= GetOrCreateAccService();
2011 return accService
->GetRootDocumentAccessible(
2012 presShell
, nsContentUtils::IsSafeToRunScript());
2018 #endif // ACCESSIBILITY
2020 void nsBaseWidget::StartAsyncScrollbarDrag(
2021 const AsyncDragMetrics
& aDragMetrics
) {
2022 if (!AsyncPanZoomEnabled()) {
2026 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession
);
2028 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
2029 ScrollableLayerGuid
guid(layersId
, aDragMetrics
.mPresShellId
,
2030 aDragMetrics
.mViewId
);
2032 mAPZC
->StartScrollbarDrag(guid
, aDragMetrics
);
2035 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint
& aAnchorLocation
,
2036 const ScrollableLayerGuid
& aGuid
) {
2037 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2039 return mAPZC
->StartAutoscroll(aGuid
, aAnchorLocation
);
2042 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid
& aGuid
) {
2043 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2045 mAPZC
->StopAutoscroll(aGuid
);
2048 LayersId
nsBaseWidget::GetRootLayerTreeId() {
2049 return mCompositorSession
? mCompositorSession
->RootLayerTreeId()
2053 already_AddRefed
<widget::Screen
> nsBaseWidget::GetWidgetScreen() {
2054 ScreenManager
& screenManager
= ScreenManager::GetSingleton();
2055 LayoutDeviceIntRect bounds
= GetScreenBounds();
2056 DesktopIntRect deskBounds
= RoundedToInt(bounds
/ GetDesktopToDeviceScale());
2057 return screenManager
.ScreenForRect(deskBounds
);
2060 mozilla::DesktopToLayoutDeviceScale
2061 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
2062 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
2063 ->GetDesktopToDeviceScale();
2066 nsresult
nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint
,
2068 nsIObserver
* aObserver
) {
2069 AutoObserverNotifier
notifier(aObserver
, "touchtap");
2071 if (sPointerIdCounter
> TOUCH_INJECT_MAX_POINTS
) {
2072 sPointerIdCounter
= 0;
2074 int pointerId
= sPointerIdCounter
;
2075 sPointerIdCounter
++;
2076 nsresult rv
= SynthesizeNativeTouchPoint(pointerId
, TOUCH_CONTACT
, aPoint
,
2078 if (NS_FAILED(rv
)) {
2083 return SynthesizeNativeTouchPoint(pointerId
, TOUCH_REMOVE
, aPoint
, 0, 0,
2087 // initiate a long tap
2088 int elapse
= Preferences::GetInt("ui.click_hold_context_menus.delay",
2089 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC
);
2090 if (!mLongTapTimer
) {
2091 mLongTapTimer
= NS_NewTimer();
2092 if (!mLongTapTimer
) {
2093 SynthesizeNativeTouchPoint(pointerId
, TOUCH_CANCEL
, aPoint
, 0, 0,
2095 return NS_ERROR_UNEXPECTED
;
2097 // Windows requires recuring events, so we set this to a smaller window
2098 // than the pref value.
2099 int timeout
= elapse
;
2100 if (timeout
> TOUCH_INJECT_PUMP_TIMER_MSEC
) {
2101 timeout
= TOUCH_INJECT_PUMP_TIMER_MSEC
;
2103 mLongTapTimer
->InitWithNamedFuncCallback(
2104 OnLongTapTimerCallback
, this, timeout
, nsITimer::TYPE_REPEATING_SLACK
,
2105 "nsIWidget::SynthesizeNativeTouchTap");
2108 // If we already have a long tap pending, cancel it. We only allow one long
2109 // tap to be active at a time.
2110 if (mLongTapTouchPoint
) {
2111 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2112 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2115 mLongTapTouchPoint
= MakeUnique
<LongTapInfo
>(
2116 pointerId
, aPoint
, TimeDuration::FromMilliseconds(elapse
), aObserver
);
2117 notifier
.SkipNotification(); // we'll do it in the long-tap callback
2122 void nsIWidget::OnLongTapTimerCallback(nsITimer
* aTimer
, void* aClosure
) {
2123 auto* self
= static_cast<nsIWidget
*>(aClosure
);
2125 if ((self
->mLongTapTouchPoint
->mStamp
+ self
->mLongTapTouchPoint
->mDuration
) >
2128 // Windows needs us to keep pumping feedback to the digitizer, so update
2129 // the pointer id with the same position.
2130 self
->SynthesizeNativeTouchPoint(
2131 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_CONTACT
,
2132 self
->mLongTapTouchPoint
->mPosition
, 1.0, 90, nullptr);
2137 AutoObserverNotifier
notifier(self
->mLongTapTouchPoint
->mObserver
,
2140 // finished, remove the touch point
2141 self
->mLongTapTimer
->Cancel();
2142 self
->mLongTapTimer
= nullptr;
2143 self
->SynthesizeNativeTouchPoint(
2144 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_REMOVE
,
2145 self
->mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2146 self
->mLongTapTouchPoint
= nullptr;
2149 float nsIWidget::GetFallbackDPI() {
2150 RefPtr
<const Screen
> primaryScreen
=
2151 ScreenManager::GetSingleton().GetPrimaryScreen();
2152 return primaryScreen
->GetDPI();
2155 CSSToLayoutDeviceScale
nsIWidget::GetFallbackDefaultScale() {
2156 RefPtr
<const Screen
> s
= ScreenManager::GetSingleton().GetPrimaryScreen();
2157 return s
->GetCSSToLayoutDeviceScale(Screen::IncludeOSZoom::No
);
2160 nsresult
nsIWidget::ClearNativeTouchSequence(nsIObserver
* aObserver
) {
2161 AutoObserverNotifier
notifier(aObserver
, "cleartouch");
2163 // XXX This is odd. This is called by the constructor of nsIWidget. However,
2164 // at that point, nsIWidget::mLongTapTimer must be nullptr. Therefore,
2165 // this must do nothing at initializing the instance.
2166 if (!mLongTapTimer
) {
2169 mLongTapTimer
->Cancel();
2170 mLongTapTimer
= nullptr;
2171 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2172 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2173 mLongTapTouchPoint
= nullptr;
2177 MultiTouchInput
nsBaseWidget::UpdateSynthesizedTouchState(
2178 MultiTouchInput
* aState
, mozilla::TimeStamp aTimeStamp
, uint32_t aPointerId
,
2179 TouchPointerState aPointerState
, LayoutDeviceIntPoint aPoint
,
2180 double aPointerPressure
, uint32_t aPointerOrientation
) {
2181 ScreenIntPoint pointerScreenPoint
= ViewAs
<ScreenPixel
>(
2182 aPoint
, PixelCastJustification::LayoutDeviceIsScreenForBounds
);
2184 // We can't dispatch *aState directly because (a) dispatching
2185 // it might inadvertently modify it and (b) in the case of touchend or
2186 // touchcancel events aState will hold the touches that are
2187 // still down whereas the input dispatched needs to hold the removed
2188 // touch(es). We use |inputToDispatch| for this purpose.
2189 MultiTouchInput inputToDispatch
;
2190 inputToDispatch
.mInputType
= MULTITOUCH_INPUT
;
2191 inputToDispatch
.mTimeStamp
= aTimeStamp
;
2193 int32_t index
= aState
->IndexOfTouch((int32_t)aPointerId
);
2194 if (aPointerState
== TOUCH_CONTACT
) {
2196 // found an existing touch point, update it
2197 SingleTouchData
& point
= aState
->mTouches
[index
];
2198 point
.mScreenPoint
= pointerScreenPoint
;
2199 point
.mRotationAngle
= (float)aPointerOrientation
;
2200 point
.mForce
= (float)aPointerPressure
;
2201 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_MOVE
;
2203 // new touch point, add it
2204 aState
->mTouches
.AppendElement(SingleTouchData(
2205 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2206 (float)aPointerOrientation
, (float)aPointerPressure
));
2207 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_START
;
2209 inputToDispatch
.mTouches
= aState
->mTouches
;
2211 MOZ_ASSERT(aPointerState
== TOUCH_REMOVE
|| aPointerState
== TOUCH_CANCEL
);
2212 // a touch point is being lifted, so remove it from the stored list
2214 aState
->mTouches
.RemoveElementAt(index
);
2216 inputToDispatch
.mType
=
2217 (aPointerState
== TOUCH_REMOVE
? MultiTouchInput::MULTITOUCH_END
2218 : MultiTouchInput::MULTITOUCH_CANCEL
);
2219 inputToDispatch
.mTouches
.AppendElement(SingleTouchData(
2220 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2221 (float)aPointerOrientation
, (float)aPointerPressure
));
2224 return inputToDispatch
;
2227 void nsBaseWidget::NotifyLiveResizeStarted() {
2228 // If we have mLiveResizeListeners already non-empty, we should notify those
2229 // listeners that the resize stopped before starting anew. In theory this
2230 // should never happen because we shouldn't get nested live resize actions.
2231 NotifyLiveResizeStopped();
2232 MOZ_ASSERT(mLiveResizeListeners
.IsEmpty());
2234 // If we can get the active remote tab for the current widget, suppress
2235 // the displayport on it during the live resize.
2236 if (!mWidgetListener
) {
2239 nsCOMPtr
<nsIAppWindow
> appWindow
= mWidgetListener
->GetAppWindow();
2243 mLiveResizeListeners
= appWindow
->GetLiveResizeListeners();
2244 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2245 mLiveResizeListeners
[i
]->LiveResizeStarted();
2249 void nsBaseWidget::NotifyLiveResizeStopped() {
2250 if (!mLiveResizeListeners
.IsEmpty()) {
2251 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2252 mLiveResizeListeners
[i
]->LiveResizeStopped();
2254 mLiveResizeListeners
.Clear();
2258 nsresult
nsBaseWidget::AsyncEnableDragDrop(bool aEnable
) {
2259 RefPtr
<nsBaseWidget
> kungFuDeathGrip
= this;
2260 return NS_DispatchToCurrentThreadQueue(
2261 NS_NewRunnableFunction(
2262 "AsyncEnableDragDropFn",
2263 [this, aEnable
, kungFuDeathGrip
]() { EnableDragDrop(aEnable
); }),
2264 kAsyncDragDropTimeout
, EventQueuePriority::Idle
);
2267 void nsBaseWidget::SwipeFinished() {
2268 if (mSwipeTracker
) {
2269 mSwipeTracker
->Destroy();
2270 mSwipeTracker
= nullptr;
2274 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId
,
2276 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== aInputBlockId
) {
2278 PanGestureInput
& startEvent
= mSwipeEventQueue
->queuedEvents
[0];
2279 TrackScrollEventAsSwipe(startEvent
, mSwipeEventQueue
->allowedDirections
,
2281 for (size_t i
= 1; i
< mSwipeEventQueue
->queuedEvents
.Length(); i
++) {
2282 mSwipeTracker
->ProcessEvent(mSwipeEventQueue
->queuedEvents
[i
]);
2285 // If the event wasn't start swipe, we need to notify it to APZ.
2286 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2287 BrowserGestureResponse::NotConsumed
);
2289 mSwipeEventQueue
= nullptr;
2293 void nsBaseWidget::TrackScrollEventAsSwipe(
2294 const mozilla::PanGestureInput
& aSwipeStartEvent
,
2295 uint32_t aAllowedDirections
, uint64_t aInputBlockId
) {
2296 // If a swipe is currently being tracked kill it -- it's been interrupted
2297 // by another gesture event.
2298 if (mSwipeTracker
) {
2299 mSwipeTracker
->CancelSwipe(aSwipeStartEvent
.mTimeStamp
);
2300 mSwipeTracker
->Destroy();
2301 mSwipeTracker
= nullptr;
2304 uint32_t direction
=
2305 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2306 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2307 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2310 new SwipeTracker(*this, aSwipeStartEvent
, aAllowedDirections
, direction
);
2313 mCurrentPanGestureBelongsToSwipe
= true;
2315 // Now SwipeTracker has started consuming pan events, notify it to APZ so
2316 // that APZ can discard queued events.
2317 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2318 BrowserGestureResponse::Consumed
);
2322 nsBaseWidget::SwipeInfo
nsBaseWidget::SendMayStartSwipe(
2323 const mozilla::PanGestureInput
& aSwipeStartEvent
) {
2324 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
2326 uint32_t direction
=
2327 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2328 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2329 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2331 // We're ready to start the animation. Tell Gecko about it, and at the same
2332 // time ask it if it really wants to start an animation for this event.
2333 // This event also reports back the directions that we can swipe in.
2334 LayoutDeviceIntPoint position
= RoundedToInt(aSwipeStartEvent
.mPanStartPoint
*
2335 ScreenToLayoutDeviceScale(1));
2336 WidgetSimpleGestureEvent geckoEvent
= SwipeTracker::CreateSwipeGestureEvent(
2337 eSwipeGestureMayStart
, this, position
, aSwipeStartEvent
.mTimeStamp
);
2338 geckoEvent
.mDirection
= direction
;
2339 geckoEvent
.mDelta
= 0.0;
2340 geckoEvent
.mAllowedDirections
= 0;
2341 bool shouldStartSwipe
=
2342 DispatchWindowEvent(geckoEvent
); // event cancelled == swipe should start
2344 SwipeInfo result
= {shouldStartSwipe
, geckoEvent
.mAllowedDirections
};
2348 WidgetWheelEvent
nsBaseWidget::MayStartSwipeForAPZ(
2349 const PanGestureInput
& aPanInput
, const APZEventResult
& aApzResult
) {
2350 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2352 // Ignore swipe-to-navigation in PiP window.
2357 if (aPanInput
.AllowsSwipe()) {
2358 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2359 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2360 if (swipeInfo
.wantsSwipe
) {
2361 if (aApzResult
.GetStatus() == nsEventStatus_eIgnore
) {
2362 // APZ has determined and that scrolling horizontally in the
2363 // requested direction is impossible, so it didn't do any
2364 // scrolling for the event.
2365 // We know now that MayStartSwipe wants a swipe, so we can start
2367 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
,
2368 aApzResult
.mInputBlockId
);
2369 } else if (!aApzResult
.GetHandledResult() ||
2370 !aApzResult
.GetHandledResult()->IsHandledByRoot()) {
2371 // We don't know whether this event can start a swipe, so we need
2372 // to queue up events and wait for a call to ReportSwipeStarted.
2373 // APZ might already have started scrolling in response to the
2374 // event if it knew that it's the right thing to do. In that case
2375 // we'll still get a call to ReportSwipeStarted, and we will
2376 // discard the queued events at that point.
2377 mSwipeEventQueue
= MakeUnique
<SwipeEventQueue
>(
2378 swipeInfo
.allowedDirections
, aApzResult
.mInputBlockId
);
2381 // Inform that the browser gesture didn't use the pan event (pan-start
2382 // precisely), so that APZ can now start using the event for
2383 // scrolling/overscrolling.
2384 mAPZC
->SetBrowserGestureResponse(aApzResult
.mInputBlockId
,
2385 BrowserGestureResponse::NotConsumed
);
2389 if (mSwipeEventQueue
&&
2390 mSwipeEventQueue
->inputBlockId
== aApzResult
.mInputBlockId
) {
2391 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2397 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput
& aPanInput
) {
2398 // Ignore swipe-to-navigation in PiP window.
2403 if (aPanInput
.mType
== PanGestureInput::PANGESTURE_MAYSTART
||
2404 aPanInput
.mType
== PanGestureInput::PANGESTURE_START
) {
2405 mCurrentPanGestureBelongsToSwipe
= false;
2407 if (mCurrentPanGestureBelongsToSwipe
) {
2408 // Ignore this event. It's a momentum event from a scroll gesture
2409 // that was processed as a swipe, and the swipe animation has
2410 // already finished (so mSwipeTracker is already null).
2411 MOZ_ASSERT(aPanInput
.IsMomentum(),
2412 "If the fingers are still on the touchpad, we should still have "
2414 "and it should have consumed this event.");
2418 if (!aPanInput
.MayTriggerSwipe()) {
2422 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2424 // We're in the non-APZ case here, but we still want to know whether
2425 // the event was routed to a child process, so we use InputAPZContext
2426 // to get that piece of information.
2427 ScrollableLayerGuid guid
;
2428 uint64_t blockId
= 0;
2429 InputAPZContext
context(guid
, blockId
, nsEventStatus_eIgnore
);
2431 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2432 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2433 nsEventStatus status
;
2434 DispatchEvent(&event
, status
);
2435 if (swipeInfo
.wantsSwipe
) {
2436 if (context
.WasRoutedToChildProcess()) {
2437 // We don't know whether this event can start a swipe, so we need
2438 // to queue up events and wait for a call to ReportSwipeStarted.
2440 MakeUnique
<SwipeEventQueue
>(swipeInfo
.allowedDirections
, blockId
);
2441 } else if (event
.TriggersSwipe()) {
2442 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
, blockId
);
2446 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== 0) {
2447 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2453 const IMENotificationRequests
& nsIWidget::IMENotificationRequestsRef() {
2454 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
2455 return dispatcher
->IMENotificationRequestsRef();
2458 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent
* aEvent
) {}
2460 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType
,
2461 const WidgetKeyboardEvent
& aEvent
,
2462 nsTArray
<CommandInt
>& aCommands
) {
2463 MOZ_ASSERT(aEvent
.IsTrusted());
2464 MOZ_ASSERT(aCommands
.IsEmpty());
2468 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboard() {
2469 if (XRE_IsContentProcess()) {
2470 return CreateBidiKeyboardContentProcess();
2472 return CreateBidiKeyboardInner();
2476 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboardInner() {
2477 // no bidi keyboard implementation
2482 namespace mozilla::widget
{
2484 const char* ToChar(InputContext::Origin aOrigin
) {
2486 case InputContext::ORIGIN_MAIN
:
2487 return "ORIGIN_MAIN";
2488 case InputContext::ORIGIN_CONTENT
:
2489 return "ORIGIN_CONTENT";
2491 return "Unexpected value";
2495 const char* ToChar(IMEMessage aIMEMessage
) {
2496 switch (aIMEMessage
) {
2497 case NOTIFY_IME_OF_NOTHING
:
2498 return "NOTIFY_IME_OF_NOTHING";
2499 case NOTIFY_IME_OF_FOCUS
:
2500 return "NOTIFY_IME_OF_FOCUS";
2501 case NOTIFY_IME_OF_BLUR
:
2502 return "NOTIFY_IME_OF_BLUR";
2503 case NOTIFY_IME_OF_SELECTION_CHANGE
:
2504 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2505 case NOTIFY_IME_OF_TEXT_CHANGE
:
2506 return "NOTIFY_IME_OF_TEXT_CHANGE";
2507 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED
:
2508 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2509 case NOTIFY_IME_OF_POSITION_CHANGE
:
2510 return "NOTIFY_IME_OF_POSITION_CHANGE";
2511 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT
:
2512 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2513 case REQUEST_TO_COMMIT_COMPOSITION
:
2514 return "REQUEST_TO_COMMIT_COMPOSITION";
2515 case REQUEST_TO_CANCEL_COMPOSITION
:
2516 return "REQUEST_TO_CANCEL_COMPOSITION";
2518 return "Unexpected value";
2522 void NativeIMEContext::Init(nsIWidget
* aWidget
) {
2524 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2525 mOriginProcessID
= static_cast<uint64_t>(-1);
2528 if (!XRE_IsContentProcess()) {
2529 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(
2530 aWidget
->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT
));
2531 mOriginProcessID
= 0;
2534 // If this is created in a child process, aWidget is an instance of
2535 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2536 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2537 // native IME context of the parent process.
2538 *this = aWidget
->GetNativeIMEContext();
2541 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext
) {
2542 if (NS_WARN_IF(!aRawNativeIMEContext
)) {
2543 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2544 mOriginProcessID
= static_cast<uint64_t>(-1);
2547 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(aRawNativeIMEContext
);
2549 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2552 void IMENotification::TextChangeDataBase::MergeWith(
2553 const IMENotification::TextChangeDataBase
& aOther
) {
2554 MOZ_ASSERT(aOther
.IsValid(), "Merging data must store valid data");
2555 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mRemovedEndOffset
,
2556 "end of removed text must be same or larger than start");
2557 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mAddedEndOffset
,
2558 "end of added text must be same or larger than start");
2565 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2566 // text ranges. I.e., mStartOffset should be the smallest offset of all
2567 // modified text ranges in old text. |mRemovedEndOffset| should be the
2568 // largest end offset in old text of all modified text ranges.
2569 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2570 // I.e., only this is an offset in new text.
2571 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2572 // premodified text was already removed. And some text whose length is
2573 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2574 // this allows IME to mark dirty the modified text range with |mStartOffset|
2575 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2576 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2577 // Additionally, IME can retrieve only the text between |mStartOffset| and
2578 // |mAddedEndOffset| for updating stored text.
2580 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2581 // should be adjusted to be in same text. The |newData.mStartOffset| and
2582 // |newData.mRemovedEndOffset| should be computed as in old text because
2583 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2584 // in the old text but even if some text before the values of the newData
2585 // has already been modified, the values don't include the changes.
2587 // For comparing new and old |mAddedEndOffset| values, they should be
2588 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2589 // computed as in the new text because |mAddedEndOffset| indicates the end
2590 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2591 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2593 const TextChangeDataBase
& newData
= aOther
;
2594 const TextChangeDataBase oldData
= *this;
2596 // mCausedOnlyByComposition should be true only when all changes are caused
2598 mCausedOnlyByComposition
=
2599 newData
.mCausedOnlyByComposition
&& oldData
.mCausedOnlyByComposition
;
2601 // mIncludingChangesWithoutComposition should be true if at least one of
2602 // merged changes occurred without composition.
2603 mIncludingChangesWithoutComposition
=
2604 newData
.mIncludingChangesWithoutComposition
||
2605 oldData
.mIncludingChangesWithoutComposition
;
2607 // mIncludingChangesDuringComposition should be true when at least one of
2608 // the merged non-composition changes occurred during the latest composition.
2609 if (!newData
.mCausedOnlyByComposition
&&
2610 !newData
.mIncludingChangesDuringComposition
) {
2611 MOZ_ASSERT(newData
.mIncludingChangesWithoutComposition
);
2612 MOZ_ASSERT(mIncludingChangesWithoutComposition
);
2613 // If new change is neither caused by composition nor occurred during
2614 // composition, set mIncludingChangesDuringComposition to false because
2615 // IME doesn't want outdated text changes as text change during current
2617 mIncludingChangesDuringComposition
= false;
2619 // Otherwise, set mIncludingChangesDuringComposition to true if either
2620 // oldData or newData includes changes during composition.
2621 mIncludingChangesDuringComposition
=
2622 newData
.mIncludingChangesDuringComposition
||
2623 oldData
.mIncludingChangesDuringComposition
;
2626 if (newData
.mStartOffset
>= oldData
.mAddedEndOffset
) {
2628 // If new start is after old end offset of added text, it means that text
2629 // after the modified range is modified. Like:
2630 // added range of old change: +----------+
2631 // removed range of new change: +----------+
2632 // So, the old start offset is always the smaller offset.
2633 mStartOffset
= oldData
.mStartOffset
;
2634 // The new end offset of removed text is moved by the old change and we
2635 // need to cancel the move of the old change for comparing the offsets in
2636 // same text because it doesn't make sensce to compare offsets in different
2638 uint32_t newRemovedEndOffsetInOldText
=
2639 newData
.mRemovedEndOffset
- oldData
.Difference();
2641 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2642 // The new end offset of added text is always the larger offset.
2643 mAddedEndOffset
= newData
.mAddedEndOffset
;
2647 if (newData
.mStartOffset
>= oldData
.mStartOffset
) {
2648 // If new start is in the modified range, it means that new data changes
2649 // a part or all of the range.
2650 mStartOffset
= oldData
.mStartOffset
;
2651 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2653 // If new end of removed text is greater than old end of added text, it
2654 // means that all or a part of modified range modified again and text
2655 // after the modified range is also modified. Like:
2656 // added range of old change: +----------+
2657 // removed range of new change: +----------+
2658 // So, the new removed end offset is moved by the old change and we need
2659 // to cancel the move of the old change for comparing the offsets in the
2660 // same text because it doesn't make sense to compare the offsets in
2662 uint32_t newRemovedEndOffsetInOldText
=
2663 newData
.mRemovedEndOffset
- oldData
.Difference();
2665 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2666 // The old end of added text is replaced by new change. So, it should be
2667 // same as the new start. On the other hand, the new added end offset is
2668 // always same or larger. Therefore, the merged end offset of added
2669 // text should be the new end offset of added text.
2670 mAddedEndOffset
= newData
.mAddedEndOffset
;
2675 // If new end of removed text is less than old end of added text, it means
2676 // that only a part of the modified range is modified again. Like:
2677 // added range of old change: +------------+
2678 // removed range of new change: +-----+
2679 // So, the new end offset of removed text should be same as the old end
2680 // offset of removed text. Therefore, the merged end offset of removed
2681 // text should be the old text change's |mRemovedEndOffset|.
2682 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2683 // The old end of added text is moved by new change. So, we need to cancel
2684 // the move of the new change for comparing the offsets in same text.
2685 uint32_t oldAddedEndOffsetInNewText
=
2686 oldData
.mAddedEndOffset
+ newData
.Difference();
2688 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2692 if (newData
.mRemovedEndOffset
>= oldData
.mStartOffset
) {
2693 // If new end of removed text is greater than old start (and new start is
2694 // less than old start), it means that a part of modified range is modified
2695 // again and some new text before the modified range is also modified.
2696 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2697 "new start offset should be less than old one here");
2698 mStartOffset
= newData
.mStartOffset
;
2699 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2701 // If new end of removed text is greater than old end of added text, it
2702 // means that all modified text and text after the modified range is
2704 // added range of old change: +----------+
2705 // removed range of new change: +------------------+
2706 // So, the new end of removed text is moved by the old change. Therefore,
2707 // we need to cancel the move of the old change for comparing the offsets
2708 // in same text because it doesn't make sense to compare the offsets in
2710 uint32_t newRemovedEndOffsetInOldText
=
2711 newData
.mRemovedEndOffset
- oldData
.Difference();
2713 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2714 // The old end of added text is replaced by new change. So, the old end
2715 // offset of added text is same as new text change's start offset. Then,
2716 // new change's end offset of added text is always same or larger than
2717 // it. Therefore, merged end offset of added text is always the new end
2718 // offset of added text.
2719 mAddedEndOffset
= newData
.mAddedEndOffset
;
2724 // If new end of removed text is less than old end of added text, it
2725 // means 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 of removed text should be same as old end of removed
2729 // text for preventing end of removed text to be modified. Therefore,
2730 // merged end offset of removed text is always the old end offset of removed
2732 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2733 // The old end of added text is moved by this change. So, we need to
2734 // cancel the move of the new change for comparing the offsets in same text
2735 // because it doesn't make sense to compare the offsets in different text.
2736 uint32_t oldAddedEndOffsetInNewText
=
2737 oldData
.mAddedEndOffset
+ newData
.Difference();
2739 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2744 // Otherwise, i.e., both new end of added text and new start are less than
2745 // old start, text before the modified range is modified. Like:
2746 // added range of old change: +----------+
2747 // removed range of new change: +----------+
2748 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2749 "new start offset should be less than old one here");
2750 mStartOffset
= newData
.mStartOffset
;
2751 MOZ_ASSERT(newData
.mRemovedEndOffset
< oldData
.mRemovedEndOffset
,
2752 "new removed end offset should be less than old one here");
2753 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2754 // The end of added text should be adjusted with the new difference.
2755 uint32_t oldAddedEndOffsetInNewText
=
2756 oldData
.mAddedEndOffset
+ newData
.Difference();
2758 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2763 // Let's test the code of merging multiple text change data in debug build
2764 // and crash if one of them fails because this feature is very complex but
2765 // cannot be tested with mochitest.
2766 void IMENotification::TextChangeDataBase::Test() {
2767 static bool gTestTextChangeEvent
= true;
2768 if (!gTestTextChangeEvent
) {
2771 gTestTextChangeEvent
= false;
2773 /****************************************************************************
2775 ****************************************************************************/
2778 MergeWith(TextChangeData(10, 10, 20, false, false));
2779 MergeWith(TextChangeData(20, 20, 35, false, false));
2780 MOZ_ASSERT(mStartOffset
== 10,
2781 "Test 1-1-1: mStartOffset should be the first offset");
2783 mRemovedEndOffset
== 10, // 20 - (20 - 10)
2784 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2786 mAddedEndOffset
== 35,
2787 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2790 // Removing text (longer line -> shorter line)
2791 MergeWith(TextChangeData(10, 20, 10, false, false));
2792 MergeWith(TextChangeData(10, 30, 10, false, false));
2793 MOZ_ASSERT(mStartOffset
== 10,
2794 "Test 1-2-1: mStartOffset should be the first offset");
2795 MOZ_ASSERT(mRemovedEndOffset
== 40, // 30 + (10 - 20)
2796 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2798 "with already removed length");
2800 mAddedEndOffset
== 10,
2801 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2804 // Removing text (shorter line -> longer line)
2805 MergeWith(TextChangeData(10, 20, 10, false, false));
2806 MergeWith(TextChangeData(10, 15, 10, false, false));
2807 MOZ_ASSERT(mStartOffset
== 10,
2808 "Test 1-3-1: mStartOffset should be the first offset");
2809 MOZ_ASSERT(mRemovedEndOffset
== 25, // 15 + (10 - 20)
2810 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2812 "with already removed length");
2814 mAddedEndOffset
== 10,
2815 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2818 // Appending text at different point (not sure if actually occurs)
2819 MergeWith(TextChangeData(10, 10, 20, false, false));
2820 MergeWith(TextChangeData(55, 55, 60, false, false));
2821 MOZ_ASSERT(mStartOffset
== 10,
2822 "Test 1-4-1: mStartOffset should be the smallest offset");
2824 mRemovedEndOffset
== 45, // 55 - (10 - 20)
2825 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2826 "text without already added length");
2828 mAddedEndOffset
== 60,
2829 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2832 // Removing text at different point (not sure if actually occurs)
2833 MergeWith(TextChangeData(10, 20, 10, false, false));
2834 MergeWith(TextChangeData(55, 68, 55, false, false));
2835 MOZ_ASSERT(mStartOffset
== 10,
2836 "Test 1-5-1: mStartOffset should be the smallest offset");
2838 mRemovedEndOffset
== 78, // 68 - (10 - 20)
2839 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2840 "text with already removed length");
2842 mAddedEndOffset
== 55,
2843 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2846 // Replacing text and append text (becomes longer)
2847 MergeWith(TextChangeData(30, 35, 32, false, false));
2848 MergeWith(TextChangeData(32, 32, 40, false, false));
2849 MOZ_ASSERT(mStartOffset
== 30,
2850 "Test 1-6-1: mStartOffset should be the smallest offset");
2852 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2853 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2856 mAddedEndOffset
== 40,
2857 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2860 // Replacing text and append text (becomes shorter)
2861 MergeWith(TextChangeData(30, 35, 32, false, false));
2862 MergeWith(TextChangeData(32, 32, 33, false, false));
2863 MOZ_ASSERT(mStartOffset
== 30,
2864 "Test 1-7-1: mStartOffset should be the smallest offset");
2866 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2867 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2870 mAddedEndOffset
== 33,
2871 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2874 // Removing text and replacing text after first range (not sure if actually
2876 MergeWith(TextChangeData(30, 35, 30, false, false));
2877 MergeWith(TextChangeData(32, 34, 48, false, false));
2878 MOZ_ASSERT(mStartOffset
== 30,
2879 "Test 1-8-1: mStartOffset should be the smallest offset");
2880 MOZ_ASSERT(mRemovedEndOffset
== 39, // 34 - (30 - 35)
2881 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2883 "without already removed text");
2885 mAddedEndOffset
== 48,
2886 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2889 // Removing text and replacing text after first range (not sure if actually
2891 MergeWith(TextChangeData(30, 35, 30, false, false));
2892 MergeWith(TextChangeData(32, 38, 36, false, false));
2893 MOZ_ASSERT(mStartOffset
== 30,
2894 "Test 1-9-1: mStartOffset should be the smallest offset");
2895 MOZ_ASSERT(mRemovedEndOffset
== 43, // 38 - (30 - 35)
2896 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2898 "without already removed text");
2900 mAddedEndOffset
== 36,
2901 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2904 /****************************************************************************
2906 ****************************************************************************/
2908 // Replacing text in around end of added text (becomes shorter) (not sure
2909 // if actually occurs)
2910 MergeWith(TextChangeData(50, 50, 55, false, false));
2911 MergeWith(TextChangeData(53, 60, 54, false, false));
2912 MOZ_ASSERT(mStartOffset
== 50,
2913 "Test 2-1-1: mStartOffset should be the smallest offset");
2914 MOZ_ASSERT(mRemovedEndOffset
== 55, // 60 - (55 - 50)
2915 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2917 "without already added text length");
2919 mAddedEndOffset
== 54,
2920 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2923 // Replacing text around end of added text (becomes longer) (not sure
2924 // if actually occurs)
2925 MergeWith(TextChangeData(50, 50, 55, false, false));
2926 MergeWith(TextChangeData(54, 62, 68, false, false));
2927 MOZ_ASSERT(mStartOffset
== 50,
2928 "Test 2-2-1: mStartOffset should be the smallest offset");
2929 MOZ_ASSERT(mRemovedEndOffset
== 57, // 62 - (55 - 50)
2930 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2932 "without already added text length");
2934 mAddedEndOffset
== 68,
2935 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2938 // Replacing text around end of replaced text (became shorter) (not sure if
2940 MergeWith(TextChangeData(36, 48, 45, false, false));
2941 MergeWith(TextChangeData(43, 50, 49, false, false));
2942 MOZ_ASSERT(mStartOffset
== 36,
2943 "Test 2-3-1: mStartOffset should be the smallest offset");
2944 MOZ_ASSERT(mRemovedEndOffset
== 53, // 50 - (45 - 48)
2945 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2947 "without already removed text length");
2949 mAddedEndOffset
== 49,
2950 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2953 // Replacing text around end of replaced text (became longer) (not sure if
2955 MergeWith(TextChangeData(36, 52, 53, false, false));
2956 MergeWith(TextChangeData(43, 68, 61, false, false));
2957 MOZ_ASSERT(mStartOffset
== 36,
2958 "Test 2-4-1: mStartOffset should be the smallest offset");
2959 MOZ_ASSERT(mRemovedEndOffset
== 67, // 68 - (53 - 52)
2960 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2962 "without already added text length");
2964 mAddedEndOffset
== 61,
2965 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2968 /****************************************************************************
2970 ****************************************************************************/
2972 // Appending text in already added text (not sure if actually occurs)
2973 MergeWith(TextChangeData(10, 10, 20, false, false));
2974 MergeWith(TextChangeData(15, 15, 30, false, false));
2975 MOZ_ASSERT(mStartOffset
== 10,
2976 "Test 3-1-1: mStartOffset should be the smallest offset");
2977 MOZ_ASSERT(mRemovedEndOffset
== 10,
2978 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2981 mAddedEndOffset
== 35, // 20 + (30 - 15)
2982 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2983 "added text length by the new change");
2986 // Replacing text in added text (not sure if actually occurs)
2987 MergeWith(TextChangeData(50, 50, 55, false, false));
2988 MergeWith(TextChangeData(52, 53, 56, false, false));
2989 MOZ_ASSERT(mStartOffset
== 50,
2990 "Test 3-2-1: mStartOffset should be the smallest offset");
2991 MOZ_ASSERT(mRemovedEndOffset
== 50,
2992 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2995 mAddedEndOffset
== 58, // 55 + (56 - 53)
2996 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2997 "added text length by the new change");
3000 // Replacing text in replaced text (became shorter) (not sure if actually
3002 MergeWith(TextChangeData(36, 48, 45, false, false));
3003 MergeWith(TextChangeData(37, 38, 50, false, false));
3004 MOZ_ASSERT(mStartOffset
== 36,
3005 "Test 3-3-1: mStartOffset should be the smallest offset");
3006 MOZ_ASSERT(mRemovedEndOffset
== 48,
3007 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
3010 mAddedEndOffset
== 57, // 45 + (50 - 38)
3011 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
3012 "added text length by the new change");
3015 // Replacing text in replaced text (became longer) (not sure if actually
3017 MergeWith(TextChangeData(32, 48, 53, false, false));
3018 MergeWith(TextChangeData(43, 50, 52, false, false));
3019 MOZ_ASSERT(mStartOffset
== 32,
3020 "Test 3-4-1: mStartOffset should be the smallest offset");
3021 MOZ_ASSERT(mRemovedEndOffset
== 48,
3022 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
3024 "without already added text length");
3026 mAddedEndOffset
== 55, // 53 + (52 - 50)
3027 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
3028 "added text length by the new change");
3031 // Replacing text in replaced text (became shorter) (not sure if actually
3033 MergeWith(TextChangeData(36, 48, 50, false, false));
3034 MergeWith(TextChangeData(37, 49, 47, false, false));
3035 MOZ_ASSERT(mStartOffset
== 36,
3036 "Test 3-5-1: mStartOffset should be the smallest offset");
3038 mRemovedEndOffset
== 48,
3039 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
3041 MOZ_ASSERT(mAddedEndOffset
== 48, // 50 + (47 - 49)
3042 "Test 3-5-3: mAddedEndOffset should be the first end of added "
3044 "removed text length by the new change");
3047 // Replacing text in replaced text (became longer) (not sure if actually
3049 MergeWith(TextChangeData(32, 48, 53, false, false));
3050 MergeWith(TextChangeData(43, 50, 47, false, false));
3051 MOZ_ASSERT(mStartOffset
== 32,
3052 "Test 3-6-1: mStartOffset should be the smallest offset");
3053 MOZ_ASSERT(mRemovedEndOffset
== 48,
3054 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
3056 "without already added text length");
3057 MOZ_ASSERT(mAddedEndOffset
== 50, // 53 + (47 - 50)
3058 "Test 3-6-3: mAddedEndOffset should be the first end of added "
3060 "removed text length by the new change");
3063 /****************************************************************************
3065 ****************************************************************************/
3067 // Replacing text all of already append text (not sure if actually occurs)
3068 MergeWith(TextChangeData(50, 50, 55, false, false));
3069 MergeWith(TextChangeData(44, 66, 68, false, false));
3070 MOZ_ASSERT(mStartOffset
== 44,
3071 "Test 4-1-1: mStartOffset should be the smallest offset");
3072 MOZ_ASSERT(mRemovedEndOffset
== 61, // 66 - (55 - 50)
3073 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
3075 "without already added text length");
3077 mAddedEndOffset
== 68,
3078 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3081 // Replacing text around a point in which text was removed (not sure if
3083 MergeWith(TextChangeData(50, 62, 50, false, false));
3084 MergeWith(TextChangeData(44, 66, 68, false, false));
3085 MOZ_ASSERT(mStartOffset
== 44,
3086 "Test 4-2-1: mStartOffset should be the smallest offset");
3087 MOZ_ASSERT(mRemovedEndOffset
== 78, // 66 - (50 - 62)
3088 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
3090 "without already removed text length");
3092 mAddedEndOffset
== 68,
3093 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3096 // Replacing text all replaced text (became shorter) (not sure if actually
3098 MergeWith(TextChangeData(50, 62, 60, false, false));
3099 MergeWith(TextChangeData(49, 128, 130, false, false));
3100 MOZ_ASSERT(mStartOffset
== 49,
3101 "Test 4-3-1: mStartOffset should be the smallest offset");
3102 MOZ_ASSERT(mRemovedEndOffset
== 130, // 128 - (60 - 62)
3103 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
3105 "without already removed text length");
3107 mAddedEndOffset
== 130,
3108 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3111 // Replacing text all replaced text (became longer) (not sure if actually
3113 MergeWith(TextChangeData(50, 61, 73, false, false));
3114 MergeWith(TextChangeData(44, 100, 50, false, false));
3115 MOZ_ASSERT(mStartOffset
== 44,
3116 "Test 4-4-1: mStartOffset should be the smallest offset");
3117 MOZ_ASSERT(mRemovedEndOffset
== 88, // 100 - (73 - 61)
3118 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
3120 "with already added text length");
3122 mAddedEndOffset
== 50,
3123 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3126 /****************************************************************************
3128 ****************************************************************************/
3130 // Replacing text around start of added text (not sure if actually occurs)
3131 MergeWith(TextChangeData(50, 50, 55, false, false));
3132 MergeWith(TextChangeData(48, 52, 49, false, false));
3133 MOZ_ASSERT(mStartOffset
== 48,
3134 "Test 5-1-1: mStartOffset should be the smallest offset");
3136 mRemovedEndOffset
== 50,
3137 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
3140 mAddedEndOffset
== 52, // 55 + (52 - 49)
3141 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
3142 "added text length by the new change");
3145 // Replacing text around start of replaced text (became shorter) (not sure if
3147 MergeWith(TextChangeData(50, 60, 58, false, false));
3148 MergeWith(TextChangeData(43, 50, 48, false, false));
3149 MOZ_ASSERT(mStartOffset
== 43,
3150 "Test 5-2-1: mStartOffset should be the smallest offset");
3152 mRemovedEndOffset
== 60,
3153 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3155 MOZ_ASSERT(mAddedEndOffset
== 56, // 58 + (48 - 50)
3156 "Test 5-2-3: mAddedEndOffset should be the first end of added "
3158 "removed text length by the new change");
3161 // Replacing text around start of replaced text (became longer) (not sure if
3163 MergeWith(TextChangeData(50, 60, 68, false, false));
3164 MergeWith(TextChangeData(43, 55, 53, false, false));
3165 MOZ_ASSERT(mStartOffset
== 43,
3166 "Test 5-3-1: mStartOffset should be the smallest offset");
3168 mRemovedEndOffset
== 60,
3169 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3171 MOZ_ASSERT(mAddedEndOffset
== 66, // 68 + (53 - 55)
3172 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3174 "removed text length by the new change");
3177 // Replacing text around start of replaced text (became shorter) (not sure if
3179 MergeWith(TextChangeData(50, 60, 58, false, false));
3180 MergeWith(TextChangeData(43, 50, 128, false, false));
3181 MOZ_ASSERT(mStartOffset
== 43,
3182 "Test 5-4-1: mStartOffset should be the smallest offset");
3184 mRemovedEndOffset
== 60,
3185 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
3188 mAddedEndOffset
== 136, // 58 + (128 - 50)
3189 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
3190 "added text length by the new change");
3193 // Replacing text around start of replaced text (became longer) (not sure if
3195 MergeWith(TextChangeData(50, 60, 68, false, false));
3196 MergeWith(TextChangeData(43, 55, 65, false, false));
3197 MOZ_ASSERT(mStartOffset
== 43,
3198 "Test 5-5-1: mStartOffset should be the smallest offset");
3200 mRemovedEndOffset
== 60,
3201 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
3204 mAddedEndOffset
== 78, // 68 + (65 - 55)
3205 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
3206 "added text length by the new change");
3209 /****************************************************************************
3211 ****************************************************************************/
3213 // Appending text before already added text (not sure if actually occurs)
3214 MergeWith(TextChangeData(30, 30, 45, false, false));
3215 MergeWith(TextChangeData(10, 10, 20, false, false));
3216 MOZ_ASSERT(mStartOffset
== 10,
3217 "Test 6-1-1: mStartOffset should be the smallest offset");
3219 mRemovedEndOffset
== 30,
3220 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3223 mAddedEndOffset
== 55, // 45 + (20 - 10)
3224 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3225 "added text length by the new change");
3228 // Removing text before already removed text (not sure if actually occurs)
3229 MergeWith(TextChangeData(30, 35, 30, false, false));
3230 MergeWith(TextChangeData(10, 25, 10, false, false));
3231 MOZ_ASSERT(mStartOffset
== 10,
3232 "Test 6-2-1: mStartOffset should be the smallest offset");
3234 mRemovedEndOffset
== 35,
3235 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3238 mAddedEndOffset
== 15, // 30 - (25 - 10)
3239 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3240 "removed text length by the new change");
3243 // Replacing text before already replaced text (not sure if actually occurs)
3244 MergeWith(TextChangeData(50, 65, 70, false, false));
3245 MergeWith(TextChangeData(13, 24, 15, false, false));
3246 MOZ_ASSERT(mStartOffset
== 13,
3247 "Test 6-3-1: mStartOffset should be the smallest offset");
3249 mRemovedEndOffset
== 65,
3250 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3252 MOZ_ASSERT(mAddedEndOffset
== 61, // 70 + (15 - 24)
3253 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3255 "removed text length by the new change");
3258 // Replacing text before already replaced text (not sure if actually occurs)
3259 MergeWith(TextChangeData(50, 65, 70, false, false));
3260 MergeWith(TextChangeData(13, 24, 36, false, false));
3261 MOZ_ASSERT(mStartOffset
== 13,
3262 "Test 6-4-1: mStartOffset should be the smallest offset");
3264 mRemovedEndOffset
== 65,
3265 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3267 MOZ_ASSERT(mAddedEndOffset
== 82, // 70 + (36 - 24)
3268 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3270 "removed text length by the new change");
3274 #endif // #ifdef DEBUG
3276 } // namespace mozilla::widget
3279 //////////////////////////////////////////////////////////////
3281 // Convert a GUI event message code to a string.
3282 // Makes it a lot easier to debug events.
3284 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3285 // for a DebugPrintEvent() function that uses
3288 //////////////////////////////////////////////////////////////
3290 nsAutoString
nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent
* aGuiEvent
) {
3291 NS_ASSERTION(nullptr != aGuiEvent
, "cmon, null gui event.");
3293 nsAutoString
eventName(u
"UNKNOWN"_ns
);
3295 # define _ASSIGN_eventName(_value, _name) \
3297 eventName.AssignLiteral(_name); \
3300 switch (aGuiEvent
->mMessage
) {
3301 _ASSIGN_eventName(eBlur
, "eBlur");
3302 _ASSIGN_eventName(eDrop
, "eDrop");
3303 _ASSIGN_eventName(eDragEnter
, "eDragEnter");
3304 _ASSIGN_eventName(eDragExit
, "eDragExit");
3305 _ASSIGN_eventName(eDragOver
, "eDragOver");
3306 _ASSIGN_eventName(eEditorInput
, "eEditorInput");
3307 _ASSIGN_eventName(eFocus
, "eFocus");
3308 _ASSIGN_eventName(eFocusIn
, "eFocusIn");
3309 _ASSIGN_eventName(eFocusOut
, "eFocusOut");
3310 _ASSIGN_eventName(eFormSelect
, "eFormSelect");
3311 _ASSIGN_eventName(eFormChange
, "eFormChange");
3312 _ASSIGN_eventName(eFormReset
, "eFormReset");
3313 _ASSIGN_eventName(eFormSubmit
, "eFormSubmit");
3314 _ASSIGN_eventName(eImageAbort
, "eImageAbort");
3315 _ASSIGN_eventName(eLoadError
, "eLoadError");
3316 _ASSIGN_eventName(eKeyDown
, "eKeyDown");
3317 _ASSIGN_eventName(eKeyPress
, "eKeyPress");
3318 _ASSIGN_eventName(eKeyUp
, "eKeyUp");
3319 _ASSIGN_eventName(eMouseEnterIntoWidget
, "eMouseEnterIntoWidget");
3320 _ASSIGN_eventName(eMouseExitFromWidget
, "eMouseExitFromWidget");
3321 _ASSIGN_eventName(eMouseDown
, "eMouseDown");
3322 _ASSIGN_eventName(eMouseUp
, "eMouseUp");
3323 _ASSIGN_eventName(eMouseClick
, "eMouseClick");
3324 _ASSIGN_eventName(eMouseAuxClick
, "eMouseAuxClick");
3325 _ASSIGN_eventName(eMouseDoubleClick
, "eMouseDoubleClick");
3326 _ASSIGN_eventName(eMouseMove
, "eMouseMove");
3327 _ASSIGN_eventName(eLoad
, "eLoad");
3328 _ASSIGN_eventName(ePopState
, "ePopState");
3329 _ASSIGN_eventName(eBeforeScriptExecute
, "eBeforeScriptExecute");
3330 _ASSIGN_eventName(eAfterScriptExecute
, "eAfterScriptExecute");
3331 _ASSIGN_eventName(eUnload
, "eUnload");
3332 _ASSIGN_eventName(eHashChange
, "eHashChange");
3333 _ASSIGN_eventName(eReadyStateChange
, "eReadyStateChange");
3334 _ASSIGN_eventName(eXULBroadcast
, "eXULBroadcast");
3335 _ASSIGN_eventName(eXULCommandUpdate
, "eXULCommandUpdate");
3337 # undef _ASSIGN_eventName
3340 eventName
.AssignLiteral("UNKNOWN: ");
3341 eventName
.AppendInt(aGuiEvent
->mMessage
);
3345 return nsAutoString(eventName
);
3347 //////////////////////////////////////////////////////////////
3349 // Code to deal with paint and event debug prefs.
3351 //////////////////////////////////////////////////////////////
3357 static PrefPair debug_PrefValues
[] = {
3358 {"nglayout.debug.crossing_event_dumping", false},
3359 {"nglayout.debug.event_dumping", false},
3360 {"nglayout.debug.invalidate_dumping", false},
3361 {"nglayout.debug.motion_event_dumping", false},
3362 {"nglayout.debug.paint_dumping", false}};
3364 //////////////////////////////////////////////////////////////
3365 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName
) {
3366 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3368 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3369 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3370 return debug_PrefValues
[i
].value
;
3376 //////////////////////////////////////////////////////////////
3377 static void debug_SetCachedBoolPref(const char* aPrefName
, bool aValue
) {
3378 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3380 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3381 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3382 debug_PrefValues
[i
].value
= aValue
;
3388 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3391 //////////////////////////////////////////////////////////////
3392 class Debug_PrefObserver final
: public nsIObserver
{
3393 ~Debug_PrefObserver() = default;
3400 NS_IMPL_ISUPPORTS(Debug_PrefObserver
, nsIObserver
)
3403 Debug_PrefObserver::Observe(nsISupports
* subject
, const char* topic
,
3404 const char16_t
* data
) {
3405 NS_ConvertUTF16toUTF8
prefName(data
);
3407 bool value
= Preferences::GetBool(prefName
.get(), false);
3408 debug_SetCachedBoolPref(prefName
.get(), value
);
3412 //////////////////////////////////////////////////////////////
3413 /* static */ void debug_RegisterPrefCallbacks() {
3414 static bool once
= true;
3422 nsCOMPtr
<nsIObserver
> obs(new Debug_PrefObserver());
3423 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3424 // Initialize the pref values
3425 debug_PrefValues
[i
].value
=
3426 Preferences::GetBool(debug_PrefValues
[i
].name
, false);
3429 // Register callbacks for when these change
3431 name
.AssignLiteral(debug_PrefValues
[i
].name
,
3432 strlen(debug_PrefValues
[i
].name
));
3433 Preferences::AddStrongObserver(obs
, name
);
3437 //////////////////////////////////////////////////////////////
3438 static int32_t _GetPrintCount() {
3439 static int32_t sCount
= 0;
3443 //////////////////////////////////////////////////////////////
3445 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3446 WidgetGUIEvent
* aGuiEvent
,
3447 const char* aWidgetName
, int32_t aWindowID
) {
3448 if (aGuiEvent
->mMessage
== eMouseMove
) {
3449 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3452 if (aGuiEvent
->mMessage
== eMouseEnterIntoWidget
||
3453 aGuiEvent
->mMessage
== eMouseExitFromWidget
) {
3454 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3458 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3460 NS_LossyConvertUTF16toASCII
tempString(
3461 debug_GuiEventToString(aGuiEvent
).get());
3463 fprintf(aFileOut
, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3464 _GetPrintCount(), tempString
.get(), (void*)aWidget
, aWidgetName
,
3465 aWindowID
, aGuiEvent
->mRefPoint
.x
.value
,
3466 aGuiEvent
->mRefPoint
.y
.value
);
3468 //////////////////////////////////////////////////////////////
3470 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3471 const nsIntRegion
& aRegion
,
3472 const char* aWidgetName
,
3473 int32_t aWindowID
) {
3474 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3475 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3477 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3479 nsIntRect rect
= aRegion
.GetBounds();
3481 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3483 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
, rect
.X(),
3484 rect
.Y(), rect
.Width(), rect
.Height());
3486 fprintf(aFileOut
, "\n");
3488 //////////////////////////////////////////////////////////////
3490 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut
, nsIWidget
* aWidget
,
3491 const LayoutDeviceIntRect
* aRect
,
3492 const char* aWidgetName
,
3493 int32_t aWindowID
) {
3494 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3496 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3497 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3499 fprintf(aFileOut
, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3500 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
);
3503 fprintf(aFileOut
, " rect=%3d,%-3d %3d,%-3d", aRect
->X(), aRect
->Y(),
3504 aRect
->Width(), aRect
->Height());
3506 fprintf(aFileOut
, " rect=%-15s", "none");
3509 fprintf(aFileOut
, "\n");
3511 //////////////////////////////////////////////////////////////