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 #ifdef NOISY_WIDGET_LEAKS
160 printf("WIDGETS+ = %d\n", gNumWidgets
);
164 debug_RegisterPrefCallbacks();
167 mShutdownObserver
= new WidgetShutdownObserver(this);
170 NS_IMPL_ISUPPORTS(WidgetShutdownObserver
, nsIObserver
)
172 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget
* aWidget
)
173 : mWidget(aWidget
), mRegistered(false) {
177 WidgetShutdownObserver::~WidgetShutdownObserver() {
178 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
179 // gets torn down. The observer service and nsBaseWidget have a ref on us
180 // so nsBaseWidget has to call Unregister and then clear its ref.
184 WidgetShutdownObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
185 const char16_t
* aData
) {
189 if (!strcmp(aTopic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
)) {
190 RefPtr
<nsBaseWidget
> widget(mWidget
);
192 } else if (!strcmp(aTopic
, "quit-application")) {
193 RefPtr
<nsBaseWidget
> widget(mWidget
);
199 void WidgetShutdownObserver::Register() {
202 nsContentUtils::RegisterShutdownObserver(this);
204 #ifndef MOZ_WIDGET_ANDROID
205 // The primary purpose of observing quit-application is
206 // to avoid leaking a widget on Windows when nothing else
207 // breaks the circular reference between the widget and
208 // TSFTextStore. However, our Android IME code crashes if
209 // doing this on Android, so let's not do this on Android.
210 // Doing this on Gtk and Mac just in case.
211 nsCOMPtr
<nsIObserverService
> observerService
=
212 mozilla::services::GetObserverService();
213 if (observerService
) {
214 observerService
->AddObserver(this, "quit-application", false);
220 void WidgetShutdownObserver::Unregister() {
224 #ifndef MOZ_WIDGET_ANDROID
225 nsCOMPtr
<nsIObserverService
> observerService
=
226 mozilla::services::GetObserverService();
227 if (observerService
) {
228 observerService
->RemoveObserver(this, "quit-application");
232 nsContentUtils::UnregisterShutdownObserver(this);
237 #define INTL_APP_LOCALES_CHANGED "intl:app-locales-changed"
239 NS_IMPL_ISUPPORTS(LocalesChangedObserver
, nsIObserver
)
241 LocalesChangedObserver::LocalesChangedObserver(nsBaseWidget
* aWidget
)
242 : mWidget(aWidget
), mRegistered(false) {
246 LocalesChangedObserver::~LocalesChangedObserver() {
247 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
248 // gets torn down. The observer service and nsBaseWidget have a ref on us
249 // so nsBaseWidget has to call Unregister and then clear its ref.
253 LocalesChangedObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
254 const char16_t
* aData
) {
258 if (!strcmp(aTopic
, INTL_APP_LOCALES_CHANGED
)) {
259 RefPtr
<nsBaseWidget
> widget(mWidget
);
260 widget
->LocalesChanged();
265 void LocalesChangedObserver::Register() {
270 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
272 obs
->AddObserver(this, INTL_APP_LOCALES_CHANGED
, true);
275 // Locale might be update before registering
276 RefPtr
<nsBaseWidget
> widget(mWidget
);
277 widget
->LocalesChanged();
282 void LocalesChangedObserver::Unregister() {
287 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
289 obs
->RemoveObserver(this, INTL_APP_LOCALES_CHANGED
);
296 void nsBaseWidget::Shutdown() {
297 NotifyLiveResizeStopped();
299 FreeLocalesChangedObserver();
300 FreeShutdownObserver();
303 void nsBaseWidget::QuitIME() {
304 IMEStateManager::WidgetOnQuit(this);
305 this->mIMEHasQuit
= true;
308 void nsBaseWidget::DestroyCompositor() {
309 RevokeTransactionIdAllocator();
311 // We release this before releasing the compositor, since it may hold the
312 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
313 // trigger a paint, creating a new compositor, and we don't want to re-use
314 // the old vsync dispatcher.
315 if (mCompositorVsyncDispatcher
) {
316 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
318 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
319 mCompositorVsyncDispatcher
->Shutdown();
320 mCompositorVsyncDispatcher
= nullptr;
323 // The compositor shutdown sequence looks like this:
324 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
325 // 2. CompositorBridgeChild synchronously sends WillClose.
326 // 3. CompositorBridgeParent releases some resources (such as the layer
327 // manager, compositor, and widget).
328 // 4. CompositorBridgeChild::Destroy returns.
329 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
330 // compositor thread when the I/O thread closes the IPC channel.
331 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
332 // releases the reference CompositorBridgeParent holds to itself.
334 // When CompositorSession::Shutdown returns, we assume the compositor is gone
335 // or will be gone very soon.
336 if (mCompositorSession
) {
337 ReleaseContentController();
339 SetCompositorWidgetDelegate(nullptr);
340 mCompositorBridgeChild
= nullptr;
341 mCompositorSession
->Shutdown();
342 mCompositorSession
= nullptr;
346 // This prevents the layer manager from starting a new transaction during
348 void nsBaseWidget::RevokeTransactionIdAllocator() {
349 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
352 mWindowRenderer
->AsWebRender()->SetTransactionIdAllocator(nullptr);
355 void nsBaseWidget::ReleaseContentController() {
356 if (mRootContentController
) {
357 mRootContentController
->Destroy();
358 mRootContentController
= nullptr;
362 void nsBaseWidget::DestroyLayerManager() {
363 if (mWindowRenderer
) {
364 mWindowRenderer
->Destroy();
365 mWindowRenderer
= nullptr;
370 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
372 void nsBaseWidget::FreeShutdownObserver() {
373 if (mShutdownObserver
) {
374 mShutdownObserver
->Unregister();
376 mShutdownObserver
= nullptr;
379 void nsBaseWidget::FreeLocalesChangedObserver() {
380 if (mLocalesChangedObserver
) {
381 mLocalesChangedObserver
->Unregister();
383 mLocalesChangedObserver
= nullptr;
386 //-------------------------------------------------------------------------
388 // nsBaseWidget destructor
390 //-------------------------------------------------------------------------
392 nsBaseWidget::~nsBaseWidget() {
394 mSwipeTracker
->Destroy();
395 mSwipeTracker
= nullptr;
398 IMEStateManager::WidgetDestroyed(this);
400 FreeLocalesChangedObserver();
401 FreeShutdownObserver();
402 DestroyLayerManager();
404 #ifdef NOISY_WIDGET_LEAKS
406 printf("WIDGETS- = %d\n", gNumWidgets
);
410 //-------------------------------------------------------------------------
414 //-------------------------------------------------------------------------
415 void nsBaseWidget::BaseCreate(nsIWidget
* aParent
, widget::InitData
* aInitData
) {
417 mWindowType
= aInitData
->mWindowType
;
418 mBorderStyle
= aInitData
->mBorderStyle
;
419 mPopupLevel
= aInitData
->mPopupLevel
;
420 mPopupType
= aInitData
->mPopupHint
;
421 mHasRemoteContent
= aInitData
->mHasRemoteContent
;
425 aParent
->AddChild(this);
429 //-------------------------------------------------------------------------
431 // Accessor functions to get/set the client data
433 //-------------------------------------------------------------------------
435 nsIWidgetListener
* nsBaseWidget::GetWidgetListener() const {
436 return mWidgetListener
;
439 void nsBaseWidget::SetWidgetListener(nsIWidgetListener
* aWidgetListener
) {
440 mWidgetListener
= aWidgetListener
;
443 already_AddRefed
<nsIWidget
> nsBaseWidget::CreateChild(
444 const LayoutDeviceIntRect
& aRect
, widget::InitData
* aInitData
,
445 bool aForceUseIWidgetParent
) {
446 nsIWidget
* parent
= this;
447 nsNativeWidget nativeParent
= nullptr;
449 if (!aForceUseIWidgetParent
) {
450 // Use only either parent or nativeParent, not both, to match
451 // existing code. Eventually Create() should be divested of its
452 // nativeWidget parameter.
453 nativeParent
= parent
? parent
->GetNativeData(NS_NATIVE_WIDGET
) : nullptr;
454 parent
= nativeParent
? nullptr : parent
;
455 MOZ_ASSERT(!parent
|| !nativeParent
, "messed up logic");
458 nsCOMPtr
<nsIWidget
> widget
;
459 if (aInitData
&& aInitData
->mWindowType
== WindowType::Popup
) {
460 widget
= AllocateChildPopupWidget();
462 widget
= nsIWidget::CreateChildWindow();
465 if (widget
&& mNeedFastSnaphot
) {
466 widget
->SetNeedFastSnaphot();
470 NS_SUCCEEDED(widget
->Create(parent
, nativeParent
, aRect
, aInitData
))) {
471 return widget
.forget();
477 // Attach a view to our widget which we'll send events to.
478 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents
) {
479 NS_ASSERTION((mWindowType
== WindowType::TopLevel
||
480 mWindowType
== WindowType::Dialog
||
481 mWindowType
== WindowType::Invisible
||
482 mWindowType
== WindowType::Child
),
483 "Can't attach to window of that type");
485 mUseAttachedEvents
= aUseAttachedEvents
;
488 nsIWidgetListener
* nsBaseWidget::GetAttachedWidgetListener() const {
489 return mAttachedWidgetListener
;
492 nsIWidgetListener
* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
493 return mPreviouslyAttachedWidgetListener
;
496 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
497 nsIWidgetListener
* aListener
) {
498 mPreviouslyAttachedWidgetListener
= aListener
;
501 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener
* aListener
) {
502 mAttachedWidgetListener
= aListener
;
505 //-------------------------------------------------------------------------
507 // Close this nsBaseWidget
509 //-------------------------------------------------------------------------
510 void nsBaseWidget::Destroy() {
513 // Just in case our parent is the only ref to us
514 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
515 // disconnect from the parent
516 nsIWidget
* parent
= GetParent();
518 parent
->RemoveChild(this);
522 //-------------------------------------------------------------------------
524 // Get this nsBaseWidget parent
526 //-------------------------------------------------------------------------
527 nsIWidget
* nsBaseWidget::GetParent(void) { return nullptr; }
529 //-------------------------------------------------------------------------
531 // Get this nsBaseWidget top level widget
533 //-------------------------------------------------------------------------
534 nsIWidget
* nsBaseWidget::GetTopLevelWidget() {
535 nsIWidget
*topLevelWidget
= nullptr, *widget
= this;
537 topLevelWidget
= widget
;
538 widget
= widget
->GetParent();
540 return topLevelWidget
;
543 //-------------------------------------------------------------------------
545 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
547 //-------------------------------------------------------------------------
548 nsIWidget
* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
550 float nsBaseWidget::GetDPI() { return 96.0f
; }
552 CSSToLayoutDeviceScale
nsIWidget::GetDefaultScale() {
553 double devPixelsPerCSSPixel
= StaticPrefs::layout_css_devPixelsPerPx();
555 if (devPixelsPerCSSPixel
<= 0.0) {
556 devPixelsPerCSSPixel
= GetDefaultScaleInternal();
559 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel
);
562 nsIntSize
nsIWidget::CustomCursorSize(const Cursor
& aCursor
) {
563 MOZ_ASSERT(aCursor
.IsCustom());
566 aCursor
.mContainer
->GetWidth(&width
);
567 aCursor
.mContainer
->GetHeight(&height
);
568 aCursor
.mResolution
.ApplyTo(width
, height
);
569 return {width
, height
};
572 LayoutDeviceIntSize
nsIWidget::ClientToWindowSizeDifference() {
573 auto margin
= ClientToWindowMargin();
574 MOZ_ASSERT(margin
.top
>= 0, "Window should be bigger than client area");
575 MOZ_ASSERT(margin
.left
>= 0, "Window should be bigger than client area");
576 MOZ_ASSERT(margin
.right
>= 0, "Window should be bigger than client area");
577 MOZ_ASSERT(margin
.bottom
>= 0, "Window should be bigger than client area");
578 return {margin
.LeftRight(), margin
.TopBottom()};
581 RefPtr
<mozilla::VsyncDispatcher
> nsIWidget::GetVsyncDispatcher() {
585 //-------------------------------------------------------------------------
587 // Add a child to the list of children
589 //-------------------------------------------------------------------------
590 void nsBaseWidget::AddChild(nsIWidget
* aChild
) {
591 MOZ_ASSERT(!aChild
->GetNextSibling() && !aChild
->GetPrevSibling(),
592 "aChild not properly removed from its old child list");
595 mFirstChild
= mLastChild
= aChild
;
597 // append to the list
598 MOZ_ASSERT(mLastChild
);
599 MOZ_ASSERT(!mLastChild
->GetNextSibling());
600 mLastChild
->SetNextSibling(aChild
);
601 aChild
->SetPrevSibling(mLastChild
);
606 //-------------------------------------------------------------------------
608 // Remove a child from the list of children
610 //-------------------------------------------------------------------------
611 void nsBaseWidget::RemoveChild(nsIWidget
* aChild
) {
614 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
615 // null and we'll just have to do without this assertion.
616 nsIWidget
* parent
= aChild
->GetParent();
617 NS_ASSERTION(!parent
|| parent
== this, "Not one of our kids!");
619 MOZ_RELEASE_ASSERT(aChild
->GetParent() == this, "Not one of our kids!");
623 if (mLastChild
== aChild
) {
624 mLastChild
= mLastChild
->GetPrevSibling();
626 if (mFirstChild
== aChild
) {
627 mFirstChild
= mFirstChild
->GetNextSibling();
630 // Now remove from the list. Make sure that we pass ownership of the tail
631 // of the list correctly before we have aChild let go of it.
632 nsIWidget
* prev
= aChild
->GetPrevSibling();
633 nsIWidget
* next
= aChild
->GetNextSibling();
635 prev
->SetNextSibling(next
);
638 next
->SetPrevSibling(prev
);
641 aChild
->SetNextSibling(nullptr);
642 aChild
->SetPrevSibling(nullptr);
645 //-------------------------------------------------------------------------
647 // Sets widget's position within its parent's child list.
649 //-------------------------------------------------------------------------
650 void nsBaseWidget::SetZIndex(int32_t aZIndex
) {
651 // Hold a ref to ourselves just in case, since we're going to remove
653 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
657 // reorder this child in its parent's list.
658 auto* parent
= static_cast<nsBaseWidget
*>(GetParent());
660 parent
->RemoveChild(this);
661 // Scope sib outside the for loop so we can check it afterward
662 nsIWidget
* sib
= parent
->GetFirstChild();
663 for (; sib
; sib
= sib
->GetNextSibling()) {
664 int32_t childZIndex
= GetZIndex();
665 if (aZIndex
< childZIndex
) {
666 // Insert ourselves before sib
667 nsIWidget
* prev
= sib
->GetPrevSibling();
670 sib
->SetPrevSibling(this);
672 prev
->SetNextSibling(this);
674 NS_ASSERTION(sib
== parent
->mFirstChild
, "Broken child list");
675 // We've taken ownership of sib, so it's safe to have parent let
677 parent
->mFirstChild
= this;
679 PlaceBehind(eZPlacementBelow
, sib
, false);
683 // were we added to the list?
685 parent
->AddChild(this);
690 void nsBaseWidget::GetWorkspaceID(nsAString
& workspaceID
) {
691 workspaceID
.Truncate();
694 void nsBaseWidget::MoveToWorkspace(const nsAString
& workspaceID
) {
698 //-------------------------------------------------------------------------
700 // Get this component cursor
702 //-------------------------------------------------------------------------
704 void nsBaseWidget::SetCursor(const Cursor
& aCursor
) { mCursor
= aCursor
; }
706 //-------------------------------------------------------------------------
708 // Window transparency methods
710 //-------------------------------------------------------------------------
712 void nsBaseWidget::SetTransparencyMode(TransparencyMode aMode
) {}
714 TransparencyMode
nsBaseWidget::GetTransparencyMode() {
715 return TransparencyMode::Opaque
;
719 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage
,
722 nsIRunnable
* aCallback
) {
723 MOZ_ASSERT_UNREACHABLE(
724 "Should never call PerformFullscreenTransition on nsBaseWidget");
727 //-------------------------------------------------------------------------
729 // Put the window into full-screen mode
731 //-------------------------------------------------------------------------
732 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen
) {
733 #define MOZ_FORMAT_RECT(fmtstr) "[" fmtstr "," fmtstr " " fmtstr "x" fmtstr "]"
734 #define MOZ_SPLAT_RECT(rect) \
735 (rect).X(), (rect).Y(), (rect).Width(), (rect).Height()
737 // Windows which can be made fullscreen are exactly those which are located on
738 // the desktop, rather than being a child of some other window.
739 MOZ_DIAGNOSTIC_ASSERT(BoundsUseDesktopPixels(),
740 "non-desktop windows cannot be made fullscreen");
742 // Ensure that the OS chrome is hidden/shown before we resize and/or exit the
745 // HideWindowChrome() may (depending on platform, implementation details, and
746 // OS-level user preferences) alter the reported size of the window. The
747 // obvious and principled solution is socks-and-shoes:
748 // - On entering fullscreen mode: hide window chrome, then perform resize.
749 // - On leaving fullscreen mode: unperform resize, then show window chrome.
751 // ... unfortunately, HideWindowChrome() requires Resize() to be called
752 // afterwards (see bug 498835), which prevents this from being done in a
753 // straightforward way.
755 // Instead, we always call HideWindowChrome() just before we call Resize().
756 // This at least ensures that our measurements are consistently taken in a
757 // pre-transition state.
759 // ... unfortunately again, coupling HideWindowChrome() to Resize() means that
760 // we have to worry about the possibility of control flows that don't call
761 // Resize() at all. (That shouldn't happen, but it's not trivial to rule out.)
762 // We therefore set up a fallback to fix up the OS chrome if it hasn't been
763 // done at exit time.
764 bool hasAdjustedOSChrome
= false;
765 const auto adjustOSChrome
= [&]() {
766 if (hasAdjustedOSChrome
) {
767 MOZ_ASSERT_UNREACHABLE("window chrome should only be adjusted once");
770 HideWindowChrome(aFullScreen
);
771 hasAdjustedOSChrome
= true;
773 const auto adjustChromeOnScopeExit
= MakeScopeExit([&]() {
774 if (hasAdjustedOSChrome
) {
778 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
779 ("window was not resized within InfallibleMakeFullScreen()"));
781 // Hide chrome and "resize" the window to its current size.
782 auto rect
= GetBounds();
784 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
787 // Attempt to resize to `rect`.
789 // Returns the actual rectangle resized to. (This may differ from `rect`, if
790 // the OS is unhappy with it. See bug 1786226.)
791 const auto doReposition
= [&](auto rect
) -> void {
792 static_assert(std::is_base_of_v
<DesktopPixel
,
793 std::remove_reference_t
<decltype(rect
)>>,
794 "doReposition requires a rectangle using desktop pixels");
796 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Debug
)) {
797 const DesktopRect previousSize
=
798 GetScreenBounds() / GetDesktopToDeviceScale();
799 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
800 ("before resize: " MOZ_FORMAT_RECT("%f"),
801 MOZ_SPLAT_RECT(previousSize
)));
805 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
807 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Warning
)) {
808 // `rect` may have any underlying data type; coerce to float to
809 // simplify printf-style logging
810 const gfx::RectTyped
<DesktopPixel
, float> rectAsFloat
{rect
};
812 // The OS may have objected to the target position. That's not necessarily
813 // a problem -- it'll happen regularly on Macs with camera notches in the
814 // monitor, for instance (see bug 1786226) -- but it probably deserves to
817 // Since there's floating-point math involved, the actual values may be
818 // off by a few ulps -- as an upper bound, perhaps 8 * FLT_EPSILON *
819 // max(MOZ_SPLAT_RECT(rect)) -- but 0.01 should be several orders of
820 // magnitude bigger than that.
822 const auto postResizeRectRaw
= GetScreenBounds();
823 const auto postResizeRect
= postResizeRectRaw
/ GetDesktopToDeviceScale();
824 const bool succeeded
= postResizeRect
.WithinEpsilonOf(rectAsFloat
, 0.01);
827 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
828 ("resized to: " MOZ_FORMAT_RECT("%f"),
829 MOZ_SPLAT_RECT(rectAsFloat
)));
831 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
832 ("attempted to resize to: " MOZ_FORMAT_RECT("%f"),
833 MOZ_SPLAT_RECT(rectAsFloat
)));
834 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
835 ("... but ended up at: " MOZ_FORMAT_RECT("%f"),
836 MOZ_SPLAT_RECT(postResizeRect
)));
840 sBaseWidgetLog
, LogLevel::Verbose
,
841 ("(... which, before DPI adjustment, is:" MOZ_FORMAT_RECT("%d") ")",
842 MOZ_SPLAT_RECT(postResizeRectRaw
)));
848 mSavedBounds
= Some(FullscreenSavedState());
850 // save current position
851 mSavedBounds
->windowRect
= GetScreenBounds() / GetDesktopToDeviceScale();
853 nsCOMPtr
<nsIScreen
> screen
= GetWidgetScreen();
858 // Move to fill the screen.
859 doReposition(screen
->GetRectDisplayPix());
860 // Save off the new position. (This may differ from GetRectDisplayPix(), if
861 // the OS was unhappy with it. See bug 1786226.)
862 mSavedBounds
->screenRect
= GetScreenBounds() / GetDesktopToDeviceScale();
865 // This should never happen, at present, since we don't make windows
866 // fullscreen at their creation time; but it's not logically impossible.
867 MOZ_ASSERT(false, "fullscreen window did not have saved position");
871 // Figure out where to go from here.
873 // Fortunately, since we're currently fullscreen (and other code should be
874 // handling _keeping_ us fullscreen even after display-layout changes),
875 // there's an obvious choice for which display we should attach to; all we
876 // need to determine is where on that display we should go.
878 const DesktopRect currentWinRect
=
879 GetScreenBounds() / GetDesktopToDeviceScale();
881 // Optimization: if where we are is where we were, then where we originally
882 // came from is where we're going to go.
883 if (currentWinRect
== DesktopRect(mSavedBounds
->screenRect
)) {
884 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
885 ("no location change detected; returning to saved location"));
886 doReposition(mSavedBounds
->windowRect
);
891 General case: figure out where we're going to go by dividing where we are
892 by where we were, and then multiplying by where we originally came from.
894 Less abstrusely: resize so that we occupy the same proportional position
895 on our current display after leaving fullscreen as we occupied on our
896 previous display before entering fullscreen.
898 (N.B.: We do not clamp. If we were only partially on the old display,
899 we'll be only partially on the new one, too.)
902 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
903 ("location change detected; computing new destination"));
905 // splat: convert an arbitrary Rect into a tuple, for syntactic convenience.
906 const auto splat
= [](auto rect
) {
907 return std::tuple(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height());
910 // remap: find the unique affine mapping which transforms `src` to `dst`,
911 // and apply it to `val`.
912 using Range
= std::pair
<float, float>;
913 const auto remap
= [](Range dst
, Range src
, float val
) {
914 // linear interpolation and its inverse: lerp(a, b, invlerp(a, b, t)) == t
915 const auto lerp
= [](float lo
, float hi
, float t
) {
916 return lo
+ t
* (hi
- lo
);
918 const auto invlerp
= [](float lo
, float hi
, float mid
) {
919 return (mid
- lo
) / (hi
- lo
);
922 const auto [dst_a
, dst_b
] = dst
;
923 const auto [src_a
, src_b
] = src
;
924 return lerp(dst_a
, dst_b
, invlerp(src_a
, src_b
, val
));
928 const auto [px
, py
, pw
, ph
] = splat(mSavedBounds
->windowRect
);
929 // source desktop rect
930 const auto [sx
, sy
, sw
, sh
] = splat(mSavedBounds
->screenRect
);
931 // target desktop rect
932 const auto [tx
, ty
, tw
, th
] = splat(currentWinRect
);
934 const float nx
= remap({tx
, tx
+ tw
}, {sx
, sx
+ sw
}, px
);
935 const float ny
= remap({ty
, ty
+ th
}, {sy
, sy
+ sh
}, py
);
936 const float nw
= remap({0, tw
}, {0, sw
}, pw
);
937 const float nh
= remap({0, th
}, {0, sh
}, ph
);
939 doReposition(DesktopRect
{nx
, ny
, nw
, nh
});
942 #undef MOZ_SPLAT_RECT
943 #undef MOZ_FORMAT_RECT
946 nsresult
nsBaseWidget::MakeFullScreen(bool aFullScreen
) {
947 InfallibleMakeFullScreen(aFullScreen
);
951 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
952 nsBaseWidget
* aWidget
, gfxContext
* aTarget
, BufferMode aDoubleBuffering
)
954 WindowRenderer
* renderer
= mWidget
->GetWindowRenderer();
955 if (renderer
->AsFallback()) {
956 mRenderer
= renderer
->AsFallback();
957 mRenderer
->SetTarget(aTarget
, aDoubleBuffering
);
961 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
963 mRenderer
->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE
);
967 bool nsBaseWidget::IsSmallPopup() const {
968 return mWindowType
== WindowType::Popup
&& mPopupType
!= PopupType::Panel
;
971 bool nsBaseWidget::ComputeShouldAccelerate() {
972 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING
) &&
973 (WidgetTypeSupportsAcceleration() ||
974 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
977 bool nsBaseWidget::UseAPZ() {
978 return (gfxPlatform::AsyncPanZoomEnabled() &&
979 (mWindowType
== WindowType::TopLevel
||
980 mWindowType
== WindowType::Child
||
981 ((mWindowType
== WindowType::Popup
||
982 mWindowType
== WindowType::Dialog
) &&
983 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
986 void nsBaseWidget::CreateCompositor() {
987 LayoutDeviceIntRect rect
= GetBounds();
988 CreateCompositor(rect
.Width(), rect
.Height());
991 void nsIWidget::PauseOrResumeCompositor(bool aPause
) {
992 auto* renderer
= GetRemoteRenderer();
997 renderer
->SendPause();
999 renderer
->SendResume();
1003 already_AddRefed
<GeckoContentController
>
1004 nsBaseWidget::CreateRootContentController() {
1005 RefPtr
<GeckoContentController
> controller
=
1006 new ChromeProcessController(this, mAPZEventState
, mAPZC
);
1007 return controller
.forget();
1010 void nsBaseWidget::ConfigureAPZCTreeManager() {
1011 MOZ_ASSERT(NS_IsMainThread());
1014 mAPZC
->SetDPI(GetDPI());
1016 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
1017 KeyboardMap map
= RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
1018 mAPZC
->SetKeyboardMap(map
);
1021 ContentReceivedInputBlockCallback
callback(
1022 [treeManager
= RefPtr
{mAPZC
.get()}](uint64_t aInputBlockId
,
1023 bool aPreventDefault
) {
1024 MOZ_ASSERT(NS_IsMainThread());
1025 treeManager
->ContentReceivedInputBlock(aInputBlockId
, aPreventDefault
);
1027 mAPZEventState
= new APZEventState(this, std::move(callback
));
1029 mRootContentController
= CreateRootContentController();
1030 if (mRootContentController
) {
1031 mCompositorSession
->SetContentController(mRootContentController
);
1034 // When APZ is enabled, we can actually enable raw touch events because we
1035 // have code that can deal with them properly. If APZ is not enabled, this
1036 // function doesn't get called.
1037 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
1038 RegisterTouchWindow();
1042 void nsBaseWidget::ConfigureAPZControllerThread() {
1043 // By default the controller thread is the main thread.
1044 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
1047 void nsBaseWidget::SetConfirmedTargetAPZC(
1048 uint64_t aInputBlockId
,
1049 const nsTArray
<ScrollableLayerGuid
>& aTargets
) const {
1050 mAPZC
->SetTargetAPZC(aInputBlockId
, aTargets
);
1053 void nsBaseWidget::UpdateZoomConstraints(
1054 const uint32_t& aPresShellId
, const ScrollableLayerGuid::ViewID
& aViewId
,
1055 const Maybe
<ZoomConstraints
>& aConstraints
) {
1056 if (!mCompositorSession
|| !mAPZC
) {
1057 if (mInitialZoomConstraints
) {
1058 MOZ_ASSERT(mInitialZoomConstraints
->mPresShellID
== aPresShellId
);
1059 MOZ_ASSERT(mInitialZoomConstraints
->mViewID
== aViewId
);
1060 if (!aConstraints
) {
1061 mInitialZoomConstraints
.reset();
1066 // We have some constraints, but the compositor and APZC aren't created
1067 // yet. Save these so we can use them later.
1068 mInitialZoomConstraints
= Some(
1069 InitialZoomConstraints(aPresShellId
, aViewId
, aConstraints
.ref()));
1073 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1074 mAPZC
->UpdateZoomConstraints(
1075 ScrollableLayerGuid(layersId
, aPresShellId
, aViewId
), aConstraints
);
1078 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC
; }
1080 nsEventStatus
nsBaseWidget::ProcessUntransformedAPZEvent(
1081 WidgetInputEvent
* aEvent
, const APZEventResult
& aApzResult
) {
1082 MOZ_ASSERT(NS_IsMainThread());
1083 ScrollableLayerGuid targetGuid
= aApzResult
.mTargetGuid
;
1084 uint64_t inputBlockId
= aApzResult
.mInputBlockId
;
1085 InputAPZContext
context(aApzResult
.mTargetGuid
, inputBlockId
,
1086 aApzResult
.GetStatus());
1088 // Make a copy of the original event for the APZCCallbackHelper helpers that
1089 // we call later, because the event passed to DispatchEvent can get mutated in
1090 // ways that we don't want (i.e. touch points can get stripped out).
1091 nsEventStatus status
;
1092 UniquePtr
<WidgetEvent
> original(aEvent
->Duplicate());
1093 DispatchEvent(aEvent
, status
);
1095 if (mAPZC
&& !InputAPZContext::WasRoutedToChildProcess() && inputBlockId
) {
1096 // EventStateManager did not route the event into the child process.
1097 // It's safe to communicate to APZ that the event has been processed.
1098 // Note that here aGuid.mLayersId might be different from
1099 // mCompositorSession->RootLayerTreeId() because the event might have gotten
1100 // hit-tested by APZ to be targeted at a child process, but a parent process
1101 // event listener called preventDefault on it. In that case aGuid.mLayersId
1102 // would still be the layers id for the child process, but the event would
1103 // not have actually gotten routed to the child process. The main-thread
1104 // hit-test result therefore needs to use the parent process layers id.
1105 LayersId rootLayersId
= mCompositorSession
->RootLayerTreeId();
1107 RefPtr
<DisplayportSetListener
> postLayerization
;
1108 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1109 nsTArray
<TouchBehaviorFlags
> allowedTouchBehaviors
;
1110 if (touchEvent
->mMessage
== eTouchStart
) {
1111 auto& originalEvent
= *original
->AsTouchEvent();
1112 MOZ_ASSERT(NS_IsMainThread());
1113 allowedTouchBehaviors
= TouchActionHelper::GetAllowedTouchBehavior(
1114 this, GetDocument(), originalEvent
);
1115 if (!allowedTouchBehaviors
.IsEmpty()) {
1116 mAPZC
->SetAllowedTouchBehavior(inputBlockId
, allowedTouchBehaviors
);
1118 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1119 this, GetDocument(), originalEvent
, rootLayersId
, inputBlockId
);
1121 mAPZEventState
->ProcessTouchEvent(*touchEvent
, targetGuid
, inputBlockId
,
1122 aApzResult
.GetStatus(), status
,
1123 std::move(allowedTouchBehaviors
));
1124 } else if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1125 MOZ_ASSERT(wheelEvent
->mFlags
.mHandledByAPZ
);
1126 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1127 this, GetDocument(), *original
->AsWheelEvent(), rootLayersId
,
1129 if (wheelEvent
->mCanTriggerSwipe
) {
1130 ReportSwipeStarted(inputBlockId
, wheelEvent
->TriggersSwipe());
1132 mAPZEventState
->ProcessWheelEvent(*wheelEvent
, inputBlockId
);
1133 } else if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1134 MOZ_ASSERT(mouseEvent
->mFlags
.mHandledByAPZ
);
1135 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1136 this, GetDocument(), *original
->AsMouseEvent(), rootLayersId
,
1138 mAPZEventState
->ProcessMouseEvent(*mouseEvent
, inputBlockId
);
1140 if (postLayerization
) {
1141 postLayerization
->Register();
1148 template <class InputType
, class EventType
>
1149 class DispatchEventOnMainThread
: public Runnable
{
1151 DispatchEventOnMainThread(const InputType
& aInput
, nsBaseWidget
* aWidget
,
1152 const APZEventResult
& aAPZResult
)
1153 : mozilla::Runnable("DispatchEventOnMainThread"),
1156 mAPZResult(aAPZResult
) {}
1158 NS_IMETHOD
Run() override
{
1159 EventType event
= mInput
.ToWidgetEvent(mWidget
);
1160 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1166 nsBaseWidget
* mWidget
;
1167 APZEventResult mAPZResult
;
1170 template <class InputType
, class EventType
>
1171 class DispatchInputOnControllerThread
: public Runnable
{
1173 DispatchInputOnControllerThread(const EventType
& aEvent
,
1174 IAPZCTreeManager
* aAPZC
,
1175 nsBaseWidget
* aWidget
)
1176 : mozilla::Runnable("DispatchInputOnControllerThread"),
1177 mMainMessageLoop(MessageLoop::current()),
1182 NS_IMETHOD
Run() override
{
1183 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(mInput
);
1184 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1187 RefPtr
<Runnable
> r
= new DispatchEventOnMainThread
<InputType
, EventType
>(
1188 mInput
, mWidget
, result
);
1189 mMainMessageLoop
->PostTask(r
.forget());
1194 MessageLoop
* mMainMessageLoop
;
1196 RefPtr
<IAPZCTreeManager
> mAPZC
;
1197 nsBaseWidget
* mWidget
;
1200 void nsBaseWidget::DispatchTouchInput(MultiTouchInput
& aInput
,
1201 uint16_t aInputSource
) {
1202 MOZ_ASSERT(NS_IsMainThread());
1203 MOZ_ASSERT(aInputSource
==
1204 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH
||
1205 aInputSource
== mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN
);
1207 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1209 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1210 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1214 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1215 ProcessUntransformedAPZEvent(&event
, result
);
1217 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1219 nsEventStatus status
;
1220 DispatchEvent(&event
, status
);
1224 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput
& aInput
) {
1225 MOZ_ASSERT(NS_IsMainThread());
1227 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1229 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1230 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1234 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1235 ProcessUntransformedAPZEvent(&event
, result
);
1237 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1238 nsEventStatus status
;
1239 DispatchEvent(&event
, status
);
1243 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput
& aInput
) {
1244 MOZ_ASSERT(NS_IsMainThread());
1246 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1247 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1249 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1252 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1253 ProcessUntransformedAPZEvent(&event
, result
);
1255 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1256 nsEventStatus status
;
1257 DispatchEvent(&event
, status
);
1261 nsIWidget::ContentAndAPZEventStatus
nsBaseWidget::DispatchInputEvent(
1262 WidgetInputEvent
* aEvent
) {
1263 nsIWidget::ContentAndAPZEventStatus status
;
1264 MOZ_ASSERT(NS_IsMainThread());
1266 if (APZThreadUtils::IsControllerThread()) {
1267 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1268 status
.mApzStatus
= result
.GetStatus();
1269 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1272 status
.mContentStatus
= ProcessUntransformedAPZEvent(aEvent
, result
);
1275 if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1276 RefPtr
<Runnable
> r
=
1277 new DispatchInputOnControllerThread
<ScrollWheelInput
,
1278 WidgetWheelEvent
>(*wheelEvent
,
1280 APZThreadUtils::RunOnControllerThread(std::move(r
));
1281 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1284 if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1285 RefPtr
<Runnable
> r
=
1286 new DispatchInputOnControllerThread
<MouseInput
, WidgetMouseEvent
>(
1287 *mouseEvent
, mAPZC
, this);
1288 APZThreadUtils::RunOnControllerThread(std::move(r
));
1289 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1292 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1293 RefPtr
<Runnable
> r
=
1294 new DispatchInputOnControllerThread
<MultiTouchInput
,
1295 WidgetTouchEvent
>(*touchEvent
,
1297 APZThreadUtils::RunOnControllerThread(std::move(r
));
1298 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1301 // Allow dispatching keyboard events on Gecko thread.
1302 MOZ_ASSERT(aEvent
->AsKeyboardEvent());
1305 DispatchEvent(aEvent
, status
.mContentStatus
);
1309 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent
* aEvent
) {
1310 MOZ_ASSERT(NS_IsMainThread());
1312 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1313 mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1317 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent
& event
) {
1318 nsEventStatus status
;
1319 DispatchEvent(&event
, status
);
1320 return ConvertStatus(status
);
1323 Document
* nsBaseWidget::GetDocument() const {
1324 if (mWidgetListener
) {
1325 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1326 return presShell
->GetDocument();
1332 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1333 // Parent directly listens to the vsync source whereas
1334 // child process communicate via IPC
1335 // Should be called AFTER gfxPlatform is initialized
1336 if (XRE_IsParentProcess()) {
1337 if (!mCompositorVsyncDispatcherLock
) {
1338 mCompositorVsyncDispatcherLock
=
1339 MakeUnique
<Mutex
>("mCompositorVsyncDispatcherLock");
1341 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1342 if (!mCompositorVsyncDispatcher
) {
1343 RefPtr
<VsyncDispatcher
> vsyncDispatcher
=
1344 gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
1345 mCompositorVsyncDispatcher
=
1346 new CompositorVsyncDispatcher(std::move(vsyncDispatcher
));
1351 already_AddRefed
<CompositorVsyncDispatcher
>
1352 nsBaseWidget::GetCompositorVsyncDispatcher() {
1353 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
1355 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1356 RefPtr
<CompositorVsyncDispatcher
> dispatcher
= mCompositorVsyncDispatcher
;
1357 return dispatcher
.forget();
1360 already_AddRefed
<WebRenderLayerManager
> nsBaseWidget::CreateCompositorSession(
1361 int aWidth
, int aHeight
, CompositorOptions
* aOptionsOut
) {
1362 MOZ_ASSERT(aOptionsOut
);
1365 CreateCompositorVsyncDispatcher();
1367 gfx::GPUProcessManager
* gpu
= gfx::GPUProcessManager::Get();
1368 // Make sure GPU process is ready for use.
1369 // If it failed to connect to GPU process, GPU process usage is disabled in
1370 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1371 gpu
->EnsureGPUReady();
1373 // If widget type does not supports acceleration, we may be allowed to use
1374 // software WebRender instead.
1375 bool supportsAcceleration
= WidgetTypeSupportsAcceleration();
1376 bool enableSWWR
= true;
1377 if (supportsAcceleration
||
1378 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1379 enableSWWR
= gfx::gfxVars::UseSoftwareWebRender();
1381 bool enableAPZ
= UseAPZ();
1382 CompositorOptions
options(enableAPZ
, enableSWWR
);
1385 if (supportsAcceleration
) {
1386 options
.SetAllowSoftwareWebRenderD3D11(
1387 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1389 if (mNeedFastSnaphot
) {
1390 options
.SetNeedFastSnaphot(true);
1392 #elif defined(MOZ_WIDGET_ANDROID)
1393 MOZ_ASSERT(supportsAcceleration
);
1394 options
.SetAllowSoftwareWebRenderOGL(
1395 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1396 #elif defined(MOZ_WIDGET_GTK)
1397 if (supportsAcceleration
) {
1398 options
.SetAllowSoftwareWebRenderOGL(
1399 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1403 #ifdef MOZ_WIDGET_ANDROID
1404 // Unconditionally set the compositor as initially paused, as we have not
1405 // yet had a chance to send the compositor surface to the GPU process. We
1406 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1407 // where we will also resume the compositor if required.
1408 options
.SetInitiallyPaused(true);
1410 options
.SetInitiallyPaused(CompositorInitiallyPaused());
1413 RefPtr
<WebRenderLayerManager
> lm
= new WebRenderLayerManager(this);
1415 uint64_t innerWindowId
= 0;
1416 if (Document
* doc
= GetDocument()) {
1417 innerWindowId
= doc
->InnerWindowID();
1421 mCompositorSession
= gpu
->CreateTopLevelCompositor(
1422 this, lm
, GetDefaultScale(), options
, UseExternalCompositingSurface(),
1423 gfx::IntSize(aWidth
, aHeight
), innerWindowId
, &retry
);
1425 if (mCompositorSession
) {
1426 TextureFactoryIdentifier textureFactoryIdentifier
;
1428 lm
->Initialize(mCompositorSession
->GetCompositorBridgeChild(),
1429 wr::AsPipelineId(mCompositorSession
->RootLayerTreeId()),
1430 &textureFactoryIdentifier
, error
);
1431 if (textureFactoryIdentifier
.mParentBackend
!= LayersBackend::LAYERS_WR
) {
1433 DestroyCompositor();
1434 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1435 gfx::GPUProcessManager::Get()->DisableWebRender(
1436 wr::WebRenderError::INITIALIZE
, error
);
1440 // We need to retry in a loop because the act of failing to create the
1441 // compositor can change our state (e.g. disable WebRender).
1442 if (mCompositorSession
|| !retry
) {
1443 *aOptionsOut
= options
;
1449 void nsBaseWidget::CreateCompositor(int aWidth
, int aHeight
) {
1450 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1451 gfxPlatform::GetPlatform();
1453 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1454 "This function assumes OMTC");
1456 MOZ_ASSERT(!mCompositorSession
&& !mCompositorBridgeChild
,
1457 "Should have properly cleaned up the previous PCompositor pair "
1460 if (mCompositorBridgeChild
) {
1461 mCompositorBridgeChild
->Destroy();
1464 // Recreating this is tricky, as we may still have an old and we need
1465 // to make sure it's properly destroyed by calling DestroyCompositor!
1467 // If we've already received a shutdown notification, don't try
1468 // create a new compositor.
1469 if (!mShutdownObserver
) {
1473 // The controller thread must be configured before the compositor
1474 // session is created, so that the input bridge runs on the right
1476 ConfigureAPZControllerThread();
1478 CompositorOptions options
;
1479 RefPtr
<WebRenderLayerManager
> lm
=
1480 CreateCompositorSession(aWidth
, aHeight
, &options
);
1485 MOZ_ASSERT(mCompositorSession
);
1486 mCompositorBridgeChild
= mCompositorSession
->GetCompositorBridgeChild();
1487 SetCompositorWidgetDelegate(
1488 mCompositorSession
->GetCompositorWidgetDelegate());
1490 if (options
.UseAPZ()) {
1491 mAPZC
= mCompositorSession
->GetAPZCTreeManager();
1492 ConfigureAPZCTreeManager();
1497 if (mInitialZoomConstraints
) {
1498 UpdateZoomConstraints(mInitialZoomConstraints
->mPresShellID
,
1499 mInitialZoomConstraints
->mViewID
,
1500 Some(mInitialZoomConstraints
->mConstraints
));
1501 mInitialZoomConstraints
.reset();
1504 TextureFactoryIdentifier textureFactoryIdentifier
=
1505 lm
->GetTextureFactoryIdentifier();
1506 MOZ_ASSERT(textureFactoryIdentifier
.mParentBackend
==
1507 LayersBackend::LAYERS_WR
);
1508 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier
);
1509 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier
);
1513 mWindowRenderer
= std::move(lm
);
1515 // Only track compositors for top-level windows, since other window types
1516 // may use the basic compositor. Except on the OS X - see bug 1306383
1517 #if defined(XP_MACOSX)
1518 bool getCompositorFromThisWindow
= true;
1520 bool getCompositorFromThisWindow
= mWindowType
== WindowType::TopLevel
;
1523 if (getCompositorFromThisWindow
) {
1524 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1525 mWindowRenderer
->GetCompositorBackendType());
1529 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession
* aSession
) {
1530 MOZ_ASSERT(aSession
== mCompositorSession
);
1531 DestroyLayerManager();
1534 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1535 return gfxPlatform::UsesOffMainThreadCompositing();
1538 WindowRenderer
* nsBaseWidget::GetWindowRenderer() {
1539 if (!mWindowRenderer
) {
1540 if (!mShutdownObserver
) {
1541 // We are shutting down, do not try to re-create a LayerManager
1544 // Try to use an async compositor first, if possible
1545 if (ShouldUseOffMainThreadCompositing()) {
1549 if (!mWindowRenderer
) {
1550 mWindowRenderer
= CreateFallbackRenderer();
1553 return mWindowRenderer
;
1556 WindowRenderer
* nsBaseWidget::CreateFallbackRenderer() {
1557 return new FallbackRenderer
;
1560 CompositorBridgeChild
* nsBaseWidget::GetRemoteRenderer() {
1561 return mCompositorBridgeChild
;
1564 void nsBaseWidget::ClearCachedWebrenderResources() {
1565 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1568 mWindowRenderer
->AsWebRender()->ClearCachedResources();
1571 void nsBaseWidget::ClearWebrenderAnimationResources() {
1572 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1575 mWindowRenderer
->AsWebRender()->ClearAnimationResources();
1578 bool nsBaseWidget::SetNeedFastSnaphot() {
1579 MOZ_ASSERT(XRE_IsParentProcess());
1580 MOZ_ASSERT(!mCompositorSession
);
1582 if (!XRE_IsParentProcess() || mCompositorSession
) {
1586 mNeedFastSnaphot
= true;
1590 already_AddRefed
<gfx::DrawTarget
> nsBaseWidget::StartRemoteDrawing() {
1594 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA
; }
1596 //-------------------------------------------------------------------------
1598 // Destroy the window
1600 //-------------------------------------------------------------------------
1601 void nsBaseWidget::OnDestroy() {
1602 if (mTextEventDispatcher
) {
1603 mTextEventDispatcher
->OnDestroyWidget();
1604 // Don't release it until this widget actually released because after this
1605 // is called, TextEventDispatcher() may create it again.
1608 // If this widget is being destroyed, let the APZ code know to drop references
1609 // to this widget. Callers of this function all should be holding a deathgrip
1610 // on this widget already.
1611 ReleaseContentController();
1614 void nsBaseWidget::MoveClient(const DesktopPoint
& aOffset
) {
1615 LayoutDeviceIntPoint
clientOffset(GetClientOffset());
1617 // GetClientOffset returns device pixels; scale back to desktop pixels
1618 // if that's what this widget uses for the Move/Resize APIs
1619 if (BoundsUseDesktopPixels()) {
1620 DesktopPoint desktopOffset
= clientOffset
/ GetDesktopToDeviceScale();
1621 Move(aOffset
.x
- desktopOffset
.x
, aOffset
.y
- desktopOffset
.y
);
1623 LayoutDevicePoint layoutOffset
= aOffset
* GetDesktopToDeviceScale();
1624 Move(layoutOffset
.x
- LayoutDeviceCoord(clientOffset
.x
),
1625 layoutOffset
.y
- LayoutDeviceCoord(clientOffset
.y
));
1629 void nsBaseWidget::ResizeClient(const DesktopSize
& aSize
, bool aRepaint
) {
1630 NS_ASSERTION((aSize
.width
>= 0), "Negative width passed to ResizeClient");
1631 NS_ASSERTION((aSize
.height
>= 0), "Negative height passed to ResizeClient");
1633 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1635 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1636 // if that's what this widget uses for the Move/Resize APIs
1637 if (BoundsUseDesktopPixels()) {
1638 DesktopSize desktopDelta
=
1639 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1640 clientBounds
.Size()) /
1641 GetDesktopToDeviceScale();
1642 Resize(aSize
.width
+ desktopDelta
.width
, aSize
.height
+ desktopDelta
.height
,
1645 LayoutDeviceSize layoutSize
= aSize
* GetDesktopToDeviceScale();
1646 Resize(mBounds
.Width() + (layoutSize
.width
- clientBounds
.Width()),
1647 mBounds
.Height() + (layoutSize
.height
- clientBounds
.Height()),
1652 void nsBaseWidget::ResizeClient(const DesktopRect
& aRect
, bool aRepaint
) {
1653 NS_ASSERTION((aRect
.Width() >= 0), "Negative width passed to ResizeClient");
1654 NS_ASSERTION((aRect
.Height() >= 0), "Negative height passed to ResizeClient");
1656 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1657 LayoutDeviceIntPoint clientOffset
= GetClientOffset();
1658 DesktopToLayoutDeviceScale scale
= GetDesktopToDeviceScale();
1660 if (BoundsUseDesktopPixels()) {
1661 DesktopPoint desktopOffset
= clientOffset
/ scale
;
1662 DesktopSize desktopDelta
=
1663 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1664 clientBounds
.Size()) /
1666 Resize(aRect
.X() - desktopOffset
.x
, aRect
.Y() - desktopOffset
.y
,
1667 aRect
.Width() + desktopDelta
.width
,
1668 aRect
.Height() + desktopDelta
.height
, aRepaint
);
1670 LayoutDeviceRect layoutRect
= aRect
* scale
;
1671 Resize(layoutRect
.X() - clientOffset
.x
, layoutRect
.Y() - clientOffset
.y
,
1672 layoutRect
.Width() + mBounds
.Width() - clientBounds
.Width(),
1673 layoutRect
.Height() + mBounds
.Height() - clientBounds
.Height(),
1678 //-------------------------------------------------------------------------
1682 //-------------------------------------------------------------------------
1685 * If the implementation of nsWindow supports borders this method MUST be
1689 LayoutDeviceIntRect
nsBaseWidget::GetClientBounds() { return GetBounds(); }
1692 * If the implementation of nsWindow supports borders this method MUST be
1696 LayoutDeviceIntRect
nsBaseWidget::GetBounds() { return mBounds
; }
1699 * If the implementation of nsWindow uses a local coordinate system within the
1700 *window, this method must be overridden
1703 LayoutDeviceIntRect
nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1705 nsresult
nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect
& aRect
) {
1706 if (SizeMode() != nsSizeMode_Normal
) {
1707 return NS_ERROR_FAILURE
;
1709 aRect
= GetScreenBounds();
1713 LayoutDeviceIntPoint
nsBaseWidget::GetClientOffset() {
1714 return LayoutDeviceIntPoint(0, 0);
1717 nsresult
nsBaseWidget::SetNonClientMargins(const LayoutDeviceIntMargin
&) {
1718 return NS_ERROR_NOT_IMPLEMENTED
;
1721 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin
) {}
1723 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1725 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1727 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect
* aResizerRect
) {
1732 * Modifies aFile to point at an icon file with the given name and suffix. The
1733 * suffix may correspond to a file extension with leading '.' if appropriate.
1734 * Returns true if the icon file exists and can be read.
1736 static bool ResolveIconNameHelper(nsIFile
* aFile
, const nsAString
& aIconName
,
1737 const nsAString
& aIconSuffix
) {
1738 aFile
->Append(u
"icons"_ns
);
1739 aFile
->Append(u
"default"_ns
);
1740 aFile
->Append(aIconName
+ aIconSuffix
);
1743 return NS_SUCCEEDED(aFile
->IsReadable(&readable
)) && readable
;
1747 * Resolve the given icon name into a local file object. This method is
1748 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1749 * platform specific icon file suffix (e.g., ".ico" under Win32).
1751 * If no file is found matching the given parameters, then null is returned.
1753 void nsBaseWidget::ResolveIconName(const nsAString
& aIconName
,
1754 const nsAString
& aIconSuffix
,
1755 nsIFile
** aResult
) {
1758 nsCOMPtr
<nsIProperties
> dirSvc
=
1759 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID
);
1760 if (!dirSvc
) return;
1762 // first check auxilary chrome directories
1764 nsCOMPtr
<nsISimpleEnumerator
> dirs
;
1765 dirSvc
->Get(NS_APP_CHROME_DIR_LIST
, NS_GET_IID(nsISimpleEnumerator
),
1766 getter_AddRefs(dirs
));
1769 while (NS_SUCCEEDED(dirs
->HasMoreElements(&hasMore
)) && hasMore
) {
1770 nsCOMPtr
<nsISupports
> element
;
1771 dirs
->GetNext(getter_AddRefs(element
));
1772 if (!element
) continue;
1773 nsCOMPtr
<nsIFile
> file
= do_QueryInterface(element
);
1774 if (!file
) continue;
1775 if (ResolveIconNameHelper(file
, aIconName
, aIconSuffix
)) {
1776 NS_ADDREF(*aResult
= file
);
1782 // then check the main app chrome directory
1784 nsCOMPtr
<nsIFile
> file
;
1785 dirSvc
->Get(NS_APP_CHROME_DIR
, NS_GET_IID(nsIFile
), getter_AddRefs(file
));
1786 if (file
&& ResolveIconNameHelper(file
, aIconName
, aIconSuffix
))
1787 NS_ADDREF(*aResult
= file
);
1790 void nsBaseWidget::SetSizeConstraints(const SizeConstraints
& aConstraints
) {
1791 mSizeConstraints
= aConstraints
;
1793 // Popups are constrained during layout, and we don't want to synchronously
1794 // paint from reflow, so bail out... This is not great, but it's no worse than
1795 // what we used to do.
1797 // The right fix here is probably making constraint changes go through the
1798 // view manager and such.
1799 if (mWindowType
== WindowType::Popup
) {
1803 // If the current size doesn't meet the new constraints, trigger a
1804 // resize to apply it. Note that, we don't want to invoke Resize if
1805 // the new constraints don't affect the current size, because Resize
1806 // implementation on some platforms may touch other geometry even if
1807 // the size don't need to change.
1808 LayoutDeviceIntSize curSize
= mBounds
.Size();
1809 LayoutDeviceIntSize clampedSize
=
1810 Max(aConstraints
.mMinSize
, Min(aConstraints
.mMaxSize
, curSize
));
1811 if (clampedSize
!= curSize
) {
1813 if (BoundsUseDesktopPixels()) {
1814 DesktopSize desktopSize
= clampedSize
/ GetDesktopToDeviceScale();
1815 size
= desktopSize
.ToUnknownSize();
1817 size
= gfx::Size(clampedSize
.ToUnknownSize());
1819 Resize(size
.width
, size
.height
, true);
1823 const widget::SizeConstraints
nsBaseWidget::GetSizeConstraints() {
1824 return mSizeConstraints
;
1828 nsIRollupListener
* nsBaseWidget::GetActiveRollupListener() {
1829 // TODO: Simplify this.
1830 return nsXULPopupManager::GetInstance();
1833 void nsBaseWidget::NotifyWindowDestroyed() {
1834 if (!mWidgetListener
) return;
1836 nsCOMPtr
<nsIAppWindow
> window
= mWidgetListener
->GetAppWindow();
1837 nsCOMPtr
<nsIBaseWindow
> appWindow(do_QueryInterface(window
));
1839 appWindow
->Destroy();
1843 void nsBaseWidget::NotifyWindowMoved(int32_t aX
, int32_t aY
,
1844 ByMoveToRect aByMoveToRect
) {
1845 if (mWidgetListener
) {
1846 mWidgetListener
->WindowMoved(this, aX
, aY
, aByMoveToRect
);
1849 if (mIMEHasFocus
&& IMENotificationRequestsRef().WantPositionChanged()) {
1850 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE
));
1854 void nsBaseWidget::NotifySizeMoveDone() {
1855 if (!mWidgetListener
) {
1858 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1859 presShell
->WindowSizeMoveDone();
1863 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind
) {
1864 LookAndFeel::NotifyChangedAllWindows(aKind
);
1867 nsresult
nsBaseWidget::NotifyIME(const IMENotification
& aIMENotification
) {
1871 switch (aIMENotification
.mMessage
) {
1872 case REQUEST_TO_COMMIT_COMPOSITION
:
1873 case REQUEST_TO_CANCEL_COMPOSITION
:
1874 // We should send request to IME only when there is a TextEventDispatcher
1875 // instance (this means that this widget has dispatched at least one
1876 // composition event or keyboard event) and the it has composition.
1877 // Otherwise, there is nothing to do.
1878 // Note that if current input transaction is for native input events,
1879 // TextEventDispatcher::NotifyIME() will call
1880 // TextEventDispatcherListener::NotifyIME().
1881 if (mTextEventDispatcher
&& mTextEventDispatcher
->IsComposing()) {
1882 return mTextEventDispatcher
->NotifyIME(aIMENotification
);
1886 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_FOCUS
) {
1887 mIMEHasFocus
= true;
1889 EnsureTextEventDispatcher();
1890 // TextEventDispatcher::NotifyIME() will always call
1891 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1892 // input transaction is for synthesized events for automated tests,
1893 // notifications will be sent to native IME.
1894 nsresult rv
= mTextEventDispatcher
->NotifyIME(aIMENotification
);
1895 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_BLUR
) {
1896 mIMEHasFocus
= false;
1903 void nsBaseWidget::EnsureTextEventDispatcher() {
1904 if (mTextEventDispatcher
) {
1907 mTextEventDispatcher
= new TextEventDispatcher(this);
1910 nsIWidget::NativeIMEContext
nsBaseWidget::GetNativeIMEContext() {
1911 if (mTextEventDispatcher
&& mTextEventDispatcher
->GetPseudoIMEContext()) {
1912 // If we already have a TextEventDispatcher and it's working with
1913 // a TextInputProcessor, we need to return pseudo IME context since
1914 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1915 // on the pseudo IME context in such case.
1916 NativeIMEContext pseudoIMEContext
;
1917 pseudoIMEContext
.InitWithRawNativeIMEContext(
1918 mTextEventDispatcher
->GetPseudoIMEContext());
1919 return pseudoIMEContext
;
1921 return NativeIMEContext(this);
1924 nsIWidget::TextEventDispatcher
* nsBaseWidget::GetTextEventDispatcher() {
1925 EnsureTextEventDispatcher();
1926 return mTextEventDispatcher
;
1929 void* nsBaseWidget::GetPseudoIMEContext() {
1930 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
1934 return dispatcher
->GetPseudoIMEContext();
1937 TextEventDispatcherListener
*
1938 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1939 // TODO: If all platforms supported use of TextEventDispatcher for handling
1940 // native IME and keyboard events, this method should be removed since
1941 // in such case, this is overridden by all the subclasses.
1945 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId
,
1946 const ScrollableLayerGuid::ViewID
& aViewId
,
1947 const CSSRect
& aRect
, const uint32_t& aFlags
) {
1948 if (!mCompositorSession
|| !mAPZC
) {
1951 LayersId layerId
= mCompositorSession
->RootLayerTreeId();
1952 mAPZC
->ZoomToRect(ScrollableLayerGuid(layerId
, aPresShellId
, aViewId
),
1953 ZoomTarget
{aRect
}, aFlags
);
1956 #ifdef ACCESSIBILITY
1958 a11y::LocalAccessible
* nsBaseWidget::GetRootAccessible() {
1959 NS_ENSURE_TRUE(mWidgetListener
, nullptr);
1961 PresShell
* presShell
= mWidgetListener
->GetPresShell();
1962 NS_ENSURE_TRUE(presShell
, nullptr);
1964 // If container is null then the presshell is not active. This often happens
1965 // when a preshell is being held onto for fastback.
1966 nsPresContext
* presContext
= presShell
->GetPresContext();
1967 NS_ENSURE_TRUE(presContext
->GetContainerWeak(), nullptr);
1969 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1970 // make sure it's not created at unsafe times.
1971 nsAccessibilityService
* accService
= GetOrCreateAccService();
1973 return accService
->GetRootDocumentAccessible(
1974 presShell
, nsContentUtils::IsSafeToRunScript());
1980 #endif // ACCESSIBILITY
1982 void nsBaseWidget::StartAsyncScrollbarDrag(
1983 const AsyncDragMetrics
& aDragMetrics
) {
1984 if (!AsyncPanZoomEnabled()) {
1988 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession
);
1990 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1991 ScrollableLayerGuid
guid(layersId
, aDragMetrics
.mPresShellId
,
1992 aDragMetrics
.mViewId
);
1994 mAPZC
->StartScrollbarDrag(guid
, aDragMetrics
);
1997 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint
& aAnchorLocation
,
1998 const ScrollableLayerGuid
& aGuid
) {
1999 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2001 return mAPZC
->StartAutoscroll(aGuid
, aAnchorLocation
);
2004 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid
& aGuid
) {
2005 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2007 mAPZC
->StopAutoscroll(aGuid
);
2010 LayersId
nsBaseWidget::GetRootLayerTreeId() {
2011 return mCompositorSession
? mCompositorSession
->RootLayerTreeId()
2015 already_AddRefed
<widget::Screen
> nsBaseWidget::GetWidgetScreen() {
2016 ScreenManager
& screenManager
= ScreenManager::GetSingleton();
2017 LayoutDeviceIntRect bounds
= GetScreenBounds();
2018 DesktopIntRect deskBounds
= RoundedToInt(bounds
/ GetDesktopToDeviceScale());
2019 return screenManager
.ScreenForRect(deskBounds
);
2022 mozilla::DesktopToLayoutDeviceScale
2023 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
2024 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
2025 ->GetDesktopToDeviceScale();
2028 nsresult
nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint
,
2030 nsIObserver
* aObserver
) {
2031 AutoObserverNotifier
notifier(aObserver
, "touchtap");
2033 if (sPointerIdCounter
> TOUCH_INJECT_MAX_POINTS
) {
2034 sPointerIdCounter
= 0;
2036 int pointerId
= sPointerIdCounter
;
2037 sPointerIdCounter
++;
2038 nsresult rv
= SynthesizeNativeTouchPoint(pointerId
, TOUCH_CONTACT
, aPoint
,
2040 if (NS_FAILED(rv
)) {
2045 return SynthesizeNativeTouchPoint(pointerId
, TOUCH_REMOVE
, aPoint
, 0, 0,
2049 // initiate a long tap
2050 int elapse
= Preferences::GetInt("ui.click_hold_context_menus.delay",
2051 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC
);
2052 if (!mLongTapTimer
) {
2053 mLongTapTimer
= NS_NewTimer();
2054 if (!mLongTapTimer
) {
2055 SynthesizeNativeTouchPoint(pointerId
, TOUCH_CANCEL
, aPoint
, 0, 0,
2057 return NS_ERROR_UNEXPECTED
;
2059 // Windows requires recuring events, so we set this to a smaller window
2060 // than the pref value.
2061 int timeout
= elapse
;
2062 if (timeout
> TOUCH_INJECT_PUMP_TIMER_MSEC
) {
2063 timeout
= TOUCH_INJECT_PUMP_TIMER_MSEC
;
2065 mLongTapTimer
->InitWithNamedFuncCallback(
2066 OnLongTapTimerCallback
, this, timeout
, nsITimer::TYPE_REPEATING_SLACK
,
2067 "nsIWidget::SynthesizeNativeTouchTap");
2070 // If we already have a long tap pending, cancel it. We only allow one long
2071 // tap to be active at a time.
2072 if (mLongTapTouchPoint
) {
2073 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2074 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2077 mLongTapTouchPoint
= MakeUnique
<LongTapInfo
>(
2078 pointerId
, aPoint
, TimeDuration::FromMilliseconds(elapse
), aObserver
);
2079 notifier
.SkipNotification(); // we'll do it in the long-tap callback
2084 void nsIWidget::OnLongTapTimerCallback(nsITimer
* aTimer
, void* aClosure
) {
2085 auto* self
= static_cast<nsIWidget
*>(aClosure
);
2087 if ((self
->mLongTapTouchPoint
->mStamp
+ self
->mLongTapTouchPoint
->mDuration
) >
2090 // Windows needs us to keep pumping feedback to the digitizer, so update
2091 // the pointer id with the same position.
2092 self
->SynthesizeNativeTouchPoint(
2093 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_CONTACT
,
2094 self
->mLongTapTouchPoint
->mPosition
, 1.0, 90, nullptr);
2099 AutoObserverNotifier
notifier(self
->mLongTapTouchPoint
->mObserver
,
2102 // finished, remove the touch point
2103 self
->mLongTapTimer
->Cancel();
2104 self
->mLongTapTimer
= nullptr;
2105 self
->SynthesizeNativeTouchPoint(
2106 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_REMOVE
,
2107 self
->mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2108 self
->mLongTapTouchPoint
= nullptr;
2111 float nsIWidget::GetFallbackDPI() {
2112 RefPtr
<const Screen
> primaryScreen
=
2113 ScreenManager::GetSingleton().GetPrimaryScreen();
2114 return primaryScreen
->GetDPI();
2117 CSSToLayoutDeviceScale
nsIWidget::GetFallbackDefaultScale() {
2118 RefPtr
<const Screen
> s
= ScreenManager::GetSingleton().GetPrimaryScreen();
2119 return s
->GetCSSToLayoutDeviceScale(Screen::IncludeOSZoom::No
);
2122 nsresult
nsIWidget::ClearNativeTouchSequence(nsIObserver
* aObserver
) {
2123 AutoObserverNotifier
notifier(aObserver
, "cleartouch");
2125 // XXX This is odd. This is called by the constructor of nsIWidget. However,
2126 // at that point, nsIWidget::mLongTapTimer must be nullptr. Therefore,
2127 // this must do nothing at initializing the instance.
2128 if (!mLongTapTimer
) {
2131 mLongTapTimer
->Cancel();
2132 mLongTapTimer
= nullptr;
2133 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2134 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2135 mLongTapTouchPoint
= nullptr;
2139 MultiTouchInput
nsBaseWidget::UpdateSynthesizedTouchState(
2140 MultiTouchInput
* aState
, mozilla::TimeStamp aTimeStamp
, uint32_t aPointerId
,
2141 TouchPointerState aPointerState
, LayoutDeviceIntPoint aPoint
,
2142 double aPointerPressure
, uint32_t aPointerOrientation
) {
2143 ScreenIntPoint pointerScreenPoint
= ViewAs
<ScreenPixel
>(
2144 aPoint
, PixelCastJustification::LayoutDeviceIsScreenForBounds
);
2146 // We can't dispatch *aState directly because (a) dispatching
2147 // it might inadvertently modify it and (b) in the case of touchend or
2148 // touchcancel events aState will hold the touches that are
2149 // still down whereas the input dispatched needs to hold the removed
2150 // touch(es). We use |inputToDispatch| for this purpose.
2151 MultiTouchInput inputToDispatch
;
2152 inputToDispatch
.mInputType
= MULTITOUCH_INPUT
;
2153 inputToDispatch
.mTimeStamp
= aTimeStamp
;
2155 int32_t index
= aState
->IndexOfTouch((int32_t)aPointerId
);
2156 if (aPointerState
== TOUCH_CONTACT
) {
2158 // found an existing touch point, update it
2159 SingleTouchData
& point
= aState
->mTouches
[index
];
2160 point
.mScreenPoint
= pointerScreenPoint
;
2161 point
.mRotationAngle
= (float)aPointerOrientation
;
2162 point
.mForce
= (float)aPointerPressure
;
2163 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_MOVE
;
2165 // new touch point, add it
2166 aState
->mTouches
.AppendElement(SingleTouchData(
2167 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2168 (float)aPointerOrientation
, (float)aPointerPressure
));
2169 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_START
;
2171 inputToDispatch
.mTouches
= aState
->mTouches
;
2173 MOZ_ASSERT(aPointerState
== TOUCH_REMOVE
|| aPointerState
== TOUCH_CANCEL
);
2174 // a touch point is being lifted, so remove it from the stored list
2176 aState
->mTouches
.RemoveElementAt(index
);
2178 inputToDispatch
.mType
=
2179 (aPointerState
== TOUCH_REMOVE
? MultiTouchInput::MULTITOUCH_END
2180 : MultiTouchInput::MULTITOUCH_CANCEL
);
2181 inputToDispatch
.mTouches
.AppendElement(SingleTouchData(
2182 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2183 (float)aPointerOrientation
, (float)aPointerPressure
));
2186 return inputToDispatch
;
2189 void nsBaseWidget::NotifyLiveResizeStarted() {
2190 // If we have mLiveResizeListeners already non-empty, we should notify those
2191 // listeners that the resize stopped before starting anew. In theory this
2192 // should never happen because we shouldn't get nested live resize actions.
2193 NotifyLiveResizeStopped();
2194 MOZ_ASSERT(mLiveResizeListeners
.IsEmpty());
2196 // If we can get the active remote tab for the current widget, suppress
2197 // the displayport on it during the live resize.
2198 if (!mWidgetListener
) {
2201 nsCOMPtr
<nsIAppWindow
> appWindow
= mWidgetListener
->GetAppWindow();
2205 mLiveResizeListeners
= appWindow
->GetLiveResizeListeners();
2206 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2207 mLiveResizeListeners
[i
]->LiveResizeStarted();
2211 void nsBaseWidget::NotifyLiveResizeStopped() {
2212 if (!mLiveResizeListeners
.IsEmpty()) {
2213 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2214 mLiveResizeListeners
[i
]->LiveResizeStopped();
2216 mLiveResizeListeners
.Clear();
2220 nsresult
nsBaseWidget::AsyncEnableDragDrop(bool aEnable
) {
2221 RefPtr
<nsBaseWidget
> kungFuDeathGrip
= this;
2222 return NS_DispatchToCurrentThreadQueue(
2223 NS_NewRunnableFunction(
2224 "AsyncEnableDragDropFn",
2225 [this, aEnable
, kungFuDeathGrip
]() { EnableDragDrop(aEnable
); }),
2226 kAsyncDragDropTimeout
, EventQueuePriority::Idle
);
2229 void nsBaseWidget::SwipeFinished() { mSwipeTracker
= nullptr; }
2231 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId
,
2233 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== aInputBlockId
) {
2235 PanGestureInput
& startEvent
= mSwipeEventQueue
->queuedEvents
[0];
2236 TrackScrollEventAsSwipe(startEvent
, mSwipeEventQueue
->allowedDirections
,
2238 for (size_t i
= 1; i
< mSwipeEventQueue
->queuedEvents
.Length(); i
++) {
2239 mSwipeTracker
->ProcessEvent(mSwipeEventQueue
->queuedEvents
[i
]);
2242 // If the event wasn't start swipe, we need to notify it to APZ.
2243 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2244 BrowserGestureResponse::NotConsumed
);
2246 mSwipeEventQueue
= nullptr;
2250 void nsBaseWidget::TrackScrollEventAsSwipe(
2251 const mozilla::PanGestureInput
& aSwipeStartEvent
,
2252 uint32_t aAllowedDirections
, uint64_t aInputBlockId
) {
2253 // If a swipe is currently being tracked kill it -- it's been interrupted
2254 // by another gesture event.
2255 if (mSwipeTracker
) {
2256 mSwipeTracker
->CancelSwipe(aSwipeStartEvent
.mTimeStamp
);
2257 mSwipeTracker
->Destroy();
2258 mSwipeTracker
= nullptr;
2261 uint32_t direction
=
2262 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2263 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2264 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2267 new SwipeTracker(*this, aSwipeStartEvent
, aAllowedDirections
, direction
);
2270 mCurrentPanGestureBelongsToSwipe
= true;
2272 // Now SwipeTracker has started consuming pan events, notify it to APZ so
2273 // that APZ can discard queued events.
2274 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2275 BrowserGestureResponse::Consumed
);
2279 nsBaseWidget::SwipeInfo
nsBaseWidget::SendMayStartSwipe(
2280 const mozilla::PanGestureInput
& aSwipeStartEvent
) {
2281 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
2283 uint32_t direction
=
2284 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2285 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2286 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2288 // We're ready to start the animation. Tell Gecko about it, and at the same
2289 // time ask it if it really wants to start an animation for this event.
2290 // This event also reports back the directions that we can swipe in.
2291 LayoutDeviceIntPoint position
= RoundedToInt(aSwipeStartEvent
.mPanStartPoint
*
2292 ScreenToLayoutDeviceScale(1));
2293 WidgetSimpleGestureEvent geckoEvent
= SwipeTracker::CreateSwipeGestureEvent(
2294 eSwipeGestureMayStart
, this, position
, aSwipeStartEvent
.mTimeStamp
);
2295 geckoEvent
.mDirection
= direction
;
2296 geckoEvent
.mDelta
= 0.0;
2297 geckoEvent
.mAllowedDirections
= 0;
2298 bool shouldStartSwipe
=
2299 DispatchWindowEvent(geckoEvent
); // event cancelled == swipe should start
2301 SwipeInfo result
= {shouldStartSwipe
, geckoEvent
.mAllowedDirections
};
2305 WidgetWheelEvent
nsBaseWidget::MayStartSwipeForAPZ(
2306 const PanGestureInput
& aPanInput
, const APZEventResult
& aApzResult
) {
2307 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2308 if (aPanInput
.AllowsSwipe()) {
2309 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2310 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2311 if (swipeInfo
.wantsSwipe
) {
2312 if (aApzResult
.GetStatus() == nsEventStatus_eIgnore
) {
2313 // APZ has determined and that scrolling horizontally in the
2314 // requested direction is impossible, so it didn't do any
2315 // scrolling for the event.
2316 // We know now that MayStartSwipe wants a swipe, so we can start
2318 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
,
2319 aApzResult
.mInputBlockId
);
2321 // We don't know whether this event can start a swipe, so we need
2322 // to queue up events and wait for a call to ReportSwipeStarted.
2323 // APZ might already have started scrolling in response to the
2324 // event if it knew that it's the right thing to do. In that case
2325 // we'll still get a call to ReportSwipeStarted, and we will
2326 // discard the queued events at that point.
2327 mSwipeEventQueue
= MakeUnique
<SwipeEventQueue
>(
2328 swipeInfo
.allowedDirections
, aApzResult
.mInputBlockId
);
2331 // Inform that the browser gesture didn't use the pan event (pan-start
2332 // precisely), so that APZ can now start using the event for
2333 // scrolling/overscrolling.
2334 mAPZC
->SetBrowserGestureResponse(aApzResult
.mInputBlockId
,
2335 BrowserGestureResponse::NotConsumed
);
2339 if (mSwipeEventQueue
&&
2340 mSwipeEventQueue
->inputBlockId
== aApzResult
.mInputBlockId
) {
2341 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2347 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput
& aPanInput
) {
2348 if (aPanInput
.mType
== PanGestureInput::PANGESTURE_MAYSTART
||
2349 aPanInput
.mType
== PanGestureInput::PANGESTURE_START
) {
2350 mCurrentPanGestureBelongsToSwipe
= false;
2352 if (mCurrentPanGestureBelongsToSwipe
) {
2353 // Ignore this event. It's a momentum event from a scroll gesture
2354 // that was processed as a swipe, and the swipe animation has
2355 // already finished (so mSwipeTracker is already null).
2356 MOZ_ASSERT(aPanInput
.IsMomentum(),
2357 "If the fingers are still on the touchpad, we should still have "
2359 "and it should have consumed this event.");
2363 if (!aPanInput
.MayTriggerSwipe()) {
2367 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2369 // We're in the non-APZ case here, but we still want to know whether
2370 // the event was routed to a child process, so we use InputAPZContext
2371 // to get that piece of information.
2372 ScrollableLayerGuid guid
;
2373 uint64_t blockId
= 0;
2374 InputAPZContext
context(guid
, blockId
, nsEventStatus_eIgnore
);
2376 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2377 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2378 nsEventStatus status
;
2379 DispatchEvent(&event
, status
);
2380 if (swipeInfo
.wantsSwipe
) {
2381 if (context
.WasRoutedToChildProcess()) {
2382 // We don't know whether this event can start a swipe, so we need
2383 // to queue up events and wait for a call to ReportSwipeStarted.
2385 MakeUnique
<SwipeEventQueue
>(swipeInfo
.allowedDirections
, blockId
);
2386 } else if (event
.TriggersSwipe()) {
2387 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
, blockId
);
2391 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== 0) {
2392 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2398 const IMENotificationRequests
& nsIWidget::IMENotificationRequestsRef() {
2399 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
2400 return dispatcher
->IMENotificationRequestsRef();
2403 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent
* aEvent
) {}
2405 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType
,
2406 const WidgetKeyboardEvent
& aEvent
,
2407 nsTArray
<CommandInt
>& aCommands
) {
2408 MOZ_ASSERT(aEvent
.IsTrusted());
2409 MOZ_ASSERT(aCommands
.IsEmpty());
2413 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboard() {
2414 if (XRE_IsContentProcess()) {
2415 return CreateBidiKeyboardContentProcess();
2417 return CreateBidiKeyboardInner();
2421 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboardInner() {
2422 // no bidi keyboard implementation
2427 namespace mozilla::widget
{
2429 const char* ToChar(InputContext::Origin aOrigin
) {
2431 case InputContext::ORIGIN_MAIN
:
2432 return "ORIGIN_MAIN";
2433 case InputContext::ORIGIN_CONTENT
:
2434 return "ORIGIN_CONTENT";
2436 return "Unexpected value";
2440 const char* ToChar(IMEMessage aIMEMessage
) {
2441 switch (aIMEMessage
) {
2442 case NOTIFY_IME_OF_NOTHING
:
2443 return "NOTIFY_IME_OF_NOTHING";
2444 case NOTIFY_IME_OF_FOCUS
:
2445 return "NOTIFY_IME_OF_FOCUS";
2446 case NOTIFY_IME_OF_BLUR
:
2447 return "NOTIFY_IME_OF_BLUR";
2448 case NOTIFY_IME_OF_SELECTION_CHANGE
:
2449 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2450 case NOTIFY_IME_OF_TEXT_CHANGE
:
2451 return "NOTIFY_IME_OF_TEXT_CHANGE";
2452 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED
:
2453 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2454 case NOTIFY_IME_OF_POSITION_CHANGE
:
2455 return "NOTIFY_IME_OF_POSITION_CHANGE";
2456 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT
:
2457 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2458 case REQUEST_TO_COMMIT_COMPOSITION
:
2459 return "REQUEST_TO_COMMIT_COMPOSITION";
2460 case REQUEST_TO_CANCEL_COMPOSITION
:
2461 return "REQUEST_TO_CANCEL_COMPOSITION";
2463 return "Unexpected value";
2467 void NativeIMEContext::Init(nsIWidget
* aWidget
) {
2469 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2470 mOriginProcessID
= static_cast<uint64_t>(-1);
2473 if (!XRE_IsContentProcess()) {
2474 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(
2475 aWidget
->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT
));
2476 mOriginProcessID
= 0;
2479 // If this is created in a child process, aWidget is an instance of
2480 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2481 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2482 // native IME context of the parent process.
2483 *this = aWidget
->GetNativeIMEContext();
2486 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext
) {
2487 if (NS_WARN_IF(!aRawNativeIMEContext
)) {
2488 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2489 mOriginProcessID
= static_cast<uint64_t>(-1);
2492 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(aRawNativeIMEContext
);
2494 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2497 void IMENotification::TextChangeDataBase::MergeWith(
2498 const IMENotification::TextChangeDataBase
& aOther
) {
2499 MOZ_ASSERT(aOther
.IsValid(), "Merging data must store valid data");
2500 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mRemovedEndOffset
,
2501 "end of removed text must be same or larger than start");
2502 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mAddedEndOffset
,
2503 "end of added text must be same or larger than start");
2510 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2511 // text ranges. I.e., mStartOffset should be the smallest offset of all
2512 // modified text ranges in old text. |mRemovedEndOffset| should be the
2513 // largest end offset in old text of all modified text ranges.
2514 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2515 // I.e., only this is an offset in new text.
2516 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2517 // premodified text was already removed. And some text whose length is
2518 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2519 // this allows IME to mark dirty the modified text range with |mStartOffset|
2520 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2521 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2522 // Additionally, IME can retrieve only the text between |mStartOffset| and
2523 // |mAddedEndOffset| for updating stored text.
2525 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2526 // should be adjusted to be in same text. The |newData.mStartOffset| and
2527 // |newData.mRemovedEndOffset| should be computed as in old text because
2528 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2529 // in the old text but even if some text before the values of the newData
2530 // has already been modified, the values don't include the changes.
2532 // For comparing new and old |mAddedEndOffset| values, they should be
2533 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2534 // computed as in the new text because |mAddedEndOffset| indicates the end
2535 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2536 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2538 const TextChangeDataBase
& newData
= aOther
;
2539 const TextChangeDataBase oldData
= *this;
2541 // mCausedOnlyByComposition should be true only when all changes are caused
2543 mCausedOnlyByComposition
=
2544 newData
.mCausedOnlyByComposition
&& oldData
.mCausedOnlyByComposition
;
2546 // mIncludingChangesWithoutComposition should be true if at least one of
2547 // merged changes occurred without composition.
2548 mIncludingChangesWithoutComposition
=
2549 newData
.mIncludingChangesWithoutComposition
||
2550 oldData
.mIncludingChangesWithoutComposition
;
2552 // mIncludingChangesDuringComposition should be true when at least one of
2553 // the merged non-composition changes occurred during the latest composition.
2554 if (!newData
.mCausedOnlyByComposition
&&
2555 !newData
.mIncludingChangesDuringComposition
) {
2556 MOZ_ASSERT(newData
.mIncludingChangesWithoutComposition
);
2557 MOZ_ASSERT(mIncludingChangesWithoutComposition
);
2558 // If new change is neither caused by composition nor occurred during
2559 // composition, set mIncludingChangesDuringComposition to false because
2560 // IME doesn't want outdated text changes as text change during current
2562 mIncludingChangesDuringComposition
= false;
2564 // Otherwise, set mIncludingChangesDuringComposition to true if either
2565 // oldData or newData includes changes during composition.
2566 mIncludingChangesDuringComposition
=
2567 newData
.mIncludingChangesDuringComposition
||
2568 oldData
.mIncludingChangesDuringComposition
;
2571 if (newData
.mStartOffset
>= oldData
.mAddedEndOffset
) {
2573 // If new start is after old end offset of added text, it means that text
2574 // after the modified range is modified. Like:
2575 // added range of old change: +----------+
2576 // removed range of new change: +----------+
2577 // So, the old start offset is always the smaller offset.
2578 mStartOffset
= oldData
.mStartOffset
;
2579 // The new end offset of removed text is moved by the old change and we
2580 // need to cancel the move of the old change for comparing the offsets in
2581 // same text because it doesn't make sensce to compare offsets in different
2583 uint32_t newRemovedEndOffsetInOldText
=
2584 newData
.mRemovedEndOffset
- oldData
.Difference();
2586 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2587 // The new end offset of added text is always the larger offset.
2588 mAddedEndOffset
= newData
.mAddedEndOffset
;
2592 if (newData
.mStartOffset
>= oldData
.mStartOffset
) {
2593 // If new start is in the modified range, it means that new data changes
2594 // a part or all of the range.
2595 mStartOffset
= oldData
.mStartOffset
;
2596 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2598 // If new end of removed text is greater than old end of added text, it
2599 // means that all or a part of modified range modified again and text
2600 // after the modified range is also modified. Like:
2601 // added range of old change: +----------+
2602 // removed range of new change: +----------+
2603 // So, the new removed end offset is moved by the old change and we need
2604 // to cancel the move of the old change for comparing the offsets in the
2605 // same text because it doesn't make sense to compare the offsets in
2607 uint32_t newRemovedEndOffsetInOldText
=
2608 newData
.mRemovedEndOffset
- oldData
.Difference();
2610 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2611 // The old end of added text is replaced by new change. So, it should be
2612 // same as the new start. On the other hand, the new added end offset is
2613 // always same or larger. Therefore, the merged end offset of added
2614 // text should be the new end offset of added text.
2615 mAddedEndOffset
= newData
.mAddedEndOffset
;
2620 // If new end of removed text is less than old end of added text, it means
2621 // that only a part of the modified range is modified again. Like:
2622 // added range of old change: +------------+
2623 // removed range of new change: +-----+
2624 // So, the new end offset of removed text should be same as the old end
2625 // offset of removed text. Therefore, the merged end offset of removed
2626 // text should be the old text change's |mRemovedEndOffset|.
2627 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2628 // The old end of added text is moved by new change. So, we need to cancel
2629 // the move of the new change for comparing the offsets in same text.
2630 uint32_t oldAddedEndOffsetInNewText
=
2631 oldData
.mAddedEndOffset
+ newData
.Difference();
2633 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2637 if (newData
.mRemovedEndOffset
>= oldData
.mStartOffset
) {
2638 // If new end of removed text is greater than old start (and new start is
2639 // less than old start), it means that a part of modified range is modified
2640 // again and some new text before the modified range is also modified.
2641 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2642 "new start offset should be less than old one here");
2643 mStartOffset
= newData
.mStartOffset
;
2644 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2646 // If new end of removed text is greater than old end of added text, it
2647 // means that all modified text and text after the modified range is
2649 // added range of old change: +----------+
2650 // removed range of new change: +------------------+
2651 // So, the new end of removed text is moved by the old change. Therefore,
2652 // we need to cancel the move of the old change for comparing the offsets
2653 // in same text because it doesn't make sense to compare the offsets in
2655 uint32_t newRemovedEndOffsetInOldText
=
2656 newData
.mRemovedEndOffset
- oldData
.Difference();
2658 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2659 // The old end of added text is replaced by new change. So, the old end
2660 // offset of added text is same as new text change's start offset. Then,
2661 // new change's end offset of added text is always same or larger than
2662 // it. Therefore, merged end offset of added text is always the new end
2663 // offset of added text.
2664 mAddedEndOffset
= newData
.mAddedEndOffset
;
2669 // If new end of removed text is less than old end of added text, it
2670 // means that only a part of the modified range is modified again. Like:
2671 // added range of old change: +----------+
2672 // removed range of new change: +----------+
2673 // So, the new end of removed text should be same as old end of removed
2674 // text for preventing end of removed text to be modified. Therefore,
2675 // merged end offset of removed text is always the old end offset of removed
2677 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2678 // The old end of added text is moved by this change. So, we need to
2679 // cancel the move of the new change for comparing the offsets in same text
2680 // because it doesn't make sense to compare the offsets in different text.
2681 uint32_t oldAddedEndOffsetInNewText
=
2682 oldData
.mAddedEndOffset
+ newData
.Difference();
2684 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2689 // Otherwise, i.e., both new end of added text and new start are less than
2690 // old start, text before the modified range is modified. Like:
2691 // added range of old change: +----------+
2692 // removed range of new change: +----------+
2693 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2694 "new start offset should be less than old one here");
2695 mStartOffset
= newData
.mStartOffset
;
2696 MOZ_ASSERT(newData
.mRemovedEndOffset
< oldData
.mRemovedEndOffset
,
2697 "new removed end offset should be less than old one here");
2698 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2699 // The end of added text should be adjusted with the new difference.
2700 uint32_t oldAddedEndOffsetInNewText
=
2701 oldData
.mAddedEndOffset
+ newData
.Difference();
2703 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2708 // Let's test the code of merging multiple text change data in debug build
2709 // and crash if one of them fails because this feature is very complex but
2710 // cannot be tested with mochitest.
2711 void IMENotification::TextChangeDataBase::Test() {
2712 static bool gTestTextChangeEvent
= true;
2713 if (!gTestTextChangeEvent
) {
2716 gTestTextChangeEvent
= false;
2718 /****************************************************************************
2720 ****************************************************************************/
2723 MergeWith(TextChangeData(10, 10, 20, false, false));
2724 MergeWith(TextChangeData(20, 20, 35, false, false));
2725 MOZ_ASSERT(mStartOffset
== 10,
2726 "Test 1-1-1: mStartOffset should be the first offset");
2728 mRemovedEndOffset
== 10, // 20 - (20 - 10)
2729 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2731 mAddedEndOffset
== 35,
2732 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2735 // Removing text (longer line -> shorter line)
2736 MergeWith(TextChangeData(10, 20, 10, false, false));
2737 MergeWith(TextChangeData(10, 30, 10, false, false));
2738 MOZ_ASSERT(mStartOffset
== 10,
2739 "Test 1-2-1: mStartOffset should be the first offset");
2740 MOZ_ASSERT(mRemovedEndOffset
== 40, // 30 + (10 - 20)
2741 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2743 "with already removed length");
2745 mAddedEndOffset
== 10,
2746 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2749 // Removing text (shorter line -> longer line)
2750 MergeWith(TextChangeData(10, 20, 10, false, false));
2751 MergeWith(TextChangeData(10, 15, 10, false, false));
2752 MOZ_ASSERT(mStartOffset
== 10,
2753 "Test 1-3-1: mStartOffset should be the first offset");
2754 MOZ_ASSERT(mRemovedEndOffset
== 25, // 15 + (10 - 20)
2755 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2757 "with already removed length");
2759 mAddedEndOffset
== 10,
2760 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2763 // Appending text at different point (not sure if actually occurs)
2764 MergeWith(TextChangeData(10, 10, 20, false, false));
2765 MergeWith(TextChangeData(55, 55, 60, false, false));
2766 MOZ_ASSERT(mStartOffset
== 10,
2767 "Test 1-4-1: mStartOffset should be the smallest offset");
2769 mRemovedEndOffset
== 45, // 55 - (10 - 20)
2770 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2771 "text without already added length");
2773 mAddedEndOffset
== 60,
2774 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2777 // Removing text at different point (not sure if actually occurs)
2778 MergeWith(TextChangeData(10, 20, 10, false, false));
2779 MergeWith(TextChangeData(55, 68, 55, false, false));
2780 MOZ_ASSERT(mStartOffset
== 10,
2781 "Test 1-5-1: mStartOffset should be the smallest offset");
2783 mRemovedEndOffset
== 78, // 68 - (10 - 20)
2784 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2785 "text with already removed length");
2787 mAddedEndOffset
== 55,
2788 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2791 // Replacing text and append text (becomes longer)
2792 MergeWith(TextChangeData(30, 35, 32, false, false));
2793 MergeWith(TextChangeData(32, 32, 40, false, false));
2794 MOZ_ASSERT(mStartOffset
== 30,
2795 "Test 1-6-1: mStartOffset should be the smallest offset");
2797 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2798 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2801 mAddedEndOffset
== 40,
2802 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2805 // Replacing text and append text (becomes shorter)
2806 MergeWith(TextChangeData(30, 35, 32, false, false));
2807 MergeWith(TextChangeData(32, 32, 33, false, false));
2808 MOZ_ASSERT(mStartOffset
== 30,
2809 "Test 1-7-1: mStartOffset should be the smallest offset");
2811 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2812 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2815 mAddedEndOffset
== 33,
2816 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2819 // Removing text and replacing text after first range (not sure if actually
2821 MergeWith(TextChangeData(30, 35, 30, false, false));
2822 MergeWith(TextChangeData(32, 34, 48, false, false));
2823 MOZ_ASSERT(mStartOffset
== 30,
2824 "Test 1-8-1: mStartOffset should be the smallest offset");
2825 MOZ_ASSERT(mRemovedEndOffset
== 39, // 34 - (30 - 35)
2826 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2828 "without already removed text");
2830 mAddedEndOffset
== 48,
2831 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2834 // Removing text and replacing text after first range (not sure if actually
2836 MergeWith(TextChangeData(30, 35, 30, false, false));
2837 MergeWith(TextChangeData(32, 38, 36, false, false));
2838 MOZ_ASSERT(mStartOffset
== 30,
2839 "Test 1-9-1: mStartOffset should be the smallest offset");
2840 MOZ_ASSERT(mRemovedEndOffset
== 43, // 38 - (30 - 35)
2841 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2843 "without already removed text");
2845 mAddedEndOffset
== 36,
2846 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2849 /****************************************************************************
2851 ****************************************************************************/
2853 // Replacing text in around end of added text (becomes shorter) (not sure
2854 // if actually occurs)
2855 MergeWith(TextChangeData(50, 50, 55, false, false));
2856 MergeWith(TextChangeData(53, 60, 54, false, false));
2857 MOZ_ASSERT(mStartOffset
== 50,
2858 "Test 2-1-1: mStartOffset should be the smallest offset");
2859 MOZ_ASSERT(mRemovedEndOffset
== 55, // 60 - (55 - 50)
2860 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2862 "without already added text length");
2864 mAddedEndOffset
== 54,
2865 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2868 // Replacing text around end of added text (becomes longer) (not sure
2869 // if actually occurs)
2870 MergeWith(TextChangeData(50, 50, 55, false, false));
2871 MergeWith(TextChangeData(54, 62, 68, false, false));
2872 MOZ_ASSERT(mStartOffset
== 50,
2873 "Test 2-2-1: mStartOffset should be the smallest offset");
2874 MOZ_ASSERT(mRemovedEndOffset
== 57, // 62 - (55 - 50)
2875 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2877 "without already added text length");
2879 mAddedEndOffset
== 68,
2880 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2883 // Replacing text around end of replaced text (became shorter) (not sure if
2885 MergeWith(TextChangeData(36, 48, 45, false, false));
2886 MergeWith(TextChangeData(43, 50, 49, false, false));
2887 MOZ_ASSERT(mStartOffset
== 36,
2888 "Test 2-3-1: mStartOffset should be the smallest offset");
2889 MOZ_ASSERT(mRemovedEndOffset
== 53, // 50 - (45 - 48)
2890 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2892 "without already removed text length");
2894 mAddedEndOffset
== 49,
2895 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2898 // Replacing text around end of replaced text (became longer) (not sure if
2900 MergeWith(TextChangeData(36, 52, 53, false, false));
2901 MergeWith(TextChangeData(43, 68, 61, false, false));
2902 MOZ_ASSERT(mStartOffset
== 36,
2903 "Test 2-4-1: mStartOffset should be the smallest offset");
2904 MOZ_ASSERT(mRemovedEndOffset
== 67, // 68 - (53 - 52)
2905 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2907 "without already added text length");
2909 mAddedEndOffset
== 61,
2910 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2913 /****************************************************************************
2915 ****************************************************************************/
2917 // Appending text in already added text (not sure if actually occurs)
2918 MergeWith(TextChangeData(10, 10, 20, false, false));
2919 MergeWith(TextChangeData(15, 15, 30, false, false));
2920 MOZ_ASSERT(mStartOffset
== 10,
2921 "Test 3-1-1: mStartOffset should be the smallest offset");
2922 MOZ_ASSERT(mRemovedEndOffset
== 10,
2923 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2926 mAddedEndOffset
== 35, // 20 + (30 - 15)
2927 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2928 "added text length by the new change");
2931 // Replacing text in added text (not sure if actually occurs)
2932 MergeWith(TextChangeData(50, 50, 55, false, false));
2933 MergeWith(TextChangeData(52, 53, 56, false, false));
2934 MOZ_ASSERT(mStartOffset
== 50,
2935 "Test 3-2-1: mStartOffset should be the smallest offset");
2936 MOZ_ASSERT(mRemovedEndOffset
== 50,
2937 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2940 mAddedEndOffset
== 58, // 55 + (56 - 53)
2941 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2942 "added text length by the new change");
2945 // Replacing text in replaced text (became shorter) (not sure if actually
2947 MergeWith(TextChangeData(36, 48, 45, false, false));
2948 MergeWith(TextChangeData(37, 38, 50, false, false));
2949 MOZ_ASSERT(mStartOffset
== 36,
2950 "Test 3-3-1: mStartOffset should be the smallest offset");
2951 MOZ_ASSERT(mRemovedEndOffset
== 48,
2952 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2955 mAddedEndOffset
== 57, // 45 + (50 - 38)
2956 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2957 "added text length by the new change");
2960 // Replacing text in replaced text (became longer) (not sure if actually
2962 MergeWith(TextChangeData(32, 48, 53, false, false));
2963 MergeWith(TextChangeData(43, 50, 52, false, false));
2964 MOZ_ASSERT(mStartOffset
== 32,
2965 "Test 3-4-1: mStartOffset should be the smallest offset");
2966 MOZ_ASSERT(mRemovedEndOffset
== 48,
2967 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2969 "without already added text length");
2971 mAddedEndOffset
== 55, // 53 + (52 - 50)
2972 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2973 "added text length by the new change");
2976 // Replacing text in replaced text (became shorter) (not sure if actually
2978 MergeWith(TextChangeData(36, 48, 50, false, false));
2979 MergeWith(TextChangeData(37, 49, 47, false, false));
2980 MOZ_ASSERT(mStartOffset
== 36,
2981 "Test 3-5-1: mStartOffset should be the smallest offset");
2983 mRemovedEndOffset
== 48,
2984 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
2986 MOZ_ASSERT(mAddedEndOffset
== 48, // 50 + (47 - 49)
2987 "Test 3-5-3: mAddedEndOffset should be the first end of added "
2989 "removed text length by the new change");
2992 // Replacing text in replaced text (became longer) (not sure if actually
2994 MergeWith(TextChangeData(32, 48, 53, false, false));
2995 MergeWith(TextChangeData(43, 50, 47, false, false));
2996 MOZ_ASSERT(mStartOffset
== 32,
2997 "Test 3-6-1: mStartOffset should be the smallest offset");
2998 MOZ_ASSERT(mRemovedEndOffset
== 48,
2999 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
3001 "without already added text length");
3002 MOZ_ASSERT(mAddedEndOffset
== 50, // 53 + (47 - 50)
3003 "Test 3-6-3: mAddedEndOffset should be the first end of added "
3005 "removed text length by the new change");
3008 /****************************************************************************
3010 ****************************************************************************/
3012 // Replacing text all of already append text (not sure if actually occurs)
3013 MergeWith(TextChangeData(50, 50, 55, false, false));
3014 MergeWith(TextChangeData(44, 66, 68, false, false));
3015 MOZ_ASSERT(mStartOffset
== 44,
3016 "Test 4-1-1: mStartOffset should be the smallest offset");
3017 MOZ_ASSERT(mRemovedEndOffset
== 61, // 66 - (55 - 50)
3018 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
3020 "without already added text length");
3022 mAddedEndOffset
== 68,
3023 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3026 // Replacing text around a point in which text was removed (not sure if
3028 MergeWith(TextChangeData(50, 62, 50, false, false));
3029 MergeWith(TextChangeData(44, 66, 68, false, false));
3030 MOZ_ASSERT(mStartOffset
== 44,
3031 "Test 4-2-1: mStartOffset should be the smallest offset");
3032 MOZ_ASSERT(mRemovedEndOffset
== 78, // 66 - (50 - 62)
3033 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
3035 "without already removed text length");
3037 mAddedEndOffset
== 68,
3038 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3041 // Replacing text all replaced text (became shorter) (not sure if actually
3043 MergeWith(TextChangeData(50, 62, 60, false, false));
3044 MergeWith(TextChangeData(49, 128, 130, false, false));
3045 MOZ_ASSERT(mStartOffset
== 49,
3046 "Test 4-3-1: mStartOffset should be the smallest offset");
3047 MOZ_ASSERT(mRemovedEndOffset
== 130, // 128 - (60 - 62)
3048 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
3050 "without already removed text length");
3052 mAddedEndOffset
== 130,
3053 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3056 // Replacing text all replaced text (became longer) (not sure if actually
3058 MergeWith(TextChangeData(50, 61, 73, false, false));
3059 MergeWith(TextChangeData(44, 100, 50, false, false));
3060 MOZ_ASSERT(mStartOffset
== 44,
3061 "Test 4-4-1: mStartOffset should be the smallest offset");
3062 MOZ_ASSERT(mRemovedEndOffset
== 88, // 100 - (73 - 61)
3063 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
3065 "with already added text length");
3067 mAddedEndOffset
== 50,
3068 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3071 /****************************************************************************
3073 ****************************************************************************/
3075 // Replacing text around start of added text (not sure if actually occurs)
3076 MergeWith(TextChangeData(50, 50, 55, false, false));
3077 MergeWith(TextChangeData(48, 52, 49, false, false));
3078 MOZ_ASSERT(mStartOffset
== 48,
3079 "Test 5-1-1: mStartOffset should be the smallest offset");
3081 mRemovedEndOffset
== 50,
3082 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
3085 mAddedEndOffset
== 52, // 55 + (52 - 49)
3086 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
3087 "added text length by the new change");
3090 // Replacing text around start of replaced text (became shorter) (not sure if
3092 MergeWith(TextChangeData(50, 60, 58, false, false));
3093 MergeWith(TextChangeData(43, 50, 48, false, false));
3094 MOZ_ASSERT(mStartOffset
== 43,
3095 "Test 5-2-1: mStartOffset should be the smallest offset");
3097 mRemovedEndOffset
== 60,
3098 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3100 MOZ_ASSERT(mAddedEndOffset
== 56, // 58 + (48 - 50)
3101 "Test 5-2-3: mAddedEndOffset should be the first end of added "
3103 "removed text length by the new change");
3106 // Replacing text around start of replaced text (became longer) (not sure if
3108 MergeWith(TextChangeData(50, 60, 68, false, false));
3109 MergeWith(TextChangeData(43, 55, 53, false, false));
3110 MOZ_ASSERT(mStartOffset
== 43,
3111 "Test 5-3-1: mStartOffset should be the smallest offset");
3113 mRemovedEndOffset
== 60,
3114 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3116 MOZ_ASSERT(mAddedEndOffset
== 66, // 68 + (53 - 55)
3117 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3119 "removed text length by the new change");
3122 // Replacing text around start of replaced text (became shorter) (not sure if
3124 MergeWith(TextChangeData(50, 60, 58, false, false));
3125 MergeWith(TextChangeData(43, 50, 128, false, false));
3126 MOZ_ASSERT(mStartOffset
== 43,
3127 "Test 5-4-1: mStartOffset should be the smallest offset");
3129 mRemovedEndOffset
== 60,
3130 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
3133 mAddedEndOffset
== 136, // 58 + (128 - 50)
3134 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
3135 "added text length by the new change");
3138 // Replacing text around start of replaced text (became longer) (not sure if
3140 MergeWith(TextChangeData(50, 60, 68, false, false));
3141 MergeWith(TextChangeData(43, 55, 65, false, false));
3142 MOZ_ASSERT(mStartOffset
== 43,
3143 "Test 5-5-1: mStartOffset should be the smallest offset");
3145 mRemovedEndOffset
== 60,
3146 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
3149 mAddedEndOffset
== 78, // 68 + (65 - 55)
3150 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
3151 "added text length by the new change");
3154 /****************************************************************************
3156 ****************************************************************************/
3158 // Appending text before already added text (not sure if actually occurs)
3159 MergeWith(TextChangeData(30, 30, 45, false, false));
3160 MergeWith(TextChangeData(10, 10, 20, false, false));
3161 MOZ_ASSERT(mStartOffset
== 10,
3162 "Test 6-1-1: mStartOffset should be the smallest offset");
3164 mRemovedEndOffset
== 30,
3165 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3168 mAddedEndOffset
== 55, // 45 + (20 - 10)
3169 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3170 "added text length by the new change");
3173 // Removing text before already removed text (not sure if actually occurs)
3174 MergeWith(TextChangeData(30, 35, 30, false, false));
3175 MergeWith(TextChangeData(10, 25, 10, false, false));
3176 MOZ_ASSERT(mStartOffset
== 10,
3177 "Test 6-2-1: mStartOffset should be the smallest offset");
3179 mRemovedEndOffset
== 35,
3180 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3183 mAddedEndOffset
== 15, // 30 - (25 - 10)
3184 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3185 "removed text length by the new change");
3188 // Replacing text before already replaced text (not sure if actually occurs)
3189 MergeWith(TextChangeData(50, 65, 70, false, false));
3190 MergeWith(TextChangeData(13, 24, 15, false, false));
3191 MOZ_ASSERT(mStartOffset
== 13,
3192 "Test 6-3-1: mStartOffset should be the smallest offset");
3194 mRemovedEndOffset
== 65,
3195 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3197 MOZ_ASSERT(mAddedEndOffset
== 61, // 70 + (15 - 24)
3198 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3200 "removed text length by the new change");
3203 // Replacing text before already replaced text (not sure if actually occurs)
3204 MergeWith(TextChangeData(50, 65, 70, false, false));
3205 MergeWith(TextChangeData(13, 24, 36, false, false));
3206 MOZ_ASSERT(mStartOffset
== 13,
3207 "Test 6-4-1: mStartOffset should be the smallest offset");
3209 mRemovedEndOffset
== 65,
3210 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3212 MOZ_ASSERT(mAddedEndOffset
== 82, // 70 + (36 - 24)
3213 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3215 "removed text length by the new change");
3219 #endif // #ifdef DEBUG
3221 } // namespace mozilla::widget
3224 //////////////////////////////////////////////////////////////
3226 // Convert a GUI event message code to a string.
3227 // Makes it a lot easier to debug events.
3229 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3230 // for a DebugPrintEvent() function that uses
3233 //////////////////////////////////////////////////////////////
3235 nsAutoString
nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent
* aGuiEvent
) {
3236 NS_ASSERTION(nullptr != aGuiEvent
, "cmon, null gui event.");
3238 nsAutoString
eventName(u
"UNKNOWN"_ns
);
3240 # define _ASSIGN_eventName(_value, _name) \
3242 eventName.AssignLiteral(_name); \
3245 switch (aGuiEvent
->mMessage
) {
3246 _ASSIGN_eventName(eBlur
, "eBlur");
3247 _ASSIGN_eventName(eDrop
, "eDrop");
3248 _ASSIGN_eventName(eDragEnter
, "eDragEnter");
3249 _ASSIGN_eventName(eDragExit
, "eDragExit");
3250 _ASSIGN_eventName(eDragOver
, "eDragOver");
3251 _ASSIGN_eventName(eEditorInput
, "eEditorInput");
3252 _ASSIGN_eventName(eFocus
, "eFocus");
3253 _ASSIGN_eventName(eFocusIn
, "eFocusIn");
3254 _ASSIGN_eventName(eFocusOut
, "eFocusOut");
3255 _ASSIGN_eventName(eFormSelect
, "eFormSelect");
3256 _ASSIGN_eventName(eFormChange
, "eFormChange");
3257 _ASSIGN_eventName(eFormReset
, "eFormReset");
3258 _ASSIGN_eventName(eFormSubmit
, "eFormSubmit");
3259 _ASSIGN_eventName(eImageAbort
, "eImageAbort");
3260 _ASSIGN_eventName(eLoadError
, "eLoadError");
3261 _ASSIGN_eventName(eKeyDown
, "eKeyDown");
3262 _ASSIGN_eventName(eKeyPress
, "eKeyPress");
3263 _ASSIGN_eventName(eKeyUp
, "eKeyUp");
3264 _ASSIGN_eventName(eMouseEnterIntoWidget
, "eMouseEnterIntoWidget");
3265 _ASSIGN_eventName(eMouseExitFromWidget
, "eMouseExitFromWidget");
3266 _ASSIGN_eventName(eMouseDown
, "eMouseDown");
3267 _ASSIGN_eventName(eMouseUp
, "eMouseUp");
3268 _ASSIGN_eventName(eMouseClick
, "eMouseClick");
3269 _ASSIGN_eventName(eMouseAuxClick
, "eMouseAuxClick");
3270 _ASSIGN_eventName(eMouseDoubleClick
, "eMouseDoubleClick");
3271 _ASSIGN_eventName(eMouseMove
, "eMouseMove");
3272 _ASSIGN_eventName(eLoad
, "eLoad");
3273 _ASSIGN_eventName(ePopState
, "ePopState");
3274 _ASSIGN_eventName(eBeforeScriptExecute
, "eBeforeScriptExecute");
3275 _ASSIGN_eventName(eAfterScriptExecute
, "eAfterScriptExecute");
3276 _ASSIGN_eventName(eUnload
, "eUnload");
3277 _ASSIGN_eventName(eHashChange
, "eHashChange");
3278 _ASSIGN_eventName(eReadyStateChange
, "eReadyStateChange");
3279 _ASSIGN_eventName(eXULBroadcast
, "eXULBroadcast");
3280 _ASSIGN_eventName(eXULCommandUpdate
, "eXULCommandUpdate");
3282 # undef _ASSIGN_eventName
3285 eventName
.AssignLiteral("UNKNOWN: ");
3286 eventName
.AppendInt(aGuiEvent
->mMessage
);
3290 return nsAutoString(eventName
);
3292 //////////////////////////////////////////////////////////////
3294 // Code to deal with paint and event debug prefs.
3296 //////////////////////////////////////////////////////////////
3302 static PrefPair debug_PrefValues
[] = {
3303 {"nglayout.debug.crossing_event_dumping", false},
3304 {"nglayout.debug.event_dumping", false},
3305 {"nglayout.debug.invalidate_dumping", false},
3306 {"nglayout.debug.motion_event_dumping", false},
3307 {"nglayout.debug.paint_dumping", false}};
3309 //////////////////////////////////////////////////////////////
3310 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName
) {
3311 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3313 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3314 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3315 return debug_PrefValues
[i
].value
;
3321 //////////////////////////////////////////////////////////////
3322 static void debug_SetCachedBoolPref(const char* aPrefName
, bool aValue
) {
3323 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3325 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3326 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3327 debug_PrefValues
[i
].value
= aValue
;
3333 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3336 //////////////////////////////////////////////////////////////
3337 class Debug_PrefObserver final
: public nsIObserver
{
3338 ~Debug_PrefObserver() = default;
3345 NS_IMPL_ISUPPORTS(Debug_PrefObserver
, nsIObserver
)
3348 Debug_PrefObserver::Observe(nsISupports
* subject
, const char* topic
,
3349 const char16_t
* data
) {
3350 NS_ConvertUTF16toUTF8
prefName(data
);
3352 bool value
= Preferences::GetBool(prefName
.get(), false);
3353 debug_SetCachedBoolPref(prefName
.get(), value
);
3357 //////////////////////////////////////////////////////////////
3358 /* static */ void debug_RegisterPrefCallbacks() {
3359 static bool once
= true;
3367 nsCOMPtr
<nsIObserver
> obs(new Debug_PrefObserver());
3368 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3369 // Initialize the pref values
3370 debug_PrefValues
[i
].value
=
3371 Preferences::GetBool(debug_PrefValues
[i
].name
, false);
3374 // Register callbacks for when these change
3376 name
.AssignLiteral(debug_PrefValues
[i
].name
,
3377 strlen(debug_PrefValues
[i
].name
));
3378 Preferences::AddStrongObserver(obs
, name
);
3382 //////////////////////////////////////////////////////////////
3383 static int32_t _GetPrintCount() {
3384 static int32_t sCount
= 0;
3388 //////////////////////////////////////////////////////////////
3390 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3391 WidgetGUIEvent
* aGuiEvent
,
3392 const char* aWidgetName
, int32_t aWindowID
) {
3393 if (aGuiEvent
->mMessage
== eMouseMove
) {
3394 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3397 if (aGuiEvent
->mMessage
== eMouseEnterIntoWidget
||
3398 aGuiEvent
->mMessage
== eMouseExitFromWidget
) {
3399 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3403 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3405 NS_LossyConvertUTF16toASCII
tempString(
3406 debug_GuiEventToString(aGuiEvent
).get());
3408 fprintf(aFileOut
, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3409 _GetPrintCount(), tempString
.get(), (void*)aWidget
, aWidgetName
,
3410 aWindowID
, aGuiEvent
->mRefPoint
.x
.value
,
3411 aGuiEvent
->mRefPoint
.y
.value
);
3413 //////////////////////////////////////////////////////////////
3415 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3416 const nsIntRegion
& aRegion
,
3417 const char* aWidgetName
,
3418 int32_t aWindowID
) {
3419 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3420 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3422 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3424 nsIntRect rect
= aRegion
.GetBounds();
3426 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3428 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
, rect
.X(),
3429 rect
.Y(), rect
.Width(), rect
.Height());
3431 fprintf(aFileOut
, "\n");
3433 //////////////////////////////////////////////////////////////
3435 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut
, nsIWidget
* aWidget
,
3436 const LayoutDeviceIntRect
* aRect
,
3437 const char* aWidgetName
,
3438 int32_t aWindowID
) {
3439 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3441 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3442 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3444 fprintf(aFileOut
, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3445 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
);
3448 fprintf(aFileOut
, " rect=%3d,%-3d %3d,%-3d", aRect
->X(), aRect
->Y(),
3449 aRect
->Width(), aRect
->Height());
3451 fprintf(aFileOut
, " rect=%-15s", "none");
3454 fprintf(aFileOut
, "\n");
3456 //////////////////////////////////////////////////////////////