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 //-------------------------------------------------------------------------
706 // Window transparency methods
708 //-------------------------------------------------------------------------
710 void nsBaseWidget::SetTransparencyMode(TransparencyMode aMode
) {}
712 TransparencyMode
nsBaseWidget::GetTransparencyMode() {
713 return TransparencyMode::Opaque
;
717 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage
,
720 nsIRunnable
* aCallback
) {
721 MOZ_ASSERT_UNREACHABLE(
722 "Should never call PerformFullscreenTransition on nsBaseWidget");
725 //-------------------------------------------------------------------------
727 // Put the window into full-screen mode
729 //-------------------------------------------------------------------------
730 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen
) {
731 #define MOZ_FORMAT_RECT(fmtstr) "[" fmtstr "," fmtstr " " fmtstr "x" fmtstr "]"
732 #define MOZ_SPLAT_RECT(rect) \
733 (rect).X(), (rect).Y(), (rect).Width(), (rect).Height()
735 // Windows which can be made fullscreen are exactly those which are located on
736 // the desktop, rather than being a child of some other window.
737 MOZ_DIAGNOSTIC_ASSERT(BoundsUseDesktopPixels(),
738 "non-desktop windows cannot be made fullscreen");
740 // Ensure that the OS chrome is hidden/shown before we resize and/or exit the
743 // HideWindowChrome() may (depending on platform, implementation details, and
744 // OS-level user preferences) alter the reported size of the window. The
745 // obvious and principled solution is socks-and-shoes:
746 // - On entering fullscreen mode: hide window chrome, then perform resize.
747 // - On leaving fullscreen mode: unperform resize, then show window chrome.
749 // ... unfortunately, HideWindowChrome() requires Resize() to be called
750 // afterwards (see bug 498835), which prevents this from being done in a
751 // straightforward way.
753 // Instead, we always call HideWindowChrome() just before we call Resize().
754 // This at least ensures that our measurements are consistently taken in a
755 // pre-transition state.
757 // ... unfortunately again, coupling HideWindowChrome() to Resize() means that
758 // we have to worry about the possibility of control flows that don't call
759 // Resize() at all. (That shouldn't happen, but it's not trivial to rule out.)
760 // We therefore set up a fallback to fix up the OS chrome if it hasn't been
761 // done at exit time.
762 bool hasAdjustedOSChrome
= false;
763 const auto adjustOSChrome
= [&]() {
764 if (hasAdjustedOSChrome
) {
765 MOZ_ASSERT_UNREACHABLE("window chrome should only be adjusted once");
768 HideWindowChrome(aFullScreen
);
769 hasAdjustedOSChrome
= true;
771 const auto adjustChromeOnScopeExit
= MakeScopeExit([&]() {
772 if (hasAdjustedOSChrome
) {
776 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
777 ("window was not resized within InfallibleMakeFullScreen()"));
779 // Hide chrome and "resize" the window to its current size.
780 auto rect
= GetBounds();
782 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
785 // Attempt to resize to `rect`.
787 // Returns the actual rectangle resized to. (This may differ from `rect`, if
788 // the OS is unhappy with it. See bug 1786226.)
789 const auto doReposition
= [&](auto rect
) -> void {
790 static_assert(std::is_base_of_v
<DesktopPixel
,
791 std::remove_reference_t
<decltype(rect
)>>,
792 "doReposition requires a rectangle using desktop pixels");
794 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Debug
)) {
795 const DesktopRect previousSize
=
796 GetScreenBounds() / GetDesktopToDeviceScale();
797 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
798 ("before resize: " MOZ_FORMAT_RECT("%f"),
799 MOZ_SPLAT_RECT(previousSize
)));
803 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
805 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Warning
)) {
806 // `rect` may have any underlying data type; coerce to float to
807 // simplify printf-style logging
808 const gfx::RectTyped
<DesktopPixel
, float> rectAsFloat
{rect
};
810 // The OS may have objected to the target position. That's not necessarily
811 // a problem -- it'll happen regularly on Macs with camera notches in the
812 // monitor, for instance (see bug 1786226) -- but it probably deserves to
815 // Since there's floating-point math involved, the actual values may be
816 // off by a few ulps -- as an upper bound, perhaps 8 * FLT_EPSILON *
817 // max(MOZ_SPLAT_RECT(rect)) -- but 0.01 should be several orders of
818 // magnitude bigger than that.
820 const auto postResizeRectRaw
= GetScreenBounds();
821 const auto postResizeRect
= postResizeRectRaw
/ GetDesktopToDeviceScale();
822 const bool succeeded
= postResizeRect
.WithinEpsilonOf(rectAsFloat
, 0.01);
825 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
826 ("resized to: " MOZ_FORMAT_RECT("%f"),
827 MOZ_SPLAT_RECT(rectAsFloat
)));
829 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
830 ("attempted to resize to: " MOZ_FORMAT_RECT("%f"),
831 MOZ_SPLAT_RECT(rectAsFloat
)));
832 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
833 ("... but ended up at: " MOZ_FORMAT_RECT("%f"),
834 MOZ_SPLAT_RECT(postResizeRect
)));
838 sBaseWidgetLog
, LogLevel::Verbose
,
839 ("(... which, before DPI adjustment, is:" MOZ_FORMAT_RECT("%d") ")",
840 MOZ_SPLAT_RECT(postResizeRectRaw
)));
846 mSavedBounds
= Some(FullscreenSavedState());
848 // save current position
849 mSavedBounds
->windowRect
= GetScreenBounds() / GetDesktopToDeviceScale();
851 nsCOMPtr
<nsIScreen
> screen
= GetWidgetScreen();
856 // Move to fill the screen.
857 doReposition(screen
->GetRectDisplayPix());
858 // Save off the new position. (This may differ from GetRectDisplayPix(), if
859 // the OS was unhappy with it. See bug 1786226.)
860 mSavedBounds
->screenRect
= GetScreenBounds() / GetDesktopToDeviceScale();
863 // This should never happen, at present, since we don't make windows
864 // fullscreen at their creation time; but it's not logically impossible.
865 MOZ_ASSERT(false, "fullscreen window did not have saved position");
869 // Figure out where to go from here.
871 // Fortunately, since we're currently fullscreen (and other code should be
872 // handling _keeping_ us fullscreen even after display-layout changes),
873 // there's an obvious choice for which display we should attach to; all we
874 // need to determine is where on that display we should go.
876 const DesktopRect currentWinRect
=
877 GetScreenBounds() / GetDesktopToDeviceScale();
879 // Optimization: if where we are is where we were, then where we originally
880 // came from is where we're going to go.
881 if (currentWinRect
== DesktopRect(mSavedBounds
->screenRect
)) {
882 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
883 ("no location change detected; returning to saved location"));
884 doReposition(mSavedBounds
->windowRect
);
889 General case: figure out where we're going to go by dividing where we are
890 by where we were, and then multiplying by where we originally came from.
892 Less abstrusely: resize so that we occupy the same proportional position
893 on our current display after leaving fullscreen as we occupied on our
894 previous display before entering fullscreen.
896 (N.B.: We do not clamp. If we were only partially on the old display,
897 we'll be only partially on the new one, too.)
900 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
901 ("location change detected; computing new destination"));
903 // splat: convert an arbitrary Rect into a tuple, for syntactic convenience.
904 const auto splat
= [](auto rect
) {
905 return std::tuple(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height());
908 // remap: find the unique affine mapping which transforms `src` to `dst`,
909 // and apply it to `val`.
910 using Range
= std::pair
<float, float>;
911 const auto remap
= [](Range dst
, Range src
, float val
) {
912 // linear interpolation and its inverse: lerp(a, b, invlerp(a, b, t)) == t
913 const auto lerp
= [](float lo
, float hi
, float t
) {
914 return lo
+ t
* (hi
- lo
);
916 const auto invlerp
= [](float lo
, float hi
, float mid
) {
917 return (mid
- lo
) / (hi
- lo
);
920 const auto [dst_a
, dst_b
] = dst
;
921 const auto [src_a
, src_b
] = src
;
922 return lerp(dst_a
, dst_b
, invlerp(src_a
, src_b
, val
));
926 const auto [px
, py
, pw
, ph
] = splat(mSavedBounds
->windowRect
);
927 // source desktop rect
928 const auto [sx
, sy
, sw
, sh
] = splat(mSavedBounds
->screenRect
);
929 // target desktop rect
930 const auto [tx
, ty
, tw
, th
] = splat(currentWinRect
);
932 const float nx
= remap({tx
, tx
+ tw
}, {sx
, sx
+ sw
}, px
);
933 const float ny
= remap({ty
, ty
+ th
}, {sy
, sy
+ sh
}, py
);
934 const float nw
= remap({0, tw
}, {0, sw
}, pw
);
935 const float nh
= remap({0, th
}, {0, sh
}, ph
);
937 doReposition(DesktopRect
{nx
, ny
, nw
, nh
});
940 #undef MOZ_SPLAT_RECT
941 #undef MOZ_FORMAT_RECT
944 nsresult
nsBaseWidget::MakeFullScreen(bool aFullScreen
) {
945 InfallibleMakeFullScreen(aFullScreen
);
949 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
950 nsBaseWidget
* aWidget
, gfxContext
* aTarget
, BufferMode aDoubleBuffering
)
952 WindowRenderer
* renderer
= mWidget
->GetWindowRenderer();
953 if (renderer
->AsFallback()) {
954 mRenderer
= renderer
->AsFallback();
955 mRenderer
->SetTarget(aTarget
, aDoubleBuffering
);
959 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
961 mRenderer
->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE
);
965 bool nsBaseWidget::IsSmallPopup() const {
966 return mWindowType
== WindowType::Popup
&& mPopupType
!= PopupType::Panel
;
969 bool nsBaseWidget::ComputeShouldAccelerate() {
970 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING
) &&
971 (WidgetTypeSupportsAcceleration() ||
972 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
975 bool nsBaseWidget::UseAPZ() {
976 return (gfxPlatform::AsyncPanZoomEnabled() &&
977 (mWindowType
== WindowType::TopLevel
||
978 mWindowType
== WindowType::Child
||
979 ((mWindowType
== WindowType::Popup
||
980 mWindowType
== WindowType::Dialog
) &&
981 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
984 void nsBaseWidget::CreateCompositor() {
985 LayoutDeviceIntRect rect
= GetBounds();
986 CreateCompositor(rect
.Width(), rect
.Height());
989 void nsIWidget::PauseOrResumeCompositor(bool aPause
) {
990 auto* renderer
= GetRemoteRenderer();
995 renderer
->SendPause();
997 renderer
->SendResume();
1001 already_AddRefed
<GeckoContentController
>
1002 nsBaseWidget::CreateRootContentController() {
1003 RefPtr
<GeckoContentController
> controller
=
1004 new ChromeProcessController(this, mAPZEventState
, mAPZC
);
1005 return controller
.forget();
1008 void nsBaseWidget::ConfigureAPZCTreeManager() {
1009 MOZ_ASSERT(NS_IsMainThread());
1012 mAPZC
->SetDPI(GetDPI());
1014 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
1015 KeyboardMap map
= RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
1016 mAPZC
->SetKeyboardMap(map
);
1019 ContentReceivedInputBlockCallback
callback(
1020 [treeManager
= RefPtr
{mAPZC
.get()}](uint64_t aInputBlockId
,
1021 bool aPreventDefault
) {
1022 MOZ_ASSERT(NS_IsMainThread());
1023 treeManager
->ContentReceivedInputBlock(aInputBlockId
, aPreventDefault
);
1025 mAPZEventState
= new APZEventState(this, std::move(callback
));
1027 mRootContentController
= CreateRootContentController();
1028 if (mRootContentController
) {
1029 mCompositorSession
->SetContentController(mRootContentController
);
1032 // When APZ is enabled, we can actually enable raw touch events because we
1033 // have code that can deal with them properly. If APZ is not enabled, this
1034 // function doesn't get called.
1035 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
1036 RegisterTouchWindow();
1040 void nsBaseWidget::ConfigureAPZControllerThread() {
1041 // By default the controller thread is the main thread.
1042 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
1045 void nsBaseWidget::SetConfirmedTargetAPZC(
1046 uint64_t aInputBlockId
,
1047 const nsTArray
<ScrollableLayerGuid
>& aTargets
) const {
1048 mAPZC
->SetTargetAPZC(aInputBlockId
, aTargets
);
1051 void nsBaseWidget::UpdateZoomConstraints(
1052 const uint32_t& aPresShellId
, const ScrollableLayerGuid::ViewID
& aViewId
,
1053 const Maybe
<ZoomConstraints
>& aConstraints
) {
1054 if (!mCompositorSession
|| !mAPZC
) {
1055 if (mInitialZoomConstraints
) {
1056 MOZ_ASSERT(mInitialZoomConstraints
->mPresShellID
== aPresShellId
);
1057 MOZ_ASSERT(mInitialZoomConstraints
->mViewID
== aViewId
);
1058 if (!aConstraints
) {
1059 mInitialZoomConstraints
.reset();
1064 // We have some constraints, but the compositor and APZC aren't created
1065 // yet. Save these so we can use them later.
1066 mInitialZoomConstraints
= Some(
1067 InitialZoomConstraints(aPresShellId
, aViewId
, aConstraints
.ref()));
1071 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1072 mAPZC
->UpdateZoomConstraints(
1073 ScrollableLayerGuid(layersId
, aPresShellId
, aViewId
), aConstraints
);
1076 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC
; }
1078 nsEventStatus
nsBaseWidget::ProcessUntransformedAPZEvent(
1079 WidgetInputEvent
* aEvent
, const APZEventResult
& aApzResult
) {
1080 MOZ_ASSERT(NS_IsMainThread());
1081 ScrollableLayerGuid targetGuid
= aApzResult
.mTargetGuid
;
1082 uint64_t inputBlockId
= aApzResult
.mInputBlockId
;
1083 InputAPZContext
context(aApzResult
.mTargetGuid
, inputBlockId
,
1084 aApzResult
.GetStatus());
1086 // Make a copy of the original event for the APZCCallbackHelper helpers that
1087 // we call later, because the event passed to DispatchEvent can get mutated in
1088 // ways that we don't want (i.e. touch points can get stripped out).
1089 nsEventStatus status
;
1090 UniquePtr
<WidgetEvent
> original(aEvent
->Duplicate());
1091 DispatchEvent(aEvent
, status
);
1093 if (mAPZC
&& !InputAPZContext::WasRoutedToChildProcess() &&
1094 !InputAPZContext::WasDropped() && inputBlockId
) {
1095 // EventStateManager did not route the event into the child process and
1096 // the event was dispatched in the parent process.
1097 // It's safe to communicate to APZ that the event has been processed.
1098 // Note that here aGuid.mLayersId might be different from
1099 // mCompositorSession->RootLayerTreeId() because the event might have gotten
1100 // hit-tested by APZ to be targeted at a child process, but a parent process
1101 // event listener called preventDefault on it. In that case aGuid.mLayersId
1102 // would still be the layers id for the child process, but the event would
1103 // not have actually gotten routed to the child process. The main-thread
1104 // hit-test result therefore needs to use the parent process layers id.
1105 LayersId rootLayersId
= mCompositorSession
->RootLayerTreeId();
1107 RefPtr
<DisplayportSetListener
> postLayerization
;
1108 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1109 nsTArray
<TouchBehaviorFlags
> allowedTouchBehaviors
;
1110 if (touchEvent
->mMessage
== eTouchStart
) {
1111 auto& originalEvent
= *original
->AsTouchEvent();
1112 MOZ_ASSERT(NS_IsMainThread());
1113 allowedTouchBehaviors
= TouchActionHelper::GetAllowedTouchBehavior(
1114 this, GetDocument(), originalEvent
);
1115 if (!allowedTouchBehaviors
.IsEmpty()) {
1116 mAPZC
->SetAllowedTouchBehavior(inputBlockId
, allowedTouchBehaviors
);
1118 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1119 this, GetDocument(), originalEvent
, rootLayersId
, inputBlockId
);
1121 mAPZEventState
->ProcessTouchEvent(*touchEvent
, targetGuid
, inputBlockId
,
1122 aApzResult
.GetStatus(), status
,
1123 std::move(allowedTouchBehaviors
));
1124 } else if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1125 MOZ_ASSERT(wheelEvent
->mFlags
.mHandledByAPZ
);
1126 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1127 this, GetDocument(), *original
->AsWheelEvent(), rootLayersId
,
1129 if (wheelEvent
->mCanTriggerSwipe
) {
1130 ReportSwipeStarted(inputBlockId
, wheelEvent
->TriggersSwipe());
1132 mAPZEventState
->ProcessWheelEvent(*wheelEvent
, inputBlockId
);
1133 } else if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1134 MOZ_ASSERT(mouseEvent
->mFlags
.mHandledByAPZ
);
1135 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1136 this, GetDocument(), *original
->AsMouseEvent(), rootLayersId
,
1138 mAPZEventState
->ProcessMouseEvent(*mouseEvent
, inputBlockId
);
1140 if (postLayerization
) {
1141 postLayerization
->Register();
1148 template <class InputType
, class EventType
>
1149 class DispatchEventOnMainThread
: public Runnable
{
1151 DispatchEventOnMainThread(const InputType
& aInput
, nsBaseWidget
* aWidget
,
1152 const APZEventResult
& aAPZResult
)
1153 : mozilla::Runnable("DispatchEventOnMainThread"),
1156 mAPZResult(aAPZResult
) {}
1158 NS_IMETHOD
Run() override
{
1159 EventType event
= mInput
.ToWidgetEvent(mWidget
);
1160 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1166 nsBaseWidget
* mWidget
;
1167 APZEventResult mAPZResult
;
1170 template <class InputType
, class EventType
>
1171 class DispatchInputOnControllerThread
: public Runnable
{
1173 DispatchInputOnControllerThread(const EventType
& aEvent
,
1174 IAPZCTreeManager
* aAPZC
,
1175 nsBaseWidget
* aWidget
)
1176 : mozilla::Runnable("DispatchInputOnControllerThread"),
1177 mMainMessageLoop(MessageLoop::current()),
1182 NS_IMETHOD
Run() override
{
1183 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(mInput
);
1184 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1187 RefPtr
<Runnable
> r
= new DispatchEventOnMainThread
<InputType
, EventType
>(
1188 mInput
, mWidget
, result
);
1189 mMainMessageLoop
->PostTask(r
.forget());
1194 MessageLoop
* mMainMessageLoop
;
1196 RefPtr
<IAPZCTreeManager
> mAPZC
;
1197 nsBaseWidget
* mWidget
;
1200 void nsBaseWidget::DispatchTouchInput(MultiTouchInput
& aInput
,
1201 uint16_t aInputSource
) {
1202 MOZ_ASSERT(NS_IsMainThread());
1203 MOZ_ASSERT(aInputSource
==
1204 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH
||
1205 aInputSource
== mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN
);
1207 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1209 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1210 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1214 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1215 ProcessUntransformedAPZEvent(&event
, result
);
1217 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1219 nsEventStatus status
;
1220 DispatchEvent(&event
, status
);
1224 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput
& aInput
) {
1225 MOZ_ASSERT(NS_IsMainThread());
1227 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1229 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1230 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1234 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1235 ProcessUntransformedAPZEvent(&event
, result
);
1237 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1238 nsEventStatus status
;
1239 DispatchEvent(&event
, status
);
1243 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput
& aInput
) {
1244 MOZ_ASSERT(NS_IsMainThread());
1246 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1247 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1249 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1252 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1253 ProcessUntransformedAPZEvent(&event
, result
);
1255 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1256 nsEventStatus status
;
1257 DispatchEvent(&event
, status
);
1261 nsIWidget::ContentAndAPZEventStatus
nsBaseWidget::DispatchInputEvent(
1262 WidgetInputEvent
* aEvent
) {
1263 nsIWidget::ContentAndAPZEventStatus status
;
1264 MOZ_ASSERT(NS_IsMainThread());
1266 if (APZThreadUtils::IsControllerThread()) {
1267 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1268 status
.mApzStatus
= result
.GetStatus();
1269 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1272 status
.mContentStatus
= ProcessUntransformedAPZEvent(aEvent
, result
);
1275 if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1276 RefPtr
<Runnable
> r
=
1277 new DispatchInputOnControllerThread
<ScrollWheelInput
,
1278 WidgetWheelEvent
>(*wheelEvent
,
1280 APZThreadUtils::RunOnControllerThread(std::move(r
));
1281 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1284 if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1285 RefPtr
<Runnable
> r
=
1286 new DispatchInputOnControllerThread
<MouseInput
, WidgetMouseEvent
>(
1287 *mouseEvent
, mAPZC
, this);
1288 APZThreadUtils::RunOnControllerThread(std::move(r
));
1289 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1292 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1293 RefPtr
<Runnable
> r
=
1294 new DispatchInputOnControllerThread
<MultiTouchInput
,
1295 WidgetTouchEvent
>(*touchEvent
,
1297 APZThreadUtils::RunOnControllerThread(std::move(r
));
1298 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1301 // Allow dispatching keyboard events on Gecko thread.
1302 MOZ_ASSERT(aEvent
->AsKeyboardEvent());
1305 DispatchEvent(aEvent
, status
.mContentStatus
);
1309 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent
* aEvent
) {
1310 MOZ_ASSERT(NS_IsMainThread());
1312 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1313 mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1317 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent
& event
) {
1318 nsEventStatus status
;
1319 DispatchEvent(&event
, status
);
1320 return ConvertStatus(status
);
1323 Document
* nsBaseWidget::GetDocument() const {
1324 if (mWidgetListener
) {
1325 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1326 return presShell
->GetDocument();
1332 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1333 // Parent directly listens to the vsync source whereas
1334 // child process communicate via IPC
1335 // Should be called AFTER gfxPlatform is initialized
1336 if (XRE_IsParentProcess()) {
1337 if (!mCompositorVsyncDispatcherLock
) {
1338 mCompositorVsyncDispatcherLock
=
1339 MakeUnique
<Mutex
>("mCompositorVsyncDispatcherLock");
1341 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1342 if (!mCompositorVsyncDispatcher
) {
1343 RefPtr
<VsyncDispatcher
> vsyncDispatcher
=
1344 gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
1345 mCompositorVsyncDispatcher
=
1346 new CompositorVsyncDispatcher(std::move(vsyncDispatcher
));
1351 already_AddRefed
<CompositorVsyncDispatcher
>
1352 nsBaseWidget::GetCompositorVsyncDispatcher() {
1353 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
1355 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1356 RefPtr
<CompositorVsyncDispatcher
> dispatcher
= mCompositorVsyncDispatcher
;
1357 return dispatcher
.forget();
1360 already_AddRefed
<WebRenderLayerManager
> nsBaseWidget::CreateCompositorSession(
1361 int aWidth
, int aHeight
, CompositorOptions
* aOptionsOut
) {
1362 MOZ_ASSERT(aOptionsOut
);
1365 CreateCompositorVsyncDispatcher();
1367 gfx::GPUProcessManager
* gpu
= gfx::GPUProcessManager::Get();
1368 // Make sure GPU process is ready for use.
1369 // If it failed to connect to GPU process, GPU process usage is disabled in
1370 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1371 nsresult rv
= gpu
->EnsureGPUReady();
1372 if (NS_WARN_IF(rv
== NS_ERROR_ILLEGAL_DURING_SHUTDOWN
)) {
1376 // If widget type does not supports acceleration, we may be allowed to use
1377 // software WebRender instead.
1378 bool supportsAcceleration
= WidgetTypeSupportsAcceleration();
1379 bool enableSWWR
= true;
1380 if (supportsAcceleration
||
1381 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1382 enableSWWR
= gfx::gfxVars::UseSoftwareWebRender();
1384 bool enableAPZ
= UseAPZ();
1385 CompositorOptions
options(enableAPZ
, enableSWWR
);
1388 if (supportsAcceleration
) {
1389 options
.SetAllowSoftwareWebRenderD3D11(
1390 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1392 if (mNeedFastSnaphot
) {
1393 options
.SetNeedFastSnaphot(true);
1395 #elif defined(MOZ_WIDGET_ANDROID)
1396 MOZ_ASSERT(supportsAcceleration
);
1397 options
.SetAllowSoftwareWebRenderOGL(
1398 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1399 #elif defined(MOZ_WIDGET_GTK)
1400 if (supportsAcceleration
) {
1401 options
.SetAllowSoftwareWebRenderOGL(
1402 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1406 #ifdef MOZ_WIDGET_ANDROID
1407 // Unconditionally set the compositor as initially paused, as we have not
1408 // yet had a chance to send the compositor surface to the GPU process. We
1409 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1410 // where we will also resume the compositor if required.
1411 options
.SetInitiallyPaused(true);
1413 options
.SetInitiallyPaused(CompositorInitiallyPaused());
1416 RefPtr
<WebRenderLayerManager
> lm
= new WebRenderLayerManager(this);
1418 uint64_t innerWindowId
= 0;
1419 if (Document
* doc
= GetDocument()) {
1420 innerWindowId
= doc
->InnerWindowID();
1424 mCompositorSession
= gpu
->CreateTopLevelCompositor(
1425 this, lm
, GetDefaultScale(), options
, UseExternalCompositingSurface(),
1426 gfx::IntSize(aWidth
, aHeight
), innerWindowId
, &retry
);
1428 if (mCompositorSession
) {
1429 TextureFactoryIdentifier textureFactoryIdentifier
;
1431 lm
->Initialize(mCompositorSession
->GetCompositorBridgeChild(),
1432 wr::AsPipelineId(mCompositorSession
->RootLayerTreeId()),
1433 &textureFactoryIdentifier
, error
);
1434 if (textureFactoryIdentifier
.mParentBackend
!= LayersBackend::LAYERS_WR
) {
1436 DestroyCompositor();
1437 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1438 gfx::GPUProcessManager::Get()->DisableWebRender(
1439 wr::WebRenderError::INITIALIZE
, error
);
1443 // We need to retry in a loop because the act of failing to create the
1444 // compositor can change our state (e.g. disable WebRender).
1445 if (mCompositorSession
|| !retry
) {
1446 *aOptionsOut
= options
;
1452 void nsBaseWidget::CreateCompositor(int aWidth
, int aHeight
) {
1453 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1454 gfxPlatform::GetPlatform();
1456 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1457 "This function assumes OMTC");
1459 MOZ_ASSERT(!mCompositorSession
&& !mCompositorBridgeChild
,
1460 "Should have properly cleaned up the previous PCompositor pair "
1463 if (mCompositorBridgeChild
) {
1464 mCompositorBridgeChild
->Destroy();
1467 // Recreating this is tricky, as we may still have an old and we need
1468 // to make sure it's properly destroyed by calling DestroyCompositor!
1470 // If we've already received a shutdown notification, don't try
1471 // create a new compositor.
1472 if (!mShutdownObserver
) {
1476 // The controller thread must be configured before the compositor
1477 // session is created, so that the input bridge runs on the right
1479 ConfigureAPZControllerThread();
1481 CompositorOptions options
;
1482 RefPtr
<WebRenderLayerManager
> lm
=
1483 CreateCompositorSession(aWidth
, aHeight
, &options
);
1488 MOZ_ASSERT(mCompositorSession
);
1489 mCompositorBridgeChild
= mCompositorSession
->GetCompositorBridgeChild();
1490 SetCompositorWidgetDelegate(
1491 mCompositorSession
->GetCompositorWidgetDelegate());
1493 if (options
.UseAPZ()) {
1494 mAPZC
= mCompositorSession
->GetAPZCTreeManager();
1495 ConfigureAPZCTreeManager();
1500 if (mInitialZoomConstraints
) {
1501 UpdateZoomConstraints(mInitialZoomConstraints
->mPresShellID
,
1502 mInitialZoomConstraints
->mViewID
,
1503 Some(mInitialZoomConstraints
->mConstraints
));
1504 mInitialZoomConstraints
.reset();
1507 TextureFactoryIdentifier textureFactoryIdentifier
=
1508 lm
->GetTextureFactoryIdentifier();
1509 MOZ_ASSERT(textureFactoryIdentifier
.mParentBackend
==
1510 LayersBackend::LAYERS_WR
);
1511 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier
);
1512 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier
);
1516 mWindowRenderer
= std::move(lm
);
1518 // Only track compositors for top-level windows, since other window types
1519 // may use the basic compositor. Except on the OS X - see bug 1306383
1520 #if defined(XP_MACOSX)
1521 bool getCompositorFromThisWindow
= true;
1523 bool getCompositorFromThisWindow
= mWindowType
== WindowType::TopLevel
;
1526 if (getCompositorFromThisWindow
) {
1527 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1528 mWindowRenderer
->GetCompositorBackendType());
1532 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession
* aSession
) {
1533 MOZ_ASSERT(aSession
== mCompositorSession
);
1534 DestroyLayerManager();
1537 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1538 return gfxPlatform::UsesOffMainThreadCompositing();
1541 WindowRenderer
* nsBaseWidget::GetWindowRenderer() {
1542 if (!mWindowRenderer
) {
1543 if (!mShutdownObserver
) {
1544 // We are shutting down, do not try to re-create a LayerManager
1547 // Try to use an async compositor first, if possible
1548 if (ShouldUseOffMainThreadCompositing()) {
1552 if (!mWindowRenderer
) {
1553 mWindowRenderer
= CreateFallbackRenderer();
1556 return mWindowRenderer
;
1559 WindowRenderer
* nsBaseWidget::CreateFallbackRenderer() {
1560 return new FallbackRenderer
;
1563 CompositorBridgeChild
* nsBaseWidget::GetRemoteRenderer() {
1564 return mCompositorBridgeChild
;
1567 void nsBaseWidget::ClearCachedWebrenderResources() {
1568 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1571 mWindowRenderer
->AsWebRender()->ClearCachedResources();
1574 void nsBaseWidget::ClearWebrenderAnimationResources() {
1575 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1578 mWindowRenderer
->AsWebRender()->ClearAnimationResources();
1581 bool nsBaseWidget::SetNeedFastSnaphot() {
1582 MOZ_ASSERT(XRE_IsParentProcess());
1583 MOZ_ASSERT(!mCompositorSession
);
1585 if (!XRE_IsParentProcess() || mCompositorSession
) {
1589 mNeedFastSnaphot
= true;
1593 already_AddRefed
<gfx::DrawTarget
> nsBaseWidget::StartRemoteDrawing() {
1597 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA
; }
1599 //-------------------------------------------------------------------------
1601 // Destroy the window
1603 //-------------------------------------------------------------------------
1604 void nsBaseWidget::OnDestroy() {
1605 if (mTextEventDispatcher
) {
1606 mTextEventDispatcher
->OnDestroyWidget();
1607 // Don't release it until this widget actually released because after this
1608 // is called, TextEventDispatcher() may create it again.
1611 // If this widget is being destroyed, let the APZ code know to drop references
1612 // to this widget. Callers of this function all should be holding a deathgrip
1613 // on this widget already.
1614 ReleaseContentController();
1617 void nsBaseWidget::MoveClient(const DesktopPoint
& aOffset
) {
1618 LayoutDeviceIntPoint
clientOffset(GetClientOffset());
1620 // GetClientOffset returns device pixels; scale back to desktop pixels
1621 // if that's what this widget uses for the Move/Resize APIs
1622 if (BoundsUseDesktopPixels()) {
1623 DesktopPoint desktopOffset
= clientOffset
/ GetDesktopToDeviceScale();
1624 Move(aOffset
.x
- desktopOffset
.x
, aOffset
.y
- desktopOffset
.y
);
1626 LayoutDevicePoint layoutOffset
= aOffset
* GetDesktopToDeviceScale();
1627 Move(layoutOffset
.x
- LayoutDeviceCoord(clientOffset
.x
),
1628 layoutOffset
.y
- LayoutDeviceCoord(clientOffset
.y
));
1632 void nsBaseWidget::ResizeClient(const DesktopSize
& aSize
, bool aRepaint
) {
1633 NS_ASSERTION((aSize
.width
>= 0), "Negative width passed to ResizeClient");
1634 NS_ASSERTION((aSize
.height
>= 0), "Negative height passed to ResizeClient");
1636 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1638 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1639 // if that's what this widget uses for the Move/Resize APIs
1640 if (BoundsUseDesktopPixels()) {
1641 DesktopSize desktopDelta
=
1642 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1643 clientBounds
.Size()) /
1644 GetDesktopToDeviceScale();
1645 Resize(aSize
.width
+ desktopDelta
.width
, aSize
.height
+ desktopDelta
.height
,
1648 LayoutDeviceSize layoutSize
= aSize
* GetDesktopToDeviceScale();
1649 Resize(mBounds
.Width() + (layoutSize
.width
- clientBounds
.Width()),
1650 mBounds
.Height() + (layoutSize
.height
- clientBounds
.Height()),
1655 void nsBaseWidget::ResizeClient(const DesktopRect
& aRect
, bool aRepaint
) {
1656 NS_ASSERTION((aRect
.Width() >= 0), "Negative width passed to ResizeClient");
1657 NS_ASSERTION((aRect
.Height() >= 0), "Negative height passed to ResizeClient");
1659 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1660 LayoutDeviceIntPoint clientOffset
= GetClientOffset();
1661 DesktopToLayoutDeviceScale scale
= GetDesktopToDeviceScale();
1663 if (BoundsUseDesktopPixels()) {
1664 DesktopPoint desktopOffset
= clientOffset
/ scale
;
1665 DesktopSize desktopDelta
=
1666 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1667 clientBounds
.Size()) /
1669 Resize(aRect
.X() - desktopOffset
.x
, aRect
.Y() - desktopOffset
.y
,
1670 aRect
.Width() + desktopDelta
.width
,
1671 aRect
.Height() + desktopDelta
.height
, aRepaint
);
1673 LayoutDeviceRect layoutRect
= aRect
* scale
;
1674 Resize(layoutRect
.X() - clientOffset
.x
, layoutRect
.Y() - clientOffset
.y
,
1675 layoutRect
.Width() + mBounds
.Width() - clientBounds
.Width(),
1676 layoutRect
.Height() + mBounds
.Height() - clientBounds
.Height(),
1681 //-------------------------------------------------------------------------
1685 //-------------------------------------------------------------------------
1688 * If the implementation of nsWindow supports borders this method MUST be
1692 LayoutDeviceIntRect
nsBaseWidget::GetClientBounds() { return GetBounds(); }
1695 * If the implementation of nsWindow supports borders this method MUST be
1699 LayoutDeviceIntRect
nsBaseWidget::GetBounds() { return mBounds
; }
1702 * If the implementation of nsWindow uses a local coordinate system within the
1703 *window, this method must be overridden
1706 LayoutDeviceIntRect
nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1708 nsresult
nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect
& aRect
) {
1709 if (SizeMode() != nsSizeMode_Normal
) {
1710 return NS_ERROR_FAILURE
;
1712 aRect
= GetScreenBounds();
1716 LayoutDeviceIntPoint
nsBaseWidget::GetClientOffset() {
1717 return LayoutDeviceIntPoint(0, 0);
1720 nsresult
nsBaseWidget::SetNonClientMargins(const LayoutDeviceIntMargin
&) {
1721 return NS_ERROR_NOT_IMPLEMENTED
;
1724 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin
) {}
1726 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1728 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1730 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect
* aResizerRect
) {
1735 * Modifies aFile to point at an icon file with the given name and suffix. The
1736 * suffix may correspond to a file extension with leading '.' if appropriate.
1737 * Returns true if the icon file exists and can be read.
1739 static bool ResolveIconNameHelper(nsIFile
* aFile
, const nsAString
& aIconName
,
1740 const nsAString
& aIconSuffix
) {
1741 aFile
->Append(u
"icons"_ns
);
1742 aFile
->Append(u
"default"_ns
);
1743 aFile
->Append(aIconName
+ aIconSuffix
);
1746 return NS_SUCCEEDED(aFile
->IsReadable(&readable
)) && readable
;
1750 * Resolve the given icon name into a local file object. This method is
1751 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1752 * platform specific icon file suffix (e.g., ".ico" under Win32).
1754 * If no file is found matching the given parameters, then null is returned.
1756 void nsBaseWidget::ResolveIconName(const nsAString
& aIconName
,
1757 const nsAString
& aIconSuffix
,
1758 nsIFile
** aResult
) {
1761 nsCOMPtr
<nsIProperties
> dirSvc
=
1762 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID
);
1763 if (!dirSvc
) return;
1765 // first check auxilary chrome directories
1767 nsCOMPtr
<nsISimpleEnumerator
> dirs
;
1768 dirSvc
->Get(NS_APP_CHROME_DIR_LIST
, NS_GET_IID(nsISimpleEnumerator
),
1769 getter_AddRefs(dirs
));
1772 while (NS_SUCCEEDED(dirs
->HasMoreElements(&hasMore
)) && hasMore
) {
1773 nsCOMPtr
<nsISupports
> element
;
1774 dirs
->GetNext(getter_AddRefs(element
));
1775 if (!element
) continue;
1776 nsCOMPtr
<nsIFile
> file
= do_QueryInterface(element
);
1777 if (!file
) continue;
1778 if (ResolveIconNameHelper(file
, aIconName
, aIconSuffix
)) {
1779 NS_ADDREF(*aResult
= file
);
1785 // then check the main app chrome directory
1787 nsCOMPtr
<nsIFile
> file
;
1788 dirSvc
->Get(NS_APP_CHROME_DIR
, NS_GET_IID(nsIFile
), getter_AddRefs(file
));
1789 if (file
&& ResolveIconNameHelper(file
, aIconName
, aIconSuffix
))
1790 NS_ADDREF(*aResult
= file
);
1793 void nsBaseWidget::SetSizeConstraints(const SizeConstraints
& aConstraints
) {
1794 mSizeConstraints
= aConstraints
;
1796 // Popups are constrained during layout, and we don't want to synchronously
1797 // paint from reflow, so bail out... This is not great, but it's no worse than
1798 // what we used to do.
1800 // The right fix here is probably making constraint changes go through the
1801 // view manager and such.
1802 if (mWindowType
== WindowType::Popup
) {
1806 // If the current size doesn't meet the new constraints, trigger a
1807 // resize to apply it. Note that, we don't want to invoke Resize if
1808 // the new constraints don't affect the current size, because Resize
1809 // implementation on some platforms may touch other geometry even if
1810 // the size don't need to change.
1811 LayoutDeviceIntSize curSize
= mBounds
.Size();
1812 LayoutDeviceIntSize clampedSize
=
1813 Max(aConstraints
.mMinSize
, Min(aConstraints
.mMaxSize
, curSize
));
1814 if (clampedSize
!= curSize
) {
1816 if (BoundsUseDesktopPixels()) {
1817 DesktopSize desktopSize
= clampedSize
/ GetDesktopToDeviceScale();
1818 size
= desktopSize
.ToUnknownSize();
1820 size
= gfx::Size(clampedSize
.ToUnknownSize());
1822 Resize(size
.width
, size
.height
, true);
1826 const widget::SizeConstraints
nsBaseWidget::GetSizeConstraints() {
1827 return mSizeConstraints
;
1831 nsIRollupListener
* nsBaseWidget::GetActiveRollupListener() {
1832 // TODO: Simplify this.
1833 return nsXULPopupManager::GetInstance();
1836 void nsBaseWidget::NotifyWindowDestroyed() {
1837 if (!mWidgetListener
) return;
1839 nsCOMPtr
<nsIAppWindow
> window
= mWidgetListener
->GetAppWindow();
1840 nsCOMPtr
<nsIBaseWindow
> appWindow(do_QueryInterface(window
));
1842 appWindow
->Destroy();
1846 void nsBaseWidget::NotifyWindowMoved(int32_t aX
, int32_t aY
,
1847 ByMoveToRect aByMoveToRect
) {
1848 if (mWidgetListener
) {
1849 mWidgetListener
->WindowMoved(this, aX
, aY
, aByMoveToRect
);
1852 if (mIMEHasFocus
&& IMENotificationRequestsRef().WantPositionChanged()) {
1853 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE
));
1857 void nsBaseWidget::NotifySizeMoveDone() {
1858 if (!mWidgetListener
) {
1861 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1862 presShell
->WindowSizeMoveDone();
1866 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind
) {
1867 LookAndFeel::NotifyChangedAllWindows(aKind
);
1870 nsresult
nsBaseWidget::NotifyIME(const IMENotification
& aIMENotification
) {
1874 switch (aIMENotification
.mMessage
) {
1875 case REQUEST_TO_COMMIT_COMPOSITION
:
1876 case REQUEST_TO_CANCEL_COMPOSITION
:
1877 // We should send request to IME only when there is a TextEventDispatcher
1878 // instance (this means that this widget has dispatched at least one
1879 // composition event or keyboard event) and the it has composition.
1880 // Otherwise, there is nothing to do.
1881 // Note that if current input transaction is for native input events,
1882 // TextEventDispatcher::NotifyIME() will call
1883 // TextEventDispatcherListener::NotifyIME().
1884 if (mTextEventDispatcher
&& mTextEventDispatcher
->IsComposing()) {
1885 return mTextEventDispatcher
->NotifyIME(aIMENotification
);
1889 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_FOCUS
) {
1890 mIMEHasFocus
= true;
1892 EnsureTextEventDispatcher();
1893 // TextEventDispatcher::NotifyIME() will always call
1894 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1895 // input transaction is for synthesized events for automated tests,
1896 // notifications will be sent to native IME.
1897 nsresult rv
= mTextEventDispatcher
->NotifyIME(aIMENotification
);
1898 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_BLUR
) {
1899 mIMEHasFocus
= false;
1906 void nsBaseWidget::EnsureTextEventDispatcher() {
1907 if (mTextEventDispatcher
) {
1910 mTextEventDispatcher
= new TextEventDispatcher(this);
1913 nsIWidget::NativeIMEContext
nsBaseWidget::GetNativeIMEContext() {
1914 if (mTextEventDispatcher
&& mTextEventDispatcher
->GetPseudoIMEContext()) {
1915 // If we already have a TextEventDispatcher and it's working with
1916 // a TextInputProcessor, we need to return pseudo IME context since
1917 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1918 // on the pseudo IME context in such case.
1919 NativeIMEContext pseudoIMEContext
;
1920 pseudoIMEContext
.InitWithRawNativeIMEContext(
1921 mTextEventDispatcher
->GetPseudoIMEContext());
1922 return pseudoIMEContext
;
1924 return NativeIMEContext(this);
1927 nsIWidget::TextEventDispatcher
* nsBaseWidget::GetTextEventDispatcher() {
1928 EnsureTextEventDispatcher();
1929 return mTextEventDispatcher
;
1932 void* nsBaseWidget::GetPseudoIMEContext() {
1933 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
1937 return dispatcher
->GetPseudoIMEContext();
1940 TextEventDispatcherListener
*
1941 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1942 // TODO: If all platforms supported use of TextEventDispatcher for handling
1943 // native IME and keyboard events, this method should be removed since
1944 // in such case, this is overridden by all the subclasses.
1948 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId
,
1949 const ScrollableLayerGuid::ViewID
& aViewId
,
1950 const CSSRect
& aRect
, const uint32_t& aFlags
) {
1951 if (!mCompositorSession
|| !mAPZC
) {
1954 LayersId layerId
= mCompositorSession
->RootLayerTreeId();
1955 mAPZC
->ZoomToRect(ScrollableLayerGuid(layerId
, aPresShellId
, aViewId
),
1956 ZoomTarget
{aRect
}, aFlags
);
1959 #ifdef ACCESSIBILITY
1961 a11y::LocalAccessible
* nsBaseWidget::GetRootAccessible() {
1962 NS_ENSURE_TRUE(mWidgetListener
, nullptr);
1964 PresShell
* presShell
= mWidgetListener
->GetPresShell();
1965 NS_ENSURE_TRUE(presShell
, nullptr);
1967 // If container is null then the presshell is not active. This often happens
1968 // when a preshell is being held onto for fastback.
1969 nsPresContext
* presContext
= presShell
->GetPresContext();
1970 NS_ENSURE_TRUE(presContext
->GetContainerWeak(), nullptr);
1972 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1973 // make sure it's not created at unsafe times.
1974 nsAccessibilityService
* accService
= GetOrCreateAccService();
1976 return accService
->GetRootDocumentAccessible(
1977 presShell
, nsContentUtils::IsSafeToRunScript());
1983 #endif // ACCESSIBILITY
1985 void nsBaseWidget::StartAsyncScrollbarDrag(
1986 const AsyncDragMetrics
& aDragMetrics
) {
1987 if (!AsyncPanZoomEnabled()) {
1991 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession
);
1993 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1994 ScrollableLayerGuid
guid(layersId
, aDragMetrics
.mPresShellId
,
1995 aDragMetrics
.mViewId
);
1997 mAPZC
->StartScrollbarDrag(guid
, aDragMetrics
);
2000 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint
& aAnchorLocation
,
2001 const ScrollableLayerGuid
& aGuid
) {
2002 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2004 return mAPZC
->StartAutoscroll(aGuid
, aAnchorLocation
);
2007 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid
& aGuid
) {
2008 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2010 mAPZC
->StopAutoscroll(aGuid
);
2013 LayersId
nsBaseWidget::GetRootLayerTreeId() {
2014 return mCompositorSession
? mCompositorSession
->RootLayerTreeId()
2018 already_AddRefed
<widget::Screen
> nsBaseWidget::GetWidgetScreen() {
2019 ScreenManager
& screenManager
= ScreenManager::GetSingleton();
2020 LayoutDeviceIntRect bounds
= GetScreenBounds();
2021 DesktopIntRect deskBounds
= RoundedToInt(bounds
/ GetDesktopToDeviceScale());
2022 return screenManager
.ScreenForRect(deskBounds
);
2025 mozilla::DesktopToLayoutDeviceScale
2026 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
2027 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
2028 ->GetDesktopToDeviceScale();
2031 nsresult
nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint
,
2033 nsIObserver
* aObserver
) {
2034 AutoObserverNotifier
notifier(aObserver
, "touchtap");
2036 if (sPointerIdCounter
> TOUCH_INJECT_MAX_POINTS
) {
2037 sPointerIdCounter
= 0;
2039 int pointerId
= sPointerIdCounter
;
2040 sPointerIdCounter
++;
2041 nsresult rv
= SynthesizeNativeTouchPoint(pointerId
, TOUCH_CONTACT
, aPoint
,
2043 if (NS_FAILED(rv
)) {
2048 return SynthesizeNativeTouchPoint(pointerId
, TOUCH_REMOVE
, aPoint
, 0, 0,
2052 // initiate a long tap
2053 int elapse
= Preferences::GetInt("ui.click_hold_context_menus.delay",
2054 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC
);
2055 if (!mLongTapTimer
) {
2056 mLongTapTimer
= NS_NewTimer();
2057 if (!mLongTapTimer
) {
2058 SynthesizeNativeTouchPoint(pointerId
, TOUCH_CANCEL
, aPoint
, 0, 0,
2060 return NS_ERROR_UNEXPECTED
;
2062 // Windows requires recuring events, so we set this to a smaller window
2063 // than the pref value.
2064 int timeout
= elapse
;
2065 if (timeout
> TOUCH_INJECT_PUMP_TIMER_MSEC
) {
2066 timeout
= TOUCH_INJECT_PUMP_TIMER_MSEC
;
2068 mLongTapTimer
->InitWithNamedFuncCallback(
2069 OnLongTapTimerCallback
, this, timeout
, nsITimer::TYPE_REPEATING_SLACK
,
2070 "nsIWidget::SynthesizeNativeTouchTap");
2073 // If we already have a long tap pending, cancel it. We only allow one long
2074 // tap to be active at a time.
2075 if (mLongTapTouchPoint
) {
2076 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2077 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2080 mLongTapTouchPoint
= MakeUnique
<LongTapInfo
>(
2081 pointerId
, aPoint
, TimeDuration::FromMilliseconds(elapse
), aObserver
);
2082 notifier
.SkipNotification(); // we'll do it in the long-tap callback
2087 void nsIWidget::OnLongTapTimerCallback(nsITimer
* aTimer
, void* aClosure
) {
2088 auto* self
= static_cast<nsIWidget
*>(aClosure
);
2090 if ((self
->mLongTapTouchPoint
->mStamp
+ self
->mLongTapTouchPoint
->mDuration
) >
2093 // Windows needs us to keep pumping feedback to the digitizer, so update
2094 // the pointer id with the same position.
2095 self
->SynthesizeNativeTouchPoint(
2096 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_CONTACT
,
2097 self
->mLongTapTouchPoint
->mPosition
, 1.0, 90, nullptr);
2102 AutoObserverNotifier
notifier(self
->mLongTapTouchPoint
->mObserver
,
2105 // finished, remove the touch point
2106 self
->mLongTapTimer
->Cancel();
2107 self
->mLongTapTimer
= nullptr;
2108 self
->SynthesizeNativeTouchPoint(
2109 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_REMOVE
,
2110 self
->mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2111 self
->mLongTapTouchPoint
= nullptr;
2114 float nsIWidget::GetFallbackDPI() {
2115 RefPtr
<const Screen
> primaryScreen
=
2116 ScreenManager::GetSingleton().GetPrimaryScreen();
2117 return primaryScreen
->GetDPI();
2120 CSSToLayoutDeviceScale
nsIWidget::GetFallbackDefaultScale() {
2121 RefPtr
<const Screen
> s
= ScreenManager::GetSingleton().GetPrimaryScreen();
2122 return s
->GetCSSToLayoutDeviceScale(Screen::IncludeOSZoom::No
);
2125 nsresult
nsIWidget::ClearNativeTouchSequence(nsIObserver
* aObserver
) {
2126 AutoObserverNotifier
notifier(aObserver
, "cleartouch");
2128 // XXX This is odd. This is called by the constructor of nsIWidget. However,
2129 // at that point, nsIWidget::mLongTapTimer must be nullptr. Therefore,
2130 // this must do nothing at initializing the instance.
2131 if (!mLongTapTimer
) {
2134 mLongTapTimer
->Cancel();
2135 mLongTapTimer
= nullptr;
2136 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2137 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2138 mLongTapTouchPoint
= nullptr;
2142 MultiTouchInput
nsBaseWidget::UpdateSynthesizedTouchState(
2143 MultiTouchInput
* aState
, mozilla::TimeStamp aTimeStamp
, uint32_t aPointerId
,
2144 TouchPointerState aPointerState
, LayoutDeviceIntPoint aPoint
,
2145 double aPointerPressure
, uint32_t aPointerOrientation
) {
2146 ScreenIntPoint pointerScreenPoint
= ViewAs
<ScreenPixel
>(
2147 aPoint
, PixelCastJustification::LayoutDeviceIsScreenForBounds
);
2149 // We can't dispatch *aState directly because (a) dispatching
2150 // it might inadvertently modify it and (b) in the case of touchend or
2151 // touchcancel events aState will hold the touches that are
2152 // still down whereas the input dispatched needs to hold the removed
2153 // touch(es). We use |inputToDispatch| for this purpose.
2154 MultiTouchInput inputToDispatch
;
2155 inputToDispatch
.mInputType
= MULTITOUCH_INPUT
;
2156 inputToDispatch
.mTimeStamp
= aTimeStamp
;
2158 int32_t index
= aState
->IndexOfTouch((int32_t)aPointerId
);
2159 if (aPointerState
== TOUCH_CONTACT
) {
2161 // found an existing touch point, update it
2162 SingleTouchData
& point
= aState
->mTouches
[index
];
2163 point
.mScreenPoint
= pointerScreenPoint
;
2164 point
.mRotationAngle
= (float)aPointerOrientation
;
2165 point
.mForce
= (float)aPointerPressure
;
2166 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_MOVE
;
2168 // new touch point, add it
2169 aState
->mTouches
.AppendElement(SingleTouchData(
2170 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2171 (float)aPointerOrientation
, (float)aPointerPressure
));
2172 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_START
;
2174 inputToDispatch
.mTouches
= aState
->mTouches
;
2176 MOZ_ASSERT(aPointerState
== TOUCH_REMOVE
|| aPointerState
== TOUCH_CANCEL
);
2177 // a touch point is being lifted, so remove it from the stored list
2179 aState
->mTouches
.RemoveElementAt(index
);
2181 inputToDispatch
.mType
=
2182 (aPointerState
== TOUCH_REMOVE
? MultiTouchInput::MULTITOUCH_END
2183 : MultiTouchInput::MULTITOUCH_CANCEL
);
2184 inputToDispatch
.mTouches
.AppendElement(SingleTouchData(
2185 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2186 (float)aPointerOrientation
, (float)aPointerPressure
));
2189 return inputToDispatch
;
2192 void nsBaseWidget::NotifyLiveResizeStarted() {
2193 // If we have mLiveResizeListeners already non-empty, we should notify those
2194 // listeners that the resize stopped before starting anew. In theory this
2195 // should never happen because we shouldn't get nested live resize actions.
2196 NotifyLiveResizeStopped();
2197 MOZ_ASSERT(mLiveResizeListeners
.IsEmpty());
2199 // If we can get the active remote tab for the current widget, suppress
2200 // the displayport on it during the live resize.
2201 if (!mWidgetListener
) {
2204 nsCOMPtr
<nsIAppWindow
> appWindow
= mWidgetListener
->GetAppWindow();
2208 mLiveResizeListeners
= appWindow
->GetLiveResizeListeners();
2209 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2210 mLiveResizeListeners
[i
]->LiveResizeStarted();
2214 void nsBaseWidget::NotifyLiveResizeStopped() {
2215 if (!mLiveResizeListeners
.IsEmpty()) {
2216 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2217 mLiveResizeListeners
[i
]->LiveResizeStopped();
2219 mLiveResizeListeners
.Clear();
2223 nsresult
nsBaseWidget::AsyncEnableDragDrop(bool aEnable
) {
2224 RefPtr
<nsBaseWidget
> kungFuDeathGrip
= this;
2225 return NS_DispatchToCurrentThreadQueue(
2226 NS_NewRunnableFunction(
2227 "AsyncEnableDragDropFn",
2228 [this, aEnable
, kungFuDeathGrip
]() { EnableDragDrop(aEnable
); }),
2229 kAsyncDragDropTimeout
, EventQueuePriority::Idle
);
2232 void nsBaseWidget::SwipeFinished() {
2233 if (mSwipeTracker
) {
2234 mSwipeTracker
->Destroy();
2235 mSwipeTracker
= nullptr;
2239 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId
,
2241 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== aInputBlockId
) {
2243 PanGestureInput
& startEvent
= mSwipeEventQueue
->queuedEvents
[0];
2244 TrackScrollEventAsSwipe(startEvent
, mSwipeEventQueue
->allowedDirections
,
2246 for (size_t i
= 1; i
< mSwipeEventQueue
->queuedEvents
.Length(); i
++) {
2247 mSwipeTracker
->ProcessEvent(mSwipeEventQueue
->queuedEvents
[i
]);
2250 // If the event wasn't start swipe, we need to notify it to APZ.
2251 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2252 BrowserGestureResponse::NotConsumed
);
2254 mSwipeEventQueue
= nullptr;
2258 void nsBaseWidget::TrackScrollEventAsSwipe(
2259 const mozilla::PanGestureInput
& aSwipeStartEvent
,
2260 uint32_t aAllowedDirections
, uint64_t aInputBlockId
) {
2261 // If a swipe is currently being tracked kill it -- it's been interrupted
2262 // by another gesture event.
2263 if (mSwipeTracker
) {
2264 mSwipeTracker
->CancelSwipe(aSwipeStartEvent
.mTimeStamp
);
2265 mSwipeTracker
->Destroy();
2266 mSwipeTracker
= nullptr;
2269 uint32_t direction
=
2270 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2271 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2272 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2275 new SwipeTracker(*this, aSwipeStartEvent
, aAllowedDirections
, direction
);
2278 mCurrentPanGestureBelongsToSwipe
= true;
2280 // Now SwipeTracker has started consuming pan events, notify it to APZ so
2281 // that APZ can discard queued events.
2282 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2283 BrowserGestureResponse::Consumed
);
2287 nsBaseWidget::SwipeInfo
nsBaseWidget::SendMayStartSwipe(
2288 const mozilla::PanGestureInput
& aSwipeStartEvent
) {
2289 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
2291 uint32_t direction
=
2292 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2293 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2294 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2296 // We're ready to start the animation. Tell Gecko about it, and at the same
2297 // time ask it if it really wants to start an animation for this event.
2298 // This event also reports back the directions that we can swipe in.
2299 LayoutDeviceIntPoint position
= RoundedToInt(aSwipeStartEvent
.mPanStartPoint
*
2300 ScreenToLayoutDeviceScale(1));
2301 WidgetSimpleGestureEvent geckoEvent
= SwipeTracker::CreateSwipeGestureEvent(
2302 eSwipeGestureMayStart
, this, position
, aSwipeStartEvent
.mTimeStamp
);
2303 geckoEvent
.mDirection
= direction
;
2304 geckoEvent
.mDelta
= 0.0;
2305 geckoEvent
.mAllowedDirections
= 0;
2306 bool shouldStartSwipe
=
2307 DispatchWindowEvent(geckoEvent
); // event cancelled == swipe should start
2309 SwipeInfo result
= {shouldStartSwipe
, geckoEvent
.mAllowedDirections
};
2313 WidgetWheelEvent
nsBaseWidget::MayStartSwipeForAPZ(
2314 const PanGestureInput
& aPanInput
, const APZEventResult
& aApzResult
) {
2315 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2317 // Ignore swipe-to-navigation in PiP window.
2322 if (aPanInput
.AllowsSwipe()) {
2323 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2324 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2325 if (swipeInfo
.wantsSwipe
) {
2326 if (aApzResult
.GetStatus() == nsEventStatus_eIgnore
) {
2327 // APZ has determined and that scrolling horizontally in the
2328 // requested direction is impossible, so it didn't do any
2329 // scrolling for the event.
2330 // We know now that MayStartSwipe wants a swipe, so we can start
2332 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
,
2333 aApzResult
.mInputBlockId
);
2334 } else if (!aApzResult
.GetHandledResult() ||
2335 !aApzResult
.GetHandledResult()->IsHandledByRoot()) {
2336 // We don't know whether this event can start a swipe, so we need
2337 // to queue up events and wait for a call to ReportSwipeStarted.
2338 // APZ might already have started scrolling in response to the
2339 // event if it knew that it's the right thing to do. In that case
2340 // we'll still get a call to ReportSwipeStarted, and we will
2341 // discard the queued events at that point.
2342 mSwipeEventQueue
= MakeUnique
<SwipeEventQueue
>(
2343 swipeInfo
.allowedDirections
, aApzResult
.mInputBlockId
);
2346 // Inform that the browser gesture didn't use the pan event (pan-start
2347 // precisely), so that APZ can now start using the event for
2348 // scrolling/overscrolling.
2349 mAPZC
->SetBrowserGestureResponse(aApzResult
.mInputBlockId
,
2350 BrowserGestureResponse::NotConsumed
);
2354 if (mSwipeEventQueue
&&
2355 mSwipeEventQueue
->inputBlockId
== aApzResult
.mInputBlockId
) {
2356 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2362 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput
& aPanInput
) {
2363 // Ignore swipe-to-navigation in PiP window.
2368 if (aPanInput
.mType
== PanGestureInput::PANGESTURE_MAYSTART
||
2369 aPanInput
.mType
== PanGestureInput::PANGESTURE_START
) {
2370 mCurrentPanGestureBelongsToSwipe
= false;
2372 if (mCurrentPanGestureBelongsToSwipe
) {
2373 // Ignore this event. It's a momentum event from a scroll gesture
2374 // that was processed as a swipe, and the swipe animation has
2375 // already finished (so mSwipeTracker is already null).
2376 MOZ_ASSERT(aPanInput
.IsMomentum(),
2377 "If the fingers are still on the touchpad, we should still have "
2379 "and it should have consumed this event.");
2383 if (!aPanInput
.MayTriggerSwipe()) {
2387 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2389 // We're in the non-APZ case here, but we still want to know whether
2390 // the event was routed to a child process, so we use InputAPZContext
2391 // to get that piece of information.
2392 ScrollableLayerGuid guid
;
2393 uint64_t blockId
= 0;
2394 InputAPZContext
context(guid
, blockId
, nsEventStatus_eIgnore
);
2396 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2397 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2398 nsEventStatus status
;
2399 DispatchEvent(&event
, status
);
2400 if (swipeInfo
.wantsSwipe
) {
2401 if (context
.WasRoutedToChildProcess()) {
2402 // We don't know whether this event can start a swipe, so we need
2403 // to queue up events and wait for a call to ReportSwipeStarted.
2405 MakeUnique
<SwipeEventQueue
>(swipeInfo
.allowedDirections
, blockId
);
2406 } else if (event
.TriggersSwipe()) {
2407 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
, blockId
);
2411 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== 0) {
2412 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2418 const IMENotificationRequests
& nsIWidget::IMENotificationRequestsRef() {
2419 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
2420 return dispatcher
->IMENotificationRequestsRef();
2423 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent
* aEvent
) {}
2425 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType
,
2426 const WidgetKeyboardEvent
& aEvent
,
2427 nsTArray
<CommandInt
>& aCommands
) {
2428 MOZ_ASSERT(aEvent
.IsTrusted());
2429 MOZ_ASSERT(aCommands
.IsEmpty());
2433 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboard() {
2434 if (XRE_IsContentProcess()) {
2435 return CreateBidiKeyboardContentProcess();
2437 return CreateBidiKeyboardInner();
2441 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboardInner() {
2442 // no bidi keyboard implementation
2447 namespace mozilla::widget
{
2449 const char* ToChar(InputContext::Origin aOrigin
) {
2451 case InputContext::ORIGIN_MAIN
:
2452 return "ORIGIN_MAIN";
2453 case InputContext::ORIGIN_CONTENT
:
2454 return "ORIGIN_CONTENT";
2456 return "Unexpected value";
2460 const char* ToChar(IMEMessage aIMEMessage
) {
2461 switch (aIMEMessage
) {
2462 case NOTIFY_IME_OF_NOTHING
:
2463 return "NOTIFY_IME_OF_NOTHING";
2464 case NOTIFY_IME_OF_FOCUS
:
2465 return "NOTIFY_IME_OF_FOCUS";
2466 case NOTIFY_IME_OF_BLUR
:
2467 return "NOTIFY_IME_OF_BLUR";
2468 case NOTIFY_IME_OF_SELECTION_CHANGE
:
2469 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2470 case NOTIFY_IME_OF_TEXT_CHANGE
:
2471 return "NOTIFY_IME_OF_TEXT_CHANGE";
2472 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED
:
2473 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2474 case NOTIFY_IME_OF_POSITION_CHANGE
:
2475 return "NOTIFY_IME_OF_POSITION_CHANGE";
2476 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT
:
2477 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2478 case REQUEST_TO_COMMIT_COMPOSITION
:
2479 return "REQUEST_TO_COMMIT_COMPOSITION";
2480 case REQUEST_TO_CANCEL_COMPOSITION
:
2481 return "REQUEST_TO_CANCEL_COMPOSITION";
2483 return "Unexpected value";
2487 void NativeIMEContext::Init(nsIWidget
* aWidget
) {
2489 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2490 mOriginProcessID
= static_cast<uint64_t>(-1);
2493 if (!XRE_IsContentProcess()) {
2494 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(
2495 aWidget
->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT
));
2496 mOriginProcessID
= 0;
2499 // If this is created in a child process, aWidget is an instance of
2500 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2501 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2502 // native IME context of the parent process.
2503 *this = aWidget
->GetNativeIMEContext();
2506 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext
) {
2507 if (NS_WARN_IF(!aRawNativeIMEContext
)) {
2508 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2509 mOriginProcessID
= static_cast<uint64_t>(-1);
2512 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(aRawNativeIMEContext
);
2514 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2517 void IMENotification::TextChangeDataBase::MergeWith(
2518 const IMENotification::TextChangeDataBase
& aOther
) {
2519 MOZ_ASSERT(aOther
.IsValid(), "Merging data must store valid data");
2520 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mRemovedEndOffset
,
2521 "end of removed text must be same or larger than start");
2522 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mAddedEndOffset
,
2523 "end of added text must be same or larger than start");
2530 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2531 // text ranges. I.e., mStartOffset should be the smallest offset of all
2532 // modified text ranges in old text. |mRemovedEndOffset| should be the
2533 // largest end offset in old text of all modified text ranges.
2534 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2535 // I.e., only this is an offset in new text.
2536 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2537 // premodified text was already removed. And some text whose length is
2538 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2539 // this allows IME to mark dirty the modified text range with |mStartOffset|
2540 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2541 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2542 // Additionally, IME can retrieve only the text between |mStartOffset| and
2543 // |mAddedEndOffset| for updating stored text.
2545 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2546 // should be adjusted to be in same text. The |newData.mStartOffset| and
2547 // |newData.mRemovedEndOffset| should be computed as in old text because
2548 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2549 // in the old text but even if some text before the values of the newData
2550 // has already been modified, the values don't include the changes.
2552 // For comparing new and old |mAddedEndOffset| values, they should be
2553 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2554 // computed as in the new text because |mAddedEndOffset| indicates the end
2555 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2556 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2558 const TextChangeDataBase
& newData
= aOther
;
2559 const TextChangeDataBase oldData
= *this;
2561 // mCausedOnlyByComposition should be true only when all changes are caused
2563 mCausedOnlyByComposition
=
2564 newData
.mCausedOnlyByComposition
&& oldData
.mCausedOnlyByComposition
;
2566 // mIncludingChangesWithoutComposition should be true if at least one of
2567 // merged changes occurred without composition.
2568 mIncludingChangesWithoutComposition
=
2569 newData
.mIncludingChangesWithoutComposition
||
2570 oldData
.mIncludingChangesWithoutComposition
;
2572 // mIncludingChangesDuringComposition should be true when at least one of
2573 // the merged non-composition changes occurred during the latest composition.
2574 if (!newData
.mCausedOnlyByComposition
&&
2575 !newData
.mIncludingChangesDuringComposition
) {
2576 MOZ_ASSERT(newData
.mIncludingChangesWithoutComposition
);
2577 MOZ_ASSERT(mIncludingChangesWithoutComposition
);
2578 // If new change is neither caused by composition nor occurred during
2579 // composition, set mIncludingChangesDuringComposition to false because
2580 // IME doesn't want outdated text changes as text change during current
2582 mIncludingChangesDuringComposition
= false;
2584 // Otherwise, set mIncludingChangesDuringComposition to true if either
2585 // oldData or newData includes changes during composition.
2586 mIncludingChangesDuringComposition
=
2587 newData
.mIncludingChangesDuringComposition
||
2588 oldData
.mIncludingChangesDuringComposition
;
2591 if (newData
.mStartOffset
>= oldData
.mAddedEndOffset
) {
2593 // If new start is after old end offset of added text, it means that text
2594 // after the modified range is modified. Like:
2595 // added range of old change: +----------+
2596 // removed range of new change: +----------+
2597 // So, the old start offset is always the smaller offset.
2598 mStartOffset
= oldData
.mStartOffset
;
2599 // The new end offset of removed text is moved by the old change and we
2600 // need to cancel the move of the old change for comparing the offsets in
2601 // same text because it doesn't make sensce to compare offsets in different
2603 uint32_t newRemovedEndOffsetInOldText
=
2604 newData
.mRemovedEndOffset
- oldData
.Difference();
2606 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2607 // The new end offset of added text is always the larger offset.
2608 mAddedEndOffset
= newData
.mAddedEndOffset
;
2612 if (newData
.mStartOffset
>= oldData
.mStartOffset
) {
2613 // If new start is in the modified range, it means that new data changes
2614 // a part or all of the range.
2615 mStartOffset
= oldData
.mStartOffset
;
2616 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2618 // If new end of removed text is greater than old end of added text, it
2619 // means that all or a part of modified range modified again and text
2620 // after the modified range is also modified. Like:
2621 // added range of old change: +----------+
2622 // removed range of new change: +----------+
2623 // So, the new removed end offset is moved by the old change and we need
2624 // to cancel the move of the old change for comparing the offsets in the
2625 // same text because it doesn't make sense to compare the offsets in
2627 uint32_t newRemovedEndOffsetInOldText
=
2628 newData
.mRemovedEndOffset
- oldData
.Difference();
2630 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2631 // The old end of added text is replaced by new change. So, it should be
2632 // same as the new start. On the other hand, the new added end offset is
2633 // always same or larger. Therefore, the merged end offset of added
2634 // text should be the new end offset of added text.
2635 mAddedEndOffset
= newData
.mAddedEndOffset
;
2640 // If new end of removed text is less than old end of added text, it means
2641 // that only a part of the modified range is modified again. Like:
2642 // added range of old change: +------------+
2643 // removed range of new change: +-----+
2644 // So, the new end offset of removed text should be same as the old end
2645 // offset of removed text. Therefore, the merged end offset of removed
2646 // text should be the old text change's |mRemovedEndOffset|.
2647 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2648 // The old end of added text is moved by new change. So, we need to cancel
2649 // the move of the new change for comparing the offsets in same text.
2650 uint32_t oldAddedEndOffsetInNewText
=
2651 oldData
.mAddedEndOffset
+ newData
.Difference();
2653 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2657 if (newData
.mRemovedEndOffset
>= oldData
.mStartOffset
) {
2658 // If new end of removed text is greater than old start (and new start is
2659 // less than old start), it means that a part of modified range is modified
2660 // again and some new text before the modified range is also modified.
2661 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2662 "new start offset should be less than old one here");
2663 mStartOffset
= newData
.mStartOffset
;
2664 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2666 // If new end of removed text is greater than old end of added text, it
2667 // means that all modified text and text after the modified range is
2669 // added range of old change: +----------+
2670 // removed range of new change: +------------------+
2671 // So, the new end of removed text is moved by the old change. Therefore,
2672 // we need to cancel the move of the old change for comparing the offsets
2673 // in same text because it doesn't make sense to compare the offsets in
2675 uint32_t newRemovedEndOffsetInOldText
=
2676 newData
.mRemovedEndOffset
- oldData
.Difference();
2678 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2679 // The old end of added text is replaced by new change. So, the old end
2680 // offset of added text is same as new text change's start offset. Then,
2681 // new change's end offset of added text is always same or larger than
2682 // it. Therefore, merged end offset of added text is always the new end
2683 // offset of added text.
2684 mAddedEndOffset
= newData
.mAddedEndOffset
;
2689 // If new end of removed text is less than old end of added text, it
2690 // means that only a part of the modified range is modified again. Like:
2691 // added range of old change: +----------+
2692 // removed range of new change: +----------+
2693 // So, the new end of removed text should be same as old end of removed
2694 // text for preventing end of removed text to be modified. Therefore,
2695 // merged end offset of removed text is always the old end offset of removed
2697 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2698 // The old end of added text is moved by this change. So, we need to
2699 // cancel the move of the new change for comparing the offsets in same text
2700 // because it doesn't make sense to compare the offsets in different text.
2701 uint32_t oldAddedEndOffsetInNewText
=
2702 oldData
.mAddedEndOffset
+ newData
.Difference();
2704 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2709 // Otherwise, i.e., both new end of added text and new start are less than
2710 // old start, text before the modified range is modified. Like:
2711 // added range of old change: +----------+
2712 // removed range of new change: +----------+
2713 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2714 "new start offset should be less than old one here");
2715 mStartOffset
= newData
.mStartOffset
;
2716 MOZ_ASSERT(newData
.mRemovedEndOffset
< oldData
.mRemovedEndOffset
,
2717 "new removed end offset should be less than old one here");
2718 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2719 // The end of added text should be adjusted with the new difference.
2720 uint32_t oldAddedEndOffsetInNewText
=
2721 oldData
.mAddedEndOffset
+ newData
.Difference();
2723 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2728 // Let's test the code of merging multiple text change data in debug build
2729 // and crash if one of them fails because this feature is very complex but
2730 // cannot be tested with mochitest.
2731 void IMENotification::TextChangeDataBase::Test() {
2732 static bool gTestTextChangeEvent
= true;
2733 if (!gTestTextChangeEvent
) {
2736 gTestTextChangeEvent
= false;
2738 /****************************************************************************
2740 ****************************************************************************/
2743 MergeWith(TextChangeData(10, 10, 20, false, false));
2744 MergeWith(TextChangeData(20, 20, 35, false, false));
2745 MOZ_ASSERT(mStartOffset
== 10,
2746 "Test 1-1-1: mStartOffset should be the first offset");
2748 mRemovedEndOffset
== 10, // 20 - (20 - 10)
2749 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2751 mAddedEndOffset
== 35,
2752 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2755 // Removing text (longer line -> shorter line)
2756 MergeWith(TextChangeData(10, 20, 10, false, false));
2757 MergeWith(TextChangeData(10, 30, 10, false, false));
2758 MOZ_ASSERT(mStartOffset
== 10,
2759 "Test 1-2-1: mStartOffset should be the first offset");
2760 MOZ_ASSERT(mRemovedEndOffset
== 40, // 30 + (10 - 20)
2761 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2763 "with already removed length");
2765 mAddedEndOffset
== 10,
2766 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2769 // Removing text (shorter line -> longer line)
2770 MergeWith(TextChangeData(10, 20, 10, false, false));
2771 MergeWith(TextChangeData(10, 15, 10, false, false));
2772 MOZ_ASSERT(mStartOffset
== 10,
2773 "Test 1-3-1: mStartOffset should be the first offset");
2774 MOZ_ASSERT(mRemovedEndOffset
== 25, // 15 + (10 - 20)
2775 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2777 "with already removed length");
2779 mAddedEndOffset
== 10,
2780 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2783 // Appending text at different point (not sure if actually occurs)
2784 MergeWith(TextChangeData(10, 10, 20, false, false));
2785 MergeWith(TextChangeData(55, 55, 60, false, false));
2786 MOZ_ASSERT(mStartOffset
== 10,
2787 "Test 1-4-1: mStartOffset should be the smallest offset");
2789 mRemovedEndOffset
== 45, // 55 - (10 - 20)
2790 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2791 "text without already added length");
2793 mAddedEndOffset
== 60,
2794 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2797 // Removing text at different point (not sure if actually occurs)
2798 MergeWith(TextChangeData(10, 20, 10, false, false));
2799 MergeWith(TextChangeData(55, 68, 55, false, false));
2800 MOZ_ASSERT(mStartOffset
== 10,
2801 "Test 1-5-1: mStartOffset should be the smallest offset");
2803 mRemovedEndOffset
== 78, // 68 - (10 - 20)
2804 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2805 "text with already removed length");
2807 mAddedEndOffset
== 55,
2808 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2811 // Replacing text and append text (becomes longer)
2812 MergeWith(TextChangeData(30, 35, 32, false, false));
2813 MergeWith(TextChangeData(32, 32, 40, false, false));
2814 MOZ_ASSERT(mStartOffset
== 30,
2815 "Test 1-6-1: mStartOffset should be the smallest offset");
2817 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2818 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2821 mAddedEndOffset
== 40,
2822 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2825 // Replacing text and append text (becomes shorter)
2826 MergeWith(TextChangeData(30, 35, 32, false, false));
2827 MergeWith(TextChangeData(32, 32, 33, false, false));
2828 MOZ_ASSERT(mStartOffset
== 30,
2829 "Test 1-7-1: mStartOffset should be the smallest offset");
2831 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2832 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2835 mAddedEndOffset
== 33,
2836 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2839 // Removing text and replacing text after first range (not sure if actually
2841 MergeWith(TextChangeData(30, 35, 30, false, false));
2842 MergeWith(TextChangeData(32, 34, 48, false, false));
2843 MOZ_ASSERT(mStartOffset
== 30,
2844 "Test 1-8-1: mStartOffset should be the smallest offset");
2845 MOZ_ASSERT(mRemovedEndOffset
== 39, // 34 - (30 - 35)
2846 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2848 "without already removed text");
2850 mAddedEndOffset
== 48,
2851 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2854 // Removing text and replacing text after first range (not sure if actually
2856 MergeWith(TextChangeData(30, 35, 30, false, false));
2857 MergeWith(TextChangeData(32, 38, 36, false, false));
2858 MOZ_ASSERT(mStartOffset
== 30,
2859 "Test 1-9-1: mStartOffset should be the smallest offset");
2860 MOZ_ASSERT(mRemovedEndOffset
== 43, // 38 - (30 - 35)
2861 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2863 "without already removed text");
2865 mAddedEndOffset
== 36,
2866 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2869 /****************************************************************************
2871 ****************************************************************************/
2873 // Replacing text in around end of added text (becomes shorter) (not sure
2874 // if actually occurs)
2875 MergeWith(TextChangeData(50, 50, 55, false, false));
2876 MergeWith(TextChangeData(53, 60, 54, false, false));
2877 MOZ_ASSERT(mStartOffset
== 50,
2878 "Test 2-1-1: mStartOffset should be the smallest offset");
2879 MOZ_ASSERT(mRemovedEndOffset
== 55, // 60 - (55 - 50)
2880 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2882 "without already added text length");
2884 mAddedEndOffset
== 54,
2885 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2888 // Replacing text around end of added text (becomes longer) (not sure
2889 // if actually occurs)
2890 MergeWith(TextChangeData(50, 50, 55, false, false));
2891 MergeWith(TextChangeData(54, 62, 68, false, false));
2892 MOZ_ASSERT(mStartOffset
== 50,
2893 "Test 2-2-1: mStartOffset should be the smallest offset");
2894 MOZ_ASSERT(mRemovedEndOffset
== 57, // 62 - (55 - 50)
2895 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2897 "without already added text length");
2899 mAddedEndOffset
== 68,
2900 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2903 // Replacing text around end of replaced text (became shorter) (not sure if
2905 MergeWith(TextChangeData(36, 48, 45, false, false));
2906 MergeWith(TextChangeData(43, 50, 49, false, false));
2907 MOZ_ASSERT(mStartOffset
== 36,
2908 "Test 2-3-1: mStartOffset should be the smallest offset");
2909 MOZ_ASSERT(mRemovedEndOffset
== 53, // 50 - (45 - 48)
2910 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2912 "without already removed text length");
2914 mAddedEndOffset
== 49,
2915 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2918 // Replacing text around end of replaced text (became longer) (not sure if
2920 MergeWith(TextChangeData(36, 52, 53, false, false));
2921 MergeWith(TextChangeData(43, 68, 61, false, false));
2922 MOZ_ASSERT(mStartOffset
== 36,
2923 "Test 2-4-1: mStartOffset should be the smallest offset");
2924 MOZ_ASSERT(mRemovedEndOffset
== 67, // 68 - (53 - 52)
2925 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2927 "without already added text length");
2929 mAddedEndOffset
== 61,
2930 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2933 /****************************************************************************
2935 ****************************************************************************/
2937 // Appending text in already added text (not sure if actually occurs)
2938 MergeWith(TextChangeData(10, 10, 20, false, false));
2939 MergeWith(TextChangeData(15, 15, 30, false, false));
2940 MOZ_ASSERT(mStartOffset
== 10,
2941 "Test 3-1-1: mStartOffset should be the smallest offset");
2942 MOZ_ASSERT(mRemovedEndOffset
== 10,
2943 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2946 mAddedEndOffset
== 35, // 20 + (30 - 15)
2947 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2948 "added text length by the new change");
2951 // Replacing text in added text (not sure if actually occurs)
2952 MergeWith(TextChangeData(50, 50, 55, false, false));
2953 MergeWith(TextChangeData(52, 53, 56, false, false));
2954 MOZ_ASSERT(mStartOffset
== 50,
2955 "Test 3-2-1: mStartOffset should be the smallest offset");
2956 MOZ_ASSERT(mRemovedEndOffset
== 50,
2957 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2960 mAddedEndOffset
== 58, // 55 + (56 - 53)
2961 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2962 "added text length by the new change");
2965 // Replacing text in replaced text (became shorter) (not sure if actually
2967 MergeWith(TextChangeData(36, 48, 45, false, false));
2968 MergeWith(TextChangeData(37, 38, 50, false, false));
2969 MOZ_ASSERT(mStartOffset
== 36,
2970 "Test 3-3-1: mStartOffset should be the smallest offset");
2971 MOZ_ASSERT(mRemovedEndOffset
== 48,
2972 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2975 mAddedEndOffset
== 57, // 45 + (50 - 38)
2976 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2977 "added text length by the new change");
2980 // Replacing text in replaced text (became longer) (not sure if actually
2982 MergeWith(TextChangeData(32, 48, 53, false, false));
2983 MergeWith(TextChangeData(43, 50, 52, false, false));
2984 MOZ_ASSERT(mStartOffset
== 32,
2985 "Test 3-4-1: mStartOffset should be the smallest offset");
2986 MOZ_ASSERT(mRemovedEndOffset
== 48,
2987 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2989 "without already added text length");
2991 mAddedEndOffset
== 55, // 53 + (52 - 50)
2992 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2993 "added text length by the new change");
2996 // Replacing text in replaced text (became shorter) (not sure if actually
2998 MergeWith(TextChangeData(36, 48, 50, false, false));
2999 MergeWith(TextChangeData(37, 49, 47, false, false));
3000 MOZ_ASSERT(mStartOffset
== 36,
3001 "Test 3-5-1: mStartOffset should be the smallest offset");
3003 mRemovedEndOffset
== 48,
3004 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
3006 MOZ_ASSERT(mAddedEndOffset
== 48, // 50 + (47 - 49)
3007 "Test 3-5-3: mAddedEndOffset should be the first end of added "
3009 "removed text length by the new change");
3012 // Replacing text in replaced text (became longer) (not sure if actually
3014 MergeWith(TextChangeData(32, 48, 53, false, false));
3015 MergeWith(TextChangeData(43, 50, 47, false, false));
3016 MOZ_ASSERT(mStartOffset
== 32,
3017 "Test 3-6-1: mStartOffset should be the smallest offset");
3018 MOZ_ASSERT(mRemovedEndOffset
== 48,
3019 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
3021 "without already added text length");
3022 MOZ_ASSERT(mAddedEndOffset
== 50, // 53 + (47 - 50)
3023 "Test 3-6-3: mAddedEndOffset should be the first end of added "
3025 "removed text length by the new change");
3028 /****************************************************************************
3030 ****************************************************************************/
3032 // Replacing text all of already append text (not sure if actually occurs)
3033 MergeWith(TextChangeData(50, 50, 55, false, false));
3034 MergeWith(TextChangeData(44, 66, 68, false, false));
3035 MOZ_ASSERT(mStartOffset
== 44,
3036 "Test 4-1-1: mStartOffset should be the smallest offset");
3037 MOZ_ASSERT(mRemovedEndOffset
== 61, // 66 - (55 - 50)
3038 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
3040 "without already added text length");
3042 mAddedEndOffset
== 68,
3043 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3046 // Replacing text around a point in which text was removed (not sure if
3048 MergeWith(TextChangeData(50, 62, 50, false, false));
3049 MergeWith(TextChangeData(44, 66, 68, false, false));
3050 MOZ_ASSERT(mStartOffset
== 44,
3051 "Test 4-2-1: mStartOffset should be the smallest offset");
3052 MOZ_ASSERT(mRemovedEndOffset
== 78, // 66 - (50 - 62)
3053 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
3055 "without already removed text length");
3057 mAddedEndOffset
== 68,
3058 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3061 // Replacing text all replaced text (became shorter) (not sure if actually
3063 MergeWith(TextChangeData(50, 62, 60, false, false));
3064 MergeWith(TextChangeData(49, 128, 130, false, false));
3065 MOZ_ASSERT(mStartOffset
== 49,
3066 "Test 4-3-1: mStartOffset should be the smallest offset");
3067 MOZ_ASSERT(mRemovedEndOffset
== 130, // 128 - (60 - 62)
3068 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
3070 "without already removed text length");
3072 mAddedEndOffset
== 130,
3073 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3076 // Replacing text all replaced text (became longer) (not sure if actually
3078 MergeWith(TextChangeData(50, 61, 73, false, false));
3079 MergeWith(TextChangeData(44, 100, 50, false, false));
3080 MOZ_ASSERT(mStartOffset
== 44,
3081 "Test 4-4-1: mStartOffset should be the smallest offset");
3082 MOZ_ASSERT(mRemovedEndOffset
== 88, // 100 - (73 - 61)
3083 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
3085 "with already added text length");
3087 mAddedEndOffset
== 50,
3088 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3091 /****************************************************************************
3093 ****************************************************************************/
3095 // Replacing text around start of added text (not sure if actually occurs)
3096 MergeWith(TextChangeData(50, 50, 55, false, false));
3097 MergeWith(TextChangeData(48, 52, 49, false, false));
3098 MOZ_ASSERT(mStartOffset
== 48,
3099 "Test 5-1-1: mStartOffset should be the smallest offset");
3101 mRemovedEndOffset
== 50,
3102 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
3105 mAddedEndOffset
== 52, // 55 + (52 - 49)
3106 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
3107 "added text length by the new change");
3110 // Replacing text around start of replaced text (became shorter) (not sure if
3112 MergeWith(TextChangeData(50, 60, 58, false, false));
3113 MergeWith(TextChangeData(43, 50, 48, false, false));
3114 MOZ_ASSERT(mStartOffset
== 43,
3115 "Test 5-2-1: mStartOffset should be the smallest offset");
3117 mRemovedEndOffset
== 60,
3118 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3120 MOZ_ASSERT(mAddedEndOffset
== 56, // 58 + (48 - 50)
3121 "Test 5-2-3: mAddedEndOffset should be the first end of added "
3123 "removed text length by the new change");
3126 // Replacing text around start of replaced text (became longer) (not sure if
3128 MergeWith(TextChangeData(50, 60, 68, false, false));
3129 MergeWith(TextChangeData(43, 55, 53, false, false));
3130 MOZ_ASSERT(mStartOffset
== 43,
3131 "Test 5-3-1: mStartOffset should be the smallest offset");
3133 mRemovedEndOffset
== 60,
3134 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3136 MOZ_ASSERT(mAddedEndOffset
== 66, // 68 + (53 - 55)
3137 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3139 "removed text length by the new change");
3142 // Replacing text around start of replaced text (became shorter) (not sure if
3144 MergeWith(TextChangeData(50, 60, 58, false, false));
3145 MergeWith(TextChangeData(43, 50, 128, false, false));
3146 MOZ_ASSERT(mStartOffset
== 43,
3147 "Test 5-4-1: mStartOffset should be the smallest offset");
3149 mRemovedEndOffset
== 60,
3150 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
3153 mAddedEndOffset
== 136, // 58 + (128 - 50)
3154 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
3155 "added text length by the new change");
3158 // Replacing text around start of replaced text (became longer) (not sure if
3160 MergeWith(TextChangeData(50, 60, 68, false, false));
3161 MergeWith(TextChangeData(43, 55, 65, false, false));
3162 MOZ_ASSERT(mStartOffset
== 43,
3163 "Test 5-5-1: mStartOffset should be the smallest offset");
3165 mRemovedEndOffset
== 60,
3166 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
3169 mAddedEndOffset
== 78, // 68 + (65 - 55)
3170 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
3171 "added text length by the new change");
3174 /****************************************************************************
3176 ****************************************************************************/
3178 // Appending text before already added text (not sure if actually occurs)
3179 MergeWith(TextChangeData(30, 30, 45, false, false));
3180 MergeWith(TextChangeData(10, 10, 20, false, false));
3181 MOZ_ASSERT(mStartOffset
== 10,
3182 "Test 6-1-1: mStartOffset should be the smallest offset");
3184 mRemovedEndOffset
== 30,
3185 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3188 mAddedEndOffset
== 55, // 45 + (20 - 10)
3189 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3190 "added text length by the new change");
3193 // Removing text before already removed text (not sure if actually occurs)
3194 MergeWith(TextChangeData(30, 35, 30, false, false));
3195 MergeWith(TextChangeData(10, 25, 10, false, false));
3196 MOZ_ASSERT(mStartOffset
== 10,
3197 "Test 6-2-1: mStartOffset should be the smallest offset");
3199 mRemovedEndOffset
== 35,
3200 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3203 mAddedEndOffset
== 15, // 30 - (25 - 10)
3204 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3205 "removed text length by the new change");
3208 // Replacing text before already replaced text (not sure if actually occurs)
3209 MergeWith(TextChangeData(50, 65, 70, false, false));
3210 MergeWith(TextChangeData(13, 24, 15, false, false));
3211 MOZ_ASSERT(mStartOffset
== 13,
3212 "Test 6-3-1: mStartOffset should be the smallest offset");
3214 mRemovedEndOffset
== 65,
3215 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3217 MOZ_ASSERT(mAddedEndOffset
== 61, // 70 + (15 - 24)
3218 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3220 "removed text length by the new change");
3223 // Replacing text before already replaced text (not sure if actually occurs)
3224 MergeWith(TextChangeData(50, 65, 70, false, false));
3225 MergeWith(TextChangeData(13, 24, 36, false, false));
3226 MOZ_ASSERT(mStartOffset
== 13,
3227 "Test 6-4-1: mStartOffset should be the smallest offset");
3229 mRemovedEndOffset
== 65,
3230 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3232 MOZ_ASSERT(mAddedEndOffset
== 82, // 70 + (36 - 24)
3233 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3235 "removed text length by the new change");
3239 #endif // #ifdef DEBUG
3241 } // namespace mozilla::widget
3244 //////////////////////////////////////////////////////////////
3246 // Convert a GUI event message code to a string.
3247 // Makes it a lot easier to debug events.
3249 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3250 // for a DebugPrintEvent() function that uses
3253 //////////////////////////////////////////////////////////////
3255 nsAutoString
nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent
* aGuiEvent
) {
3256 NS_ASSERTION(nullptr != aGuiEvent
, "cmon, null gui event.");
3258 nsAutoString
eventName(u
"UNKNOWN"_ns
);
3260 # define _ASSIGN_eventName(_value, _name) \
3262 eventName.AssignLiteral(_name); \
3265 switch (aGuiEvent
->mMessage
) {
3266 _ASSIGN_eventName(eBlur
, "eBlur");
3267 _ASSIGN_eventName(eDrop
, "eDrop");
3268 _ASSIGN_eventName(eDragEnter
, "eDragEnter");
3269 _ASSIGN_eventName(eDragExit
, "eDragExit");
3270 _ASSIGN_eventName(eDragOver
, "eDragOver");
3271 _ASSIGN_eventName(eEditorInput
, "eEditorInput");
3272 _ASSIGN_eventName(eFocus
, "eFocus");
3273 _ASSIGN_eventName(eFocusIn
, "eFocusIn");
3274 _ASSIGN_eventName(eFocusOut
, "eFocusOut");
3275 _ASSIGN_eventName(eFormSelect
, "eFormSelect");
3276 _ASSIGN_eventName(eFormChange
, "eFormChange");
3277 _ASSIGN_eventName(eFormReset
, "eFormReset");
3278 _ASSIGN_eventName(eFormSubmit
, "eFormSubmit");
3279 _ASSIGN_eventName(eImageAbort
, "eImageAbort");
3280 _ASSIGN_eventName(eLoadError
, "eLoadError");
3281 _ASSIGN_eventName(eKeyDown
, "eKeyDown");
3282 _ASSIGN_eventName(eKeyPress
, "eKeyPress");
3283 _ASSIGN_eventName(eKeyUp
, "eKeyUp");
3284 _ASSIGN_eventName(eMouseEnterIntoWidget
, "eMouseEnterIntoWidget");
3285 _ASSIGN_eventName(eMouseExitFromWidget
, "eMouseExitFromWidget");
3286 _ASSIGN_eventName(eMouseDown
, "eMouseDown");
3287 _ASSIGN_eventName(eMouseUp
, "eMouseUp");
3288 _ASSIGN_eventName(eMouseClick
, "eMouseClick");
3289 _ASSIGN_eventName(eMouseAuxClick
, "eMouseAuxClick");
3290 _ASSIGN_eventName(eMouseDoubleClick
, "eMouseDoubleClick");
3291 _ASSIGN_eventName(eMouseMove
, "eMouseMove");
3292 _ASSIGN_eventName(eLoad
, "eLoad");
3293 _ASSIGN_eventName(ePopState
, "ePopState");
3294 _ASSIGN_eventName(eBeforeScriptExecute
, "eBeforeScriptExecute");
3295 _ASSIGN_eventName(eAfterScriptExecute
, "eAfterScriptExecute");
3296 _ASSIGN_eventName(eUnload
, "eUnload");
3297 _ASSIGN_eventName(eHashChange
, "eHashChange");
3298 _ASSIGN_eventName(eReadyStateChange
, "eReadyStateChange");
3299 _ASSIGN_eventName(eXULBroadcast
, "eXULBroadcast");
3300 _ASSIGN_eventName(eXULCommandUpdate
, "eXULCommandUpdate");
3302 # undef _ASSIGN_eventName
3305 eventName
.AssignLiteral("UNKNOWN: ");
3306 eventName
.AppendInt(aGuiEvent
->mMessage
);
3310 return nsAutoString(eventName
);
3312 //////////////////////////////////////////////////////////////
3314 // Code to deal with paint and event debug prefs.
3316 //////////////////////////////////////////////////////////////
3322 static PrefPair debug_PrefValues
[] = {
3323 {"nglayout.debug.crossing_event_dumping", false},
3324 {"nglayout.debug.event_dumping", false},
3325 {"nglayout.debug.invalidate_dumping", false},
3326 {"nglayout.debug.motion_event_dumping", false},
3327 {"nglayout.debug.paint_dumping", false}};
3329 //////////////////////////////////////////////////////////////
3330 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName
) {
3331 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3333 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3334 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3335 return debug_PrefValues
[i
].value
;
3341 //////////////////////////////////////////////////////////////
3342 static void debug_SetCachedBoolPref(const char* aPrefName
, bool aValue
) {
3343 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3345 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3346 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3347 debug_PrefValues
[i
].value
= aValue
;
3353 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3356 //////////////////////////////////////////////////////////////
3357 class Debug_PrefObserver final
: public nsIObserver
{
3358 ~Debug_PrefObserver() = default;
3365 NS_IMPL_ISUPPORTS(Debug_PrefObserver
, nsIObserver
)
3368 Debug_PrefObserver::Observe(nsISupports
* subject
, const char* topic
,
3369 const char16_t
* data
) {
3370 NS_ConvertUTF16toUTF8
prefName(data
);
3372 bool value
= Preferences::GetBool(prefName
.get(), false);
3373 debug_SetCachedBoolPref(prefName
.get(), value
);
3377 //////////////////////////////////////////////////////////////
3378 /* static */ void debug_RegisterPrefCallbacks() {
3379 static bool once
= true;
3387 nsCOMPtr
<nsIObserver
> obs(new Debug_PrefObserver());
3388 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3389 // Initialize the pref values
3390 debug_PrefValues
[i
].value
=
3391 Preferences::GetBool(debug_PrefValues
[i
].name
, false);
3394 // Register callbacks for when these change
3396 name
.AssignLiteral(debug_PrefValues
[i
].name
,
3397 strlen(debug_PrefValues
[i
].name
));
3398 Preferences::AddStrongObserver(obs
, name
);
3402 //////////////////////////////////////////////////////////////
3403 static int32_t _GetPrintCount() {
3404 static int32_t sCount
= 0;
3408 //////////////////////////////////////////////////////////////
3410 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3411 WidgetGUIEvent
* aGuiEvent
,
3412 const char* aWidgetName
, int32_t aWindowID
) {
3413 if (aGuiEvent
->mMessage
== eMouseMove
) {
3414 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3417 if (aGuiEvent
->mMessage
== eMouseEnterIntoWidget
||
3418 aGuiEvent
->mMessage
== eMouseExitFromWidget
) {
3419 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3423 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3425 NS_LossyConvertUTF16toASCII
tempString(
3426 debug_GuiEventToString(aGuiEvent
).get());
3428 fprintf(aFileOut
, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3429 _GetPrintCount(), tempString
.get(), (void*)aWidget
, aWidgetName
,
3430 aWindowID
, aGuiEvent
->mRefPoint
.x
.value
,
3431 aGuiEvent
->mRefPoint
.y
.value
);
3433 //////////////////////////////////////////////////////////////
3435 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3436 const nsIntRegion
& aRegion
,
3437 const char* aWidgetName
,
3438 int32_t aWindowID
) {
3439 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3440 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3442 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3444 nsIntRect rect
= aRegion
.GetBounds();
3446 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3448 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
, rect
.X(),
3449 rect
.Y(), rect
.Width(), rect
.Height());
3451 fprintf(aFileOut
, "\n");
3453 //////////////////////////////////////////////////////////////
3455 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut
, nsIWidget
* aWidget
,
3456 const LayoutDeviceIntRect
* aRect
,
3457 const char* aWidgetName
,
3458 int32_t aWindowID
) {
3459 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3461 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3462 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3464 fprintf(aFileOut
, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3465 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
);
3468 fprintf(aFileOut
, " rect=%3d,%-3d %3d,%-3d", aRect
->X(), aRect
->Y(),
3469 aRect
->Width(), aRect
->Height());
3471 fprintf(aFileOut
, " rect=%-15s", "none");
3474 fprintf(aFileOut
, "\n");
3476 //////////////////////////////////////////////////////////////