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