2 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
3 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
4 /* This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 #include "nsBaseWidget.h"
13 #include "InputData.h"
14 #include "LiveResizeListener.h"
15 #include "SwipeTracker.h"
16 #include "TouchEvents.h"
17 #include "X11UndefineNone.h"
18 #include "base/thread.h"
19 #include "mozilla/ArrayUtils.h"
20 #include "mozilla/Attributes.h"
21 #include "mozilla/GlobalKeyListener.h"
22 #include "mozilla/IMEStateManager.h"
23 #include "mozilla/Logging.h"
24 #include "mozilla/MouseEvents.h"
25 #include "mozilla/NativeKeyBindingsType.h"
26 #include "mozilla/Preferences.h"
27 #include "mozilla/PresShell.h"
28 #include "mozilla/ScopeExit.h"
29 #include "mozilla/Sprintf.h"
30 #include "mozilla/StaticPrefs_apz.h"
31 #include "mozilla/StaticPrefs_dom.h"
32 #include "mozilla/StaticPrefs_gfx.h"
33 #include "mozilla/StaticPrefs_layers.h"
34 #include "mozilla/StaticPrefs_layout.h"
35 #include "mozilla/TextEventDispatcher.h"
36 #include "mozilla/TextEventDispatcherListener.h"
37 #include "mozilla/UniquePtr.h"
38 #include "mozilla/Unused.h"
39 #include "mozilla/VsyncDispatcher.h"
40 #include "mozilla/dom/BrowserParent.h"
41 #include "mozilla/dom/ContentChild.h"
42 #include "mozilla/dom/Document.h"
43 #include "mozilla/dom/SimpleGestureEventBinding.h"
44 #include "mozilla/gfx/2D.h"
45 #include "mozilla/gfx/GPUProcessManager.h"
46 #include "mozilla/gfx/gfxVars.h"
47 #include "mozilla/layers/APZCCallbackHelper.h"
48 #include "mozilla/layers/TouchActionHelper.h"
49 #include "mozilla/layers/APZEventState.h"
50 #include "mozilla/layers/APZInputBridge.h"
51 #include "mozilla/layers/APZThreadUtils.h"
52 #include "mozilla/layers/ChromeProcessController.h"
53 #include "mozilla/layers/Compositor.h"
54 #include "mozilla/layers/CompositorBridgeChild.h"
55 #include "mozilla/layers/CompositorBridgeParent.h"
56 #include "mozilla/layers/CompositorOptions.h"
57 #include "mozilla/layers/IAPZCTreeManager.h"
58 #include "mozilla/layers/ImageBridgeChild.h"
59 #include "mozilla/layers/InputAPZContext.h"
60 #include "mozilla/layers/WebRenderLayerManager.h"
61 #include "mozilla/webrender/WebRenderTypes.h"
62 #include "mozilla/widget/ScreenManager.h"
63 #include "nsAppDirectoryServiceDefs.h"
65 #include "nsContentUtils.h"
66 #include "nsDeviceContext.h"
67 #include "nsGfxCIID.h"
68 #include "nsIAppWindow.h"
69 #include "nsIBaseWindow.h"
70 #include "nsIContent.h"
71 #include "nsIScreenManager.h"
72 #include "nsISimpleEnumerator.h"
73 #include "nsIWidgetListener.h"
74 #include "nsRefPtrHashtable.h"
75 #include "nsServiceManagerUtils.h"
76 #include "nsWidgetsCID.h"
77 #include "nsXULPopupManager.h"
81 # include "nsAccessibilityService.h"
83 #include "gfxConfig.h"
84 #include "gfxUtils.h" // for ToDeviceColor
85 #include "mozilla/layers/CompositorSession.h"
86 #include "VRManagerChild.h"
87 #include "gfxConfig.h"
89 #include "nsViewManager.h"
91 static mozilla::LazyLogModule
sBaseWidgetLog("BaseWidget");
94 # include "nsIObserver.h"
96 static void debug_RegisterPrefCallbacks();
100 #ifdef NOISY_WIDGET_LEAKS
101 static int32_t gNumWidgets
;
104 using namespace mozilla::dom
;
105 using namespace mozilla::layers
;
106 using namespace mozilla::ipc
;
107 using namespace mozilla::widget
;
108 using namespace mozilla
;
110 // Async pump timer during injected long touch taps
111 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
112 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
113 int32_t nsIWidget::sPointerIdCounter
= 0;
115 // Some statics from nsIWidget.h
117 uint64_t AutoObserverNotifier::sObserverId
= 0;
118 /*static*/ nsTHashMap
<uint64_t, nsCOMPtr
<nsIObserver
>>
119 AutoObserverNotifier::sSavedObservers
;
121 // The maximum amount of time to let the EnableDragDrop runnable wait in the
122 // idle queue before timing out and moving it to the regular queue. Value is in
124 const uint32_t kAsyncDragDropTimeout
= 1000;
126 NS_IMPL_ISUPPORTS(nsBaseWidget
, nsIWidget
, nsISupportsWeakReference
)
128 //-------------------------------------------------------------------------
130 // nsBaseWidget constructor
132 //-------------------------------------------------------------------------
134 nsBaseWidget::nsBaseWidget() : nsBaseWidget(BorderStyle::None
) {}
136 nsBaseWidget::nsBaseWidget(BorderStyle aBorderStyle
)
137 : mWidgetListener(nullptr),
138 mAttachedWidgetListener(nullptr),
139 mPreviouslyAttachedWidgetListener(nullptr),
140 mCompositorVsyncDispatcher(nullptr),
141 mBorderStyle(aBorderStyle
),
144 mPopupLevel(PopupLevel::Top
),
145 mPopupType(PopupType::Any
),
146 mHasRemoteContent(false),
148 mUseAttachedEvents(false),
151 mIsFullyOccluded(false),
152 mNeedFastSnaphot(false),
153 mCurrentPanGestureBelongsToSwipe(false),
154 mIsPIPWindow(false) {
155 #ifdef NOISY_WIDGET_LEAKS
157 printf("WIDGETS+ = %d\n", gNumWidgets
);
161 debug_RegisterPrefCallbacks();
164 mShutdownObserver
= new WidgetShutdownObserver(this);
167 NS_IMPL_ISUPPORTS(WidgetShutdownObserver
, nsIObserver
)
169 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget
* aWidget
)
170 : mWidget(aWidget
), mRegistered(false) {
174 WidgetShutdownObserver::~WidgetShutdownObserver() {
175 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
176 // gets torn down. The observer service and nsBaseWidget have a ref on us
177 // so nsBaseWidget has to call Unregister and then clear its ref.
181 WidgetShutdownObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
182 const char16_t
* aData
) {
186 if (!strcmp(aTopic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
)) {
187 RefPtr
<nsBaseWidget
> widget(mWidget
);
189 } else if (!strcmp(aTopic
, "quit-application")) {
190 RefPtr
<nsBaseWidget
> widget(mWidget
);
196 void WidgetShutdownObserver::Register() {
199 nsContentUtils::RegisterShutdownObserver(this);
201 #ifndef MOZ_WIDGET_ANDROID
202 // The primary purpose of observing quit-application is
203 // to avoid leaking a widget on Windows when nothing else
204 // breaks the circular reference between the widget and
205 // TSFTextStore. However, our Android IME code crashes if
206 // doing this on Android, so let's not do this on Android.
207 // Doing this on Gtk and Mac just in case.
208 nsCOMPtr
<nsIObserverService
> observerService
=
209 mozilla::services::GetObserverService();
210 if (observerService
) {
211 observerService
->AddObserver(this, "quit-application", false);
217 void WidgetShutdownObserver::Unregister() {
221 #ifndef MOZ_WIDGET_ANDROID
222 nsCOMPtr
<nsIObserverService
> observerService
=
223 mozilla::services::GetObserverService();
224 if (observerService
) {
225 observerService
->RemoveObserver(this, "quit-application");
229 nsContentUtils::UnregisterShutdownObserver(this);
234 #define INTL_APP_LOCALES_CHANGED "intl:app-locales-changed"
236 NS_IMPL_ISUPPORTS(LocalesChangedObserver
, nsIObserver
)
238 LocalesChangedObserver::LocalesChangedObserver(nsBaseWidget
* aWidget
)
239 : mWidget(aWidget
), mRegistered(false) {
243 LocalesChangedObserver::~LocalesChangedObserver() {
244 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
245 // gets torn down. The observer service and nsBaseWidget have a ref on us
246 // so nsBaseWidget has to call Unregister and then clear its ref.
250 LocalesChangedObserver::Observe(nsISupports
* aSubject
, const char* aTopic
,
251 const char16_t
* aData
) {
255 if (!strcmp(aTopic
, INTL_APP_LOCALES_CHANGED
)) {
256 RefPtr
<nsBaseWidget
> widget(mWidget
);
257 widget
->LocalesChanged();
262 void LocalesChangedObserver::Register() {
267 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
269 obs
->AddObserver(this, INTL_APP_LOCALES_CHANGED
, true);
272 // Locale might be update before registering
273 RefPtr
<nsBaseWidget
> widget(mWidget
);
274 widget
->LocalesChanged();
279 void LocalesChangedObserver::Unregister() {
284 nsCOMPtr
<nsIObserverService
> obs
= mozilla::services::GetObserverService();
286 obs
->RemoveObserver(this, INTL_APP_LOCALES_CHANGED
);
293 void nsBaseWidget::Shutdown() {
294 NotifyLiveResizeStopped();
296 FreeLocalesChangedObserver();
297 FreeShutdownObserver();
300 void nsBaseWidget::QuitIME() {
301 IMEStateManager::WidgetOnQuit(this);
302 this->mIMEHasQuit
= true;
305 void nsBaseWidget::DestroyCompositor() {
306 RevokeTransactionIdAllocator();
308 // We release this before releasing the compositor, since it may hold the
309 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
310 // trigger a paint, creating a new compositor, and we don't want to re-use
311 // the old vsync dispatcher.
312 if (mCompositorVsyncDispatcher
) {
313 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
315 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
316 mCompositorVsyncDispatcher
->Shutdown();
317 mCompositorVsyncDispatcher
= nullptr;
320 // The compositor shutdown sequence looks like this:
321 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
322 // 2. CompositorBridgeChild synchronously sends WillClose.
323 // 3. CompositorBridgeParent releases some resources (such as the layer
324 // manager, compositor, and widget).
325 // 4. CompositorBridgeChild::Destroy returns.
326 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
327 // compositor thread when the I/O thread closes the IPC channel.
328 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
329 // releases the reference CompositorBridgeParent holds to itself.
331 // When CompositorSession::Shutdown returns, we assume the compositor is gone
332 // or will be gone very soon.
333 if (mCompositorSession
) {
334 ReleaseContentController();
336 SetCompositorWidgetDelegate(nullptr);
337 mCompositorBridgeChild
= nullptr;
338 mCompositorSession
->Shutdown();
339 mCompositorSession
= nullptr;
343 // This prevents the layer manager from starting a new transaction during
345 void nsBaseWidget::RevokeTransactionIdAllocator() {
346 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
349 mWindowRenderer
->AsWebRender()->SetTransactionIdAllocator(nullptr);
352 void nsBaseWidget::ReleaseContentController() {
353 if (mRootContentController
) {
354 mRootContentController
->Destroy();
355 mRootContentController
= nullptr;
359 void nsBaseWidget::DestroyLayerManager() {
360 if (mWindowRenderer
) {
361 mWindowRenderer
->Destroy();
362 mWindowRenderer
= nullptr;
367 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
369 void nsBaseWidget::FreeShutdownObserver() {
370 if (mShutdownObserver
) {
371 mShutdownObserver
->Unregister();
373 mShutdownObserver
= nullptr;
376 void nsBaseWidget::FreeLocalesChangedObserver() {
377 if (mLocalesChangedObserver
) {
378 mLocalesChangedObserver
->Unregister();
380 mLocalesChangedObserver
= nullptr;
383 //-------------------------------------------------------------------------
385 // nsBaseWidget destructor
387 //-------------------------------------------------------------------------
389 nsBaseWidget::~nsBaseWidget() {
391 mSwipeTracker
->Destroy();
392 mSwipeTracker
= nullptr;
395 IMEStateManager::WidgetDestroyed(this);
397 FreeLocalesChangedObserver();
398 FreeShutdownObserver();
399 DestroyLayerManager();
401 #ifdef NOISY_WIDGET_LEAKS
403 printf("WIDGETS- = %d\n", gNumWidgets
);
407 //-------------------------------------------------------------------------
411 //-------------------------------------------------------------------------
412 void nsBaseWidget::BaseCreate(nsIWidget
* aParent
, widget::InitData
* aInitData
) {
414 mWindowType
= aInitData
->mWindowType
;
415 mBorderStyle
= aInitData
->mBorderStyle
;
416 mPopupLevel
= aInitData
->mPopupLevel
;
417 mPopupType
= aInitData
->mPopupHint
;
418 mHasRemoteContent
= aInitData
->mHasRemoteContent
;
419 mIsPIPWindow
= aInitData
->mPIPWindow
;
423 aParent
->AddChild(this);
427 //-------------------------------------------------------------------------
429 // Accessor functions to get/set the client data
431 //-------------------------------------------------------------------------
433 nsIWidgetListener
* nsBaseWidget::GetWidgetListener() const {
434 return mWidgetListener
;
437 void nsBaseWidget::SetWidgetListener(nsIWidgetListener
* aWidgetListener
) {
438 mWidgetListener
= aWidgetListener
;
441 already_AddRefed
<nsIWidget
> nsBaseWidget::CreateChild(
442 const LayoutDeviceIntRect
& aRect
, widget::InitData
* aInitData
,
443 bool aForceUseIWidgetParent
) {
444 nsIWidget
* parent
= this;
445 nsNativeWidget nativeParent
= nullptr;
447 if (!aForceUseIWidgetParent
) {
448 // Use only either parent or nativeParent, not both, to match
449 // existing code. Eventually Create() should be divested of its
450 // nativeWidget parameter.
451 nativeParent
= parent
? parent
->GetNativeData(NS_NATIVE_WIDGET
) : nullptr;
452 parent
= nativeParent
? nullptr : parent
;
453 MOZ_ASSERT(!parent
|| !nativeParent
, "messed up logic");
456 nsCOMPtr
<nsIWidget
> widget
;
457 if (aInitData
&& aInitData
->mWindowType
== WindowType::Popup
) {
458 widget
= AllocateChildPopupWidget();
460 widget
= nsIWidget::CreateChildWindow();
463 if (widget
&& mNeedFastSnaphot
) {
464 widget
->SetNeedFastSnaphot();
468 NS_SUCCEEDED(widget
->Create(parent
, nativeParent
, aRect
, aInitData
))) {
469 return widget
.forget();
475 // Attach a view to our widget which we'll send events to.
476 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents
) {
477 NS_ASSERTION((mWindowType
== WindowType::TopLevel
||
478 mWindowType
== WindowType::Dialog
||
479 mWindowType
== WindowType::Invisible
||
480 mWindowType
== WindowType::Child
),
481 "Can't attach to window of that type");
483 mUseAttachedEvents
= aUseAttachedEvents
;
486 nsIWidgetListener
* nsBaseWidget::GetAttachedWidgetListener() const {
487 return mAttachedWidgetListener
;
490 nsIWidgetListener
* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
491 return mPreviouslyAttachedWidgetListener
;
494 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
495 nsIWidgetListener
* aListener
) {
496 mPreviouslyAttachedWidgetListener
= aListener
;
499 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener
* aListener
) {
500 mAttachedWidgetListener
= aListener
;
503 //-------------------------------------------------------------------------
505 // Close this nsBaseWidget
507 //-------------------------------------------------------------------------
508 void nsBaseWidget::Destroy() {
511 // Just in case our parent is the only ref to us
512 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
513 // disconnect from the parent
514 nsIWidget
* parent
= GetParent();
516 parent
->RemoveChild(this);
520 //-------------------------------------------------------------------------
522 // Get this nsBaseWidget parent
524 //-------------------------------------------------------------------------
525 nsIWidget
* nsBaseWidget::GetParent(void) { return nullptr; }
527 //-------------------------------------------------------------------------
529 // Get this nsBaseWidget top level widget
531 //-------------------------------------------------------------------------
532 nsIWidget
* nsBaseWidget::GetTopLevelWidget() {
533 nsIWidget
*topLevelWidget
= nullptr, *widget
= this;
535 topLevelWidget
= widget
;
536 widget
= widget
->GetParent();
538 return topLevelWidget
;
541 //-------------------------------------------------------------------------
543 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
545 //-------------------------------------------------------------------------
546 nsIWidget
* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
548 float nsBaseWidget::GetDPI() { return 96.0f
; }
550 void nsBaseWidget::NotifyAPZOfDPIChange() {
552 mAPZC
->SetDPI(GetDPI());
556 CSSToLayoutDeviceScale
nsIWidget::GetDefaultScale() {
557 double devPixelsPerCSSPixel
= StaticPrefs::layout_css_devPixelsPerPx();
559 if (devPixelsPerCSSPixel
<= 0.0) {
560 devPixelsPerCSSPixel
= GetDefaultScaleInternal();
563 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel
);
566 nsIntSize
nsIWidget::CustomCursorSize(const Cursor
& aCursor
) {
567 MOZ_ASSERT(aCursor
.IsCustom());
570 aCursor
.mContainer
->GetWidth(&width
);
571 aCursor
.mContainer
->GetHeight(&height
);
572 aCursor
.mResolution
.ApplyTo(width
, height
);
573 return {width
, height
};
576 LayoutDeviceIntSize
nsIWidget::ClientToWindowSizeDifference() {
577 auto margin
= ClientToWindowMargin();
578 MOZ_ASSERT(margin
.top
>= 0, "Window should be bigger than client area");
579 MOZ_ASSERT(margin
.left
>= 0, "Window should be bigger than client area");
580 MOZ_ASSERT(margin
.right
>= 0, "Window should be bigger than client area");
581 MOZ_ASSERT(margin
.bottom
>= 0, "Window should be bigger than client area");
582 return {margin
.LeftRight(), margin
.TopBottom()};
585 RefPtr
<mozilla::VsyncDispatcher
> nsIWidget::GetVsyncDispatcher() {
589 //-------------------------------------------------------------------------
591 // Add a child to the list of children
593 //-------------------------------------------------------------------------
594 void nsBaseWidget::AddChild(nsIWidget
* aChild
) {
595 MOZ_ASSERT(!aChild
->GetNextSibling() && !aChild
->GetPrevSibling(),
596 "aChild not properly removed from its old child list");
599 mFirstChild
= mLastChild
= aChild
;
601 // append to the list
602 MOZ_ASSERT(mLastChild
);
603 MOZ_ASSERT(!mLastChild
->GetNextSibling());
604 mLastChild
->SetNextSibling(aChild
);
605 aChild
->SetPrevSibling(mLastChild
);
610 //-------------------------------------------------------------------------
612 // Remove a child from the list of children
614 //-------------------------------------------------------------------------
615 void nsBaseWidget::RemoveChild(nsIWidget
* aChild
) {
618 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
619 // null and we'll just have to do without this assertion.
620 nsIWidget
* parent
= aChild
->GetParent();
621 NS_ASSERTION(!parent
|| parent
== this, "Not one of our kids!");
623 MOZ_RELEASE_ASSERT(aChild
->GetParent() == this, "Not one of our kids!");
627 if (mLastChild
== aChild
) {
628 mLastChild
= mLastChild
->GetPrevSibling();
630 if (mFirstChild
== aChild
) {
631 mFirstChild
= mFirstChild
->GetNextSibling();
634 // Now remove from the list. Make sure that we pass ownership of the tail
635 // of the list correctly before we have aChild let go of it.
636 nsIWidget
* prev
= aChild
->GetPrevSibling();
637 nsIWidget
* next
= aChild
->GetNextSibling();
639 prev
->SetNextSibling(next
);
642 next
->SetPrevSibling(prev
);
645 aChild
->SetNextSibling(nullptr);
646 aChild
->SetPrevSibling(nullptr);
649 void nsBaseWidget::GetWorkspaceID(nsAString
& workspaceID
) {
650 workspaceID
.Truncate();
653 void nsBaseWidget::MoveToWorkspace(const nsAString
& workspaceID
) {
657 //-------------------------------------------------------------------------
659 // Get this component cursor
661 //-------------------------------------------------------------------------
663 void nsBaseWidget::SetCursor(const Cursor
& aCursor
) { mCursor
= aCursor
; }
665 void nsBaseWidget::SetCustomCursorAllowed(bool aIsAllowed
) {
666 if (aIsAllowed
!= mCustomCursorAllowed
) {
667 mCustomCursorAllowed
= aIsAllowed
;
668 mUpdateCursor
= true;
673 //-------------------------------------------------------------------------
675 // Window transparency methods
677 //-------------------------------------------------------------------------
679 void nsBaseWidget::SetTransparencyMode(TransparencyMode aMode
) {}
681 TransparencyMode
nsBaseWidget::GetTransparencyMode() {
682 return TransparencyMode::Opaque
;
686 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage
,
689 nsIRunnable
* aCallback
) {
690 MOZ_ASSERT_UNREACHABLE(
691 "Should never call PerformFullscreenTransition on nsBaseWidget");
694 //-------------------------------------------------------------------------
696 // Put the window into full-screen mode
698 //-------------------------------------------------------------------------
699 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen
) {
700 #define MOZ_FORMAT_RECT(fmtstr) "[" fmtstr "," fmtstr " " fmtstr "x" fmtstr "]"
701 #define MOZ_SPLAT_RECT(rect) \
702 (rect).X(), (rect).Y(), (rect).Width(), (rect).Height()
704 // Windows which can be made fullscreen are exactly those which are located on
705 // the desktop, rather than being a child of some other window.
706 MOZ_DIAGNOSTIC_ASSERT(BoundsUseDesktopPixels(),
707 "non-desktop windows cannot be made fullscreen");
709 // Ensure that the OS chrome is hidden/shown before we resize and/or exit the
712 // HideWindowChrome() may (depending on platform, implementation details, and
713 // OS-level user preferences) alter the reported size of the window. The
714 // obvious and principled solution is socks-and-shoes:
715 // - On entering fullscreen mode: hide window chrome, then perform resize.
716 // - On leaving fullscreen mode: unperform resize, then show window chrome.
718 // ... unfortunately, HideWindowChrome() requires Resize() to be called
719 // afterwards (see bug 498835), which prevents this from being done in a
720 // straightforward way.
722 // Instead, we always call HideWindowChrome() just before we call Resize().
723 // This at least ensures that our measurements are consistently taken in a
724 // pre-transition state.
726 // ... unfortunately again, coupling HideWindowChrome() to Resize() means that
727 // we have to worry about the possibility of control flows that don't call
728 // Resize() at all. (That shouldn't happen, but it's not trivial to rule out.)
729 // We therefore set up a fallback to fix up the OS chrome if it hasn't been
730 // done at exit time.
731 bool hasAdjustedOSChrome
= false;
732 const auto adjustOSChrome
= [&]() {
733 if (hasAdjustedOSChrome
) {
734 MOZ_ASSERT_UNREACHABLE("window chrome should only be adjusted once");
737 HideWindowChrome(aFullScreen
);
738 hasAdjustedOSChrome
= true;
740 const auto adjustChromeOnScopeExit
= MakeScopeExit([&]() {
741 if (hasAdjustedOSChrome
) {
745 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
746 ("window was not resized within InfallibleMakeFullScreen()"));
748 // Hide chrome and "resize" the window to its current size.
749 auto rect
= GetBounds();
751 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
754 // Attempt to resize to `rect`.
756 // Returns the actual rectangle resized to. (This may differ from `rect`, if
757 // the OS is unhappy with it. See bug 1786226.)
758 const auto doReposition
= [&](auto rect
) -> void {
759 static_assert(std::is_base_of_v
<DesktopPixel
,
760 std::remove_reference_t
<decltype(rect
)>>,
761 "doReposition requires a rectangle using desktop pixels");
763 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Debug
)) {
764 const DesktopRect previousSize
=
765 GetScreenBounds() / GetDesktopToDeviceScale();
766 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
767 ("before resize: " MOZ_FORMAT_RECT("%f"),
768 MOZ_SPLAT_RECT(previousSize
)));
772 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
774 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Warning
)) {
775 // `rect` may have any underlying data type; coerce to float to
776 // simplify printf-style logging
777 const gfx::RectTyped
<DesktopPixel
, float> rectAsFloat
{rect
};
779 // The OS may have objected to the target position. That's not necessarily
780 // a problem -- it'll happen regularly on Macs with camera notches in the
781 // monitor, for instance (see bug 1786226) -- but it probably deserves to
784 // Since there's floating-point math involved, the actual values may be
785 // off by a few ulps -- as an upper bound, perhaps 8 * FLT_EPSILON *
786 // max(MOZ_SPLAT_RECT(rect)) -- but 0.01 should be several orders of
787 // magnitude bigger than that.
789 const auto postResizeRectRaw
= GetScreenBounds();
790 const auto postResizeRect
= postResizeRectRaw
/ GetDesktopToDeviceScale();
791 const bool succeeded
= postResizeRect
.WithinEpsilonOf(rectAsFloat
, 0.01);
794 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
795 ("resized to: " MOZ_FORMAT_RECT("%f"),
796 MOZ_SPLAT_RECT(rectAsFloat
)));
798 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
799 ("attempted to resize to: " MOZ_FORMAT_RECT("%f"),
800 MOZ_SPLAT_RECT(rectAsFloat
)));
801 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
802 ("... but ended up at: " MOZ_FORMAT_RECT("%f"),
803 MOZ_SPLAT_RECT(postResizeRect
)));
807 sBaseWidgetLog
, LogLevel::Verbose
,
808 ("(... which, before DPI adjustment, is:" MOZ_FORMAT_RECT("%d") ")",
809 MOZ_SPLAT_RECT(postResizeRectRaw
)));
815 mSavedBounds
= Some(FullscreenSavedState());
817 // save current position
818 mSavedBounds
->windowRect
= GetScreenBounds() / GetDesktopToDeviceScale();
820 nsCOMPtr
<nsIScreen
> screen
= GetWidgetScreen();
825 // Move to fill the screen.
826 doReposition(screen
->GetRectDisplayPix());
827 // Save off the new position. (This may differ from GetRectDisplayPix(), if
828 // the OS was unhappy with it. See bug 1786226.)
829 mSavedBounds
->screenRect
= GetScreenBounds() / GetDesktopToDeviceScale();
832 // This should never happen, at present, since we don't make windows
833 // fullscreen at their creation time; but it's not logically impossible.
834 MOZ_ASSERT(false, "fullscreen window did not have saved position");
838 // Figure out where to go from here.
840 // Fortunately, since we're currently fullscreen (and other code should be
841 // handling _keeping_ us fullscreen even after display-layout changes),
842 // there's an obvious choice for which display we should attach to; all we
843 // need to determine is where on that display we should go.
845 const DesktopRect currentWinRect
=
846 GetScreenBounds() / GetDesktopToDeviceScale();
848 // Optimization: if where we are is where we were, then where we originally
849 // came from is where we're going to go.
850 if (currentWinRect
== DesktopRect(mSavedBounds
->screenRect
)) {
851 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
852 ("no location change detected; returning to saved location"));
853 doReposition(mSavedBounds
->windowRect
);
858 General case: figure out where we're going to go by dividing where we are
859 by where we were, and then multiplying by where we originally came from.
861 Less abstrusely: resize so that we occupy the same proportional position
862 on our current display after leaving fullscreen as we occupied on our
863 previous display before entering fullscreen.
865 (N.B.: We do not clamp. If we were only partially on the old display,
866 we'll be only partially on the new one, too.)
869 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
870 ("location change detected; computing new destination"));
872 // splat: convert an arbitrary Rect into a tuple, for syntactic convenience.
873 const auto splat
= [](auto rect
) {
874 return std::tuple(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height());
877 // remap: find the unique affine mapping which transforms `src` to `dst`,
878 // and apply it to `val`.
879 using Range
= std::pair
<float, float>;
880 const auto remap
= [](Range dst
, Range src
, float val
) {
881 // linear interpolation and its inverse: lerp(a, b, invlerp(a, b, t)) == t
882 const auto lerp
= [](float lo
, float hi
, float t
) {
883 return lo
+ t
* (hi
- lo
);
885 const auto invlerp
= [](float lo
, float hi
, float mid
) {
886 return (mid
- lo
) / (hi
- lo
);
889 const auto [dst_a
, dst_b
] = dst
;
890 const auto [src_a
, src_b
] = src
;
891 return lerp(dst_a
, dst_b
, invlerp(src_a
, src_b
, val
));
895 const auto [px
, py
, pw
, ph
] = splat(mSavedBounds
->windowRect
);
896 // source desktop rect
897 const auto [sx
, sy
, sw
, sh
] = splat(mSavedBounds
->screenRect
);
898 // target desktop rect
899 const auto [tx
, ty
, tw
, th
] = splat(currentWinRect
);
901 const float nx
= remap({tx
, tx
+ tw
}, {sx
, sx
+ sw
}, px
);
902 const float ny
= remap({ty
, ty
+ th
}, {sy
, sy
+ sh
}, py
);
903 const float nw
= remap({0, tw
}, {0, sw
}, pw
);
904 const float nh
= remap({0, th
}, {0, sh
}, ph
);
906 doReposition(DesktopRect
{nx
, ny
, nw
, nh
});
909 #undef MOZ_SPLAT_RECT
910 #undef MOZ_FORMAT_RECT
913 nsresult
nsBaseWidget::MakeFullScreen(bool aFullScreen
) {
914 InfallibleMakeFullScreen(aFullScreen
);
918 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
919 nsBaseWidget
* aWidget
, gfxContext
* aTarget
, BufferMode aDoubleBuffering
)
921 WindowRenderer
* renderer
= mWidget
->GetWindowRenderer();
922 if (renderer
->AsFallback()) {
923 mRenderer
= renderer
->AsFallback();
924 mRenderer
->SetTarget(aTarget
, aDoubleBuffering
);
928 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
930 mRenderer
->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE
);
934 bool nsBaseWidget::IsSmallPopup() const {
935 return mWindowType
== WindowType::Popup
&& mPopupType
!= PopupType::Panel
;
938 bool nsBaseWidget::ComputeShouldAccelerate() {
939 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING
) &&
940 (WidgetTypeSupportsAcceleration() ||
941 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
944 bool nsBaseWidget::UseAPZ() {
945 return (gfxPlatform::AsyncPanZoomEnabled() &&
946 (mWindowType
== WindowType::TopLevel
||
947 mWindowType
== WindowType::Child
||
948 ((mWindowType
== WindowType::Popup
||
949 mWindowType
== WindowType::Dialog
) &&
950 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
953 void nsBaseWidget::CreateCompositor() {
954 LayoutDeviceIntRect rect
= GetBounds();
955 CreateCompositor(rect
.Width(), rect
.Height());
958 void nsIWidget::PauseOrResumeCompositor(bool aPause
) {
959 auto* renderer
= GetRemoteRenderer();
964 renderer
->SendPause();
966 renderer
->SendResume();
970 already_AddRefed
<GeckoContentController
>
971 nsBaseWidget::CreateRootContentController() {
972 RefPtr
<GeckoContentController
> controller
=
973 new ChromeProcessController(this, mAPZEventState
, mAPZC
);
974 return controller
.forget();
977 void nsBaseWidget::ConfigureAPZCTreeManager() {
978 MOZ_ASSERT(NS_IsMainThread());
981 mAPZC
->SetDPI(GetDPI());
983 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
984 KeyboardMap map
= RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
985 mAPZC
->SetKeyboardMap(map
);
988 ContentReceivedInputBlockCallback
callback(
989 [treeManager
= RefPtr
{mAPZC
.get()}](uint64_t aInputBlockId
,
990 bool aPreventDefault
) {
991 MOZ_ASSERT(NS_IsMainThread());
992 treeManager
->ContentReceivedInputBlock(aInputBlockId
, aPreventDefault
);
994 mAPZEventState
= new APZEventState(this, std::move(callback
));
996 mRootContentController
= CreateRootContentController();
997 if (mRootContentController
) {
998 mCompositorSession
->SetContentController(mRootContentController
);
1001 // When APZ is enabled, we can actually enable raw touch events because we
1002 // have code that can deal with them properly. If APZ is not enabled, this
1003 // function doesn't get called.
1004 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
1005 RegisterTouchWindow();
1009 void nsBaseWidget::ConfigureAPZControllerThread() {
1010 // By default the controller thread is the main thread.
1011 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
1014 void nsBaseWidget::SetConfirmedTargetAPZC(
1015 uint64_t aInputBlockId
,
1016 const nsTArray
<ScrollableLayerGuid
>& aTargets
) const {
1017 mAPZC
->SetTargetAPZC(aInputBlockId
, aTargets
);
1020 void nsBaseWidget::UpdateZoomConstraints(
1021 const uint32_t& aPresShellId
, const ScrollableLayerGuid::ViewID
& aViewId
,
1022 const Maybe
<ZoomConstraints
>& aConstraints
) {
1023 if (!mCompositorSession
|| !mAPZC
) {
1024 MOZ_ASSERT_IF(mInitialZoomConstraints
,
1025 mInitialZoomConstraints
->mViewID
== aViewId
);
1027 // We have some constraints, but the compositor and APZC aren't
1028 // created yet. Save these so we can use them later.
1029 mInitialZoomConstraints
= Some(
1030 InitialZoomConstraints(aPresShellId
, aViewId
, aConstraints
.ref()));
1032 mInitialZoomConstraints
.reset();
1036 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1037 mAPZC
->UpdateZoomConstraints(
1038 ScrollableLayerGuid(layersId
, aPresShellId
, aViewId
), aConstraints
);
1041 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC
; }
1043 nsEventStatus
nsBaseWidget::ProcessUntransformedAPZEvent(
1044 WidgetInputEvent
* aEvent
, const APZEventResult
& aApzResult
) {
1045 MOZ_ASSERT(NS_IsMainThread());
1046 ScrollableLayerGuid targetGuid
= aApzResult
.mTargetGuid
;
1047 uint64_t inputBlockId
= aApzResult
.mInputBlockId
;
1048 InputAPZContext
context(aApzResult
.mTargetGuid
, inputBlockId
,
1049 aApzResult
.GetStatus());
1051 // Make a copy of the original event for the APZCCallbackHelper helpers that
1052 // we call later, because the event passed to DispatchEvent can get mutated in
1053 // ways that we don't want (i.e. touch points can get stripped out).
1054 nsEventStatus status
;
1055 UniquePtr
<WidgetEvent
> original(aEvent
->Duplicate());
1056 DispatchEvent(aEvent
, status
);
1058 if (mAPZC
&& !InputAPZContext::WasRoutedToChildProcess() &&
1059 !InputAPZContext::WasDropped() && inputBlockId
) {
1060 // EventStateManager did not route the event into the child process and
1061 // the event was dispatched in the parent process.
1062 // It's safe to communicate to APZ that the event has been processed.
1063 // Note that here aGuid.mLayersId might be different from
1064 // mCompositorSession->RootLayerTreeId() because the event might have gotten
1065 // hit-tested by APZ to be targeted at a child process, but a parent process
1066 // event listener called preventDefault on it. In that case aGuid.mLayersId
1067 // would still be the layers id for the child process, but the event would
1068 // not have actually gotten routed to the child process. The main-thread
1069 // hit-test result therefore needs to use the parent process layers id.
1070 LayersId rootLayersId
= mCompositorSession
->RootLayerTreeId();
1072 RefPtr
<DisplayportSetListener
> postLayerization
;
1073 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1074 nsTArray
<TouchBehaviorFlags
> allowedTouchBehaviors
;
1075 if (touchEvent
->mMessage
== eTouchStart
) {
1076 auto& originalEvent
= *original
->AsTouchEvent();
1077 MOZ_ASSERT(NS_IsMainThread());
1078 allowedTouchBehaviors
= TouchActionHelper::GetAllowedTouchBehavior(
1079 this, GetDocument(), originalEvent
);
1080 if (!allowedTouchBehaviors
.IsEmpty()) {
1081 mAPZC
->SetAllowedTouchBehavior(inputBlockId
, allowedTouchBehaviors
);
1083 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1084 this, GetDocument(), originalEvent
, rootLayersId
, inputBlockId
);
1086 mAPZEventState
->ProcessTouchEvent(*touchEvent
, targetGuid
, inputBlockId
,
1087 aApzResult
.GetStatus(), status
,
1088 std::move(allowedTouchBehaviors
));
1089 } else if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1090 MOZ_ASSERT(wheelEvent
->mFlags
.mHandledByAPZ
);
1091 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1092 this, GetDocument(), *original
->AsWheelEvent(), rootLayersId
,
1094 if (wheelEvent
->mCanTriggerSwipe
) {
1095 ReportSwipeStarted(inputBlockId
, wheelEvent
->TriggersSwipe());
1097 mAPZEventState
->ProcessWheelEvent(*wheelEvent
, inputBlockId
);
1098 } else if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1099 MOZ_ASSERT(mouseEvent
->mFlags
.mHandledByAPZ
);
1100 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1101 this, GetDocument(), *original
->AsMouseEvent(), rootLayersId
,
1103 mAPZEventState
->ProcessMouseEvent(*mouseEvent
, inputBlockId
);
1105 if (postLayerization
) {
1106 postLayerization
->Register();
1113 template <class InputType
, class EventType
>
1114 class DispatchEventOnMainThread
: public Runnable
{
1116 DispatchEventOnMainThread(const InputType
& aInput
, nsBaseWidget
* aWidget
,
1117 const APZEventResult
& aAPZResult
)
1118 : mozilla::Runnable("DispatchEventOnMainThread"),
1121 mAPZResult(aAPZResult
) {}
1123 NS_IMETHOD
Run() override
{
1124 EventType event
= mInput
.ToWidgetEvent(mWidget
);
1125 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1131 nsBaseWidget
* mWidget
;
1132 APZEventResult mAPZResult
;
1136 NS_IMETHODIMP DispatchEventOnMainThread
<MouseInput
, WidgetMouseEvent
>::Run() {
1138 !mInput
.IsPointerEventType(),
1139 "Please use DispatchEventOnMainThread<MouseInput, WidgetPointerEvent>");
1140 WidgetMouseEvent event
= mInput
.ToWidgetEvent
<WidgetMouseEvent
>(mWidget
);
1141 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1146 NS_IMETHODIMP DispatchEventOnMainThread
<MouseInput
, WidgetPointerEvent
>::Run() {
1148 mInput
.IsPointerEventType(),
1149 "Please use DispatchEventOnMainThread<MouseInput, WidgetMouseEvent>");
1150 WidgetPointerEvent event
= mInput
.ToWidgetEvent
<WidgetPointerEvent
>(mWidget
);
1151 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1155 template <class InputType
, class EventType
>
1156 class DispatchInputOnControllerThread
: public Runnable
{
1158 enum class APZOnly
{ Yes
, No
};
1159 DispatchInputOnControllerThread(const EventType
& aEvent
,
1160 IAPZCTreeManager
* aAPZC
,
1161 nsBaseWidget
* aWidget
,
1162 APZOnly aAPZOnly
= APZOnly::No
)
1163 : mozilla::Runnable("DispatchInputOnControllerThread"),
1164 mMainMessageLoop(MessageLoop::current()),
1168 mAPZOnly(aAPZOnly
) {}
1170 NS_IMETHOD
Run() override
{
1171 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(mInput
);
1172 if (mAPZOnly
== APZOnly::Yes
||
1173 result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1176 RefPtr
<Runnable
> r
= new DispatchEventOnMainThread
<InputType
, EventType
>(
1177 mInput
, mWidget
, result
);
1178 mMainMessageLoop
->PostTask(r
.forget());
1183 MessageLoop
* mMainMessageLoop
;
1185 RefPtr
<IAPZCTreeManager
> mAPZC
;
1186 nsBaseWidget
* mWidget
;
1187 const APZOnly mAPZOnly
;
1190 void nsBaseWidget::DispatchTouchInput(MultiTouchInput
& aInput
,
1191 uint16_t aInputSource
) {
1192 MOZ_ASSERT(NS_IsMainThread());
1193 MOZ_ASSERT(aInputSource
==
1194 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH
||
1195 aInputSource
== mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN
);
1197 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1199 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1200 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1204 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1205 ProcessUntransformedAPZEvent(&event
, result
);
1207 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1209 nsEventStatus status
;
1210 DispatchEvent(&event
, status
);
1214 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput
& aInput
) {
1215 MOZ_ASSERT(NS_IsMainThread());
1217 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1219 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1220 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1224 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1225 ProcessUntransformedAPZEvent(&event
, result
);
1227 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1228 nsEventStatus status
;
1229 DispatchEvent(&event
, status
);
1233 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput
& aInput
) {
1234 MOZ_ASSERT(NS_IsMainThread());
1236 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1237 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1239 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1242 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1243 ProcessUntransformedAPZEvent(&event
, result
);
1245 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1246 nsEventStatus status
;
1247 DispatchEvent(&event
, status
);
1251 nsIWidget::ContentAndAPZEventStatus
nsBaseWidget::DispatchInputEvent(
1252 WidgetInputEvent
* aEvent
) {
1253 nsIWidget::ContentAndAPZEventStatus status
;
1254 MOZ_ASSERT(NS_IsMainThread());
1257 if (APZThreadUtils::IsControllerThread()) {
1258 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1259 status
.mApzStatus
= result
.GetStatus();
1260 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1263 status
.mContentStatus
= ProcessUntransformedAPZEvent(aEvent
, result
);
1266 // Most drag events aren't able to converted to MouseEvent except to
1267 // eDragStart and eDragEnd.
1268 const bool canDispatchToApzc
=
1269 !aEvent
->AsDragEvent() ||
1270 aEvent
->AsDragEvent()->CanConvertToInputData();
1271 if (canDispatchToApzc
) {
1272 if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1273 RefPtr
<Runnable
> r
=
1274 new DispatchInputOnControllerThread
<ScrollWheelInput
,
1275 WidgetWheelEvent
>(*wheelEvent
,
1277 APZThreadUtils::RunOnControllerThread(std::move(r
));
1278 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1281 if (WidgetPointerEvent
* pointerEvent
= aEvent
->AsPointerEvent()) {
1282 MOZ_ASSERT(aEvent
->mMessage
== eContextMenu
);
1283 RefPtr
<Runnable
> r
=
1284 new DispatchInputOnControllerThread
<MouseInput
, WidgetPointerEvent
>(
1285 *pointerEvent
, mAPZC
, this);
1286 APZThreadUtils::RunOnControllerThread(std::move(r
));
1287 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1290 if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1291 RefPtr
<Runnable
> r
=
1292 new DispatchInputOnControllerThread
<MouseInput
, WidgetMouseEvent
>(
1293 *mouseEvent
, mAPZC
, this);
1294 APZThreadUtils::RunOnControllerThread(std::move(r
));
1295 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1298 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1299 RefPtr
<Runnable
> r
=
1300 new DispatchInputOnControllerThread
<MultiTouchInput
,
1301 WidgetTouchEvent
>(*touchEvent
,
1303 APZThreadUtils::RunOnControllerThread(std::move(r
));
1304 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1307 // Allow dispatching keyboard/drag events on Gecko thread
1308 // without sending them to APZ
1310 // FIXME: APZ can handle keyboard events now, we should
1311 // be sending them to APZ here
1312 MOZ_ASSERT(aEvent
->AsKeyboardEvent() || aEvent
->AsDragEvent());
1316 DispatchEvent(aEvent
, status
.mContentStatus
);
1320 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent
* aEvent
) {
1321 MOZ_ASSERT(NS_IsMainThread());
1323 if (APZThreadUtils::IsControllerThread()) {
1324 mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1328 if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1329 RefPtr
<Runnable
> r
=
1330 new DispatchInputOnControllerThread
<MouseInput
, WidgetMouseEvent
>(
1331 *mouseEvent
, mAPZC
, this,
1332 DispatchInputOnControllerThread
<MouseInput
,
1333 WidgetMouseEvent
>::APZOnly::Yes
);
1334 APZThreadUtils::RunOnControllerThread(std::move(r
));
1338 MOZ_ASSERT_UNREACHABLE("Not implemented yet");
1342 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent
& event
) {
1343 nsEventStatus status
;
1344 DispatchEvent(&event
, status
);
1345 return ConvertStatus(status
);
1348 Document
* nsBaseWidget::GetDocument() const {
1349 if (mWidgetListener
) {
1350 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1351 return presShell
->GetDocument();
1357 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1358 // Parent directly listens to the vsync source whereas
1359 // child process communicate via IPC
1360 // Should be called AFTER gfxPlatform is initialized
1361 if (XRE_IsParentProcess()) {
1362 if (!mCompositorVsyncDispatcherLock
) {
1363 mCompositorVsyncDispatcherLock
=
1364 MakeUnique
<Mutex
>("mCompositorVsyncDispatcherLock");
1366 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1367 if (!mCompositorVsyncDispatcher
) {
1368 RefPtr
<VsyncDispatcher
> vsyncDispatcher
=
1369 gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
1370 mCompositorVsyncDispatcher
=
1371 new CompositorVsyncDispatcher(std::move(vsyncDispatcher
));
1376 already_AddRefed
<CompositorVsyncDispatcher
>
1377 nsBaseWidget::GetCompositorVsyncDispatcher() {
1378 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
1380 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1381 RefPtr
<CompositorVsyncDispatcher
> dispatcher
= mCompositorVsyncDispatcher
;
1382 return dispatcher
.forget();
1385 already_AddRefed
<WebRenderLayerManager
> nsBaseWidget::CreateCompositorSession(
1386 int aWidth
, int aHeight
, CompositorOptions
* aOptionsOut
) {
1387 MOZ_ASSERT(aOptionsOut
);
1390 CreateCompositorVsyncDispatcher();
1392 gfx::GPUProcessManager
* gpu
= gfx::GPUProcessManager::Get();
1393 // Make sure GPU process is ready for use.
1394 // If it failed to connect to GPU process, GPU process usage is disabled in
1395 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1396 nsresult rv
= gpu
->EnsureGPUReady();
1397 if (NS_WARN_IF(rv
== NS_ERROR_ILLEGAL_DURING_SHUTDOWN
)) {
1401 // If widget type does not supports acceleration, we may be allowed to use
1402 // software WebRender instead.
1403 bool supportsAcceleration
= WidgetTypeSupportsAcceleration();
1404 bool enableSWWR
= true;
1405 if (supportsAcceleration
||
1406 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1407 enableSWWR
= gfx::gfxVars::UseSoftwareWebRender();
1409 bool enableAPZ
= UseAPZ();
1410 CompositorOptions
options(enableAPZ
, enableSWWR
);
1413 if (supportsAcceleration
) {
1414 options
.SetAllowSoftwareWebRenderD3D11(
1415 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1417 if (mNeedFastSnaphot
) {
1418 options
.SetNeedFastSnaphot(true);
1420 #elif defined(MOZ_WIDGET_ANDROID)
1421 MOZ_ASSERT(supportsAcceleration
);
1422 options
.SetAllowSoftwareWebRenderOGL(
1423 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1424 #elif defined(MOZ_WIDGET_GTK)
1425 if (supportsAcceleration
) {
1426 options
.SetAllowSoftwareWebRenderOGL(
1427 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1431 #ifdef MOZ_WIDGET_ANDROID
1432 // Unconditionally set the compositor as initially paused, as we have not
1433 // yet had a chance to send the compositor surface to the GPU process. We
1434 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1435 // where we will also resume the compositor if required.
1436 options
.SetInitiallyPaused(true);
1438 options
.SetInitiallyPaused(CompositorInitiallyPaused());
1441 RefPtr
<WebRenderLayerManager
> lm
= new WebRenderLayerManager(this);
1443 uint64_t innerWindowId
= 0;
1444 if (Document
* doc
= GetDocument()) {
1445 innerWindowId
= doc
->InnerWindowID();
1449 mCompositorSession
= gpu
->CreateTopLevelCompositor(
1450 this, lm
, GetDefaultScale(), options
, UseExternalCompositingSurface(),
1451 gfx::IntSize(aWidth
, aHeight
), innerWindowId
, &retry
);
1453 if (mCompositorSession
) {
1454 TextureFactoryIdentifier textureFactoryIdentifier
;
1456 lm
->Initialize(mCompositorSession
->GetCompositorBridgeChild(),
1457 wr::AsPipelineId(mCompositorSession
->RootLayerTreeId()),
1458 &textureFactoryIdentifier
, error
);
1459 if (textureFactoryIdentifier
.mParentBackend
!= LayersBackend::LAYERS_WR
) {
1461 DestroyCompositor();
1462 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1463 gfx::GPUProcessManager::Get()->DisableWebRender(
1464 wr::WebRenderError::INITIALIZE
, error
);
1468 // We need to retry in a loop because the act of failing to create the
1469 // compositor can change our state (e.g. disable WebRender).
1470 if (mCompositorSession
|| !retry
) {
1471 *aOptionsOut
= options
;
1477 void nsBaseWidget::CreateCompositor(int aWidth
, int aHeight
) {
1478 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1479 gfxPlatform::GetPlatform();
1481 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1482 "This function assumes OMTC");
1484 MOZ_ASSERT(!mCompositorSession
&& !mCompositorBridgeChild
,
1485 "Should have properly cleaned up the previous PCompositor pair "
1488 if (mCompositorBridgeChild
) {
1489 mCompositorBridgeChild
->Destroy();
1492 // Recreating this is tricky, as we may still have an old and we need
1493 // to make sure it's properly destroyed by calling DestroyCompositor!
1495 // If we've already received a shutdown notification, don't try
1496 // create a new compositor.
1497 if (!mShutdownObserver
) {
1501 // The controller thread must be configured before the compositor
1502 // session is created, so that the input bridge runs on the right
1504 ConfigureAPZControllerThread();
1506 CompositorOptions options
;
1507 RefPtr
<WebRenderLayerManager
> lm
=
1508 CreateCompositorSession(aWidth
, aHeight
, &options
);
1513 MOZ_ASSERT(mCompositorSession
);
1514 mCompositorBridgeChild
= mCompositorSession
->GetCompositorBridgeChild();
1515 SetCompositorWidgetDelegate(
1516 mCompositorSession
->GetCompositorWidgetDelegate());
1518 if (options
.UseAPZ()) {
1519 mAPZC
= mCompositorSession
->GetAPZCTreeManager();
1520 ConfigureAPZCTreeManager();
1525 if (mInitialZoomConstraints
) {
1526 UpdateZoomConstraints(mInitialZoomConstraints
->mPresShellID
,
1527 mInitialZoomConstraints
->mViewID
,
1528 Some(mInitialZoomConstraints
->mConstraints
));
1529 mInitialZoomConstraints
.reset();
1532 TextureFactoryIdentifier textureFactoryIdentifier
=
1533 lm
->GetTextureFactoryIdentifier();
1534 MOZ_ASSERT(textureFactoryIdentifier
.mParentBackend
==
1535 LayersBackend::LAYERS_WR
);
1536 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier
);
1537 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier
);
1541 mWindowRenderer
= std::move(lm
);
1543 // Only track compositors for top-level windows, since other window types
1544 // may use the basic compositor. Except on the OS X - see bug 1306383
1545 #if defined(XP_MACOSX)
1546 bool getCompositorFromThisWindow
= true;
1548 bool getCompositorFromThisWindow
= mWindowType
== WindowType::TopLevel
;
1551 if (getCompositorFromThisWindow
) {
1552 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1553 mWindowRenderer
->GetCompositorBackendType());
1557 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession
* aSession
) {
1558 MOZ_ASSERT(aSession
== mCompositorSession
);
1559 DestroyLayerManager();
1562 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1563 return gfxPlatform::UsesOffMainThreadCompositing();
1566 WindowRenderer
* nsBaseWidget::GetWindowRenderer() {
1567 if (!mWindowRenderer
) {
1568 if (!mShutdownObserver
) {
1569 // We are shutting down, do not try to re-create a LayerManager
1572 // Try to use an async compositor first, if possible
1573 if (ShouldUseOffMainThreadCompositing()) {
1577 if (!mWindowRenderer
) {
1578 mWindowRenderer
= CreateFallbackRenderer();
1581 return mWindowRenderer
;
1584 WindowRenderer
* nsBaseWidget::CreateFallbackRenderer() {
1585 return new FallbackRenderer
;
1588 CompositorBridgeChild
* nsBaseWidget::GetRemoteRenderer() {
1589 return mCompositorBridgeChild
;
1592 void nsBaseWidget::ClearCachedWebrenderResources() {
1593 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1596 mWindowRenderer
->AsWebRender()->ClearCachedResources();
1599 void nsBaseWidget::ClearWebrenderAnimationResources() {
1600 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1603 mWindowRenderer
->AsWebRender()->ClearAnimationResources();
1606 bool nsBaseWidget::SetNeedFastSnaphot() {
1607 MOZ_ASSERT(XRE_IsParentProcess());
1608 MOZ_ASSERT(!mCompositorSession
);
1610 if (!XRE_IsParentProcess() || mCompositorSession
) {
1614 mNeedFastSnaphot
= true;
1618 already_AddRefed
<gfx::DrawTarget
> nsBaseWidget::StartRemoteDrawing() {
1622 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA
; }
1624 //-------------------------------------------------------------------------
1626 // Destroy the window
1628 //-------------------------------------------------------------------------
1629 void nsBaseWidget::OnDestroy() {
1630 if (mTextEventDispatcher
) {
1631 mTextEventDispatcher
->OnDestroyWidget();
1632 // Don't release it until this widget actually released because after this
1633 // is called, TextEventDispatcher() may create it again.
1636 // If this widget is being destroyed, let the APZ code know to drop references
1637 // to this widget. Callers of this function all should be holding a deathgrip
1638 // on this widget already.
1639 ReleaseContentController();
1642 void nsBaseWidget::MoveClient(const DesktopPoint
& aOffset
) {
1643 LayoutDeviceIntPoint
clientOffset(GetClientOffset());
1645 // GetClientOffset returns device pixels; scale back to desktop pixels
1646 // if that's what this widget uses for the Move/Resize APIs
1647 if (BoundsUseDesktopPixels()) {
1648 DesktopPoint desktopOffset
= clientOffset
/ GetDesktopToDeviceScale();
1649 Move(aOffset
.x
- desktopOffset
.x
, aOffset
.y
- desktopOffset
.y
);
1651 LayoutDevicePoint layoutOffset
= aOffset
* GetDesktopToDeviceScale();
1652 Move(layoutOffset
.x
- LayoutDeviceCoord(clientOffset
.x
),
1653 layoutOffset
.y
- LayoutDeviceCoord(clientOffset
.y
));
1657 void nsBaseWidget::ResizeClient(const DesktopSize
& aSize
, bool aRepaint
) {
1658 NS_ASSERTION((aSize
.width
>= 0), "Negative width passed to ResizeClient");
1659 NS_ASSERTION((aSize
.height
>= 0), "Negative height passed to ResizeClient");
1661 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1663 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1664 // if that's what this widget uses for the Move/Resize APIs
1665 if (BoundsUseDesktopPixels()) {
1666 DesktopSize desktopDelta
=
1667 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1668 clientBounds
.Size()) /
1669 GetDesktopToDeviceScale();
1670 Resize(aSize
.width
+ desktopDelta
.width
, aSize
.height
+ desktopDelta
.height
,
1673 LayoutDeviceSize layoutSize
= aSize
* GetDesktopToDeviceScale();
1674 Resize(mBounds
.Width() + (layoutSize
.width
- clientBounds
.Width()),
1675 mBounds
.Height() + (layoutSize
.height
- clientBounds
.Height()),
1680 void nsBaseWidget::ResizeClient(const DesktopRect
& aRect
, bool aRepaint
) {
1681 NS_ASSERTION((aRect
.Width() >= 0), "Negative width passed to ResizeClient");
1682 NS_ASSERTION((aRect
.Height() >= 0), "Negative height passed to ResizeClient");
1684 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1685 LayoutDeviceIntPoint clientOffset
= GetClientOffset();
1686 DesktopToLayoutDeviceScale scale
= GetDesktopToDeviceScale();
1688 if (BoundsUseDesktopPixels()) {
1689 DesktopPoint desktopOffset
= clientOffset
/ scale
;
1690 DesktopSize desktopDelta
=
1691 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1692 clientBounds
.Size()) /
1694 Resize(aRect
.X() - desktopOffset
.x
, aRect
.Y() - desktopOffset
.y
,
1695 aRect
.Width() + desktopDelta
.width
,
1696 aRect
.Height() + desktopDelta
.height
, aRepaint
);
1698 LayoutDeviceRect layoutRect
= aRect
* scale
;
1699 Resize(layoutRect
.X() - clientOffset
.x
, layoutRect
.Y() - clientOffset
.y
,
1700 layoutRect
.Width() + mBounds
.Width() - clientBounds
.Width(),
1701 layoutRect
.Height() + mBounds
.Height() - clientBounds
.Height(),
1706 //-------------------------------------------------------------------------
1710 //-------------------------------------------------------------------------
1713 * If the implementation of nsWindow supports borders this method MUST be
1717 LayoutDeviceIntRect
nsBaseWidget::GetClientBounds() { return GetBounds(); }
1720 * If the implementation of nsWindow supports borders this method MUST be
1724 LayoutDeviceIntRect
nsBaseWidget::GetBounds() { return mBounds
; }
1727 * If the implementation of nsWindow uses a local coordinate system within the
1728 *window, this method must be overridden
1731 LayoutDeviceIntRect
nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1733 nsresult
nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect
& aRect
) {
1734 if (SizeMode() != nsSizeMode_Normal
) {
1735 return NS_ERROR_FAILURE
;
1737 aRect
= GetScreenBounds();
1741 LayoutDeviceIntPoint
nsBaseWidget::GetClientOffset() {
1742 return LayoutDeviceIntPoint(0, 0);
1745 nsresult
nsBaseWidget::SetNonClientMargins(const LayoutDeviceIntMargin
&) {
1746 return NS_ERROR_NOT_IMPLEMENTED
;
1749 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin
) {}
1751 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1753 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1755 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect
* aResizerRect
) {
1760 * Modifies aFile to point at an icon file with the given name and suffix. The
1761 * suffix may correspond to a file extension with leading '.' if appropriate.
1762 * Returns true if the icon file exists and can be read.
1764 static bool ResolveIconNameHelper(nsIFile
* aFile
, const nsAString
& aIconName
,
1765 const nsAString
& aIconSuffix
) {
1766 aFile
->Append(u
"icons"_ns
);
1767 aFile
->Append(u
"default"_ns
);
1768 aFile
->Append(aIconName
+ aIconSuffix
);
1771 return NS_SUCCEEDED(aFile
->IsReadable(&readable
)) && readable
;
1775 * Resolve the given icon name into a local file object. This method is
1776 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1777 * platform specific icon file suffix (e.g., ".ico" under Win32).
1779 * If no file is found matching the given parameters, then null is returned.
1781 void nsBaseWidget::ResolveIconName(const nsAString
& aIconName
,
1782 const nsAString
& aIconSuffix
,
1783 nsIFile
** aResult
) {
1786 nsCOMPtr
<nsIProperties
> dirSvc
=
1787 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID
);
1788 if (!dirSvc
) return;
1790 // first check auxilary chrome directories
1792 nsCOMPtr
<nsISimpleEnumerator
> dirs
;
1793 dirSvc
->Get(NS_APP_CHROME_DIR_LIST
, NS_GET_IID(nsISimpleEnumerator
),
1794 getter_AddRefs(dirs
));
1797 while (NS_SUCCEEDED(dirs
->HasMoreElements(&hasMore
)) && hasMore
) {
1798 nsCOMPtr
<nsISupports
> element
;
1799 dirs
->GetNext(getter_AddRefs(element
));
1800 if (!element
) continue;
1801 nsCOMPtr
<nsIFile
> file
= do_QueryInterface(element
);
1802 if (!file
) continue;
1803 if (ResolveIconNameHelper(file
, aIconName
, aIconSuffix
)) {
1804 NS_ADDREF(*aResult
= file
);
1810 // then check the main app chrome directory
1812 nsCOMPtr
<nsIFile
> file
;
1813 dirSvc
->Get(NS_APP_CHROME_DIR
, NS_GET_IID(nsIFile
), getter_AddRefs(file
));
1814 if (file
&& ResolveIconNameHelper(file
, aIconName
, aIconSuffix
))
1815 NS_ADDREF(*aResult
= file
);
1818 void nsBaseWidget::SetSizeConstraints(const SizeConstraints
& aConstraints
) {
1819 mSizeConstraints
= aConstraints
;
1821 // Popups are constrained during layout, and we don't want to synchronously
1822 // paint from reflow, so bail out... This is not great, but it's no worse than
1823 // what we used to do.
1825 // The right fix here is probably making constraint changes go through the
1826 // view manager and such.
1827 if (mWindowType
== WindowType::Popup
) {
1831 // If the current size doesn't meet the new constraints, trigger a
1832 // resize to apply it. Note that, we don't want to invoke Resize if
1833 // the new constraints don't affect the current size, because Resize
1834 // implementation on some platforms may touch other geometry even if
1835 // the size don't need to change.
1836 LayoutDeviceIntSize curSize
= mBounds
.Size();
1837 LayoutDeviceIntSize clampedSize
=
1838 Max(aConstraints
.mMinSize
, Min(aConstraints
.mMaxSize
, curSize
));
1839 if (clampedSize
!= curSize
) {
1841 if (BoundsUseDesktopPixels()) {
1842 DesktopSize desktopSize
= clampedSize
/ GetDesktopToDeviceScale();
1843 size
= desktopSize
.ToUnknownSize();
1845 size
= gfx::Size(clampedSize
.ToUnknownSize());
1847 Resize(size
.width
, size
.height
, true);
1851 const widget::SizeConstraints
nsBaseWidget::GetSizeConstraints() {
1852 return mSizeConstraints
;
1856 nsIRollupListener
* nsBaseWidget::GetActiveRollupListener() {
1857 // TODO: Simplify this.
1858 return nsXULPopupManager::GetInstance();
1861 void nsBaseWidget::NotifyWindowDestroyed() {
1862 if (!mWidgetListener
) return;
1864 nsCOMPtr
<nsIAppWindow
> window
= mWidgetListener
->GetAppWindow();
1865 nsCOMPtr
<nsIBaseWindow
> appWindow(do_QueryInterface(window
));
1867 appWindow
->Destroy();
1871 void nsBaseWidget::NotifyWindowMoved(int32_t aX
, int32_t aY
,
1872 ByMoveToRect aByMoveToRect
) {
1873 if (mWidgetListener
) {
1874 mWidgetListener
->WindowMoved(this, aX
, aY
, aByMoveToRect
);
1877 if (mIMEHasFocus
&& IMENotificationRequestsRef().WantPositionChanged()) {
1878 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE
));
1882 void nsBaseWidget::NotifySizeMoveDone() {
1883 if (!mWidgetListener
) {
1886 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1887 presShell
->WindowSizeMoveDone();
1891 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind
) {
1892 LookAndFeel::NotifyChangedAllWindows(aKind
);
1895 nsresult
nsBaseWidget::NotifyIME(const IMENotification
& aIMENotification
) {
1899 switch (aIMENotification
.mMessage
) {
1900 case REQUEST_TO_COMMIT_COMPOSITION
:
1901 case REQUEST_TO_CANCEL_COMPOSITION
:
1902 // We should send request to IME only when there is a TextEventDispatcher
1903 // instance (this means that this widget has dispatched at least one
1904 // composition event or keyboard event) and the it has composition.
1905 // Otherwise, there is nothing to do.
1906 // Note that if current input transaction is for native input events,
1907 // TextEventDispatcher::NotifyIME() will call
1908 // TextEventDispatcherListener::NotifyIME().
1909 if (mTextEventDispatcher
&& mTextEventDispatcher
->IsComposing()) {
1910 return mTextEventDispatcher
->NotifyIME(aIMENotification
);
1914 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_FOCUS
) {
1915 mIMEHasFocus
= true;
1917 EnsureTextEventDispatcher();
1918 // TextEventDispatcher::NotifyIME() will always call
1919 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1920 // input transaction is for synthesized events for automated tests,
1921 // notifications will be sent to native IME.
1922 nsresult rv
= mTextEventDispatcher
->NotifyIME(aIMENotification
);
1923 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_BLUR
) {
1924 mIMEHasFocus
= false;
1931 void nsBaseWidget::EnsureTextEventDispatcher() {
1932 if (mTextEventDispatcher
) {
1935 mTextEventDispatcher
= new TextEventDispatcher(this);
1938 nsIWidget::NativeIMEContext
nsBaseWidget::GetNativeIMEContext() {
1939 if (mTextEventDispatcher
&& mTextEventDispatcher
->GetPseudoIMEContext()) {
1940 // If we already have a TextEventDispatcher and it's working with
1941 // a TextInputProcessor, we need to return pseudo IME context since
1942 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1943 // on the pseudo IME context in such case.
1944 NativeIMEContext pseudoIMEContext
;
1945 pseudoIMEContext
.InitWithRawNativeIMEContext(
1946 mTextEventDispatcher
->GetPseudoIMEContext());
1947 return pseudoIMEContext
;
1949 return NativeIMEContext(this);
1952 nsIWidget::TextEventDispatcher
* nsBaseWidget::GetTextEventDispatcher() {
1953 EnsureTextEventDispatcher();
1954 return mTextEventDispatcher
;
1957 void* nsBaseWidget::GetPseudoIMEContext() {
1958 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
1962 return dispatcher
->GetPseudoIMEContext();
1965 TextEventDispatcherListener
*
1966 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1967 // TODO: If all platforms supported use of TextEventDispatcher for handling
1968 // native IME and keyboard events, this method should be removed since
1969 // in such case, this is overridden by all the subclasses.
1973 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId
,
1974 const ScrollableLayerGuid::ViewID
& aViewId
,
1975 const CSSRect
& aRect
, const uint32_t& aFlags
) {
1976 if (!mCompositorSession
|| !mAPZC
) {
1979 LayersId layerId
= mCompositorSession
->RootLayerTreeId();
1980 mAPZC
->ZoomToRect(ScrollableLayerGuid(layerId
, aPresShellId
, aViewId
),
1981 ZoomTarget
{aRect
}, aFlags
);
1984 #ifdef ACCESSIBILITY
1986 a11y::LocalAccessible
* nsBaseWidget::GetRootAccessible() {
1987 NS_ENSURE_TRUE(mWidgetListener
, nullptr);
1989 PresShell
* presShell
= mWidgetListener
->GetPresShell();
1990 NS_ENSURE_TRUE(presShell
, nullptr);
1992 // If container is null then the presshell is not active. This often happens
1993 // when a preshell is being held onto for fastback.
1994 nsPresContext
* presContext
= presShell
->GetPresContext();
1995 NS_ENSURE_TRUE(presContext
->GetContainerWeak(), nullptr);
1997 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1998 // make sure it's not created at unsafe times.
1999 nsAccessibilityService
* accService
= GetOrCreateAccService();
2001 return accService
->GetRootDocumentAccessible(
2002 presShell
, nsContentUtils::IsSafeToRunScript());
2008 #endif // ACCESSIBILITY
2010 void nsBaseWidget::StartAsyncScrollbarDrag(
2011 const AsyncDragMetrics
& aDragMetrics
) {
2012 if (!AsyncPanZoomEnabled()) {
2016 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession
);
2018 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
2019 ScrollableLayerGuid
guid(layersId
, aDragMetrics
.mPresShellId
,
2020 aDragMetrics
.mViewId
);
2022 mAPZC
->StartScrollbarDrag(guid
, aDragMetrics
);
2025 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint
& aAnchorLocation
,
2026 const ScrollableLayerGuid
& aGuid
) {
2027 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2029 return mAPZC
->StartAutoscroll(aGuid
, aAnchorLocation
);
2032 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid
& aGuid
) {
2033 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2035 mAPZC
->StopAutoscroll(aGuid
);
2038 LayersId
nsBaseWidget::GetRootLayerTreeId() {
2039 return mCompositorSession
? mCompositorSession
->RootLayerTreeId()
2043 already_AddRefed
<widget::Screen
> nsBaseWidget::GetWidgetScreen() {
2044 ScreenManager
& screenManager
= ScreenManager::GetSingleton();
2045 LayoutDeviceIntRect bounds
= GetScreenBounds();
2046 DesktopIntRect deskBounds
= RoundedToInt(bounds
/ GetDesktopToDeviceScale());
2047 return screenManager
.ScreenForRect(deskBounds
);
2050 mozilla::DesktopToLayoutDeviceScale
2051 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
2052 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
2053 ->GetDesktopToDeviceScale();
2056 nsresult
nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint
,
2058 nsIObserver
* aObserver
) {
2059 AutoObserverNotifier
notifier(aObserver
, "touchtap");
2061 if (sPointerIdCounter
> TOUCH_INJECT_MAX_POINTS
) {
2062 sPointerIdCounter
= 0;
2064 int pointerId
= sPointerIdCounter
;
2065 sPointerIdCounter
++;
2066 nsresult rv
= SynthesizeNativeTouchPoint(pointerId
, TOUCH_CONTACT
, aPoint
,
2068 if (NS_FAILED(rv
)) {
2073 return SynthesizeNativeTouchPoint(pointerId
, TOUCH_REMOVE
, aPoint
, 0, 0,
2077 // initiate a long tap
2078 int elapse
= Preferences::GetInt("ui.click_hold_context_menus.delay",
2079 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC
);
2080 if (!mLongTapTimer
) {
2081 mLongTapTimer
= NS_NewTimer();
2082 if (!mLongTapTimer
) {
2083 SynthesizeNativeTouchPoint(pointerId
, TOUCH_CANCEL
, aPoint
, 0, 0,
2085 return NS_ERROR_UNEXPECTED
;
2087 // Windows requires recuring events, so we set this to a smaller window
2088 // than the pref value.
2089 int timeout
= elapse
;
2090 if (timeout
> TOUCH_INJECT_PUMP_TIMER_MSEC
) {
2091 timeout
= TOUCH_INJECT_PUMP_TIMER_MSEC
;
2093 mLongTapTimer
->InitWithNamedFuncCallback(
2094 OnLongTapTimerCallback
, this, timeout
, nsITimer::TYPE_REPEATING_SLACK
,
2095 "nsIWidget::SynthesizeNativeTouchTap");
2098 // If we already have a long tap pending, cancel it. We only allow one long
2099 // tap to be active at a time.
2100 if (mLongTapTouchPoint
) {
2101 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2102 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2105 mLongTapTouchPoint
= MakeUnique
<LongTapInfo
>(
2106 pointerId
, aPoint
, TimeDuration::FromMilliseconds(elapse
), aObserver
);
2107 notifier
.SkipNotification(); // we'll do it in the long-tap callback
2112 void nsIWidget::OnLongTapTimerCallback(nsITimer
* aTimer
, void* aClosure
) {
2113 auto* self
= static_cast<nsIWidget
*>(aClosure
);
2115 if ((self
->mLongTapTouchPoint
->mStamp
+ self
->mLongTapTouchPoint
->mDuration
) >
2118 // Windows needs us to keep pumping feedback to the digitizer, so update
2119 // the pointer id with the same position.
2120 self
->SynthesizeNativeTouchPoint(
2121 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_CONTACT
,
2122 self
->mLongTapTouchPoint
->mPosition
, 1.0, 90, nullptr);
2127 AutoObserverNotifier
notifier(self
->mLongTapTouchPoint
->mObserver
,
2130 // finished, remove the touch point
2131 self
->mLongTapTimer
->Cancel();
2132 self
->mLongTapTimer
= nullptr;
2133 self
->SynthesizeNativeTouchPoint(
2134 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_REMOVE
,
2135 self
->mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2136 self
->mLongTapTouchPoint
= nullptr;
2139 float nsIWidget::GetFallbackDPI() {
2140 RefPtr
<const Screen
> primaryScreen
=
2141 ScreenManager::GetSingleton().GetPrimaryScreen();
2142 return primaryScreen
->GetDPI();
2145 CSSToLayoutDeviceScale
nsIWidget::GetFallbackDefaultScale() {
2146 RefPtr
<const Screen
> s
= ScreenManager::GetSingleton().GetPrimaryScreen();
2147 return s
->GetCSSToLayoutDeviceScale(Screen::IncludeOSZoom::No
);
2150 nsresult
nsIWidget::ClearNativeTouchSequence(nsIObserver
* aObserver
) {
2151 AutoObserverNotifier
notifier(aObserver
, "cleartouch");
2153 // XXX This is odd. This is called by the constructor of nsIWidget. However,
2154 // at that point, nsIWidget::mLongTapTimer must be nullptr. Therefore,
2155 // this must do nothing at initializing the instance.
2156 if (!mLongTapTimer
) {
2159 mLongTapTimer
->Cancel();
2160 mLongTapTimer
= nullptr;
2161 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2162 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2163 mLongTapTouchPoint
= nullptr;
2167 MultiTouchInput
nsBaseWidget::UpdateSynthesizedTouchState(
2168 MultiTouchInput
* aState
, mozilla::TimeStamp aTimeStamp
, uint32_t aPointerId
,
2169 TouchPointerState aPointerState
, LayoutDeviceIntPoint aPoint
,
2170 double aPointerPressure
, uint32_t aPointerOrientation
) {
2171 ScreenIntPoint pointerScreenPoint
= ViewAs
<ScreenPixel
>(
2172 aPoint
, PixelCastJustification::LayoutDeviceIsScreenForBounds
);
2174 // We can't dispatch *aState directly because (a) dispatching
2175 // it might inadvertently modify it and (b) in the case of touchend or
2176 // touchcancel events aState will hold the touches that are
2177 // still down whereas the input dispatched needs to hold the removed
2178 // touch(es). We use |inputToDispatch| for this purpose.
2179 MultiTouchInput inputToDispatch
;
2180 inputToDispatch
.mInputType
= MULTITOUCH_INPUT
;
2181 inputToDispatch
.mTimeStamp
= aTimeStamp
;
2183 int32_t index
= aState
->IndexOfTouch((int32_t)aPointerId
);
2184 if (aPointerState
== TOUCH_CONTACT
) {
2186 // found an existing touch point, update it
2187 SingleTouchData
& point
= aState
->mTouches
[index
];
2188 point
.mScreenPoint
= pointerScreenPoint
;
2189 point
.mRotationAngle
= (float)aPointerOrientation
;
2190 point
.mForce
= (float)aPointerPressure
;
2191 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_MOVE
;
2193 // new touch point, add it
2194 aState
->mTouches
.AppendElement(SingleTouchData(
2195 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2196 (float)aPointerOrientation
, (float)aPointerPressure
));
2197 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_START
;
2199 inputToDispatch
.mTouches
= aState
->mTouches
;
2201 MOZ_ASSERT(aPointerState
== TOUCH_REMOVE
|| aPointerState
== TOUCH_CANCEL
);
2202 // a touch point is being lifted, so remove it from the stored list
2204 aState
->mTouches
.RemoveElementAt(index
);
2206 inputToDispatch
.mType
=
2207 (aPointerState
== TOUCH_REMOVE
? MultiTouchInput::MULTITOUCH_END
2208 : MultiTouchInput::MULTITOUCH_CANCEL
);
2209 inputToDispatch
.mTouches
.AppendElement(SingleTouchData(
2210 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2211 (float)aPointerOrientation
, (float)aPointerPressure
));
2214 return inputToDispatch
;
2217 void nsBaseWidget::NotifyLiveResizeStarted() {
2218 // If we have mLiveResizeListeners already non-empty, we should notify those
2219 // listeners that the resize stopped before starting anew. In theory this
2220 // should never happen because we shouldn't get nested live resize actions.
2221 NotifyLiveResizeStopped();
2222 MOZ_ASSERT(mLiveResizeListeners
.IsEmpty());
2224 // If we can get the active remote tab for the current widget, suppress
2225 // the displayport on it during the live resize.
2226 if (!mWidgetListener
) {
2229 nsCOMPtr
<nsIAppWindow
> appWindow
= mWidgetListener
->GetAppWindow();
2233 mLiveResizeListeners
= appWindow
->GetLiveResizeListeners();
2234 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2235 mLiveResizeListeners
[i
]->LiveResizeStarted();
2239 void nsBaseWidget::NotifyLiveResizeStopped() {
2240 if (!mLiveResizeListeners
.IsEmpty()) {
2241 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2242 mLiveResizeListeners
[i
]->LiveResizeStopped();
2244 mLiveResizeListeners
.Clear();
2248 nsresult
nsBaseWidget::AsyncEnableDragDrop(bool aEnable
) {
2249 RefPtr
<nsBaseWidget
> kungFuDeathGrip
= this;
2250 return NS_DispatchToCurrentThreadQueue(
2251 NS_NewRunnableFunction(
2252 "AsyncEnableDragDropFn",
2253 [this, aEnable
, kungFuDeathGrip
]() { EnableDragDrop(aEnable
); }),
2254 kAsyncDragDropTimeout
, EventQueuePriority::Idle
);
2257 void nsBaseWidget::SwipeFinished() {
2258 if (mSwipeTracker
) {
2259 mSwipeTracker
->Destroy();
2260 mSwipeTracker
= nullptr;
2264 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId
,
2266 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== aInputBlockId
) {
2268 PanGestureInput
& startEvent
= mSwipeEventQueue
->queuedEvents
[0];
2269 TrackScrollEventAsSwipe(startEvent
, mSwipeEventQueue
->allowedDirections
,
2271 for (size_t i
= 1; i
< mSwipeEventQueue
->queuedEvents
.Length(); i
++) {
2272 mSwipeTracker
->ProcessEvent(mSwipeEventQueue
->queuedEvents
[i
]);
2275 // If the event wasn't start swipe, we need to notify it to APZ.
2276 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2277 BrowserGestureResponse::NotConsumed
);
2279 mSwipeEventQueue
= nullptr;
2283 void nsBaseWidget::TrackScrollEventAsSwipe(
2284 const mozilla::PanGestureInput
& aSwipeStartEvent
,
2285 uint32_t aAllowedDirections
, uint64_t aInputBlockId
) {
2286 // If a swipe is currently being tracked kill it -- it's been interrupted
2287 // by another gesture event.
2288 if (mSwipeTracker
) {
2289 mSwipeTracker
->CancelSwipe(aSwipeStartEvent
.mTimeStamp
);
2290 mSwipeTracker
->Destroy();
2291 mSwipeTracker
= nullptr;
2294 uint32_t direction
=
2295 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2296 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2297 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2300 new SwipeTracker(*this, aSwipeStartEvent
, aAllowedDirections
, direction
);
2303 mCurrentPanGestureBelongsToSwipe
= true;
2305 // Now SwipeTracker has started consuming pan events, notify it to APZ so
2306 // that APZ can discard queued events.
2307 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2308 BrowserGestureResponse::Consumed
);
2312 nsBaseWidget::SwipeInfo
nsBaseWidget::SendMayStartSwipe(
2313 const mozilla::PanGestureInput
& aSwipeStartEvent
) {
2314 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
2316 uint32_t direction
=
2317 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2318 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2319 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2321 // We're ready to start the animation. Tell Gecko about it, and at the same
2322 // time ask it if it really wants to start an animation for this event.
2323 // This event also reports back the directions that we can swipe in.
2324 LayoutDeviceIntPoint position
= RoundedToInt(aSwipeStartEvent
.mPanStartPoint
*
2325 ScreenToLayoutDeviceScale(1));
2326 WidgetSimpleGestureEvent geckoEvent
= SwipeTracker::CreateSwipeGestureEvent(
2327 eSwipeGestureMayStart
, this, position
, aSwipeStartEvent
.mTimeStamp
);
2328 geckoEvent
.mDirection
= direction
;
2329 geckoEvent
.mDelta
= 0.0;
2330 geckoEvent
.mAllowedDirections
= 0;
2331 bool shouldStartSwipe
=
2332 DispatchWindowEvent(geckoEvent
); // event cancelled == swipe should start
2334 SwipeInfo result
= {shouldStartSwipe
, geckoEvent
.mAllowedDirections
};
2338 WidgetWheelEvent
nsBaseWidget::MayStartSwipeForAPZ(
2339 const PanGestureInput
& aPanInput
, const APZEventResult
& aApzResult
) {
2340 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2342 // Ignore swipe-to-navigation in PiP window.
2347 if (aPanInput
.AllowsSwipe()) {
2348 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2349 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2350 if (swipeInfo
.wantsSwipe
) {
2351 if (aApzResult
.GetStatus() == nsEventStatus_eIgnore
) {
2352 // APZ has determined and that scrolling horizontally in the
2353 // requested direction is impossible, so it didn't do any
2354 // scrolling for the event.
2355 // We know now that MayStartSwipe wants a swipe, so we can start
2357 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
,
2358 aApzResult
.mInputBlockId
);
2359 } else if (!aApzResult
.GetHandledResult() ||
2360 !aApzResult
.GetHandledResult()->IsHandledByRoot()) {
2361 // We don't know whether this event can start a swipe, so we need
2362 // to queue up events and wait for a call to ReportSwipeStarted.
2363 // APZ might already have started scrolling in response to the
2364 // event if it knew that it's the right thing to do. In that case
2365 // we'll still get a call to ReportSwipeStarted, and we will
2366 // discard the queued events at that point.
2367 mSwipeEventQueue
= MakeUnique
<SwipeEventQueue
>(
2368 swipeInfo
.allowedDirections
, aApzResult
.mInputBlockId
);
2371 // Inform that the browser gesture didn't use the pan event (pan-start
2372 // precisely), so that APZ can now start using the event for
2373 // scrolling/overscrolling.
2374 mAPZC
->SetBrowserGestureResponse(aApzResult
.mInputBlockId
,
2375 BrowserGestureResponse::NotConsumed
);
2379 if (mSwipeEventQueue
&&
2380 mSwipeEventQueue
->inputBlockId
== aApzResult
.mInputBlockId
) {
2381 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2387 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput
& aPanInput
) {
2388 // Ignore swipe-to-navigation in PiP window.
2393 if (aPanInput
.mType
== PanGestureInput::PANGESTURE_MAYSTART
||
2394 aPanInput
.mType
== PanGestureInput::PANGESTURE_START
) {
2395 mCurrentPanGestureBelongsToSwipe
= false;
2397 if (mCurrentPanGestureBelongsToSwipe
) {
2398 // Ignore this event. It's a momentum event from a scroll gesture
2399 // that was processed as a swipe, and the swipe animation has
2400 // already finished (so mSwipeTracker is already null).
2401 MOZ_ASSERT(aPanInput
.IsMomentum(),
2402 "If the fingers are still on the touchpad, we should still have "
2404 "and it should have consumed this event.");
2408 if (!aPanInput
.MayTriggerSwipe()) {
2412 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2414 // We're in the non-APZ case here, but we still want to know whether
2415 // the event was routed to a child process, so we use InputAPZContext
2416 // to get that piece of information.
2417 ScrollableLayerGuid guid
;
2418 uint64_t blockId
= 0;
2419 InputAPZContext
context(guid
, blockId
, nsEventStatus_eIgnore
);
2421 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2422 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2423 nsEventStatus status
;
2424 DispatchEvent(&event
, status
);
2425 if (swipeInfo
.wantsSwipe
) {
2426 if (context
.WasRoutedToChildProcess()) {
2427 // We don't know whether this event can start a swipe, so we need
2428 // to queue up events and wait for a call to ReportSwipeStarted.
2430 MakeUnique
<SwipeEventQueue
>(swipeInfo
.allowedDirections
, blockId
);
2431 } else if (event
.TriggersSwipe()) {
2432 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
, blockId
);
2436 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== 0) {
2437 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2443 const IMENotificationRequests
& nsIWidget::IMENotificationRequestsRef() {
2444 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
2445 return dispatcher
->IMENotificationRequestsRef();
2448 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent
* aEvent
) {}
2450 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType
,
2451 const WidgetKeyboardEvent
& aEvent
,
2452 nsTArray
<CommandInt
>& aCommands
) {
2453 MOZ_ASSERT(aEvent
.IsTrusted());
2454 MOZ_ASSERT(aCommands
.IsEmpty());
2458 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboard() {
2459 if (XRE_IsContentProcess()) {
2460 return CreateBidiKeyboardContentProcess();
2462 return CreateBidiKeyboardInner();
2466 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboardInner() {
2467 // no bidi keyboard implementation
2472 namespace mozilla::widget
{
2474 const char* ToChar(InputContext::Origin aOrigin
) {
2476 case InputContext::ORIGIN_MAIN
:
2477 return "ORIGIN_MAIN";
2478 case InputContext::ORIGIN_CONTENT
:
2479 return "ORIGIN_CONTENT";
2481 return "Unexpected value";
2485 const char* ToChar(IMEMessage aIMEMessage
) {
2486 switch (aIMEMessage
) {
2487 case NOTIFY_IME_OF_NOTHING
:
2488 return "NOTIFY_IME_OF_NOTHING";
2489 case NOTIFY_IME_OF_FOCUS
:
2490 return "NOTIFY_IME_OF_FOCUS";
2491 case NOTIFY_IME_OF_BLUR
:
2492 return "NOTIFY_IME_OF_BLUR";
2493 case NOTIFY_IME_OF_SELECTION_CHANGE
:
2494 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2495 case NOTIFY_IME_OF_TEXT_CHANGE
:
2496 return "NOTIFY_IME_OF_TEXT_CHANGE";
2497 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED
:
2498 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2499 case NOTIFY_IME_OF_POSITION_CHANGE
:
2500 return "NOTIFY_IME_OF_POSITION_CHANGE";
2501 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT
:
2502 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2503 case REQUEST_TO_COMMIT_COMPOSITION
:
2504 return "REQUEST_TO_COMMIT_COMPOSITION";
2505 case REQUEST_TO_CANCEL_COMPOSITION
:
2506 return "REQUEST_TO_CANCEL_COMPOSITION";
2508 return "Unexpected value";
2512 void NativeIMEContext::Init(nsIWidget
* aWidget
) {
2514 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2515 mOriginProcessID
= static_cast<uint64_t>(-1);
2518 if (!XRE_IsContentProcess()) {
2519 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(
2520 aWidget
->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT
));
2521 mOriginProcessID
= 0;
2524 // If this is created in a child process, aWidget is an instance of
2525 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2526 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2527 // native IME context of the parent process.
2528 *this = aWidget
->GetNativeIMEContext();
2531 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext
) {
2532 if (NS_WARN_IF(!aRawNativeIMEContext
)) {
2533 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2534 mOriginProcessID
= static_cast<uint64_t>(-1);
2537 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(aRawNativeIMEContext
);
2539 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2542 void IMENotification::TextChangeDataBase::MergeWith(
2543 const IMENotification::TextChangeDataBase
& aOther
) {
2544 MOZ_ASSERT(aOther
.IsValid(), "Merging data must store valid data");
2545 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mRemovedEndOffset
,
2546 "end of removed text must be same or larger than start");
2547 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mAddedEndOffset
,
2548 "end of added text must be same or larger than start");
2555 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2556 // text ranges. I.e., mStartOffset should be the smallest offset of all
2557 // modified text ranges in old text. |mRemovedEndOffset| should be the
2558 // largest end offset in old text of all modified text ranges.
2559 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2560 // I.e., only this is an offset in new text.
2561 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2562 // premodified text was already removed. And some text whose length is
2563 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2564 // this allows IME to mark dirty the modified text range with |mStartOffset|
2565 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2566 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2567 // Additionally, IME can retrieve only the text between |mStartOffset| and
2568 // |mAddedEndOffset| for updating stored text.
2570 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2571 // should be adjusted to be in same text. The |newData.mStartOffset| and
2572 // |newData.mRemovedEndOffset| should be computed as in old text because
2573 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2574 // in the old text but even if some text before the values of the newData
2575 // has already been modified, the values don't include the changes.
2577 // For comparing new and old |mAddedEndOffset| values, they should be
2578 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2579 // computed as in the new text because |mAddedEndOffset| indicates the end
2580 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2581 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2583 const TextChangeDataBase
& newData
= aOther
;
2584 const TextChangeDataBase oldData
= *this;
2586 // mCausedOnlyByComposition should be true only when all changes are caused
2588 mCausedOnlyByComposition
=
2589 newData
.mCausedOnlyByComposition
&& oldData
.mCausedOnlyByComposition
;
2591 // mIncludingChangesWithoutComposition should be true if at least one of
2592 // merged changes occurred without composition.
2593 mIncludingChangesWithoutComposition
=
2594 newData
.mIncludingChangesWithoutComposition
||
2595 oldData
.mIncludingChangesWithoutComposition
;
2597 // mIncludingChangesDuringComposition should be true when at least one of
2598 // the merged non-composition changes occurred during the latest composition.
2599 if (!newData
.mCausedOnlyByComposition
&&
2600 !newData
.mIncludingChangesDuringComposition
) {
2601 MOZ_ASSERT(newData
.mIncludingChangesWithoutComposition
);
2602 MOZ_ASSERT(mIncludingChangesWithoutComposition
);
2603 // If new change is neither caused by composition nor occurred during
2604 // composition, set mIncludingChangesDuringComposition to false because
2605 // IME doesn't want outdated text changes as text change during current
2607 mIncludingChangesDuringComposition
= false;
2609 // Otherwise, set mIncludingChangesDuringComposition to true if either
2610 // oldData or newData includes changes during composition.
2611 mIncludingChangesDuringComposition
=
2612 newData
.mIncludingChangesDuringComposition
||
2613 oldData
.mIncludingChangesDuringComposition
;
2616 if (newData
.mStartOffset
>= oldData
.mAddedEndOffset
) {
2618 // If new start is after old end offset of added text, it means that text
2619 // after the modified range is modified. Like:
2620 // added range of old change: +----------+
2621 // removed range of new change: +----------+
2622 // So, the old start offset is always the smaller offset.
2623 mStartOffset
= oldData
.mStartOffset
;
2624 // The new end offset of removed text is moved by the old change and we
2625 // need to cancel the move of the old change for comparing the offsets in
2626 // same text because it doesn't make sensce to compare offsets in different
2628 uint32_t newRemovedEndOffsetInOldText
=
2629 newData
.mRemovedEndOffset
- oldData
.Difference();
2631 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2632 // The new end offset of added text is always the larger offset.
2633 mAddedEndOffset
= newData
.mAddedEndOffset
;
2637 if (newData
.mStartOffset
>= oldData
.mStartOffset
) {
2638 // If new start is in the modified range, it means that new data changes
2639 // a part or all of the range.
2640 mStartOffset
= oldData
.mStartOffset
;
2641 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2643 // If new end of removed text is greater than old end of added text, it
2644 // means that all or a part of modified range modified again and text
2645 // after the modified range is also modified. Like:
2646 // added range of old change: +----------+
2647 // removed range of new change: +----------+
2648 // So, the new removed end offset is moved by the old change and we need
2649 // to cancel the move of the old change for comparing the offsets in the
2650 // same text because it doesn't make sense to compare the offsets in
2652 uint32_t newRemovedEndOffsetInOldText
=
2653 newData
.mRemovedEndOffset
- oldData
.Difference();
2655 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2656 // The old end of added text is replaced by new change. So, it should be
2657 // same as the new start. On the other hand, the new added end offset is
2658 // always same or larger. Therefore, the merged end offset of added
2659 // text should be the new end offset of added text.
2660 mAddedEndOffset
= newData
.mAddedEndOffset
;
2665 // If new end of removed text is less than old end of added text, it means
2666 // that only a part of the modified range is modified again. Like:
2667 // added range of old change: +------------+
2668 // removed range of new change: +-----+
2669 // So, the new end offset of removed text should be same as the old end
2670 // offset of removed text. Therefore, the merged end offset of removed
2671 // text should be the old text change's |mRemovedEndOffset|.
2672 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2673 // The old end of added text is moved by new change. So, we need to cancel
2674 // the move of the new change for comparing the offsets in same text.
2675 uint32_t oldAddedEndOffsetInNewText
=
2676 oldData
.mAddedEndOffset
+ newData
.Difference();
2678 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2682 if (newData
.mRemovedEndOffset
>= oldData
.mStartOffset
) {
2683 // If new end of removed text is greater than old start (and new start is
2684 // less than old start), it means that a part of modified range is modified
2685 // again and some new text before the modified range is also modified.
2686 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2687 "new start offset should be less than old one here");
2688 mStartOffset
= newData
.mStartOffset
;
2689 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2691 // If new end of removed text is greater than old end of added text, it
2692 // means that all modified text and text after the modified range is
2694 // added range of old change: +----------+
2695 // removed range of new change: +------------------+
2696 // So, the new end of removed text is moved by the old change. Therefore,
2697 // we need to cancel the move of the old change for comparing the offsets
2698 // in same text because it doesn't make sense to compare the offsets in
2700 uint32_t newRemovedEndOffsetInOldText
=
2701 newData
.mRemovedEndOffset
- oldData
.Difference();
2703 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2704 // The old end of added text is replaced by new change. So, the old end
2705 // offset of added text is same as new text change's start offset. Then,
2706 // new change's end offset of added text is always same or larger than
2707 // it. Therefore, merged end offset of added text is always the new end
2708 // offset of added text.
2709 mAddedEndOffset
= newData
.mAddedEndOffset
;
2714 // If new end of removed text is less than old end of added text, it
2715 // means that only a part of the modified range is modified again. Like:
2716 // added range of old change: +----------+
2717 // removed range of new change: +----------+
2718 // So, the new end of removed text should be same as old end of removed
2719 // text for preventing end of removed text to be modified. Therefore,
2720 // merged end offset of removed text is always the old end offset of removed
2722 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2723 // The old end of added text is moved by this change. So, we need to
2724 // cancel the move of the new change for comparing the offsets in same text
2725 // because it doesn't make sense to compare the offsets in different text.
2726 uint32_t oldAddedEndOffsetInNewText
=
2727 oldData
.mAddedEndOffset
+ newData
.Difference();
2729 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2734 // Otherwise, i.e., both new end of added text and new start are less than
2735 // old start, text before the modified range is modified. Like:
2736 // added range of old change: +----------+
2737 // removed range of new change: +----------+
2738 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2739 "new start offset should be less than old one here");
2740 mStartOffset
= newData
.mStartOffset
;
2741 MOZ_ASSERT(newData
.mRemovedEndOffset
< oldData
.mRemovedEndOffset
,
2742 "new removed end offset should be less than old one here");
2743 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2744 // The end of added text should be adjusted with the new difference.
2745 uint32_t oldAddedEndOffsetInNewText
=
2746 oldData
.mAddedEndOffset
+ newData
.Difference();
2748 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2753 // Let's test the code of merging multiple text change data in debug build
2754 // and crash if one of them fails because this feature is very complex but
2755 // cannot be tested with mochitest.
2756 void IMENotification::TextChangeDataBase::Test() {
2757 static bool gTestTextChangeEvent
= true;
2758 if (!gTestTextChangeEvent
) {
2761 gTestTextChangeEvent
= false;
2763 /****************************************************************************
2765 ****************************************************************************/
2768 MergeWith(TextChangeData(10, 10, 20, false, false));
2769 MergeWith(TextChangeData(20, 20, 35, false, false));
2770 MOZ_ASSERT(mStartOffset
== 10,
2771 "Test 1-1-1: mStartOffset should be the first offset");
2773 mRemovedEndOffset
== 10, // 20 - (20 - 10)
2774 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2776 mAddedEndOffset
== 35,
2777 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2780 // Removing text (longer line -> shorter line)
2781 MergeWith(TextChangeData(10, 20, 10, false, false));
2782 MergeWith(TextChangeData(10, 30, 10, false, false));
2783 MOZ_ASSERT(mStartOffset
== 10,
2784 "Test 1-2-1: mStartOffset should be the first offset");
2785 MOZ_ASSERT(mRemovedEndOffset
== 40, // 30 + (10 - 20)
2786 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2788 "with already removed length");
2790 mAddedEndOffset
== 10,
2791 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2794 // Removing text (shorter line -> longer line)
2795 MergeWith(TextChangeData(10, 20, 10, false, false));
2796 MergeWith(TextChangeData(10, 15, 10, false, false));
2797 MOZ_ASSERT(mStartOffset
== 10,
2798 "Test 1-3-1: mStartOffset should be the first offset");
2799 MOZ_ASSERT(mRemovedEndOffset
== 25, // 15 + (10 - 20)
2800 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2802 "with already removed length");
2804 mAddedEndOffset
== 10,
2805 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2808 // Appending text at different point (not sure if actually occurs)
2809 MergeWith(TextChangeData(10, 10, 20, false, false));
2810 MergeWith(TextChangeData(55, 55, 60, false, false));
2811 MOZ_ASSERT(mStartOffset
== 10,
2812 "Test 1-4-1: mStartOffset should be the smallest offset");
2814 mRemovedEndOffset
== 45, // 55 - (10 - 20)
2815 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2816 "text without already added length");
2818 mAddedEndOffset
== 60,
2819 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2822 // Removing text at different point (not sure if actually occurs)
2823 MergeWith(TextChangeData(10, 20, 10, false, false));
2824 MergeWith(TextChangeData(55, 68, 55, false, false));
2825 MOZ_ASSERT(mStartOffset
== 10,
2826 "Test 1-5-1: mStartOffset should be the smallest offset");
2828 mRemovedEndOffset
== 78, // 68 - (10 - 20)
2829 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2830 "text with already removed length");
2832 mAddedEndOffset
== 55,
2833 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2836 // Replacing text and append text (becomes longer)
2837 MergeWith(TextChangeData(30, 35, 32, false, false));
2838 MergeWith(TextChangeData(32, 32, 40, false, false));
2839 MOZ_ASSERT(mStartOffset
== 30,
2840 "Test 1-6-1: mStartOffset should be the smallest offset");
2842 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2843 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2846 mAddedEndOffset
== 40,
2847 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2850 // Replacing text and append text (becomes shorter)
2851 MergeWith(TextChangeData(30, 35, 32, false, false));
2852 MergeWith(TextChangeData(32, 32, 33, false, false));
2853 MOZ_ASSERT(mStartOffset
== 30,
2854 "Test 1-7-1: mStartOffset should be the smallest offset");
2856 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2857 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2860 mAddedEndOffset
== 33,
2861 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2864 // Removing text and replacing text after first range (not sure if actually
2866 MergeWith(TextChangeData(30, 35, 30, false, false));
2867 MergeWith(TextChangeData(32, 34, 48, false, false));
2868 MOZ_ASSERT(mStartOffset
== 30,
2869 "Test 1-8-1: mStartOffset should be the smallest offset");
2870 MOZ_ASSERT(mRemovedEndOffset
== 39, // 34 - (30 - 35)
2871 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2873 "without already removed text");
2875 mAddedEndOffset
== 48,
2876 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2879 // Removing text and replacing text after first range (not sure if actually
2881 MergeWith(TextChangeData(30, 35, 30, false, false));
2882 MergeWith(TextChangeData(32, 38, 36, false, false));
2883 MOZ_ASSERT(mStartOffset
== 30,
2884 "Test 1-9-1: mStartOffset should be the smallest offset");
2885 MOZ_ASSERT(mRemovedEndOffset
== 43, // 38 - (30 - 35)
2886 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2888 "without already removed text");
2890 mAddedEndOffset
== 36,
2891 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2894 /****************************************************************************
2896 ****************************************************************************/
2898 // Replacing text in around end of added text (becomes shorter) (not sure
2899 // if actually occurs)
2900 MergeWith(TextChangeData(50, 50, 55, false, false));
2901 MergeWith(TextChangeData(53, 60, 54, false, false));
2902 MOZ_ASSERT(mStartOffset
== 50,
2903 "Test 2-1-1: mStartOffset should be the smallest offset");
2904 MOZ_ASSERT(mRemovedEndOffset
== 55, // 60 - (55 - 50)
2905 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2907 "without already added text length");
2909 mAddedEndOffset
== 54,
2910 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2913 // Replacing text around end of added text (becomes longer) (not sure
2914 // if actually occurs)
2915 MergeWith(TextChangeData(50, 50, 55, false, false));
2916 MergeWith(TextChangeData(54, 62, 68, false, false));
2917 MOZ_ASSERT(mStartOffset
== 50,
2918 "Test 2-2-1: mStartOffset should be the smallest offset");
2919 MOZ_ASSERT(mRemovedEndOffset
== 57, // 62 - (55 - 50)
2920 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2922 "without already added text length");
2924 mAddedEndOffset
== 68,
2925 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2928 // Replacing text around end of replaced text (became shorter) (not sure if
2930 MergeWith(TextChangeData(36, 48, 45, false, false));
2931 MergeWith(TextChangeData(43, 50, 49, false, false));
2932 MOZ_ASSERT(mStartOffset
== 36,
2933 "Test 2-3-1: mStartOffset should be the smallest offset");
2934 MOZ_ASSERT(mRemovedEndOffset
== 53, // 50 - (45 - 48)
2935 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2937 "without already removed text length");
2939 mAddedEndOffset
== 49,
2940 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2943 // Replacing text around end of replaced text (became longer) (not sure if
2945 MergeWith(TextChangeData(36, 52, 53, false, false));
2946 MergeWith(TextChangeData(43, 68, 61, false, false));
2947 MOZ_ASSERT(mStartOffset
== 36,
2948 "Test 2-4-1: mStartOffset should be the smallest offset");
2949 MOZ_ASSERT(mRemovedEndOffset
== 67, // 68 - (53 - 52)
2950 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2952 "without already added text length");
2954 mAddedEndOffset
== 61,
2955 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2958 /****************************************************************************
2960 ****************************************************************************/
2962 // Appending text in already added text (not sure if actually occurs)
2963 MergeWith(TextChangeData(10, 10, 20, false, false));
2964 MergeWith(TextChangeData(15, 15, 30, false, false));
2965 MOZ_ASSERT(mStartOffset
== 10,
2966 "Test 3-1-1: mStartOffset should be the smallest offset");
2967 MOZ_ASSERT(mRemovedEndOffset
== 10,
2968 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2971 mAddedEndOffset
== 35, // 20 + (30 - 15)
2972 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2973 "added text length by the new change");
2976 // Replacing text in added text (not sure if actually occurs)
2977 MergeWith(TextChangeData(50, 50, 55, false, false));
2978 MergeWith(TextChangeData(52, 53, 56, false, false));
2979 MOZ_ASSERT(mStartOffset
== 50,
2980 "Test 3-2-1: mStartOffset should be the smallest offset");
2981 MOZ_ASSERT(mRemovedEndOffset
== 50,
2982 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2985 mAddedEndOffset
== 58, // 55 + (56 - 53)
2986 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2987 "added text length by the new change");
2990 // Replacing text in replaced text (became shorter) (not sure if actually
2992 MergeWith(TextChangeData(36, 48, 45, false, false));
2993 MergeWith(TextChangeData(37, 38, 50, false, false));
2994 MOZ_ASSERT(mStartOffset
== 36,
2995 "Test 3-3-1: mStartOffset should be the smallest offset");
2996 MOZ_ASSERT(mRemovedEndOffset
== 48,
2997 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
3000 mAddedEndOffset
== 57, // 45 + (50 - 38)
3001 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
3002 "added text length by the new change");
3005 // Replacing text in replaced text (became longer) (not sure if actually
3007 MergeWith(TextChangeData(32, 48, 53, false, false));
3008 MergeWith(TextChangeData(43, 50, 52, false, false));
3009 MOZ_ASSERT(mStartOffset
== 32,
3010 "Test 3-4-1: mStartOffset should be the smallest offset");
3011 MOZ_ASSERT(mRemovedEndOffset
== 48,
3012 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
3014 "without already added text length");
3016 mAddedEndOffset
== 55, // 53 + (52 - 50)
3017 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
3018 "added text length by the new change");
3021 // Replacing text in replaced text (became shorter) (not sure if actually
3023 MergeWith(TextChangeData(36, 48, 50, false, false));
3024 MergeWith(TextChangeData(37, 49, 47, false, false));
3025 MOZ_ASSERT(mStartOffset
== 36,
3026 "Test 3-5-1: mStartOffset should be the smallest offset");
3028 mRemovedEndOffset
== 48,
3029 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
3031 MOZ_ASSERT(mAddedEndOffset
== 48, // 50 + (47 - 49)
3032 "Test 3-5-3: mAddedEndOffset should be the first end of added "
3034 "removed text length by the new change");
3037 // Replacing text in replaced text (became longer) (not sure if actually
3039 MergeWith(TextChangeData(32, 48, 53, false, false));
3040 MergeWith(TextChangeData(43, 50, 47, false, false));
3041 MOZ_ASSERT(mStartOffset
== 32,
3042 "Test 3-6-1: mStartOffset should be the smallest offset");
3043 MOZ_ASSERT(mRemovedEndOffset
== 48,
3044 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
3046 "without already added text length");
3047 MOZ_ASSERT(mAddedEndOffset
== 50, // 53 + (47 - 50)
3048 "Test 3-6-3: mAddedEndOffset should be the first end of added "
3050 "removed text length by the new change");
3053 /****************************************************************************
3055 ****************************************************************************/
3057 // Replacing text all of already append text (not sure if actually occurs)
3058 MergeWith(TextChangeData(50, 50, 55, false, false));
3059 MergeWith(TextChangeData(44, 66, 68, false, false));
3060 MOZ_ASSERT(mStartOffset
== 44,
3061 "Test 4-1-1: mStartOffset should be the smallest offset");
3062 MOZ_ASSERT(mRemovedEndOffset
== 61, // 66 - (55 - 50)
3063 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
3065 "without already added text length");
3067 mAddedEndOffset
== 68,
3068 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3071 // Replacing text around a point in which text was removed (not sure if
3073 MergeWith(TextChangeData(50, 62, 50, false, false));
3074 MergeWith(TextChangeData(44, 66, 68, false, false));
3075 MOZ_ASSERT(mStartOffset
== 44,
3076 "Test 4-2-1: mStartOffset should be the smallest offset");
3077 MOZ_ASSERT(mRemovedEndOffset
== 78, // 66 - (50 - 62)
3078 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
3080 "without already removed text length");
3082 mAddedEndOffset
== 68,
3083 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3086 // Replacing text all replaced text (became shorter) (not sure if actually
3088 MergeWith(TextChangeData(50, 62, 60, false, false));
3089 MergeWith(TextChangeData(49, 128, 130, false, false));
3090 MOZ_ASSERT(mStartOffset
== 49,
3091 "Test 4-3-1: mStartOffset should be the smallest offset");
3092 MOZ_ASSERT(mRemovedEndOffset
== 130, // 128 - (60 - 62)
3093 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
3095 "without already removed text length");
3097 mAddedEndOffset
== 130,
3098 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3101 // Replacing text all replaced text (became longer) (not sure if actually
3103 MergeWith(TextChangeData(50, 61, 73, false, false));
3104 MergeWith(TextChangeData(44, 100, 50, false, false));
3105 MOZ_ASSERT(mStartOffset
== 44,
3106 "Test 4-4-1: mStartOffset should be the smallest offset");
3107 MOZ_ASSERT(mRemovedEndOffset
== 88, // 100 - (73 - 61)
3108 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
3110 "with already added text length");
3112 mAddedEndOffset
== 50,
3113 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3116 /****************************************************************************
3118 ****************************************************************************/
3120 // Replacing text around start of added text (not sure if actually occurs)
3121 MergeWith(TextChangeData(50, 50, 55, false, false));
3122 MergeWith(TextChangeData(48, 52, 49, false, false));
3123 MOZ_ASSERT(mStartOffset
== 48,
3124 "Test 5-1-1: mStartOffset should be the smallest offset");
3126 mRemovedEndOffset
== 50,
3127 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
3130 mAddedEndOffset
== 52, // 55 + (52 - 49)
3131 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
3132 "added text length by the new change");
3135 // Replacing text around start of replaced text (became shorter) (not sure if
3137 MergeWith(TextChangeData(50, 60, 58, false, false));
3138 MergeWith(TextChangeData(43, 50, 48, false, false));
3139 MOZ_ASSERT(mStartOffset
== 43,
3140 "Test 5-2-1: mStartOffset should be the smallest offset");
3142 mRemovedEndOffset
== 60,
3143 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3145 MOZ_ASSERT(mAddedEndOffset
== 56, // 58 + (48 - 50)
3146 "Test 5-2-3: mAddedEndOffset should be the first end of added "
3148 "removed text length by the new change");
3151 // Replacing text around start of replaced text (became longer) (not sure if
3153 MergeWith(TextChangeData(50, 60, 68, false, false));
3154 MergeWith(TextChangeData(43, 55, 53, false, false));
3155 MOZ_ASSERT(mStartOffset
== 43,
3156 "Test 5-3-1: mStartOffset should be the smallest offset");
3158 mRemovedEndOffset
== 60,
3159 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3161 MOZ_ASSERT(mAddedEndOffset
== 66, // 68 + (53 - 55)
3162 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3164 "removed text length by the new change");
3167 // Replacing text around start of replaced text (became shorter) (not sure if
3169 MergeWith(TextChangeData(50, 60, 58, false, false));
3170 MergeWith(TextChangeData(43, 50, 128, false, false));
3171 MOZ_ASSERT(mStartOffset
== 43,
3172 "Test 5-4-1: mStartOffset should be the smallest offset");
3174 mRemovedEndOffset
== 60,
3175 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
3178 mAddedEndOffset
== 136, // 58 + (128 - 50)
3179 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
3180 "added text length by the new change");
3183 // Replacing text around start of replaced text (became longer) (not sure if
3185 MergeWith(TextChangeData(50, 60, 68, false, false));
3186 MergeWith(TextChangeData(43, 55, 65, false, false));
3187 MOZ_ASSERT(mStartOffset
== 43,
3188 "Test 5-5-1: mStartOffset should be the smallest offset");
3190 mRemovedEndOffset
== 60,
3191 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
3194 mAddedEndOffset
== 78, // 68 + (65 - 55)
3195 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
3196 "added text length by the new change");
3199 /****************************************************************************
3201 ****************************************************************************/
3203 // Appending text before already added text (not sure if actually occurs)
3204 MergeWith(TextChangeData(30, 30, 45, false, false));
3205 MergeWith(TextChangeData(10, 10, 20, false, false));
3206 MOZ_ASSERT(mStartOffset
== 10,
3207 "Test 6-1-1: mStartOffset should be the smallest offset");
3209 mRemovedEndOffset
== 30,
3210 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3213 mAddedEndOffset
== 55, // 45 + (20 - 10)
3214 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3215 "added text length by the new change");
3218 // Removing text before already removed text (not sure if actually occurs)
3219 MergeWith(TextChangeData(30, 35, 30, false, false));
3220 MergeWith(TextChangeData(10, 25, 10, false, false));
3221 MOZ_ASSERT(mStartOffset
== 10,
3222 "Test 6-2-1: mStartOffset should be the smallest offset");
3224 mRemovedEndOffset
== 35,
3225 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3228 mAddedEndOffset
== 15, // 30 - (25 - 10)
3229 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3230 "removed text length by the new change");
3233 // Replacing text before already replaced text (not sure if actually occurs)
3234 MergeWith(TextChangeData(50, 65, 70, false, false));
3235 MergeWith(TextChangeData(13, 24, 15, false, false));
3236 MOZ_ASSERT(mStartOffset
== 13,
3237 "Test 6-3-1: mStartOffset should be the smallest offset");
3239 mRemovedEndOffset
== 65,
3240 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3242 MOZ_ASSERT(mAddedEndOffset
== 61, // 70 + (15 - 24)
3243 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3245 "removed text length by the new change");
3248 // Replacing text before already replaced text (not sure if actually occurs)
3249 MergeWith(TextChangeData(50, 65, 70, false, false));
3250 MergeWith(TextChangeData(13, 24, 36, false, false));
3251 MOZ_ASSERT(mStartOffset
== 13,
3252 "Test 6-4-1: mStartOffset should be the smallest offset");
3254 mRemovedEndOffset
== 65,
3255 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3257 MOZ_ASSERT(mAddedEndOffset
== 82, // 70 + (36 - 24)
3258 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3260 "removed text length by the new change");
3264 #endif // #ifdef DEBUG
3266 } // namespace mozilla::widget
3269 //////////////////////////////////////////////////////////////
3271 // Convert a GUI event message code to a string.
3272 // Makes it a lot easier to debug events.
3274 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3275 // for a DebugPrintEvent() function that uses
3278 //////////////////////////////////////////////////////////////
3280 nsAutoString
nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent
* aGuiEvent
) {
3281 NS_ASSERTION(nullptr != aGuiEvent
, "cmon, null gui event.");
3283 nsAutoString
eventName(u
"UNKNOWN"_ns
);
3285 # define _ASSIGN_eventName(_value, _name) \
3287 eventName.AssignLiteral(_name); \
3290 switch (aGuiEvent
->mMessage
) {
3291 _ASSIGN_eventName(eBlur
, "eBlur");
3292 _ASSIGN_eventName(eDrop
, "eDrop");
3293 _ASSIGN_eventName(eDragEnter
, "eDragEnter");
3294 _ASSIGN_eventName(eDragExit
, "eDragExit");
3295 _ASSIGN_eventName(eDragOver
, "eDragOver");
3296 _ASSIGN_eventName(eEditorInput
, "eEditorInput");
3297 _ASSIGN_eventName(eFocus
, "eFocus");
3298 _ASSIGN_eventName(eFocusIn
, "eFocusIn");
3299 _ASSIGN_eventName(eFocusOut
, "eFocusOut");
3300 _ASSIGN_eventName(eFormSelect
, "eFormSelect");
3301 _ASSIGN_eventName(eFormChange
, "eFormChange");
3302 _ASSIGN_eventName(eFormReset
, "eFormReset");
3303 _ASSIGN_eventName(eFormSubmit
, "eFormSubmit");
3304 _ASSIGN_eventName(eImageAbort
, "eImageAbort");
3305 _ASSIGN_eventName(eLoadError
, "eLoadError");
3306 _ASSIGN_eventName(eKeyDown
, "eKeyDown");
3307 _ASSIGN_eventName(eKeyPress
, "eKeyPress");
3308 _ASSIGN_eventName(eKeyUp
, "eKeyUp");
3309 _ASSIGN_eventName(eMouseEnterIntoWidget
, "eMouseEnterIntoWidget");
3310 _ASSIGN_eventName(eMouseExitFromWidget
, "eMouseExitFromWidget");
3311 _ASSIGN_eventName(eMouseDown
, "eMouseDown");
3312 _ASSIGN_eventName(eMouseUp
, "eMouseUp");
3313 _ASSIGN_eventName(eMouseDoubleClick
, "eMouseDoubleClick");
3314 _ASSIGN_eventName(eMouseMove
, "eMouseMove");
3315 _ASSIGN_eventName(ePointerClick
, "ePointerClick");
3316 _ASSIGN_eventName(ePointerAuxClick
, "ePointerAuxClick");
3317 _ASSIGN_eventName(eLoad
, "eLoad");
3318 _ASSIGN_eventName(ePopState
, "ePopState");
3319 _ASSIGN_eventName(eBeforeScriptExecute
, "eBeforeScriptExecute");
3320 _ASSIGN_eventName(eAfterScriptExecute
, "eAfterScriptExecute");
3321 _ASSIGN_eventName(eUnload
, "eUnload");
3322 _ASSIGN_eventName(eHashChange
, "eHashChange");
3323 _ASSIGN_eventName(eReadyStateChange
, "eReadyStateChange");
3324 _ASSIGN_eventName(eXULBroadcast
, "eXULBroadcast");
3325 _ASSIGN_eventName(eXULCommandUpdate
, "eXULCommandUpdate");
3327 # undef _ASSIGN_eventName
3330 eventName
.AssignLiteral("UNKNOWN: ");
3331 eventName
.AppendInt(aGuiEvent
->mMessage
);
3335 return nsAutoString(eventName
);
3337 //////////////////////////////////////////////////////////////
3339 // Code to deal with paint and event debug prefs.
3341 //////////////////////////////////////////////////////////////
3347 static PrefPair debug_PrefValues
[] = {
3348 {"nglayout.debug.crossing_event_dumping", false},
3349 {"nglayout.debug.event_dumping", false},
3350 {"nglayout.debug.invalidate_dumping", false},
3351 {"nglayout.debug.motion_event_dumping", false},
3352 {"nglayout.debug.paint_dumping", false}};
3354 //////////////////////////////////////////////////////////////
3355 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName
) {
3356 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3358 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3359 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3360 return debug_PrefValues
[i
].value
;
3366 //////////////////////////////////////////////////////////////
3367 static void debug_SetCachedBoolPref(const char* aPrefName
, bool aValue
) {
3368 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3370 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3371 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3372 debug_PrefValues
[i
].value
= aValue
;
3378 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3381 //////////////////////////////////////////////////////////////
3382 class Debug_PrefObserver final
: public nsIObserver
{
3383 ~Debug_PrefObserver() = default;
3390 NS_IMPL_ISUPPORTS(Debug_PrefObserver
, nsIObserver
)
3393 Debug_PrefObserver::Observe(nsISupports
* subject
, const char* topic
,
3394 const char16_t
* data
) {
3395 NS_ConvertUTF16toUTF8
prefName(data
);
3397 bool value
= Preferences::GetBool(prefName
.get(), false);
3398 debug_SetCachedBoolPref(prefName
.get(), value
);
3402 //////////////////////////////////////////////////////////////
3403 /* static */ void debug_RegisterPrefCallbacks() {
3404 static bool once
= true;
3412 nsCOMPtr
<nsIObserver
> obs(new Debug_PrefObserver());
3413 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3414 // Initialize the pref values
3415 debug_PrefValues
[i
].value
=
3416 Preferences::GetBool(debug_PrefValues
[i
].name
, false);
3419 // Register callbacks for when these change
3421 name
.AssignLiteral(debug_PrefValues
[i
].name
,
3422 strlen(debug_PrefValues
[i
].name
));
3423 Preferences::AddStrongObserver(obs
, name
);
3427 //////////////////////////////////////////////////////////////
3428 static int32_t _GetPrintCount() {
3429 static int32_t sCount
= 0;
3433 //////////////////////////////////////////////////////////////
3435 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3436 WidgetGUIEvent
* aGuiEvent
,
3437 const char* aWidgetName
, int32_t aWindowID
) {
3438 if (aGuiEvent
->mMessage
== eMouseMove
) {
3439 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3442 if (aGuiEvent
->mMessage
== eMouseEnterIntoWidget
||
3443 aGuiEvent
->mMessage
== eMouseExitFromWidget
) {
3444 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3448 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3450 NS_LossyConvertUTF16toASCII
tempString(
3451 debug_GuiEventToString(aGuiEvent
).get());
3453 fprintf(aFileOut
, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3454 _GetPrintCount(), tempString
.get(), (void*)aWidget
, aWidgetName
,
3455 aWindowID
, aGuiEvent
->mRefPoint
.x
.value
,
3456 aGuiEvent
->mRefPoint
.y
.value
);
3458 //////////////////////////////////////////////////////////////
3460 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3461 const nsIntRegion
& aRegion
,
3462 const char* aWidgetName
,
3463 int32_t aWindowID
) {
3464 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3465 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3467 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3469 nsIntRect rect
= aRegion
.GetBounds();
3471 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3473 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
, rect
.X(),
3474 rect
.Y(), rect
.Width(), rect
.Height());
3476 fprintf(aFileOut
, "\n");
3478 //////////////////////////////////////////////////////////////
3480 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut
, nsIWidget
* aWidget
,
3481 const LayoutDeviceIntRect
* aRect
,
3482 const char* aWidgetName
,
3483 int32_t aWindowID
) {
3484 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3486 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3487 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3489 fprintf(aFileOut
, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3490 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
);
3493 fprintf(aFileOut
, " rect=%3d,%-3d %3d,%-3d", aRect
->X(), aRect
->Y(),
3494 aRect
->Width(), aRect
->Height());
3496 fprintf(aFileOut
, " rect=%-15s", "none");
3499 fprintf(aFileOut
, "\n");
3501 //////////////////////////////////////////////////////////////