2 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
3 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
4 /* This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 #include "nsBaseWidget.h"
13 #include "InputData.h"
14 #include "LiveResizeListener.h"
15 #include "SwipeTracker.h"
16 #include "TouchEvents.h"
17 #include "X11UndefineNone.h"
18 #include "base/thread.h"
19 #include "mozilla/ArrayUtils.h"
20 #include "mozilla/Attributes.h"
21 #include "mozilla/GlobalKeyListener.h"
22 #include "mozilla/IMEStateManager.h"
23 #include "mozilla/Logging.h"
24 #include "mozilla/MouseEvents.h"
25 #include "mozilla/NativeKeyBindingsType.h"
26 #include "mozilla/Preferences.h"
27 #include "mozilla/PresShell.h"
28 #include "mozilla/ScopeExit.h"
29 #include "mozilla/Sprintf.h"
30 #include "mozilla/StaticPrefs_apz.h"
31 #include "mozilla/StaticPrefs_dom.h"
32 #include "mozilla/StaticPrefs_gfx.h"
33 #include "mozilla/StaticPrefs_layers.h"
34 #include "mozilla/StaticPrefs_layout.h"
35 #include "mozilla/TextEventDispatcher.h"
36 #include "mozilla/TextEventDispatcherListener.h"
37 #include "mozilla/UniquePtr.h"
38 #include "mozilla/Unused.h"
39 #include "mozilla/VsyncDispatcher.h"
40 #include "mozilla/dom/BrowserParent.h"
41 #include "mozilla/dom/ContentChild.h"
42 #include "mozilla/dom/Document.h"
43 #include "mozilla/dom/SimpleGestureEventBinding.h"
44 #include "mozilla/gfx/2D.h"
45 #include "mozilla/gfx/GPUProcessManager.h"
46 #include "mozilla/gfx/gfxVars.h"
47 #include "mozilla/layers/APZCCallbackHelper.h"
48 #include "mozilla/layers/TouchActionHelper.h"
49 #include "mozilla/layers/APZEventState.h"
50 #include "mozilla/layers/APZInputBridge.h"
51 #include "mozilla/layers/APZThreadUtils.h"
52 #include "mozilla/layers/ChromeProcessController.h"
53 #include "mozilla/layers/Compositor.h"
54 #include "mozilla/layers/CompositorBridgeChild.h"
55 #include "mozilla/layers/CompositorBridgeParent.h"
56 #include "mozilla/layers/CompositorOptions.h"
57 #include "mozilla/layers/IAPZCTreeManager.h"
58 #include "mozilla/layers/ImageBridgeChild.h"
59 #include "mozilla/layers/InputAPZContext.h"
60 #include "mozilla/layers/WebRenderLayerManager.h"
61 #include "mozilla/webrender/WebRenderTypes.h"
62 #include "mozilla/widget/ScreenManager.h"
63 #include "nsAppDirectoryServiceDefs.h"
65 #include "nsContentUtils.h"
66 #include "nsDeviceContext.h"
67 #include "nsGfxCIID.h"
68 #include "nsIAppWindow.h"
69 #include "nsIBaseWindow.h"
70 #include "nsIContent.h"
71 #include "nsIScreenManager.h"
72 #include "nsISimpleEnumerator.h"
73 #include "nsIWidgetListener.h"
74 #include "nsRefPtrHashtable.h"
75 #include "nsServiceManagerUtils.h"
76 #include "nsWidgetsCID.h"
77 #include "nsXULPopupManager.h"
81 # include "nsAccessibilityService.h"
83 #include "gfxConfig.h"
84 #include "gfxUtils.h" // for ToDeviceColor
85 #include "mozilla/layers/CompositorSession.h"
86 #include "VRManagerChild.h"
87 #include "gfxConfig.h"
89 #include "nsViewManager.h"
91 static mozilla::LazyLogModule
sBaseWidgetLog("BaseWidget");
94 # include "nsIObserver.h"
96 static void debug_RegisterPrefCallbacks();
100 #ifdef NOISY_WIDGET_LEAKS
101 static int32_t gNumWidgets
;
105 # include "nsCocoaFeatures.h"
108 using namespace mozilla::dom
;
109 using namespace mozilla::layers
;
110 using namespace mozilla::ipc
;
111 using namespace mozilla::widget
;
112 using namespace mozilla
;
114 // Async pump timer during injected long touch taps
115 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
116 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
117 int32_t nsIWidget::sPointerIdCounter
= 0;
119 // Some statics from nsIWidget.h
121 uint64_t AutoObserverNotifier::sObserverId
= 0;
122 /*static*/ nsTHashMap
<uint64_t, nsCOMPtr
<nsIObserver
>>
123 AutoObserverNotifier::sSavedObservers
;
125 // The maximum amount of time to let the EnableDragDrop runnable wait in the
126 // idle queue before timing out and moving it to the regular queue. Value is in
128 const uint32_t kAsyncDragDropTimeout
= 1000;
130 NS_IMPL_ISUPPORTS(nsBaseWidget
, nsIWidget
, nsISupportsWeakReference
)
132 //-------------------------------------------------------------------------
134 // nsBaseWidget constructor
136 //-------------------------------------------------------------------------
138 nsBaseWidget::nsBaseWidget() : nsBaseWidget(BorderStyle::None
) {}
140 nsBaseWidget::nsBaseWidget(BorderStyle aBorderStyle
)
141 : mWidgetListener(nullptr),
142 mAttachedWidgetListener(nullptr),
143 mPreviouslyAttachedWidgetListener(nullptr),
144 mCompositorVsyncDispatcher(nullptr),
145 mBorderStyle(aBorderStyle
),
148 mPopupLevel(PopupLevel::Top
),
149 mPopupType(PopupType::Any
),
150 mHasRemoteContent(false),
152 mUseAttachedEvents(false),
155 mIsFullyOccluded(false),
156 mNeedFastSnaphot(false),
157 mCurrentPanGestureBelongsToSwipe(false) {
158 #ifdef NOISY_WIDGET_LEAKS
160 printf("WIDGETS+ = %d\n", gNumWidgets
);
164 debug_RegisterPrefCallbacks();
167 mShutdownObserver
= new WidgetShutdownObserver(this);
170 NS_IMPL_ISUPPORTS(WidgetShutdownObserver
, nsIObserver
)
172 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget
* aWidget
)
173 : mWidget(aWidget
), mRegistered(false) {
177 WidgetShutdownObserver::~WidgetShutdownObserver() {
178 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
179 // gets torn down. The observer service and nsBaseWidget have a ref on us
180 // so nsBaseWidget has to call Unregister and then clear its ref.
184 WidgetShutdownObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
185 const char16_t
* aData
) {
189 if (!strcmp(aTopic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
)) {
190 RefPtr
<nsBaseWidget
> widget(mWidget
);
192 } else if (!strcmp(aTopic
, "quit-application")) {
193 RefPtr
<nsBaseWidget
> widget(mWidget
);
199 void WidgetShutdownObserver::Register() {
202 nsContentUtils::RegisterShutdownObserver(this);
204 #ifndef MOZ_WIDGET_ANDROID
205 // The primary purpose of observing quit-application is
206 // to avoid leaking a widget on Windows when nothing else
207 // breaks the circular reference between the widget and
208 // TSFTextStore. However, our Android IME code crashes if
209 // doing this on Android, so let's not do this on Android.
210 // Doing this on Gtk and Mac just in case.
211 nsCOMPtr
<nsIObserverService
> observerService
=
212 mozilla::services::GetObserverService();
213 if (observerService
) {
214 observerService
->AddObserver(this, "quit-application", false);
220 void WidgetShutdownObserver::Unregister() {
224 #ifndef MOZ_WIDGET_ANDROID
225 nsCOMPtr
<nsIObserverService
> observerService
=
226 mozilla::services::GetObserverService();
227 if (observerService
) {
228 observerService
->RemoveObserver(this, "quit-application");
232 nsContentUtils::UnregisterShutdownObserver(this);
237 #define INTL_APP_LOCALES_CHANGED "intl:app-locales-changed"
239 NS_IMPL_ISUPPORTS(LocalesChangedObserver
, nsIObserver
)
241 LocalesChangedObserver::LocalesChangedObserver(nsBaseWidget
* aWidget
)
242 : mWidget(aWidget
), mRegistered(false) {
246 LocalesChangedObserver::~LocalesChangedObserver() {
247 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
248 // gets torn down. The observer service and nsBaseWidget have a ref on us
249 // so nsBaseWidget has to call Unregister and then clear its ref.
253 LocalesChangedObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
254 const char16_t
* aData
) {
258 if (!strcmp(aTopic
, INTL_APP_LOCALES_CHANGED
)) {
259 RefPtr
<nsBaseWidget
> widget(mWidget
);
260 widget
->LocalesChanged();
265 void LocalesChangedObserver::Register() {
270 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
272 obs
->AddObserver(this, INTL_APP_LOCALES_CHANGED
, true);
275 // Locale might be update before registering
276 RefPtr
<nsBaseWidget
> widget(mWidget
);
277 widget
->LocalesChanged();
282 void LocalesChangedObserver::Unregister() {
287 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
289 obs
->RemoveObserver(this, INTL_APP_LOCALES_CHANGED
);
296 void nsBaseWidget::Shutdown() {
297 NotifyLiveResizeStopped();
299 FreeLocalesChangedObserver();
300 FreeShutdownObserver();
303 void nsBaseWidget::QuitIME() {
304 IMEStateManager::WidgetOnQuit(this);
305 this->mIMEHasQuit
= true;
308 void nsBaseWidget::DestroyCompositor() {
309 RevokeTransactionIdAllocator();
311 // We release this before releasing the compositor, since it may hold the
312 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
313 // trigger a paint, creating a new compositor, and we don't want to re-use
314 // the old vsync dispatcher.
315 if (mCompositorVsyncDispatcher
) {
316 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
318 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
319 mCompositorVsyncDispatcher
->Shutdown();
320 mCompositorVsyncDispatcher
= nullptr;
323 // The compositor shutdown sequence looks like this:
324 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
325 // 2. CompositorBridgeChild synchronously sends WillClose.
326 // 3. CompositorBridgeParent releases some resources (such as the layer
327 // manager, compositor, and widget).
328 // 4. CompositorBridgeChild::Destroy returns.
329 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
330 // compositor thread when the I/O thread closes the IPC channel.
331 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
332 // releases the reference CompositorBridgeParent holds to itself.
334 // When CompositorSession::Shutdown returns, we assume the compositor is gone
335 // or will be gone very soon.
336 if (mCompositorSession
) {
337 ReleaseContentController();
339 SetCompositorWidgetDelegate(nullptr);
340 mCompositorBridgeChild
= nullptr;
341 mCompositorSession
->Shutdown();
342 mCompositorSession
= nullptr;
346 // This prevents the layer manager from starting a new transaction during
348 void nsBaseWidget::RevokeTransactionIdAllocator() {
349 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
352 mWindowRenderer
->AsWebRender()->SetTransactionIdAllocator(nullptr);
355 void nsBaseWidget::ReleaseContentController() {
356 if (mRootContentController
) {
357 mRootContentController
->Destroy();
358 mRootContentController
= nullptr;
362 void nsBaseWidget::DestroyLayerManager() {
363 if (mWindowRenderer
) {
364 mWindowRenderer
->Destroy();
365 mWindowRenderer
= nullptr;
370 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
372 void nsBaseWidget::FreeShutdownObserver() {
373 if (mShutdownObserver
) {
374 mShutdownObserver
->Unregister();
376 mShutdownObserver
= nullptr;
379 void nsBaseWidget::FreeLocalesChangedObserver() {
380 if (mLocalesChangedObserver
) {
381 mLocalesChangedObserver
->Unregister();
383 mLocalesChangedObserver
= nullptr;
386 //-------------------------------------------------------------------------
388 // nsBaseWidget destructor
390 //-------------------------------------------------------------------------
392 nsBaseWidget::~nsBaseWidget() {
394 mSwipeTracker
->Destroy();
395 mSwipeTracker
= nullptr;
398 IMEStateManager::WidgetDestroyed(this);
400 FreeLocalesChangedObserver();
401 FreeShutdownObserver();
402 DestroyLayerManager();
404 #ifdef NOISY_WIDGET_LEAKS
406 printf("WIDGETS- = %d\n", gNumWidgets
);
410 //-------------------------------------------------------------------------
414 //-------------------------------------------------------------------------
415 void nsBaseWidget::BaseCreate(nsIWidget
* aParent
, widget::InitData
* aInitData
) {
417 mWindowType
= aInitData
->mWindowType
;
418 mBorderStyle
= aInitData
->mBorderStyle
;
419 mPopupLevel
= aInitData
->mPopupLevel
;
420 mPopupType
= aInitData
->mPopupHint
;
421 mHasRemoteContent
= aInitData
->mHasRemoteContent
;
425 aParent
->AddChild(this);
429 //-------------------------------------------------------------------------
431 // Accessor functions to get/set the client data
433 //-------------------------------------------------------------------------
435 nsIWidgetListener
* nsBaseWidget::GetWidgetListener() const {
436 return mWidgetListener
;
439 void nsBaseWidget::SetWidgetListener(nsIWidgetListener
* aWidgetListener
) {
440 mWidgetListener
= aWidgetListener
;
443 already_AddRefed
<nsIWidget
> nsBaseWidget::CreateChild(
444 const LayoutDeviceIntRect
& aRect
, widget::InitData
* aInitData
,
445 bool aForceUseIWidgetParent
) {
446 nsIWidget
* parent
= this;
447 nsNativeWidget nativeParent
= nullptr;
449 if (!aForceUseIWidgetParent
) {
450 // Use only either parent or nativeParent, not both, to match
451 // existing code. Eventually Create() should be divested of its
452 // nativeWidget parameter.
453 nativeParent
= parent
? parent
->GetNativeData(NS_NATIVE_WIDGET
) : nullptr;
454 parent
= nativeParent
? nullptr : parent
;
455 MOZ_ASSERT(!parent
|| !nativeParent
, "messed up logic");
458 nsCOMPtr
<nsIWidget
> widget
;
459 if (aInitData
&& aInitData
->mWindowType
== WindowType::Popup
) {
460 widget
= AllocateChildPopupWidget();
462 widget
= nsIWidget::CreateChildWindow();
465 if (widget
&& mNeedFastSnaphot
) {
466 widget
->SetNeedFastSnaphot();
470 NS_SUCCEEDED(widget
->Create(parent
, nativeParent
, aRect
, aInitData
))) {
471 return widget
.forget();
477 // Attach a view to our widget which we'll send events to.
478 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents
) {
479 NS_ASSERTION((mWindowType
== WindowType::TopLevel
||
480 mWindowType
== WindowType::Dialog
||
481 mWindowType
== WindowType::Invisible
||
482 mWindowType
== WindowType::Child
),
483 "Can't attach to window of that type");
485 mUseAttachedEvents
= aUseAttachedEvents
;
488 nsIWidgetListener
* nsBaseWidget::GetAttachedWidgetListener() const {
489 return mAttachedWidgetListener
;
492 nsIWidgetListener
* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
493 return mPreviouslyAttachedWidgetListener
;
496 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
497 nsIWidgetListener
* aListener
) {
498 mPreviouslyAttachedWidgetListener
= aListener
;
501 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener
* aListener
) {
502 mAttachedWidgetListener
= aListener
;
505 //-------------------------------------------------------------------------
507 // Close this nsBaseWidget
509 //-------------------------------------------------------------------------
510 void nsBaseWidget::Destroy() {
513 // Just in case our parent is the only ref to us
514 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
515 // disconnect from the parent
516 nsIWidget
* parent
= GetParent();
518 parent
->RemoveChild(this);
522 //-------------------------------------------------------------------------
524 // Get this nsBaseWidget parent
526 //-------------------------------------------------------------------------
527 nsIWidget
* nsBaseWidget::GetParent(void) { return nullptr; }
529 //-------------------------------------------------------------------------
531 // Get this nsBaseWidget top level widget
533 //-------------------------------------------------------------------------
534 nsIWidget
* nsBaseWidget::GetTopLevelWidget() {
535 nsIWidget
*topLevelWidget
= nullptr, *widget
= this;
537 topLevelWidget
= widget
;
538 widget
= widget
->GetParent();
540 return topLevelWidget
;
543 //-------------------------------------------------------------------------
545 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
547 //-------------------------------------------------------------------------
548 nsIWidget
* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
550 float nsBaseWidget::GetDPI() { return 96.0f
; }
552 CSSToLayoutDeviceScale
nsIWidget::GetDefaultScale() {
553 double devPixelsPerCSSPixel
= StaticPrefs::layout_css_devPixelsPerPx();
555 if (devPixelsPerCSSPixel
<= 0.0) {
556 devPixelsPerCSSPixel
= GetDefaultScaleInternal();
559 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel
);
562 nsIntSize
nsIWidget::CustomCursorSize(const Cursor
& aCursor
) {
563 MOZ_ASSERT(aCursor
.IsCustom());
566 aCursor
.mContainer
->GetWidth(&width
);
567 aCursor
.mContainer
->GetHeight(&height
);
568 aCursor
.mResolution
.ApplyTo(width
, height
);
569 return {width
, height
};
572 LayoutDeviceIntSize
nsIWidget::ClientToWindowSizeDifference() {
573 auto margin
= ClientToWindowMargin();
574 MOZ_ASSERT(margin
.top
>= 0, "Window should be bigger than client area");
575 MOZ_ASSERT(margin
.left
>= 0, "Window should be bigger than client area");
576 MOZ_ASSERT(margin
.right
>= 0, "Window should be bigger than client area");
577 MOZ_ASSERT(margin
.bottom
>= 0, "Window should be bigger than client area");
578 return {margin
.LeftRight(), margin
.TopBottom()};
581 RefPtr
<mozilla::VsyncDispatcher
> nsIWidget::GetVsyncDispatcher() {
585 //-------------------------------------------------------------------------
587 // Add a child to the list of children
589 //-------------------------------------------------------------------------
590 void nsBaseWidget::AddChild(nsIWidget
* aChild
) {
591 MOZ_ASSERT(!aChild
->GetNextSibling() && !aChild
->GetPrevSibling(),
592 "aChild not properly removed from its old child list");
595 mFirstChild
= mLastChild
= aChild
;
597 // append to the list
598 MOZ_ASSERT(mLastChild
);
599 MOZ_ASSERT(!mLastChild
->GetNextSibling());
600 mLastChild
->SetNextSibling(aChild
);
601 aChild
->SetPrevSibling(mLastChild
);
606 //-------------------------------------------------------------------------
608 // Remove a child from the list of children
610 //-------------------------------------------------------------------------
611 void nsBaseWidget::RemoveChild(nsIWidget
* aChild
) {
614 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
615 // null and we'll just have to do without this assertion.
616 nsIWidget
* parent
= aChild
->GetParent();
617 NS_ASSERTION(!parent
|| parent
== this, "Not one of our kids!");
619 MOZ_RELEASE_ASSERT(aChild
->GetParent() == this, "Not one of our kids!");
623 if (mLastChild
== aChild
) {
624 mLastChild
= mLastChild
->GetPrevSibling();
626 if (mFirstChild
== aChild
) {
627 mFirstChild
= mFirstChild
->GetNextSibling();
630 // Now remove from the list. Make sure that we pass ownership of the tail
631 // of the list correctly before we have aChild let go of it.
632 nsIWidget
* prev
= aChild
->GetPrevSibling();
633 nsIWidget
* next
= aChild
->GetNextSibling();
635 prev
->SetNextSibling(next
);
638 next
->SetPrevSibling(prev
);
641 aChild
->SetNextSibling(nullptr);
642 aChild
->SetPrevSibling(nullptr);
645 //-------------------------------------------------------------------------
647 // Sets widget's position within its parent's child list.
649 //-------------------------------------------------------------------------
650 void nsBaseWidget::SetZIndex(int32_t aZIndex
) {
651 // Hold a ref to ourselves just in case, since we're going to remove
653 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
657 // reorder this child in its parent's list.
658 auto* parent
= static_cast<nsBaseWidget
*>(GetParent());
660 parent
->RemoveChild(this);
661 // Scope sib outside the for loop so we can check it afterward
662 nsIWidget
* sib
= parent
->GetFirstChild();
663 for (; sib
; sib
= sib
->GetNextSibling()) {
664 int32_t childZIndex
= GetZIndex();
665 if (aZIndex
< childZIndex
) {
666 // Insert ourselves before sib
667 nsIWidget
* prev
= sib
->GetPrevSibling();
670 sib
->SetPrevSibling(this);
672 prev
->SetNextSibling(this);
674 NS_ASSERTION(sib
== parent
->mFirstChild
, "Broken child list");
675 // We've taken ownership of sib, so it's safe to have parent let
677 parent
->mFirstChild
= this;
679 PlaceBehind(eZPlacementBelow
, sib
, false);
683 // were we added to the list?
685 parent
->AddChild(this);
690 void nsBaseWidget::GetWorkspaceID(nsAString
& workspaceID
) {
691 workspaceID
.Truncate();
694 void nsBaseWidget::MoveToWorkspace(const nsAString
& workspaceID
) {
698 //-------------------------------------------------------------------------
700 // Get this component cursor
702 //-------------------------------------------------------------------------
704 void nsBaseWidget::SetCursor(const Cursor
& aCursor
) { mCursor
= aCursor
; }
706 //-------------------------------------------------------------------------
708 // Window transparency methods
710 //-------------------------------------------------------------------------
712 void nsBaseWidget::SetTransparencyMode(TransparencyMode aMode
) {}
714 TransparencyMode
nsBaseWidget::GetTransparencyMode() {
715 return TransparencyMode::Opaque
;
719 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage
,
722 nsIRunnable
* aCallback
) {
723 MOZ_ASSERT_UNREACHABLE(
724 "Should never call PerformFullscreenTransition on nsBaseWidget");
727 //-------------------------------------------------------------------------
729 // Put the window into full-screen mode
731 //-------------------------------------------------------------------------
732 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen
) {
733 #define MOZ_FORMAT_RECT(fmtstr) "[" fmtstr "," fmtstr " " fmtstr "x" fmtstr "]"
734 #define MOZ_SPLAT_RECT(rect) \
735 (rect).X(), (rect).Y(), (rect).Width(), (rect).Height()
737 // Windows which can be made fullscreen are exactly those which are located on
738 // the desktop, rather than being a child of some other window.
739 MOZ_DIAGNOSTIC_ASSERT(BoundsUseDesktopPixels(),
740 "non-desktop windows cannot be made fullscreen");
742 // Ensure that the OS chrome is hidden/shown before we resize and/or exit the
745 // HideWindowChrome() may (depending on platform, implementation details, and
746 // OS-level user preferences) alter the reported size of the window. The
747 // obvious and principled solution is socks-and-shoes:
748 // - On entering fullscreen mode: hide window chrome, then perform resize.
749 // - On leaving fullscreen mode: unperform resize, then show window chrome.
751 // ... unfortunately, HideWindowChrome() requires Resize() to be called
752 // afterwards (see bug 498835), which prevents this from being done in a
753 // straightforward way.
755 // Instead, we always call HideWindowChrome() just before we call Resize().
756 // This at least ensures that our measurements are consistently taken in a
757 // pre-transition state.
759 // ... unfortunately again, coupling HideWindowChrome() to Resize() means that
760 // we have to worry about the possibility of control flows that don't call
761 // Resize() at all. (That shouldn't happen, but it's not trivial to rule out.)
762 // We therefore set up a fallback to fix up the OS chrome if it hasn't been
763 // done at exit time.
764 bool hasAdjustedOSChrome
= false;
765 const auto adjustOSChrome
= [&]() {
766 if (hasAdjustedOSChrome
) {
767 MOZ_ASSERT_UNREACHABLE("window chrome should only be adjusted once");
770 HideWindowChrome(aFullScreen
);
771 hasAdjustedOSChrome
= true;
773 const auto adjustChromeOnScopeExit
= MakeScopeExit([&]() {
774 if (hasAdjustedOSChrome
) {
778 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
779 ("window was not resized within InfallibleMakeFullScreen()"));
781 // Hide chrome and "resize" the window to its current size.
782 auto rect
= GetBounds();
784 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
787 // Attempt to resize to `rect`.
789 // Returns the actual rectangle resized to. (This may differ from `rect`, if
790 // the OS is unhappy with it. See bug 1786226.)
791 const auto doReposition
= [&](auto rect
) -> void {
792 static_assert(std::is_base_of_v
<DesktopPixel
,
793 std::remove_reference_t
<decltype(rect
)>>,
794 "doReposition requires a rectangle using desktop pixels");
796 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Debug
)) {
797 const DesktopRect previousSize
=
798 GetScreenBounds() / GetDesktopToDeviceScale();
799 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
800 ("before resize: " MOZ_FORMAT_RECT("%f"),
801 MOZ_SPLAT_RECT(previousSize
)));
805 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
807 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Warning
)) {
808 // `rect` may have any underlying data type; coerce to float to
809 // simplify printf-style logging
810 const gfx::RectTyped
<DesktopPixel
, float> rectAsFloat
{rect
};
812 // The OS may have objected to the target position. That's not necessarily
813 // a problem -- it'll happen regularly on Macs with camera notches in the
814 // monitor, for instance (see bug 1786226) -- but it probably deserves to
817 // Since there's floating-point math involved, the actual values may be
818 // off by a few ulps -- as an upper bound, perhaps 8 * FLT_EPSILON *
819 // max(MOZ_SPLAT_RECT(rect)) -- but 0.01 should be several orders of
820 // magnitude bigger than that.
822 const auto postResizeRectRaw
= GetScreenBounds();
823 const auto postResizeRect
= postResizeRectRaw
/ GetDesktopToDeviceScale();
824 const bool succeeded
= postResizeRect
.WithinEpsilonOf(rectAsFloat
, 0.01);
827 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
828 ("resized to: " MOZ_FORMAT_RECT("%f"),
829 MOZ_SPLAT_RECT(rectAsFloat
)));
831 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
832 ("attempted to resize to: " MOZ_FORMAT_RECT("%f"),
833 MOZ_SPLAT_RECT(rectAsFloat
)));
834 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
835 ("... but ended up at: " MOZ_FORMAT_RECT("%f"),
836 MOZ_SPLAT_RECT(postResizeRect
)));
840 sBaseWidgetLog
, LogLevel::Verbose
,
841 ("(... which, before DPI adjustment, is:" MOZ_FORMAT_RECT("%d") ")",
842 MOZ_SPLAT_RECT(postResizeRectRaw
)));
848 mSavedBounds
= Some(FullscreenSavedState());
850 // save current position
851 mSavedBounds
->windowRect
= GetScreenBounds() / GetDesktopToDeviceScale();
853 nsCOMPtr
<nsIScreen
> screen
= GetWidgetScreen();
858 // Move to fill the screen.
859 doReposition(screen
->GetRectDisplayPix());
860 // Save off the new position. (This may differ from GetRectDisplayPix(), if
861 // the OS was unhappy with it. See bug 1786226.)
862 mSavedBounds
->screenRect
= GetScreenBounds() / GetDesktopToDeviceScale();
865 // This should never happen, at present, since we don't make windows
866 // fullscreen at their creation time; but it's not logically impossible.
867 MOZ_ASSERT(false, "fullscreen window did not have saved position");
871 // Figure out where to go from here.
873 // Fortunately, since we're currently fullscreen (and other code should be
874 // handling _keeping_ us fullscreen even after display-layout changes),
875 // there's an obvious choice for which display we should attach to; all we
876 // need to determine is where on that display we should go.
878 const DesktopRect currentWinRect
=
879 GetScreenBounds() / GetDesktopToDeviceScale();
881 // Optimization: if where we are is where we were, then where we originally
882 // came from is where we're going to go.
883 if (currentWinRect
== DesktopRect(mSavedBounds
->screenRect
)) {
884 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
885 ("no location change detected; returning to saved location"));
886 doReposition(mSavedBounds
->windowRect
);
891 General case: figure out where we're going to go by dividing where we are
892 by where we were, and then multiplying by where we originally came from.
894 Less abstrusely: resize so that we occupy the same proportional position
895 on our current display after leaving fullscreen as we occupied on our
896 previous display before entering fullscreen.
898 (N.B.: We do not clamp. If we were only partially on the old display,
899 we'll be only partially on the new one, too.)
902 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
903 ("location change detected; computing new destination"));
905 // splat: convert an arbitrary Rect into a tuple, for syntactic convenience.
906 const auto splat
= [](auto rect
) {
907 return std::tuple(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height());
910 // remap: find the unique affine mapping which transforms `src` to `dst`,
911 // and apply it to `val`.
912 using Range
= std::pair
<float, float>;
913 const auto remap
= [](Range dst
, Range src
, float val
) {
914 // linear interpolation and its inverse: lerp(a, b, invlerp(a, b, t)) == t
915 const auto lerp
= [](float lo
, float hi
, float t
) {
916 return lo
+ t
* (hi
- lo
);
918 const auto invlerp
= [](float lo
, float hi
, float mid
) {
919 return (mid
- lo
) / (hi
- lo
);
922 const auto [dst_a
, dst_b
] = dst
;
923 const auto [src_a
, src_b
] = src
;
924 return lerp(dst_a
, dst_b
, invlerp(src_a
, src_b
, val
));
928 const auto [px
, py
, pw
, ph
] = splat(mSavedBounds
->windowRect
);
929 // source desktop rect
930 const auto [sx
, sy
, sw
, sh
] = splat(mSavedBounds
->screenRect
);
931 // target desktop rect
932 const auto [tx
, ty
, tw
, th
] = splat(currentWinRect
);
934 const float nx
= remap({tx
, tx
+ tw
}, {sx
, sx
+ sw
}, px
);
935 const float ny
= remap({ty
, ty
+ th
}, {sy
, sy
+ sh
}, py
);
936 const float nw
= remap({0, tw
}, {0, sw
}, pw
);
937 const float nh
= remap({0, th
}, {0, sh
}, ph
);
939 doReposition(DesktopRect
{nx
, ny
, nw
, nh
});
942 #undef MOZ_SPLAT_RECT
943 #undef MOZ_FORMAT_RECT
946 nsresult
nsBaseWidget::MakeFullScreen(bool aFullScreen
) {
947 InfallibleMakeFullScreen(aFullScreen
);
951 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
952 nsBaseWidget
* aWidget
, gfxContext
* aTarget
, BufferMode aDoubleBuffering
)
954 WindowRenderer
* renderer
= mWidget
->GetWindowRenderer();
955 if (renderer
->AsFallback()) {
956 mRenderer
= renderer
->AsFallback();
957 mRenderer
->SetTarget(aTarget
, aDoubleBuffering
);
961 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
963 mRenderer
->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE
);
967 bool nsBaseWidget::IsSmallPopup() const {
968 return mWindowType
== WindowType::Popup
&& mPopupType
!= PopupType::Panel
;
971 bool nsBaseWidget::ComputeShouldAccelerate() {
972 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING
) &&
973 (WidgetTypeSupportsAcceleration() ||
974 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
977 bool nsBaseWidget::UseAPZ() {
978 return (gfxPlatform::AsyncPanZoomEnabled() &&
979 (mWindowType
== WindowType::TopLevel
||
980 mWindowType
== WindowType::Child
||
981 ((mWindowType
== WindowType::Popup
||
982 mWindowType
== WindowType::Dialog
) &&
983 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
986 void nsBaseWidget::CreateCompositor() {
987 LayoutDeviceIntRect rect
= GetBounds();
988 CreateCompositor(rect
.Width(), rect
.Height());
991 void nsIWidget::PauseOrResumeCompositor(bool aPause
) {
992 auto* renderer
= GetRemoteRenderer();
997 renderer
->SendPause();
999 renderer
->SendResume();
1003 already_AddRefed
<GeckoContentController
>
1004 nsBaseWidget::CreateRootContentController() {
1005 RefPtr
<GeckoContentController
> controller
=
1006 new ChromeProcessController(this, mAPZEventState
, mAPZC
);
1007 return controller
.forget();
1010 void nsBaseWidget::ConfigureAPZCTreeManager() {
1011 MOZ_ASSERT(NS_IsMainThread());
1014 mAPZC
->SetDPI(GetDPI());
1016 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
1017 KeyboardMap map
= RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
1018 mAPZC
->SetKeyboardMap(map
);
1021 ContentReceivedInputBlockCallback
callback(
1022 [treeManager
= RefPtr
{mAPZC
.get()}](uint64_t aInputBlockId
,
1023 bool aPreventDefault
) {
1024 MOZ_ASSERT(NS_IsMainThread());
1025 treeManager
->ContentReceivedInputBlock(aInputBlockId
, aPreventDefault
);
1027 mAPZEventState
= new APZEventState(this, std::move(callback
));
1029 mRootContentController
= CreateRootContentController();
1030 if (mRootContentController
) {
1031 mCompositorSession
->SetContentController(mRootContentController
);
1034 // When APZ is enabled, we can actually enable raw touch events because we
1035 // have code that can deal with them properly. If APZ is not enabled, this
1036 // function doesn't get called.
1037 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
1038 RegisterTouchWindow();
1042 void nsBaseWidget::ConfigureAPZControllerThread() {
1043 // By default the controller thread is the main thread.
1044 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
1047 void nsBaseWidget::SetConfirmedTargetAPZC(
1048 uint64_t aInputBlockId
,
1049 const nsTArray
<ScrollableLayerGuid
>& aTargets
) const {
1050 mAPZC
->SetTargetAPZC(aInputBlockId
, aTargets
);
1053 void nsBaseWidget::UpdateZoomConstraints(
1054 const uint32_t& aPresShellId
, const ScrollableLayerGuid::ViewID
& aViewId
,
1055 const Maybe
<ZoomConstraints
>& aConstraints
) {
1056 if (!mCompositorSession
|| !mAPZC
) {
1057 if (mInitialZoomConstraints
) {
1058 MOZ_ASSERT(mInitialZoomConstraints
->mPresShellID
== aPresShellId
);
1059 MOZ_ASSERT(mInitialZoomConstraints
->mViewID
== aViewId
);
1060 if (!aConstraints
) {
1061 mInitialZoomConstraints
.reset();
1066 // We have some constraints, but the compositor and APZC aren't created
1067 // yet. Save these so we can use them later.
1068 mInitialZoomConstraints
= Some(
1069 InitialZoomConstraints(aPresShellId
, aViewId
, aConstraints
.ref()));
1073 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1074 mAPZC
->UpdateZoomConstraints(
1075 ScrollableLayerGuid(layersId
, aPresShellId
, aViewId
), aConstraints
);
1078 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC
; }
1080 nsEventStatus
nsBaseWidget::ProcessUntransformedAPZEvent(
1081 WidgetInputEvent
* aEvent
, const APZEventResult
& aApzResult
) {
1082 MOZ_ASSERT(NS_IsMainThread());
1083 ScrollableLayerGuid targetGuid
= aApzResult
.mTargetGuid
;
1084 uint64_t inputBlockId
= aApzResult
.mInputBlockId
;
1085 InputAPZContext
context(aApzResult
.mTargetGuid
, inputBlockId
,
1086 aApzResult
.GetStatus());
1088 // Make a copy of the original event for the APZCCallbackHelper helpers that
1089 // we call later, because the event passed to DispatchEvent can get mutated in
1090 // ways that we don't want (i.e. touch points can get stripped out).
1091 nsEventStatus status
;
1092 UniquePtr
<WidgetEvent
> original(aEvent
->Duplicate());
1093 DispatchEvent(aEvent
, status
);
1095 if (mAPZC
&& !InputAPZContext::WasRoutedToChildProcess() && inputBlockId
) {
1096 // EventStateManager did not route the event into the child process.
1097 // It's safe to communicate to APZ that the event has been processed.
1098 // Note that here aGuid.mLayersId might be different from
1099 // mCompositorSession->RootLayerTreeId() because the event might have gotten
1100 // hit-tested by APZ to be targeted at a child process, but a parent process
1101 // event listener called preventDefault on it. In that case aGuid.mLayersId
1102 // would still be the layers id for the child process, but the event would
1103 // not have actually gotten routed to the child process. The main-thread
1104 // hit-test result therefore needs to use the parent process layers id.
1105 LayersId rootLayersId
= mCompositorSession
->RootLayerTreeId();
1107 RefPtr
<DisplayportSetListener
> postLayerization
;
1108 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1109 nsTArray
<TouchBehaviorFlags
> allowedTouchBehaviors
;
1110 if (touchEvent
->mMessage
== eTouchStart
) {
1111 auto& originalEvent
= *original
->AsTouchEvent();
1112 MOZ_ASSERT(NS_IsMainThread());
1113 allowedTouchBehaviors
= TouchActionHelper::GetAllowedTouchBehavior(
1114 this, GetDocument(), originalEvent
);
1115 if (!allowedTouchBehaviors
.IsEmpty()) {
1116 mAPZC
->SetAllowedTouchBehavior(inputBlockId
, allowedTouchBehaviors
);
1118 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1119 this, GetDocument(), originalEvent
, rootLayersId
, inputBlockId
);
1121 mAPZEventState
->ProcessTouchEvent(*touchEvent
, targetGuid
, inputBlockId
,
1122 aApzResult
.GetStatus(), status
,
1123 std::move(allowedTouchBehaviors
));
1124 } else if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1125 MOZ_ASSERT(wheelEvent
->mFlags
.mHandledByAPZ
);
1126 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1127 this, GetDocument(), *original
->AsWheelEvent(), rootLayersId
,
1129 if (wheelEvent
->mCanTriggerSwipe
) {
1130 ReportSwipeStarted(inputBlockId
, wheelEvent
->TriggersSwipe());
1132 mAPZEventState
->ProcessWheelEvent(*wheelEvent
, inputBlockId
);
1133 } else if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1134 MOZ_ASSERT(mouseEvent
->mFlags
.mHandledByAPZ
);
1135 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1136 this, GetDocument(), *original
->AsMouseEvent(), rootLayersId
,
1138 mAPZEventState
->ProcessMouseEvent(*mouseEvent
, inputBlockId
);
1140 if (postLayerization
) {
1141 postLayerization
->Register();
1148 template <class InputType
, class EventType
>
1149 class DispatchEventOnMainThread
: public Runnable
{
1151 DispatchEventOnMainThread(const InputType
& aInput
, nsBaseWidget
* aWidget
,
1152 const APZEventResult
& aAPZResult
)
1153 : mozilla::Runnable("DispatchEventOnMainThread"),
1156 mAPZResult(aAPZResult
) {}
1158 NS_IMETHOD
Run() override
{
1159 EventType event
= mInput
.ToWidgetEvent(mWidget
);
1160 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1166 nsBaseWidget
* mWidget
;
1167 APZEventResult mAPZResult
;
1170 template <class InputType
, class EventType
>
1171 class DispatchInputOnControllerThread
: public Runnable
{
1173 DispatchInputOnControllerThread(const EventType
& aEvent
,
1174 IAPZCTreeManager
* aAPZC
,
1175 nsBaseWidget
* aWidget
)
1176 : mozilla::Runnable("DispatchInputOnControllerThread"),
1177 mMainMessageLoop(MessageLoop::current()),
1182 NS_IMETHOD
Run() override
{
1183 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(mInput
);
1184 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1187 RefPtr
<Runnable
> r
= new DispatchEventOnMainThread
<InputType
, EventType
>(
1188 mInput
, mWidget
, result
);
1189 mMainMessageLoop
->PostTask(r
.forget());
1194 MessageLoop
* mMainMessageLoop
;
1196 RefPtr
<IAPZCTreeManager
> mAPZC
;
1197 nsBaseWidget
* mWidget
;
1200 void nsBaseWidget::DispatchTouchInput(MultiTouchInput
& aInput
,
1201 uint16_t aInputSource
) {
1202 MOZ_ASSERT(NS_IsMainThread());
1203 MOZ_ASSERT(aInputSource
==
1204 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH
||
1205 aInputSource
== mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN
);
1207 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1209 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1210 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1214 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1215 ProcessUntransformedAPZEvent(&event
, result
);
1217 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1219 nsEventStatus status
;
1220 DispatchEvent(&event
, status
);
1224 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput
& aInput
) {
1225 MOZ_ASSERT(NS_IsMainThread());
1227 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1229 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1230 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1234 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1235 ProcessUntransformedAPZEvent(&event
, result
);
1237 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1238 nsEventStatus status
;
1239 DispatchEvent(&event
, status
);
1243 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput
& aInput
) {
1244 MOZ_ASSERT(NS_IsMainThread());
1246 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1247 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1249 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1252 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1253 ProcessUntransformedAPZEvent(&event
, result
);
1255 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1256 nsEventStatus status
;
1257 DispatchEvent(&event
, status
);
1261 nsIWidget::ContentAndAPZEventStatus
nsBaseWidget::DispatchInputEvent(
1262 WidgetInputEvent
* aEvent
) {
1263 nsIWidget::ContentAndAPZEventStatus status
;
1264 MOZ_ASSERT(NS_IsMainThread());
1266 if (APZThreadUtils::IsControllerThread()) {
1267 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1268 status
.mApzStatus
= result
.GetStatus();
1269 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1272 status
.mContentStatus
= ProcessUntransformedAPZEvent(aEvent
, result
);
1275 if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1276 RefPtr
<Runnable
> r
=
1277 new DispatchInputOnControllerThread
<ScrollWheelInput
,
1278 WidgetWheelEvent
>(*wheelEvent
,
1280 APZThreadUtils::RunOnControllerThread(std::move(r
));
1281 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1284 if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1285 RefPtr
<Runnable
> r
=
1286 new DispatchInputOnControllerThread
<MouseInput
, WidgetMouseEvent
>(
1287 *mouseEvent
, mAPZC
, this);
1288 APZThreadUtils::RunOnControllerThread(std::move(r
));
1289 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1292 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1293 RefPtr
<Runnable
> r
=
1294 new DispatchInputOnControllerThread
<MultiTouchInput
,
1295 WidgetTouchEvent
>(*touchEvent
,
1297 APZThreadUtils::RunOnControllerThread(std::move(r
));
1298 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1301 // Allow dispatching keyboard events on Gecko thread.
1302 MOZ_ASSERT(aEvent
->AsKeyboardEvent());
1305 DispatchEvent(aEvent
, status
.mContentStatus
);
1309 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent
* aEvent
) {
1310 MOZ_ASSERT(NS_IsMainThread());
1312 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1313 mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1317 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent
& event
) {
1318 nsEventStatus status
;
1319 DispatchEvent(&event
, status
);
1320 return ConvertStatus(status
);
1323 Document
* nsBaseWidget::GetDocument() const {
1324 if (mWidgetListener
) {
1325 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1326 return presShell
->GetDocument();
1332 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1333 // Parent directly listens to the vsync source whereas
1334 // child process communicate via IPC
1335 // Should be called AFTER gfxPlatform is initialized
1336 if (XRE_IsParentProcess()) {
1337 if (!mCompositorVsyncDispatcherLock
) {
1338 mCompositorVsyncDispatcherLock
=
1339 MakeUnique
<Mutex
>("mCompositorVsyncDispatcherLock");
1341 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1342 if (!mCompositorVsyncDispatcher
) {
1343 RefPtr
<VsyncDispatcher
> vsyncDispatcher
=
1344 gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
1345 mCompositorVsyncDispatcher
=
1346 new CompositorVsyncDispatcher(std::move(vsyncDispatcher
));
1351 already_AddRefed
<CompositorVsyncDispatcher
>
1352 nsBaseWidget::GetCompositorVsyncDispatcher() {
1353 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
1355 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1356 RefPtr
<CompositorVsyncDispatcher
> dispatcher
= mCompositorVsyncDispatcher
;
1357 return dispatcher
.forget();
1360 already_AddRefed
<WebRenderLayerManager
> nsBaseWidget::CreateCompositorSession(
1361 int aWidth
, int aHeight
, CompositorOptions
* aOptionsOut
) {
1362 MOZ_ASSERT(aOptionsOut
);
1365 CreateCompositorVsyncDispatcher();
1367 gfx::GPUProcessManager
* gpu
= gfx::GPUProcessManager::Get();
1368 // Make sure GPU process is ready for use.
1369 // If it failed to connect to GPU process, GPU process usage is disabled in
1370 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1371 nsresult rv
= gpu
->EnsureGPUReady();
1372 if (NS_WARN_IF(rv
== NS_ERROR_ILLEGAL_DURING_SHUTDOWN
)) {
1376 // If widget type does not supports acceleration, we may be allowed to use
1377 // software WebRender instead.
1378 bool supportsAcceleration
= WidgetTypeSupportsAcceleration();
1379 bool enableSWWR
= true;
1380 if (supportsAcceleration
||
1381 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1382 enableSWWR
= gfx::gfxVars::UseSoftwareWebRender();
1384 bool enableAPZ
= UseAPZ();
1385 CompositorOptions
options(enableAPZ
, enableSWWR
);
1388 if (supportsAcceleration
) {
1389 options
.SetAllowSoftwareWebRenderD3D11(
1390 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1392 if (mNeedFastSnaphot
) {
1393 options
.SetNeedFastSnaphot(true);
1395 #elif defined(MOZ_WIDGET_ANDROID)
1396 MOZ_ASSERT(supportsAcceleration
);
1397 options
.SetAllowSoftwareWebRenderOGL(
1398 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1399 #elif defined(MOZ_WIDGET_GTK)
1400 if (supportsAcceleration
) {
1401 options
.SetAllowSoftwareWebRenderOGL(
1402 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1406 #ifdef MOZ_WIDGET_ANDROID
1407 // Unconditionally set the compositor as initially paused, as we have not
1408 // yet had a chance to send the compositor surface to the GPU process. We
1409 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1410 // where we will also resume the compositor if required.
1411 options
.SetInitiallyPaused(true);
1413 options
.SetInitiallyPaused(CompositorInitiallyPaused());
1416 RefPtr
<WebRenderLayerManager
> lm
= new WebRenderLayerManager(this);
1418 uint64_t innerWindowId
= 0;
1419 if (Document
* doc
= GetDocument()) {
1420 innerWindowId
= doc
->InnerWindowID();
1424 mCompositorSession
= gpu
->CreateTopLevelCompositor(
1425 this, lm
, GetDefaultScale(), options
, UseExternalCompositingSurface(),
1426 gfx::IntSize(aWidth
, aHeight
), innerWindowId
, &retry
);
1428 if (mCompositorSession
) {
1429 TextureFactoryIdentifier textureFactoryIdentifier
;
1431 lm
->Initialize(mCompositorSession
->GetCompositorBridgeChild(),
1432 wr::AsPipelineId(mCompositorSession
->RootLayerTreeId()),
1433 &textureFactoryIdentifier
, error
);
1434 if (textureFactoryIdentifier
.mParentBackend
!= LayersBackend::LAYERS_WR
) {
1436 DestroyCompositor();
1437 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1438 gfx::GPUProcessManager::Get()->DisableWebRender(
1439 wr::WebRenderError::INITIALIZE
, error
);
1443 // We need to retry in a loop because the act of failing to create the
1444 // compositor can change our state (e.g. disable WebRender).
1445 if (mCompositorSession
|| !retry
) {
1446 *aOptionsOut
= options
;
1452 void nsBaseWidget::CreateCompositor(int aWidth
, int aHeight
) {
1453 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1454 gfxPlatform::GetPlatform();
1456 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1457 "This function assumes OMTC");
1459 MOZ_ASSERT(!mCompositorSession
&& !mCompositorBridgeChild
,
1460 "Should have properly cleaned up the previous PCompositor pair "
1463 if (mCompositorBridgeChild
) {
1464 mCompositorBridgeChild
->Destroy();
1467 // Recreating this is tricky, as we may still have an old and we need
1468 // to make sure it's properly destroyed by calling DestroyCompositor!
1470 // If we've already received a shutdown notification, don't try
1471 // create a new compositor.
1472 if (!mShutdownObserver
) {
1476 // The controller thread must be configured before the compositor
1477 // session is created, so that the input bridge runs on the right
1479 ConfigureAPZControllerThread();
1481 CompositorOptions options
;
1482 RefPtr
<WebRenderLayerManager
> lm
=
1483 CreateCompositorSession(aWidth
, aHeight
, &options
);
1488 MOZ_ASSERT(mCompositorSession
);
1489 mCompositorBridgeChild
= mCompositorSession
->GetCompositorBridgeChild();
1490 SetCompositorWidgetDelegate(
1491 mCompositorSession
->GetCompositorWidgetDelegate());
1493 if (options
.UseAPZ()) {
1494 mAPZC
= mCompositorSession
->GetAPZCTreeManager();
1495 ConfigureAPZCTreeManager();
1500 if (mInitialZoomConstraints
) {
1501 UpdateZoomConstraints(mInitialZoomConstraints
->mPresShellID
,
1502 mInitialZoomConstraints
->mViewID
,
1503 Some(mInitialZoomConstraints
->mConstraints
));
1504 mInitialZoomConstraints
.reset();
1507 TextureFactoryIdentifier textureFactoryIdentifier
=
1508 lm
->GetTextureFactoryIdentifier();
1509 MOZ_ASSERT(textureFactoryIdentifier
.mParentBackend
==
1510 LayersBackend::LAYERS_WR
);
1511 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier
);
1512 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier
);
1516 mWindowRenderer
= std::move(lm
);
1518 // Only track compositors for top-level windows, since other window types
1519 // may use the basic compositor. Except on the OS X - see bug 1306383
1520 #if defined(XP_MACOSX)
1521 bool getCompositorFromThisWindow
= true;
1523 bool getCompositorFromThisWindow
= mWindowType
== WindowType::TopLevel
;
1526 if (getCompositorFromThisWindow
) {
1527 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1528 mWindowRenderer
->GetCompositorBackendType());
1532 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession
* aSession
) {
1533 MOZ_ASSERT(aSession
== mCompositorSession
);
1534 DestroyLayerManager();
1537 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1538 return gfxPlatform::UsesOffMainThreadCompositing();
1541 WindowRenderer
* nsBaseWidget::GetWindowRenderer() {
1542 if (!mWindowRenderer
) {
1543 if (!mShutdownObserver
) {
1544 // We are shutting down, do not try to re-create a LayerManager
1547 // Try to use an async compositor first, if possible
1548 if (ShouldUseOffMainThreadCompositing()) {
1552 if (!mWindowRenderer
) {
1553 mWindowRenderer
= CreateFallbackRenderer();
1556 return mWindowRenderer
;
1559 WindowRenderer
* nsBaseWidget::CreateFallbackRenderer() {
1560 return new FallbackRenderer
;
1563 CompositorBridgeChild
* nsBaseWidget::GetRemoteRenderer() {
1564 return mCompositorBridgeChild
;
1567 void nsBaseWidget::ClearCachedWebrenderResources() {
1568 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1571 mWindowRenderer
->AsWebRender()->ClearCachedResources();
1574 void nsBaseWidget::ClearWebrenderAnimationResources() {
1575 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1578 mWindowRenderer
->AsWebRender()->ClearAnimationResources();
1581 bool nsBaseWidget::SetNeedFastSnaphot() {
1582 MOZ_ASSERT(XRE_IsParentProcess());
1583 MOZ_ASSERT(!mCompositorSession
);
1585 if (!XRE_IsParentProcess() || mCompositorSession
) {
1589 mNeedFastSnaphot
= true;
1593 already_AddRefed
<gfx::DrawTarget
> nsBaseWidget::StartRemoteDrawing() {
1597 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA
; }
1599 //-------------------------------------------------------------------------
1601 // Destroy the window
1603 //-------------------------------------------------------------------------
1604 void nsBaseWidget::OnDestroy() {
1605 if (mTextEventDispatcher
) {
1606 mTextEventDispatcher
->OnDestroyWidget();
1607 // Don't release it until this widget actually released because after this
1608 // is called, TextEventDispatcher() may create it again.
1611 // If this widget is being destroyed, let the APZ code know to drop references
1612 // to this widget. Callers of this function all should be holding a deathgrip
1613 // on this widget already.
1614 ReleaseContentController();
1617 void nsBaseWidget::MoveClient(const DesktopPoint
& aOffset
) {
1618 LayoutDeviceIntPoint
clientOffset(GetClientOffset());
1620 // GetClientOffset returns device pixels; scale back to desktop pixels
1621 // if that's what this widget uses for the Move/Resize APIs
1622 if (BoundsUseDesktopPixels()) {
1623 DesktopPoint desktopOffset
= clientOffset
/ GetDesktopToDeviceScale();
1624 Move(aOffset
.x
- desktopOffset
.x
, aOffset
.y
- desktopOffset
.y
);
1626 LayoutDevicePoint layoutOffset
= aOffset
* GetDesktopToDeviceScale();
1627 Move(layoutOffset
.x
- LayoutDeviceCoord(clientOffset
.x
),
1628 layoutOffset
.y
- LayoutDeviceCoord(clientOffset
.y
));
1632 void nsBaseWidget::ResizeClient(const DesktopSize
& aSize
, bool aRepaint
) {
1633 NS_ASSERTION((aSize
.width
>= 0), "Negative width passed to ResizeClient");
1634 NS_ASSERTION((aSize
.height
>= 0), "Negative height passed to ResizeClient");
1636 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1638 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1639 // if that's what this widget uses for the Move/Resize APIs
1640 if (BoundsUseDesktopPixels()) {
1641 DesktopSize desktopDelta
=
1642 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1643 clientBounds
.Size()) /
1644 GetDesktopToDeviceScale();
1645 Resize(aSize
.width
+ desktopDelta
.width
, aSize
.height
+ desktopDelta
.height
,
1648 LayoutDeviceSize layoutSize
= aSize
* GetDesktopToDeviceScale();
1649 Resize(mBounds
.Width() + (layoutSize
.width
- clientBounds
.Width()),
1650 mBounds
.Height() + (layoutSize
.height
- clientBounds
.Height()),
1655 void nsBaseWidget::ResizeClient(const DesktopRect
& aRect
, bool aRepaint
) {
1656 NS_ASSERTION((aRect
.Width() >= 0), "Negative width passed to ResizeClient");
1657 NS_ASSERTION((aRect
.Height() >= 0), "Negative height passed to ResizeClient");
1659 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1660 LayoutDeviceIntPoint clientOffset
= GetClientOffset();
1661 DesktopToLayoutDeviceScale scale
= GetDesktopToDeviceScale();
1663 if (BoundsUseDesktopPixels()) {
1664 DesktopPoint desktopOffset
= clientOffset
/ scale
;
1665 DesktopSize desktopDelta
=
1666 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1667 clientBounds
.Size()) /
1669 Resize(aRect
.X() - desktopOffset
.x
, aRect
.Y() - desktopOffset
.y
,
1670 aRect
.Width() + desktopDelta
.width
,
1671 aRect
.Height() + desktopDelta
.height
, aRepaint
);
1673 LayoutDeviceRect layoutRect
= aRect
* scale
;
1674 Resize(layoutRect
.X() - clientOffset
.x
, layoutRect
.Y() - clientOffset
.y
,
1675 layoutRect
.Width() + mBounds
.Width() - clientBounds
.Width(),
1676 layoutRect
.Height() + mBounds
.Height() - clientBounds
.Height(),
1681 //-------------------------------------------------------------------------
1685 //-------------------------------------------------------------------------
1688 * If the implementation of nsWindow supports borders this method MUST be
1692 LayoutDeviceIntRect
nsBaseWidget::GetClientBounds() { return GetBounds(); }
1695 * If the implementation of nsWindow supports borders this method MUST be
1699 LayoutDeviceIntRect
nsBaseWidget::GetBounds() { return mBounds
; }
1702 * If the implementation of nsWindow uses a local coordinate system within the
1703 *window, this method must be overridden
1706 LayoutDeviceIntRect
nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1708 nsresult
nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect
& aRect
) {
1709 if (SizeMode() != nsSizeMode_Normal
) {
1710 return NS_ERROR_FAILURE
;
1712 aRect
= GetScreenBounds();
1716 LayoutDeviceIntPoint
nsBaseWidget::GetClientOffset() {
1717 return LayoutDeviceIntPoint(0, 0);
1720 nsresult
nsBaseWidget::SetNonClientMargins(const LayoutDeviceIntMargin
&) {
1721 return NS_ERROR_NOT_IMPLEMENTED
;
1724 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin
) {}
1726 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1728 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1730 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect
* aResizerRect
) {
1735 * Modifies aFile to point at an icon file with the given name and suffix. The
1736 * suffix may correspond to a file extension with leading '.' if appropriate.
1737 * Returns true if the icon file exists and can be read.
1739 static bool ResolveIconNameHelper(nsIFile
* aFile
, const nsAString
& aIconName
,
1740 const nsAString
& aIconSuffix
) {
1741 aFile
->Append(u
"icons"_ns
);
1742 aFile
->Append(u
"default"_ns
);
1743 aFile
->Append(aIconName
+ aIconSuffix
);
1746 return NS_SUCCEEDED(aFile
->IsReadable(&readable
)) && readable
;
1750 * Resolve the given icon name into a local file object. This method is
1751 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1752 * platform specific icon file suffix (e.g., ".ico" under Win32).
1754 * If no file is found matching the given parameters, then null is returned.
1756 void nsBaseWidget::ResolveIconName(const nsAString
& aIconName
,
1757 const nsAString
& aIconSuffix
,
1758 nsIFile
** aResult
) {
1761 nsCOMPtr
<nsIProperties
> dirSvc
=
1762 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID
);
1763 if (!dirSvc
) return;
1765 // first check auxilary chrome directories
1767 nsCOMPtr
<nsISimpleEnumerator
> dirs
;
1768 dirSvc
->Get(NS_APP_CHROME_DIR_LIST
, NS_GET_IID(nsISimpleEnumerator
),
1769 getter_AddRefs(dirs
));
1772 while (NS_SUCCEEDED(dirs
->HasMoreElements(&hasMore
)) && hasMore
) {
1773 nsCOMPtr
<nsISupports
> element
;
1774 dirs
->GetNext(getter_AddRefs(element
));
1775 if (!element
) continue;
1776 nsCOMPtr
<nsIFile
> file
= do_QueryInterface(element
);
1777 if (!file
) continue;
1778 if (ResolveIconNameHelper(file
, aIconName
, aIconSuffix
)) {
1779 NS_ADDREF(*aResult
= file
);
1785 // then check the main app chrome directory
1787 nsCOMPtr
<nsIFile
> file
;
1788 dirSvc
->Get(NS_APP_CHROME_DIR
, NS_GET_IID(nsIFile
), getter_AddRefs(file
));
1789 if (file
&& ResolveIconNameHelper(file
, aIconName
, aIconSuffix
))
1790 NS_ADDREF(*aResult
= file
);
1793 void nsBaseWidget::SetSizeConstraints(const SizeConstraints
& aConstraints
) {
1794 mSizeConstraints
= aConstraints
;
1796 // Popups are constrained during layout, and we don't want to synchronously
1797 // paint from reflow, so bail out... This is not great, but it's no worse than
1798 // what we used to do.
1800 // The right fix here is probably making constraint changes go through the
1801 // view manager and such.
1802 if (mWindowType
== WindowType::Popup
) {
1806 // If the current size doesn't meet the new constraints, trigger a
1807 // resize to apply it. Note that, we don't want to invoke Resize if
1808 // the new constraints don't affect the current size, because Resize
1809 // implementation on some platforms may touch other geometry even if
1810 // the size don't need to change.
1811 LayoutDeviceIntSize curSize
= mBounds
.Size();
1812 LayoutDeviceIntSize clampedSize
=
1813 Max(aConstraints
.mMinSize
, Min(aConstraints
.mMaxSize
, curSize
));
1814 if (clampedSize
!= curSize
) {
1816 if (BoundsUseDesktopPixels()) {
1817 DesktopSize desktopSize
= clampedSize
/ GetDesktopToDeviceScale();
1818 size
= desktopSize
.ToUnknownSize();
1820 size
= gfx::Size(clampedSize
.ToUnknownSize());
1822 Resize(size
.width
, size
.height
, true);
1826 const widget::SizeConstraints
nsBaseWidget::GetSizeConstraints() {
1827 return mSizeConstraints
;
1831 nsIRollupListener
* nsBaseWidget::GetActiveRollupListener() {
1832 // TODO: Simplify this.
1833 return nsXULPopupManager::GetInstance();
1836 void nsBaseWidget::NotifyWindowDestroyed() {
1837 if (!mWidgetListener
) return;
1839 nsCOMPtr
<nsIAppWindow
> window
= mWidgetListener
->GetAppWindow();
1840 nsCOMPtr
<nsIBaseWindow
> appWindow(do_QueryInterface(window
));
1842 appWindow
->Destroy();
1846 void nsBaseWidget::NotifyWindowMoved(int32_t aX
, int32_t aY
,
1847 ByMoveToRect aByMoveToRect
) {
1848 if (mWidgetListener
) {
1849 mWidgetListener
->WindowMoved(this, aX
, aY
, aByMoveToRect
);
1852 if (mIMEHasFocus
&& IMENotificationRequestsRef().WantPositionChanged()) {
1853 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE
));
1857 void nsBaseWidget::NotifySizeMoveDone() {
1858 if (!mWidgetListener
) {
1861 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1862 presShell
->WindowSizeMoveDone();
1866 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind
) {
1867 LookAndFeel::NotifyChangedAllWindows(aKind
);
1870 nsresult
nsBaseWidget::NotifyIME(const IMENotification
& aIMENotification
) {
1874 switch (aIMENotification
.mMessage
) {
1875 case REQUEST_TO_COMMIT_COMPOSITION
:
1876 case REQUEST_TO_CANCEL_COMPOSITION
:
1877 // We should send request to IME only when there is a TextEventDispatcher
1878 // instance (this means that this widget has dispatched at least one
1879 // composition event or keyboard event) and the it has composition.
1880 // Otherwise, there is nothing to do.
1881 // Note that if current input transaction is for native input events,
1882 // TextEventDispatcher::NotifyIME() will call
1883 // TextEventDispatcherListener::NotifyIME().
1884 if (mTextEventDispatcher
&& mTextEventDispatcher
->IsComposing()) {
1885 return mTextEventDispatcher
->NotifyIME(aIMENotification
);
1889 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_FOCUS
) {
1890 mIMEHasFocus
= true;
1892 EnsureTextEventDispatcher();
1893 // TextEventDispatcher::NotifyIME() will always call
1894 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1895 // input transaction is for synthesized events for automated tests,
1896 // notifications will be sent to native IME.
1897 nsresult rv
= mTextEventDispatcher
->NotifyIME(aIMENotification
);
1898 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_BLUR
) {
1899 mIMEHasFocus
= false;
1906 void nsBaseWidget::EnsureTextEventDispatcher() {
1907 if (mTextEventDispatcher
) {
1910 mTextEventDispatcher
= new TextEventDispatcher(this);
1913 nsIWidget::NativeIMEContext
nsBaseWidget::GetNativeIMEContext() {
1914 if (mTextEventDispatcher
&& mTextEventDispatcher
->GetPseudoIMEContext()) {
1915 // If we already have a TextEventDispatcher and it's working with
1916 // a TextInputProcessor, we need to return pseudo IME context since
1917 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1918 // on the pseudo IME context in such case.
1919 NativeIMEContext pseudoIMEContext
;
1920 pseudoIMEContext
.InitWithRawNativeIMEContext(
1921 mTextEventDispatcher
->GetPseudoIMEContext());
1922 return pseudoIMEContext
;
1924 return NativeIMEContext(this);
1927 nsIWidget::TextEventDispatcher
* nsBaseWidget::GetTextEventDispatcher() {
1928 EnsureTextEventDispatcher();
1929 return mTextEventDispatcher
;
1932 void* nsBaseWidget::GetPseudoIMEContext() {
1933 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
1937 return dispatcher
->GetPseudoIMEContext();
1940 TextEventDispatcherListener
*
1941 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1942 // TODO: If all platforms supported use of TextEventDispatcher for handling
1943 // native IME and keyboard events, this method should be removed since
1944 // in such case, this is overridden by all the subclasses.
1948 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId
,
1949 const ScrollableLayerGuid::ViewID
& aViewId
,
1950 const CSSRect
& aRect
, const uint32_t& aFlags
) {
1951 if (!mCompositorSession
|| !mAPZC
) {
1954 LayersId layerId
= mCompositorSession
->RootLayerTreeId();
1955 mAPZC
->ZoomToRect(ScrollableLayerGuid(layerId
, aPresShellId
, aViewId
),
1956 ZoomTarget
{aRect
}, aFlags
);
1959 #ifdef ACCESSIBILITY
1961 a11y::LocalAccessible
* nsBaseWidget::GetRootAccessible() {
1962 NS_ENSURE_TRUE(mWidgetListener
, nullptr);
1964 PresShell
* presShell
= mWidgetListener
->GetPresShell();
1965 NS_ENSURE_TRUE(presShell
, nullptr);
1967 // If container is null then the presshell is not active. This often happens
1968 // when a preshell is being held onto for fastback.
1969 nsPresContext
* presContext
= presShell
->GetPresContext();
1970 NS_ENSURE_TRUE(presContext
->GetContainerWeak(), nullptr);
1972 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1973 // make sure it's not created at unsafe times.
1974 nsAccessibilityService
* accService
= GetOrCreateAccService();
1976 return accService
->GetRootDocumentAccessible(
1977 presShell
, nsContentUtils::IsSafeToRunScript());
1983 #endif // ACCESSIBILITY
1985 void nsBaseWidget::StartAsyncScrollbarDrag(
1986 const AsyncDragMetrics
& aDragMetrics
) {
1987 if (!AsyncPanZoomEnabled()) {
1991 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession
);
1993 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1994 ScrollableLayerGuid
guid(layersId
, aDragMetrics
.mPresShellId
,
1995 aDragMetrics
.mViewId
);
1997 mAPZC
->StartScrollbarDrag(guid
, aDragMetrics
);
2000 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint
& aAnchorLocation
,
2001 const ScrollableLayerGuid
& aGuid
) {
2002 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2004 return mAPZC
->StartAutoscroll(aGuid
, aAnchorLocation
);
2007 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid
& aGuid
) {
2008 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2010 mAPZC
->StopAutoscroll(aGuid
);
2013 LayersId
nsBaseWidget::GetRootLayerTreeId() {
2014 return mCompositorSession
? mCompositorSession
->RootLayerTreeId()
2018 already_AddRefed
<widget::Screen
> nsBaseWidget::GetWidgetScreen() {
2019 ScreenManager
& screenManager
= ScreenManager::GetSingleton();
2020 LayoutDeviceIntRect bounds
= GetScreenBounds();
2021 DesktopIntRect deskBounds
= RoundedToInt(bounds
/ GetDesktopToDeviceScale());
2022 return screenManager
.ScreenForRect(deskBounds
);
2025 mozilla::DesktopToLayoutDeviceScale
2026 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
2027 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
2028 ->GetDesktopToDeviceScale();
2031 nsresult
nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint
,
2033 nsIObserver
* aObserver
) {
2034 AutoObserverNotifier
notifier(aObserver
, "touchtap");
2036 if (sPointerIdCounter
> TOUCH_INJECT_MAX_POINTS
) {
2037 sPointerIdCounter
= 0;
2039 int pointerId
= sPointerIdCounter
;
2040 sPointerIdCounter
++;
2041 nsresult rv
= SynthesizeNativeTouchPoint(pointerId
, TOUCH_CONTACT
, aPoint
,
2043 if (NS_FAILED(rv
)) {
2048 return SynthesizeNativeTouchPoint(pointerId
, TOUCH_REMOVE
, aPoint
, 0, 0,
2052 // initiate a long tap
2053 int elapse
= Preferences::GetInt("ui.click_hold_context_menus.delay",
2054 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC
);
2055 if (!mLongTapTimer
) {
2056 mLongTapTimer
= NS_NewTimer();
2057 if (!mLongTapTimer
) {
2058 SynthesizeNativeTouchPoint(pointerId
, TOUCH_CANCEL
, aPoint
, 0, 0,
2060 return NS_ERROR_UNEXPECTED
;
2062 // Windows requires recuring events, so we set this to a smaller window
2063 // than the pref value.
2064 int timeout
= elapse
;
2065 if (timeout
> TOUCH_INJECT_PUMP_TIMER_MSEC
) {
2066 timeout
= TOUCH_INJECT_PUMP_TIMER_MSEC
;
2068 mLongTapTimer
->InitWithNamedFuncCallback(
2069 OnLongTapTimerCallback
, this, timeout
, nsITimer::TYPE_REPEATING_SLACK
,
2070 "nsIWidget::SynthesizeNativeTouchTap");
2073 // If we already have a long tap pending, cancel it. We only allow one long
2074 // tap to be active at a time.
2075 if (mLongTapTouchPoint
) {
2076 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2077 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2080 mLongTapTouchPoint
= MakeUnique
<LongTapInfo
>(
2081 pointerId
, aPoint
, TimeDuration::FromMilliseconds(elapse
), aObserver
);
2082 notifier
.SkipNotification(); // we'll do it in the long-tap callback
2087 void nsIWidget::OnLongTapTimerCallback(nsITimer
* aTimer
, void* aClosure
) {
2088 auto* self
= static_cast<nsIWidget
*>(aClosure
);
2090 if ((self
->mLongTapTouchPoint
->mStamp
+ self
->mLongTapTouchPoint
->mDuration
) >
2093 // Windows needs us to keep pumping feedback to the digitizer, so update
2094 // the pointer id with the same position.
2095 self
->SynthesizeNativeTouchPoint(
2096 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_CONTACT
,
2097 self
->mLongTapTouchPoint
->mPosition
, 1.0, 90, nullptr);
2102 AutoObserverNotifier
notifier(self
->mLongTapTouchPoint
->mObserver
,
2105 // finished, remove the touch point
2106 self
->mLongTapTimer
->Cancel();
2107 self
->mLongTapTimer
= nullptr;
2108 self
->SynthesizeNativeTouchPoint(
2109 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_REMOVE
,
2110 self
->mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2111 self
->mLongTapTouchPoint
= nullptr;
2114 float nsIWidget::GetFallbackDPI() {
2115 RefPtr
<const Screen
> primaryScreen
=
2116 ScreenManager::GetSingleton().GetPrimaryScreen();
2117 return primaryScreen
->GetDPI();
2120 CSSToLayoutDeviceScale
nsIWidget::GetFallbackDefaultScale() {
2121 RefPtr
<const Screen
> s
= ScreenManager::GetSingleton().GetPrimaryScreen();
2122 return s
->GetCSSToLayoutDeviceScale(Screen::IncludeOSZoom::No
);
2125 nsresult
nsIWidget::ClearNativeTouchSequence(nsIObserver
* aObserver
) {
2126 AutoObserverNotifier
notifier(aObserver
, "cleartouch");
2128 // XXX This is odd. This is called by the constructor of nsIWidget. However,
2129 // at that point, nsIWidget::mLongTapTimer must be nullptr. Therefore,
2130 // this must do nothing at initializing the instance.
2131 if (!mLongTapTimer
) {
2134 mLongTapTimer
->Cancel();
2135 mLongTapTimer
= nullptr;
2136 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2137 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2138 mLongTapTouchPoint
= nullptr;
2142 MultiTouchInput
nsBaseWidget::UpdateSynthesizedTouchState(
2143 MultiTouchInput
* aState
, mozilla::TimeStamp aTimeStamp
, uint32_t aPointerId
,
2144 TouchPointerState aPointerState
, LayoutDeviceIntPoint aPoint
,
2145 double aPointerPressure
, uint32_t aPointerOrientation
) {
2146 ScreenIntPoint pointerScreenPoint
= ViewAs
<ScreenPixel
>(
2147 aPoint
, PixelCastJustification::LayoutDeviceIsScreenForBounds
);
2149 // We can't dispatch *aState directly because (a) dispatching
2150 // it might inadvertently modify it and (b) in the case of touchend or
2151 // touchcancel events aState will hold the touches that are
2152 // still down whereas the input dispatched needs to hold the removed
2153 // touch(es). We use |inputToDispatch| for this purpose.
2154 MultiTouchInput inputToDispatch
;
2155 inputToDispatch
.mInputType
= MULTITOUCH_INPUT
;
2156 inputToDispatch
.mTimeStamp
= aTimeStamp
;
2158 int32_t index
= aState
->IndexOfTouch((int32_t)aPointerId
);
2159 if (aPointerState
== TOUCH_CONTACT
) {
2161 // found an existing touch point, update it
2162 SingleTouchData
& point
= aState
->mTouches
[index
];
2163 point
.mScreenPoint
= pointerScreenPoint
;
2164 point
.mRotationAngle
= (float)aPointerOrientation
;
2165 point
.mForce
= (float)aPointerPressure
;
2166 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_MOVE
;
2168 // new touch point, add it
2169 aState
->mTouches
.AppendElement(SingleTouchData(
2170 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2171 (float)aPointerOrientation
, (float)aPointerPressure
));
2172 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_START
;
2174 inputToDispatch
.mTouches
= aState
->mTouches
;
2176 MOZ_ASSERT(aPointerState
== TOUCH_REMOVE
|| aPointerState
== TOUCH_CANCEL
);
2177 // a touch point is being lifted, so remove it from the stored list
2179 aState
->mTouches
.RemoveElementAt(index
);
2181 inputToDispatch
.mType
=
2182 (aPointerState
== TOUCH_REMOVE
? MultiTouchInput::MULTITOUCH_END
2183 : MultiTouchInput::MULTITOUCH_CANCEL
);
2184 inputToDispatch
.mTouches
.AppendElement(SingleTouchData(
2185 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2186 (float)aPointerOrientation
, (float)aPointerPressure
));
2189 return inputToDispatch
;
2192 void nsBaseWidget::NotifyLiveResizeStarted() {
2193 // If we have mLiveResizeListeners already non-empty, we should notify those
2194 // listeners that the resize stopped before starting anew. In theory this
2195 // should never happen because we shouldn't get nested live resize actions.
2196 NotifyLiveResizeStopped();
2197 MOZ_ASSERT(mLiveResizeListeners
.IsEmpty());
2199 // If we can get the active remote tab for the current widget, suppress
2200 // the displayport on it during the live resize.
2201 if (!mWidgetListener
) {
2204 nsCOMPtr
<nsIAppWindow
> appWindow
= mWidgetListener
->GetAppWindow();
2208 mLiveResizeListeners
= appWindow
->GetLiveResizeListeners();
2209 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2210 mLiveResizeListeners
[i
]->LiveResizeStarted();
2214 void nsBaseWidget::NotifyLiveResizeStopped() {
2215 if (!mLiveResizeListeners
.IsEmpty()) {
2216 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2217 mLiveResizeListeners
[i
]->LiveResizeStopped();
2219 mLiveResizeListeners
.Clear();
2223 nsresult
nsBaseWidget::AsyncEnableDragDrop(bool aEnable
) {
2224 RefPtr
<nsBaseWidget
> kungFuDeathGrip
= this;
2225 return NS_DispatchToCurrentThreadQueue(
2226 NS_NewRunnableFunction(
2227 "AsyncEnableDragDropFn",
2228 [this, aEnable
, kungFuDeathGrip
]() { EnableDragDrop(aEnable
); }),
2229 kAsyncDragDropTimeout
, EventQueuePriority::Idle
);
2232 void nsBaseWidget::SwipeFinished() {
2233 mSwipeTracker
->Destroy();
2234 mSwipeTracker
= nullptr;
2237 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId
,
2239 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== aInputBlockId
) {
2241 PanGestureInput
& startEvent
= mSwipeEventQueue
->queuedEvents
[0];
2242 TrackScrollEventAsSwipe(startEvent
, mSwipeEventQueue
->allowedDirections
,
2244 for (size_t i
= 1; i
< mSwipeEventQueue
->queuedEvents
.Length(); i
++) {
2245 mSwipeTracker
->ProcessEvent(mSwipeEventQueue
->queuedEvents
[i
]);
2248 // If the event wasn't start swipe, we need to notify it to APZ.
2249 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2250 BrowserGestureResponse::NotConsumed
);
2252 mSwipeEventQueue
= nullptr;
2256 void nsBaseWidget::TrackScrollEventAsSwipe(
2257 const mozilla::PanGestureInput
& aSwipeStartEvent
,
2258 uint32_t aAllowedDirections
, uint64_t aInputBlockId
) {
2259 // If a swipe is currently being tracked kill it -- it's been interrupted
2260 // by another gesture event.
2261 if (mSwipeTracker
) {
2262 mSwipeTracker
->CancelSwipe(aSwipeStartEvent
.mTimeStamp
);
2263 mSwipeTracker
->Destroy();
2264 mSwipeTracker
= nullptr;
2267 uint32_t direction
=
2268 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2269 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2270 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2273 new SwipeTracker(*this, aSwipeStartEvent
, aAllowedDirections
, direction
);
2276 mCurrentPanGestureBelongsToSwipe
= true;
2278 // Now SwipeTracker has started consuming pan events, notify it to APZ so
2279 // that APZ can discard queued events.
2280 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2281 BrowserGestureResponse::Consumed
);
2285 nsBaseWidget::SwipeInfo
nsBaseWidget::SendMayStartSwipe(
2286 const mozilla::PanGestureInput
& aSwipeStartEvent
) {
2287 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
2289 uint32_t direction
=
2290 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2291 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2292 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2294 // We're ready to start the animation. Tell Gecko about it, and at the same
2295 // time ask it if it really wants to start an animation for this event.
2296 // This event also reports back the directions that we can swipe in.
2297 LayoutDeviceIntPoint position
= RoundedToInt(aSwipeStartEvent
.mPanStartPoint
*
2298 ScreenToLayoutDeviceScale(1));
2299 WidgetSimpleGestureEvent geckoEvent
= SwipeTracker::CreateSwipeGestureEvent(
2300 eSwipeGestureMayStart
, this, position
, aSwipeStartEvent
.mTimeStamp
);
2301 geckoEvent
.mDirection
= direction
;
2302 geckoEvent
.mDelta
= 0.0;
2303 geckoEvent
.mAllowedDirections
= 0;
2304 bool shouldStartSwipe
=
2305 DispatchWindowEvent(geckoEvent
); // event cancelled == swipe should start
2307 SwipeInfo result
= {shouldStartSwipe
, geckoEvent
.mAllowedDirections
};
2311 WidgetWheelEvent
nsBaseWidget::MayStartSwipeForAPZ(
2312 const PanGestureInput
& aPanInput
, const APZEventResult
& aApzResult
) {
2313 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2314 if (aPanInput
.AllowsSwipe()) {
2315 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2316 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2317 if (swipeInfo
.wantsSwipe
) {
2318 if (aApzResult
.GetStatus() == nsEventStatus_eIgnore
) {
2319 // APZ has determined and that scrolling horizontally in the
2320 // requested direction is impossible, so it didn't do any
2321 // scrolling for the event.
2322 // We know now that MayStartSwipe wants a swipe, so we can start
2324 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
,
2325 aApzResult
.mInputBlockId
);
2326 } else if (!aApzResult
.GetHandledResult() ||
2327 !aApzResult
.GetHandledResult()->IsHandledByRoot()) {
2328 // We don't know whether this event can start a swipe, so we need
2329 // to queue up events and wait for a call to ReportSwipeStarted.
2330 // APZ might already have started scrolling in response to the
2331 // event if it knew that it's the right thing to do. In that case
2332 // we'll still get a call to ReportSwipeStarted, and we will
2333 // discard the queued events at that point.
2334 mSwipeEventQueue
= MakeUnique
<SwipeEventQueue
>(
2335 swipeInfo
.allowedDirections
, aApzResult
.mInputBlockId
);
2338 // Inform that the browser gesture didn't use the pan event (pan-start
2339 // precisely), so that APZ can now start using the event for
2340 // scrolling/overscrolling.
2341 mAPZC
->SetBrowserGestureResponse(aApzResult
.mInputBlockId
,
2342 BrowserGestureResponse::NotConsumed
);
2346 if (mSwipeEventQueue
&&
2347 mSwipeEventQueue
->inputBlockId
== aApzResult
.mInputBlockId
) {
2348 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2354 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput
& aPanInput
) {
2355 if (aPanInput
.mType
== PanGestureInput::PANGESTURE_MAYSTART
||
2356 aPanInput
.mType
== PanGestureInput::PANGESTURE_START
) {
2357 mCurrentPanGestureBelongsToSwipe
= false;
2359 if (mCurrentPanGestureBelongsToSwipe
) {
2360 // Ignore this event. It's a momentum event from a scroll gesture
2361 // that was processed as a swipe, and the swipe animation has
2362 // already finished (so mSwipeTracker is already null).
2363 MOZ_ASSERT(aPanInput
.IsMomentum(),
2364 "If the fingers are still on the touchpad, we should still have "
2366 "and it should have consumed this event.");
2370 if (!aPanInput
.MayTriggerSwipe()) {
2374 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2376 // We're in the non-APZ case here, but we still want to know whether
2377 // the event was routed to a child process, so we use InputAPZContext
2378 // to get that piece of information.
2379 ScrollableLayerGuid guid
;
2380 uint64_t blockId
= 0;
2381 InputAPZContext
context(guid
, blockId
, nsEventStatus_eIgnore
);
2383 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2384 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2385 nsEventStatus status
;
2386 DispatchEvent(&event
, status
);
2387 if (swipeInfo
.wantsSwipe
) {
2388 if (context
.WasRoutedToChildProcess()) {
2389 // We don't know whether this event can start a swipe, so we need
2390 // to queue up events and wait for a call to ReportSwipeStarted.
2392 MakeUnique
<SwipeEventQueue
>(swipeInfo
.allowedDirections
, blockId
);
2393 } else if (event
.TriggersSwipe()) {
2394 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
, blockId
);
2398 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== 0) {
2399 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2405 const IMENotificationRequests
& nsIWidget::IMENotificationRequestsRef() {
2406 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
2407 return dispatcher
->IMENotificationRequestsRef();
2410 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent
* aEvent
) {}
2412 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType
,
2413 const WidgetKeyboardEvent
& aEvent
,
2414 nsTArray
<CommandInt
>& aCommands
) {
2415 MOZ_ASSERT(aEvent
.IsTrusted());
2416 MOZ_ASSERT(aCommands
.IsEmpty());
2420 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboard() {
2421 if (XRE_IsContentProcess()) {
2422 return CreateBidiKeyboardContentProcess();
2424 return CreateBidiKeyboardInner();
2428 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboardInner() {
2429 // no bidi keyboard implementation
2434 namespace mozilla::widget
{
2436 const char* ToChar(InputContext::Origin aOrigin
) {
2438 case InputContext::ORIGIN_MAIN
:
2439 return "ORIGIN_MAIN";
2440 case InputContext::ORIGIN_CONTENT
:
2441 return "ORIGIN_CONTENT";
2443 return "Unexpected value";
2447 const char* ToChar(IMEMessage aIMEMessage
) {
2448 switch (aIMEMessage
) {
2449 case NOTIFY_IME_OF_NOTHING
:
2450 return "NOTIFY_IME_OF_NOTHING";
2451 case NOTIFY_IME_OF_FOCUS
:
2452 return "NOTIFY_IME_OF_FOCUS";
2453 case NOTIFY_IME_OF_BLUR
:
2454 return "NOTIFY_IME_OF_BLUR";
2455 case NOTIFY_IME_OF_SELECTION_CHANGE
:
2456 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2457 case NOTIFY_IME_OF_TEXT_CHANGE
:
2458 return "NOTIFY_IME_OF_TEXT_CHANGE";
2459 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED
:
2460 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2461 case NOTIFY_IME_OF_POSITION_CHANGE
:
2462 return "NOTIFY_IME_OF_POSITION_CHANGE";
2463 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT
:
2464 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2465 case REQUEST_TO_COMMIT_COMPOSITION
:
2466 return "REQUEST_TO_COMMIT_COMPOSITION";
2467 case REQUEST_TO_CANCEL_COMPOSITION
:
2468 return "REQUEST_TO_CANCEL_COMPOSITION";
2470 return "Unexpected value";
2474 void NativeIMEContext::Init(nsIWidget
* aWidget
) {
2476 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2477 mOriginProcessID
= static_cast<uint64_t>(-1);
2480 if (!XRE_IsContentProcess()) {
2481 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(
2482 aWidget
->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT
));
2483 mOriginProcessID
= 0;
2486 // If this is created in a child process, aWidget is an instance of
2487 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2488 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2489 // native IME context of the parent process.
2490 *this = aWidget
->GetNativeIMEContext();
2493 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext
) {
2494 if (NS_WARN_IF(!aRawNativeIMEContext
)) {
2495 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2496 mOriginProcessID
= static_cast<uint64_t>(-1);
2499 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(aRawNativeIMEContext
);
2501 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2504 void IMENotification::TextChangeDataBase::MergeWith(
2505 const IMENotification::TextChangeDataBase
& aOther
) {
2506 MOZ_ASSERT(aOther
.IsValid(), "Merging data must store valid data");
2507 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mRemovedEndOffset
,
2508 "end of removed text must be same or larger than start");
2509 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mAddedEndOffset
,
2510 "end of added text must be same or larger than start");
2517 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2518 // text ranges. I.e., mStartOffset should be the smallest offset of all
2519 // modified text ranges in old text. |mRemovedEndOffset| should be the
2520 // largest end offset in old text of all modified text ranges.
2521 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2522 // I.e., only this is an offset in new text.
2523 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2524 // premodified text was already removed. And some text whose length is
2525 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2526 // this allows IME to mark dirty the modified text range with |mStartOffset|
2527 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2528 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2529 // Additionally, IME can retrieve only the text between |mStartOffset| and
2530 // |mAddedEndOffset| for updating stored text.
2532 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2533 // should be adjusted to be in same text. The |newData.mStartOffset| and
2534 // |newData.mRemovedEndOffset| should be computed as in old text because
2535 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2536 // in the old text but even if some text before the values of the newData
2537 // has already been modified, the values don't include the changes.
2539 // For comparing new and old |mAddedEndOffset| values, they should be
2540 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2541 // computed as in the new text because |mAddedEndOffset| indicates the end
2542 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2543 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2545 const TextChangeDataBase
& newData
= aOther
;
2546 const TextChangeDataBase oldData
= *this;
2548 // mCausedOnlyByComposition should be true only when all changes are caused
2550 mCausedOnlyByComposition
=
2551 newData
.mCausedOnlyByComposition
&& oldData
.mCausedOnlyByComposition
;
2553 // mIncludingChangesWithoutComposition should be true if at least one of
2554 // merged changes occurred without composition.
2555 mIncludingChangesWithoutComposition
=
2556 newData
.mIncludingChangesWithoutComposition
||
2557 oldData
.mIncludingChangesWithoutComposition
;
2559 // mIncludingChangesDuringComposition should be true when at least one of
2560 // the merged non-composition changes occurred during the latest composition.
2561 if (!newData
.mCausedOnlyByComposition
&&
2562 !newData
.mIncludingChangesDuringComposition
) {
2563 MOZ_ASSERT(newData
.mIncludingChangesWithoutComposition
);
2564 MOZ_ASSERT(mIncludingChangesWithoutComposition
);
2565 // If new change is neither caused by composition nor occurred during
2566 // composition, set mIncludingChangesDuringComposition to false because
2567 // IME doesn't want outdated text changes as text change during current
2569 mIncludingChangesDuringComposition
= false;
2571 // Otherwise, set mIncludingChangesDuringComposition to true if either
2572 // oldData or newData includes changes during composition.
2573 mIncludingChangesDuringComposition
=
2574 newData
.mIncludingChangesDuringComposition
||
2575 oldData
.mIncludingChangesDuringComposition
;
2578 if (newData
.mStartOffset
>= oldData
.mAddedEndOffset
) {
2580 // If new start is after old end offset of added text, it means that text
2581 // after the modified range is modified. Like:
2582 // added range of old change: +----------+
2583 // removed range of new change: +----------+
2584 // So, the old start offset is always the smaller offset.
2585 mStartOffset
= oldData
.mStartOffset
;
2586 // The new end offset of removed text is moved by the old change and we
2587 // need to cancel the move of the old change for comparing the offsets in
2588 // same text because it doesn't make sensce to compare offsets in different
2590 uint32_t newRemovedEndOffsetInOldText
=
2591 newData
.mRemovedEndOffset
- oldData
.Difference();
2593 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2594 // The new end offset of added text is always the larger offset.
2595 mAddedEndOffset
= newData
.mAddedEndOffset
;
2599 if (newData
.mStartOffset
>= oldData
.mStartOffset
) {
2600 // If new start is in the modified range, it means that new data changes
2601 // a part or all of the range.
2602 mStartOffset
= oldData
.mStartOffset
;
2603 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2605 // If new end of removed text is greater than old end of added text, it
2606 // means that all or a part of modified range modified again and text
2607 // after the modified range is also modified. Like:
2608 // added range of old change: +----------+
2609 // removed range of new change: +----------+
2610 // So, the new removed end offset is moved by the old change and we need
2611 // to cancel the move of the old change for comparing the offsets in the
2612 // same text because it doesn't make sense to compare the offsets in
2614 uint32_t newRemovedEndOffsetInOldText
=
2615 newData
.mRemovedEndOffset
- oldData
.Difference();
2617 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2618 // The old end of added text is replaced by new change. So, it should be
2619 // same as the new start. On the other hand, the new added end offset is
2620 // always same or larger. Therefore, the merged end offset of added
2621 // text should be the new end offset of added text.
2622 mAddedEndOffset
= newData
.mAddedEndOffset
;
2627 // If new end of removed text is less than old end of added text, it means
2628 // that only a part of the modified range is modified again. Like:
2629 // added range of old change: +------------+
2630 // removed range of new change: +-----+
2631 // So, the new end offset of removed text should be same as the old end
2632 // offset of removed text. Therefore, the merged end offset of removed
2633 // text should be the old text change's |mRemovedEndOffset|.
2634 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2635 // The old end of added text is moved by new change. So, we need to cancel
2636 // the move of the new change for comparing the offsets in same text.
2637 uint32_t oldAddedEndOffsetInNewText
=
2638 oldData
.mAddedEndOffset
+ newData
.Difference();
2640 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2644 if (newData
.mRemovedEndOffset
>= oldData
.mStartOffset
) {
2645 // If new end of removed text is greater than old start (and new start is
2646 // less than old start), it means that a part of modified range is modified
2647 // again and some new text before the modified range is also modified.
2648 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2649 "new start offset should be less than old one here");
2650 mStartOffset
= newData
.mStartOffset
;
2651 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2653 // If new end of removed text is greater than old end of added text, it
2654 // means that all modified text and text after the modified range is
2656 // added range of old change: +----------+
2657 // removed range of new change: +------------------+
2658 // So, the new end of removed text is moved by the old change. Therefore,
2659 // we need to cancel the move of the old change for comparing the offsets
2660 // in same text because it doesn't make sense to compare the offsets in
2662 uint32_t newRemovedEndOffsetInOldText
=
2663 newData
.mRemovedEndOffset
- oldData
.Difference();
2665 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2666 // The old end of added text is replaced by new change. So, the old end
2667 // offset of added text is same as new text change's start offset. Then,
2668 // new change's end offset of added text is always same or larger than
2669 // it. Therefore, merged end offset of added text is always the new end
2670 // offset of added text.
2671 mAddedEndOffset
= newData
.mAddedEndOffset
;
2676 // If new end of removed text is less than old end of added text, it
2677 // means that only a part of the modified range is modified again. Like:
2678 // added range of old change: +----------+
2679 // removed range of new change: +----------+
2680 // So, the new end of removed text should be same as old end of removed
2681 // text for preventing end of removed text to be modified. Therefore,
2682 // merged end offset of removed text is always the old end offset of removed
2684 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2685 // The old end of added text is moved by this change. So, we need to
2686 // cancel the move of the new change for comparing the offsets in same text
2687 // because it doesn't make sense to compare the offsets in different text.
2688 uint32_t oldAddedEndOffsetInNewText
=
2689 oldData
.mAddedEndOffset
+ newData
.Difference();
2691 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2696 // Otherwise, i.e., both new end of added text and new start are less than
2697 // old start, text before the modified range is modified. Like:
2698 // added range of old change: +----------+
2699 // removed range of new change: +----------+
2700 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2701 "new start offset should be less than old one here");
2702 mStartOffset
= newData
.mStartOffset
;
2703 MOZ_ASSERT(newData
.mRemovedEndOffset
< oldData
.mRemovedEndOffset
,
2704 "new removed end offset should be less than old one here");
2705 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2706 // The end of added text should be adjusted with the new difference.
2707 uint32_t oldAddedEndOffsetInNewText
=
2708 oldData
.mAddedEndOffset
+ newData
.Difference();
2710 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2715 // Let's test the code of merging multiple text change data in debug build
2716 // and crash if one of them fails because this feature is very complex but
2717 // cannot be tested with mochitest.
2718 void IMENotification::TextChangeDataBase::Test() {
2719 static bool gTestTextChangeEvent
= true;
2720 if (!gTestTextChangeEvent
) {
2723 gTestTextChangeEvent
= false;
2725 /****************************************************************************
2727 ****************************************************************************/
2730 MergeWith(TextChangeData(10, 10, 20, false, false));
2731 MergeWith(TextChangeData(20, 20, 35, false, false));
2732 MOZ_ASSERT(mStartOffset
== 10,
2733 "Test 1-1-1: mStartOffset should be the first offset");
2735 mRemovedEndOffset
== 10, // 20 - (20 - 10)
2736 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2738 mAddedEndOffset
== 35,
2739 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2742 // Removing text (longer line -> shorter line)
2743 MergeWith(TextChangeData(10, 20, 10, false, false));
2744 MergeWith(TextChangeData(10, 30, 10, false, false));
2745 MOZ_ASSERT(mStartOffset
== 10,
2746 "Test 1-2-1: mStartOffset should be the first offset");
2747 MOZ_ASSERT(mRemovedEndOffset
== 40, // 30 + (10 - 20)
2748 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2750 "with already removed length");
2752 mAddedEndOffset
== 10,
2753 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2756 // Removing text (shorter line -> longer line)
2757 MergeWith(TextChangeData(10, 20, 10, false, false));
2758 MergeWith(TextChangeData(10, 15, 10, false, false));
2759 MOZ_ASSERT(mStartOffset
== 10,
2760 "Test 1-3-1: mStartOffset should be the first offset");
2761 MOZ_ASSERT(mRemovedEndOffset
== 25, // 15 + (10 - 20)
2762 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2764 "with already removed length");
2766 mAddedEndOffset
== 10,
2767 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2770 // Appending text at different point (not sure if actually occurs)
2771 MergeWith(TextChangeData(10, 10, 20, false, false));
2772 MergeWith(TextChangeData(55, 55, 60, false, false));
2773 MOZ_ASSERT(mStartOffset
== 10,
2774 "Test 1-4-1: mStartOffset should be the smallest offset");
2776 mRemovedEndOffset
== 45, // 55 - (10 - 20)
2777 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2778 "text without already added length");
2780 mAddedEndOffset
== 60,
2781 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2784 // Removing text at different point (not sure if actually occurs)
2785 MergeWith(TextChangeData(10, 20, 10, false, false));
2786 MergeWith(TextChangeData(55, 68, 55, false, false));
2787 MOZ_ASSERT(mStartOffset
== 10,
2788 "Test 1-5-1: mStartOffset should be the smallest offset");
2790 mRemovedEndOffset
== 78, // 68 - (10 - 20)
2791 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2792 "text with already removed length");
2794 mAddedEndOffset
== 55,
2795 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2798 // Replacing text and append text (becomes longer)
2799 MergeWith(TextChangeData(30, 35, 32, false, false));
2800 MergeWith(TextChangeData(32, 32, 40, false, false));
2801 MOZ_ASSERT(mStartOffset
== 30,
2802 "Test 1-6-1: mStartOffset should be the smallest offset");
2804 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2805 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2808 mAddedEndOffset
== 40,
2809 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2812 // Replacing text and append text (becomes shorter)
2813 MergeWith(TextChangeData(30, 35, 32, false, false));
2814 MergeWith(TextChangeData(32, 32, 33, false, false));
2815 MOZ_ASSERT(mStartOffset
== 30,
2816 "Test 1-7-1: mStartOffset should be the smallest offset");
2818 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2819 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2822 mAddedEndOffset
== 33,
2823 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2826 // Removing text and replacing text after first range (not sure if actually
2828 MergeWith(TextChangeData(30, 35, 30, false, false));
2829 MergeWith(TextChangeData(32, 34, 48, false, false));
2830 MOZ_ASSERT(mStartOffset
== 30,
2831 "Test 1-8-1: mStartOffset should be the smallest offset");
2832 MOZ_ASSERT(mRemovedEndOffset
== 39, // 34 - (30 - 35)
2833 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2835 "without already removed text");
2837 mAddedEndOffset
== 48,
2838 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2841 // Removing text and replacing text after first range (not sure if actually
2843 MergeWith(TextChangeData(30, 35, 30, false, false));
2844 MergeWith(TextChangeData(32, 38, 36, false, false));
2845 MOZ_ASSERT(mStartOffset
== 30,
2846 "Test 1-9-1: mStartOffset should be the smallest offset");
2847 MOZ_ASSERT(mRemovedEndOffset
== 43, // 38 - (30 - 35)
2848 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2850 "without already removed text");
2852 mAddedEndOffset
== 36,
2853 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2856 /****************************************************************************
2858 ****************************************************************************/
2860 // Replacing text in around end of added text (becomes shorter) (not sure
2861 // if actually occurs)
2862 MergeWith(TextChangeData(50, 50, 55, false, false));
2863 MergeWith(TextChangeData(53, 60, 54, false, false));
2864 MOZ_ASSERT(mStartOffset
== 50,
2865 "Test 2-1-1: mStartOffset should be the smallest offset");
2866 MOZ_ASSERT(mRemovedEndOffset
== 55, // 60 - (55 - 50)
2867 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2869 "without already added text length");
2871 mAddedEndOffset
== 54,
2872 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2875 // Replacing text around end of added text (becomes longer) (not sure
2876 // if actually occurs)
2877 MergeWith(TextChangeData(50, 50, 55, false, false));
2878 MergeWith(TextChangeData(54, 62, 68, false, false));
2879 MOZ_ASSERT(mStartOffset
== 50,
2880 "Test 2-2-1: mStartOffset should be the smallest offset");
2881 MOZ_ASSERT(mRemovedEndOffset
== 57, // 62 - (55 - 50)
2882 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2884 "without already added text length");
2886 mAddedEndOffset
== 68,
2887 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2890 // Replacing text around end of replaced text (became shorter) (not sure if
2892 MergeWith(TextChangeData(36, 48, 45, false, false));
2893 MergeWith(TextChangeData(43, 50, 49, false, false));
2894 MOZ_ASSERT(mStartOffset
== 36,
2895 "Test 2-3-1: mStartOffset should be the smallest offset");
2896 MOZ_ASSERT(mRemovedEndOffset
== 53, // 50 - (45 - 48)
2897 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2899 "without already removed text length");
2901 mAddedEndOffset
== 49,
2902 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2905 // Replacing text around end of replaced text (became longer) (not sure if
2907 MergeWith(TextChangeData(36, 52, 53, false, false));
2908 MergeWith(TextChangeData(43, 68, 61, false, false));
2909 MOZ_ASSERT(mStartOffset
== 36,
2910 "Test 2-4-1: mStartOffset should be the smallest offset");
2911 MOZ_ASSERT(mRemovedEndOffset
== 67, // 68 - (53 - 52)
2912 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2914 "without already added text length");
2916 mAddedEndOffset
== 61,
2917 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2920 /****************************************************************************
2922 ****************************************************************************/
2924 // Appending text in already added text (not sure if actually occurs)
2925 MergeWith(TextChangeData(10, 10, 20, false, false));
2926 MergeWith(TextChangeData(15, 15, 30, false, false));
2927 MOZ_ASSERT(mStartOffset
== 10,
2928 "Test 3-1-1: mStartOffset should be the smallest offset");
2929 MOZ_ASSERT(mRemovedEndOffset
== 10,
2930 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2933 mAddedEndOffset
== 35, // 20 + (30 - 15)
2934 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2935 "added text length by the new change");
2938 // Replacing text in added text (not sure if actually occurs)
2939 MergeWith(TextChangeData(50, 50, 55, false, false));
2940 MergeWith(TextChangeData(52, 53, 56, false, false));
2941 MOZ_ASSERT(mStartOffset
== 50,
2942 "Test 3-2-1: mStartOffset should be the smallest offset");
2943 MOZ_ASSERT(mRemovedEndOffset
== 50,
2944 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2947 mAddedEndOffset
== 58, // 55 + (56 - 53)
2948 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2949 "added text length by the new change");
2952 // Replacing text in replaced text (became shorter) (not sure if actually
2954 MergeWith(TextChangeData(36, 48, 45, false, false));
2955 MergeWith(TextChangeData(37, 38, 50, false, false));
2956 MOZ_ASSERT(mStartOffset
== 36,
2957 "Test 3-3-1: mStartOffset should be the smallest offset");
2958 MOZ_ASSERT(mRemovedEndOffset
== 48,
2959 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2962 mAddedEndOffset
== 57, // 45 + (50 - 38)
2963 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2964 "added text length by the new change");
2967 // Replacing text in replaced text (became longer) (not sure if actually
2969 MergeWith(TextChangeData(32, 48, 53, false, false));
2970 MergeWith(TextChangeData(43, 50, 52, false, false));
2971 MOZ_ASSERT(mStartOffset
== 32,
2972 "Test 3-4-1: mStartOffset should be the smallest offset");
2973 MOZ_ASSERT(mRemovedEndOffset
== 48,
2974 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2976 "without already added text length");
2978 mAddedEndOffset
== 55, // 53 + (52 - 50)
2979 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2980 "added text length by the new change");
2983 // Replacing text in replaced text (became shorter) (not sure if actually
2985 MergeWith(TextChangeData(36, 48, 50, false, false));
2986 MergeWith(TextChangeData(37, 49, 47, false, false));
2987 MOZ_ASSERT(mStartOffset
== 36,
2988 "Test 3-5-1: mStartOffset should be the smallest offset");
2990 mRemovedEndOffset
== 48,
2991 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
2993 MOZ_ASSERT(mAddedEndOffset
== 48, // 50 + (47 - 49)
2994 "Test 3-5-3: mAddedEndOffset should be the first end of added "
2996 "removed text length by the new change");
2999 // Replacing text in replaced text (became longer) (not sure if actually
3001 MergeWith(TextChangeData(32, 48, 53, false, false));
3002 MergeWith(TextChangeData(43, 50, 47, false, false));
3003 MOZ_ASSERT(mStartOffset
== 32,
3004 "Test 3-6-1: mStartOffset should be the smallest offset");
3005 MOZ_ASSERT(mRemovedEndOffset
== 48,
3006 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
3008 "without already added text length");
3009 MOZ_ASSERT(mAddedEndOffset
== 50, // 53 + (47 - 50)
3010 "Test 3-6-3: mAddedEndOffset should be the first end of added "
3012 "removed text length by the new change");
3015 /****************************************************************************
3017 ****************************************************************************/
3019 // Replacing text all of already append text (not sure if actually occurs)
3020 MergeWith(TextChangeData(50, 50, 55, false, false));
3021 MergeWith(TextChangeData(44, 66, 68, false, false));
3022 MOZ_ASSERT(mStartOffset
== 44,
3023 "Test 4-1-1: mStartOffset should be the smallest offset");
3024 MOZ_ASSERT(mRemovedEndOffset
== 61, // 66 - (55 - 50)
3025 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
3027 "without already added text length");
3029 mAddedEndOffset
== 68,
3030 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3033 // Replacing text around a point in which text was removed (not sure if
3035 MergeWith(TextChangeData(50, 62, 50, false, false));
3036 MergeWith(TextChangeData(44, 66, 68, false, false));
3037 MOZ_ASSERT(mStartOffset
== 44,
3038 "Test 4-2-1: mStartOffset should be the smallest offset");
3039 MOZ_ASSERT(mRemovedEndOffset
== 78, // 66 - (50 - 62)
3040 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
3042 "without already removed text length");
3044 mAddedEndOffset
== 68,
3045 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3048 // Replacing text all replaced text (became shorter) (not sure if actually
3050 MergeWith(TextChangeData(50, 62, 60, false, false));
3051 MergeWith(TextChangeData(49, 128, 130, false, false));
3052 MOZ_ASSERT(mStartOffset
== 49,
3053 "Test 4-3-1: mStartOffset should be the smallest offset");
3054 MOZ_ASSERT(mRemovedEndOffset
== 130, // 128 - (60 - 62)
3055 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
3057 "without already removed text length");
3059 mAddedEndOffset
== 130,
3060 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3063 // Replacing text all replaced text (became longer) (not sure if actually
3065 MergeWith(TextChangeData(50, 61, 73, false, false));
3066 MergeWith(TextChangeData(44, 100, 50, false, false));
3067 MOZ_ASSERT(mStartOffset
== 44,
3068 "Test 4-4-1: mStartOffset should be the smallest offset");
3069 MOZ_ASSERT(mRemovedEndOffset
== 88, // 100 - (73 - 61)
3070 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
3072 "with already added text length");
3074 mAddedEndOffset
== 50,
3075 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3078 /****************************************************************************
3080 ****************************************************************************/
3082 // Replacing text around start of added text (not sure if actually occurs)
3083 MergeWith(TextChangeData(50, 50, 55, false, false));
3084 MergeWith(TextChangeData(48, 52, 49, false, false));
3085 MOZ_ASSERT(mStartOffset
== 48,
3086 "Test 5-1-1: mStartOffset should be the smallest offset");
3088 mRemovedEndOffset
== 50,
3089 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
3092 mAddedEndOffset
== 52, // 55 + (52 - 49)
3093 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
3094 "added text length by the new change");
3097 // Replacing text around start of replaced text (became shorter) (not sure if
3099 MergeWith(TextChangeData(50, 60, 58, false, false));
3100 MergeWith(TextChangeData(43, 50, 48, false, false));
3101 MOZ_ASSERT(mStartOffset
== 43,
3102 "Test 5-2-1: mStartOffset should be the smallest offset");
3104 mRemovedEndOffset
== 60,
3105 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3107 MOZ_ASSERT(mAddedEndOffset
== 56, // 58 + (48 - 50)
3108 "Test 5-2-3: mAddedEndOffset should be the first end of added "
3110 "removed text length by the new change");
3113 // Replacing text around start of replaced text (became longer) (not sure if
3115 MergeWith(TextChangeData(50, 60, 68, false, false));
3116 MergeWith(TextChangeData(43, 55, 53, false, false));
3117 MOZ_ASSERT(mStartOffset
== 43,
3118 "Test 5-3-1: mStartOffset should be the smallest offset");
3120 mRemovedEndOffset
== 60,
3121 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3123 MOZ_ASSERT(mAddedEndOffset
== 66, // 68 + (53 - 55)
3124 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3126 "removed text length by the new change");
3129 // Replacing text around start of replaced text (became shorter) (not sure if
3131 MergeWith(TextChangeData(50, 60, 58, false, false));
3132 MergeWith(TextChangeData(43, 50, 128, false, false));
3133 MOZ_ASSERT(mStartOffset
== 43,
3134 "Test 5-4-1: mStartOffset should be the smallest offset");
3136 mRemovedEndOffset
== 60,
3137 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
3140 mAddedEndOffset
== 136, // 58 + (128 - 50)
3141 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
3142 "added text length by the new change");
3145 // Replacing text around start of replaced text (became longer) (not sure if
3147 MergeWith(TextChangeData(50, 60, 68, false, false));
3148 MergeWith(TextChangeData(43, 55, 65, false, false));
3149 MOZ_ASSERT(mStartOffset
== 43,
3150 "Test 5-5-1: mStartOffset should be the smallest offset");
3152 mRemovedEndOffset
== 60,
3153 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
3156 mAddedEndOffset
== 78, // 68 + (65 - 55)
3157 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
3158 "added text length by the new change");
3161 /****************************************************************************
3163 ****************************************************************************/
3165 // Appending text before already added text (not sure if actually occurs)
3166 MergeWith(TextChangeData(30, 30, 45, false, false));
3167 MergeWith(TextChangeData(10, 10, 20, false, false));
3168 MOZ_ASSERT(mStartOffset
== 10,
3169 "Test 6-1-1: mStartOffset should be the smallest offset");
3171 mRemovedEndOffset
== 30,
3172 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3175 mAddedEndOffset
== 55, // 45 + (20 - 10)
3176 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3177 "added text length by the new change");
3180 // Removing text before already removed text (not sure if actually occurs)
3181 MergeWith(TextChangeData(30, 35, 30, false, false));
3182 MergeWith(TextChangeData(10, 25, 10, false, false));
3183 MOZ_ASSERT(mStartOffset
== 10,
3184 "Test 6-2-1: mStartOffset should be the smallest offset");
3186 mRemovedEndOffset
== 35,
3187 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3190 mAddedEndOffset
== 15, // 30 - (25 - 10)
3191 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3192 "removed text length by the new change");
3195 // Replacing text before already replaced text (not sure if actually occurs)
3196 MergeWith(TextChangeData(50, 65, 70, false, false));
3197 MergeWith(TextChangeData(13, 24, 15, false, false));
3198 MOZ_ASSERT(mStartOffset
== 13,
3199 "Test 6-3-1: mStartOffset should be the smallest offset");
3201 mRemovedEndOffset
== 65,
3202 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3204 MOZ_ASSERT(mAddedEndOffset
== 61, // 70 + (15 - 24)
3205 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3207 "removed text length by the new change");
3210 // Replacing text before already replaced text (not sure if actually occurs)
3211 MergeWith(TextChangeData(50, 65, 70, false, false));
3212 MergeWith(TextChangeData(13, 24, 36, false, false));
3213 MOZ_ASSERT(mStartOffset
== 13,
3214 "Test 6-4-1: mStartOffset should be the smallest offset");
3216 mRemovedEndOffset
== 65,
3217 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3219 MOZ_ASSERT(mAddedEndOffset
== 82, // 70 + (36 - 24)
3220 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3222 "removed text length by the new change");
3226 #endif // #ifdef DEBUG
3228 } // namespace mozilla::widget
3231 //////////////////////////////////////////////////////////////
3233 // Convert a GUI event message code to a string.
3234 // Makes it a lot easier to debug events.
3236 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3237 // for a DebugPrintEvent() function that uses
3240 //////////////////////////////////////////////////////////////
3242 nsAutoString
nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent
* aGuiEvent
) {
3243 NS_ASSERTION(nullptr != aGuiEvent
, "cmon, null gui event.");
3245 nsAutoString
eventName(u
"UNKNOWN"_ns
);
3247 # define _ASSIGN_eventName(_value, _name) \
3249 eventName.AssignLiteral(_name); \
3252 switch (aGuiEvent
->mMessage
) {
3253 _ASSIGN_eventName(eBlur
, "eBlur");
3254 _ASSIGN_eventName(eDrop
, "eDrop");
3255 _ASSIGN_eventName(eDragEnter
, "eDragEnter");
3256 _ASSIGN_eventName(eDragExit
, "eDragExit");
3257 _ASSIGN_eventName(eDragOver
, "eDragOver");
3258 _ASSIGN_eventName(eEditorInput
, "eEditorInput");
3259 _ASSIGN_eventName(eFocus
, "eFocus");
3260 _ASSIGN_eventName(eFocusIn
, "eFocusIn");
3261 _ASSIGN_eventName(eFocusOut
, "eFocusOut");
3262 _ASSIGN_eventName(eFormSelect
, "eFormSelect");
3263 _ASSIGN_eventName(eFormChange
, "eFormChange");
3264 _ASSIGN_eventName(eFormReset
, "eFormReset");
3265 _ASSIGN_eventName(eFormSubmit
, "eFormSubmit");
3266 _ASSIGN_eventName(eImageAbort
, "eImageAbort");
3267 _ASSIGN_eventName(eLoadError
, "eLoadError");
3268 _ASSIGN_eventName(eKeyDown
, "eKeyDown");
3269 _ASSIGN_eventName(eKeyPress
, "eKeyPress");
3270 _ASSIGN_eventName(eKeyUp
, "eKeyUp");
3271 _ASSIGN_eventName(eMouseEnterIntoWidget
, "eMouseEnterIntoWidget");
3272 _ASSIGN_eventName(eMouseExitFromWidget
, "eMouseExitFromWidget");
3273 _ASSIGN_eventName(eMouseDown
, "eMouseDown");
3274 _ASSIGN_eventName(eMouseUp
, "eMouseUp");
3275 _ASSIGN_eventName(eMouseClick
, "eMouseClick");
3276 _ASSIGN_eventName(eMouseAuxClick
, "eMouseAuxClick");
3277 _ASSIGN_eventName(eMouseDoubleClick
, "eMouseDoubleClick");
3278 _ASSIGN_eventName(eMouseMove
, "eMouseMove");
3279 _ASSIGN_eventName(eLoad
, "eLoad");
3280 _ASSIGN_eventName(ePopState
, "ePopState");
3281 _ASSIGN_eventName(eBeforeScriptExecute
, "eBeforeScriptExecute");
3282 _ASSIGN_eventName(eAfterScriptExecute
, "eAfterScriptExecute");
3283 _ASSIGN_eventName(eUnload
, "eUnload");
3284 _ASSIGN_eventName(eHashChange
, "eHashChange");
3285 _ASSIGN_eventName(eReadyStateChange
, "eReadyStateChange");
3286 _ASSIGN_eventName(eXULBroadcast
, "eXULBroadcast");
3287 _ASSIGN_eventName(eXULCommandUpdate
, "eXULCommandUpdate");
3289 # undef _ASSIGN_eventName
3292 eventName
.AssignLiteral("UNKNOWN: ");
3293 eventName
.AppendInt(aGuiEvent
->mMessage
);
3297 return nsAutoString(eventName
);
3299 //////////////////////////////////////////////////////////////
3301 // Code to deal with paint and event debug prefs.
3303 //////////////////////////////////////////////////////////////
3309 static PrefPair debug_PrefValues
[] = {
3310 {"nglayout.debug.crossing_event_dumping", false},
3311 {"nglayout.debug.event_dumping", false},
3312 {"nglayout.debug.invalidate_dumping", false},
3313 {"nglayout.debug.motion_event_dumping", false},
3314 {"nglayout.debug.paint_dumping", false}};
3316 //////////////////////////////////////////////////////////////
3317 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName
) {
3318 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3320 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3321 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3322 return debug_PrefValues
[i
].value
;
3328 //////////////////////////////////////////////////////////////
3329 static void debug_SetCachedBoolPref(const char* aPrefName
, bool aValue
) {
3330 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3332 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3333 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3334 debug_PrefValues
[i
].value
= aValue
;
3340 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3343 //////////////////////////////////////////////////////////////
3344 class Debug_PrefObserver final
: public nsIObserver
{
3345 ~Debug_PrefObserver() = default;
3352 NS_IMPL_ISUPPORTS(Debug_PrefObserver
, nsIObserver
)
3355 Debug_PrefObserver::Observe(nsISupports
* subject
, const char* topic
,
3356 const char16_t
* data
) {
3357 NS_ConvertUTF16toUTF8
prefName(data
);
3359 bool value
= Preferences::GetBool(prefName
.get(), false);
3360 debug_SetCachedBoolPref(prefName
.get(), value
);
3364 //////////////////////////////////////////////////////////////
3365 /* static */ void debug_RegisterPrefCallbacks() {
3366 static bool once
= true;
3374 nsCOMPtr
<nsIObserver
> obs(new Debug_PrefObserver());
3375 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3376 // Initialize the pref values
3377 debug_PrefValues
[i
].value
=
3378 Preferences::GetBool(debug_PrefValues
[i
].name
, false);
3381 // Register callbacks for when these change
3383 name
.AssignLiteral(debug_PrefValues
[i
].name
,
3384 strlen(debug_PrefValues
[i
].name
));
3385 Preferences::AddStrongObserver(obs
, name
);
3389 //////////////////////////////////////////////////////////////
3390 static int32_t _GetPrintCount() {
3391 static int32_t sCount
= 0;
3395 //////////////////////////////////////////////////////////////
3397 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3398 WidgetGUIEvent
* aGuiEvent
,
3399 const char* aWidgetName
, int32_t aWindowID
) {
3400 if (aGuiEvent
->mMessage
== eMouseMove
) {
3401 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3404 if (aGuiEvent
->mMessage
== eMouseEnterIntoWidget
||
3405 aGuiEvent
->mMessage
== eMouseExitFromWidget
) {
3406 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3410 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3412 NS_LossyConvertUTF16toASCII
tempString(
3413 debug_GuiEventToString(aGuiEvent
).get());
3415 fprintf(aFileOut
, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3416 _GetPrintCount(), tempString
.get(), (void*)aWidget
, aWidgetName
,
3417 aWindowID
, aGuiEvent
->mRefPoint
.x
.value
,
3418 aGuiEvent
->mRefPoint
.y
.value
);
3420 //////////////////////////////////////////////////////////////
3422 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3423 const nsIntRegion
& aRegion
,
3424 const char* aWidgetName
,
3425 int32_t aWindowID
) {
3426 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3427 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3429 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3431 nsIntRect rect
= aRegion
.GetBounds();
3433 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3435 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
, rect
.X(),
3436 rect
.Y(), rect
.Width(), rect
.Height());
3438 fprintf(aFileOut
, "\n");
3440 //////////////////////////////////////////////////////////////
3442 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut
, nsIWidget
* aWidget
,
3443 const LayoutDeviceIntRect
* aRect
,
3444 const char* aWidgetName
,
3445 int32_t aWindowID
) {
3446 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3448 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3449 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3451 fprintf(aFileOut
, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3452 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
);
3455 fprintf(aFileOut
, " rect=%3d,%-3d %3d,%-3d", aRect
->X(), aRect
->Y(),
3456 aRect
->Width(), aRect
->Height());
3458 fprintf(aFileOut
, " rect=%-15s", "none");
3461 fprintf(aFileOut
, "\n");
3463 //////////////////////////////////////////////////////////////