2 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
3 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
4 /* This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 #include "nsBaseWidget.h"
13 #include "InputData.h"
14 #include "LiveResizeListener.h"
15 #include "SwipeTracker.h"
16 #include "TouchEvents.h"
17 #include "X11UndefineNone.h"
18 #include "base/thread.h"
19 #include "mozilla/ArrayUtils.h"
20 #include "mozilla/Attributes.h"
21 #include "mozilla/GlobalKeyListener.h"
22 #include "mozilla/IMEStateManager.h"
23 #include "mozilla/Logging.h"
24 #include "mozilla/MouseEvents.h"
25 #include "mozilla/NativeKeyBindingsType.h"
26 #include "mozilla/Preferences.h"
27 #include "mozilla/PresShell.h"
28 #include "mozilla/ScopeExit.h"
29 #include "mozilla/Sprintf.h"
30 #include "mozilla/StaticPrefs_apz.h"
31 #include "mozilla/StaticPrefs_dom.h"
32 #include "mozilla/StaticPrefs_gfx.h"
33 #include "mozilla/StaticPrefs_layers.h"
34 #include "mozilla/StaticPrefs_layout.h"
35 #include "mozilla/TextEventDispatcher.h"
36 #include "mozilla/TextEventDispatcherListener.h"
37 #include "mozilla/UniquePtr.h"
38 #include "mozilla/Unused.h"
39 #include "mozilla/VsyncDispatcher.h"
40 #include "mozilla/dom/BrowserParent.h"
41 #include "mozilla/dom/ContentChild.h"
42 #include "mozilla/dom/Document.h"
43 #include "mozilla/dom/SimpleGestureEventBinding.h"
44 #include "mozilla/gfx/2D.h"
45 #include "mozilla/gfx/GPUProcessManager.h"
46 #include "mozilla/gfx/gfxVars.h"
47 #include "mozilla/layers/APZCCallbackHelper.h"
48 #include "mozilla/layers/TouchActionHelper.h"
49 #include "mozilla/layers/APZEventState.h"
50 #include "mozilla/layers/APZInputBridge.h"
51 #include "mozilla/layers/APZThreadUtils.h"
52 #include "mozilla/layers/ChromeProcessController.h"
53 #include "mozilla/layers/Compositor.h"
54 #include "mozilla/layers/CompositorBridgeChild.h"
55 #include "mozilla/layers/CompositorBridgeParent.h"
56 #include "mozilla/layers/CompositorOptions.h"
57 #include "mozilla/layers/IAPZCTreeManager.h"
58 #include "mozilla/layers/ImageBridgeChild.h"
59 #include "mozilla/layers/InputAPZContext.h"
60 #include "mozilla/layers/WebRenderLayerManager.h"
61 #include "mozilla/webrender/WebRenderTypes.h"
62 #include "mozilla/widget/ScreenManager.h"
63 #include "nsAppDirectoryServiceDefs.h"
65 #include "nsContentUtils.h"
66 #include "nsDeviceContext.h"
67 #include "nsGfxCIID.h"
68 #include "nsIAppWindow.h"
69 #include "nsIBaseWindow.h"
70 #include "nsIContent.h"
71 #include "nsIScreenManager.h"
72 #include "nsISimpleEnumerator.h"
73 #include "nsIWidgetListener.h"
74 #include "nsRefPtrHashtable.h"
75 #include "nsServiceManagerUtils.h"
76 #include "nsWidgetsCID.h"
77 #include "nsXULPopupManager.h"
81 # include "nsAccessibilityService.h"
83 #include "gfxConfig.h"
84 #include "gfxUtils.h" // for ToDeviceColor
85 #include "mozilla/layers/CompositorSession.h"
86 #include "VRManagerChild.h"
87 #include "gfxConfig.h"
89 #include "nsViewManager.h"
91 static mozilla::LazyLogModule
sBaseWidgetLog("BaseWidget");
94 # include "nsIObserver.h"
96 static void debug_RegisterPrefCallbacks();
100 #ifdef NOISY_WIDGET_LEAKS
101 static int32_t gNumWidgets
;
104 using namespace mozilla::dom
;
105 using namespace mozilla::layers
;
106 using namespace mozilla::ipc
;
107 using namespace mozilla::widget
;
108 using namespace mozilla
;
110 // Async pump timer during injected long touch taps
111 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
112 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
113 int32_t nsIWidget::sPointerIdCounter
= 0;
115 // Some statics from nsIWidget.h
117 uint64_t AutoObserverNotifier::sObserverId
= 0;
118 /*static*/ nsTHashMap
<uint64_t, nsCOMPtr
<nsIObserver
>>
119 AutoObserverNotifier::sSavedObservers
;
121 // The maximum amount of time to let the EnableDragDrop runnable wait in the
122 // idle queue before timing out and moving it to the regular queue. Value is in
124 const uint32_t kAsyncDragDropTimeout
= 1000;
126 NS_IMPL_ISUPPORTS(nsBaseWidget
, nsIWidget
, nsISupportsWeakReference
)
128 //-------------------------------------------------------------------------
130 // nsBaseWidget constructor
132 //-------------------------------------------------------------------------
134 nsBaseWidget::nsBaseWidget() : nsBaseWidget(BorderStyle::None
) {}
136 nsBaseWidget::nsBaseWidget(BorderStyle aBorderStyle
)
137 : mWidgetListener(nullptr),
138 mAttachedWidgetListener(nullptr),
139 mPreviouslyAttachedWidgetListener(nullptr),
140 mCompositorVsyncDispatcher(nullptr),
141 mBorderStyle(aBorderStyle
),
144 mPopupLevel(PopupLevel::Top
),
145 mPopupType(PopupType::Any
),
146 mHasRemoteContent(false),
148 mUseAttachedEvents(false),
151 mIsFullyOccluded(false),
152 mNeedFastSnaphot(false),
153 mCurrentPanGestureBelongsToSwipe(false),
154 mIsPIPWindow(false) {
155 #ifdef NOISY_WIDGET_LEAKS
157 printf("WIDGETS+ = %d\n", gNumWidgets
);
161 debug_RegisterPrefCallbacks();
164 mShutdownObserver
= new WidgetShutdownObserver(this);
167 NS_IMPL_ISUPPORTS(WidgetShutdownObserver
, nsIObserver
)
169 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget
* aWidget
)
170 : mWidget(aWidget
), mRegistered(false) {
174 WidgetShutdownObserver::~WidgetShutdownObserver() {
175 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
176 // gets torn down. The observer service and nsBaseWidget have a ref on us
177 // so nsBaseWidget has to call Unregister and then clear its ref.
181 WidgetShutdownObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
182 const char16_t
* aData
) {
186 if (!strcmp(aTopic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
)) {
187 RefPtr
<nsBaseWidget
> widget(mWidget
);
189 } else if (!strcmp(aTopic
, "quit-application")) {
190 RefPtr
<nsBaseWidget
> widget(mWidget
);
196 void WidgetShutdownObserver::Register() {
199 nsContentUtils::RegisterShutdownObserver(this);
201 #ifndef MOZ_WIDGET_ANDROID
202 // The primary purpose of observing quit-application is
203 // to avoid leaking a widget on Windows when nothing else
204 // breaks the circular reference between the widget and
205 // TSFTextStore. However, our Android IME code crashes if
206 // doing this on Android, so let's not do this on Android.
207 // Doing this on Gtk and Mac just in case.
208 nsCOMPtr
<nsIObserverService
> observerService
=
209 mozilla::services::GetObserverService();
210 if (observerService
) {
211 observerService
->AddObserver(this, "quit-application", false);
217 void WidgetShutdownObserver::Unregister() {
221 #ifndef MOZ_WIDGET_ANDROID
222 nsCOMPtr
<nsIObserverService
> observerService
=
223 mozilla::services::GetObserverService();
224 if (observerService
) {
225 observerService
->RemoveObserver(this, "quit-application");
229 nsContentUtils::UnregisterShutdownObserver(this);
234 #define INTL_APP_LOCALES_CHANGED "intl:app-locales-changed"
236 NS_IMPL_ISUPPORTS(LocalesChangedObserver
, nsIObserver
)
238 LocalesChangedObserver::LocalesChangedObserver(nsBaseWidget
* aWidget
)
239 : mWidget(aWidget
), mRegistered(false) {
243 LocalesChangedObserver::~LocalesChangedObserver() {
244 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
245 // gets torn down. The observer service and nsBaseWidget have a ref on us
246 // so nsBaseWidget has to call Unregister and then clear its ref.
250 LocalesChangedObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
251 const char16_t
* aData
) {
255 if (!strcmp(aTopic
, INTL_APP_LOCALES_CHANGED
)) {
256 RefPtr
<nsBaseWidget
> widget(mWidget
);
257 widget
->LocalesChanged();
262 void LocalesChangedObserver::Register() {
267 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
269 obs
->AddObserver(this, INTL_APP_LOCALES_CHANGED
, true);
272 // Locale might be update before registering
273 RefPtr
<nsBaseWidget
> widget(mWidget
);
274 widget
->LocalesChanged();
279 void LocalesChangedObserver::Unregister() {
284 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
286 obs
->RemoveObserver(this, INTL_APP_LOCALES_CHANGED
);
293 void nsBaseWidget::Shutdown() {
294 NotifyLiveResizeStopped();
296 FreeLocalesChangedObserver();
297 FreeShutdownObserver();
300 void nsBaseWidget::QuitIME() {
301 IMEStateManager::WidgetOnQuit(this);
302 this->mIMEHasQuit
= true;
305 void nsBaseWidget::DestroyCompositor() {
306 RevokeTransactionIdAllocator();
308 // We release this before releasing the compositor, since it may hold the
309 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
310 // trigger a paint, creating a new compositor, and we don't want to re-use
311 // the old vsync dispatcher.
312 if (mCompositorVsyncDispatcher
) {
313 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
315 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
316 mCompositorVsyncDispatcher
->Shutdown();
317 mCompositorVsyncDispatcher
= nullptr;
320 // The compositor shutdown sequence looks like this:
321 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
322 // 2. CompositorBridgeChild synchronously sends WillClose.
323 // 3. CompositorBridgeParent releases some resources (such as the layer
324 // manager, compositor, and widget).
325 // 4. CompositorBridgeChild::Destroy returns.
326 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
327 // compositor thread when the I/O thread closes the IPC channel.
328 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
329 // releases the reference CompositorBridgeParent holds to itself.
331 // When CompositorSession::Shutdown returns, we assume the compositor is gone
332 // or will be gone very soon.
333 if (mCompositorSession
) {
334 ReleaseContentController();
336 SetCompositorWidgetDelegate(nullptr);
337 mCompositorBridgeChild
= nullptr;
338 mCompositorSession
->Shutdown();
339 mCompositorSession
= nullptr;
343 // This prevents the layer manager from starting a new transaction during
345 void nsBaseWidget::RevokeTransactionIdAllocator() {
346 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
349 mWindowRenderer
->AsWebRender()->SetTransactionIdAllocator(nullptr);
352 void nsBaseWidget::ReleaseContentController() {
353 if (mRootContentController
) {
354 mRootContentController
->Destroy();
355 mRootContentController
= nullptr;
359 void nsBaseWidget::DestroyLayerManager() {
360 if (mWindowRenderer
) {
361 mWindowRenderer
->Destroy();
362 mWindowRenderer
= nullptr;
367 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
369 void nsBaseWidget::FreeShutdownObserver() {
370 if (mShutdownObserver
) {
371 mShutdownObserver
->Unregister();
373 mShutdownObserver
= nullptr;
376 void nsBaseWidget::FreeLocalesChangedObserver() {
377 if (mLocalesChangedObserver
) {
378 mLocalesChangedObserver
->Unregister();
380 mLocalesChangedObserver
= nullptr;
383 //-------------------------------------------------------------------------
385 // nsBaseWidget destructor
387 //-------------------------------------------------------------------------
389 nsBaseWidget::~nsBaseWidget() {
391 mSwipeTracker
->Destroy();
392 mSwipeTracker
= nullptr;
395 IMEStateManager::WidgetDestroyed(this);
397 FreeLocalesChangedObserver();
398 FreeShutdownObserver();
399 DestroyLayerManager();
401 #ifdef NOISY_WIDGET_LEAKS
403 printf("WIDGETS- = %d\n", gNumWidgets
);
407 //-------------------------------------------------------------------------
411 //-------------------------------------------------------------------------
412 void nsBaseWidget::BaseCreate(nsIWidget
* aParent
, widget::InitData
* aInitData
) {
414 mWindowType
= aInitData
->mWindowType
;
415 mBorderStyle
= aInitData
->mBorderStyle
;
416 mPopupLevel
= aInitData
->mPopupLevel
;
417 mPopupType
= aInitData
->mPopupHint
;
418 mHasRemoteContent
= aInitData
->mHasRemoteContent
;
419 mIsPIPWindow
= aInitData
->mPIPWindow
;
423 aParent
->AddChild(this);
427 //-------------------------------------------------------------------------
429 // Accessor functions to get/set the client data
431 //-------------------------------------------------------------------------
433 nsIWidgetListener
* nsBaseWidget::GetWidgetListener() const {
434 return mWidgetListener
;
437 void nsBaseWidget::SetWidgetListener(nsIWidgetListener
* aWidgetListener
) {
438 mWidgetListener
= aWidgetListener
;
441 already_AddRefed
<nsIWidget
> nsBaseWidget::CreateChild(
442 const LayoutDeviceIntRect
& aRect
, widget::InitData
* aInitData
,
443 bool aForceUseIWidgetParent
) {
444 nsIWidget
* parent
= this;
445 nsNativeWidget nativeParent
= nullptr;
447 if (!aForceUseIWidgetParent
) {
448 // Use only either parent or nativeParent, not both, to match
449 // existing code. Eventually Create() should be divested of its
450 // nativeWidget parameter.
451 nativeParent
= parent
? parent
->GetNativeData(NS_NATIVE_WIDGET
) : nullptr;
452 parent
= nativeParent
? nullptr : parent
;
453 MOZ_ASSERT(!parent
|| !nativeParent
, "messed up logic");
456 nsCOMPtr
<nsIWidget
> widget
;
457 if (aInitData
&& aInitData
->mWindowType
== WindowType::Popup
) {
458 widget
= AllocateChildPopupWidget();
460 widget
= nsIWidget::CreateChildWindow();
463 if (widget
&& mNeedFastSnaphot
) {
464 widget
->SetNeedFastSnaphot();
468 NS_SUCCEEDED(widget
->Create(parent
, nativeParent
, aRect
, aInitData
))) {
469 return widget
.forget();
475 // Attach a view to our widget which we'll send events to.
476 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents
) {
477 NS_ASSERTION((mWindowType
== WindowType::TopLevel
||
478 mWindowType
== WindowType::Dialog
||
479 mWindowType
== WindowType::Invisible
||
480 mWindowType
== WindowType::Child
),
481 "Can't attach to window of that type");
483 mUseAttachedEvents
= aUseAttachedEvents
;
486 nsIWidgetListener
* nsBaseWidget::GetAttachedWidgetListener() const {
487 return mAttachedWidgetListener
;
490 nsIWidgetListener
* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
491 return mPreviouslyAttachedWidgetListener
;
494 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
495 nsIWidgetListener
* aListener
) {
496 mPreviouslyAttachedWidgetListener
= aListener
;
499 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener
* aListener
) {
500 mAttachedWidgetListener
= aListener
;
503 //-------------------------------------------------------------------------
505 // Close this nsBaseWidget
507 //-------------------------------------------------------------------------
508 void nsBaseWidget::Destroy() {
511 // Just in case our parent is the only ref to us
512 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
513 // disconnect from the parent
514 nsIWidget
* parent
= GetParent();
516 parent
->RemoveChild(this);
520 //-------------------------------------------------------------------------
522 // Get this nsBaseWidget parent
524 //-------------------------------------------------------------------------
525 nsIWidget
* nsBaseWidget::GetParent(void) { return nullptr; }
527 //-------------------------------------------------------------------------
529 // Get this nsBaseWidget top level widget
531 //-------------------------------------------------------------------------
532 nsIWidget
* nsBaseWidget::GetTopLevelWidget() {
533 nsIWidget
*topLevelWidget
= nullptr, *widget
= this;
535 topLevelWidget
= widget
;
536 widget
= widget
->GetParent();
538 return topLevelWidget
;
541 //-------------------------------------------------------------------------
543 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
545 //-------------------------------------------------------------------------
546 nsIWidget
* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
548 float nsBaseWidget::GetDPI() { return 96.0f
; }
550 CSSToLayoutDeviceScale
nsIWidget::GetDefaultScale() {
551 double devPixelsPerCSSPixel
= StaticPrefs::layout_css_devPixelsPerPx();
553 if (devPixelsPerCSSPixel
<= 0.0) {
554 devPixelsPerCSSPixel
= GetDefaultScaleInternal();
557 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel
);
560 nsIntSize
nsIWidget::CustomCursorSize(const Cursor
& aCursor
) {
561 MOZ_ASSERT(aCursor
.IsCustom());
564 aCursor
.mContainer
->GetWidth(&width
);
565 aCursor
.mContainer
->GetHeight(&height
);
566 aCursor
.mResolution
.ApplyTo(width
, height
);
567 return {width
, height
};
570 LayoutDeviceIntSize
nsIWidget::ClientToWindowSizeDifference() {
571 auto margin
= ClientToWindowMargin();
572 MOZ_ASSERT(margin
.top
>= 0, "Window should be bigger than client area");
573 MOZ_ASSERT(margin
.left
>= 0, "Window should be bigger than client area");
574 MOZ_ASSERT(margin
.right
>= 0, "Window should be bigger than client area");
575 MOZ_ASSERT(margin
.bottom
>= 0, "Window should be bigger than client area");
576 return {margin
.LeftRight(), margin
.TopBottom()};
579 RefPtr
<mozilla::VsyncDispatcher
> nsIWidget::GetVsyncDispatcher() {
583 //-------------------------------------------------------------------------
585 // Add a child to the list of children
587 //-------------------------------------------------------------------------
588 void nsBaseWidget::AddChild(nsIWidget
* aChild
) {
589 MOZ_ASSERT(!aChild
->GetNextSibling() && !aChild
->GetPrevSibling(),
590 "aChild not properly removed from its old child list");
593 mFirstChild
= mLastChild
= aChild
;
595 // append to the list
596 MOZ_ASSERT(mLastChild
);
597 MOZ_ASSERT(!mLastChild
->GetNextSibling());
598 mLastChild
->SetNextSibling(aChild
);
599 aChild
->SetPrevSibling(mLastChild
);
604 //-------------------------------------------------------------------------
606 // Remove a child from the list of children
608 //-------------------------------------------------------------------------
609 void nsBaseWidget::RemoveChild(nsIWidget
* aChild
) {
612 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
613 // null and we'll just have to do without this assertion.
614 nsIWidget
* parent
= aChild
->GetParent();
615 NS_ASSERTION(!parent
|| parent
== this, "Not one of our kids!");
617 MOZ_RELEASE_ASSERT(aChild
->GetParent() == this, "Not one of our kids!");
621 if (mLastChild
== aChild
) {
622 mLastChild
= mLastChild
->GetPrevSibling();
624 if (mFirstChild
== aChild
) {
625 mFirstChild
= mFirstChild
->GetNextSibling();
628 // Now remove from the list. Make sure that we pass ownership of the tail
629 // of the list correctly before we have aChild let go of it.
630 nsIWidget
* prev
= aChild
->GetPrevSibling();
631 nsIWidget
* next
= aChild
->GetNextSibling();
633 prev
->SetNextSibling(next
);
636 next
->SetPrevSibling(prev
);
639 aChild
->SetNextSibling(nullptr);
640 aChild
->SetPrevSibling(nullptr);
643 //-------------------------------------------------------------------------
645 // Sets widget's position within its parent's child list.
647 //-------------------------------------------------------------------------
648 void nsBaseWidget::SetZIndex(int32_t aZIndex
) {
649 // Hold a ref to ourselves just in case, since we're going to remove
651 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
655 // reorder this child in its parent's list.
656 auto* parent
= static_cast<nsBaseWidget
*>(GetParent());
658 parent
->RemoveChild(this);
659 // Scope sib outside the for loop so we can check it afterward
660 nsIWidget
* sib
= parent
->GetFirstChild();
661 for (; sib
; sib
= sib
->GetNextSibling()) {
662 int32_t childZIndex
= GetZIndex();
663 if (aZIndex
< childZIndex
) {
664 // Insert ourselves before sib
665 nsIWidget
* prev
= sib
->GetPrevSibling();
668 sib
->SetPrevSibling(this);
670 prev
->SetNextSibling(this);
672 NS_ASSERTION(sib
== parent
->mFirstChild
, "Broken child list");
673 // We've taken ownership of sib, so it's safe to have parent let
675 parent
->mFirstChild
= this;
677 PlaceBehind(eZPlacementBelow
, sib
, false);
681 // were we added to the list?
683 parent
->AddChild(this);
688 void nsBaseWidget::GetWorkspaceID(nsAString
& workspaceID
) {
689 workspaceID
.Truncate();
692 void nsBaseWidget::MoveToWorkspace(const nsAString
& workspaceID
) {
696 //-------------------------------------------------------------------------
698 // Get this component cursor
700 //-------------------------------------------------------------------------
702 void nsBaseWidget::SetCursor(const Cursor
& aCursor
) { mCursor
= aCursor
; }
704 //-------------------------------------------------------------------------
706 // Window transparency methods
708 //-------------------------------------------------------------------------
710 void nsBaseWidget::SetTransparencyMode(TransparencyMode aMode
) {}
712 TransparencyMode
nsBaseWidget::GetTransparencyMode() {
713 return TransparencyMode::Opaque
;
717 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage
,
720 nsIRunnable
* aCallback
) {
721 MOZ_ASSERT_UNREACHABLE(
722 "Should never call PerformFullscreenTransition on nsBaseWidget");
725 //-------------------------------------------------------------------------
727 // Put the window into full-screen mode
729 //-------------------------------------------------------------------------
730 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen
) {
731 #define MOZ_FORMAT_RECT(fmtstr) "[" fmtstr "," fmtstr " " fmtstr "x" fmtstr "]"
732 #define MOZ_SPLAT_RECT(rect) \
733 (rect).X(), (rect).Y(), (rect).Width(), (rect).Height()
735 // Windows which can be made fullscreen are exactly those which are located on
736 // the desktop, rather than being a child of some other window.
737 MOZ_DIAGNOSTIC_ASSERT(BoundsUseDesktopPixels(),
738 "non-desktop windows cannot be made fullscreen");
740 // Ensure that the OS chrome is hidden/shown before we resize and/or exit the
743 // HideWindowChrome() may (depending on platform, implementation details, and
744 // OS-level user preferences) alter the reported size of the window. The
745 // obvious and principled solution is socks-and-shoes:
746 // - On entering fullscreen mode: hide window chrome, then perform resize.
747 // - On leaving fullscreen mode: unperform resize, then show window chrome.
749 // ... unfortunately, HideWindowChrome() requires Resize() to be called
750 // afterwards (see bug 498835), which prevents this from being done in a
751 // straightforward way.
753 // Instead, we always call HideWindowChrome() just before we call Resize().
754 // This at least ensures that our measurements are consistently taken in a
755 // pre-transition state.
757 // ... unfortunately again, coupling HideWindowChrome() to Resize() means that
758 // we have to worry about the possibility of control flows that don't call
759 // Resize() at all. (That shouldn't happen, but it's not trivial to rule out.)
760 // We therefore set up a fallback to fix up the OS chrome if it hasn't been
761 // done at exit time.
762 bool hasAdjustedOSChrome
= false;
763 const auto adjustOSChrome
= [&]() {
764 if (hasAdjustedOSChrome
) {
765 MOZ_ASSERT_UNREACHABLE("window chrome should only be adjusted once");
768 HideWindowChrome(aFullScreen
);
769 hasAdjustedOSChrome
= true;
771 const auto adjustChromeOnScopeExit
= MakeScopeExit([&]() {
772 if (hasAdjustedOSChrome
) {
776 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
777 ("window was not resized within InfallibleMakeFullScreen()"));
779 // Hide chrome and "resize" the window to its current size.
780 auto rect
= GetBounds();
782 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
785 // Attempt to resize to `rect`.
787 // Returns the actual rectangle resized to. (This may differ from `rect`, if
788 // the OS is unhappy with it. See bug 1786226.)
789 const auto doReposition
= [&](auto rect
) -> void {
790 static_assert(std::is_base_of_v
<DesktopPixel
,
791 std::remove_reference_t
<decltype(rect
)>>,
792 "doReposition requires a rectangle using desktop pixels");
794 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Debug
)) {
795 const DesktopRect previousSize
=
796 GetScreenBounds() / GetDesktopToDeviceScale();
797 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
798 ("before resize: " MOZ_FORMAT_RECT("%f"),
799 MOZ_SPLAT_RECT(previousSize
)));
803 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
805 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Warning
)) {
806 // `rect` may have any underlying data type; coerce to float to
807 // simplify printf-style logging
808 const gfx::RectTyped
<DesktopPixel
, float> rectAsFloat
{rect
};
810 // The OS may have objected to the target position. That's not necessarily
811 // a problem -- it'll happen regularly on Macs with camera notches in the
812 // monitor, for instance (see bug 1786226) -- but it probably deserves to
815 // Since there's floating-point math involved, the actual values may be
816 // off by a few ulps -- as an upper bound, perhaps 8 * FLT_EPSILON *
817 // max(MOZ_SPLAT_RECT(rect)) -- but 0.01 should be several orders of
818 // magnitude bigger than that.
820 const auto postResizeRectRaw
= GetScreenBounds();
821 const auto postResizeRect
= postResizeRectRaw
/ GetDesktopToDeviceScale();
822 const bool succeeded
= postResizeRect
.WithinEpsilonOf(rectAsFloat
, 0.01);
825 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
826 ("resized to: " MOZ_FORMAT_RECT("%f"),
827 MOZ_SPLAT_RECT(rectAsFloat
)));
829 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
830 ("attempted to resize to: " MOZ_FORMAT_RECT("%f"),
831 MOZ_SPLAT_RECT(rectAsFloat
)));
832 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
833 ("... but ended up at: " MOZ_FORMAT_RECT("%f"),
834 MOZ_SPLAT_RECT(postResizeRect
)));
838 sBaseWidgetLog
, LogLevel::Verbose
,
839 ("(... which, before DPI adjustment, is:" MOZ_FORMAT_RECT("%d") ")",
840 MOZ_SPLAT_RECT(postResizeRectRaw
)));
846 mSavedBounds
= Some(FullscreenSavedState());
848 // save current position
849 mSavedBounds
->windowRect
= GetScreenBounds() / GetDesktopToDeviceScale();
851 nsCOMPtr
<nsIScreen
> screen
= GetWidgetScreen();
856 // Move to fill the screen.
857 doReposition(screen
->GetRectDisplayPix());
858 // Save off the new position. (This may differ from GetRectDisplayPix(), if
859 // the OS was unhappy with it. See bug 1786226.)
860 mSavedBounds
->screenRect
= GetScreenBounds() / GetDesktopToDeviceScale();
863 // This should never happen, at present, since we don't make windows
864 // fullscreen at their creation time; but it's not logically impossible.
865 MOZ_ASSERT(false, "fullscreen window did not have saved position");
869 // Figure out where to go from here.
871 // Fortunately, since we're currently fullscreen (and other code should be
872 // handling _keeping_ us fullscreen even after display-layout changes),
873 // there's an obvious choice for which display we should attach to; all we
874 // need to determine is where on that display we should go.
876 const DesktopRect currentWinRect
=
877 GetScreenBounds() / GetDesktopToDeviceScale();
879 // Optimization: if where we are is where we were, then where we originally
880 // came from is where we're going to go.
881 if (currentWinRect
== DesktopRect(mSavedBounds
->screenRect
)) {
882 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
883 ("no location change detected; returning to saved location"));
884 doReposition(mSavedBounds
->windowRect
);
889 General case: figure out where we're going to go by dividing where we are
890 by where we were, and then multiplying by where we originally came from.
892 Less abstrusely: resize so that we occupy the same proportional position
893 on our current display after leaving fullscreen as we occupied on our
894 previous display before entering fullscreen.
896 (N.B.: We do not clamp. If we were only partially on the old display,
897 we'll be only partially on the new one, too.)
900 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
901 ("location change detected; computing new destination"));
903 // splat: convert an arbitrary Rect into a tuple, for syntactic convenience.
904 const auto splat
= [](auto rect
) {
905 return std::tuple(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height());
908 // remap: find the unique affine mapping which transforms `src` to `dst`,
909 // and apply it to `val`.
910 using Range
= std::pair
<float, float>;
911 const auto remap
= [](Range dst
, Range src
, float val
) {
912 // linear interpolation and its inverse: lerp(a, b, invlerp(a, b, t)) == t
913 const auto lerp
= [](float lo
, float hi
, float t
) {
914 return lo
+ t
* (hi
- lo
);
916 const auto invlerp
= [](float lo
, float hi
, float mid
) {
917 return (mid
- lo
) / (hi
- lo
);
920 const auto [dst_a
, dst_b
] = dst
;
921 const auto [src_a
, src_b
] = src
;
922 return lerp(dst_a
, dst_b
, invlerp(src_a
, src_b
, val
));
926 const auto [px
, py
, pw
, ph
] = splat(mSavedBounds
->windowRect
);
927 // source desktop rect
928 const auto [sx
, sy
, sw
, sh
] = splat(mSavedBounds
->screenRect
);
929 // target desktop rect
930 const auto [tx
, ty
, tw
, th
] = splat(currentWinRect
);
932 const float nx
= remap({tx
, tx
+ tw
}, {sx
, sx
+ sw
}, px
);
933 const float ny
= remap({ty
, ty
+ th
}, {sy
, sy
+ sh
}, py
);
934 const float nw
= remap({0, tw
}, {0, sw
}, pw
);
935 const float nh
= remap({0, th
}, {0, sh
}, ph
);
937 doReposition(DesktopRect
{nx
, ny
, nw
, nh
});
940 #undef MOZ_SPLAT_RECT
941 #undef MOZ_FORMAT_RECT
944 nsresult
nsBaseWidget::MakeFullScreen(bool aFullScreen
) {
945 InfallibleMakeFullScreen(aFullScreen
);
949 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
950 nsBaseWidget
* aWidget
, gfxContext
* aTarget
, BufferMode aDoubleBuffering
)
952 WindowRenderer
* renderer
= mWidget
->GetWindowRenderer();
953 if (renderer
->AsFallback()) {
954 mRenderer
= renderer
->AsFallback();
955 mRenderer
->SetTarget(aTarget
, aDoubleBuffering
);
959 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
961 mRenderer
->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE
);
965 bool nsBaseWidget::IsSmallPopup() const {
966 return mWindowType
== WindowType::Popup
&& mPopupType
!= PopupType::Panel
;
969 bool nsBaseWidget::ComputeShouldAccelerate() {
970 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING
) &&
971 (WidgetTypeSupportsAcceleration() ||
972 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
975 bool nsBaseWidget::UseAPZ() {
976 return (gfxPlatform::AsyncPanZoomEnabled() &&
977 (mWindowType
== WindowType::TopLevel
||
978 mWindowType
== WindowType::Child
||
979 ((mWindowType
== WindowType::Popup
||
980 mWindowType
== WindowType::Dialog
) &&
981 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
984 void nsBaseWidget::CreateCompositor() {
985 LayoutDeviceIntRect rect
= GetBounds();
986 CreateCompositor(rect
.Width(), rect
.Height());
989 void nsIWidget::PauseOrResumeCompositor(bool aPause
) {
990 auto* renderer
= GetRemoteRenderer();
995 renderer
->SendPause();
997 renderer
->SendResume();
1001 already_AddRefed
<GeckoContentController
>
1002 nsBaseWidget::CreateRootContentController() {
1003 RefPtr
<GeckoContentController
> controller
=
1004 new ChromeProcessController(this, mAPZEventState
, mAPZC
);
1005 return controller
.forget();
1008 void nsBaseWidget::ConfigureAPZCTreeManager() {
1009 MOZ_ASSERT(NS_IsMainThread());
1012 mAPZC
->SetDPI(GetDPI());
1014 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
1015 KeyboardMap map
= RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
1016 mAPZC
->SetKeyboardMap(map
);
1019 ContentReceivedInputBlockCallback
callback(
1020 [treeManager
= RefPtr
{mAPZC
.get()}](uint64_t aInputBlockId
,
1021 bool aPreventDefault
) {
1022 MOZ_ASSERT(NS_IsMainThread());
1023 treeManager
->ContentReceivedInputBlock(aInputBlockId
, aPreventDefault
);
1025 mAPZEventState
= new APZEventState(this, std::move(callback
));
1027 mRootContentController
= CreateRootContentController();
1028 if (mRootContentController
) {
1029 mCompositorSession
->SetContentController(mRootContentController
);
1032 // When APZ is enabled, we can actually enable raw touch events because we
1033 // have code that can deal with them properly. If APZ is not enabled, this
1034 // function doesn't get called.
1035 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
1036 RegisterTouchWindow();
1040 void nsBaseWidget::ConfigureAPZControllerThread() {
1041 // By default the controller thread is the main thread.
1042 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
1045 void nsBaseWidget::SetConfirmedTargetAPZC(
1046 uint64_t aInputBlockId
,
1047 const nsTArray
<ScrollableLayerGuid
>& aTargets
) const {
1048 mAPZC
->SetTargetAPZC(aInputBlockId
, aTargets
);
1051 void nsBaseWidget::UpdateZoomConstraints(
1052 const uint32_t& aPresShellId
, const ScrollableLayerGuid::ViewID
& aViewId
,
1053 const Maybe
<ZoomConstraints
>& aConstraints
) {
1054 if (!mCompositorSession
|| !mAPZC
) {
1055 MOZ_ASSERT_IF(mInitialZoomConstraints
,
1056 mInitialZoomConstraints
->mViewID
== aViewId
);
1058 // We have some constraints, but the compositor and APZC aren't
1059 // created yet. Save these so we can use them later.
1060 mInitialZoomConstraints
= Some(
1061 InitialZoomConstraints(aPresShellId
, aViewId
, aConstraints
.ref()));
1063 mInitialZoomConstraints
.reset();
1067 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1068 mAPZC
->UpdateZoomConstraints(
1069 ScrollableLayerGuid(layersId
, aPresShellId
, aViewId
), aConstraints
);
1072 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC
; }
1074 nsEventStatus
nsBaseWidget::ProcessUntransformedAPZEvent(
1075 WidgetInputEvent
* aEvent
, const APZEventResult
& aApzResult
) {
1076 MOZ_ASSERT(NS_IsMainThread());
1077 ScrollableLayerGuid targetGuid
= aApzResult
.mTargetGuid
;
1078 uint64_t inputBlockId
= aApzResult
.mInputBlockId
;
1079 InputAPZContext
context(aApzResult
.mTargetGuid
, inputBlockId
,
1080 aApzResult
.GetStatus());
1082 // Make a copy of the original event for the APZCCallbackHelper helpers that
1083 // we call later, because the event passed to DispatchEvent can get mutated in
1084 // ways that we don't want (i.e. touch points can get stripped out).
1085 nsEventStatus status
;
1086 UniquePtr
<WidgetEvent
> original(aEvent
->Duplicate());
1087 DispatchEvent(aEvent
, status
);
1089 if (mAPZC
&& !InputAPZContext::WasRoutedToChildProcess() &&
1090 !InputAPZContext::WasDropped() && inputBlockId
) {
1091 // EventStateManager did not route the event into the child process and
1092 // the event was dispatched in the parent process.
1093 // It's safe to communicate to APZ that the event has been processed.
1094 // Note that here aGuid.mLayersId might be different from
1095 // mCompositorSession->RootLayerTreeId() because the event might have gotten
1096 // hit-tested by APZ to be targeted at a child process, but a parent process
1097 // event listener called preventDefault on it. In that case aGuid.mLayersId
1098 // would still be the layers id for the child process, but the event would
1099 // not have actually gotten routed to the child process. The main-thread
1100 // hit-test result therefore needs to use the parent process layers id.
1101 LayersId rootLayersId
= mCompositorSession
->RootLayerTreeId();
1103 RefPtr
<DisplayportSetListener
> postLayerization
;
1104 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1105 nsTArray
<TouchBehaviorFlags
> allowedTouchBehaviors
;
1106 if (touchEvent
->mMessage
== eTouchStart
) {
1107 auto& originalEvent
= *original
->AsTouchEvent();
1108 MOZ_ASSERT(NS_IsMainThread());
1109 allowedTouchBehaviors
= TouchActionHelper::GetAllowedTouchBehavior(
1110 this, GetDocument(), originalEvent
);
1111 if (!allowedTouchBehaviors
.IsEmpty()) {
1112 mAPZC
->SetAllowedTouchBehavior(inputBlockId
, allowedTouchBehaviors
);
1114 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1115 this, GetDocument(), originalEvent
, rootLayersId
, inputBlockId
);
1117 mAPZEventState
->ProcessTouchEvent(*touchEvent
, targetGuid
, inputBlockId
,
1118 aApzResult
.GetStatus(), status
,
1119 std::move(allowedTouchBehaviors
));
1120 } else if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1121 MOZ_ASSERT(wheelEvent
->mFlags
.mHandledByAPZ
);
1122 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1123 this, GetDocument(), *original
->AsWheelEvent(), rootLayersId
,
1125 if (wheelEvent
->mCanTriggerSwipe
) {
1126 ReportSwipeStarted(inputBlockId
, wheelEvent
->TriggersSwipe());
1128 mAPZEventState
->ProcessWheelEvent(*wheelEvent
, inputBlockId
);
1129 } else if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1130 MOZ_ASSERT(mouseEvent
->mFlags
.mHandledByAPZ
);
1131 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1132 this, GetDocument(), *original
->AsMouseEvent(), rootLayersId
,
1134 mAPZEventState
->ProcessMouseEvent(*mouseEvent
, inputBlockId
);
1136 if (postLayerization
) {
1137 postLayerization
->Register();
1144 template <class InputType
, class EventType
>
1145 class DispatchEventOnMainThread
: public Runnable
{
1147 DispatchEventOnMainThread(const InputType
& aInput
, nsBaseWidget
* aWidget
,
1148 const APZEventResult
& aAPZResult
)
1149 : mozilla::Runnable("DispatchEventOnMainThread"),
1152 mAPZResult(aAPZResult
) {}
1154 NS_IMETHOD
Run() override
{
1155 EventType event
= mInput
.ToWidgetEvent(mWidget
);
1156 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1162 nsBaseWidget
* mWidget
;
1163 APZEventResult mAPZResult
;
1166 template <class InputType
, class EventType
>
1167 class DispatchInputOnControllerThread
: public Runnable
{
1169 DispatchInputOnControllerThread(const EventType
& aEvent
,
1170 IAPZCTreeManager
* aAPZC
,
1171 nsBaseWidget
* aWidget
)
1172 : mozilla::Runnable("DispatchInputOnControllerThread"),
1173 mMainMessageLoop(MessageLoop::current()),
1178 NS_IMETHOD
Run() override
{
1179 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(mInput
);
1180 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1183 RefPtr
<Runnable
> r
= new DispatchEventOnMainThread
<InputType
, EventType
>(
1184 mInput
, mWidget
, result
);
1185 mMainMessageLoop
->PostTask(r
.forget());
1190 MessageLoop
* mMainMessageLoop
;
1192 RefPtr
<IAPZCTreeManager
> mAPZC
;
1193 nsBaseWidget
* mWidget
;
1196 void nsBaseWidget::DispatchTouchInput(MultiTouchInput
& aInput
,
1197 uint16_t aInputSource
) {
1198 MOZ_ASSERT(NS_IsMainThread());
1199 MOZ_ASSERT(aInputSource
==
1200 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH
||
1201 aInputSource
== mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN
);
1203 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1205 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1206 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1210 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1211 ProcessUntransformedAPZEvent(&event
, result
);
1213 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1215 nsEventStatus status
;
1216 DispatchEvent(&event
, status
);
1220 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput
& aInput
) {
1221 MOZ_ASSERT(NS_IsMainThread());
1223 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1225 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1226 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1230 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1231 ProcessUntransformedAPZEvent(&event
, result
);
1233 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1234 nsEventStatus status
;
1235 DispatchEvent(&event
, status
);
1239 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput
& aInput
) {
1240 MOZ_ASSERT(NS_IsMainThread());
1242 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1243 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1245 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1248 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1249 ProcessUntransformedAPZEvent(&event
, result
);
1251 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1252 nsEventStatus status
;
1253 DispatchEvent(&event
, status
);
1257 nsIWidget::ContentAndAPZEventStatus
nsBaseWidget::DispatchInputEvent(
1258 WidgetInputEvent
* aEvent
) {
1259 nsIWidget::ContentAndAPZEventStatus status
;
1260 MOZ_ASSERT(NS_IsMainThread());
1262 if (APZThreadUtils::IsControllerThread()) {
1263 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1264 status
.mApzStatus
= result
.GetStatus();
1265 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1268 status
.mContentStatus
= ProcessUntransformedAPZEvent(aEvent
, result
);
1271 if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1272 RefPtr
<Runnable
> r
=
1273 new DispatchInputOnControllerThread
<ScrollWheelInput
,
1274 WidgetWheelEvent
>(*wheelEvent
,
1276 APZThreadUtils::RunOnControllerThread(std::move(r
));
1277 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1280 if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1281 RefPtr
<Runnable
> r
=
1282 new DispatchInputOnControllerThread
<MouseInput
, WidgetMouseEvent
>(
1283 *mouseEvent
, mAPZC
, this);
1284 APZThreadUtils::RunOnControllerThread(std::move(r
));
1285 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1288 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1289 RefPtr
<Runnable
> r
=
1290 new DispatchInputOnControllerThread
<MultiTouchInput
,
1291 WidgetTouchEvent
>(*touchEvent
,
1293 APZThreadUtils::RunOnControllerThread(std::move(r
));
1294 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1297 // Allow dispatching keyboard events on Gecko thread.
1298 MOZ_ASSERT(aEvent
->AsKeyboardEvent());
1301 DispatchEvent(aEvent
, status
.mContentStatus
);
1305 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent
* aEvent
) {
1306 MOZ_ASSERT(NS_IsMainThread());
1308 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1309 mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1313 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent
& event
) {
1314 nsEventStatus status
;
1315 DispatchEvent(&event
, status
);
1316 return ConvertStatus(status
);
1319 Document
* nsBaseWidget::GetDocument() const {
1320 if (mWidgetListener
) {
1321 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1322 return presShell
->GetDocument();
1328 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1329 // Parent directly listens to the vsync source whereas
1330 // child process communicate via IPC
1331 // Should be called AFTER gfxPlatform is initialized
1332 if (XRE_IsParentProcess()) {
1333 if (!mCompositorVsyncDispatcherLock
) {
1334 mCompositorVsyncDispatcherLock
=
1335 MakeUnique
<Mutex
>("mCompositorVsyncDispatcherLock");
1337 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1338 if (!mCompositorVsyncDispatcher
) {
1339 RefPtr
<VsyncDispatcher
> vsyncDispatcher
=
1340 gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
1341 mCompositorVsyncDispatcher
=
1342 new CompositorVsyncDispatcher(std::move(vsyncDispatcher
));
1347 already_AddRefed
<CompositorVsyncDispatcher
>
1348 nsBaseWidget::GetCompositorVsyncDispatcher() {
1349 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
1351 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1352 RefPtr
<CompositorVsyncDispatcher
> dispatcher
= mCompositorVsyncDispatcher
;
1353 return dispatcher
.forget();
1356 already_AddRefed
<WebRenderLayerManager
> nsBaseWidget::CreateCompositorSession(
1357 int aWidth
, int aHeight
, CompositorOptions
* aOptionsOut
) {
1358 MOZ_ASSERT(aOptionsOut
);
1361 CreateCompositorVsyncDispatcher();
1363 gfx::GPUProcessManager
* gpu
= gfx::GPUProcessManager::Get();
1364 // Make sure GPU process is ready for use.
1365 // If it failed to connect to GPU process, GPU process usage is disabled in
1366 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1367 nsresult rv
= gpu
->EnsureGPUReady();
1368 if (NS_WARN_IF(rv
== NS_ERROR_ILLEGAL_DURING_SHUTDOWN
)) {
1372 // If widget type does not supports acceleration, we may be allowed to use
1373 // software WebRender instead.
1374 bool supportsAcceleration
= WidgetTypeSupportsAcceleration();
1375 bool enableSWWR
= true;
1376 if (supportsAcceleration
||
1377 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1378 enableSWWR
= gfx::gfxVars::UseSoftwareWebRender();
1380 bool enableAPZ
= UseAPZ();
1381 CompositorOptions
options(enableAPZ
, enableSWWR
);
1384 if (supportsAcceleration
) {
1385 options
.SetAllowSoftwareWebRenderD3D11(
1386 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1388 if (mNeedFastSnaphot
) {
1389 options
.SetNeedFastSnaphot(true);
1391 #elif defined(MOZ_WIDGET_ANDROID)
1392 MOZ_ASSERT(supportsAcceleration
);
1393 options
.SetAllowSoftwareWebRenderOGL(
1394 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1395 #elif defined(MOZ_WIDGET_GTK)
1396 if (supportsAcceleration
) {
1397 options
.SetAllowSoftwareWebRenderOGL(
1398 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1402 #ifdef MOZ_WIDGET_ANDROID
1403 // Unconditionally set the compositor as initially paused, as we have not
1404 // yet had a chance to send the compositor surface to the GPU process. We
1405 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1406 // where we will also resume the compositor if required.
1407 options
.SetInitiallyPaused(true);
1409 options
.SetInitiallyPaused(CompositorInitiallyPaused());
1412 RefPtr
<WebRenderLayerManager
> lm
= new WebRenderLayerManager(this);
1414 uint64_t innerWindowId
= 0;
1415 if (Document
* doc
= GetDocument()) {
1416 innerWindowId
= doc
->InnerWindowID();
1420 mCompositorSession
= gpu
->CreateTopLevelCompositor(
1421 this, lm
, GetDefaultScale(), options
, UseExternalCompositingSurface(),
1422 gfx::IntSize(aWidth
, aHeight
), innerWindowId
, &retry
);
1424 if (mCompositorSession
) {
1425 TextureFactoryIdentifier textureFactoryIdentifier
;
1427 lm
->Initialize(mCompositorSession
->GetCompositorBridgeChild(),
1428 wr::AsPipelineId(mCompositorSession
->RootLayerTreeId()),
1429 &textureFactoryIdentifier
, error
);
1430 if (textureFactoryIdentifier
.mParentBackend
!= LayersBackend::LAYERS_WR
) {
1432 DestroyCompositor();
1433 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1434 gfx::GPUProcessManager::Get()->DisableWebRender(
1435 wr::WebRenderError::INITIALIZE
, error
);
1439 // We need to retry in a loop because the act of failing to create the
1440 // compositor can change our state (e.g. disable WebRender).
1441 if (mCompositorSession
|| !retry
) {
1442 *aOptionsOut
= options
;
1448 void nsBaseWidget::CreateCompositor(int aWidth
, int aHeight
) {
1449 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1450 gfxPlatform::GetPlatform();
1452 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1453 "This function assumes OMTC");
1455 MOZ_ASSERT(!mCompositorSession
&& !mCompositorBridgeChild
,
1456 "Should have properly cleaned up the previous PCompositor pair "
1459 if (mCompositorBridgeChild
) {
1460 mCompositorBridgeChild
->Destroy();
1463 // Recreating this is tricky, as we may still have an old and we need
1464 // to make sure it's properly destroyed by calling DestroyCompositor!
1466 // If we've already received a shutdown notification, don't try
1467 // create a new compositor.
1468 if (!mShutdownObserver
) {
1472 // The controller thread must be configured before the compositor
1473 // session is created, so that the input bridge runs on the right
1475 ConfigureAPZControllerThread();
1477 CompositorOptions options
;
1478 RefPtr
<WebRenderLayerManager
> lm
=
1479 CreateCompositorSession(aWidth
, aHeight
, &options
);
1484 MOZ_ASSERT(mCompositorSession
);
1485 mCompositorBridgeChild
= mCompositorSession
->GetCompositorBridgeChild();
1486 SetCompositorWidgetDelegate(
1487 mCompositorSession
->GetCompositorWidgetDelegate());
1489 if (options
.UseAPZ()) {
1490 mAPZC
= mCompositorSession
->GetAPZCTreeManager();
1491 ConfigureAPZCTreeManager();
1496 if (mInitialZoomConstraints
) {
1497 UpdateZoomConstraints(mInitialZoomConstraints
->mPresShellID
,
1498 mInitialZoomConstraints
->mViewID
,
1499 Some(mInitialZoomConstraints
->mConstraints
));
1500 mInitialZoomConstraints
.reset();
1503 TextureFactoryIdentifier textureFactoryIdentifier
=
1504 lm
->GetTextureFactoryIdentifier();
1505 MOZ_ASSERT(textureFactoryIdentifier
.mParentBackend
==
1506 LayersBackend::LAYERS_WR
);
1507 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier
);
1508 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier
);
1512 mWindowRenderer
= std::move(lm
);
1514 // Only track compositors for top-level windows, since other window types
1515 // may use the basic compositor. Except on the OS X - see bug 1306383
1516 #if defined(XP_MACOSX)
1517 bool getCompositorFromThisWindow
= true;
1519 bool getCompositorFromThisWindow
= mWindowType
== WindowType::TopLevel
;
1522 if (getCompositorFromThisWindow
) {
1523 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1524 mWindowRenderer
->GetCompositorBackendType());
1528 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession
* aSession
) {
1529 MOZ_ASSERT(aSession
== mCompositorSession
);
1530 DestroyLayerManager();
1533 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1534 return gfxPlatform::UsesOffMainThreadCompositing();
1537 WindowRenderer
* nsBaseWidget::GetWindowRenderer() {
1538 if (!mWindowRenderer
) {
1539 if (!mShutdownObserver
) {
1540 // We are shutting down, do not try to re-create a LayerManager
1543 // Try to use an async compositor first, if possible
1544 if (ShouldUseOffMainThreadCompositing()) {
1548 if (!mWindowRenderer
) {
1549 mWindowRenderer
= CreateFallbackRenderer();
1552 return mWindowRenderer
;
1555 WindowRenderer
* nsBaseWidget::CreateFallbackRenderer() {
1556 return new FallbackRenderer
;
1559 CompositorBridgeChild
* nsBaseWidget::GetRemoteRenderer() {
1560 return mCompositorBridgeChild
;
1563 void nsBaseWidget::ClearCachedWebrenderResources() {
1564 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1567 mWindowRenderer
->AsWebRender()->ClearCachedResources();
1570 void nsBaseWidget::ClearWebrenderAnimationResources() {
1571 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1574 mWindowRenderer
->AsWebRender()->ClearAnimationResources();
1577 bool nsBaseWidget::SetNeedFastSnaphot() {
1578 MOZ_ASSERT(XRE_IsParentProcess());
1579 MOZ_ASSERT(!mCompositorSession
);
1581 if (!XRE_IsParentProcess() || mCompositorSession
) {
1585 mNeedFastSnaphot
= true;
1589 already_AddRefed
<gfx::DrawTarget
> nsBaseWidget::StartRemoteDrawing() {
1593 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA
; }
1595 //-------------------------------------------------------------------------
1597 // Destroy the window
1599 //-------------------------------------------------------------------------
1600 void nsBaseWidget::OnDestroy() {
1601 if (mTextEventDispatcher
) {
1602 mTextEventDispatcher
->OnDestroyWidget();
1603 // Don't release it until this widget actually released because after this
1604 // is called, TextEventDispatcher() may create it again.
1607 // If this widget is being destroyed, let the APZ code know to drop references
1608 // to this widget. Callers of this function all should be holding a deathgrip
1609 // on this widget already.
1610 ReleaseContentController();
1613 void nsBaseWidget::MoveClient(const DesktopPoint
& aOffset
) {
1614 LayoutDeviceIntPoint
clientOffset(GetClientOffset());
1616 // GetClientOffset returns device pixels; scale back to desktop pixels
1617 // if that's what this widget uses for the Move/Resize APIs
1618 if (BoundsUseDesktopPixels()) {
1619 DesktopPoint desktopOffset
= clientOffset
/ GetDesktopToDeviceScale();
1620 Move(aOffset
.x
- desktopOffset
.x
, aOffset
.y
- desktopOffset
.y
);
1622 LayoutDevicePoint layoutOffset
= aOffset
* GetDesktopToDeviceScale();
1623 Move(layoutOffset
.x
- LayoutDeviceCoord(clientOffset
.x
),
1624 layoutOffset
.y
- LayoutDeviceCoord(clientOffset
.y
));
1628 void nsBaseWidget::ResizeClient(const DesktopSize
& aSize
, bool aRepaint
) {
1629 NS_ASSERTION((aSize
.width
>= 0), "Negative width passed to ResizeClient");
1630 NS_ASSERTION((aSize
.height
>= 0), "Negative height passed to ResizeClient");
1632 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1634 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1635 // if that's what this widget uses for the Move/Resize APIs
1636 if (BoundsUseDesktopPixels()) {
1637 DesktopSize desktopDelta
=
1638 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1639 clientBounds
.Size()) /
1640 GetDesktopToDeviceScale();
1641 Resize(aSize
.width
+ desktopDelta
.width
, aSize
.height
+ desktopDelta
.height
,
1644 LayoutDeviceSize layoutSize
= aSize
* GetDesktopToDeviceScale();
1645 Resize(mBounds
.Width() + (layoutSize
.width
- clientBounds
.Width()),
1646 mBounds
.Height() + (layoutSize
.height
- clientBounds
.Height()),
1651 void nsBaseWidget::ResizeClient(const DesktopRect
& aRect
, bool aRepaint
) {
1652 NS_ASSERTION((aRect
.Width() >= 0), "Negative width passed to ResizeClient");
1653 NS_ASSERTION((aRect
.Height() >= 0), "Negative height passed to ResizeClient");
1655 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1656 LayoutDeviceIntPoint clientOffset
= GetClientOffset();
1657 DesktopToLayoutDeviceScale scale
= GetDesktopToDeviceScale();
1659 if (BoundsUseDesktopPixels()) {
1660 DesktopPoint desktopOffset
= clientOffset
/ scale
;
1661 DesktopSize desktopDelta
=
1662 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1663 clientBounds
.Size()) /
1665 Resize(aRect
.X() - desktopOffset
.x
, aRect
.Y() - desktopOffset
.y
,
1666 aRect
.Width() + desktopDelta
.width
,
1667 aRect
.Height() + desktopDelta
.height
, aRepaint
);
1669 LayoutDeviceRect layoutRect
= aRect
* scale
;
1670 Resize(layoutRect
.X() - clientOffset
.x
, layoutRect
.Y() - clientOffset
.y
,
1671 layoutRect
.Width() + mBounds
.Width() - clientBounds
.Width(),
1672 layoutRect
.Height() + mBounds
.Height() - clientBounds
.Height(),
1677 //-------------------------------------------------------------------------
1681 //-------------------------------------------------------------------------
1684 * If the implementation of nsWindow supports borders this method MUST be
1688 LayoutDeviceIntRect
nsBaseWidget::GetClientBounds() { return GetBounds(); }
1691 * If the implementation of nsWindow supports borders this method MUST be
1695 LayoutDeviceIntRect
nsBaseWidget::GetBounds() { return mBounds
; }
1698 * If the implementation of nsWindow uses a local coordinate system within the
1699 *window, this method must be overridden
1702 LayoutDeviceIntRect
nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1704 nsresult
nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect
& aRect
) {
1705 if (SizeMode() != nsSizeMode_Normal
) {
1706 return NS_ERROR_FAILURE
;
1708 aRect
= GetScreenBounds();
1712 LayoutDeviceIntPoint
nsBaseWidget::GetClientOffset() {
1713 return LayoutDeviceIntPoint(0, 0);
1716 nsresult
nsBaseWidget::SetNonClientMargins(const LayoutDeviceIntMargin
&) {
1717 return NS_ERROR_NOT_IMPLEMENTED
;
1720 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin
) {}
1722 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1724 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1726 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect
* aResizerRect
) {
1731 * Modifies aFile to point at an icon file with the given name and suffix. The
1732 * suffix may correspond to a file extension with leading '.' if appropriate.
1733 * Returns true if the icon file exists and can be read.
1735 static bool ResolveIconNameHelper(nsIFile
* aFile
, const nsAString
& aIconName
,
1736 const nsAString
& aIconSuffix
) {
1737 aFile
->Append(u
"icons"_ns
);
1738 aFile
->Append(u
"default"_ns
);
1739 aFile
->Append(aIconName
+ aIconSuffix
);
1742 return NS_SUCCEEDED(aFile
->IsReadable(&readable
)) && readable
;
1746 * Resolve the given icon name into a local file object. This method is
1747 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1748 * platform specific icon file suffix (e.g., ".ico" under Win32).
1750 * If no file is found matching the given parameters, then null is returned.
1752 void nsBaseWidget::ResolveIconName(const nsAString
& aIconName
,
1753 const nsAString
& aIconSuffix
,
1754 nsIFile
** aResult
) {
1757 nsCOMPtr
<nsIProperties
> dirSvc
=
1758 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID
);
1759 if (!dirSvc
) return;
1761 // first check auxilary chrome directories
1763 nsCOMPtr
<nsISimpleEnumerator
> dirs
;
1764 dirSvc
->Get(NS_APP_CHROME_DIR_LIST
, NS_GET_IID(nsISimpleEnumerator
),
1765 getter_AddRefs(dirs
));
1768 while (NS_SUCCEEDED(dirs
->HasMoreElements(&hasMore
)) && hasMore
) {
1769 nsCOMPtr
<nsISupports
> element
;
1770 dirs
->GetNext(getter_AddRefs(element
));
1771 if (!element
) continue;
1772 nsCOMPtr
<nsIFile
> file
= do_QueryInterface(element
);
1773 if (!file
) continue;
1774 if (ResolveIconNameHelper(file
, aIconName
, aIconSuffix
)) {
1775 NS_ADDREF(*aResult
= file
);
1781 // then check the main app chrome directory
1783 nsCOMPtr
<nsIFile
> file
;
1784 dirSvc
->Get(NS_APP_CHROME_DIR
, NS_GET_IID(nsIFile
), getter_AddRefs(file
));
1785 if (file
&& ResolveIconNameHelper(file
, aIconName
, aIconSuffix
))
1786 NS_ADDREF(*aResult
= file
);
1789 void nsBaseWidget::SetSizeConstraints(const SizeConstraints
& aConstraints
) {
1790 mSizeConstraints
= aConstraints
;
1792 // Popups are constrained during layout, and we don't want to synchronously
1793 // paint from reflow, so bail out... This is not great, but it's no worse than
1794 // what we used to do.
1796 // The right fix here is probably making constraint changes go through the
1797 // view manager and such.
1798 if (mWindowType
== WindowType::Popup
) {
1802 // If the current size doesn't meet the new constraints, trigger a
1803 // resize to apply it. Note that, we don't want to invoke Resize if
1804 // the new constraints don't affect the current size, because Resize
1805 // implementation on some platforms may touch other geometry even if
1806 // the size don't need to change.
1807 LayoutDeviceIntSize curSize
= mBounds
.Size();
1808 LayoutDeviceIntSize clampedSize
=
1809 Max(aConstraints
.mMinSize
, Min(aConstraints
.mMaxSize
, curSize
));
1810 if (clampedSize
!= curSize
) {
1812 if (BoundsUseDesktopPixels()) {
1813 DesktopSize desktopSize
= clampedSize
/ GetDesktopToDeviceScale();
1814 size
= desktopSize
.ToUnknownSize();
1816 size
= gfx::Size(clampedSize
.ToUnknownSize());
1818 Resize(size
.width
, size
.height
, true);
1822 const widget::SizeConstraints
nsBaseWidget::GetSizeConstraints() {
1823 return mSizeConstraints
;
1827 nsIRollupListener
* nsBaseWidget::GetActiveRollupListener() {
1828 // TODO: Simplify this.
1829 return nsXULPopupManager::GetInstance();
1832 void nsBaseWidget::NotifyWindowDestroyed() {
1833 if (!mWidgetListener
) return;
1835 nsCOMPtr
<nsIAppWindow
> window
= mWidgetListener
->GetAppWindow();
1836 nsCOMPtr
<nsIBaseWindow
> appWindow(do_QueryInterface(window
));
1838 appWindow
->Destroy();
1842 void nsBaseWidget::NotifyWindowMoved(int32_t aX
, int32_t aY
,
1843 ByMoveToRect aByMoveToRect
) {
1844 if (mWidgetListener
) {
1845 mWidgetListener
->WindowMoved(this, aX
, aY
, aByMoveToRect
);
1848 if (mIMEHasFocus
&& IMENotificationRequestsRef().WantPositionChanged()) {
1849 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE
));
1853 void nsBaseWidget::NotifySizeMoveDone() {
1854 if (!mWidgetListener
) {
1857 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1858 presShell
->WindowSizeMoveDone();
1862 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind
) {
1863 LookAndFeel::NotifyChangedAllWindows(aKind
);
1866 nsresult
nsBaseWidget::NotifyIME(const IMENotification
& aIMENotification
) {
1870 switch (aIMENotification
.mMessage
) {
1871 case REQUEST_TO_COMMIT_COMPOSITION
:
1872 case REQUEST_TO_CANCEL_COMPOSITION
:
1873 // We should send request to IME only when there is a TextEventDispatcher
1874 // instance (this means that this widget has dispatched at least one
1875 // composition event or keyboard event) and the it has composition.
1876 // Otherwise, there is nothing to do.
1877 // Note that if current input transaction is for native input events,
1878 // TextEventDispatcher::NotifyIME() will call
1879 // TextEventDispatcherListener::NotifyIME().
1880 if (mTextEventDispatcher
&& mTextEventDispatcher
->IsComposing()) {
1881 return mTextEventDispatcher
->NotifyIME(aIMENotification
);
1885 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_FOCUS
) {
1886 mIMEHasFocus
= true;
1888 EnsureTextEventDispatcher();
1889 // TextEventDispatcher::NotifyIME() will always call
1890 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1891 // input transaction is for synthesized events for automated tests,
1892 // notifications will be sent to native IME.
1893 nsresult rv
= mTextEventDispatcher
->NotifyIME(aIMENotification
);
1894 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_BLUR
) {
1895 mIMEHasFocus
= false;
1902 void nsBaseWidget::EnsureTextEventDispatcher() {
1903 if (mTextEventDispatcher
) {
1906 mTextEventDispatcher
= new TextEventDispatcher(this);
1909 nsIWidget::NativeIMEContext
nsBaseWidget::GetNativeIMEContext() {
1910 if (mTextEventDispatcher
&& mTextEventDispatcher
->GetPseudoIMEContext()) {
1911 // If we already have a TextEventDispatcher and it's working with
1912 // a TextInputProcessor, we need to return pseudo IME context since
1913 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1914 // on the pseudo IME context in such case.
1915 NativeIMEContext pseudoIMEContext
;
1916 pseudoIMEContext
.InitWithRawNativeIMEContext(
1917 mTextEventDispatcher
->GetPseudoIMEContext());
1918 return pseudoIMEContext
;
1920 return NativeIMEContext(this);
1923 nsIWidget::TextEventDispatcher
* nsBaseWidget::GetTextEventDispatcher() {
1924 EnsureTextEventDispatcher();
1925 return mTextEventDispatcher
;
1928 void* nsBaseWidget::GetPseudoIMEContext() {
1929 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
1933 return dispatcher
->GetPseudoIMEContext();
1936 TextEventDispatcherListener
*
1937 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1938 // TODO: If all platforms supported use of TextEventDispatcher for handling
1939 // native IME and keyboard events, this method should be removed since
1940 // in such case, this is overridden by all the subclasses.
1944 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId
,
1945 const ScrollableLayerGuid::ViewID
& aViewId
,
1946 const CSSRect
& aRect
, const uint32_t& aFlags
) {
1947 if (!mCompositorSession
|| !mAPZC
) {
1950 LayersId layerId
= mCompositorSession
->RootLayerTreeId();
1951 mAPZC
->ZoomToRect(ScrollableLayerGuid(layerId
, aPresShellId
, aViewId
),
1952 ZoomTarget
{aRect
}, aFlags
);
1955 #ifdef ACCESSIBILITY
1957 a11y::LocalAccessible
* nsBaseWidget::GetRootAccessible() {
1958 NS_ENSURE_TRUE(mWidgetListener
, nullptr);
1960 PresShell
* presShell
= mWidgetListener
->GetPresShell();
1961 NS_ENSURE_TRUE(presShell
, nullptr);
1963 // If container is null then the presshell is not active. This often happens
1964 // when a preshell is being held onto for fastback.
1965 nsPresContext
* presContext
= presShell
->GetPresContext();
1966 NS_ENSURE_TRUE(presContext
->GetContainerWeak(), nullptr);
1968 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1969 // make sure it's not created at unsafe times.
1970 nsAccessibilityService
* accService
= GetOrCreateAccService();
1972 return accService
->GetRootDocumentAccessible(
1973 presShell
, nsContentUtils::IsSafeToRunScript());
1979 #endif // ACCESSIBILITY
1981 void nsBaseWidget::StartAsyncScrollbarDrag(
1982 const AsyncDragMetrics
& aDragMetrics
) {
1983 if (!AsyncPanZoomEnabled()) {
1987 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession
);
1989 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1990 ScrollableLayerGuid
guid(layersId
, aDragMetrics
.mPresShellId
,
1991 aDragMetrics
.mViewId
);
1993 mAPZC
->StartScrollbarDrag(guid
, aDragMetrics
);
1996 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint
& aAnchorLocation
,
1997 const ScrollableLayerGuid
& aGuid
) {
1998 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2000 return mAPZC
->StartAutoscroll(aGuid
, aAnchorLocation
);
2003 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid
& aGuid
) {
2004 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2006 mAPZC
->StopAutoscroll(aGuid
);
2009 LayersId
nsBaseWidget::GetRootLayerTreeId() {
2010 return mCompositorSession
? mCompositorSession
->RootLayerTreeId()
2014 already_AddRefed
<widget::Screen
> nsBaseWidget::GetWidgetScreen() {
2015 ScreenManager
& screenManager
= ScreenManager::GetSingleton();
2016 LayoutDeviceIntRect bounds
= GetScreenBounds();
2017 DesktopIntRect deskBounds
= RoundedToInt(bounds
/ GetDesktopToDeviceScale());
2018 return screenManager
.ScreenForRect(deskBounds
);
2021 mozilla::DesktopToLayoutDeviceScale
2022 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
2023 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
2024 ->GetDesktopToDeviceScale();
2027 nsresult
nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint
,
2029 nsIObserver
* aObserver
) {
2030 AutoObserverNotifier
notifier(aObserver
, "touchtap");
2032 if (sPointerIdCounter
> TOUCH_INJECT_MAX_POINTS
) {
2033 sPointerIdCounter
= 0;
2035 int pointerId
= sPointerIdCounter
;
2036 sPointerIdCounter
++;
2037 nsresult rv
= SynthesizeNativeTouchPoint(pointerId
, TOUCH_CONTACT
, aPoint
,
2039 if (NS_FAILED(rv
)) {
2044 return SynthesizeNativeTouchPoint(pointerId
, TOUCH_REMOVE
, aPoint
, 0, 0,
2048 // initiate a long tap
2049 int elapse
= Preferences::GetInt("ui.click_hold_context_menus.delay",
2050 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC
);
2051 if (!mLongTapTimer
) {
2052 mLongTapTimer
= NS_NewTimer();
2053 if (!mLongTapTimer
) {
2054 SynthesizeNativeTouchPoint(pointerId
, TOUCH_CANCEL
, aPoint
, 0, 0,
2056 return NS_ERROR_UNEXPECTED
;
2058 // Windows requires recuring events, so we set this to a smaller window
2059 // than the pref value.
2060 int timeout
= elapse
;
2061 if (timeout
> TOUCH_INJECT_PUMP_TIMER_MSEC
) {
2062 timeout
= TOUCH_INJECT_PUMP_TIMER_MSEC
;
2064 mLongTapTimer
->InitWithNamedFuncCallback(
2065 OnLongTapTimerCallback
, this, timeout
, nsITimer::TYPE_REPEATING_SLACK
,
2066 "nsIWidget::SynthesizeNativeTouchTap");
2069 // If we already have a long tap pending, cancel it. We only allow one long
2070 // tap to be active at a time.
2071 if (mLongTapTouchPoint
) {
2072 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2073 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2076 mLongTapTouchPoint
= MakeUnique
<LongTapInfo
>(
2077 pointerId
, aPoint
, TimeDuration::FromMilliseconds(elapse
), aObserver
);
2078 notifier
.SkipNotification(); // we'll do it in the long-tap callback
2083 void nsIWidget::OnLongTapTimerCallback(nsITimer
* aTimer
, void* aClosure
) {
2084 auto* self
= static_cast<nsIWidget
*>(aClosure
);
2086 if ((self
->mLongTapTouchPoint
->mStamp
+ self
->mLongTapTouchPoint
->mDuration
) >
2089 // Windows needs us to keep pumping feedback to the digitizer, so update
2090 // the pointer id with the same position.
2091 self
->SynthesizeNativeTouchPoint(
2092 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_CONTACT
,
2093 self
->mLongTapTouchPoint
->mPosition
, 1.0, 90, nullptr);
2098 AutoObserverNotifier
notifier(self
->mLongTapTouchPoint
->mObserver
,
2101 // finished, remove the touch point
2102 self
->mLongTapTimer
->Cancel();
2103 self
->mLongTapTimer
= nullptr;
2104 self
->SynthesizeNativeTouchPoint(
2105 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_REMOVE
,
2106 self
->mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2107 self
->mLongTapTouchPoint
= nullptr;
2110 float nsIWidget::GetFallbackDPI() {
2111 RefPtr
<const Screen
> primaryScreen
=
2112 ScreenManager::GetSingleton().GetPrimaryScreen();
2113 return primaryScreen
->GetDPI();
2116 CSSToLayoutDeviceScale
nsIWidget::GetFallbackDefaultScale() {
2117 RefPtr
<const Screen
> s
= ScreenManager::GetSingleton().GetPrimaryScreen();
2118 return s
->GetCSSToLayoutDeviceScale(Screen::IncludeOSZoom::No
);
2121 nsresult
nsIWidget::ClearNativeTouchSequence(nsIObserver
* aObserver
) {
2122 AutoObserverNotifier
notifier(aObserver
, "cleartouch");
2124 // XXX This is odd. This is called by the constructor of nsIWidget. However,
2125 // at that point, nsIWidget::mLongTapTimer must be nullptr. Therefore,
2126 // this must do nothing at initializing the instance.
2127 if (!mLongTapTimer
) {
2130 mLongTapTimer
->Cancel();
2131 mLongTapTimer
= nullptr;
2132 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2133 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2134 mLongTapTouchPoint
= nullptr;
2138 MultiTouchInput
nsBaseWidget::UpdateSynthesizedTouchState(
2139 MultiTouchInput
* aState
, mozilla::TimeStamp aTimeStamp
, uint32_t aPointerId
,
2140 TouchPointerState aPointerState
, LayoutDeviceIntPoint aPoint
,
2141 double aPointerPressure
, uint32_t aPointerOrientation
) {
2142 ScreenIntPoint pointerScreenPoint
= ViewAs
<ScreenPixel
>(
2143 aPoint
, PixelCastJustification::LayoutDeviceIsScreenForBounds
);
2145 // We can't dispatch *aState directly because (a) dispatching
2146 // it might inadvertently modify it and (b) in the case of touchend or
2147 // touchcancel events aState will hold the touches that are
2148 // still down whereas the input dispatched needs to hold the removed
2149 // touch(es). We use |inputToDispatch| for this purpose.
2150 MultiTouchInput inputToDispatch
;
2151 inputToDispatch
.mInputType
= MULTITOUCH_INPUT
;
2152 inputToDispatch
.mTimeStamp
= aTimeStamp
;
2154 int32_t index
= aState
->IndexOfTouch((int32_t)aPointerId
);
2155 if (aPointerState
== TOUCH_CONTACT
) {
2157 // found an existing touch point, update it
2158 SingleTouchData
& point
= aState
->mTouches
[index
];
2159 point
.mScreenPoint
= pointerScreenPoint
;
2160 point
.mRotationAngle
= (float)aPointerOrientation
;
2161 point
.mForce
= (float)aPointerPressure
;
2162 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_MOVE
;
2164 // new touch point, add it
2165 aState
->mTouches
.AppendElement(SingleTouchData(
2166 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2167 (float)aPointerOrientation
, (float)aPointerPressure
));
2168 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_START
;
2170 inputToDispatch
.mTouches
= aState
->mTouches
;
2172 MOZ_ASSERT(aPointerState
== TOUCH_REMOVE
|| aPointerState
== TOUCH_CANCEL
);
2173 // a touch point is being lifted, so remove it from the stored list
2175 aState
->mTouches
.RemoveElementAt(index
);
2177 inputToDispatch
.mType
=
2178 (aPointerState
== TOUCH_REMOVE
? MultiTouchInput::MULTITOUCH_END
2179 : MultiTouchInput::MULTITOUCH_CANCEL
);
2180 inputToDispatch
.mTouches
.AppendElement(SingleTouchData(
2181 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2182 (float)aPointerOrientation
, (float)aPointerPressure
));
2185 return inputToDispatch
;
2188 void nsBaseWidget::NotifyLiveResizeStarted() {
2189 // If we have mLiveResizeListeners already non-empty, we should notify those
2190 // listeners that the resize stopped before starting anew. In theory this
2191 // should never happen because we shouldn't get nested live resize actions.
2192 NotifyLiveResizeStopped();
2193 MOZ_ASSERT(mLiveResizeListeners
.IsEmpty());
2195 // If we can get the active remote tab for the current widget, suppress
2196 // the displayport on it during the live resize.
2197 if (!mWidgetListener
) {
2200 nsCOMPtr
<nsIAppWindow
> appWindow
= mWidgetListener
->GetAppWindow();
2204 mLiveResizeListeners
= appWindow
->GetLiveResizeListeners();
2205 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2206 mLiveResizeListeners
[i
]->LiveResizeStarted();
2210 void nsBaseWidget::NotifyLiveResizeStopped() {
2211 if (!mLiveResizeListeners
.IsEmpty()) {
2212 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2213 mLiveResizeListeners
[i
]->LiveResizeStopped();
2215 mLiveResizeListeners
.Clear();
2219 nsresult
nsBaseWidget::AsyncEnableDragDrop(bool aEnable
) {
2220 RefPtr
<nsBaseWidget
> kungFuDeathGrip
= this;
2221 return NS_DispatchToCurrentThreadQueue(
2222 NS_NewRunnableFunction(
2223 "AsyncEnableDragDropFn",
2224 [this, aEnable
, kungFuDeathGrip
]() { EnableDragDrop(aEnable
); }),
2225 kAsyncDragDropTimeout
, EventQueuePriority::Idle
);
2228 void nsBaseWidget::SwipeFinished() {
2229 if (mSwipeTracker
) {
2230 mSwipeTracker
->Destroy();
2231 mSwipeTracker
= nullptr;
2235 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId
,
2237 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== aInputBlockId
) {
2239 PanGestureInput
& startEvent
= mSwipeEventQueue
->queuedEvents
[0];
2240 TrackScrollEventAsSwipe(startEvent
, mSwipeEventQueue
->allowedDirections
,
2242 for (size_t i
= 1; i
< mSwipeEventQueue
->queuedEvents
.Length(); i
++) {
2243 mSwipeTracker
->ProcessEvent(mSwipeEventQueue
->queuedEvents
[i
]);
2246 // If the event wasn't start swipe, we need to notify it to APZ.
2247 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2248 BrowserGestureResponse::NotConsumed
);
2250 mSwipeEventQueue
= nullptr;
2254 void nsBaseWidget::TrackScrollEventAsSwipe(
2255 const mozilla::PanGestureInput
& aSwipeStartEvent
,
2256 uint32_t aAllowedDirections
, uint64_t aInputBlockId
) {
2257 // If a swipe is currently being tracked kill it -- it's been interrupted
2258 // by another gesture event.
2259 if (mSwipeTracker
) {
2260 mSwipeTracker
->CancelSwipe(aSwipeStartEvent
.mTimeStamp
);
2261 mSwipeTracker
->Destroy();
2262 mSwipeTracker
= nullptr;
2265 uint32_t direction
=
2266 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2267 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2268 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2271 new SwipeTracker(*this, aSwipeStartEvent
, aAllowedDirections
, direction
);
2274 mCurrentPanGestureBelongsToSwipe
= true;
2276 // Now SwipeTracker has started consuming pan events, notify it to APZ so
2277 // that APZ can discard queued events.
2278 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2279 BrowserGestureResponse::Consumed
);
2283 nsBaseWidget::SwipeInfo
nsBaseWidget::SendMayStartSwipe(
2284 const mozilla::PanGestureInput
& aSwipeStartEvent
) {
2285 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
2287 uint32_t direction
=
2288 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2289 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2290 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2292 // We're ready to start the animation. Tell Gecko about it, and at the same
2293 // time ask it if it really wants to start an animation for this event.
2294 // This event also reports back the directions that we can swipe in.
2295 LayoutDeviceIntPoint position
= RoundedToInt(aSwipeStartEvent
.mPanStartPoint
*
2296 ScreenToLayoutDeviceScale(1));
2297 WidgetSimpleGestureEvent geckoEvent
= SwipeTracker::CreateSwipeGestureEvent(
2298 eSwipeGestureMayStart
, this, position
, aSwipeStartEvent
.mTimeStamp
);
2299 geckoEvent
.mDirection
= direction
;
2300 geckoEvent
.mDelta
= 0.0;
2301 geckoEvent
.mAllowedDirections
= 0;
2302 bool shouldStartSwipe
=
2303 DispatchWindowEvent(geckoEvent
); // event cancelled == swipe should start
2305 SwipeInfo result
= {shouldStartSwipe
, geckoEvent
.mAllowedDirections
};
2309 WidgetWheelEvent
nsBaseWidget::MayStartSwipeForAPZ(
2310 const PanGestureInput
& aPanInput
, const APZEventResult
& aApzResult
) {
2311 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2313 // Ignore swipe-to-navigation in PiP window.
2318 if (aPanInput
.AllowsSwipe()) {
2319 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2320 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2321 if (swipeInfo
.wantsSwipe
) {
2322 if (aApzResult
.GetStatus() == nsEventStatus_eIgnore
) {
2323 // APZ has determined and that scrolling horizontally in the
2324 // requested direction is impossible, so it didn't do any
2325 // scrolling for the event.
2326 // We know now that MayStartSwipe wants a swipe, so we can start
2328 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
,
2329 aApzResult
.mInputBlockId
);
2330 } else if (!aApzResult
.GetHandledResult() ||
2331 !aApzResult
.GetHandledResult()->IsHandledByRoot()) {
2332 // We don't know whether this event can start a swipe, so we need
2333 // to queue up events and wait for a call to ReportSwipeStarted.
2334 // APZ might already have started scrolling in response to the
2335 // event if it knew that it's the right thing to do. In that case
2336 // we'll still get a call to ReportSwipeStarted, and we will
2337 // discard the queued events at that point.
2338 mSwipeEventQueue
= MakeUnique
<SwipeEventQueue
>(
2339 swipeInfo
.allowedDirections
, aApzResult
.mInputBlockId
);
2342 // Inform that the browser gesture didn't use the pan event (pan-start
2343 // precisely), so that APZ can now start using the event for
2344 // scrolling/overscrolling.
2345 mAPZC
->SetBrowserGestureResponse(aApzResult
.mInputBlockId
,
2346 BrowserGestureResponse::NotConsumed
);
2350 if (mSwipeEventQueue
&&
2351 mSwipeEventQueue
->inputBlockId
== aApzResult
.mInputBlockId
) {
2352 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2358 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput
& aPanInput
) {
2359 // Ignore swipe-to-navigation in PiP window.
2364 if (aPanInput
.mType
== PanGestureInput::PANGESTURE_MAYSTART
||
2365 aPanInput
.mType
== PanGestureInput::PANGESTURE_START
) {
2366 mCurrentPanGestureBelongsToSwipe
= false;
2368 if (mCurrentPanGestureBelongsToSwipe
) {
2369 // Ignore this event. It's a momentum event from a scroll gesture
2370 // that was processed as a swipe, and the swipe animation has
2371 // already finished (so mSwipeTracker is already null).
2372 MOZ_ASSERT(aPanInput
.IsMomentum(),
2373 "If the fingers are still on the touchpad, we should still have "
2375 "and it should have consumed this event.");
2379 if (!aPanInput
.MayTriggerSwipe()) {
2383 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2385 // We're in the non-APZ case here, but we still want to know whether
2386 // the event was routed to a child process, so we use InputAPZContext
2387 // to get that piece of information.
2388 ScrollableLayerGuid guid
;
2389 uint64_t blockId
= 0;
2390 InputAPZContext
context(guid
, blockId
, nsEventStatus_eIgnore
);
2392 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2393 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2394 nsEventStatus status
;
2395 DispatchEvent(&event
, status
);
2396 if (swipeInfo
.wantsSwipe
) {
2397 if (context
.WasRoutedToChildProcess()) {
2398 // We don't know whether this event can start a swipe, so we need
2399 // to queue up events and wait for a call to ReportSwipeStarted.
2401 MakeUnique
<SwipeEventQueue
>(swipeInfo
.allowedDirections
, blockId
);
2402 } else if (event
.TriggersSwipe()) {
2403 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
, blockId
);
2407 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== 0) {
2408 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2414 const IMENotificationRequests
& nsIWidget::IMENotificationRequestsRef() {
2415 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
2416 return dispatcher
->IMENotificationRequestsRef();
2419 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent
* aEvent
) {}
2421 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType
,
2422 const WidgetKeyboardEvent
& aEvent
,
2423 nsTArray
<CommandInt
>& aCommands
) {
2424 MOZ_ASSERT(aEvent
.IsTrusted());
2425 MOZ_ASSERT(aCommands
.IsEmpty());
2429 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboard() {
2430 if (XRE_IsContentProcess()) {
2431 return CreateBidiKeyboardContentProcess();
2433 return CreateBidiKeyboardInner();
2437 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboardInner() {
2438 // no bidi keyboard implementation
2443 namespace mozilla::widget
{
2445 const char* ToChar(InputContext::Origin aOrigin
) {
2447 case InputContext::ORIGIN_MAIN
:
2448 return "ORIGIN_MAIN";
2449 case InputContext::ORIGIN_CONTENT
:
2450 return "ORIGIN_CONTENT";
2452 return "Unexpected value";
2456 const char* ToChar(IMEMessage aIMEMessage
) {
2457 switch (aIMEMessage
) {
2458 case NOTIFY_IME_OF_NOTHING
:
2459 return "NOTIFY_IME_OF_NOTHING";
2460 case NOTIFY_IME_OF_FOCUS
:
2461 return "NOTIFY_IME_OF_FOCUS";
2462 case NOTIFY_IME_OF_BLUR
:
2463 return "NOTIFY_IME_OF_BLUR";
2464 case NOTIFY_IME_OF_SELECTION_CHANGE
:
2465 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2466 case NOTIFY_IME_OF_TEXT_CHANGE
:
2467 return "NOTIFY_IME_OF_TEXT_CHANGE";
2468 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED
:
2469 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2470 case NOTIFY_IME_OF_POSITION_CHANGE
:
2471 return "NOTIFY_IME_OF_POSITION_CHANGE";
2472 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT
:
2473 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2474 case REQUEST_TO_COMMIT_COMPOSITION
:
2475 return "REQUEST_TO_COMMIT_COMPOSITION";
2476 case REQUEST_TO_CANCEL_COMPOSITION
:
2477 return "REQUEST_TO_CANCEL_COMPOSITION";
2479 return "Unexpected value";
2483 void NativeIMEContext::Init(nsIWidget
* aWidget
) {
2485 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2486 mOriginProcessID
= static_cast<uint64_t>(-1);
2489 if (!XRE_IsContentProcess()) {
2490 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(
2491 aWidget
->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT
));
2492 mOriginProcessID
= 0;
2495 // If this is created in a child process, aWidget is an instance of
2496 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2497 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2498 // native IME context of the parent process.
2499 *this = aWidget
->GetNativeIMEContext();
2502 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext
) {
2503 if (NS_WARN_IF(!aRawNativeIMEContext
)) {
2504 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2505 mOriginProcessID
= static_cast<uint64_t>(-1);
2508 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(aRawNativeIMEContext
);
2510 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2513 void IMENotification::TextChangeDataBase::MergeWith(
2514 const IMENotification::TextChangeDataBase
& aOther
) {
2515 MOZ_ASSERT(aOther
.IsValid(), "Merging data must store valid data");
2516 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mRemovedEndOffset
,
2517 "end of removed text must be same or larger than start");
2518 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mAddedEndOffset
,
2519 "end of added text must be same or larger than start");
2526 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2527 // text ranges. I.e., mStartOffset should be the smallest offset of all
2528 // modified text ranges in old text. |mRemovedEndOffset| should be the
2529 // largest end offset in old text of all modified text ranges.
2530 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2531 // I.e., only this is an offset in new text.
2532 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2533 // premodified text was already removed. And some text whose length is
2534 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2535 // this allows IME to mark dirty the modified text range with |mStartOffset|
2536 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2537 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2538 // Additionally, IME can retrieve only the text between |mStartOffset| and
2539 // |mAddedEndOffset| for updating stored text.
2541 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2542 // should be adjusted to be in same text. The |newData.mStartOffset| and
2543 // |newData.mRemovedEndOffset| should be computed as in old text because
2544 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2545 // in the old text but even if some text before the values of the newData
2546 // has already been modified, the values don't include the changes.
2548 // For comparing new and old |mAddedEndOffset| values, they should be
2549 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2550 // computed as in the new text because |mAddedEndOffset| indicates the end
2551 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2552 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2554 const TextChangeDataBase
& newData
= aOther
;
2555 const TextChangeDataBase oldData
= *this;
2557 // mCausedOnlyByComposition should be true only when all changes are caused
2559 mCausedOnlyByComposition
=
2560 newData
.mCausedOnlyByComposition
&& oldData
.mCausedOnlyByComposition
;
2562 // mIncludingChangesWithoutComposition should be true if at least one of
2563 // merged changes occurred without composition.
2564 mIncludingChangesWithoutComposition
=
2565 newData
.mIncludingChangesWithoutComposition
||
2566 oldData
.mIncludingChangesWithoutComposition
;
2568 // mIncludingChangesDuringComposition should be true when at least one of
2569 // the merged non-composition changes occurred during the latest composition.
2570 if (!newData
.mCausedOnlyByComposition
&&
2571 !newData
.mIncludingChangesDuringComposition
) {
2572 MOZ_ASSERT(newData
.mIncludingChangesWithoutComposition
);
2573 MOZ_ASSERT(mIncludingChangesWithoutComposition
);
2574 // If new change is neither caused by composition nor occurred during
2575 // composition, set mIncludingChangesDuringComposition to false because
2576 // IME doesn't want outdated text changes as text change during current
2578 mIncludingChangesDuringComposition
= false;
2580 // Otherwise, set mIncludingChangesDuringComposition to true if either
2581 // oldData or newData includes changes during composition.
2582 mIncludingChangesDuringComposition
=
2583 newData
.mIncludingChangesDuringComposition
||
2584 oldData
.mIncludingChangesDuringComposition
;
2587 if (newData
.mStartOffset
>= oldData
.mAddedEndOffset
) {
2589 // If new start is after old end offset of added text, it means that text
2590 // after the modified range is modified. Like:
2591 // added range of old change: +----------+
2592 // removed range of new change: +----------+
2593 // So, the old start offset is always the smaller offset.
2594 mStartOffset
= oldData
.mStartOffset
;
2595 // The new end offset of removed text is moved by the old change and we
2596 // need to cancel the move of the old change for comparing the offsets in
2597 // same text because it doesn't make sensce to compare offsets in different
2599 uint32_t newRemovedEndOffsetInOldText
=
2600 newData
.mRemovedEndOffset
- oldData
.Difference();
2602 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2603 // The new end offset of added text is always the larger offset.
2604 mAddedEndOffset
= newData
.mAddedEndOffset
;
2608 if (newData
.mStartOffset
>= oldData
.mStartOffset
) {
2609 // If new start is in the modified range, it means that new data changes
2610 // a part or all of the range.
2611 mStartOffset
= oldData
.mStartOffset
;
2612 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2614 // If new end of removed text is greater than old end of added text, it
2615 // means that all or a part of modified range modified again and text
2616 // after the modified range is also modified. Like:
2617 // added range of old change: +----------+
2618 // removed range of new change: +----------+
2619 // So, the new removed end offset is moved by the old change and we need
2620 // to cancel the move of the old change for comparing the offsets in the
2621 // same text because it doesn't make sense to compare the offsets in
2623 uint32_t newRemovedEndOffsetInOldText
=
2624 newData
.mRemovedEndOffset
- oldData
.Difference();
2626 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2627 // The old end of added text is replaced by new change. So, it should be
2628 // same as the new start. On the other hand, the new added end offset is
2629 // always same or larger. Therefore, the merged end offset of added
2630 // text should be the new end offset of added text.
2631 mAddedEndOffset
= newData
.mAddedEndOffset
;
2636 // If new end of removed text is less than old end of added text, it means
2637 // that only a part of the modified range is modified again. Like:
2638 // added range of old change: +------------+
2639 // removed range of new change: +-----+
2640 // So, the new end offset of removed text should be same as the old end
2641 // offset of removed text. Therefore, the merged end offset of removed
2642 // text should be the old text change's |mRemovedEndOffset|.
2643 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2644 // The old end of added text is moved by new change. So, we need to cancel
2645 // the move of the new change for comparing the offsets in same text.
2646 uint32_t oldAddedEndOffsetInNewText
=
2647 oldData
.mAddedEndOffset
+ newData
.Difference();
2649 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2653 if (newData
.mRemovedEndOffset
>= oldData
.mStartOffset
) {
2654 // If new end of removed text is greater than old start (and new start is
2655 // less than old start), it means that a part of modified range is modified
2656 // again and some new text before the modified range is also modified.
2657 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2658 "new start offset should be less than old one here");
2659 mStartOffset
= newData
.mStartOffset
;
2660 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2662 // If new end of removed text is greater than old end of added text, it
2663 // means that all modified text and text after the modified range is
2665 // added range of old change: +----------+
2666 // removed range of new change: +------------------+
2667 // So, the new end of removed text is moved by the old change. Therefore,
2668 // we need to cancel the move of the old change for comparing the offsets
2669 // in same text because it doesn't make sense to compare the offsets in
2671 uint32_t newRemovedEndOffsetInOldText
=
2672 newData
.mRemovedEndOffset
- oldData
.Difference();
2674 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2675 // The old end of added text is replaced by new change. So, the old end
2676 // offset of added text is same as new text change's start offset. Then,
2677 // new change's end offset of added text is always same or larger than
2678 // it. Therefore, merged end offset of added text is always the new end
2679 // offset of added text.
2680 mAddedEndOffset
= newData
.mAddedEndOffset
;
2685 // If new end of removed text is less than old end of added text, it
2686 // means that only a part of the modified range is modified again. Like:
2687 // added range of old change: +----------+
2688 // removed range of new change: +----------+
2689 // So, the new end of removed text should be same as old end of removed
2690 // text for preventing end of removed text to be modified. Therefore,
2691 // merged end offset of removed text is always the old end offset of removed
2693 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2694 // The old end of added text is moved by this change. So, we need to
2695 // cancel the move of the new change for comparing the offsets in same text
2696 // because it doesn't make sense to compare the offsets in different text.
2697 uint32_t oldAddedEndOffsetInNewText
=
2698 oldData
.mAddedEndOffset
+ newData
.Difference();
2700 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2705 // Otherwise, i.e., both new end of added text and new start are less than
2706 // old start, text before the modified range is modified. Like:
2707 // added range of old change: +----------+
2708 // removed range of new change: +----------+
2709 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2710 "new start offset should be less than old one here");
2711 mStartOffset
= newData
.mStartOffset
;
2712 MOZ_ASSERT(newData
.mRemovedEndOffset
< oldData
.mRemovedEndOffset
,
2713 "new removed end offset should be less than old one here");
2714 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2715 // The end of added text should be adjusted with the new difference.
2716 uint32_t oldAddedEndOffsetInNewText
=
2717 oldData
.mAddedEndOffset
+ newData
.Difference();
2719 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2724 // Let's test the code of merging multiple text change data in debug build
2725 // and crash if one of them fails because this feature is very complex but
2726 // cannot be tested with mochitest.
2727 void IMENotification::TextChangeDataBase::Test() {
2728 static bool gTestTextChangeEvent
= true;
2729 if (!gTestTextChangeEvent
) {
2732 gTestTextChangeEvent
= false;
2734 /****************************************************************************
2736 ****************************************************************************/
2739 MergeWith(TextChangeData(10, 10, 20, false, false));
2740 MergeWith(TextChangeData(20, 20, 35, false, false));
2741 MOZ_ASSERT(mStartOffset
== 10,
2742 "Test 1-1-1: mStartOffset should be the first offset");
2744 mRemovedEndOffset
== 10, // 20 - (20 - 10)
2745 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2747 mAddedEndOffset
== 35,
2748 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2751 // Removing text (longer line -> shorter line)
2752 MergeWith(TextChangeData(10, 20, 10, false, false));
2753 MergeWith(TextChangeData(10, 30, 10, false, false));
2754 MOZ_ASSERT(mStartOffset
== 10,
2755 "Test 1-2-1: mStartOffset should be the first offset");
2756 MOZ_ASSERT(mRemovedEndOffset
== 40, // 30 + (10 - 20)
2757 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2759 "with already removed length");
2761 mAddedEndOffset
== 10,
2762 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2765 // Removing text (shorter line -> longer line)
2766 MergeWith(TextChangeData(10, 20, 10, false, false));
2767 MergeWith(TextChangeData(10, 15, 10, false, false));
2768 MOZ_ASSERT(mStartOffset
== 10,
2769 "Test 1-3-1: mStartOffset should be the first offset");
2770 MOZ_ASSERT(mRemovedEndOffset
== 25, // 15 + (10 - 20)
2771 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2773 "with already removed length");
2775 mAddedEndOffset
== 10,
2776 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2779 // Appending text at different point (not sure if actually occurs)
2780 MergeWith(TextChangeData(10, 10, 20, false, false));
2781 MergeWith(TextChangeData(55, 55, 60, false, false));
2782 MOZ_ASSERT(mStartOffset
== 10,
2783 "Test 1-4-1: mStartOffset should be the smallest offset");
2785 mRemovedEndOffset
== 45, // 55 - (10 - 20)
2786 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2787 "text without already added length");
2789 mAddedEndOffset
== 60,
2790 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2793 // Removing text at different point (not sure if actually occurs)
2794 MergeWith(TextChangeData(10, 20, 10, false, false));
2795 MergeWith(TextChangeData(55, 68, 55, false, false));
2796 MOZ_ASSERT(mStartOffset
== 10,
2797 "Test 1-5-1: mStartOffset should be the smallest offset");
2799 mRemovedEndOffset
== 78, // 68 - (10 - 20)
2800 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2801 "text with already removed length");
2803 mAddedEndOffset
== 55,
2804 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2807 // Replacing text and append text (becomes longer)
2808 MergeWith(TextChangeData(30, 35, 32, false, false));
2809 MergeWith(TextChangeData(32, 32, 40, false, false));
2810 MOZ_ASSERT(mStartOffset
== 30,
2811 "Test 1-6-1: mStartOffset should be the smallest offset");
2813 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2814 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2817 mAddedEndOffset
== 40,
2818 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2821 // Replacing text and append text (becomes shorter)
2822 MergeWith(TextChangeData(30, 35, 32, false, false));
2823 MergeWith(TextChangeData(32, 32, 33, false, false));
2824 MOZ_ASSERT(mStartOffset
== 30,
2825 "Test 1-7-1: mStartOffset should be the smallest offset");
2827 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2828 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2831 mAddedEndOffset
== 33,
2832 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2835 // Removing text and replacing text after first range (not sure if actually
2837 MergeWith(TextChangeData(30, 35, 30, false, false));
2838 MergeWith(TextChangeData(32, 34, 48, false, false));
2839 MOZ_ASSERT(mStartOffset
== 30,
2840 "Test 1-8-1: mStartOffset should be the smallest offset");
2841 MOZ_ASSERT(mRemovedEndOffset
== 39, // 34 - (30 - 35)
2842 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2844 "without already removed text");
2846 mAddedEndOffset
== 48,
2847 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2850 // Removing text and replacing text after first range (not sure if actually
2852 MergeWith(TextChangeData(30, 35, 30, false, false));
2853 MergeWith(TextChangeData(32, 38, 36, false, false));
2854 MOZ_ASSERT(mStartOffset
== 30,
2855 "Test 1-9-1: mStartOffset should be the smallest offset");
2856 MOZ_ASSERT(mRemovedEndOffset
== 43, // 38 - (30 - 35)
2857 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2859 "without already removed text");
2861 mAddedEndOffset
== 36,
2862 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2865 /****************************************************************************
2867 ****************************************************************************/
2869 // Replacing text in around end of added text (becomes shorter) (not sure
2870 // if actually occurs)
2871 MergeWith(TextChangeData(50, 50, 55, false, false));
2872 MergeWith(TextChangeData(53, 60, 54, false, false));
2873 MOZ_ASSERT(mStartOffset
== 50,
2874 "Test 2-1-1: mStartOffset should be the smallest offset");
2875 MOZ_ASSERT(mRemovedEndOffset
== 55, // 60 - (55 - 50)
2876 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2878 "without already added text length");
2880 mAddedEndOffset
== 54,
2881 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2884 // Replacing text around end of added text (becomes longer) (not sure
2885 // if actually occurs)
2886 MergeWith(TextChangeData(50, 50, 55, false, false));
2887 MergeWith(TextChangeData(54, 62, 68, false, false));
2888 MOZ_ASSERT(mStartOffset
== 50,
2889 "Test 2-2-1: mStartOffset should be the smallest offset");
2890 MOZ_ASSERT(mRemovedEndOffset
== 57, // 62 - (55 - 50)
2891 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2893 "without already added text length");
2895 mAddedEndOffset
== 68,
2896 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2899 // Replacing text around end of replaced text (became shorter) (not sure if
2901 MergeWith(TextChangeData(36, 48, 45, false, false));
2902 MergeWith(TextChangeData(43, 50, 49, false, false));
2903 MOZ_ASSERT(mStartOffset
== 36,
2904 "Test 2-3-1: mStartOffset should be the smallest offset");
2905 MOZ_ASSERT(mRemovedEndOffset
== 53, // 50 - (45 - 48)
2906 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2908 "without already removed text length");
2910 mAddedEndOffset
== 49,
2911 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2914 // Replacing text around end of replaced text (became longer) (not sure if
2916 MergeWith(TextChangeData(36, 52, 53, false, false));
2917 MergeWith(TextChangeData(43, 68, 61, false, false));
2918 MOZ_ASSERT(mStartOffset
== 36,
2919 "Test 2-4-1: mStartOffset should be the smallest offset");
2920 MOZ_ASSERT(mRemovedEndOffset
== 67, // 68 - (53 - 52)
2921 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2923 "without already added text length");
2925 mAddedEndOffset
== 61,
2926 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2929 /****************************************************************************
2931 ****************************************************************************/
2933 // Appending text in already added text (not sure if actually occurs)
2934 MergeWith(TextChangeData(10, 10, 20, false, false));
2935 MergeWith(TextChangeData(15, 15, 30, false, false));
2936 MOZ_ASSERT(mStartOffset
== 10,
2937 "Test 3-1-1: mStartOffset should be the smallest offset");
2938 MOZ_ASSERT(mRemovedEndOffset
== 10,
2939 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2942 mAddedEndOffset
== 35, // 20 + (30 - 15)
2943 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2944 "added text length by the new change");
2947 // Replacing text in added text (not sure if actually occurs)
2948 MergeWith(TextChangeData(50, 50, 55, false, false));
2949 MergeWith(TextChangeData(52, 53, 56, false, false));
2950 MOZ_ASSERT(mStartOffset
== 50,
2951 "Test 3-2-1: mStartOffset should be the smallest offset");
2952 MOZ_ASSERT(mRemovedEndOffset
== 50,
2953 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2956 mAddedEndOffset
== 58, // 55 + (56 - 53)
2957 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2958 "added text length by the new change");
2961 // Replacing text in replaced text (became shorter) (not sure if actually
2963 MergeWith(TextChangeData(36, 48, 45, false, false));
2964 MergeWith(TextChangeData(37, 38, 50, false, false));
2965 MOZ_ASSERT(mStartOffset
== 36,
2966 "Test 3-3-1: mStartOffset should be the smallest offset");
2967 MOZ_ASSERT(mRemovedEndOffset
== 48,
2968 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2971 mAddedEndOffset
== 57, // 45 + (50 - 38)
2972 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2973 "added text length by the new change");
2976 // Replacing text in replaced text (became longer) (not sure if actually
2978 MergeWith(TextChangeData(32, 48, 53, false, false));
2979 MergeWith(TextChangeData(43, 50, 52, false, false));
2980 MOZ_ASSERT(mStartOffset
== 32,
2981 "Test 3-4-1: mStartOffset should be the smallest offset");
2982 MOZ_ASSERT(mRemovedEndOffset
== 48,
2983 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2985 "without already added text length");
2987 mAddedEndOffset
== 55, // 53 + (52 - 50)
2988 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2989 "added text length by the new change");
2992 // Replacing text in replaced text (became shorter) (not sure if actually
2994 MergeWith(TextChangeData(36, 48, 50, false, false));
2995 MergeWith(TextChangeData(37, 49, 47, false, false));
2996 MOZ_ASSERT(mStartOffset
== 36,
2997 "Test 3-5-1: mStartOffset should be the smallest offset");
2999 mRemovedEndOffset
== 48,
3000 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
3002 MOZ_ASSERT(mAddedEndOffset
== 48, // 50 + (47 - 49)
3003 "Test 3-5-3: mAddedEndOffset should be the first end of added "
3005 "removed text length by the new change");
3008 // Replacing text in replaced text (became longer) (not sure if actually
3010 MergeWith(TextChangeData(32, 48, 53, false, false));
3011 MergeWith(TextChangeData(43, 50, 47, false, false));
3012 MOZ_ASSERT(mStartOffset
== 32,
3013 "Test 3-6-1: mStartOffset should be the smallest offset");
3014 MOZ_ASSERT(mRemovedEndOffset
== 48,
3015 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
3017 "without already added text length");
3018 MOZ_ASSERT(mAddedEndOffset
== 50, // 53 + (47 - 50)
3019 "Test 3-6-3: mAddedEndOffset should be the first end of added "
3021 "removed text length by the new change");
3024 /****************************************************************************
3026 ****************************************************************************/
3028 // Replacing text all of already append text (not sure if actually occurs)
3029 MergeWith(TextChangeData(50, 50, 55, false, false));
3030 MergeWith(TextChangeData(44, 66, 68, false, false));
3031 MOZ_ASSERT(mStartOffset
== 44,
3032 "Test 4-1-1: mStartOffset should be the smallest offset");
3033 MOZ_ASSERT(mRemovedEndOffset
== 61, // 66 - (55 - 50)
3034 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
3036 "without already added text length");
3038 mAddedEndOffset
== 68,
3039 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3042 // Replacing text around a point in which text was removed (not sure if
3044 MergeWith(TextChangeData(50, 62, 50, false, false));
3045 MergeWith(TextChangeData(44, 66, 68, false, false));
3046 MOZ_ASSERT(mStartOffset
== 44,
3047 "Test 4-2-1: mStartOffset should be the smallest offset");
3048 MOZ_ASSERT(mRemovedEndOffset
== 78, // 66 - (50 - 62)
3049 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
3051 "without already removed text length");
3053 mAddedEndOffset
== 68,
3054 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3057 // Replacing text all replaced text (became shorter) (not sure if actually
3059 MergeWith(TextChangeData(50, 62, 60, false, false));
3060 MergeWith(TextChangeData(49, 128, 130, false, false));
3061 MOZ_ASSERT(mStartOffset
== 49,
3062 "Test 4-3-1: mStartOffset should be the smallest offset");
3063 MOZ_ASSERT(mRemovedEndOffset
== 130, // 128 - (60 - 62)
3064 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
3066 "without already removed text length");
3068 mAddedEndOffset
== 130,
3069 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3072 // Replacing text all replaced text (became longer) (not sure if actually
3074 MergeWith(TextChangeData(50, 61, 73, false, false));
3075 MergeWith(TextChangeData(44, 100, 50, false, false));
3076 MOZ_ASSERT(mStartOffset
== 44,
3077 "Test 4-4-1: mStartOffset should be the smallest offset");
3078 MOZ_ASSERT(mRemovedEndOffset
== 88, // 100 - (73 - 61)
3079 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
3081 "with already added text length");
3083 mAddedEndOffset
== 50,
3084 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3087 /****************************************************************************
3089 ****************************************************************************/
3091 // Replacing text around start of added text (not sure if actually occurs)
3092 MergeWith(TextChangeData(50, 50, 55, false, false));
3093 MergeWith(TextChangeData(48, 52, 49, false, false));
3094 MOZ_ASSERT(mStartOffset
== 48,
3095 "Test 5-1-1: mStartOffset should be the smallest offset");
3097 mRemovedEndOffset
== 50,
3098 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
3101 mAddedEndOffset
== 52, // 55 + (52 - 49)
3102 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
3103 "added text length by the new change");
3106 // Replacing text around start of replaced text (became shorter) (not sure if
3108 MergeWith(TextChangeData(50, 60, 58, false, false));
3109 MergeWith(TextChangeData(43, 50, 48, false, false));
3110 MOZ_ASSERT(mStartOffset
== 43,
3111 "Test 5-2-1: mStartOffset should be the smallest offset");
3113 mRemovedEndOffset
== 60,
3114 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3116 MOZ_ASSERT(mAddedEndOffset
== 56, // 58 + (48 - 50)
3117 "Test 5-2-3: mAddedEndOffset should be the first end of added "
3119 "removed text length by the new change");
3122 // Replacing text around start of replaced text (became longer) (not sure if
3124 MergeWith(TextChangeData(50, 60, 68, false, false));
3125 MergeWith(TextChangeData(43, 55, 53, false, false));
3126 MOZ_ASSERT(mStartOffset
== 43,
3127 "Test 5-3-1: mStartOffset should be the smallest offset");
3129 mRemovedEndOffset
== 60,
3130 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3132 MOZ_ASSERT(mAddedEndOffset
== 66, // 68 + (53 - 55)
3133 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3135 "removed text length by the new change");
3138 // Replacing text around start of replaced text (became shorter) (not sure if
3140 MergeWith(TextChangeData(50, 60, 58, false, false));
3141 MergeWith(TextChangeData(43, 50, 128, false, false));
3142 MOZ_ASSERT(mStartOffset
== 43,
3143 "Test 5-4-1: mStartOffset should be the smallest offset");
3145 mRemovedEndOffset
== 60,
3146 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
3149 mAddedEndOffset
== 136, // 58 + (128 - 50)
3150 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
3151 "added text length by the new change");
3154 // Replacing text around start of replaced text (became longer) (not sure if
3156 MergeWith(TextChangeData(50, 60, 68, false, false));
3157 MergeWith(TextChangeData(43, 55, 65, false, false));
3158 MOZ_ASSERT(mStartOffset
== 43,
3159 "Test 5-5-1: mStartOffset should be the smallest offset");
3161 mRemovedEndOffset
== 60,
3162 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
3165 mAddedEndOffset
== 78, // 68 + (65 - 55)
3166 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
3167 "added text length by the new change");
3170 /****************************************************************************
3172 ****************************************************************************/
3174 // Appending text before already added text (not sure if actually occurs)
3175 MergeWith(TextChangeData(30, 30, 45, false, false));
3176 MergeWith(TextChangeData(10, 10, 20, false, false));
3177 MOZ_ASSERT(mStartOffset
== 10,
3178 "Test 6-1-1: mStartOffset should be the smallest offset");
3180 mRemovedEndOffset
== 30,
3181 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3184 mAddedEndOffset
== 55, // 45 + (20 - 10)
3185 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3186 "added text length by the new change");
3189 // Removing text before already removed text (not sure if actually occurs)
3190 MergeWith(TextChangeData(30, 35, 30, false, false));
3191 MergeWith(TextChangeData(10, 25, 10, false, false));
3192 MOZ_ASSERT(mStartOffset
== 10,
3193 "Test 6-2-1: mStartOffset should be the smallest offset");
3195 mRemovedEndOffset
== 35,
3196 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3199 mAddedEndOffset
== 15, // 30 - (25 - 10)
3200 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3201 "removed text length by the new change");
3204 // Replacing text before already replaced text (not sure if actually occurs)
3205 MergeWith(TextChangeData(50, 65, 70, false, false));
3206 MergeWith(TextChangeData(13, 24, 15, false, false));
3207 MOZ_ASSERT(mStartOffset
== 13,
3208 "Test 6-3-1: mStartOffset should be the smallest offset");
3210 mRemovedEndOffset
== 65,
3211 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3213 MOZ_ASSERT(mAddedEndOffset
== 61, // 70 + (15 - 24)
3214 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3216 "removed text length by the new change");
3219 // Replacing text before already replaced text (not sure if actually occurs)
3220 MergeWith(TextChangeData(50, 65, 70, false, false));
3221 MergeWith(TextChangeData(13, 24, 36, false, false));
3222 MOZ_ASSERT(mStartOffset
== 13,
3223 "Test 6-4-1: mStartOffset should be the smallest offset");
3225 mRemovedEndOffset
== 65,
3226 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3228 MOZ_ASSERT(mAddedEndOffset
== 82, // 70 + (36 - 24)
3229 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3231 "removed text length by the new change");
3235 #endif // #ifdef DEBUG
3237 } // namespace mozilla::widget
3240 //////////////////////////////////////////////////////////////
3242 // Convert a GUI event message code to a string.
3243 // Makes it a lot easier to debug events.
3245 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3246 // for a DebugPrintEvent() function that uses
3249 //////////////////////////////////////////////////////////////
3251 nsAutoString
nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent
* aGuiEvent
) {
3252 NS_ASSERTION(nullptr != aGuiEvent
, "cmon, null gui event.");
3254 nsAutoString
eventName(u
"UNKNOWN"_ns
);
3256 # define _ASSIGN_eventName(_value, _name) \
3258 eventName.AssignLiteral(_name); \
3261 switch (aGuiEvent
->mMessage
) {
3262 _ASSIGN_eventName(eBlur
, "eBlur");
3263 _ASSIGN_eventName(eDrop
, "eDrop");
3264 _ASSIGN_eventName(eDragEnter
, "eDragEnter");
3265 _ASSIGN_eventName(eDragExit
, "eDragExit");
3266 _ASSIGN_eventName(eDragOver
, "eDragOver");
3267 _ASSIGN_eventName(eEditorInput
, "eEditorInput");
3268 _ASSIGN_eventName(eFocus
, "eFocus");
3269 _ASSIGN_eventName(eFocusIn
, "eFocusIn");
3270 _ASSIGN_eventName(eFocusOut
, "eFocusOut");
3271 _ASSIGN_eventName(eFormSelect
, "eFormSelect");
3272 _ASSIGN_eventName(eFormChange
, "eFormChange");
3273 _ASSIGN_eventName(eFormReset
, "eFormReset");
3274 _ASSIGN_eventName(eFormSubmit
, "eFormSubmit");
3275 _ASSIGN_eventName(eImageAbort
, "eImageAbort");
3276 _ASSIGN_eventName(eLoadError
, "eLoadError");
3277 _ASSIGN_eventName(eKeyDown
, "eKeyDown");
3278 _ASSIGN_eventName(eKeyPress
, "eKeyPress");
3279 _ASSIGN_eventName(eKeyUp
, "eKeyUp");
3280 _ASSIGN_eventName(eMouseEnterIntoWidget
, "eMouseEnterIntoWidget");
3281 _ASSIGN_eventName(eMouseExitFromWidget
, "eMouseExitFromWidget");
3282 _ASSIGN_eventName(eMouseDown
, "eMouseDown");
3283 _ASSIGN_eventName(eMouseUp
, "eMouseUp");
3284 _ASSIGN_eventName(eMouseClick
, "eMouseClick");
3285 _ASSIGN_eventName(eMouseAuxClick
, "eMouseAuxClick");
3286 _ASSIGN_eventName(eMouseDoubleClick
, "eMouseDoubleClick");
3287 _ASSIGN_eventName(eMouseMove
, "eMouseMove");
3288 _ASSIGN_eventName(eLoad
, "eLoad");
3289 _ASSIGN_eventName(ePopState
, "ePopState");
3290 _ASSIGN_eventName(eBeforeScriptExecute
, "eBeforeScriptExecute");
3291 _ASSIGN_eventName(eAfterScriptExecute
, "eAfterScriptExecute");
3292 _ASSIGN_eventName(eUnload
, "eUnload");
3293 _ASSIGN_eventName(eHashChange
, "eHashChange");
3294 _ASSIGN_eventName(eReadyStateChange
, "eReadyStateChange");
3295 _ASSIGN_eventName(eXULBroadcast
, "eXULBroadcast");
3296 _ASSIGN_eventName(eXULCommandUpdate
, "eXULCommandUpdate");
3298 # undef _ASSIGN_eventName
3301 eventName
.AssignLiteral("UNKNOWN: ");
3302 eventName
.AppendInt(aGuiEvent
->mMessage
);
3306 return nsAutoString(eventName
);
3308 //////////////////////////////////////////////////////////////
3310 // Code to deal with paint and event debug prefs.
3312 //////////////////////////////////////////////////////////////
3318 static PrefPair debug_PrefValues
[] = {
3319 {"nglayout.debug.crossing_event_dumping", false},
3320 {"nglayout.debug.event_dumping", false},
3321 {"nglayout.debug.invalidate_dumping", false},
3322 {"nglayout.debug.motion_event_dumping", false},
3323 {"nglayout.debug.paint_dumping", false}};
3325 //////////////////////////////////////////////////////////////
3326 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName
) {
3327 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3329 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3330 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3331 return debug_PrefValues
[i
].value
;
3337 //////////////////////////////////////////////////////////////
3338 static void debug_SetCachedBoolPref(const char* aPrefName
, bool aValue
) {
3339 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3341 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3342 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3343 debug_PrefValues
[i
].value
= aValue
;
3349 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3352 //////////////////////////////////////////////////////////////
3353 class Debug_PrefObserver final
: public nsIObserver
{
3354 ~Debug_PrefObserver() = default;
3361 NS_IMPL_ISUPPORTS(Debug_PrefObserver
, nsIObserver
)
3364 Debug_PrefObserver::Observe(nsISupports
* subject
, const char* topic
,
3365 const char16_t
* data
) {
3366 NS_ConvertUTF16toUTF8
prefName(data
);
3368 bool value
= Preferences::GetBool(prefName
.get(), false);
3369 debug_SetCachedBoolPref(prefName
.get(), value
);
3373 //////////////////////////////////////////////////////////////
3374 /* static */ void debug_RegisterPrefCallbacks() {
3375 static bool once
= true;
3383 nsCOMPtr
<nsIObserver
> obs(new Debug_PrefObserver());
3384 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3385 // Initialize the pref values
3386 debug_PrefValues
[i
].value
=
3387 Preferences::GetBool(debug_PrefValues
[i
].name
, false);
3390 // Register callbacks for when these change
3392 name
.AssignLiteral(debug_PrefValues
[i
].name
,
3393 strlen(debug_PrefValues
[i
].name
));
3394 Preferences::AddStrongObserver(obs
, name
);
3398 //////////////////////////////////////////////////////////////
3399 static int32_t _GetPrintCount() {
3400 static int32_t sCount
= 0;
3404 //////////////////////////////////////////////////////////////
3406 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3407 WidgetGUIEvent
* aGuiEvent
,
3408 const char* aWidgetName
, int32_t aWindowID
) {
3409 if (aGuiEvent
->mMessage
== eMouseMove
) {
3410 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3413 if (aGuiEvent
->mMessage
== eMouseEnterIntoWidget
||
3414 aGuiEvent
->mMessage
== eMouseExitFromWidget
) {
3415 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3419 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3421 NS_LossyConvertUTF16toASCII
tempString(
3422 debug_GuiEventToString(aGuiEvent
).get());
3424 fprintf(aFileOut
, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3425 _GetPrintCount(), tempString
.get(), (void*)aWidget
, aWidgetName
,
3426 aWindowID
, aGuiEvent
->mRefPoint
.x
.value
,
3427 aGuiEvent
->mRefPoint
.y
.value
);
3429 //////////////////////////////////////////////////////////////
3431 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3432 const nsIntRegion
& aRegion
,
3433 const char* aWidgetName
,
3434 int32_t aWindowID
) {
3435 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3436 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3438 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3440 nsIntRect rect
= aRegion
.GetBounds();
3442 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3444 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
, rect
.X(),
3445 rect
.Y(), rect
.Width(), rect
.Height());
3447 fprintf(aFileOut
, "\n");
3449 //////////////////////////////////////////////////////////////
3451 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut
, nsIWidget
* aWidget
,
3452 const LayoutDeviceIntRect
* aRect
,
3453 const char* aWidgetName
,
3454 int32_t aWindowID
) {
3455 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3457 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3458 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3460 fprintf(aFileOut
, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3461 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
);
3464 fprintf(aFileOut
, " rect=%3d,%-3d %3d,%-3d", aRect
->X(), aRect
->Y(),
3465 aRect
->Width(), aRect
->Height());
3467 fprintf(aFileOut
, " rect=%-15s", "none");
3470 fprintf(aFileOut
, "\n");
3472 //////////////////////////////////////////////////////////////