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
;
105 # include "nsCocoaFeatures.h"
108 using namespace mozilla::dom
;
109 using namespace mozilla::layers
;
110 using namespace mozilla::ipc
;
111 using namespace mozilla::widget
;
112 using namespace mozilla
;
114 // Async pump timer during injected long touch taps
115 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
116 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
117 int32_t nsIWidget::sPointerIdCounter
= 0;
119 // Some statics from nsIWidget.h
121 uint64_t AutoObserverNotifier::sObserverId
= 0;
122 /*static*/ nsTHashMap
<uint64_t, nsCOMPtr
<nsIObserver
>>
123 AutoObserverNotifier::sSavedObservers
;
125 // The maximum amount of time to let the EnableDragDrop runnable wait in the
126 // idle queue before timing out and moving it to the regular queue. Value is in
128 const uint32_t kAsyncDragDropTimeout
= 1000;
130 NS_IMPL_ISUPPORTS(nsBaseWidget
, nsIWidget
, nsISupportsWeakReference
)
132 //-------------------------------------------------------------------------
134 // nsBaseWidget constructor
136 //-------------------------------------------------------------------------
138 nsBaseWidget::nsBaseWidget() : nsBaseWidget(BorderStyle::None
) {}
140 nsBaseWidget::nsBaseWidget(BorderStyle aBorderStyle
)
141 : mWidgetListener(nullptr),
142 mAttachedWidgetListener(nullptr),
143 mPreviouslyAttachedWidgetListener(nullptr),
144 mCompositorVsyncDispatcher(nullptr),
145 mBorderStyle(aBorderStyle
),
148 mPopupLevel(PopupLevel::Top
),
149 mPopupType(PopupType::Any
),
150 mHasRemoteContent(false),
152 mUseAttachedEvents(false),
155 mIsFullyOccluded(false),
156 mNeedFastSnaphot(false),
157 mCurrentPanGestureBelongsToSwipe(false),
158 mIsPIPWindow(false) {
159 #ifdef NOISY_WIDGET_LEAKS
161 printf("WIDGETS+ = %d\n", gNumWidgets
);
165 debug_RegisterPrefCallbacks();
168 mShutdownObserver
= new WidgetShutdownObserver(this);
171 NS_IMPL_ISUPPORTS(WidgetShutdownObserver
, nsIObserver
)
173 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget
* aWidget
)
174 : mWidget(aWidget
), mRegistered(false) {
178 WidgetShutdownObserver::~WidgetShutdownObserver() {
179 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
180 // gets torn down. The observer service and nsBaseWidget have a ref on us
181 // so nsBaseWidget has to call Unregister and then clear its ref.
185 WidgetShutdownObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
186 const char16_t
* aData
) {
190 if (!strcmp(aTopic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
)) {
191 RefPtr
<nsBaseWidget
> widget(mWidget
);
193 } else if (!strcmp(aTopic
, "quit-application")) {
194 RefPtr
<nsBaseWidget
> widget(mWidget
);
200 void WidgetShutdownObserver::Register() {
203 nsContentUtils::RegisterShutdownObserver(this);
205 #ifndef MOZ_WIDGET_ANDROID
206 // The primary purpose of observing quit-application is
207 // to avoid leaking a widget on Windows when nothing else
208 // breaks the circular reference between the widget and
209 // TSFTextStore. However, our Android IME code crashes if
210 // doing this on Android, so let's not do this on Android.
211 // Doing this on Gtk and Mac just in case.
212 nsCOMPtr
<nsIObserverService
> observerService
=
213 mozilla::services::GetObserverService();
214 if (observerService
) {
215 observerService
->AddObserver(this, "quit-application", false);
221 void WidgetShutdownObserver::Unregister() {
225 #ifndef MOZ_WIDGET_ANDROID
226 nsCOMPtr
<nsIObserverService
> observerService
=
227 mozilla::services::GetObserverService();
228 if (observerService
) {
229 observerService
->RemoveObserver(this, "quit-application");
233 nsContentUtils::UnregisterShutdownObserver(this);
238 #define INTL_APP_LOCALES_CHANGED "intl:app-locales-changed"
240 NS_IMPL_ISUPPORTS(LocalesChangedObserver
, nsIObserver
)
242 LocalesChangedObserver::LocalesChangedObserver(nsBaseWidget
* aWidget
)
243 : mWidget(aWidget
), mRegistered(false) {
247 LocalesChangedObserver::~LocalesChangedObserver() {
248 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
249 // gets torn down. The observer service and nsBaseWidget have a ref on us
250 // so nsBaseWidget has to call Unregister and then clear its ref.
254 LocalesChangedObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
255 const char16_t
* aData
) {
259 if (!strcmp(aTopic
, INTL_APP_LOCALES_CHANGED
)) {
260 RefPtr
<nsBaseWidget
> widget(mWidget
);
261 widget
->LocalesChanged();
266 void LocalesChangedObserver::Register() {
271 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
273 obs
->AddObserver(this, INTL_APP_LOCALES_CHANGED
, true);
276 // Locale might be update before registering
277 RefPtr
<nsBaseWidget
> widget(mWidget
);
278 widget
->LocalesChanged();
283 void LocalesChangedObserver::Unregister() {
288 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
290 obs
->RemoveObserver(this, INTL_APP_LOCALES_CHANGED
);
297 void nsBaseWidget::Shutdown() {
298 NotifyLiveResizeStopped();
300 FreeLocalesChangedObserver();
301 FreeShutdownObserver();
304 void nsBaseWidget::QuitIME() {
305 IMEStateManager::WidgetOnQuit(this);
306 this->mIMEHasQuit
= true;
309 void nsBaseWidget::DestroyCompositor() {
310 RevokeTransactionIdAllocator();
312 // We release this before releasing the compositor, since it may hold the
313 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
314 // trigger a paint, creating a new compositor, and we don't want to re-use
315 // the old vsync dispatcher.
316 if (mCompositorVsyncDispatcher
) {
317 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
319 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
320 mCompositorVsyncDispatcher
->Shutdown();
321 mCompositorVsyncDispatcher
= nullptr;
324 // The compositor shutdown sequence looks like this:
325 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
326 // 2. CompositorBridgeChild synchronously sends WillClose.
327 // 3. CompositorBridgeParent releases some resources (such as the layer
328 // manager, compositor, and widget).
329 // 4. CompositorBridgeChild::Destroy returns.
330 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
331 // compositor thread when the I/O thread closes the IPC channel.
332 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
333 // releases the reference CompositorBridgeParent holds to itself.
335 // When CompositorSession::Shutdown returns, we assume the compositor is gone
336 // or will be gone very soon.
337 if (mCompositorSession
) {
338 ReleaseContentController();
340 SetCompositorWidgetDelegate(nullptr);
341 mCompositorBridgeChild
= nullptr;
342 mCompositorSession
->Shutdown();
343 mCompositorSession
= nullptr;
347 // This prevents the layer manager from starting a new transaction during
349 void nsBaseWidget::RevokeTransactionIdAllocator() {
350 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
353 mWindowRenderer
->AsWebRender()->SetTransactionIdAllocator(nullptr);
356 void nsBaseWidget::ReleaseContentController() {
357 if (mRootContentController
) {
358 mRootContentController
->Destroy();
359 mRootContentController
= nullptr;
363 void nsBaseWidget::DestroyLayerManager() {
364 if (mWindowRenderer
) {
365 mWindowRenderer
->Destroy();
366 mWindowRenderer
= nullptr;
371 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
373 void nsBaseWidget::FreeShutdownObserver() {
374 if (mShutdownObserver
) {
375 mShutdownObserver
->Unregister();
377 mShutdownObserver
= nullptr;
380 void nsBaseWidget::FreeLocalesChangedObserver() {
381 if (mLocalesChangedObserver
) {
382 mLocalesChangedObserver
->Unregister();
384 mLocalesChangedObserver
= nullptr;
387 //-------------------------------------------------------------------------
389 // nsBaseWidget destructor
391 //-------------------------------------------------------------------------
393 nsBaseWidget::~nsBaseWidget() {
395 mSwipeTracker
->Destroy();
396 mSwipeTracker
= nullptr;
399 IMEStateManager::WidgetDestroyed(this);
401 FreeLocalesChangedObserver();
402 FreeShutdownObserver();
403 DestroyLayerManager();
405 #ifdef NOISY_WIDGET_LEAKS
407 printf("WIDGETS- = %d\n", gNumWidgets
);
411 //-------------------------------------------------------------------------
415 //-------------------------------------------------------------------------
416 void nsBaseWidget::BaseCreate(nsIWidget
* aParent
, widget::InitData
* aInitData
) {
418 mWindowType
= aInitData
->mWindowType
;
419 mBorderStyle
= aInitData
->mBorderStyle
;
420 mPopupLevel
= aInitData
->mPopupLevel
;
421 mPopupType
= aInitData
->mPopupHint
;
422 mHasRemoteContent
= aInitData
->mHasRemoteContent
;
423 mIsPIPWindow
= aInitData
->mPIPWindow
;
427 aParent
->AddChild(this);
431 //-------------------------------------------------------------------------
433 // Accessor functions to get/set the client data
435 //-------------------------------------------------------------------------
437 nsIWidgetListener
* nsBaseWidget::GetWidgetListener() const {
438 return mWidgetListener
;
441 void nsBaseWidget::SetWidgetListener(nsIWidgetListener
* aWidgetListener
) {
442 mWidgetListener
= aWidgetListener
;
445 already_AddRefed
<nsIWidget
> nsBaseWidget::CreateChild(
446 const LayoutDeviceIntRect
& aRect
, widget::InitData
* aInitData
,
447 bool aForceUseIWidgetParent
) {
448 nsIWidget
* parent
= this;
449 nsNativeWidget nativeParent
= nullptr;
451 if (!aForceUseIWidgetParent
) {
452 // Use only either parent or nativeParent, not both, to match
453 // existing code. Eventually Create() should be divested of its
454 // nativeWidget parameter.
455 nativeParent
= parent
? parent
->GetNativeData(NS_NATIVE_WIDGET
) : nullptr;
456 parent
= nativeParent
? nullptr : parent
;
457 MOZ_ASSERT(!parent
|| !nativeParent
, "messed up logic");
460 nsCOMPtr
<nsIWidget
> widget
;
461 if (aInitData
&& aInitData
->mWindowType
== WindowType::Popup
) {
462 widget
= AllocateChildPopupWidget();
464 widget
= nsIWidget::CreateChildWindow();
467 if (widget
&& mNeedFastSnaphot
) {
468 widget
->SetNeedFastSnaphot();
472 NS_SUCCEEDED(widget
->Create(parent
, nativeParent
, aRect
, aInitData
))) {
473 return widget
.forget();
479 // Attach a view to our widget which we'll send events to.
480 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents
) {
481 NS_ASSERTION((mWindowType
== WindowType::TopLevel
||
482 mWindowType
== WindowType::Dialog
||
483 mWindowType
== WindowType::Invisible
||
484 mWindowType
== WindowType::Child
),
485 "Can't attach to window of that type");
487 mUseAttachedEvents
= aUseAttachedEvents
;
490 nsIWidgetListener
* nsBaseWidget::GetAttachedWidgetListener() const {
491 return mAttachedWidgetListener
;
494 nsIWidgetListener
* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
495 return mPreviouslyAttachedWidgetListener
;
498 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
499 nsIWidgetListener
* aListener
) {
500 mPreviouslyAttachedWidgetListener
= aListener
;
503 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener
* aListener
) {
504 mAttachedWidgetListener
= aListener
;
507 //-------------------------------------------------------------------------
509 // Close this nsBaseWidget
511 //-------------------------------------------------------------------------
512 void nsBaseWidget::Destroy() {
515 // Just in case our parent is the only ref to us
516 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
517 // disconnect from the parent
518 nsIWidget
* parent
= GetParent();
520 parent
->RemoveChild(this);
524 //-------------------------------------------------------------------------
526 // Get this nsBaseWidget parent
528 //-------------------------------------------------------------------------
529 nsIWidget
* nsBaseWidget::GetParent(void) { return nullptr; }
531 //-------------------------------------------------------------------------
533 // Get this nsBaseWidget top level widget
535 //-------------------------------------------------------------------------
536 nsIWidget
* nsBaseWidget::GetTopLevelWidget() {
537 nsIWidget
*topLevelWidget
= nullptr, *widget
= this;
539 topLevelWidget
= widget
;
540 widget
= widget
->GetParent();
542 return topLevelWidget
;
545 //-------------------------------------------------------------------------
547 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
549 //-------------------------------------------------------------------------
550 nsIWidget
* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
552 float nsBaseWidget::GetDPI() { return 96.0f
; }
554 CSSToLayoutDeviceScale
nsIWidget::GetDefaultScale() {
555 double devPixelsPerCSSPixel
= StaticPrefs::layout_css_devPixelsPerPx();
557 if (devPixelsPerCSSPixel
<= 0.0) {
558 devPixelsPerCSSPixel
= GetDefaultScaleInternal();
561 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel
);
564 nsIntSize
nsIWidget::CustomCursorSize(const Cursor
& aCursor
) {
565 MOZ_ASSERT(aCursor
.IsCustom());
568 aCursor
.mContainer
->GetWidth(&width
);
569 aCursor
.mContainer
->GetHeight(&height
);
570 aCursor
.mResolution
.ApplyTo(width
, height
);
571 return {width
, height
};
574 LayoutDeviceIntSize
nsIWidget::ClientToWindowSizeDifference() {
575 auto margin
= ClientToWindowMargin();
576 MOZ_ASSERT(margin
.top
>= 0, "Window should be bigger than client area");
577 MOZ_ASSERT(margin
.left
>= 0, "Window should be bigger than client area");
578 MOZ_ASSERT(margin
.right
>= 0, "Window should be bigger than client area");
579 MOZ_ASSERT(margin
.bottom
>= 0, "Window should be bigger than client area");
580 return {margin
.LeftRight(), margin
.TopBottom()};
583 RefPtr
<mozilla::VsyncDispatcher
> nsIWidget::GetVsyncDispatcher() {
587 //-------------------------------------------------------------------------
589 // Add a child to the list of children
591 //-------------------------------------------------------------------------
592 void nsBaseWidget::AddChild(nsIWidget
* aChild
) {
593 MOZ_ASSERT(!aChild
->GetNextSibling() && !aChild
->GetPrevSibling(),
594 "aChild not properly removed from its old child list");
597 mFirstChild
= mLastChild
= aChild
;
599 // append to the list
600 MOZ_ASSERT(mLastChild
);
601 MOZ_ASSERT(!mLastChild
->GetNextSibling());
602 mLastChild
->SetNextSibling(aChild
);
603 aChild
->SetPrevSibling(mLastChild
);
608 //-------------------------------------------------------------------------
610 // Remove a child from the list of children
612 //-------------------------------------------------------------------------
613 void nsBaseWidget::RemoveChild(nsIWidget
* aChild
) {
616 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
617 // null and we'll just have to do without this assertion.
618 nsIWidget
* parent
= aChild
->GetParent();
619 NS_ASSERTION(!parent
|| parent
== this, "Not one of our kids!");
621 MOZ_RELEASE_ASSERT(aChild
->GetParent() == this, "Not one of our kids!");
625 if (mLastChild
== aChild
) {
626 mLastChild
= mLastChild
->GetPrevSibling();
628 if (mFirstChild
== aChild
) {
629 mFirstChild
= mFirstChild
->GetNextSibling();
632 // Now remove from the list. Make sure that we pass ownership of the tail
633 // of the list correctly before we have aChild let go of it.
634 nsIWidget
* prev
= aChild
->GetPrevSibling();
635 nsIWidget
* next
= aChild
->GetNextSibling();
637 prev
->SetNextSibling(next
);
640 next
->SetPrevSibling(prev
);
643 aChild
->SetNextSibling(nullptr);
644 aChild
->SetPrevSibling(nullptr);
647 //-------------------------------------------------------------------------
649 // Sets widget's position within its parent's child list.
651 //-------------------------------------------------------------------------
652 void nsBaseWidget::SetZIndex(int32_t aZIndex
) {
653 // Hold a ref to ourselves just in case, since we're going to remove
655 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
659 // reorder this child in its parent's list.
660 auto* parent
= static_cast<nsBaseWidget
*>(GetParent());
662 parent
->RemoveChild(this);
663 // Scope sib outside the for loop so we can check it afterward
664 nsIWidget
* sib
= parent
->GetFirstChild();
665 for (; sib
; sib
= sib
->GetNextSibling()) {
666 int32_t childZIndex
= GetZIndex();
667 if (aZIndex
< childZIndex
) {
668 // Insert ourselves before sib
669 nsIWidget
* prev
= sib
->GetPrevSibling();
672 sib
->SetPrevSibling(this);
674 prev
->SetNextSibling(this);
676 NS_ASSERTION(sib
== parent
->mFirstChild
, "Broken child list");
677 // We've taken ownership of sib, so it's safe to have parent let
679 parent
->mFirstChild
= this;
681 PlaceBehind(eZPlacementBelow
, sib
, false);
685 // were we added to the list?
687 parent
->AddChild(this);
692 void nsBaseWidget::GetWorkspaceID(nsAString
& workspaceID
) {
693 workspaceID
.Truncate();
696 void nsBaseWidget::MoveToWorkspace(const nsAString
& workspaceID
) {
700 //-------------------------------------------------------------------------
702 // Get this component cursor
704 //-------------------------------------------------------------------------
706 void nsBaseWidget::SetCursor(const Cursor
& aCursor
) { mCursor
= aCursor
; }
708 //-------------------------------------------------------------------------
710 // Window transparency methods
712 //-------------------------------------------------------------------------
714 void nsBaseWidget::SetTransparencyMode(TransparencyMode aMode
) {}
716 TransparencyMode
nsBaseWidget::GetTransparencyMode() {
717 return TransparencyMode::Opaque
;
721 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage
,
724 nsIRunnable
* aCallback
) {
725 MOZ_ASSERT_UNREACHABLE(
726 "Should never call PerformFullscreenTransition on nsBaseWidget");
729 //-------------------------------------------------------------------------
731 // Put the window into full-screen mode
733 //-------------------------------------------------------------------------
734 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen
) {
735 #define MOZ_FORMAT_RECT(fmtstr) "[" fmtstr "," fmtstr " " fmtstr "x" fmtstr "]"
736 #define MOZ_SPLAT_RECT(rect) \
737 (rect).X(), (rect).Y(), (rect).Width(), (rect).Height()
739 // Windows which can be made fullscreen are exactly those which are located on
740 // the desktop, rather than being a child of some other window.
741 MOZ_DIAGNOSTIC_ASSERT(BoundsUseDesktopPixels(),
742 "non-desktop windows cannot be made fullscreen");
744 // Ensure that the OS chrome is hidden/shown before we resize and/or exit the
747 // HideWindowChrome() may (depending on platform, implementation details, and
748 // OS-level user preferences) alter the reported size of the window. The
749 // obvious and principled solution is socks-and-shoes:
750 // - On entering fullscreen mode: hide window chrome, then perform resize.
751 // - On leaving fullscreen mode: unperform resize, then show window chrome.
753 // ... unfortunately, HideWindowChrome() requires Resize() to be called
754 // afterwards (see bug 498835), which prevents this from being done in a
755 // straightforward way.
757 // Instead, we always call HideWindowChrome() just before we call Resize().
758 // This at least ensures that our measurements are consistently taken in a
759 // pre-transition state.
761 // ... unfortunately again, coupling HideWindowChrome() to Resize() means that
762 // we have to worry about the possibility of control flows that don't call
763 // Resize() at all. (That shouldn't happen, but it's not trivial to rule out.)
764 // We therefore set up a fallback to fix up the OS chrome if it hasn't been
765 // done at exit time.
766 bool hasAdjustedOSChrome
= false;
767 const auto adjustOSChrome
= [&]() {
768 if (hasAdjustedOSChrome
) {
769 MOZ_ASSERT_UNREACHABLE("window chrome should only be adjusted once");
772 HideWindowChrome(aFullScreen
);
773 hasAdjustedOSChrome
= true;
775 const auto adjustChromeOnScopeExit
= MakeScopeExit([&]() {
776 if (hasAdjustedOSChrome
) {
780 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
781 ("window was not resized within InfallibleMakeFullScreen()"));
783 // Hide chrome and "resize" the window to its current size.
784 auto rect
= GetBounds();
786 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
789 // Attempt to resize to `rect`.
791 // Returns the actual rectangle resized to. (This may differ from `rect`, if
792 // the OS is unhappy with it. See bug 1786226.)
793 const auto doReposition
= [&](auto rect
) -> void {
794 static_assert(std::is_base_of_v
<DesktopPixel
,
795 std::remove_reference_t
<decltype(rect
)>>,
796 "doReposition requires a rectangle using desktop pixels");
798 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Debug
)) {
799 const DesktopRect previousSize
=
800 GetScreenBounds() / GetDesktopToDeviceScale();
801 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
802 ("before resize: " MOZ_FORMAT_RECT("%f"),
803 MOZ_SPLAT_RECT(previousSize
)));
807 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
809 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Warning
)) {
810 // `rect` may have any underlying data type; coerce to float to
811 // simplify printf-style logging
812 const gfx::RectTyped
<DesktopPixel
, float> rectAsFloat
{rect
};
814 // The OS may have objected to the target position. That's not necessarily
815 // a problem -- it'll happen regularly on Macs with camera notches in the
816 // monitor, for instance (see bug 1786226) -- but it probably deserves to
819 // Since there's floating-point math involved, the actual values may be
820 // off by a few ulps -- as an upper bound, perhaps 8 * FLT_EPSILON *
821 // max(MOZ_SPLAT_RECT(rect)) -- but 0.01 should be several orders of
822 // magnitude bigger than that.
824 const auto postResizeRectRaw
= GetScreenBounds();
825 const auto postResizeRect
= postResizeRectRaw
/ GetDesktopToDeviceScale();
826 const bool succeeded
= postResizeRect
.WithinEpsilonOf(rectAsFloat
, 0.01);
829 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
830 ("resized to: " MOZ_FORMAT_RECT("%f"),
831 MOZ_SPLAT_RECT(rectAsFloat
)));
833 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
834 ("attempted to resize to: " MOZ_FORMAT_RECT("%f"),
835 MOZ_SPLAT_RECT(rectAsFloat
)));
836 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
837 ("... but ended up at: " MOZ_FORMAT_RECT("%f"),
838 MOZ_SPLAT_RECT(postResizeRect
)));
842 sBaseWidgetLog
, LogLevel::Verbose
,
843 ("(... which, before DPI adjustment, is:" MOZ_FORMAT_RECT("%d") ")",
844 MOZ_SPLAT_RECT(postResizeRectRaw
)));
850 mSavedBounds
= Some(FullscreenSavedState());
852 // save current position
853 mSavedBounds
->windowRect
= GetScreenBounds() / GetDesktopToDeviceScale();
855 nsCOMPtr
<nsIScreen
> screen
= GetWidgetScreen();
860 // Move to fill the screen.
861 doReposition(screen
->GetRectDisplayPix());
862 // Save off the new position. (This may differ from GetRectDisplayPix(), if
863 // the OS was unhappy with it. See bug 1786226.)
864 mSavedBounds
->screenRect
= GetScreenBounds() / GetDesktopToDeviceScale();
867 // This should never happen, at present, since we don't make windows
868 // fullscreen at their creation time; but it's not logically impossible.
869 MOZ_ASSERT(false, "fullscreen window did not have saved position");
873 // Figure out where to go from here.
875 // Fortunately, since we're currently fullscreen (and other code should be
876 // handling _keeping_ us fullscreen even after display-layout changes),
877 // there's an obvious choice for which display we should attach to; all we
878 // need to determine is where on that display we should go.
880 const DesktopRect currentWinRect
=
881 GetScreenBounds() / GetDesktopToDeviceScale();
883 // Optimization: if where we are is where we were, then where we originally
884 // came from is where we're going to go.
885 if (currentWinRect
== DesktopRect(mSavedBounds
->screenRect
)) {
886 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
887 ("no location change detected; returning to saved location"));
888 doReposition(mSavedBounds
->windowRect
);
893 General case: figure out where we're going to go by dividing where we are
894 by where we were, and then multiplying by where we originally came from.
896 Less abstrusely: resize so that we occupy the same proportional position
897 on our current display after leaving fullscreen as we occupied on our
898 previous display before entering fullscreen.
900 (N.B.: We do not clamp. If we were only partially on the old display,
901 we'll be only partially on the new one, too.)
904 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
905 ("location change detected; computing new destination"));
907 // splat: convert an arbitrary Rect into a tuple, for syntactic convenience.
908 const auto splat
= [](auto rect
) {
909 return std::tuple(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height());
912 // remap: find the unique affine mapping which transforms `src` to `dst`,
913 // and apply it to `val`.
914 using Range
= std::pair
<float, float>;
915 const auto remap
= [](Range dst
, Range src
, float val
) {
916 // linear interpolation and its inverse: lerp(a, b, invlerp(a, b, t)) == t
917 const auto lerp
= [](float lo
, float hi
, float t
) {
918 return lo
+ t
* (hi
- lo
);
920 const auto invlerp
= [](float lo
, float hi
, float mid
) {
921 return (mid
- lo
) / (hi
- lo
);
924 const auto [dst_a
, dst_b
] = dst
;
925 const auto [src_a
, src_b
] = src
;
926 return lerp(dst_a
, dst_b
, invlerp(src_a
, src_b
, val
));
930 const auto [px
, py
, pw
, ph
] = splat(mSavedBounds
->windowRect
);
931 // source desktop rect
932 const auto [sx
, sy
, sw
, sh
] = splat(mSavedBounds
->screenRect
);
933 // target desktop rect
934 const auto [tx
, ty
, tw
, th
] = splat(currentWinRect
);
936 const float nx
= remap({tx
, tx
+ tw
}, {sx
, sx
+ sw
}, px
);
937 const float ny
= remap({ty
, ty
+ th
}, {sy
, sy
+ sh
}, py
);
938 const float nw
= remap({0, tw
}, {0, sw
}, pw
);
939 const float nh
= remap({0, th
}, {0, sh
}, ph
);
941 doReposition(DesktopRect
{nx
, ny
, nw
, nh
});
944 #undef MOZ_SPLAT_RECT
945 #undef MOZ_FORMAT_RECT
948 nsresult
nsBaseWidget::MakeFullScreen(bool aFullScreen
) {
949 InfallibleMakeFullScreen(aFullScreen
);
953 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
954 nsBaseWidget
* aWidget
, gfxContext
* aTarget
, BufferMode aDoubleBuffering
)
956 WindowRenderer
* renderer
= mWidget
->GetWindowRenderer();
957 if (renderer
->AsFallback()) {
958 mRenderer
= renderer
->AsFallback();
959 mRenderer
->SetTarget(aTarget
, aDoubleBuffering
);
963 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
965 mRenderer
->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE
);
969 bool nsBaseWidget::IsSmallPopup() const {
970 return mWindowType
== WindowType::Popup
&& mPopupType
!= PopupType::Panel
;
973 bool nsBaseWidget::ComputeShouldAccelerate() {
974 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING
) &&
975 (WidgetTypeSupportsAcceleration() ||
976 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
979 bool nsBaseWidget::UseAPZ() {
980 return (gfxPlatform::AsyncPanZoomEnabled() &&
981 (mWindowType
== WindowType::TopLevel
||
982 mWindowType
== WindowType::Child
||
983 ((mWindowType
== WindowType::Popup
||
984 mWindowType
== WindowType::Dialog
) &&
985 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
988 void nsBaseWidget::CreateCompositor() {
989 LayoutDeviceIntRect rect
= GetBounds();
990 CreateCompositor(rect
.Width(), rect
.Height());
993 void nsIWidget::PauseOrResumeCompositor(bool aPause
) {
994 auto* renderer
= GetRemoteRenderer();
999 renderer
->SendPause();
1001 renderer
->SendResume();
1005 already_AddRefed
<GeckoContentController
>
1006 nsBaseWidget::CreateRootContentController() {
1007 RefPtr
<GeckoContentController
> controller
=
1008 new ChromeProcessController(this, mAPZEventState
, mAPZC
);
1009 return controller
.forget();
1012 void nsBaseWidget::ConfigureAPZCTreeManager() {
1013 MOZ_ASSERT(NS_IsMainThread());
1016 mAPZC
->SetDPI(GetDPI());
1018 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
1019 KeyboardMap map
= RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
1020 mAPZC
->SetKeyboardMap(map
);
1023 ContentReceivedInputBlockCallback
callback(
1024 [treeManager
= RefPtr
{mAPZC
.get()}](uint64_t aInputBlockId
,
1025 bool aPreventDefault
) {
1026 MOZ_ASSERT(NS_IsMainThread());
1027 treeManager
->ContentReceivedInputBlock(aInputBlockId
, aPreventDefault
);
1029 mAPZEventState
= new APZEventState(this, std::move(callback
));
1031 mRootContentController
= CreateRootContentController();
1032 if (mRootContentController
) {
1033 mCompositorSession
->SetContentController(mRootContentController
);
1036 // When APZ is enabled, we can actually enable raw touch events because we
1037 // have code that can deal with them properly. If APZ is not enabled, this
1038 // function doesn't get called.
1039 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
1040 RegisterTouchWindow();
1044 void nsBaseWidget::ConfigureAPZControllerThread() {
1045 // By default the controller thread is the main thread.
1046 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
1049 void nsBaseWidget::SetConfirmedTargetAPZC(
1050 uint64_t aInputBlockId
,
1051 const nsTArray
<ScrollableLayerGuid
>& aTargets
) const {
1052 mAPZC
->SetTargetAPZC(aInputBlockId
, aTargets
);
1055 void nsBaseWidget::UpdateZoomConstraints(
1056 const uint32_t& aPresShellId
, const ScrollableLayerGuid::ViewID
& aViewId
,
1057 const Maybe
<ZoomConstraints
>& aConstraints
) {
1058 if (!mCompositorSession
|| !mAPZC
) {
1059 if (mInitialZoomConstraints
) {
1060 MOZ_ASSERT(mInitialZoomConstraints
->mPresShellID
== aPresShellId
);
1061 MOZ_ASSERT(mInitialZoomConstraints
->mViewID
== aViewId
);
1062 if (!aConstraints
) {
1063 mInitialZoomConstraints
.reset();
1068 // We have some constraints, but the compositor and APZC aren't created
1069 // yet. Save these so we can use them later.
1070 mInitialZoomConstraints
= Some(
1071 InitialZoomConstraints(aPresShellId
, aViewId
, aConstraints
.ref()));
1075 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1076 mAPZC
->UpdateZoomConstraints(
1077 ScrollableLayerGuid(layersId
, aPresShellId
, aViewId
), aConstraints
);
1080 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC
; }
1082 nsEventStatus
nsBaseWidget::ProcessUntransformedAPZEvent(
1083 WidgetInputEvent
* aEvent
, const APZEventResult
& aApzResult
) {
1084 MOZ_ASSERT(NS_IsMainThread());
1085 ScrollableLayerGuid targetGuid
= aApzResult
.mTargetGuid
;
1086 uint64_t inputBlockId
= aApzResult
.mInputBlockId
;
1087 InputAPZContext
context(aApzResult
.mTargetGuid
, inputBlockId
,
1088 aApzResult
.GetStatus());
1090 // Make a copy of the original event for the APZCCallbackHelper helpers that
1091 // we call later, because the event passed to DispatchEvent can get mutated in
1092 // ways that we don't want (i.e. touch points can get stripped out).
1093 nsEventStatus status
;
1094 UniquePtr
<WidgetEvent
> original(aEvent
->Duplicate());
1095 DispatchEvent(aEvent
, status
);
1097 if (mAPZC
&& !InputAPZContext::WasRoutedToChildProcess() &&
1098 !InputAPZContext::WasDropped() && inputBlockId
) {
1099 // EventStateManager did not route the event into the child process and
1100 // the event was dispatched in the parent process.
1101 // It's safe to communicate to APZ that the event has been processed.
1102 // Note that here aGuid.mLayersId might be different from
1103 // mCompositorSession->RootLayerTreeId() because the event might have gotten
1104 // hit-tested by APZ to be targeted at a child process, but a parent process
1105 // event listener called preventDefault on it. In that case aGuid.mLayersId
1106 // would still be the layers id for the child process, but the event would
1107 // not have actually gotten routed to the child process. The main-thread
1108 // hit-test result therefore needs to use the parent process layers id.
1109 LayersId rootLayersId
= mCompositorSession
->RootLayerTreeId();
1111 RefPtr
<DisplayportSetListener
> postLayerization
;
1112 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1113 nsTArray
<TouchBehaviorFlags
> allowedTouchBehaviors
;
1114 if (touchEvent
->mMessage
== eTouchStart
) {
1115 auto& originalEvent
= *original
->AsTouchEvent();
1116 MOZ_ASSERT(NS_IsMainThread());
1117 allowedTouchBehaviors
= TouchActionHelper::GetAllowedTouchBehavior(
1118 this, GetDocument(), originalEvent
);
1119 if (!allowedTouchBehaviors
.IsEmpty()) {
1120 mAPZC
->SetAllowedTouchBehavior(inputBlockId
, allowedTouchBehaviors
);
1122 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1123 this, GetDocument(), originalEvent
, rootLayersId
, inputBlockId
);
1125 mAPZEventState
->ProcessTouchEvent(*touchEvent
, targetGuid
, inputBlockId
,
1126 aApzResult
.GetStatus(), status
,
1127 std::move(allowedTouchBehaviors
));
1128 } else if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1129 MOZ_ASSERT(wheelEvent
->mFlags
.mHandledByAPZ
);
1130 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1131 this, GetDocument(), *original
->AsWheelEvent(), rootLayersId
,
1133 if (wheelEvent
->mCanTriggerSwipe
) {
1134 ReportSwipeStarted(inputBlockId
, wheelEvent
->TriggersSwipe());
1136 mAPZEventState
->ProcessWheelEvent(*wheelEvent
, inputBlockId
);
1137 } else if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1138 MOZ_ASSERT(mouseEvent
->mFlags
.mHandledByAPZ
);
1139 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1140 this, GetDocument(), *original
->AsMouseEvent(), rootLayersId
,
1142 mAPZEventState
->ProcessMouseEvent(*mouseEvent
, inputBlockId
);
1144 if (postLayerization
) {
1145 postLayerization
->Register();
1152 template <class InputType
, class EventType
>
1153 class DispatchEventOnMainThread
: public Runnable
{
1155 DispatchEventOnMainThread(const InputType
& aInput
, nsBaseWidget
* aWidget
,
1156 const APZEventResult
& aAPZResult
)
1157 : mozilla::Runnable("DispatchEventOnMainThread"),
1160 mAPZResult(aAPZResult
) {}
1162 NS_IMETHOD
Run() override
{
1163 EventType event
= mInput
.ToWidgetEvent(mWidget
);
1164 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1170 nsBaseWidget
* mWidget
;
1171 APZEventResult mAPZResult
;
1174 template <class InputType
, class EventType
>
1175 class DispatchInputOnControllerThread
: public Runnable
{
1177 DispatchInputOnControllerThread(const EventType
& aEvent
,
1178 IAPZCTreeManager
* aAPZC
,
1179 nsBaseWidget
* aWidget
)
1180 : mozilla::Runnable("DispatchInputOnControllerThread"),
1181 mMainMessageLoop(MessageLoop::current()),
1186 NS_IMETHOD
Run() override
{
1187 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(mInput
);
1188 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1191 RefPtr
<Runnable
> r
= new DispatchEventOnMainThread
<InputType
, EventType
>(
1192 mInput
, mWidget
, result
);
1193 mMainMessageLoop
->PostTask(r
.forget());
1198 MessageLoop
* mMainMessageLoop
;
1200 RefPtr
<IAPZCTreeManager
> mAPZC
;
1201 nsBaseWidget
* mWidget
;
1204 void nsBaseWidget::DispatchTouchInput(MultiTouchInput
& aInput
,
1205 uint16_t aInputSource
) {
1206 MOZ_ASSERT(NS_IsMainThread());
1207 MOZ_ASSERT(aInputSource
==
1208 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH
||
1209 aInputSource
== mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN
);
1211 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1213 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1214 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1218 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1219 ProcessUntransformedAPZEvent(&event
, result
);
1221 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1223 nsEventStatus status
;
1224 DispatchEvent(&event
, status
);
1228 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput
& aInput
) {
1229 MOZ_ASSERT(NS_IsMainThread());
1231 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1233 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1234 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1238 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1239 ProcessUntransformedAPZEvent(&event
, result
);
1241 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1242 nsEventStatus status
;
1243 DispatchEvent(&event
, status
);
1247 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput
& aInput
) {
1248 MOZ_ASSERT(NS_IsMainThread());
1250 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1251 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1253 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1256 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1257 ProcessUntransformedAPZEvent(&event
, result
);
1259 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1260 nsEventStatus status
;
1261 DispatchEvent(&event
, status
);
1265 nsIWidget::ContentAndAPZEventStatus
nsBaseWidget::DispatchInputEvent(
1266 WidgetInputEvent
* aEvent
) {
1267 nsIWidget::ContentAndAPZEventStatus status
;
1268 MOZ_ASSERT(NS_IsMainThread());
1270 if (APZThreadUtils::IsControllerThread()) {
1271 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1272 status
.mApzStatus
= result
.GetStatus();
1273 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1276 status
.mContentStatus
= ProcessUntransformedAPZEvent(aEvent
, result
);
1279 if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1280 RefPtr
<Runnable
> r
=
1281 new DispatchInputOnControllerThread
<ScrollWheelInput
,
1282 WidgetWheelEvent
>(*wheelEvent
,
1284 APZThreadUtils::RunOnControllerThread(std::move(r
));
1285 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1288 if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1289 RefPtr
<Runnable
> r
=
1290 new DispatchInputOnControllerThread
<MouseInput
, WidgetMouseEvent
>(
1291 *mouseEvent
, mAPZC
, this);
1292 APZThreadUtils::RunOnControllerThread(std::move(r
));
1293 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1296 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1297 RefPtr
<Runnable
> r
=
1298 new DispatchInputOnControllerThread
<MultiTouchInput
,
1299 WidgetTouchEvent
>(*touchEvent
,
1301 APZThreadUtils::RunOnControllerThread(std::move(r
));
1302 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1305 // Allow dispatching keyboard events on Gecko thread.
1306 MOZ_ASSERT(aEvent
->AsKeyboardEvent());
1309 DispatchEvent(aEvent
, status
.mContentStatus
);
1313 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent
* aEvent
) {
1314 MOZ_ASSERT(NS_IsMainThread());
1316 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1317 mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1321 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent
& event
) {
1322 nsEventStatus status
;
1323 DispatchEvent(&event
, status
);
1324 return ConvertStatus(status
);
1327 Document
* nsBaseWidget::GetDocument() const {
1328 if (mWidgetListener
) {
1329 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1330 return presShell
->GetDocument();
1336 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1337 // Parent directly listens to the vsync source whereas
1338 // child process communicate via IPC
1339 // Should be called AFTER gfxPlatform is initialized
1340 if (XRE_IsParentProcess()) {
1341 if (!mCompositorVsyncDispatcherLock
) {
1342 mCompositorVsyncDispatcherLock
=
1343 MakeUnique
<Mutex
>("mCompositorVsyncDispatcherLock");
1345 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1346 if (!mCompositorVsyncDispatcher
) {
1347 RefPtr
<VsyncDispatcher
> vsyncDispatcher
=
1348 gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
1349 mCompositorVsyncDispatcher
=
1350 new CompositorVsyncDispatcher(std::move(vsyncDispatcher
));
1355 already_AddRefed
<CompositorVsyncDispatcher
>
1356 nsBaseWidget::GetCompositorVsyncDispatcher() {
1357 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
1359 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1360 RefPtr
<CompositorVsyncDispatcher
> dispatcher
= mCompositorVsyncDispatcher
;
1361 return dispatcher
.forget();
1364 already_AddRefed
<WebRenderLayerManager
> nsBaseWidget::CreateCompositorSession(
1365 int aWidth
, int aHeight
, CompositorOptions
* aOptionsOut
) {
1366 MOZ_ASSERT(aOptionsOut
);
1369 CreateCompositorVsyncDispatcher();
1371 gfx::GPUProcessManager
* gpu
= gfx::GPUProcessManager::Get();
1372 // Make sure GPU process is ready for use.
1373 // If it failed to connect to GPU process, GPU process usage is disabled in
1374 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1375 nsresult rv
= gpu
->EnsureGPUReady();
1376 if (NS_WARN_IF(rv
== NS_ERROR_ILLEGAL_DURING_SHUTDOWN
)) {
1380 // If widget type does not supports acceleration, we may be allowed to use
1381 // software WebRender instead.
1382 bool supportsAcceleration
= WidgetTypeSupportsAcceleration();
1383 bool enableSWWR
= true;
1384 if (supportsAcceleration
||
1385 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1386 enableSWWR
= gfx::gfxVars::UseSoftwareWebRender();
1388 bool enableAPZ
= UseAPZ();
1389 CompositorOptions
options(enableAPZ
, enableSWWR
);
1392 if (supportsAcceleration
) {
1393 options
.SetAllowSoftwareWebRenderD3D11(
1394 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1396 if (mNeedFastSnaphot
) {
1397 options
.SetNeedFastSnaphot(true);
1399 #elif defined(MOZ_WIDGET_ANDROID)
1400 MOZ_ASSERT(supportsAcceleration
);
1401 options
.SetAllowSoftwareWebRenderOGL(
1402 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1403 #elif defined(MOZ_WIDGET_GTK)
1404 if (supportsAcceleration
) {
1405 options
.SetAllowSoftwareWebRenderOGL(
1406 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1410 #ifdef MOZ_WIDGET_ANDROID
1411 // Unconditionally set the compositor as initially paused, as we have not
1412 // yet had a chance to send the compositor surface to the GPU process. We
1413 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1414 // where we will also resume the compositor if required.
1415 options
.SetInitiallyPaused(true);
1417 options
.SetInitiallyPaused(CompositorInitiallyPaused());
1420 RefPtr
<WebRenderLayerManager
> lm
= new WebRenderLayerManager(this);
1422 uint64_t innerWindowId
= 0;
1423 if (Document
* doc
= GetDocument()) {
1424 innerWindowId
= doc
->InnerWindowID();
1428 mCompositorSession
= gpu
->CreateTopLevelCompositor(
1429 this, lm
, GetDefaultScale(), options
, UseExternalCompositingSurface(),
1430 gfx::IntSize(aWidth
, aHeight
), innerWindowId
, &retry
);
1432 if (mCompositorSession
) {
1433 TextureFactoryIdentifier textureFactoryIdentifier
;
1435 lm
->Initialize(mCompositorSession
->GetCompositorBridgeChild(),
1436 wr::AsPipelineId(mCompositorSession
->RootLayerTreeId()),
1437 &textureFactoryIdentifier
, error
);
1438 if (textureFactoryIdentifier
.mParentBackend
!= LayersBackend::LAYERS_WR
) {
1440 DestroyCompositor();
1441 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1442 gfx::GPUProcessManager::Get()->DisableWebRender(
1443 wr::WebRenderError::INITIALIZE
, error
);
1447 // We need to retry in a loop because the act of failing to create the
1448 // compositor can change our state (e.g. disable WebRender).
1449 if (mCompositorSession
|| !retry
) {
1450 *aOptionsOut
= options
;
1456 void nsBaseWidget::CreateCompositor(int aWidth
, int aHeight
) {
1457 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1458 gfxPlatform::GetPlatform();
1460 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1461 "This function assumes OMTC");
1463 MOZ_ASSERT(!mCompositorSession
&& !mCompositorBridgeChild
,
1464 "Should have properly cleaned up the previous PCompositor pair "
1467 if (mCompositorBridgeChild
) {
1468 mCompositorBridgeChild
->Destroy();
1471 // Recreating this is tricky, as we may still have an old and we need
1472 // to make sure it's properly destroyed by calling DestroyCompositor!
1474 // If we've already received a shutdown notification, don't try
1475 // create a new compositor.
1476 if (!mShutdownObserver
) {
1480 // The controller thread must be configured before the compositor
1481 // session is created, so that the input bridge runs on the right
1483 ConfigureAPZControllerThread();
1485 CompositorOptions options
;
1486 RefPtr
<WebRenderLayerManager
> lm
=
1487 CreateCompositorSession(aWidth
, aHeight
, &options
);
1492 MOZ_ASSERT(mCompositorSession
);
1493 mCompositorBridgeChild
= mCompositorSession
->GetCompositorBridgeChild();
1494 SetCompositorWidgetDelegate(
1495 mCompositorSession
->GetCompositorWidgetDelegate());
1497 if (options
.UseAPZ()) {
1498 mAPZC
= mCompositorSession
->GetAPZCTreeManager();
1499 ConfigureAPZCTreeManager();
1504 if (mInitialZoomConstraints
) {
1505 UpdateZoomConstraints(mInitialZoomConstraints
->mPresShellID
,
1506 mInitialZoomConstraints
->mViewID
,
1507 Some(mInitialZoomConstraints
->mConstraints
));
1508 mInitialZoomConstraints
.reset();
1511 TextureFactoryIdentifier textureFactoryIdentifier
=
1512 lm
->GetTextureFactoryIdentifier();
1513 MOZ_ASSERT(textureFactoryIdentifier
.mParentBackend
==
1514 LayersBackend::LAYERS_WR
);
1515 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier
);
1516 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier
);
1520 mWindowRenderer
= std::move(lm
);
1522 // Only track compositors for top-level windows, since other window types
1523 // may use the basic compositor. Except on the OS X - see bug 1306383
1524 #if defined(XP_MACOSX)
1525 bool getCompositorFromThisWindow
= true;
1527 bool getCompositorFromThisWindow
= mWindowType
== WindowType::TopLevel
;
1530 if (getCompositorFromThisWindow
) {
1531 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1532 mWindowRenderer
->GetCompositorBackendType());
1536 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession
* aSession
) {
1537 MOZ_ASSERT(aSession
== mCompositorSession
);
1538 DestroyLayerManager();
1541 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1542 return gfxPlatform::UsesOffMainThreadCompositing();
1545 WindowRenderer
* nsBaseWidget::GetWindowRenderer() {
1546 if (!mWindowRenderer
) {
1547 if (!mShutdownObserver
) {
1548 // We are shutting down, do not try to re-create a LayerManager
1551 // Try to use an async compositor first, if possible
1552 if (ShouldUseOffMainThreadCompositing()) {
1556 if (!mWindowRenderer
) {
1557 mWindowRenderer
= CreateFallbackRenderer();
1560 return mWindowRenderer
;
1563 WindowRenderer
* nsBaseWidget::CreateFallbackRenderer() {
1564 return new FallbackRenderer
;
1567 CompositorBridgeChild
* nsBaseWidget::GetRemoteRenderer() {
1568 return mCompositorBridgeChild
;
1571 void nsBaseWidget::ClearCachedWebrenderResources() {
1572 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1575 mWindowRenderer
->AsWebRender()->ClearCachedResources();
1578 void nsBaseWidget::ClearWebrenderAnimationResources() {
1579 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1582 mWindowRenderer
->AsWebRender()->ClearAnimationResources();
1585 bool nsBaseWidget::SetNeedFastSnaphot() {
1586 MOZ_ASSERT(XRE_IsParentProcess());
1587 MOZ_ASSERT(!mCompositorSession
);
1589 if (!XRE_IsParentProcess() || mCompositorSession
) {
1593 mNeedFastSnaphot
= true;
1597 already_AddRefed
<gfx::DrawTarget
> nsBaseWidget::StartRemoteDrawing() {
1601 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA
; }
1603 //-------------------------------------------------------------------------
1605 // Destroy the window
1607 //-------------------------------------------------------------------------
1608 void nsBaseWidget::OnDestroy() {
1609 if (mTextEventDispatcher
) {
1610 mTextEventDispatcher
->OnDestroyWidget();
1611 // Don't release it until this widget actually released because after this
1612 // is called, TextEventDispatcher() may create it again.
1615 // If this widget is being destroyed, let the APZ code know to drop references
1616 // to this widget. Callers of this function all should be holding a deathgrip
1617 // on this widget already.
1618 ReleaseContentController();
1621 void nsBaseWidget::MoveClient(const DesktopPoint
& aOffset
) {
1622 LayoutDeviceIntPoint
clientOffset(GetClientOffset());
1624 // GetClientOffset returns device pixels; scale back to desktop pixels
1625 // if that's what this widget uses for the Move/Resize APIs
1626 if (BoundsUseDesktopPixels()) {
1627 DesktopPoint desktopOffset
= clientOffset
/ GetDesktopToDeviceScale();
1628 Move(aOffset
.x
- desktopOffset
.x
, aOffset
.y
- desktopOffset
.y
);
1630 LayoutDevicePoint layoutOffset
= aOffset
* GetDesktopToDeviceScale();
1631 Move(layoutOffset
.x
- LayoutDeviceCoord(clientOffset
.x
),
1632 layoutOffset
.y
- LayoutDeviceCoord(clientOffset
.y
));
1636 void nsBaseWidget::ResizeClient(const DesktopSize
& aSize
, bool aRepaint
) {
1637 NS_ASSERTION((aSize
.width
>= 0), "Negative width passed to ResizeClient");
1638 NS_ASSERTION((aSize
.height
>= 0), "Negative height passed to ResizeClient");
1640 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1642 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1643 // if that's what this widget uses for the Move/Resize APIs
1644 if (BoundsUseDesktopPixels()) {
1645 DesktopSize desktopDelta
=
1646 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1647 clientBounds
.Size()) /
1648 GetDesktopToDeviceScale();
1649 Resize(aSize
.width
+ desktopDelta
.width
, aSize
.height
+ desktopDelta
.height
,
1652 LayoutDeviceSize layoutSize
= aSize
* GetDesktopToDeviceScale();
1653 Resize(mBounds
.Width() + (layoutSize
.width
- clientBounds
.Width()),
1654 mBounds
.Height() + (layoutSize
.height
- clientBounds
.Height()),
1659 void nsBaseWidget::ResizeClient(const DesktopRect
& aRect
, bool aRepaint
) {
1660 NS_ASSERTION((aRect
.Width() >= 0), "Negative width passed to ResizeClient");
1661 NS_ASSERTION((aRect
.Height() >= 0), "Negative height passed to ResizeClient");
1663 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1664 LayoutDeviceIntPoint clientOffset
= GetClientOffset();
1665 DesktopToLayoutDeviceScale scale
= GetDesktopToDeviceScale();
1667 if (BoundsUseDesktopPixels()) {
1668 DesktopPoint desktopOffset
= clientOffset
/ scale
;
1669 DesktopSize desktopDelta
=
1670 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1671 clientBounds
.Size()) /
1673 Resize(aRect
.X() - desktopOffset
.x
, aRect
.Y() - desktopOffset
.y
,
1674 aRect
.Width() + desktopDelta
.width
,
1675 aRect
.Height() + desktopDelta
.height
, aRepaint
);
1677 LayoutDeviceRect layoutRect
= aRect
* scale
;
1678 Resize(layoutRect
.X() - clientOffset
.x
, layoutRect
.Y() - clientOffset
.y
,
1679 layoutRect
.Width() + mBounds
.Width() - clientBounds
.Width(),
1680 layoutRect
.Height() + mBounds
.Height() - clientBounds
.Height(),
1685 //-------------------------------------------------------------------------
1689 //-------------------------------------------------------------------------
1692 * If the implementation of nsWindow supports borders this method MUST be
1696 LayoutDeviceIntRect
nsBaseWidget::GetClientBounds() { return GetBounds(); }
1699 * If the implementation of nsWindow supports borders this method MUST be
1703 LayoutDeviceIntRect
nsBaseWidget::GetBounds() { return mBounds
; }
1706 * If the implementation of nsWindow uses a local coordinate system within the
1707 *window, this method must be overridden
1710 LayoutDeviceIntRect
nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1712 nsresult
nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect
& aRect
) {
1713 if (SizeMode() != nsSizeMode_Normal
) {
1714 return NS_ERROR_FAILURE
;
1716 aRect
= GetScreenBounds();
1720 LayoutDeviceIntPoint
nsBaseWidget::GetClientOffset() {
1721 return LayoutDeviceIntPoint(0, 0);
1724 nsresult
nsBaseWidget::SetNonClientMargins(const LayoutDeviceIntMargin
&) {
1725 return NS_ERROR_NOT_IMPLEMENTED
;
1728 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin
) {}
1730 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1732 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1734 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect
* aResizerRect
) {
1739 * Modifies aFile to point at an icon file with the given name and suffix. The
1740 * suffix may correspond to a file extension with leading '.' if appropriate.
1741 * Returns true if the icon file exists and can be read.
1743 static bool ResolveIconNameHelper(nsIFile
* aFile
, const nsAString
& aIconName
,
1744 const nsAString
& aIconSuffix
) {
1745 aFile
->Append(u
"icons"_ns
);
1746 aFile
->Append(u
"default"_ns
);
1747 aFile
->Append(aIconName
+ aIconSuffix
);
1750 return NS_SUCCEEDED(aFile
->IsReadable(&readable
)) && readable
;
1754 * Resolve the given icon name into a local file object. This method is
1755 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1756 * platform specific icon file suffix (e.g., ".ico" under Win32).
1758 * If no file is found matching the given parameters, then null is returned.
1760 void nsBaseWidget::ResolveIconName(const nsAString
& aIconName
,
1761 const nsAString
& aIconSuffix
,
1762 nsIFile
** aResult
) {
1765 nsCOMPtr
<nsIProperties
> dirSvc
=
1766 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID
);
1767 if (!dirSvc
) return;
1769 // first check auxilary chrome directories
1771 nsCOMPtr
<nsISimpleEnumerator
> dirs
;
1772 dirSvc
->Get(NS_APP_CHROME_DIR_LIST
, NS_GET_IID(nsISimpleEnumerator
),
1773 getter_AddRefs(dirs
));
1776 while (NS_SUCCEEDED(dirs
->HasMoreElements(&hasMore
)) && hasMore
) {
1777 nsCOMPtr
<nsISupports
> element
;
1778 dirs
->GetNext(getter_AddRefs(element
));
1779 if (!element
) continue;
1780 nsCOMPtr
<nsIFile
> file
= do_QueryInterface(element
);
1781 if (!file
) continue;
1782 if (ResolveIconNameHelper(file
, aIconName
, aIconSuffix
)) {
1783 NS_ADDREF(*aResult
= file
);
1789 // then check the main app chrome directory
1791 nsCOMPtr
<nsIFile
> file
;
1792 dirSvc
->Get(NS_APP_CHROME_DIR
, NS_GET_IID(nsIFile
), getter_AddRefs(file
));
1793 if (file
&& ResolveIconNameHelper(file
, aIconName
, aIconSuffix
))
1794 NS_ADDREF(*aResult
= file
);
1797 void nsBaseWidget::SetSizeConstraints(const SizeConstraints
& aConstraints
) {
1798 mSizeConstraints
= aConstraints
;
1800 // Popups are constrained during layout, and we don't want to synchronously
1801 // paint from reflow, so bail out... This is not great, but it's no worse than
1802 // what we used to do.
1804 // The right fix here is probably making constraint changes go through the
1805 // view manager and such.
1806 if (mWindowType
== WindowType::Popup
) {
1810 // If the current size doesn't meet the new constraints, trigger a
1811 // resize to apply it. Note that, we don't want to invoke Resize if
1812 // the new constraints don't affect the current size, because Resize
1813 // implementation on some platforms may touch other geometry even if
1814 // the size don't need to change.
1815 LayoutDeviceIntSize curSize
= mBounds
.Size();
1816 LayoutDeviceIntSize clampedSize
=
1817 Max(aConstraints
.mMinSize
, Min(aConstraints
.mMaxSize
, curSize
));
1818 if (clampedSize
!= curSize
) {
1820 if (BoundsUseDesktopPixels()) {
1821 DesktopSize desktopSize
= clampedSize
/ GetDesktopToDeviceScale();
1822 size
= desktopSize
.ToUnknownSize();
1824 size
= gfx::Size(clampedSize
.ToUnknownSize());
1826 Resize(size
.width
, size
.height
, true);
1830 const widget::SizeConstraints
nsBaseWidget::GetSizeConstraints() {
1831 return mSizeConstraints
;
1835 nsIRollupListener
* nsBaseWidget::GetActiveRollupListener() {
1836 // TODO: Simplify this.
1837 return nsXULPopupManager::GetInstance();
1840 void nsBaseWidget::NotifyWindowDestroyed() {
1841 if (!mWidgetListener
) return;
1843 nsCOMPtr
<nsIAppWindow
> window
= mWidgetListener
->GetAppWindow();
1844 nsCOMPtr
<nsIBaseWindow
> appWindow(do_QueryInterface(window
));
1846 appWindow
->Destroy();
1850 void nsBaseWidget::NotifyWindowMoved(int32_t aX
, int32_t aY
,
1851 ByMoveToRect aByMoveToRect
) {
1852 if (mWidgetListener
) {
1853 mWidgetListener
->WindowMoved(this, aX
, aY
, aByMoveToRect
);
1856 if (mIMEHasFocus
&& IMENotificationRequestsRef().WantPositionChanged()) {
1857 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE
));
1861 void nsBaseWidget::NotifySizeMoveDone() {
1862 if (!mWidgetListener
) {
1865 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1866 presShell
->WindowSizeMoveDone();
1870 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind
) {
1871 LookAndFeel::NotifyChangedAllWindows(aKind
);
1874 nsresult
nsBaseWidget::NotifyIME(const IMENotification
& aIMENotification
) {
1878 switch (aIMENotification
.mMessage
) {
1879 case REQUEST_TO_COMMIT_COMPOSITION
:
1880 case REQUEST_TO_CANCEL_COMPOSITION
:
1881 // We should send request to IME only when there is a TextEventDispatcher
1882 // instance (this means that this widget has dispatched at least one
1883 // composition event or keyboard event) and the it has composition.
1884 // Otherwise, there is nothing to do.
1885 // Note that if current input transaction is for native input events,
1886 // TextEventDispatcher::NotifyIME() will call
1887 // TextEventDispatcherListener::NotifyIME().
1888 if (mTextEventDispatcher
&& mTextEventDispatcher
->IsComposing()) {
1889 return mTextEventDispatcher
->NotifyIME(aIMENotification
);
1893 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_FOCUS
) {
1894 mIMEHasFocus
= true;
1896 EnsureTextEventDispatcher();
1897 // TextEventDispatcher::NotifyIME() will always call
1898 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1899 // input transaction is for synthesized events for automated tests,
1900 // notifications will be sent to native IME.
1901 nsresult rv
= mTextEventDispatcher
->NotifyIME(aIMENotification
);
1902 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_BLUR
) {
1903 mIMEHasFocus
= false;
1910 void nsBaseWidget::EnsureTextEventDispatcher() {
1911 if (mTextEventDispatcher
) {
1914 mTextEventDispatcher
= new TextEventDispatcher(this);
1917 nsIWidget::NativeIMEContext
nsBaseWidget::GetNativeIMEContext() {
1918 if (mTextEventDispatcher
&& mTextEventDispatcher
->GetPseudoIMEContext()) {
1919 // If we already have a TextEventDispatcher and it's working with
1920 // a TextInputProcessor, we need to return pseudo IME context since
1921 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1922 // on the pseudo IME context in such case.
1923 NativeIMEContext pseudoIMEContext
;
1924 pseudoIMEContext
.InitWithRawNativeIMEContext(
1925 mTextEventDispatcher
->GetPseudoIMEContext());
1926 return pseudoIMEContext
;
1928 return NativeIMEContext(this);
1931 nsIWidget::TextEventDispatcher
* nsBaseWidget::GetTextEventDispatcher() {
1932 EnsureTextEventDispatcher();
1933 return mTextEventDispatcher
;
1936 void* nsBaseWidget::GetPseudoIMEContext() {
1937 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
1941 return dispatcher
->GetPseudoIMEContext();
1944 TextEventDispatcherListener
*
1945 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1946 // TODO: If all platforms supported use of TextEventDispatcher for handling
1947 // native IME and keyboard events, this method should be removed since
1948 // in such case, this is overridden by all the subclasses.
1952 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId
,
1953 const ScrollableLayerGuid::ViewID
& aViewId
,
1954 const CSSRect
& aRect
, const uint32_t& aFlags
) {
1955 if (!mCompositorSession
|| !mAPZC
) {
1958 LayersId layerId
= mCompositorSession
->RootLayerTreeId();
1959 mAPZC
->ZoomToRect(ScrollableLayerGuid(layerId
, aPresShellId
, aViewId
),
1960 ZoomTarget
{aRect
}, aFlags
);
1963 #ifdef ACCESSIBILITY
1965 a11y::LocalAccessible
* nsBaseWidget::GetRootAccessible() {
1966 NS_ENSURE_TRUE(mWidgetListener
, nullptr);
1968 PresShell
* presShell
= mWidgetListener
->GetPresShell();
1969 NS_ENSURE_TRUE(presShell
, nullptr);
1971 // If container is null then the presshell is not active. This often happens
1972 // when a preshell is being held onto for fastback.
1973 nsPresContext
* presContext
= presShell
->GetPresContext();
1974 NS_ENSURE_TRUE(presContext
->GetContainerWeak(), nullptr);
1976 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1977 // make sure it's not created at unsafe times.
1978 nsAccessibilityService
* accService
= GetOrCreateAccService();
1980 return accService
->GetRootDocumentAccessible(
1981 presShell
, nsContentUtils::IsSafeToRunScript());
1987 #endif // ACCESSIBILITY
1989 void nsBaseWidget::StartAsyncScrollbarDrag(
1990 const AsyncDragMetrics
& aDragMetrics
) {
1991 if (!AsyncPanZoomEnabled()) {
1995 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession
);
1997 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1998 ScrollableLayerGuid
guid(layersId
, aDragMetrics
.mPresShellId
,
1999 aDragMetrics
.mViewId
);
2001 mAPZC
->StartScrollbarDrag(guid
, aDragMetrics
);
2004 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint
& aAnchorLocation
,
2005 const ScrollableLayerGuid
& aGuid
) {
2006 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2008 return mAPZC
->StartAutoscroll(aGuid
, aAnchorLocation
);
2011 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid
& aGuid
) {
2012 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2014 mAPZC
->StopAutoscroll(aGuid
);
2017 LayersId
nsBaseWidget::GetRootLayerTreeId() {
2018 return mCompositorSession
? mCompositorSession
->RootLayerTreeId()
2022 already_AddRefed
<widget::Screen
> nsBaseWidget::GetWidgetScreen() {
2023 ScreenManager
& screenManager
= ScreenManager::GetSingleton();
2024 LayoutDeviceIntRect bounds
= GetScreenBounds();
2025 DesktopIntRect deskBounds
= RoundedToInt(bounds
/ GetDesktopToDeviceScale());
2026 return screenManager
.ScreenForRect(deskBounds
);
2029 mozilla::DesktopToLayoutDeviceScale
2030 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
2031 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
2032 ->GetDesktopToDeviceScale();
2035 nsresult
nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint
,
2037 nsIObserver
* aObserver
) {
2038 AutoObserverNotifier
notifier(aObserver
, "touchtap");
2040 if (sPointerIdCounter
> TOUCH_INJECT_MAX_POINTS
) {
2041 sPointerIdCounter
= 0;
2043 int pointerId
= sPointerIdCounter
;
2044 sPointerIdCounter
++;
2045 nsresult rv
= SynthesizeNativeTouchPoint(pointerId
, TOUCH_CONTACT
, aPoint
,
2047 if (NS_FAILED(rv
)) {
2052 return SynthesizeNativeTouchPoint(pointerId
, TOUCH_REMOVE
, aPoint
, 0, 0,
2056 // initiate a long tap
2057 int elapse
= Preferences::GetInt("ui.click_hold_context_menus.delay",
2058 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC
);
2059 if (!mLongTapTimer
) {
2060 mLongTapTimer
= NS_NewTimer();
2061 if (!mLongTapTimer
) {
2062 SynthesizeNativeTouchPoint(pointerId
, TOUCH_CANCEL
, aPoint
, 0, 0,
2064 return NS_ERROR_UNEXPECTED
;
2066 // Windows requires recuring events, so we set this to a smaller window
2067 // than the pref value.
2068 int timeout
= elapse
;
2069 if (timeout
> TOUCH_INJECT_PUMP_TIMER_MSEC
) {
2070 timeout
= TOUCH_INJECT_PUMP_TIMER_MSEC
;
2072 mLongTapTimer
->InitWithNamedFuncCallback(
2073 OnLongTapTimerCallback
, this, timeout
, nsITimer::TYPE_REPEATING_SLACK
,
2074 "nsIWidget::SynthesizeNativeTouchTap");
2077 // If we already have a long tap pending, cancel it. We only allow one long
2078 // tap to be active at a time.
2079 if (mLongTapTouchPoint
) {
2080 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2081 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2084 mLongTapTouchPoint
= MakeUnique
<LongTapInfo
>(
2085 pointerId
, aPoint
, TimeDuration::FromMilliseconds(elapse
), aObserver
);
2086 notifier
.SkipNotification(); // we'll do it in the long-tap callback
2091 void nsIWidget::OnLongTapTimerCallback(nsITimer
* aTimer
, void* aClosure
) {
2092 auto* self
= static_cast<nsIWidget
*>(aClosure
);
2094 if ((self
->mLongTapTouchPoint
->mStamp
+ self
->mLongTapTouchPoint
->mDuration
) >
2097 // Windows needs us to keep pumping feedback to the digitizer, so update
2098 // the pointer id with the same position.
2099 self
->SynthesizeNativeTouchPoint(
2100 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_CONTACT
,
2101 self
->mLongTapTouchPoint
->mPosition
, 1.0, 90, nullptr);
2106 AutoObserverNotifier
notifier(self
->mLongTapTouchPoint
->mObserver
,
2109 // finished, remove the touch point
2110 self
->mLongTapTimer
->Cancel();
2111 self
->mLongTapTimer
= nullptr;
2112 self
->SynthesizeNativeTouchPoint(
2113 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_REMOVE
,
2114 self
->mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2115 self
->mLongTapTouchPoint
= nullptr;
2118 float nsIWidget::GetFallbackDPI() {
2119 RefPtr
<const Screen
> primaryScreen
=
2120 ScreenManager::GetSingleton().GetPrimaryScreen();
2121 return primaryScreen
->GetDPI();
2124 CSSToLayoutDeviceScale
nsIWidget::GetFallbackDefaultScale() {
2125 RefPtr
<const Screen
> s
= ScreenManager::GetSingleton().GetPrimaryScreen();
2126 return s
->GetCSSToLayoutDeviceScale(Screen::IncludeOSZoom::No
);
2129 nsresult
nsIWidget::ClearNativeTouchSequence(nsIObserver
* aObserver
) {
2130 AutoObserverNotifier
notifier(aObserver
, "cleartouch");
2132 // XXX This is odd. This is called by the constructor of nsIWidget. However,
2133 // at that point, nsIWidget::mLongTapTimer must be nullptr. Therefore,
2134 // this must do nothing at initializing the instance.
2135 if (!mLongTapTimer
) {
2138 mLongTapTimer
->Cancel();
2139 mLongTapTimer
= nullptr;
2140 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2141 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2142 mLongTapTouchPoint
= nullptr;
2146 MultiTouchInput
nsBaseWidget::UpdateSynthesizedTouchState(
2147 MultiTouchInput
* aState
, mozilla::TimeStamp aTimeStamp
, uint32_t aPointerId
,
2148 TouchPointerState aPointerState
, LayoutDeviceIntPoint aPoint
,
2149 double aPointerPressure
, uint32_t aPointerOrientation
) {
2150 ScreenIntPoint pointerScreenPoint
= ViewAs
<ScreenPixel
>(
2151 aPoint
, PixelCastJustification::LayoutDeviceIsScreenForBounds
);
2153 // We can't dispatch *aState directly because (a) dispatching
2154 // it might inadvertently modify it and (b) in the case of touchend or
2155 // touchcancel events aState will hold the touches that are
2156 // still down whereas the input dispatched needs to hold the removed
2157 // touch(es). We use |inputToDispatch| for this purpose.
2158 MultiTouchInput inputToDispatch
;
2159 inputToDispatch
.mInputType
= MULTITOUCH_INPUT
;
2160 inputToDispatch
.mTimeStamp
= aTimeStamp
;
2162 int32_t index
= aState
->IndexOfTouch((int32_t)aPointerId
);
2163 if (aPointerState
== TOUCH_CONTACT
) {
2165 // found an existing touch point, update it
2166 SingleTouchData
& point
= aState
->mTouches
[index
];
2167 point
.mScreenPoint
= pointerScreenPoint
;
2168 point
.mRotationAngle
= (float)aPointerOrientation
;
2169 point
.mForce
= (float)aPointerPressure
;
2170 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_MOVE
;
2172 // new touch point, add it
2173 aState
->mTouches
.AppendElement(SingleTouchData(
2174 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2175 (float)aPointerOrientation
, (float)aPointerPressure
));
2176 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_START
;
2178 inputToDispatch
.mTouches
= aState
->mTouches
;
2180 MOZ_ASSERT(aPointerState
== TOUCH_REMOVE
|| aPointerState
== TOUCH_CANCEL
);
2181 // a touch point is being lifted, so remove it from the stored list
2183 aState
->mTouches
.RemoveElementAt(index
);
2185 inputToDispatch
.mType
=
2186 (aPointerState
== TOUCH_REMOVE
? MultiTouchInput::MULTITOUCH_END
2187 : MultiTouchInput::MULTITOUCH_CANCEL
);
2188 inputToDispatch
.mTouches
.AppendElement(SingleTouchData(
2189 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2190 (float)aPointerOrientation
, (float)aPointerPressure
));
2193 return inputToDispatch
;
2196 void nsBaseWidget::NotifyLiveResizeStarted() {
2197 // If we have mLiveResizeListeners already non-empty, we should notify those
2198 // listeners that the resize stopped before starting anew. In theory this
2199 // should never happen because we shouldn't get nested live resize actions.
2200 NotifyLiveResizeStopped();
2201 MOZ_ASSERT(mLiveResizeListeners
.IsEmpty());
2203 // If we can get the active remote tab for the current widget, suppress
2204 // the displayport on it during the live resize.
2205 if (!mWidgetListener
) {
2208 nsCOMPtr
<nsIAppWindow
> appWindow
= mWidgetListener
->GetAppWindow();
2212 mLiveResizeListeners
= appWindow
->GetLiveResizeListeners();
2213 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2214 mLiveResizeListeners
[i
]->LiveResizeStarted();
2218 void nsBaseWidget::NotifyLiveResizeStopped() {
2219 if (!mLiveResizeListeners
.IsEmpty()) {
2220 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2221 mLiveResizeListeners
[i
]->LiveResizeStopped();
2223 mLiveResizeListeners
.Clear();
2227 nsresult
nsBaseWidget::AsyncEnableDragDrop(bool aEnable
) {
2228 RefPtr
<nsBaseWidget
> kungFuDeathGrip
= this;
2229 return NS_DispatchToCurrentThreadQueue(
2230 NS_NewRunnableFunction(
2231 "AsyncEnableDragDropFn",
2232 [this, aEnable
, kungFuDeathGrip
]() { EnableDragDrop(aEnable
); }),
2233 kAsyncDragDropTimeout
, EventQueuePriority::Idle
);
2236 void nsBaseWidget::SwipeFinished() {
2237 mSwipeTracker
->Destroy();
2238 mSwipeTracker
= nullptr;
2241 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId
,
2243 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== aInputBlockId
) {
2245 PanGestureInput
& startEvent
= mSwipeEventQueue
->queuedEvents
[0];
2246 TrackScrollEventAsSwipe(startEvent
, mSwipeEventQueue
->allowedDirections
,
2248 for (size_t i
= 1; i
< mSwipeEventQueue
->queuedEvents
.Length(); i
++) {
2249 mSwipeTracker
->ProcessEvent(mSwipeEventQueue
->queuedEvents
[i
]);
2252 // If the event wasn't start swipe, we need to notify it to APZ.
2253 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2254 BrowserGestureResponse::NotConsumed
);
2256 mSwipeEventQueue
= nullptr;
2260 void nsBaseWidget::TrackScrollEventAsSwipe(
2261 const mozilla::PanGestureInput
& aSwipeStartEvent
,
2262 uint32_t aAllowedDirections
, uint64_t aInputBlockId
) {
2263 // If a swipe is currently being tracked kill it -- it's been interrupted
2264 // by another gesture event.
2265 if (mSwipeTracker
) {
2266 mSwipeTracker
->CancelSwipe(aSwipeStartEvent
.mTimeStamp
);
2267 mSwipeTracker
->Destroy();
2268 mSwipeTracker
= nullptr;
2271 uint32_t direction
=
2272 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2273 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2274 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2277 new SwipeTracker(*this, aSwipeStartEvent
, aAllowedDirections
, direction
);
2280 mCurrentPanGestureBelongsToSwipe
= true;
2282 // Now SwipeTracker has started consuming pan events, notify it to APZ so
2283 // that APZ can discard queued events.
2284 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2285 BrowserGestureResponse::Consumed
);
2289 nsBaseWidget::SwipeInfo
nsBaseWidget::SendMayStartSwipe(
2290 const mozilla::PanGestureInput
& aSwipeStartEvent
) {
2291 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
2293 uint32_t direction
=
2294 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2295 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2296 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2298 // We're ready to start the animation. Tell Gecko about it, and at the same
2299 // time ask it if it really wants to start an animation for this event.
2300 // This event also reports back the directions that we can swipe in.
2301 LayoutDeviceIntPoint position
= RoundedToInt(aSwipeStartEvent
.mPanStartPoint
*
2302 ScreenToLayoutDeviceScale(1));
2303 WidgetSimpleGestureEvent geckoEvent
= SwipeTracker::CreateSwipeGestureEvent(
2304 eSwipeGestureMayStart
, this, position
, aSwipeStartEvent
.mTimeStamp
);
2305 geckoEvent
.mDirection
= direction
;
2306 geckoEvent
.mDelta
= 0.0;
2307 geckoEvent
.mAllowedDirections
= 0;
2308 bool shouldStartSwipe
=
2309 DispatchWindowEvent(geckoEvent
); // event cancelled == swipe should start
2311 SwipeInfo result
= {shouldStartSwipe
, geckoEvent
.mAllowedDirections
};
2315 WidgetWheelEvent
nsBaseWidget::MayStartSwipeForAPZ(
2316 const PanGestureInput
& aPanInput
, const APZEventResult
& aApzResult
) {
2317 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2319 // Ignore swipe-to-navigation in PiP window.
2324 if (aPanInput
.AllowsSwipe()) {
2325 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2326 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2327 if (swipeInfo
.wantsSwipe
) {
2328 if (aApzResult
.GetStatus() == nsEventStatus_eIgnore
) {
2329 // APZ has determined and that scrolling horizontally in the
2330 // requested direction is impossible, so it didn't do any
2331 // scrolling for the event.
2332 // We know now that MayStartSwipe wants a swipe, so we can start
2334 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
,
2335 aApzResult
.mInputBlockId
);
2336 } else if (!aApzResult
.GetHandledResult() ||
2337 !aApzResult
.GetHandledResult()->IsHandledByRoot()) {
2338 // We don't know whether this event can start a swipe, so we need
2339 // to queue up events and wait for a call to ReportSwipeStarted.
2340 // APZ might already have started scrolling in response to the
2341 // event if it knew that it's the right thing to do. In that case
2342 // we'll still get a call to ReportSwipeStarted, and we will
2343 // discard the queued events at that point.
2344 mSwipeEventQueue
= MakeUnique
<SwipeEventQueue
>(
2345 swipeInfo
.allowedDirections
, aApzResult
.mInputBlockId
);
2348 // Inform that the browser gesture didn't use the pan event (pan-start
2349 // precisely), so that APZ can now start using the event for
2350 // scrolling/overscrolling.
2351 mAPZC
->SetBrowserGestureResponse(aApzResult
.mInputBlockId
,
2352 BrowserGestureResponse::NotConsumed
);
2356 if (mSwipeEventQueue
&&
2357 mSwipeEventQueue
->inputBlockId
== aApzResult
.mInputBlockId
) {
2358 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2364 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput
& aPanInput
) {
2365 // Ignore swipe-to-navigation in PiP window.
2370 if (aPanInput
.mType
== PanGestureInput::PANGESTURE_MAYSTART
||
2371 aPanInput
.mType
== PanGestureInput::PANGESTURE_START
) {
2372 mCurrentPanGestureBelongsToSwipe
= false;
2374 if (mCurrentPanGestureBelongsToSwipe
) {
2375 // Ignore this event. It's a momentum event from a scroll gesture
2376 // that was processed as a swipe, and the swipe animation has
2377 // already finished (so mSwipeTracker is already null).
2378 MOZ_ASSERT(aPanInput
.IsMomentum(),
2379 "If the fingers are still on the touchpad, we should still have "
2381 "and it should have consumed this event.");
2385 if (!aPanInput
.MayTriggerSwipe()) {
2389 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2391 // We're in the non-APZ case here, but we still want to know whether
2392 // the event was routed to a child process, so we use InputAPZContext
2393 // to get that piece of information.
2394 ScrollableLayerGuid guid
;
2395 uint64_t blockId
= 0;
2396 InputAPZContext
context(guid
, blockId
, nsEventStatus_eIgnore
);
2398 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2399 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2400 nsEventStatus status
;
2401 DispatchEvent(&event
, status
);
2402 if (swipeInfo
.wantsSwipe
) {
2403 if (context
.WasRoutedToChildProcess()) {
2404 // We don't know whether this event can start a swipe, so we need
2405 // to queue up events and wait for a call to ReportSwipeStarted.
2407 MakeUnique
<SwipeEventQueue
>(swipeInfo
.allowedDirections
, blockId
);
2408 } else if (event
.TriggersSwipe()) {
2409 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
, blockId
);
2413 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== 0) {
2414 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2420 const IMENotificationRequests
& nsIWidget::IMENotificationRequestsRef() {
2421 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
2422 return dispatcher
->IMENotificationRequestsRef();
2425 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent
* aEvent
) {}
2427 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType
,
2428 const WidgetKeyboardEvent
& aEvent
,
2429 nsTArray
<CommandInt
>& aCommands
) {
2430 MOZ_ASSERT(aEvent
.IsTrusted());
2431 MOZ_ASSERT(aCommands
.IsEmpty());
2435 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboard() {
2436 if (XRE_IsContentProcess()) {
2437 return CreateBidiKeyboardContentProcess();
2439 return CreateBidiKeyboardInner();
2443 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboardInner() {
2444 // no bidi keyboard implementation
2449 namespace mozilla::widget
{
2451 const char* ToChar(InputContext::Origin aOrigin
) {
2453 case InputContext::ORIGIN_MAIN
:
2454 return "ORIGIN_MAIN";
2455 case InputContext::ORIGIN_CONTENT
:
2456 return "ORIGIN_CONTENT";
2458 return "Unexpected value";
2462 const char* ToChar(IMEMessage aIMEMessage
) {
2463 switch (aIMEMessage
) {
2464 case NOTIFY_IME_OF_NOTHING
:
2465 return "NOTIFY_IME_OF_NOTHING";
2466 case NOTIFY_IME_OF_FOCUS
:
2467 return "NOTIFY_IME_OF_FOCUS";
2468 case NOTIFY_IME_OF_BLUR
:
2469 return "NOTIFY_IME_OF_BLUR";
2470 case NOTIFY_IME_OF_SELECTION_CHANGE
:
2471 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2472 case NOTIFY_IME_OF_TEXT_CHANGE
:
2473 return "NOTIFY_IME_OF_TEXT_CHANGE";
2474 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED
:
2475 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2476 case NOTIFY_IME_OF_POSITION_CHANGE
:
2477 return "NOTIFY_IME_OF_POSITION_CHANGE";
2478 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT
:
2479 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2480 case REQUEST_TO_COMMIT_COMPOSITION
:
2481 return "REQUEST_TO_COMMIT_COMPOSITION";
2482 case REQUEST_TO_CANCEL_COMPOSITION
:
2483 return "REQUEST_TO_CANCEL_COMPOSITION";
2485 return "Unexpected value";
2489 void NativeIMEContext::Init(nsIWidget
* aWidget
) {
2491 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2492 mOriginProcessID
= static_cast<uint64_t>(-1);
2495 if (!XRE_IsContentProcess()) {
2496 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(
2497 aWidget
->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT
));
2498 mOriginProcessID
= 0;
2501 // If this is created in a child process, aWidget is an instance of
2502 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2503 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2504 // native IME context of the parent process.
2505 *this = aWidget
->GetNativeIMEContext();
2508 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext
) {
2509 if (NS_WARN_IF(!aRawNativeIMEContext
)) {
2510 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2511 mOriginProcessID
= static_cast<uint64_t>(-1);
2514 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(aRawNativeIMEContext
);
2516 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2519 void IMENotification::TextChangeDataBase::MergeWith(
2520 const IMENotification::TextChangeDataBase
& aOther
) {
2521 MOZ_ASSERT(aOther
.IsValid(), "Merging data must store valid data");
2522 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mRemovedEndOffset
,
2523 "end of removed text must be same or larger than start");
2524 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mAddedEndOffset
,
2525 "end of added text must be same or larger than start");
2532 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2533 // text ranges. I.e., mStartOffset should be the smallest offset of all
2534 // modified text ranges in old text. |mRemovedEndOffset| should be the
2535 // largest end offset in old text of all modified text ranges.
2536 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2537 // I.e., only this is an offset in new text.
2538 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2539 // premodified text was already removed. And some text whose length is
2540 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2541 // this allows IME to mark dirty the modified text range with |mStartOffset|
2542 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2543 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2544 // Additionally, IME can retrieve only the text between |mStartOffset| and
2545 // |mAddedEndOffset| for updating stored text.
2547 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2548 // should be adjusted to be in same text. The |newData.mStartOffset| and
2549 // |newData.mRemovedEndOffset| should be computed as in old text because
2550 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2551 // in the old text but even if some text before the values of the newData
2552 // has already been modified, the values don't include the changes.
2554 // For comparing new and old |mAddedEndOffset| values, they should be
2555 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2556 // computed as in the new text because |mAddedEndOffset| indicates the end
2557 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2558 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2560 const TextChangeDataBase
& newData
= aOther
;
2561 const TextChangeDataBase oldData
= *this;
2563 // mCausedOnlyByComposition should be true only when all changes are caused
2565 mCausedOnlyByComposition
=
2566 newData
.mCausedOnlyByComposition
&& oldData
.mCausedOnlyByComposition
;
2568 // mIncludingChangesWithoutComposition should be true if at least one of
2569 // merged changes occurred without composition.
2570 mIncludingChangesWithoutComposition
=
2571 newData
.mIncludingChangesWithoutComposition
||
2572 oldData
.mIncludingChangesWithoutComposition
;
2574 // mIncludingChangesDuringComposition should be true when at least one of
2575 // the merged non-composition changes occurred during the latest composition.
2576 if (!newData
.mCausedOnlyByComposition
&&
2577 !newData
.mIncludingChangesDuringComposition
) {
2578 MOZ_ASSERT(newData
.mIncludingChangesWithoutComposition
);
2579 MOZ_ASSERT(mIncludingChangesWithoutComposition
);
2580 // If new change is neither caused by composition nor occurred during
2581 // composition, set mIncludingChangesDuringComposition to false because
2582 // IME doesn't want outdated text changes as text change during current
2584 mIncludingChangesDuringComposition
= false;
2586 // Otherwise, set mIncludingChangesDuringComposition to true if either
2587 // oldData or newData includes changes during composition.
2588 mIncludingChangesDuringComposition
=
2589 newData
.mIncludingChangesDuringComposition
||
2590 oldData
.mIncludingChangesDuringComposition
;
2593 if (newData
.mStartOffset
>= oldData
.mAddedEndOffset
) {
2595 // If new start is after old end offset of added text, it means that text
2596 // after the modified range is modified. Like:
2597 // added range of old change: +----------+
2598 // removed range of new change: +----------+
2599 // So, the old start offset is always the smaller offset.
2600 mStartOffset
= oldData
.mStartOffset
;
2601 // The new end offset of removed text is moved by the old change and we
2602 // need to cancel the move of the old change for comparing the offsets in
2603 // same text because it doesn't make sensce to compare offsets in different
2605 uint32_t newRemovedEndOffsetInOldText
=
2606 newData
.mRemovedEndOffset
- oldData
.Difference();
2608 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2609 // The new end offset of added text is always the larger offset.
2610 mAddedEndOffset
= newData
.mAddedEndOffset
;
2614 if (newData
.mStartOffset
>= oldData
.mStartOffset
) {
2615 // If new start is in the modified range, it means that new data changes
2616 // a part or all of the range.
2617 mStartOffset
= oldData
.mStartOffset
;
2618 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2620 // If new end of removed text is greater than old end of added text, it
2621 // means that all or a part of modified range modified again and text
2622 // after the modified range is also modified. Like:
2623 // added range of old change: +----------+
2624 // removed range of new change: +----------+
2625 // So, the new removed end offset is moved by the old change and we need
2626 // to cancel the move of the old change for comparing the offsets in the
2627 // same text because it doesn't make sense to compare the offsets in
2629 uint32_t newRemovedEndOffsetInOldText
=
2630 newData
.mRemovedEndOffset
- oldData
.Difference();
2632 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2633 // The old end of added text is replaced by new change. So, it should be
2634 // same as the new start. On the other hand, the new added end offset is
2635 // always same or larger. Therefore, the merged end offset of added
2636 // text should be the new end offset of added text.
2637 mAddedEndOffset
= newData
.mAddedEndOffset
;
2642 // If new end of removed text is less than old end of added text, it means
2643 // that only a part of the modified range is modified again. Like:
2644 // added range of old change: +------------+
2645 // removed range of new change: +-----+
2646 // So, the new end offset of removed text should be same as the old end
2647 // offset of removed text. Therefore, the merged end offset of removed
2648 // text should be the old text change's |mRemovedEndOffset|.
2649 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2650 // The old end of added text is moved by new change. So, we need to cancel
2651 // the move of the new change for comparing the offsets in same text.
2652 uint32_t oldAddedEndOffsetInNewText
=
2653 oldData
.mAddedEndOffset
+ newData
.Difference();
2655 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2659 if (newData
.mRemovedEndOffset
>= oldData
.mStartOffset
) {
2660 // If new end of removed text is greater than old start (and new start is
2661 // less than old start), it means that a part of modified range is modified
2662 // again and some new text before the modified range is also modified.
2663 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2664 "new start offset should be less than old one here");
2665 mStartOffset
= newData
.mStartOffset
;
2666 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2668 // If new end of removed text is greater than old end of added text, it
2669 // means that all modified text and text after the modified range is
2671 // added range of old change: +----------+
2672 // removed range of new change: +------------------+
2673 // So, the new end of removed text is moved by the old change. Therefore,
2674 // we need to cancel the move of the old change for comparing the offsets
2675 // in same text because it doesn't make sense to compare the offsets in
2677 uint32_t newRemovedEndOffsetInOldText
=
2678 newData
.mRemovedEndOffset
- oldData
.Difference();
2680 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2681 // The old end of added text is replaced by new change. So, the old end
2682 // offset of added text is same as new text change's start offset. Then,
2683 // new change's end offset of added text is always same or larger than
2684 // it. Therefore, merged end offset of added text is always the new end
2685 // offset of added text.
2686 mAddedEndOffset
= newData
.mAddedEndOffset
;
2691 // If new end of removed text is less than old end of added text, it
2692 // means that only a part of the modified range is modified again. Like:
2693 // added range of old change: +----------+
2694 // removed range of new change: +----------+
2695 // So, the new end of removed text should be same as old end of removed
2696 // text for preventing end of removed text to be modified. Therefore,
2697 // merged end offset of removed text is always the old end offset of removed
2699 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2700 // The old end of added text is moved by this change. So, we need to
2701 // cancel the move of the new change for comparing the offsets in same text
2702 // because it doesn't make sense to compare the offsets in different text.
2703 uint32_t oldAddedEndOffsetInNewText
=
2704 oldData
.mAddedEndOffset
+ newData
.Difference();
2706 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2711 // Otherwise, i.e., both new end of added text and new start are less than
2712 // old start, text before the modified range is modified. Like:
2713 // added range of old change: +----------+
2714 // removed range of new change: +----------+
2715 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2716 "new start offset should be less than old one here");
2717 mStartOffset
= newData
.mStartOffset
;
2718 MOZ_ASSERT(newData
.mRemovedEndOffset
< oldData
.mRemovedEndOffset
,
2719 "new removed end offset should be less than old one here");
2720 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2721 // The end of added text should be adjusted with the new difference.
2722 uint32_t oldAddedEndOffsetInNewText
=
2723 oldData
.mAddedEndOffset
+ newData
.Difference();
2725 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2730 // Let's test the code of merging multiple text change data in debug build
2731 // and crash if one of them fails because this feature is very complex but
2732 // cannot be tested with mochitest.
2733 void IMENotification::TextChangeDataBase::Test() {
2734 static bool gTestTextChangeEvent
= true;
2735 if (!gTestTextChangeEvent
) {
2738 gTestTextChangeEvent
= false;
2740 /****************************************************************************
2742 ****************************************************************************/
2745 MergeWith(TextChangeData(10, 10, 20, false, false));
2746 MergeWith(TextChangeData(20, 20, 35, false, false));
2747 MOZ_ASSERT(mStartOffset
== 10,
2748 "Test 1-1-1: mStartOffset should be the first offset");
2750 mRemovedEndOffset
== 10, // 20 - (20 - 10)
2751 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2753 mAddedEndOffset
== 35,
2754 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2757 // Removing text (longer line -> shorter line)
2758 MergeWith(TextChangeData(10, 20, 10, false, false));
2759 MergeWith(TextChangeData(10, 30, 10, false, false));
2760 MOZ_ASSERT(mStartOffset
== 10,
2761 "Test 1-2-1: mStartOffset should be the first offset");
2762 MOZ_ASSERT(mRemovedEndOffset
== 40, // 30 + (10 - 20)
2763 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2765 "with already removed length");
2767 mAddedEndOffset
== 10,
2768 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2771 // Removing text (shorter line -> longer line)
2772 MergeWith(TextChangeData(10, 20, 10, false, false));
2773 MergeWith(TextChangeData(10, 15, 10, false, false));
2774 MOZ_ASSERT(mStartOffset
== 10,
2775 "Test 1-3-1: mStartOffset should be the first offset");
2776 MOZ_ASSERT(mRemovedEndOffset
== 25, // 15 + (10 - 20)
2777 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2779 "with already removed length");
2781 mAddedEndOffset
== 10,
2782 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2785 // Appending text at different point (not sure if actually occurs)
2786 MergeWith(TextChangeData(10, 10, 20, false, false));
2787 MergeWith(TextChangeData(55, 55, 60, false, false));
2788 MOZ_ASSERT(mStartOffset
== 10,
2789 "Test 1-4-1: mStartOffset should be the smallest offset");
2791 mRemovedEndOffset
== 45, // 55 - (10 - 20)
2792 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2793 "text without already added length");
2795 mAddedEndOffset
== 60,
2796 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2799 // Removing text at different point (not sure if actually occurs)
2800 MergeWith(TextChangeData(10, 20, 10, false, false));
2801 MergeWith(TextChangeData(55, 68, 55, false, false));
2802 MOZ_ASSERT(mStartOffset
== 10,
2803 "Test 1-5-1: mStartOffset should be the smallest offset");
2805 mRemovedEndOffset
== 78, // 68 - (10 - 20)
2806 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2807 "text with already removed length");
2809 mAddedEndOffset
== 55,
2810 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2813 // Replacing text and append text (becomes longer)
2814 MergeWith(TextChangeData(30, 35, 32, false, false));
2815 MergeWith(TextChangeData(32, 32, 40, false, false));
2816 MOZ_ASSERT(mStartOffset
== 30,
2817 "Test 1-6-1: mStartOffset should be the smallest offset");
2819 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2820 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2823 mAddedEndOffset
== 40,
2824 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2827 // Replacing text and append text (becomes shorter)
2828 MergeWith(TextChangeData(30, 35, 32, false, false));
2829 MergeWith(TextChangeData(32, 32, 33, false, false));
2830 MOZ_ASSERT(mStartOffset
== 30,
2831 "Test 1-7-1: mStartOffset should be the smallest offset");
2833 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2834 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2837 mAddedEndOffset
== 33,
2838 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2841 // Removing text and replacing text after first range (not sure if actually
2843 MergeWith(TextChangeData(30, 35, 30, false, false));
2844 MergeWith(TextChangeData(32, 34, 48, false, false));
2845 MOZ_ASSERT(mStartOffset
== 30,
2846 "Test 1-8-1: mStartOffset should be the smallest offset");
2847 MOZ_ASSERT(mRemovedEndOffset
== 39, // 34 - (30 - 35)
2848 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2850 "without already removed text");
2852 mAddedEndOffset
== 48,
2853 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2856 // Removing text and replacing text after first range (not sure if actually
2858 MergeWith(TextChangeData(30, 35, 30, false, false));
2859 MergeWith(TextChangeData(32, 38, 36, false, false));
2860 MOZ_ASSERT(mStartOffset
== 30,
2861 "Test 1-9-1: mStartOffset should be the smallest offset");
2862 MOZ_ASSERT(mRemovedEndOffset
== 43, // 38 - (30 - 35)
2863 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2865 "without already removed text");
2867 mAddedEndOffset
== 36,
2868 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2871 /****************************************************************************
2873 ****************************************************************************/
2875 // Replacing text in around end of added text (becomes shorter) (not sure
2876 // if actually occurs)
2877 MergeWith(TextChangeData(50, 50, 55, false, false));
2878 MergeWith(TextChangeData(53, 60, 54, false, false));
2879 MOZ_ASSERT(mStartOffset
== 50,
2880 "Test 2-1-1: mStartOffset should be the smallest offset");
2881 MOZ_ASSERT(mRemovedEndOffset
== 55, // 60 - (55 - 50)
2882 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2884 "without already added text length");
2886 mAddedEndOffset
== 54,
2887 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2890 // Replacing text around end of added text (becomes longer) (not sure
2891 // if actually occurs)
2892 MergeWith(TextChangeData(50, 50, 55, false, false));
2893 MergeWith(TextChangeData(54, 62, 68, false, false));
2894 MOZ_ASSERT(mStartOffset
== 50,
2895 "Test 2-2-1: mStartOffset should be the smallest offset");
2896 MOZ_ASSERT(mRemovedEndOffset
== 57, // 62 - (55 - 50)
2897 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2899 "without already added text length");
2901 mAddedEndOffset
== 68,
2902 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2905 // Replacing text around end of replaced text (became shorter) (not sure if
2907 MergeWith(TextChangeData(36, 48, 45, false, false));
2908 MergeWith(TextChangeData(43, 50, 49, false, false));
2909 MOZ_ASSERT(mStartOffset
== 36,
2910 "Test 2-3-1: mStartOffset should be the smallest offset");
2911 MOZ_ASSERT(mRemovedEndOffset
== 53, // 50 - (45 - 48)
2912 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2914 "without already removed text length");
2916 mAddedEndOffset
== 49,
2917 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2920 // Replacing text around end of replaced text (became longer) (not sure if
2922 MergeWith(TextChangeData(36, 52, 53, false, false));
2923 MergeWith(TextChangeData(43, 68, 61, false, false));
2924 MOZ_ASSERT(mStartOffset
== 36,
2925 "Test 2-4-1: mStartOffset should be the smallest offset");
2926 MOZ_ASSERT(mRemovedEndOffset
== 67, // 68 - (53 - 52)
2927 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2929 "without already added text length");
2931 mAddedEndOffset
== 61,
2932 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2935 /****************************************************************************
2937 ****************************************************************************/
2939 // Appending text in already added text (not sure if actually occurs)
2940 MergeWith(TextChangeData(10, 10, 20, false, false));
2941 MergeWith(TextChangeData(15, 15, 30, false, false));
2942 MOZ_ASSERT(mStartOffset
== 10,
2943 "Test 3-1-1: mStartOffset should be the smallest offset");
2944 MOZ_ASSERT(mRemovedEndOffset
== 10,
2945 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2948 mAddedEndOffset
== 35, // 20 + (30 - 15)
2949 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2950 "added text length by the new change");
2953 // Replacing text in added text (not sure if actually occurs)
2954 MergeWith(TextChangeData(50, 50, 55, false, false));
2955 MergeWith(TextChangeData(52, 53, 56, false, false));
2956 MOZ_ASSERT(mStartOffset
== 50,
2957 "Test 3-2-1: mStartOffset should be the smallest offset");
2958 MOZ_ASSERT(mRemovedEndOffset
== 50,
2959 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2962 mAddedEndOffset
== 58, // 55 + (56 - 53)
2963 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2964 "added text length by the new change");
2967 // Replacing text in replaced text (became shorter) (not sure if actually
2969 MergeWith(TextChangeData(36, 48, 45, false, false));
2970 MergeWith(TextChangeData(37, 38, 50, false, false));
2971 MOZ_ASSERT(mStartOffset
== 36,
2972 "Test 3-3-1: mStartOffset should be the smallest offset");
2973 MOZ_ASSERT(mRemovedEndOffset
== 48,
2974 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2977 mAddedEndOffset
== 57, // 45 + (50 - 38)
2978 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2979 "added text length by the new change");
2982 // Replacing text in replaced text (became longer) (not sure if actually
2984 MergeWith(TextChangeData(32, 48, 53, false, false));
2985 MergeWith(TextChangeData(43, 50, 52, false, false));
2986 MOZ_ASSERT(mStartOffset
== 32,
2987 "Test 3-4-1: mStartOffset should be the smallest offset");
2988 MOZ_ASSERT(mRemovedEndOffset
== 48,
2989 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2991 "without already added text length");
2993 mAddedEndOffset
== 55, // 53 + (52 - 50)
2994 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2995 "added text length by the new change");
2998 // Replacing text in replaced text (became shorter) (not sure if actually
3000 MergeWith(TextChangeData(36, 48, 50, false, false));
3001 MergeWith(TextChangeData(37, 49, 47, false, false));
3002 MOZ_ASSERT(mStartOffset
== 36,
3003 "Test 3-5-1: mStartOffset should be the smallest offset");
3005 mRemovedEndOffset
== 48,
3006 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
3008 MOZ_ASSERT(mAddedEndOffset
== 48, // 50 + (47 - 49)
3009 "Test 3-5-3: mAddedEndOffset should be the first end of added "
3011 "removed text length by the new change");
3014 // Replacing text in replaced text (became longer) (not sure if actually
3016 MergeWith(TextChangeData(32, 48, 53, false, false));
3017 MergeWith(TextChangeData(43, 50, 47, false, false));
3018 MOZ_ASSERT(mStartOffset
== 32,
3019 "Test 3-6-1: mStartOffset should be the smallest offset");
3020 MOZ_ASSERT(mRemovedEndOffset
== 48,
3021 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
3023 "without already added text length");
3024 MOZ_ASSERT(mAddedEndOffset
== 50, // 53 + (47 - 50)
3025 "Test 3-6-3: mAddedEndOffset should be the first end of added "
3027 "removed text length by the new change");
3030 /****************************************************************************
3032 ****************************************************************************/
3034 // Replacing text all of already append text (not sure if actually occurs)
3035 MergeWith(TextChangeData(50, 50, 55, false, false));
3036 MergeWith(TextChangeData(44, 66, 68, false, false));
3037 MOZ_ASSERT(mStartOffset
== 44,
3038 "Test 4-1-1: mStartOffset should be the smallest offset");
3039 MOZ_ASSERT(mRemovedEndOffset
== 61, // 66 - (55 - 50)
3040 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
3042 "without already added text length");
3044 mAddedEndOffset
== 68,
3045 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3048 // Replacing text around a point in which text was removed (not sure if
3050 MergeWith(TextChangeData(50, 62, 50, false, false));
3051 MergeWith(TextChangeData(44, 66, 68, false, false));
3052 MOZ_ASSERT(mStartOffset
== 44,
3053 "Test 4-2-1: mStartOffset should be the smallest offset");
3054 MOZ_ASSERT(mRemovedEndOffset
== 78, // 66 - (50 - 62)
3055 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
3057 "without already removed text length");
3059 mAddedEndOffset
== 68,
3060 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3063 // Replacing text all replaced text (became shorter) (not sure if actually
3065 MergeWith(TextChangeData(50, 62, 60, false, false));
3066 MergeWith(TextChangeData(49, 128, 130, false, false));
3067 MOZ_ASSERT(mStartOffset
== 49,
3068 "Test 4-3-1: mStartOffset should be the smallest offset");
3069 MOZ_ASSERT(mRemovedEndOffset
== 130, // 128 - (60 - 62)
3070 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
3072 "without already removed text length");
3074 mAddedEndOffset
== 130,
3075 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3078 // Replacing text all replaced text (became longer) (not sure if actually
3080 MergeWith(TextChangeData(50, 61, 73, false, false));
3081 MergeWith(TextChangeData(44, 100, 50, false, false));
3082 MOZ_ASSERT(mStartOffset
== 44,
3083 "Test 4-4-1: mStartOffset should be the smallest offset");
3084 MOZ_ASSERT(mRemovedEndOffset
== 88, // 100 - (73 - 61)
3085 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
3087 "with already added text length");
3089 mAddedEndOffset
== 50,
3090 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3093 /****************************************************************************
3095 ****************************************************************************/
3097 // Replacing text around start of added text (not sure if actually occurs)
3098 MergeWith(TextChangeData(50, 50, 55, false, false));
3099 MergeWith(TextChangeData(48, 52, 49, false, false));
3100 MOZ_ASSERT(mStartOffset
== 48,
3101 "Test 5-1-1: mStartOffset should be the smallest offset");
3103 mRemovedEndOffset
== 50,
3104 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
3107 mAddedEndOffset
== 52, // 55 + (52 - 49)
3108 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
3109 "added text length by the new change");
3112 // Replacing text around start of replaced text (became shorter) (not sure if
3114 MergeWith(TextChangeData(50, 60, 58, false, false));
3115 MergeWith(TextChangeData(43, 50, 48, false, false));
3116 MOZ_ASSERT(mStartOffset
== 43,
3117 "Test 5-2-1: mStartOffset should be the smallest offset");
3119 mRemovedEndOffset
== 60,
3120 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3122 MOZ_ASSERT(mAddedEndOffset
== 56, // 58 + (48 - 50)
3123 "Test 5-2-3: mAddedEndOffset should be the first end of added "
3125 "removed text length by the new change");
3128 // Replacing text around start of replaced text (became longer) (not sure if
3130 MergeWith(TextChangeData(50, 60, 68, false, false));
3131 MergeWith(TextChangeData(43, 55, 53, false, false));
3132 MOZ_ASSERT(mStartOffset
== 43,
3133 "Test 5-3-1: mStartOffset should be the smallest offset");
3135 mRemovedEndOffset
== 60,
3136 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3138 MOZ_ASSERT(mAddedEndOffset
== 66, // 68 + (53 - 55)
3139 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3141 "removed text length by the new change");
3144 // Replacing text around start of replaced text (became shorter) (not sure if
3146 MergeWith(TextChangeData(50, 60, 58, false, false));
3147 MergeWith(TextChangeData(43, 50, 128, false, false));
3148 MOZ_ASSERT(mStartOffset
== 43,
3149 "Test 5-4-1: mStartOffset should be the smallest offset");
3151 mRemovedEndOffset
== 60,
3152 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
3155 mAddedEndOffset
== 136, // 58 + (128 - 50)
3156 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
3157 "added text length by the new change");
3160 // Replacing text around start of replaced text (became longer) (not sure if
3162 MergeWith(TextChangeData(50, 60, 68, false, false));
3163 MergeWith(TextChangeData(43, 55, 65, false, false));
3164 MOZ_ASSERT(mStartOffset
== 43,
3165 "Test 5-5-1: mStartOffset should be the smallest offset");
3167 mRemovedEndOffset
== 60,
3168 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
3171 mAddedEndOffset
== 78, // 68 + (65 - 55)
3172 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
3173 "added text length by the new change");
3176 /****************************************************************************
3178 ****************************************************************************/
3180 // Appending text before already added text (not sure if actually occurs)
3181 MergeWith(TextChangeData(30, 30, 45, false, false));
3182 MergeWith(TextChangeData(10, 10, 20, false, false));
3183 MOZ_ASSERT(mStartOffset
== 10,
3184 "Test 6-1-1: mStartOffset should be the smallest offset");
3186 mRemovedEndOffset
== 30,
3187 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3190 mAddedEndOffset
== 55, // 45 + (20 - 10)
3191 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3192 "added text length by the new change");
3195 // Removing text before already removed text (not sure if actually occurs)
3196 MergeWith(TextChangeData(30, 35, 30, false, false));
3197 MergeWith(TextChangeData(10, 25, 10, false, false));
3198 MOZ_ASSERT(mStartOffset
== 10,
3199 "Test 6-2-1: mStartOffset should be the smallest offset");
3201 mRemovedEndOffset
== 35,
3202 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3205 mAddedEndOffset
== 15, // 30 - (25 - 10)
3206 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3207 "removed text length by the new change");
3210 // Replacing text before already replaced text (not sure if actually occurs)
3211 MergeWith(TextChangeData(50, 65, 70, false, false));
3212 MergeWith(TextChangeData(13, 24, 15, false, false));
3213 MOZ_ASSERT(mStartOffset
== 13,
3214 "Test 6-3-1: mStartOffset should be the smallest offset");
3216 mRemovedEndOffset
== 65,
3217 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3219 MOZ_ASSERT(mAddedEndOffset
== 61, // 70 + (15 - 24)
3220 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3222 "removed text length by the new change");
3225 // Replacing text before already replaced text (not sure if actually occurs)
3226 MergeWith(TextChangeData(50, 65, 70, false, false));
3227 MergeWith(TextChangeData(13, 24, 36, false, false));
3228 MOZ_ASSERT(mStartOffset
== 13,
3229 "Test 6-4-1: mStartOffset should be the smallest offset");
3231 mRemovedEndOffset
== 65,
3232 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3234 MOZ_ASSERT(mAddedEndOffset
== 82, // 70 + (36 - 24)
3235 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3237 "removed text length by the new change");
3241 #endif // #ifdef DEBUG
3243 } // namespace mozilla::widget
3246 //////////////////////////////////////////////////////////////
3248 // Convert a GUI event message code to a string.
3249 // Makes it a lot easier to debug events.
3251 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3252 // for a DebugPrintEvent() function that uses
3255 //////////////////////////////////////////////////////////////
3257 nsAutoString
nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent
* aGuiEvent
) {
3258 NS_ASSERTION(nullptr != aGuiEvent
, "cmon, null gui event.");
3260 nsAutoString
eventName(u
"UNKNOWN"_ns
);
3262 # define _ASSIGN_eventName(_value, _name) \
3264 eventName.AssignLiteral(_name); \
3267 switch (aGuiEvent
->mMessage
) {
3268 _ASSIGN_eventName(eBlur
, "eBlur");
3269 _ASSIGN_eventName(eDrop
, "eDrop");
3270 _ASSIGN_eventName(eDragEnter
, "eDragEnter");
3271 _ASSIGN_eventName(eDragExit
, "eDragExit");
3272 _ASSIGN_eventName(eDragOver
, "eDragOver");
3273 _ASSIGN_eventName(eEditorInput
, "eEditorInput");
3274 _ASSIGN_eventName(eFocus
, "eFocus");
3275 _ASSIGN_eventName(eFocusIn
, "eFocusIn");
3276 _ASSIGN_eventName(eFocusOut
, "eFocusOut");
3277 _ASSIGN_eventName(eFormSelect
, "eFormSelect");
3278 _ASSIGN_eventName(eFormChange
, "eFormChange");
3279 _ASSIGN_eventName(eFormReset
, "eFormReset");
3280 _ASSIGN_eventName(eFormSubmit
, "eFormSubmit");
3281 _ASSIGN_eventName(eImageAbort
, "eImageAbort");
3282 _ASSIGN_eventName(eLoadError
, "eLoadError");
3283 _ASSIGN_eventName(eKeyDown
, "eKeyDown");
3284 _ASSIGN_eventName(eKeyPress
, "eKeyPress");
3285 _ASSIGN_eventName(eKeyUp
, "eKeyUp");
3286 _ASSIGN_eventName(eMouseEnterIntoWidget
, "eMouseEnterIntoWidget");
3287 _ASSIGN_eventName(eMouseExitFromWidget
, "eMouseExitFromWidget");
3288 _ASSIGN_eventName(eMouseDown
, "eMouseDown");
3289 _ASSIGN_eventName(eMouseUp
, "eMouseUp");
3290 _ASSIGN_eventName(eMouseClick
, "eMouseClick");
3291 _ASSIGN_eventName(eMouseAuxClick
, "eMouseAuxClick");
3292 _ASSIGN_eventName(eMouseDoubleClick
, "eMouseDoubleClick");
3293 _ASSIGN_eventName(eMouseMove
, "eMouseMove");
3294 _ASSIGN_eventName(eLoad
, "eLoad");
3295 _ASSIGN_eventName(ePopState
, "ePopState");
3296 _ASSIGN_eventName(eBeforeScriptExecute
, "eBeforeScriptExecute");
3297 _ASSIGN_eventName(eAfterScriptExecute
, "eAfterScriptExecute");
3298 _ASSIGN_eventName(eUnload
, "eUnload");
3299 _ASSIGN_eventName(eHashChange
, "eHashChange");
3300 _ASSIGN_eventName(eReadyStateChange
, "eReadyStateChange");
3301 _ASSIGN_eventName(eXULBroadcast
, "eXULBroadcast");
3302 _ASSIGN_eventName(eXULCommandUpdate
, "eXULCommandUpdate");
3304 # undef _ASSIGN_eventName
3307 eventName
.AssignLiteral("UNKNOWN: ");
3308 eventName
.AppendInt(aGuiEvent
->mMessage
);
3312 return nsAutoString(eventName
);
3314 //////////////////////////////////////////////////////////////
3316 // Code to deal with paint and event debug prefs.
3318 //////////////////////////////////////////////////////////////
3324 static PrefPair debug_PrefValues
[] = {
3325 {"nglayout.debug.crossing_event_dumping", false},
3326 {"nglayout.debug.event_dumping", false},
3327 {"nglayout.debug.invalidate_dumping", false},
3328 {"nglayout.debug.motion_event_dumping", false},
3329 {"nglayout.debug.paint_dumping", false}};
3331 //////////////////////////////////////////////////////////////
3332 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName
) {
3333 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3335 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3336 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3337 return debug_PrefValues
[i
].value
;
3343 //////////////////////////////////////////////////////////////
3344 static void debug_SetCachedBoolPref(const char* aPrefName
, bool aValue
) {
3345 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3347 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3348 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3349 debug_PrefValues
[i
].value
= aValue
;
3355 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3358 //////////////////////////////////////////////////////////////
3359 class Debug_PrefObserver final
: public nsIObserver
{
3360 ~Debug_PrefObserver() = default;
3367 NS_IMPL_ISUPPORTS(Debug_PrefObserver
, nsIObserver
)
3370 Debug_PrefObserver::Observe(nsISupports
* subject
, const char* topic
,
3371 const char16_t
* data
) {
3372 NS_ConvertUTF16toUTF8
prefName(data
);
3374 bool value
= Preferences::GetBool(prefName
.get(), false);
3375 debug_SetCachedBoolPref(prefName
.get(), value
);
3379 //////////////////////////////////////////////////////////////
3380 /* static */ void debug_RegisterPrefCallbacks() {
3381 static bool once
= true;
3389 nsCOMPtr
<nsIObserver
> obs(new Debug_PrefObserver());
3390 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3391 // Initialize the pref values
3392 debug_PrefValues
[i
].value
=
3393 Preferences::GetBool(debug_PrefValues
[i
].name
, false);
3396 // Register callbacks for when these change
3398 name
.AssignLiteral(debug_PrefValues
[i
].name
,
3399 strlen(debug_PrefValues
[i
].name
));
3400 Preferences::AddStrongObserver(obs
, name
);
3404 //////////////////////////////////////////////////////////////
3405 static int32_t _GetPrintCount() {
3406 static int32_t sCount
= 0;
3410 //////////////////////////////////////////////////////////////
3412 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3413 WidgetGUIEvent
* aGuiEvent
,
3414 const char* aWidgetName
, int32_t aWindowID
) {
3415 if (aGuiEvent
->mMessage
== eMouseMove
) {
3416 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3419 if (aGuiEvent
->mMessage
== eMouseEnterIntoWidget
||
3420 aGuiEvent
->mMessage
== eMouseExitFromWidget
) {
3421 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3425 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3427 NS_LossyConvertUTF16toASCII
tempString(
3428 debug_GuiEventToString(aGuiEvent
).get());
3430 fprintf(aFileOut
, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3431 _GetPrintCount(), tempString
.get(), (void*)aWidget
, aWidgetName
,
3432 aWindowID
, aGuiEvent
->mRefPoint
.x
.value
,
3433 aGuiEvent
->mRefPoint
.y
.value
);
3435 //////////////////////////////////////////////////////////////
3437 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3438 const nsIntRegion
& aRegion
,
3439 const char* aWidgetName
,
3440 int32_t aWindowID
) {
3441 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3442 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3444 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3446 nsIntRect rect
= aRegion
.GetBounds();
3448 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3450 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
, rect
.X(),
3451 rect
.Y(), rect
.Width(), rect
.Height());
3453 fprintf(aFileOut
, "\n");
3455 //////////////////////////////////////////////////////////////
3457 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut
, nsIWidget
* aWidget
,
3458 const LayoutDeviceIntRect
* aRect
,
3459 const char* aWidgetName
,
3460 int32_t aWindowID
) {
3461 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3463 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3464 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3466 fprintf(aFileOut
, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3467 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
);
3470 fprintf(aFileOut
, " rect=%3d,%-3d %3d,%-3d", aRect
->X(), aRect
->Y(),
3471 aRect
->Width(), aRect
->Height());
3473 fprintf(aFileOut
, " rect=%-15s", "none");
3476 fprintf(aFileOut
, "\n");
3478 //////////////////////////////////////////////////////////////