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 //-------------------------------------------------------------------------
651 // Sets widget's position within its parent's child list.
653 //-------------------------------------------------------------------------
654 void nsBaseWidget::SetZIndex(int32_t aZIndex
) {
655 // Hold a ref to ourselves just in case, since we're going to remove
657 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
661 // reorder this child in its parent's list.
662 auto* parent
= static_cast<nsBaseWidget
*>(GetParent());
664 parent
->RemoveChild(this);
665 // Scope sib outside the for loop so we can check it afterward
666 nsIWidget
* sib
= parent
->GetFirstChild();
667 for (; sib
; sib
= sib
->GetNextSibling()) {
668 int32_t childZIndex
= GetZIndex();
669 if (aZIndex
< childZIndex
) {
670 // Insert ourselves before sib
671 nsIWidget
* prev
= sib
->GetPrevSibling();
674 sib
->SetPrevSibling(this);
676 prev
->SetNextSibling(this);
678 NS_ASSERTION(sib
== parent
->mFirstChild
, "Broken child list");
679 // We've taken ownership of sib, so it's safe to have parent let
681 parent
->mFirstChild
= this;
683 PlaceBehind(eZPlacementBelow
, sib
, false);
687 // were we added to the list?
689 parent
->AddChild(this);
694 void nsBaseWidget::GetWorkspaceID(nsAString
& workspaceID
) {
695 workspaceID
.Truncate();
698 void nsBaseWidget::MoveToWorkspace(const nsAString
& workspaceID
) {
702 //-------------------------------------------------------------------------
704 // Get this component cursor
706 //-------------------------------------------------------------------------
708 void nsBaseWidget::SetCursor(const Cursor
& aCursor
) { mCursor
= aCursor
; }
710 void nsBaseWidget::SetCustomCursorAllowed(bool aIsAllowed
) {
711 if (aIsAllowed
!= mCustomCursorAllowed
) {
712 mCustomCursorAllowed
= aIsAllowed
;
713 mUpdateCursor
= true;
718 //-------------------------------------------------------------------------
720 // Window transparency methods
722 //-------------------------------------------------------------------------
724 void nsBaseWidget::SetTransparencyMode(TransparencyMode aMode
) {}
726 TransparencyMode
nsBaseWidget::GetTransparencyMode() {
727 return TransparencyMode::Opaque
;
731 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage
,
734 nsIRunnable
* aCallback
) {
735 MOZ_ASSERT_UNREACHABLE(
736 "Should never call PerformFullscreenTransition on nsBaseWidget");
739 //-------------------------------------------------------------------------
741 // Put the window into full-screen mode
743 //-------------------------------------------------------------------------
744 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen
) {
745 #define MOZ_FORMAT_RECT(fmtstr) "[" fmtstr "," fmtstr " " fmtstr "x" fmtstr "]"
746 #define MOZ_SPLAT_RECT(rect) \
747 (rect).X(), (rect).Y(), (rect).Width(), (rect).Height()
749 // Windows which can be made fullscreen are exactly those which are located on
750 // the desktop, rather than being a child of some other window.
751 MOZ_DIAGNOSTIC_ASSERT(BoundsUseDesktopPixels(),
752 "non-desktop windows cannot be made fullscreen");
754 // Ensure that the OS chrome is hidden/shown before we resize and/or exit the
757 // HideWindowChrome() may (depending on platform, implementation details, and
758 // OS-level user preferences) alter the reported size of the window. The
759 // obvious and principled solution is socks-and-shoes:
760 // - On entering fullscreen mode: hide window chrome, then perform resize.
761 // - On leaving fullscreen mode: unperform resize, then show window chrome.
763 // ... unfortunately, HideWindowChrome() requires Resize() to be called
764 // afterwards (see bug 498835), which prevents this from being done in a
765 // straightforward way.
767 // Instead, we always call HideWindowChrome() just before we call Resize().
768 // This at least ensures that our measurements are consistently taken in a
769 // pre-transition state.
771 // ... unfortunately again, coupling HideWindowChrome() to Resize() means that
772 // we have to worry about the possibility of control flows that don't call
773 // Resize() at all. (That shouldn't happen, but it's not trivial to rule out.)
774 // We therefore set up a fallback to fix up the OS chrome if it hasn't been
775 // done at exit time.
776 bool hasAdjustedOSChrome
= false;
777 const auto adjustOSChrome
= [&]() {
778 if (hasAdjustedOSChrome
) {
779 MOZ_ASSERT_UNREACHABLE("window chrome should only be adjusted once");
782 HideWindowChrome(aFullScreen
);
783 hasAdjustedOSChrome
= true;
785 const auto adjustChromeOnScopeExit
= MakeScopeExit([&]() {
786 if (hasAdjustedOSChrome
) {
790 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
791 ("window was not resized within InfallibleMakeFullScreen()"));
793 // Hide chrome and "resize" the window to its current size.
794 auto rect
= GetBounds();
796 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
799 // Attempt to resize to `rect`.
801 // Returns the actual rectangle resized to. (This may differ from `rect`, if
802 // the OS is unhappy with it. See bug 1786226.)
803 const auto doReposition
= [&](auto rect
) -> void {
804 static_assert(std::is_base_of_v
<DesktopPixel
,
805 std::remove_reference_t
<decltype(rect
)>>,
806 "doReposition requires a rectangle using desktop pixels");
808 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Debug
)) {
809 const DesktopRect previousSize
=
810 GetScreenBounds() / GetDesktopToDeviceScale();
811 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
812 ("before resize: " MOZ_FORMAT_RECT("%f"),
813 MOZ_SPLAT_RECT(previousSize
)));
817 Resize(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height(), true);
819 if (MOZ_LOG_TEST(sBaseWidgetLog
, LogLevel::Warning
)) {
820 // `rect` may have any underlying data type; coerce to float to
821 // simplify printf-style logging
822 const gfx::RectTyped
<DesktopPixel
, float> rectAsFloat
{rect
};
824 // The OS may have objected to the target position. That's not necessarily
825 // a problem -- it'll happen regularly on Macs with camera notches in the
826 // monitor, for instance (see bug 1786226) -- but it probably deserves to
829 // Since there's floating-point math involved, the actual values may be
830 // off by a few ulps -- as an upper bound, perhaps 8 * FLT_EPSILON *
831 // max(MOZ_SPLAT_RECT(rect)) -- but 0.01 should be several orders of
832 // magnitude bigger than that.
834 const auto postResizeRectRaw
= GetScreenBounds();
835 const auto postResizeRect
= postResizeRectRaw
/ GetDesktopToDeviceScale();
836 const bool succeeded
= postResizeRect
.WithinEpsilonOf(rectAsFloat
, 0.01);
839 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
840 ("resized to: " MOZ_FORMAT_RECT("%f"),
841 MOZ_SPLAT_RECT(rectAsFloat
)));
843 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
844 ("attempted to resize to: " MOZ_FORMAT_RECT("%f"),
845 MOZ_SPLAT_RECT(rectAsFloat
)));
846 MOZ_LOG(sBaseWidgetLog
, LogLevel::Warning
,
847 ("... but ended up at: " MOZ_FORMAT_RECT("%f"),
848 MOZ_SPLAT_RECT(postResizeRect
)));
852 sBaseWidgetLog
, LogLevel::Verbose
,
853 ("(... which, before DPI adjustment, is:" MOZ_FORMAT_RECT("%d") ")",
854 MOZ_SPLAT_RECT(postResizeRectRaw
)));
860 mSavedBounds
= Some(FullscreenSavedState());
862 // save current position
863 mSavedBounds
->windowRect
= GetScreenBounds() / GetDesktopToDeviceScale();
865 nsCOMPtr
<nsIScreen
> screen
= GetWidgetScreen();
870 // Move to fill the screen.
871 doReposition(screen
->GetRectDisplayPix());
872 // Save off the new position. (This may differ from GetRectDisplayPix(), if
873 // the OS was unhappy with it. See bug 1786226.)
874 mSavedBounds
->screenRect
= GetScreenBounds() / GetDesktopToDeviceScale();
877 // This should never happen, at present, since we don't make windows
878 // fullscreen at their creation time; but it's not logically impossible.
879 MOZ_ASSERT(false, "fullscreen window did not have saved position");
883 // Figure out where to go from here.
885 // Fortunately, since we're currently fullscreen (and other code should be
886 // handling _keeping_ us fullscreen even after display-layout changes),
887 // there's an obvious choice for which display we should attach to; all we
888 // need to determine is where on that display we should go.
890 const DesktopRect currentWinRect
=
891 GetScreenBounds() / GetDesktopToDeviceScale();
893 // Optimization: if where we are is where we were, then where we originally
894 // came from is where we're going to go.
895 if (currentWinRect
== DesktopRect(mSavedBounds
->screenRect
)) {
896 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
897 ("no location change detected; returning to saved location"));
898 doReposition(mSavedBounds
->windowRect
);
903 General case: figure out where we're going to go by dividing where we are
904 by where we were, and then multiplying by where we originally came from.
906 Less abstrusely: resize so that we occupy the same proportional position
907 on our current display after leaving fullscreen as we occupied on our
908 previous display before entering fullscreen.
910 (N.B.: We do not clamp. If we were only partially on the old display,
911 we'll be only partially on the new one, too.)
914 MOZ_LOG(sBaseWidgetLog
, LogLevel::Debug
,
915 ("location change detected; computing new destination"));
917 // splat: convert an arbitrary Rect into a tuple, for syntactic convenience.
918 const auto splat
= [](auto rect
) {
919 return std::tuple(rect
.X(), rect
.Y(), rect
.Width(), rect
.Height());
922 // remap: find the unique affine mapping which transforms `src` to `dst`,
923 // and apply it to `val`.
924 using Range
= std::pair
<float, float>;
925 const auto remap
= [](Range dst
, Range src
, float val
) {
926 // linear interpolation and its inverse: lerp(a, b, invlerp(a, b, t)) == t
927 const auto lerp
= [](float lo
, float hi
, float t
) {
928 return lo
+ t
* (hi
- lo
);
930 const auto invlerp
= [](float lo
, float hi
, float mid
) {
931 return (mid
- lo
) / (hi
- lo
);
934 const auto [dst_a
, dst_b
] = dst
;
935 const auto [src_a
, src_b
] = src
;
936 return lerp(dst_a
, dst_b
, invlerp(src_a
, src_b
, val
));
940 const auto [px
, py
, pw
, ph
] = splat(mSavedBounds
->windowRect
);
941 // source desktop rect
942 const auto [sx
, sy
, sw
, sh
] = splat(mSavedBounds
->screenRect
);
943 // target desktop rect
944 const auto [tx
, ty
, tw
, th
] = splat(currentWinRect
);
946 const float nx
= remap({tx
, tx
+ tw
}, {sx
, sx
+ sw
}, px
);
947 const float ny
= remap({ty
, ty
+ th
}, {sy
, sy
+ sh
}, py
);
948 const float nw
= remap({0, tw
}, {0, sw
}, pw
);
949 const float nh
= remap({0, th
}, {0, sh
}, ph
);
951 doReposition(DesktopRect
{nx
, ny
, nw
, nh
});
954 #undef MOZ_SPLAT_RECT
955 #undef MOZ_FORMAT_RECT
958 nsresult
nsBaseWidget::MakeFullScreen(bool aFullScreen
) {
959 InfallibleMakeFullScreen(aFullScreen
);
963 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
964 nsBaseWidget
* aWidget
, gfxContext
* aTarget
, BufferMode aDoubleBuffering
)
966 WindowRenderer
* renderer
= mWidget
->GetWindowRenderer();
967 if (renderer
->AsFallback()) {
968 mRenderer
= renderer
->AsFallback();
969 mRenderer
->SetTarget(aTarget
, aDoubleBuffering
);
973 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
975 mRenderer
->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE
);
979 bool nsBaseWidget::IsSmallPopup() const {
980 return mWindowType
== WindowType::Popup
&& mPopupType
!= PopupType::Panel
;
983 bool nsBaseWidget::ComputeShouldAccelerate() {
984 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING
) &&
985 (WidgetTypeSupportsAcceleration() ||
986 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
989 bool nsBaseWidget::UseAPZ() {
990 return (gfxPlatform::AsyncPanZoomEnabled() &&
991 (mWindowType
== WindowType::TopLevel
||
992 mWindowType
== WindowType::Child
||
993 ((mWindowType
== WindowType::Popup
||
994 mWindowType
== WindowType::Dialog
) &&
995 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
998 void nsBaseWidget::CreateCompositor() {
999 LayoutDeviceIntRect rect
= GetBounds();
1000 CreateCompositor(rect
.Width(), rect
.Height());
1003 void nsIWidget::PauseOrResumeCompositor(bool aPause
) {
1004 auto* renderer
= GetRemoteRenderer();
1009 renderer
->SendPause();
1011 renderer
->SendResume();
1015 already_AddRefed
<GeckoContentController
>
1016 nsBaseWidget::CreateRootContentController() {
1017 RefPtr
<GeckoContentController
> controller
=
1018 new ChromeProcessController(this, mAPZEventState
, mAPZC
);
1019 return controller
.forget();
1022 void nsBaseWidget::ConfigureAPZCTreeManager() {
1023 MOZ_ASSERT(NS_IsMainThread());
1026 mAPZC
->SetDPI(GetDPI());
1028 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
1029 KeyboardMap map
= RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
1030 mAPZC
->SetKeyboardMap(map
);
1033 ContentReceivedInputBlockCallback
callback(
1034 [treeManager
= RefPtr
{mAPZC
.get()}](uint64_t aInputBlockId
,
1035 bool aPreventDefault
) {
1036 MOZ_ASSERT(NS_IsMainThread());
1037 treeManager
->ContentReceivedInputBlock(aInputBlockId
, aPreventDefault
);
1039 mAPZEventState
= new APZEventState(this, std::move(callback
));
1041 mRootContentController
= CreateRootContentController();
1042 if (mRootContentController
) {
1043 mCompositorSession
->SetContentController(mRootContentController
);
1046 // When APZ is enabled, we can actually enable raw touch events because we
1047 // have code that can deal with them properly. If APZ is not enabled, this
1048 // function doesn't get called.
1049 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
1050 RegisterTouchWindow();
1054 void nsBaseWidget::ConfigureAPZControllerThread() {
1055 // By default the controller thread is the main thread.
1056 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
1059 void nsBaseWidget::SetConfirmedTargetAPZC(
1060 uint64_t aInputBlockId
,
1061 const nsTArray
<ScrollableLayerGuid
>& aTargets
) const {
1062 mAPZC
->SetTargetAPZC(aInputBlockId
, aTargets
);
1065 void nsBaseWidget::UpdateZoomConstraints(
1066 const uint32_t& aPresShellId
, const ScrollableLayerGuid::ViewID
& aViewId
,
1067 const Maybe
<ZoomConstraints
>& aConstraints
) {
1068 if (!mCompositorSession
|| !mAPZC
) {
1069 MOZ_ASSERT_IF(mInitialZoomConstraints
,
1070 mInitialZoomConstraints
->mViewID
== aViewId
);
1072 // We have some constraints, but the compositor and APZC aren't
1073 // created yet. Save these so we can use them later.
1074 mInitialZoomConstraints
= Some(
1075 InitialZoomConstraints(aPresShellId
, aViewId
, aConstraints
.ref()));
1077 mInitialZoomConstraints
.reset();
1081 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
1082 mAPZC
->UpdateZoomConstraints(
1083 ScrollableLayerGuid(layersId
, aPresShellId
, aViewId
), aConstraints
);
1086 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC
; }
1088 nsEventStatus
nsBaseWidget::ProcessUntransformedAPZEvent(
1089 WidgetInputEvent
* aEvent
, const APZEventResult
& aApzResult
) {
1090 MOZ_ASSERT(NS_IsMainThread());
1091 ScrollableLayerGuid targetGuid
= aApzResult
.mTargetGuid
;
1092 uint64_t inputBlockId
= aApzResult
.mInputBlockId
;
1093 InputAPZContext
context(aApzResult
.mTargetGuid
, inputBlockId
,
1094 aApzResult
.GetStatus());
1096 // Make a copy of the original event for the APZCCallbackHelper helpers that
1097 // we call later, because the event passed to DispatchEvent can get mutated in
1098 // ways that we don't want (i.e. touch points can get stripped out).
1099 nsEventStatus status
;
1100 UniquePtr
<WidgetEvent
> original(aEvent
->Duplicate());
1101 DispatchEvent(aEvent
, status
);
1103 if (mAPZC
&& !InputAPZContext::WasRoutedToChildProcess() &&
1104 !InputAPZContext::WasDropped() && inputBlockId
) {
1105 // EventStateManager did not route the event into the child process and
1106 // the event was dispatched in the parent process.
1107 // It's safe to communicate to APZ that the event has been processed.
1108 // Note that here aGuid.mLayersId might be different from
1109 // mCompositorSession->RootLayerTreeId() because the event might have gotten
1110 // hit-tested by APZ to be targeted at a child process, but a parent process
1111 // event listener called preventDefault on it. In that case aGuid.mLayersId
1112 // would still be the layers id for the child process, but the event would
1113 // not have actually gotten routed to the child process. The main-thread
1114 // hit-test result therefore needs to use the parent process layers id.
1115 LayersId rootLayersId
= mCompositorSession
->RootLayerTreeId();
1117 RefPtr
<DisplayportSetListener
> postLayerization
;
1118 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1119 nsTArray
<TouchBehaviorFlags
> allowedTouchBehaviors
;
1120 if (touchEvent
->mMessage
== eTouchStart
) {
1121 auto& originalEvent
= *original
->AsTouchEvent();
1122 MOZ_ASSERT(NS_IsMainThread());
1123 allowedTouchBehaviors
= TouchActionHelper::GetAllowedTouchBehavior(
1124 this, GetDocument(), originalEvent
);
1125 if (!allowedTouchBehaviors
.IsEmpty()) {
1126 mAPZC
->SetAllowedTouchBehavior(inputBlockId
, allowedTouchBehaviors
);
1128 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1129 this, GetDocument(), originalEvent
, rootLayersId
, inputBlockId
);
1131 mAPZEventState
->ProcessTouchEvent(*touchEvent
, targetGuid
, inputBlockId
,
1132 aApzResult
.GetStatus(), status
,
1133 std::move(allowedTouchBehaviors
));
1134 } else if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1135 MOZ_ASSERT(wheelEvent
->mFlags
.mHandledByAPZ
);
1136 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1137 this, GetDocument(), *original
->AsWheelEvent(), rootLayersId
,
1139 if (wheelEvent
->mCanTriggerSwipe
) {
1140 ReportSwipeStarted(inputBlockId
, wheelEvent
->TriggersSwipe());
1142 mAPZEventState
->ProcessWheelEvent(*wheelEvent
, inputBlockId
);
1143 } else if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1144 MOZ_ASSERT(mouseEvent
->mFlags
.mHandledByAPZ
);
1145 postLayerization
= APZCCallbackHelper::SendSetTargetAPZCNotification(
1146 this, GetDocument(), *original
->AsMouseEvent(), rootLayersId
,
1148 mAPZEventState
->ProcessMouseEvent(*mouseEvent
, inputBlockId
);
1150 if (postLayerization
) {
1151 postLayerization
->Register();
1158 template <class InputType
, class EventType
>
1159 class DispatchEventOnMainThread
: public Runnable
{
1161 DispatchEventOnMainThread(const InputType
& aInput
, nsBaseWidget
* aWidget
,
1162 const APZEventResult
& aAPZResult
)
1163 : mozilla::Runnable("DispatchEventOnMainThread"),
1166 mAPZResult(aAPZResult
) {}
1168 NS_IMETHOD
Run() override
{
1169 EventType event
= mInput
.ToWidgetEvent(mWidget
);
1170 mWidget
->ProcessUntransformedAPZEvent(&event
, mAPZResult
);
1176 nsBaseWidget
* mWidget
;
1177 APZEventResult mAPZResult
;
1180 template <class InputType
, class EventType
>
1181 class DispatchInputOnControllerThread
: public Runnable
{
1183 enum class APZOnly
{ Yes
, No
};
1184 DispatchInputOnControllerThread(const EventType
& aEvent
,
1185 IAPZCTreeManager
* aAPZC
,
1186 nsBaseWidget
* aWidget
,
1187 APZOnly aAPZOnly
= APZOnly::No
)
1188 : mozilla::Runnable("DispatchInputOnControllerThread"),
1189 mMainMessageLoop(MessageLoop::current()),
1193 mAPZOnly(aAPZOnly
) {}
1195 NS_IMETHOD
Run() override
{
1196 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(mInput
);
1197 if (mAPZOnly
== APZOnly::Yes
||
1198 result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1201 RefPtr
<Runnable
> r
= new DispatchEventOnMainThread
<InputType
, EventType
>(
1202 mInput
, mWidget
, result
);
1203 mMainMessageLoop
->PostTask(r
.forget());
1208 MessageLoop
* mMainMessageLoop
;
1210 RefPtr
<IAPZCTreeManager
> mAPZC
;
1211 nsBaseWidget
* mWidget
;
1212 const APZOnly mAPZOnly
;
1215 void nsBaseWidget::DispatchTouchInput(MultiTouchInput
& aInput
,
1216 uint16_t aInputSource
) {
1217 MOZ_ASSERT(NS_IsMainThread());
1218 MOZ_ASSERT(aInputSource
==
1219 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH
||
1220 aInputSource
== mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN
);
1222 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1224 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1225 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1229 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1230 ProcessUntransformedAPZEvent(&event
, result
);
1232 WidgetTouchEvent event
= aInput
.ToWidgetEvent(this, aInputSource
);
1234 nsEventStatus status
;
1235 DispatchEvent(&event
, status
);
1239 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput
& aInput
) {
1240 MOZ_ASSERT(NS_IsMainThread());
1242 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1244 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1245 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1249 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1250 ProcessUntransformedAPZEvent(&event
, result
);
1252 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1253 nsEventStatus status
;
1254 DispatchEvent(&event
, status
);
1258 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput
& aInput
) {
1259 MOZ_ASSERT(NS_IsMainThread());
1261 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1262 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(aInput
);
1264 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1267 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1268 ProcessUntransformedAPZEvent(&event
, result
);
1270 WidgetWheelEvent event
= aInput
.ToWidgetEvent(this);
1271 nsEventStatus status
;
1272 DispatchEvent(&event
, status
);
1276 nsIWidget::ContentAndAPZEventStatus
nsBaseWidget::DispatchInputEvent(
1277 WidgetInputEvent
* aEvent
) {
1278 nsIWidget::ContentAndAPZEventStatus status
;
1279 MOZ_ASSERT(NS_IsMainThread());
1282 if (APZThreadUtils::IsControllerThread()) {
1283 APZEventResult result
= mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1284 status
.mApzStatus
= result
.GetStatus();
1285 if (result
.GetStatus() == nsEventStatus_eConsumeNoDefault
) {
1288 status
.mContentStatus
= ProcessUntransformedAPZEvent(aEvent
, result
);
1291 // Most drag events aren't able to converted to MouseEvent except to
1292 // eDragStart and eDragEnd.
1293 const bool canDispatchToApzc
=
1294 !aEvent
->AsDragEvent() ||
1295 aEvent
->AsDragEvent()->CanConvertToInputData();
1296 if (canDispatchToApzc
) {
1297 if (WidgetWheelEvent
* wheelEvent
= aEvent
->AsWheelEvent()) {
1298 RefPtr
<Runnable
> r
=
1299 new DispatchInputOnControllerThread
<ScrollWheelInput
,
1300 WidgetWheelEvent
>(*wheelEvent
,
1302 APZThreadUtils::RunOnControllerThread(std::move(r
));
1303 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1306 if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1307 RefPtr
<Runnable
> r
=
1308 new DispatchInputOnControllerThread
<MouseInput
, WidgetMouseEvent
>(
1309 *mouseEvent
, mAPZC
, this);
1310 APZThreadUtils::RunOnControllerThread(std::move(r
));
1311 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1314 if (WidgetTouchEvent
* touchEvent
= aEvent
->AsTouchEvent()) {
1315 RefPtr
<Runnable
> r
=
1316 new DispatchInputOnControllerThread
<MultiTouchInput
,
1317 WidgetTouchEvent
>(*touchEvent
,
1319 APZThreadUtils::RunOnControllerThread(std::move(r
));
1320 status
.mContentStatus
= nsEventStatus_eConsumeDoDefault
;
1323 // Allow dispatching keyboard/drag events on Gecko thread
1324 // without sending them to APZ
1326 // FIXME: APZ can handle keyboard events now, we should
1327 // be sending them to APZ here
1328 MOZ_ASSERT(aEvent
->AsKeyboardEvent() || aEvent
->AsDragEvent());
1332 DispatchEvent(aEvent
, status
.mContentStatus
);
1336 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent
* aEvent
) {
1337 MOZ_ASSERT(NS_IsMainThread());
1339 if (APZThreadUtils::IsControllerThread()) {
1340 mAPZC
->InputBridge()->ReceiveInputEvent(*aEvent
);
1344 if (WidgetMouseEvent
* mouseEvent
= aEvent
->AsMouseEvent()) {
1345 RefPtr
<Runnable
> r
=
1346 new DispatchInputOnControllerThread
<MouseInput
, WidgetMouseEvent
>(
1347 *mouseEvent
, mAPZC
, this,
1348 DispatchInputOnControllerThread
<MouseInput
,
1349 WidgetMouseEvent
>::APZOnly::Yes
);
1350 APZThreadUtils::RunOnControllerThread(std::move(r
));
1354 MOZ_ASSERT_UNREACHABLE("Not implemented yet");
1358 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent
& event
) {
1359 nsEventStatus status
;
1360 DispatchEvent(&event
, status
);
1361 return ConvertStatus(status
);
1364 Document
* nsBaseWidget::GetDocument() const {
1365 if (mWidgetListener
) {
1366 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1367 return presShell
->GetDocument();
1373 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1374 // Parent directly listens to the vsync source whereas
1375 // child process communicate via IPC
1376 // Should be called AFTER gfxPlatform is initialized
1377 if (XRE_IsParentProcess()) {
1378 if (!mCompositorVsyncDispatcherLock
) {
1379 mCompositorVsyncDispatcherLock
=
1380 MakeUnique
<Mutex
>("mCompositorVsyncDispatcherLock");
1382 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1383 if (!mCompositorVsyncDispatcher
) {
1384 RefPtr
<VsyncDispatcher
> vsyncDispatcher
=
1385 gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
1386 mCompositorVsyncDispatcher
=
1387 new CompositorVsyncDispatcher(std::move(vsyncDispatcher
));
1392 already_AddRefed
<CompositorVsyncDispatcher
>
1393 nsBaseWidget::GetCompositorVsyncDispatcher() {
1394 MOZ_ASSERT(mCompositorVsyncDispatcherLock
.get());
1396 MutexAutoLock
lock(*mCompositorVsyncDispatcherLock
.get());
1397 RefPtr
<CompositorVsyncDispatcher
> dispatcher
= mCompositorVsyncDispatcher
;
1398 return dispatcher
.forget();
1401 already_AddRefed
<WebRenderLayerManager
> nsBaseWidget::CreateCompositorSession(
1402 int aWidth
, int aHeight
, CompositorOptions
* aOptionsOut
) {
1403 MOZ_ASSERT(aOptionsOut
);
1406 CreateCompositorVsyncDispatcher();
1408 gfx::GPUProcessManager
* gpu
= gfx::GPUProcessManager::Get();
1409 // Make sure GPU process is ready for use.
1410 // If it failed to connect to GPU process, GPU process usage is disabled in
1411 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1412 nsresult rv
= gpu
->EnsureGPUReady();
1413 if (NS_WARN_IF(rv
== NS_ERROR_ILLEGAL_DURING_SHUTDOWN
)) {
1417 // If widget type does not supports acceleration, we may be allowed to use
1418 // software WebRender instead.
1419 bool supportsAcceleration
= WidgetTypeSupportsAcceleration();
1420 bool enableSWWR
= true;
1421 if (supportsAcceleration
||
1422 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1423 enableSWWR
= gfx::gfxVars::UseSoftwareWebRender();
1425 bool enableAPZ
= UseAPZ();
1426 CompositorOptions
options(enableAPZ
, enableSWWR
);
1429 if (supportsAcceleration
) {
1430 options
.SetAllowSoftwareWebRenderD3D11(
1431 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1433 if (mNeedFastSnaphot
) {
1434 options
.SetNeedFastSnaphot(true);
1436 #elif defined(MOZ_WIDGET_ANDROID)
1437 MOZ_ASSERT(supportsAcceleration
);
1438 options
.SetAllowSoftwareWebRenderOGL(
1439 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1440 #elif defined(MOZ_WIDGET_GTK)
1441 if (supportsAcceleration
) {
1442 options
.SetAllowSoftwareWebRenderOGL(
1443 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1447 #ifdef MOZ_WIDGET_ANDROID
1448 // Unconditionally set the compositor as initially paused, as we have not
1449 // yet had a chance to send the compositor surface to the GPU process. We
1450 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1451 // where we will also resume the compositor if required.
1452 options
.SetInitiallyPaused(true);
1454 options
.SetInitiallyPaused(CompositorInitiallyPaused());
1457 RefPtr
<WebRenderLayerManager
> lm
= new WebRenderLayerManager(this);
1459 uint64_t innerWindowId
= 0;
1460 if (Document
* doc
= GetDocument()) {
1461 innerWindowId
= doc
->InnerWindowID();
1465 mCompositorSession
= gpu
->CreateTopLevelCompositor(
1466 this, lm
, GetDefaultScale(), options
, UseExternalCompositingSurface(),
1467 gfx::IntSize(aWidth
, aHeight
), innerWindowId
, &retry
);
1469 if (mCompositorSession
) {
1470 TextureFactoryIdentifier textureFactoryIdentifier
;
1472 lm
->Initialize(mCompositorSession
->GetCompositorBridgeChild(),
1473 wr::AsPipelineId(mCompositorSession
->RootLayerTreeId()),
1474 &textureFactoryIdentifier
, error
);
1475 if (textureFactoryIdentifier
.mParentBackend
!= LayersBackend::LAYERS_WR
) {
1477 DestroyCompositor();
1478 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1479 gfx::GPUProcessManager::Get()->DisableWebRender(
1480 wr::WebRenderError::INITIALIZE
, error
);
1484 // We need to retry in a loop because the act of failing to create the
1485 // compositor can change our state (e.g. disable WebRender).
1486 if (mCompositorSession
|| !retry
) {
1487 *aOptionsOut
= options
;
1493 void nsBaseWidget::CreateCompositor(int aWidth
, int aHeight
) {
1494 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1495 gfxPlatform::GetPlatform();
1497 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1498 "This function assumes OMTC");
1500 MOZ_ASSERT(!mCompositorSession
&& !mCompositorBridgeChild
,
1501 "Should have properly cleaned up the previous PCompositor pair "
1504 if (mCompositorBridgeChild
) {
1505 mCompositorBridgeChild
->Destroy();
1508 // Recreating this is tricky, as we may still have an old and we need
1509 // to make sure it's properly destroyed by calling DestroyCompositor!
1511 // If we've already received a shutdown notification, don't try
1512 // create a new compositor.
1513 if (!mShutdownObserver
) {
1517 // The controller thread must be configured before the compositor
1518 // session is created, so that the input bridge runs on the right
1520 ConfigureAPZControllerThread();
1522 CompositorOptions options
;
1523 RefPtr
<WebRenderLayerManager
> lm
=
1524 CreateCompositorSession(aWidth
, aHeight
, &options
);
1529 MOZ_ASSERT(mCompositorSession
);
1530 mCompositorBridgeChild
= mCompositorSession
->GetCompositorBridgeChild();
1531 SetCompositorWidgetDelegate(
1532 mCompositorSession
->GetCompositorWidgetDelegate());
1534 if (options
.UseAPZ()) {
1535 mAPZC
= mCompositorSession
->GetAPZCTreeManager();
1536 ConfigureAPZCTreeManager();
1541 if (mInitialZoomConstraints
) {
1542 UpdateZoomConstraints(mInitialZoomConstraints
->mPresShellID
,
1543 mInitialZoomConstraints
->mViewID
,
1544 Some(mInitialZoomConstraints
->mConstraints
));
1545 mInitialZoomConstraints
.reset();
1548 TextureFactoryIdentifier textureFactoryIdentifier
=
1549 lm
->GetTextureFactoryIdentifier();
1550 MOZ_ASSERT(textureFactoryIdentifier
.mParentBackend
==
1551 LayersBackend::LAYERS_WR
);
1552 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier
);
1553 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier
);
1557 mWindowRenderer
= std::move(lm
);
1559 // Only track compositors for top-level windows, since other window types
1560 // may use the basic compositor. Except on the OS X - see bug 1306383
1561 #if defined(XP_MACOSX)
1562 bool getCompositorFromThisWindow
= true;
1564 bool getCompositorFromThisWindow
= mWindowType
== WindowType::TopLevel
;
1567 if (getCompositorFromThisWindow
) {
1568 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1569 mWindowRenderer
->GetCompositorBackendType());
1573 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession
* aSession
) {
1574 MOZ_ASSERT(aSession
== mCompositorSession
);
1575 DestroyLayerManager();
1578 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1579 return gfxPlatform::UsesOffMainThreadCompositing();
1582 WindowRenderer
* nsBaseWidget::GetWindowRenderer() {
1583 if (!mWindowRenderer
) {
1584 if (!mShutdownObserver
) {
1585 // We are shutting down, do not try to re-create a LayerManager
1588 // Try to use an async compositor first, if possible
1589 if (ShouldUseOffMainThreadCompositing()) {
1593 if (!mWindowRenderer
) {
1594 mWindowRenderer
= CreateFallbackRenderer();
1597 return mWindowRenderer
;
1600 WindowRenderer
* nsBaseWidget::CreateFallbackRenderer() {
1601 return new FallbackRenderer
;
1604 CompositorBridgeChild
* nsBaseWidget::GetRemoteRenderer() {
1605 return mCompositorBridgeChild
;
1608 void nsBaseWidget::ClearCachedWebrenderResources() {
1609 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1612 mWindowRenderer
->AsWebRender()->ClearCachedResources();
1615 void nsBaseWidget::ClearWebrenderAnimationResources() {
1616 if (!mWindowRenderer
|| !mWindowRenderer
->AsWebRender()) {
1619 mWindowRenderer
->AsWebRender()->ClearAnimationResources();
1622 bool nsBaseWidget::SetNeedFastSnaphot() {
1623 MOZ_ASSERT(XRE_IsParentProcess());
1624 MOZ_ASSERT(!mCompositorSession
);
1626 if (!XRE_IsParentProcess() || mCompositorSession
) {
1630 mNeedFastSnaphot
= true;
1634 already_AddRefed
<gfx::DrawTarget
> nsBaseWidget::StartRemoteDrawing() {
1638 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA
; }
1640 //-------------------------------------------------------------------------
1642 // Destroy the window
1644 //-------------------------------------------------------------------------
1645 void nsBaseWidget::OnDestroy() {
1646 if (mTextEventDispatcher
) {
1647 mTextEventDispatcher
->OnDestroyWidget();
1648 // Don't release it until this widget actually released because after this
1649 // is called, TextEventDispatcher() may create it again.
1652 // If this widget is being destroyed, let the APZ code know to drop references
1653 // to this widget. Callers of this function all should be holding a deathgrip
1654 // on this widget already.
1655 ReleaseContentController();
1658 void nsBaseWidget::MoveClient(const DesktopPoint
& aOffset
) {
1659 LayoutDeviceIntPoint
clientOffset(GetClientOffset());
1661 // GetClientOffset returns device pixels; scale back to desktop pixels
1662 // if that's what this widget uses for the Move/Resize APIs
1663 if (BoundsUseDesktopPixels()) {
1664 DesktopPoint desktopOffset
= clientOffset
/ GetDesktopToDeviceScale();
1665 Move(aOffset
.x
- desktopOffset
.x
, aOffset
.y
- desktopOffset
.y
);
1667 LayoutDevicePoint layoutOffset
= aOffset
* GetDesktopToDeviceScale();
1668 Move(layoutOffset
.x
- LayoutDeviceCoord(clientOffset
.x
),
1669 layoutOffset
.y
- LayoutDeviceCoord(clientOffset
.y
));
1673 void nsBaseWidget::ResizeClient(const DesktopSize
& aSize
, bool aRepaint
) {
1674 NS_ASSERTION((aSize
.width
>= 0), "Negative width passed to ResizeClient");
1675 NS_ASSERTION((aSize
.height
>= 0), "Negative height passed to ResizeClient");
1677 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1679 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1680 // if that's what this widget uses for the Move/Resize APIs
1681 if (BoundsUseDesktopPixels()) {
1682 DesktopSize desktopDelta
=
1683 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1684 clientBounds
.Size()) /
1685 GetDesktopToDeviceScale();
1686 Resize(aSize
.width
+ desktopDelta
.width
, aSize
.height
+ desktopDelta
.height
,
1689 LayoutDeviceSize layoutSize
= aSize
* GetDesktopToDeviceScale();
1690 Resize(mBounds
.Width() + (layoutSize
.width
- clientBounds
.Width()),
1691 mBounds
.Height() + (layoutSize
.height
- clientBounds
.Height()),
1696 void nsBaseWidget::ResizeClient(const DesktopRect
& aRect
, bool aRepaint
) {
1697 NS_ASSERTION((aRect
.Width() >= 0), "Negative width passed to ResizeClient");
1698 NS_ASSERTION((aRect
.Height() >= 0), "Negative height passed to ResizeClient");
1700 LayoutDeviceIntRect clientBounds
= GetClientBounds();
1701 LayoutDeviceIntPoint clientOffset
= GetClientOffset();
1702 DesktopToLayoutDeviceScale scale
= GetDesktopToDeviceScale();
1704 if (BoundsUseDesktopPixels()) {
1705 DesktopPoint desktopOffset
= clientOffset
/ scale
;
1706 DesktopSize desktopDelta
=
1707 (LayoutDeviceIntSize(mBounds
.Width(), mBounds
.Height()) -
1708 clientBounds
.Size()) /
1710 Resize(aRect
.X() - desktopOffset
.x
, aRect
.Y() - desktopOffset
.y
,
1711 aRect
.Width() + desktopDelta
.width
,
1712 aRect
.Height() + desktopDelta
.height
, aRepaint
);
1714 LayoutDeviceRect layoutRect
= aRect
* scale
;
1715 Resize(layoutRect
.X() - clientOffset
.x
, layoutRect
.Y() - clientOffset
.y
,
1716 layoutRect
.Width() + mBounds
.Width() - clientBounds
.Width(),
1717 layoutRect
.Height() + mBounds
.Height() - clientBounds
.Height(),
1722 //-------------------------------------------------------------------------
1726 //-------------------------------------------------------------------------
1729 * If the implementation of nsWindow supports borders this method MUST be
1733 LayoutDeviceIntRect
nsBaseWidget::GetClientBounds() { return GetBounds(); }
1736 * If the implementation of nsWindow supports borders this method MUST be
1740 LayoutDeviceIntRect
nsBaseWidget::GetBounds() { return mBounds
; }
1743 * If the implementation of nsWindow uses a local coordinate system within the
1744 *window, this method must be overridden
1747 LayoutDeviceIntRect
nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1749 nsresult
nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect
& aRect
) {
1750 if (SizeMode() != nsSizeMode_Normal
) {
1751 return NS_ERROR_FAILURE
;
1753 aRect
= GetScreenBounds();
1757 LayoutDeviceIntPoint
nsBaseWidget::GetClientOffset() {
1758 return LayoutDeviceIntPoint(0, 0);
1761 nsresult
nsBaseWidget::SetNonClientMargins(const LayoutDeviceIntMargin
&) {
1762 return NS_ERROR_NOT_IMPLEMENTED
;
1765 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin
) {}
1767 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1769 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1771 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect
* aResizerRect
) {
1776 * Modifies aFile to point at an icon file with the given name and suffix. The
1777 * suffix may correspond to a file extension with leading '.' if appropriate.
1778 * Returns true if the icon file exists and can be read.
1780 static bool ResolveIconNameHelper(nsIFile
* aFile
, const nsAString
& aIconName
,
1781 const nsAString
& aIconSuffix
) {
1782 aFile
->Append(u
"icons"_ns
);
1783 aFile
->Append(u
"default"_ns
);
1784 aFile
->Append(aIconName
+ aIconSuffix
);
1787 return NS_SUCCEEDED(aFile
->IsReadable(&readable
)) && readable
;
1791 * Resolve the given icon name into a local file object. This method is
1792 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1793 * platform specific icon file suffix (e.g., ".ico" under Win32).
1795 * If no file is found matching the given parameters, then null is returned.
1797 void nsBaseWidget::ResolveIconName(const nsAString
& aIconName
,
1798 const nsAString
& aIconSuffix
,
1799 nsIFile
** aResult
) {
1802 nsCOMPtr
<nsIProperties
> dirSvc
=
1803 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID
);
1804 if (!dirSvc
) return;
1806 // first check auxilary chrome directories
1808 nsCOMPtr
<nsISimpleEnumerator
> dirs
;
1809 dirSvc
->Get(NS_APP_CHROME_DIR_LIST
, NS_GET_IID(nsISimpleEnumerator
),
1810 getter_AddRefs(dirs
));
1813 while (NS_SUCCEEDED(dirs
->HasMoreElements(&hasMore
)) && hasMore
) {
1814 nsCOMPtr
<nsISupports
> element
;
1815 dirs
->GetNext(getter_AddRefs(element
));
1816 if (!element
) continue;
1817 nsCOMPtr
<nsIFile
> file
= do_QueryInterface(element
);
1818 if (!file
) continue;
1819 if (ResolveIconNameHelper(file
, aIconName
, aIconSuffix
)) {
1820 NS_ADDREF(*aResult
= file
);
1826 // then check the main app chrome directory
1828 nsCOMPtr
<nsIFile
> file
;
1829 dirSvc
->Get(NS_APP_CHROME_DIR
, NS_GET_IID(nsIFile
), getter_AddRefs(file
));
1830 if (file
&& ResolveIconNameHelper(file
, aIconName
, aIconSuffix
))
1831 NS_ADDREF(*aResult
= file
);
1834 void nsBaseWidget::SetSizeConstraints(const SizeConstraints
& aConstraints
) {
1835 mSizeConstraints
= aConstraints
;
1837 // Popups are constrained during layout, and we don't want to synchronously
1838 // paint from reflow, so bail out... This is not great, but it's no worse than
1839 // what we used to do.
1841 // The right fix here is probably making constraint changes go through the
1842 // view manager and such.
1843 if (mWindowType
== WindowType::Popup
) {
1847 // If the current size doesn't meet the new constraints, trigger a
1848 // resize to apply it. Note that, we don't want to invoke Resize if
1849 // the new constraints don't affect the current size, because Resize
1850 // implementation on some platforms may touch other geometry even if
1851 // the size don't need to change.
1852 LayoutDeviceIntSize curSize
= mBounds
.Size();
1853 LayoutDeviceIntSize clampedSize
=
1854 Max(aConstraints
.mMinSize
, Min(aConstraints
.mMaxSize
, curSize
));
1855 if (clampedSize
!= curSize
) {
1857 if (BoundsUseDesktopPixels()) {
1858 DesktopSize desktopSize
= clampedSize
/ GetDesktopToDeviceScale();
1859 size
= desktopSize
.ToUnknownSize();
1861 size
= gfx::Size(clampedSize
.ToUnknownSize());
1863 Resize(size
.width
, size
.height
, true);
1867 const widget::SizeConstraints
nsBaseWidget::GetSizeConstraints() {
1868 return mSizeConstraints
;
1872 nsIRollupListener
* nsBaseWidget::GetActiveRollupListener() {
1873 // TODO: Simplify this.
1874 return nsXULPopupManager::GetInstance();
1877 void nsBaseWidget::NotifyWindowDestroyed() {
1878 if (!mWidgetListener
) return;
1880 nsCOMPtr
<nsIAppWindow
> window
= mWidgetListener
->GetAppWindow();
1881 nsCOMPtr
<nsIBaseWindow
> appWindow(do_QueryInterface(window
));
1883 appWindow
->Destroy();
1887 void nsBaseWidget::NotifyWindowMoved(int32_t aX
, int32_t aY
,
1888 ByMoveToRect aByMoveToRect
) {
1889 if (mWidgetListener
) {
1890 mWidgetListener
->WindowMoved(this, aX
, aY
, aByMoveToRect
);
1893 if (mIMEHasFocus
&& IMENotificationRequestsRef().WantPositionChanged()) {
1894 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE
));
1898 void nsBaseWidget::NotifySizeMoveDone() {
1899 if (!mWidgetListener
) {
1902 if (PresShell
* presShell
= mWidgetListener
->GetPresShell()) {
1903 presShell
->WindowSizeMoveDone();
1907 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind
) {
1908 LookAndFeel::NotifyChangedAllWindows(aKind
);
1911 nsresult
nsBaseWidget::NotifyIME(const IMENotification
& aIMENotification
) {
1915 switch (aIMENotification
.mMessage
) {
1916 case REQUEST_TO_COMMIT_COMPOSITION
:
1917 case REQUEST_TO_CANCEL_COMPOSITION
:
1918 // We should send request to IME only when there is a TextEventDispatcher
1919 // instance (this means that this widget has dispatched at least one
1920 // composition event or keyboard event) and the it has composition.
1921 // Otherwise, there is nothing to do.
1922 // Note that if current input transaction is for native input events,
1923 // TextEventDispatcher::NotifyIME() will call
1924 // TextEventDispatcherListener::NotifyIME().
1925 if (mTextEventDispatcher
&& mTextEventDispatcher
->IsComposing()) {
1926 return mTextEventDispatcher
->NotifyIME(aIMENotification
);
1930 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_FOCUS
) {
1931 mIMEHasFocus
= true;
1933 EnsureTextEventDispatcher();
1934 // TextEventDispatcher::NotifyIME() will always call
1935 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1936 // input transaction is for synthesized events for automated tests,
1937 // notifications will be sent to native IME.
1938 nsresult rv
= mTextEventDispatcher
->NotifyIME(aIMENotification
);
1939 if (aIMENotification
.mMessage
== NOTIFY_IME_OF_BLUR
) {
1940 mIMEHasFocus
= false;
1947 void nsBaseWidget::EnsureTextEventDispatcher() {
1948 if (mTextEventDispatcher
) {
1951 mTextEventDispatcher
= new TextEventDispatcher(this);
1954 nsIWidget::NativeIMEContext
nsBaseWidget::GetNativeIMEContext() {
1955 if (mTextEventDispatcher
&& mTextEventDispatcher
->GetPseudoIMEContext()) {
1956 // If we already have a TextEventDispatcher and it's working with
1957 // a TextInputProcessor, we need to return pseudo IME context since
1958 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1959 // on the pseudo IME context in such case.
1960 NativeIMEContext pseudoIMEContext
;
1961 pseudoIMEContext
.InitWithRawNativeIMEContext(
1962 mTextEventDispatcher
->GetPseudoIMEContext());
1963 return pseudoIMEContext
;
1965 return NativeIMEContext(this);
1968 nsIWidget::TextEventDispatcher
* nsBaseWidget::GetTextEventDispatcher() {
1969 EnsureTextEventDispatcher();
1970 return mTextEventDispatcher
;
1973 void* nsBaseWidget::GetPseudoIMEContext() {
1974 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
1978 return dispatcher
->GetPseudoIMEContext();
1981 TextEventDispatcherListener
*
1982 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1983 // TODO: If all platforms supported use of TextEventDispatcher for handling
1984 // native IME and keyboard events, this method should be removed since
1985 // in such case, this is overridden by all the subclasses.
1989 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId
,
1990 const ScrollableLayerGuid::ViewID
& aViewId
,
1991 const CSSRect
& aRect
, const uint32_t& aFlags
) {
1992 if (!mCompositorSession
|| !mAPZC
) {
1995 LayersId layerId
= mCompositorSession
->RootLayerTreeId();
1996 mAPZC
->ZoomToRect(ScrollableLayerGuid(layerId
, aPresShellId
, aViewId
),
1997 ZoomTarget
{aRect
}, aFlags
);
2000 #ifdef ACCESSIBILITY
2002 a11y::LocalAccessible
* nsBaseWidget::GetRootAccessible() {
2003 NS_ENSURE_TRUE(mWidgetListener
, nullptr);
2005 PresShell
* presShell
= mWidgetListener
->GetPresShell();
2006 NS_ENSURE_TRUE(presShell
, nullptr);
2008 // If container is null then the presshell is not active. This often happens
2009 // when a preshell is being held onto for fastback.
2010 nsPresContext
* presContext
= presShell
->GetPresContext();
2011 NS_ENSURE_TRUE(presContext
->GetContainerWeak(), nullptr);
2013 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
2014 // make sure it's not created at unsafe times.
2015 nsAccessibilityService
* accService
= GetOrCreateAccService();
2017 return accService
->GetRootDocumentAccessible(
2018 presShell
, nsContentUtils::IsSafeToRunScript());
2024 #endif // ACCESSIBILITY
2026 void nsBaseWidget::StartAsyncScrollbarDrag(
2027 const AsyncDragMetrics
& aDragMetrics
) {
2028 if (!AsyncPanZoomEnabled()) {
2032 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession
);
2034 LayersId layersId
= mCompositorSession
->RootLayerTreeId();
2035 ScrollableLayerGuid
guid(layersId
, aDragMetrics
.mPresShellId
,
2036 aDragMetrics
.mViewId
);
2038 mAPZC
->StartScrollbarDrag(guid
, aDragMetrics
);
2041 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint
& aAnchorLocation
,
2042 const ScrollableLayerGuid
& aGuid
) {
2043 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2045 return mAPZC
->StartAutoscroll(aGuid
, aAnchorLocation
);
2048 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid
& aGuid
) {
2049 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2051 mAPZC
->StopAutoscroll(aGuid
);
2054 LayersId
nsBaseWidget::GetRootLayerTreeId() {
2055 return mCompositorSession
? mCompositorSession
->RootLayerTreeId()
2059 already_AddRefed
<widget::Screen
> nsBaseWidget::GetWidgetScreen() {
2060 ScreenManager
& screenManager
= ScreenManager::GetSingleton();
2061 LayoutDeviceIntRect bounds
= GetScreenBounds();
2062 DesktopIntRect deskBounds
= RoundedToInt(bounds
/ GetDesktopToDeviceScale());
2063 return screenManager
.ScreenForRect(deskBounds
);
2066 mozilla::DesktopToLayoutDeviceScale
2067 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
2068 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
2069 ->GetDesktopToDeviceScale();
2072 nsresult
nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint
,
2074 nsIObserver
* aObserver
) {
2075 AutoObserverNotifier
notifier(aObserver
, "touchtap");
2077 if (sPointerIdCounter
> TOUCH_INJECT_MAX_POINTS
) {
2078 sPointerIdCounter
= 0;
2080 int pointerId
= sPointerIdCounter
;
2081 sPointerIdCounter
++;
2082 nsresult rv
= SynthesizeNativeTouchPoint(pointerId
, TOUCH_CONTACT
, aPoint
,
2084 if (NS_FAILED(rv
)) {
2089 return SynthesizeNativeTouchPoint(pointerId
, TOUCH_REMOVE
, aPoint
, 0, 0,
2093 // initiate a long tap
2094 int elapse
= Preferences::GetInt("ui.click_hold_context_menus.delay",
2095 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC
);
2096 if (!mLongTapTimer
) {
2097 mLongTapTimer
= NS_NewTimer();
2098 if (!mLongTapTimer
) {
2099 SynthesizeNativeTouchPoint(pointerId
, TOUCH_CANCEL
, aPoint
, 0, 0,
2101 return NS_ERROR_UNEXPECTED
;
2103 // Windows requires recuring events, so we set this to a smaller window
2104 // than the pref value.
2105 int timeout
= elapse
;
2106 if (timeout
> TOUCH_INJECT_PUMP_TIMER_MSEC
) {
2107 timeout
= TOUCH_INJECT_PUMP_TIMER_MSEC
;
2109 mLongTapTimer
->InitWithNamedFuncCallback(
2110 OnLongTapTimerCallback
, this, timeout
, nsITimer::TYPE_REPEATING_SLACK
,
2111 "nsIWidget::SynthesizeNativeTouchTap");
2114 // If we already have a long tap pending, cancel it. We only allow one long
2115 // tap to be active at a time.
2116 if (mLongTapTouchPoint
) {
2117 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2118 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2121 mLongTapTouchPoint
= MakeUnique
<LongTapInfo
>(
2122 pointerId
, aPoint
, TimeDuration::FromMilliseconds(elapse
), aObserver
);
2123 notifier
.SkipNotification(); // we'll do it in the long-tap callback
2128 void nsIWidget::OnLongTapTimerCallback(nsITimer
* aTimer
, void* aClosure
) {
2129 auto* self
= static_cast<nsIWidget
*>(aClosure
);
2131 if ((self
->mLongTapTouchPoint
->mStamp
+ self
->mLongTapTouchPoint
->mDuration
) >
2134 // Windows needs us to keep pumping feedback to the digitizer, so update
2135 // the pointer id with the same position.
2136 self
->SynthesizeNativeTouchPoint(
2137 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_CONTACT
,
2138 self
->mLongTapTouchPoint
->mPosition
, 1.0, 90, nullptr);
2143 AutoObserverNotifier
notifier(self
->mLongTapTouchPoint
->mObserver
,
2146 // finished, remove the touch point
2147 self
->mLongTapTimer
->Cancel();
2148 self
->mLongTapTimer
= nullptr;
2149 self
->SynthesizeNativeTouchPoint(
2150 self
->mLongTapTouchPoint
->mPointerId
, TOUCH_REMOVE
,
2151 self
->mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2152 self
->mLongTapTouchPoint
= nullptr;
2155 float nsIWidget::GetFallbackDPI() {
2156 RefPtr
<const Screen
> primaryScreen
=
2157 ScreenManager::GetSingleton().GetPrimaryScreen();
2158 return primaryScreen
->GetDPI();
2161 CSSToLayoutDeviceScale
nsIWidget::GetFallbackDefaultScale() {
2162 RefPtr
<const Screen
> s
= ScreenManager::GetSingleton().GetPrimaryScreen();
2163 return s
->GetCSSToLayoutDeviceScale(Screen::IncludeOSZoom::No
);
2166 nsresult
nsIWidget::ClearNativeTouchSequence(nsIObserver
* aObserver
) {
2167 AutoObserverNotifier
notifier(aObserver
, "cleartouch");
2169 // XXX This is odd. This is called by the constructor of nsIWidget. However,
2170 // at that point, nsIWidget::mLongTapTimer must be nullptr. Therefore,
2171 // this must do nothing at initializing the instance.
2172 if (!mLongTapTimer
) {
2175 mLongTapTimer
->Cancel();
2176 mLongTapTimer
= nullptr;
2177 SynthesizeNativeTouchPoint(mLongTapTouchPoint
->mPointerId
, TOUCH_CANCEL
,
2178 mLongTapTouchPoint
->mPosition
, 0, 0, nullptr);
2179 mLongTapTouchPoint
= nullptr;
2183 MultiTouchInput
nsBaseWidget::UpdateSynthesizedTouchState(
2184 MultiTouchInput
* aState
, mozilla::TimeStamp aTimeStamp
, uint32_t aPointerId
,
2185 TouchPointerState aPointerState
, LayoutDeviceIntPoint aPoint
,
2186 double aPointerPressure
, uint32_t aPointerOrientation
) {
2187 ScreenIntPoint pointerScreenPoint
= ViewAs
<ScreenPixel
>(
2188 aPoint
, PixelCastJustification::LayoutDeviceIsScreenForBounds
);
2190 // We can't dispatch *aState directly because (a) dispatching
2191 // it might inadvertently modify it and (b) in the case of touchend or
2192 // touchcancel events aState will hold the touches that are
2193 // still down whereas the input dispatched needs to hold the removed
2194 // touch(es). We use |inputToDispatch| for this purpose.
2195 MultiTouchInput inputToDispatch
;
2196 inputToDispatch
.mInputType
= MULTITOUCH_INPUT
;
2197 inputToDispatch
.mTimeStamp
= aTimeStamp
;
2199 int32_t index
= aState
->IndexOfTouch((int32_t)aPointerId
);
2200 if (aPointerState
== TOUCH_CONTACT
) {
2202 // found an existing touch point, update it
2203 SingleTouchData
& point
= aState
->mTouches
[index
];
2204 point
.mScreenPoint
= pointerScreenPoint
;
2205 point
.mRotationAngle
= (float)aPointerOrientation
;
2206 point
.mForce
= (float)aPointerPressure
;
2207 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_MOVE
;
2209 // new touch point, add it
2210 aState
->mTouches
.AppendElement(SingleTouchData(
2211 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2212 (float)aPointerOrientation
, (float)aPointerPressure
));
2213 inputToDispatch
.mType
= MultiTouchInput::MULTITOUCH_START
;
2215 inputToDispatch
.mTouches
= aState
->mTouches
;
2217 MOZ_ASSERT(aPointerState
== TOUCH_REMOVE
|| aPointerState
== TOUCH_CANCEL
);
2218 // a touch point is being lifted, so remove it from the stored list
2220 aState
->mTouches
.RemoveElementAt(index
);
2222 inputToDispatch
.mType
=
2223 (aPointerState
== TOUCH_REMOVE
? MultiTouchInput::MULTITOUCH_END
2224 : MultiTouchInput::MULTITOUCH_CANCEL
);
2225 inputToDispatch
.mTouches
.AppendElement(SingleTouchData(
2226 (int32_t)aPointerId
, pointerScreenPoint
, ScreenSize(0, 0),
2227 (float)aPointerOrientation
, (float)aPointerPressure
));
2230 return inputToDispatch
;
2233 void nsBaseWidget::NotifyLiveResizeStarted() {
2234 // If we have mLiveResizeListeners already non-empty, we should notify those
2235 // listeners that the resize stopped before starting anew. In theory this
2236 // should never happen because we shouldn't get nested live resize actions.
2237 NotifyLiveResizeStopped();
2238 MOZ_ASSERT(mLiveResizeListeners
.IsEmpty());
2240 // If we can get the active remote tab for the current widget, suppress
2241 // the displayport on it during the live resize.
2242 if (!mWidgetListener
) {
2245 nsCOMPtr
<nsIAppWindow
> appWindow
= mWidgetListener
->GetAppWindow();
2249 mLiveResizeListeners
= appWindow
->GetLiveResizeListeners();
2250 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2251 mLiveResizeListeners
[i
]->LiveResizeStarted();
2255 void nsBaseWidget::NotifyLiveResizeStopped() {
2256 if (!mLiveResizeListeners
.IsEmpty()) {
2257 for (uint32_t i
= 0; i
< mLiveResizeListeners
.Length(); i
++) {
2258 mLiveResizeListeners
[i
]->LiveResizeStopped();
2260 mLiveResizeListeners
.Clear();
2264 nsresult
nsBaseWidget::AsyncEnableDragDrop(bool aEnable
) {
2265 RefPtr
<nsBaseWidget
> kungFuDeathGrip
= this;
2266 return NS_DispatchToCurrentThreadQueue(
2267 NS_NewRunnableFunction(
2268 "AsyncEnableDragDropFn",
2269 [this, aEnable
, kungFuDeathGrip
]() { EnableDragDrop(aEnable
); }),
2270 kAsyncDragDropTimeout
, EventQueuePriority::Idle
);
2273 void nsBaseWidget::SwipeFinished() {
2274 if (mSwipeTracker
) {
2275 mSwipeTracker
->Destroy();
2276 mSwipeTracker
= nullptr;
2280 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId
,
2282 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== aInputBlockId
) {
2284 PanGestureInput
& startEvent
= mSwipeEventQueue
->queuedEvents
[0];
2285 TrackScrollEventAsSwipe(startEvent
, mSwipeEventQueue
->allowedDirections
,
2287 for (size_t i
= 1; i
< mSwipeEventQueue
->queuedEvents
.Length(); i
++) {
2288 mSwipeTracker
->ProcessEvent(mSwipeEventQueue
->queuedEvents
[i
]);
2291 // If the event wasn't start swipe, we need to notify it to APZ.
2292 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2293 BrowserGestureResponse::NotConsumed
);
2295 mSwipeEventQueue
= nullptr;
2299 void nsBaseWidget::TrackScrollEventAsSwipe(
2300 const mozilla::PanGestureInput
& aSwipeStartEvent
,
2301 uint32_t aAllowedDirections
, uint64_t aInputBlockId
) {
2302 // If a swipe is currently being tracked kill it -- it's been interrupted
2303 // by another gesture event.
2304 if (mSwipeTracker
) {
2305 mSwipeTracker
->CancelSwipe(aSwipeStartEvent
.mTimeStamp
);
2306 mSwipeTracker
->Destroy();
2307 mSwipeTracker
= nullptr;
2310 uint32_t direction
=
2311 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2312 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2313 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2316 new SwipeTracker(*this, aSwipeStartEvent
, aAllowedDirections
, direction
);
2319 mCurrentPanGestureBelongsToSwipe
= true;
2321 // Now SwipeTracker has started consuming pan events, notify it to APZ so
2322 // that APZ can discard queued events.
2323 mAPZC
->SetBrowserGestureResponse(aInputBlockId
,
2324 BrowserGestureResponse::Consumed
);
2328 nsBaseWidget::SwipeInfo
nsBaseWidget::SendMayStartSwipe(
2329 const mozilla::PanGestureInput
& aSwipeStartEvent
) {
2330 nsCOMPtr
<nsIWidget
> kungFuDeathGrip(this);
2332 uint32_t direction
=
2333 (aSwipeStartEvent
.mPanDisplacement
.x
> 0.0)
2334 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2335 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT
;
2337 // We're ready to start the animation. Tell Gecko about it, and at the same
2338 // time ask it if it really wants to start an animation for this event.
2339 // This event also reports back the directions that we can swipe in.
2340 LayoutDeviceIntPoint position
= RoundedToInt(aSwipeStartEvent
.mPanStartPoint
*
2341 ScreenToLayoutDeviceScale(1));
2342 WidgetSimpleGestureEvent geckoEvent
= SwipeTracker::CreateSwipeGestureEvent(
2343 eSwipeGestureMayStart
, this, position
, aSwipeStartEvent
.mTimeStamp
);
2344 geckoEvent
.mDirection
= direction
;
2345 geckoEvent
.mDelta
= 0.0;
2346 geckoEvent
.mAllowedDirections
= 0;
2347 bool shouldStartSwipe
=
2348 DispatchWindowEvent(geckoEvent
); // event cancelled == swipe should start
2350 SwipeInfo result
= {shouldStartSwipe
, geckoEvent
.mAllowedDirections
};
2354 WidgetWheelEvent
nsBaseWidget::MayStartSwipeForAPZ(
2355 const PanGestureInput
& aPanInput
, const APZEventResult
& aApzResult
) {
2356 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2358 // Ignore swipe-to-navigation in PiP window.
2363 if (aPanInput
.AllowsSwipe()) {
2364 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2365 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2366 if (swipeInfo
.wantsSwipe
) {
2367 if (aApzResult
.GetStatus() == nsEventStatus_eIgnore
) {
2368 // APZ has determined and that scrolling horizontally in the
2369 // requested direction is impossible, so it didn't do any
2370 // scrolling for the event.
2371 // We know now that MayStartSwipe wants a swipe, so we can start
2373 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
,
2374 aApzResult
.mInputBlockId
);
2375 } else if (!aApzResult
.GetHandledResult() ||
2376 !aApzResult
.GetHandledResult()->IsHandledByRoot()) {
2377 // We don't know whether this event can start a swipe, so we need
2378 // to queue up events and wait for a call to ReportSwipeStarted.
2379 // APZ might already have started scrolling in response to the
2380 // event if it knew that it's the right thing to do. In that case
2381 // we'll still get a call to ReportSwipeStarted, and we will
2382 // discard the queued events at that point.
2383 mSwipeEventQueue
= MakeUnique
<SwipeEventQueue
>(
2384 swipeInfo
.allowedDirections
, aApzResult
.mInputBlockId
);
2387 // Inform that the browser gesture didn't use the pan event (pan-start
2388 // precisely), so that APZ can now start using the event for
2389 // scrolling/overscrolling.
2390 mAPZC
->SetBrowserGestureResponse(aApzResult
.mInputBlockId
,
2391 BrowserGestureResponse::NotConsumed
);
2395 if (mSwipeEventQueue
&&
2396 mSwipeEventQueue
->inputBlockId
== aApzResult
.mInputBlockId
) {
2397 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2403 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput
& aPanInput
) {
2404 // Ignore swipe-to-navigation in PiP window.
2409 if (aPanInput
.mType
== PanGestureInput::PANGESTURE_MAYSTART
||
2410 aPanInput
.mType
== PanGestureInput::PANGESTURE_START
) {
2411 mCurrentPanGestureBelongsToSwipe
= false;
2413 if (mCurrentPanGestureBelongsToSwipe
) {
2414 // Ignore this event. It's a momentum event from a scroll gesture
2415 // that was processed as a swipe, and the swipe animation has
2416 // already finished (so mSwipeTracker is already null).
2417 MOZ_ASSERT(aPanInput
.IsMomentum(),
2418 "If the fingers are still on the touchpad, we should still have "
2420 "and it should have consumed this event.");
2424 if (!aPanInput
.MayTriggerSwipe()) {
2428 SwipeInfo swipeInfo
= SendMayStartSwipe(aPanInput
);
2430 // We're in the non-APZ case here, but we still want to know whether
2431 // the event was routed to a child process, so we use InputAPZContext
2432 // to get that piece of information.
2433 ScrollableLayerGuid guid
;
2434 uint64_t blockId
= 0;
2435 InputAPZContext
context(guid
, blockId
, nsEventStatus_eIgnore
);
2437 WidgetWheelEvent event
= aPanInput
.ToWidgetEvent(this);
2438 event
.mCanTriggerSwipe
= swipeInfo
.wantsSwipe
;
2439 nsEventStatus status
;
2440 DispatchEvent(&event
, status
);
2441 if (swipeInfo
.wantsSwipe
) {
2442 if (context
.WasRoutedToChildProcess()) {
2443 // We don't know whether this event can start a swipe, so we need
2444 // to queue up events and wait for a call to ReportSwipeStarted.
2446 MakeUnique
<SwipeEventQueue
>(swipeInfo
.allowedDirections
, blockId
);
2447 } else if (event
.TriggersSwipe()) {
2448 TrackScrollEventAsSwipe(aPanInput
, swipeInfo
.allowedDirections
, blockId
);
2452 if (mSwipeEventQueue
&& mSwipeEventQueue
->inputBlockId
== 0) {
2453 mSwipeEventQueue
->queuedEvents
.AppendElement(aPanInput
);
2459 const IMENotificationRequests
& nsIWidget::IMENotificationRequestsRef() {
2460 TextEventDispatcher
* dispatcher
= GetTextEventDispatcher();
2461 return dispatcher
->IMENotificationRequestsRef();
2464 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent
* aEvent
) {}
2466 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType
,
2467 const WidgetKeyboardEvent
& aEvent
,
2468 nsTArray
<CommandInt
>& aCommands
) {
2469 MOZ_ASSERT(aEvent
.IsTrusted());
2470 MOZ_ASSERT(aCommands
.IsEmpty());
2474 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboard() {
2475 if (XRE_IsContentProcess()) {
2476 return CreateBidiKeyboardContentProcess();
2478 return CreateBidiKeyboardInner();
2482 already_AddRefed
<nsIBidiKeyboard
> nsIWidget::CreateBidiKeyboardInner() {
2483 // no bidi keyboard implementation
2488 namespace mozilla::widget
{
2490 const char* ToChar(InputContext::Origin aOrigin
) {
2492 case InputContext::ORIGIN_MAIN
:
2493 return "ORIGIN_MAIN";
2494 case InputContext::ORIGIN_CONTENT
:
2495 return "ORIGIN_CONTENT";
2497 return "Unexpected value";
2501 const char* ToChar(IMEMessage aIMEMessage
) {
2502 switch (aIMEMessage
) {
2503 case NOTIFY_IME_OF_NOTHING
:
2504 return "NOTIFY_IME_OF_NOTHING";
2505 case NOTIFY_IME_OF_FOCUS
:
2506 return "NOTIFY_IME_OF_FOCUS";
2507 case NOTIFY_IME_OF_BLUR
:
2508 return "NOTIFY_IME_OF_BLUR";
2509 case NOTIFY_IME_OF_SELECTION_CHANGE
:
2510 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2511 case NOTIFY_IME_OF_TEXT_CHANGE
:
2512 return "NOTIFY_IME_OF_TEXT_CHANGE";
2513 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED
:
2514 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2515 case NOTIFY_IME_OF_POSITION_CHANGE
:
2516 return "NOTIFY_IME_OF_POSITION_CHANGE";
2517 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT
:
2518 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2519 case REQUEST_TO_COMMIT_COMPOSITION
:
2520 return "REQUEST_TO_COMMIT_COMPOSITION";
2521 case REQUEST_TO_CANCEL_COMPOSITION
:
2522 return "REQUEST_TO_CANCEL_COMPOSITION";
2524 return "Unexpected value";
2528 void NativeIMEContext::Init(nsIWidget
* aWidget
) {
2530 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2531 mOriginProcessID
= static_cast<uint64_t>(-1);
2534 if (!XRE_IsContentProcess()) {
2535 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(
2536 aWidget
->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT
));
2537 mOriginProcessID
= 0;
2540 // If this is created in a child process, aWidget is an instance of
2541 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2542 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2543 // native IME context of the parent process.
2544 *this = aWidget
->GetNativeIMEContext();
2547 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext
) {
2548 if (NS_WARN_IF(!aRawNativeIMEContext
)) {
2549 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(nullptr);
2550 mOriginProcessID
= static_cast<uint64_t>(-1);
2553 mRawNativeIMEContext
= reinterpret_cast<uintptr_t>(aRawNativeIMEContext
);
2555 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2558 void IMENotification::TextChangeDataBase::MergeWith(
2559 const IMENotification::TextChangeDataBase
& aOther
) {
2560 MOZ_ASSERT(aOther
.IsValid(), "Merging data must store valid data");
2561 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mRemovedEndOffset
,
2562 "end of removed text must be same or larger than start");
2563 MOZ_ASSERT(aOther
.mStartOffset
<= aOther
.mAddedEndOffset
,
2564 "end of added text must be same or larger than start");
2571 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2572 // text ranges. I.e., mStartOffset should be the smallest offset of all
2573 // modified text ranges in old text. |mRemovedEndOffset| should be the
2574 // largest end offset in old text of all modified text ranges.
2575 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2576 // I.e., only this is an offset in new text.
2577 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2578 // premodified text was already removed. And some text whose length is
2579 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2580 // this allows IME to mark dirty the modified text range with |mStartOffset|
2581 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2582 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2583 // Additionally, IME can retrieve only the text between |mStartOffset| and
2584 // |mAddedEndOffset| for updating stored text.
2586 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2587 // should be adjusted to be in same text. The |newData.mStartOffset| and
2588 // |newData.mRemovedEndOffset| should be computed as in old text because
2589 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2590 // in the old text but even if some text before the values of the newData
2591 // has already been modified, the values don't include the changes.
2593 // For comparing new and old |mAddedEndOffset| values, they should be
2594 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2595 // computed as in the new text because |mAddedEndOffset| indicates the end
2596 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2597 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2599 const TextChangeDataBase
& newData
= aOther
;
2600 const TextChangeDataBase oldData
= *this;
2602 // mCausedOnlyByComposition should be true only when all changes are caused
2604 mCausedOnlyByComposition
=
2605 newData
.mCausedOnlyByComposition
&& oldData
.mCausedOnlyByComposition
;
2607 // mIncludingChangesWithoutComposition should be true if at least one of
2608 // merged changes occurred without composition.
2609 mIncludingChangesWithoutComposition
=
2610 newData
.mIncludingChangesWithoutComposition
||
2611 oldData
.mIncludingChangesWithoutComposition
;
2613 // mIncludingChangesDuringComposition should be true when at least one of
2614 // the merged non-composition changes occurred during the latest composition.
2615 if (!newData
.mCausedOnlyByComposition
&&
2616 !newData
.mIncludingChangesDuringComposition
) {
2617 MOZ_ASSERT(newData
.mIncludingChangesWithoutComposition
);
2618 MOZ_ASSERT(mIncludingChangesWithoutComposition
);
2619 // If new change is neither caused by composition nor occurred during
2620 // composition, set mIncludingChangesDuringComposition to false because
2621 // IME doesn't want outdated text changes as text change during current
2623 mIncludingChangesDuringComposition
= false;
2625 // Otherwise, set mIncludingChangesDuringComposition to true if either
2626 // oldData or newData includes changes during composition.
2627 mIncludingChangesDuringComposition
=
2628 newData
.mIncludingChangesDuringComposition
||
2629 oldData
.mIncludingChangesDuringComposition
;
2632 if (newData
.mStartOffset
>= oldData
.mAddedEndOffset
) {
2634 // If new start is after old end offset of added text, it means that text
2635 // after the modified range is modified. Like:
2636 // added range of old change: +----------+
2637 // removed range of new change: +----------+
2638 // So, the old start offset is always the smaller offset.
2639 mStartOffset
= oldData
.mStartOffset
;
2640 // The new end offset of removed text is moved by the old change and we
2641 // need to cancel the move of the old change for comparing the offsets in
2642 // same text because it doesn't make sensce to compare offsets in different
2644 uint32_t newRemovedEndOffsetInOldText
=
2645 newData
.mRemovedEndOffset
- oldData
.Difference();
2647 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2648 // The new end offset of added text is always the larger offset.
2649 mAddedEndOffset
= newData
.mAddedEndOffset
;
2653 if (newData
.mStartOffset
>= oldData
.mStartOffset
) {
2654 // If new start is in the modified range, it means that new data changes
2655 // a part or all of the range.
2656 mStartOffset
= oldData
.mStartOffset
;
2657 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2659 // If new end of removed text is greater than old end of added text, it
2660 // means that all or a part of modified range modified again and text
2661 // after the modified range is also modified. Like:
2662 // added range of old change: +----------+
2663 // removed range of new change: +----------+
2664 // So, the new removed end offset is moved by the old change and we need
2665 // to cancel the move of the old change for comparing the offsets in the
2666 // same text because it doesn't make sense to compare the offsets in
2668 uint32_t newRemovedEndOffsetInOldText
=
2669 newData
.mRemovedEndOffset
- oldData
.Difference();
2671 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2672 // The old end of added text is replaced by new change. So, it should be
2673 // same as the new start. On the other hand, the new added end offset is
2674 // always same or larger. Therefore, the merged end offset of added
2675 // text should be the new end offset of added text.
2676 mAddedEndOffset
= newData
.mAddedEndOffset
;
2681 // If new end of removed text is less than old end of added text, it means
2682 // that only a part of the modified range is modified again. Like:
2683 // added range of old change: +------------+
2684 // removed range of new change: +-----+
2685 // So, the new end offset of removed text should be same as the old end
2686 // offset of removed text. Therefore, the merged end offset of removed
2687 // text should be the old text change's |mRemovedEndOffset|.
2688 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2689 // The old end of added text is moved by new change. So, we need to cancel
2690 // the move of the new change for comparing the offsets in same text.
2691 uint32_t oldAddedEndOffsetInNewText
=
2692 oldData
.mAddedEndOffset
+ newData
.Difference();
2694 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2698 if (newData
.mRemovedEndOffset
>= oldData
.mStartOffset
) {
2699 // If new end of removed text is greater than old start (and new start is
2700 // less than old start), it means that a part of modified range is modified
2701 // again and some new text before the modified range is also modified.
2702 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2703 "new start offset should be less than old one here");
2704 mStartOffset
= newData
.mStartOffset
;
2705 if (newData
.mRemovedEndOffset
>= oldData
.mAddedEndOffset
) {
2707 // If new end of removed text is greater than old end of added text, it
2708 // means that all modified text and text after the modified range is
2710 // added range of old change: +----------+
2711 // removed range of new change: +------------------+
2712 // So, the new end of removed text is moved by the old change. Therefore,
2713 // we need to cancel the move of the old change for comparing the offsets
2714 // in same text because it doesn't make sense to compare the offsets in
2716 uint32_t newRemovedEndOffsetInOldText
=
2717 newData
.mRemovedEndOffset
- oldData
.Difference();
2719 std::max(newRemovedEndOffsetInOldText
, oldData
.mRemovedEndOffset
);
2720 // The old end of added text is replaced by new change. So, the old end
2721 // offset of added text is same as new text change's start offset. Then,
2722 // new change's end offset of added text is always same or larger than
2723 // it. Therefore, merged end offset of added text is always the new end
2724 // offset of added text.
2725 mAddedEndOffset
= newData
.mAddedEndOffset
;
2730 // If new end of removed text is less than old end of added text, it
2731 // means that only a part of the modified range is modified again. Like:
2732 // added range of old change: +----------+
2733 // removed range of new change: +----------+
2734 // So, the new end of removed text should be same as old end of removed
2735 // text for preventing end of removed text to be modified. Therefore,
2736 // merged end offset of removed text is always the old end offset of removed
2738 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2739 // The old end of added text is moved by this change. So, we need to
2740 // cancel the move of the new change for comparing the offsets in same text
2741 // because it doesn't make sense to compare the offsets in different text.
2742 uint32_t oldAddedEndOffsetInNewText
=
2743 oldData
.mAddedEndOffset
+ newData
.Difference();
2745 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2750 // Otherwise, i.e., both new end of added text and new start are less than
2751 // old start, text before the modified range is modified. Like:
2752 // added range of old change: +----------+
2753 // removed range of new change: +----------+
2754 MOZ_ASSERT(newData
.mStartOffset
< oldData
.mStartOffset
,
2755 "new start offset should be less than old one here");
2756 mStartOffset
= newData
.mStartOffset
;
2757 MOZ_ASSERT(newData
.mRemovedEndOffset
< oldData
.mRemovedEndOffset
,
2758 "new removed end offset should be less than old one here");
2759 mRemovedEndOffset
= oldData
.mRemovedEndOffset
;
2760 // The end of added text should be adjusted with the new difference.
2761 uint32_t oldAddedEndOffsetInNewText
=
2762 oldData
.mAddedEndOffset
+ newData
.Difference();
2764 std::max(newData
.mAddedEndOffset
, oldAddedEndOffsetInNewText
);
2769 // Let's test the code of merging multiple text change data in debug build
2770 // and crash if one of them fails because this feature is very complex but
2771 // cannot be tested with mochitest.
2772 void IMENotification::TextChangeDataBase::Test() {
2773 static bool gTestTextChangeEvent
= true;
2774 if (!gTestTextChangeEvent
) {
2777 gTestTextChangeEvent
= false;
2779 /****************************************************************************
2781 ****************************************************************************/
2784 MergeWith(TextChangeData(10, 10, 20, false, false));
2785 MergeWith(TextChangeData(20, 20, 35, false, false));
2786 MOZ_ASSERT(mStartOffset
== 10,
2787 "Test 1-1-1: mStartOffset should be the first offset");
2789 mRemovedEndOffset
== 10, // 20 - (20 - 10)
2790 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2792 mAddedEndOffset
== 35,
2793 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2796 // Removing text (longer line -> shorter line)
2797 MergeWith(TextChangeData(10, 20, 10, false, false));
2798 MergeWith(TextChangeData(10, 30, 10, false, false));
2799 MOZ_ASSERT(mStartOffset
== 10,
2800 "Test 1-2-1: mStartOffset should be the first offset");
2801 MOZ_ASSERT(mRemovedEndOffset
== 40, // 30 + (10 - 20)
2802 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2804 "with already removed length");
2806 mAddedEndOffset
== 10,
2807 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2810 // Removing text (shorter line -> longer line)
2811 MergeWith(TextChangeData(10, 20, 10, false, false));
2812 MergeWith(TextChangeData(10, 15, 10, false, false));
2813 MOZ_ASSERT(mStartOffset
== 10,
2814 "Test 1-3-1: mStartOffset should be the first offset");
2815 MOZ_ASSERT(mRemovedEndOffset
== 25, // 15 + (10 - 20)
2816 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2818 "with already removed length");
2820 mAddedEndOffset
== 10,
2821 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2824 // Appending text at different point (not sure if actually occurs)
2825 MergeWith(TextChangeData(10, 10, 20, false, false));
2826 MergeWith(TextChangeData(55, 55, 60, false, false));
2827 MOZ_ASSERT(mStartOffset
== 10,
2828 "Test 1-4-1: mStartOffset should be the smallest offset");
2830 mRemovedEndOffset
== 45, // 55 - (10 - 20)
2831 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2832 "text without already added length");
2834 mAddedEndOffset
== 60,
2835 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2838 // Removing text at different point (not sure if actually occurs)
2839 MergeWith(TextChangeData(10, 20, 10, false, false));
2840 MergeWith(TextChangeData(55, 68, 55, false, false));
2841 MOZ_ASSERT(mStartOffset
== 10,
2842 "Test 1-5-1: mStartOffset should be the smallest offset");
2844 mRemovedEndOffset
== 78, // 68 - (10 - 20)
2845 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2846 "text with already removed length");
2848 mAddedEndOffset
== 55,
2849 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2852 // Replacing text and append text (becomes longer)
2853 MergeWith(TextChangeData(30, 35, 32, false, false));
2854 MergeWith(TextChangeData(32, 32, 40, false, false));
2855 MOZ_ASSERT(mStartOffset
== 30,
2856 "Test 1-6-1: mStartOffset should be the smallest offset");
2858 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2859 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2862 mAddedEndOffset
== 40,
2863 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2866 // Replacing text and append text (becomes shorter)
2867 MergeWith(TextChangeData(30, 35, 32, false, false));
2868 MergeWith(TextChangeData(32, 32, 33, false, false));
2869 MOZ_ASSERT(mStartOffset
== 30,
2870 "Test 1-7-1: mStartOffset should be the smallest offset");
2872 mRemovedEndOffset
== 35, // 32 - (32 - 35)
2873 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2876 mAddedEndOffset
== 33,
2877 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2880 // Removing text and replacing text after first range (not sure if actually
2882 MergeWith(TextChangeData(30, 35, 30, false, false));
2883 MergeWith(TextChangeData(32, 34, 48, false, false));
2884 MOZ_ASSERT(mStartOffset
== 30,
2885 "Test 1-8-1: mStartOffset should be the smallest offset");
2886 MOZ_ASSERT(mRemovedEndOffset
== 39, // 34 - (30 - 35)
2887 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2889 "without already removed text");
2891 mAddedEndOffset
== 48,
2892 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2895 // Removing text and replacing text after first range (not sure if actually
2897 MergeWith(TextChangeData(30, 35, 30, false, false));
2898 MergeWith(TextChangeData(32, 38, 36, false, false));
2899 MOZ_ASSERT(mStartOffset
== 30,
2900 "Test 1-9-1: mStartOffset should be the smallest offset");
2901 MOZ_ASSERT(mRemovedEndOffset
== 43, // 38 - (30 - 35)
2902 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2904 "without already removed text");
2906 mAddedEndOffset
== 36,
2907 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2910 /****************************************************************************
2912 ****************************************************************************/
2914 // Replacing text in around end of added text (becomes shorter) (not sure
2915 // if actually occurs)
2916 MergeWith(TextChangeData(50, 50, 55, false, false));
2917 MergeWith(TextChangeData(53, 60, 54, false, false));
2918 MOZ_ASSERT(mStartOffset
== 50,
2919 "Test 2-1-1: mStartOffset should be the smallest offset");
2920 MOZ_ASSERT(mRemovedEndOffset
== 55, // 60 - (55 - 50)
2921 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2923 "without already added text length");
2925 mAddedEndOffset
== 54,
2926 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2929 // Replacing text around end of added text (becomes longer) (not sure
2930 // if actually occurs)
2931 MergeWith(TextChangeData(50, 50, 55, false, false));
2932 MergeWith(TextChangeData(54, 62, 68, false, false));
2933 MOZ_ASSERT(mStartOffset
== 50,
2934 "Test 2-2-1: mStartOffset should be the smallest offset");
2935 MOZ_ASSERT(mRemovedEndOffset
== 57, // 62 - (55 - 50)
2936 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2938 "without already added text length");
2940 mAddedEndOffset
== 68,
2941 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2944 // Replacing text around end of replaced text (became shorter) (not sure if
2946 MergeWith(TextChangeData(36, 48, 45, false, false));
2947 MergeWith(TextChangeData(43, 50, 49, false, false));
2948 MOZ_ASSERT(mStartOffset
== 36,
2949 "Test 2-3-1: mStartOffset should be the smallest offset");
2950 MOZ_ASSERT(mRemovedEndOffset
== 53, // 50 - (45 - 48)
2951 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2953 "without already removed text length");
2955 mAddedEndOffset
== 49,
2956 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2959 // Replacing text around end of replaced text (became longer) (not sure if
2961 MergeWith(TextChangeData(36, 52, 53, false, false));
2962 MergeWith(TextChangeData(43, 68, 61, false, false));
2963 MOZ_ASSERT(mStartOffset
== 36,
2964 "Test 2-4-1: mStartOffset should be the smallest offset");
2965 MOZ_ASSERT(mRemovedEndOffset
== 67, // 68 - (53 - 52)
2966 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2968 "without already added text length");
2970 mAddedEndOffset
== 61,
2971 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2974 /****************************************************************************
2976 ****************************************************************************/
2978 // Appending text in already added text (not sure if actually occurs)
2979 MergeWith(TextChangeData(10, 10, 20, false, false));
2980 MergeWith(TextChangeData(15, 15, 30, false, false));
2981 MOZ_ASSERT(mStartOffset
== 10,
2982 "Test 3-1-1: mStartOffset should be the smallest offset");
2983 MOZ_ASSERT(mRemovedEndOffset
== 10,
2984 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2987 mAddedEndOffset
== 35, // 20 + (30 - 15)
2988 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2989 "added text length by the new change");
2992 // Replacing text in added text (not sure if actually occurs)
2993 MergeWith(TextChangeData(50, 50, 55, false, false));
2994 MergeWith(TextChangeData(52, 53, 56, false, false));
2995 MOZ_ASSERT(mStartOffset
== 50,
2996 "Test 3-2-1: mStartOffset should be the smallest offset");
2997 MOZ_ASSERT(mRemovedEndOffset
== 50,
2998 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
3001 mAddedEndOffset
== 58, // 55 + (56 - 53)
3002 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
3003 "added text length by the new change");
3006 // Replacing text in replaced text (became shorter) (not sure if actually
3008 MergeWith(TextChangeData(36, 48, 45, false, false));
3009 MergeWith(TextChangeData(37, 38, 50, false, false));
3010 MOZ_ASSERT(mStartOffset
== 36,
3011 "Test 3-3-1: mStartOffset should be the smallest offset");
3012 MOZ_ASSERT(mRemovedEndOffset
== 48,
3013 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
3016 mAddedEndOffset
== 57, // 45 + (50 - 38)
3017 "Test 3-3-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 longer) (not sure if actually
3023 MergeWith(TextChangeData(32, 48, 53, false, false));
3024 MergeWith(TextChangeData(43, 50, 52, false, false));
3025 MOZ_ASSERT(mStartOffset
== 32,
3026 "Test 3-4-1: mStartOffset should be the smallest offset");
3027 MOZ_ASSERT(mRemovedEndOffset
== 48,
3028 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
3030 "without already added text length");
3032 mAddedEndOffset
== 55, // 53 + (52 - 50)
3033 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
3034 "added text length by the new change");
3037 // Replacing text in replaced text (became shorter) (not sure if actually
3039 MergeWith(TextChangeData(36, 48, 50, false, false));
3040 MergeWith(TextChangeData(37, 49, 47, false, false));
3041 MOZ_ASSERT(mStartOffset
== 36,
3042 "Test 3-5-1: mStartOffset should be the smallest offset");
3044 mRemovedEndOffset
== 48,
3045 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
3047 MOZ_ASSERT(mAddedEndOffset
== 48, // 50 + (47 - 49)
3048 "Test 3-5-3: mAddedEndOffset should be the first end of added "
3050 "removed text length by the new change");
3053 // Replacing text in replaced text (became longer) (not sure if actually
3055 MergeWith(TextChangeData(32, 48, 53, false, false));
3056 MergeWith(TextChangeData(43, 50, 47, false, false));
3057 MOZ_ASSERT(mStartOffset
== 32,
3058 "Test 3-6-1: mStartOffset should be the smallest offset");
3059 MOZ_ASSERT(mRemovedEndOffset
== 48,
3060 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
3062 "without already added text length");
3063 MOZ_ASSERT(mAddedEndOffset
== 50, // 53 + (47 - 50)
3064 "Test 3-6-3: mAddedEndOffset should be the first end of added "
3066 "removed text length by the new change");
3069 /****************************************************************************
3071 ****************************************************************************/
3073 // Replacing text all of already append text (not sure if actually occurs)
3074 MergeWith(TextChangeData(50, 50, 55, false, false));
3075 MergeWith(TextChangeData(44, 66, 68, false, false));
3076 MOZ_ASSERT(mStartOffset
== 44,
3077 "Test 4-1-1: mStartOffset should be the smallest offset");
3078 MOZ_ASSERT(mRemovedEndOffset
== 61, // 66 - (55 - 50)
3079 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
3081 "without already added text length");
3083 mAddedEndOffset
== 68,
3084 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3087 // Replacing text around a point in which text was removed (not sure if
3089 MergeWith(TextChangeData(50, 62, 50, false, false));
3090 MergeWith(TextChangeData(44, 66, 68, false, false));
3091 MOZ_ASSERT(mStartOffset
== 44,
3092 "Test 4-2-1: mStartOffset should be the smallest offset");
3093 MOZ_ASSERT(mRemovedEndOffset
== 78, // 66 - (50 - 62)
3094 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
3096 "without already removed text length");
3098 mAddedEndOffset
== 68,
3099 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3102 // Replacing text all replaced text (became shorter) (not sure if actually
3104 MergeWith(TextChangeData(50, 62, 60, false, false));
3105 MergeWith(TextChangeData(49, 128, 130, false, false));
3106 MOZ_ASSERT(mStartOffset
== 49,
3107 "Test 4-3-1: mStartOffset should be the smallest offset");
3108 MOZ_ASSERT(mRemovedEndOffset
== 130, // 128 - (60 - 62)
3109 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
3111 "without already removed text length");
3113 mAddedEndOffset
== 130,
3114 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3117 // Replacing text all replaced text (became longer) (not sure if actually
3119 MergeWith(TextChangeData(50, 61, 73, false, false));
3120 MergeWith(TextChangeData(44, 100, 50, false, false));
3121 MOZ_ASSERT(mStartOffset
== 44,
3122 "Test 4-4-1: mStartOffset should be the smallest offset");
3123 MOZ_ASSERT(mRemovedEndOffset
== 88, // 100 - (73 - 61)
3124 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
3126 "with already added text length");
3128 mAddedEndOffset
== 50,
3129 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3132 /****************************************************************************
3134 ****************************************************************************/
3136 // Replacing text around start of added text (not sure if actually occurs)
3137 MergeWith(TextChangeData(50, 50, 55, false, false));
3138 MergeWith(TextChangeData(48, 52, 49, false, false));
3139 MOZ_ASSERT(mStartOffset
== 48,
3140 "Test 5-1-1: mStartOffset should be the smallest offset");
3142 mRemovedEndOffset
== 50,
3143 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
3146 mAddedEndOffset
== 52, // 55 + (52 - 49)
3147 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
3148 "added text length by the new change");
3151 // Replacing text around start of replaced text (became shorter) (not sure if
3153 MergeWith(TextChangeData(50, 60, 58, false, false));
3154 MergeWith(TextChangeData(43, 50, 48, false, false));
3155 MOZ_ASSERT(mStartOffset
== 43,
3156 "Test 5-2-1: mStartOffset should be the smallest offset");
3158 mRemovedEndOffset
== 60,
3159 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3161 MOZ_ASSERT(mAddedEndOffset
== 56, // 58 + (48 - 50)
3162 "Test 5-2-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 longer) (not sure if
3169 MergeWith(TextChangeData(50, 60, 68, false, false));
3170 MergeWith(TextChangeData(43, 55, 53, false, false));
3171 MOZ_ASSERT(mStartOffset
== 43,
3172 "Test 5-3-1: mStartOffset should be the smallest offset");
3174 mRemovedEndOffset
== 60,
3175 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3177 MOZ_ASSERT(mAddedEndOffset
== 66, // 68 + (53 - 55)
3178 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3180 "removed text length by the new change");
3183 // Replacing text around start of replaced text (became shorter) (not sure if
3185 MergeWith(TextChangeData(50, 60, 58, false, false));
3186 MergeWith(TextChangeData(43, 50, 128, false, false));
3187 MOZ_ASSERT(mStartOffset
== 43,
3188 "Test 5-4-1: mStartOffset should be the smallest offset");
3190 mRemovedEndOffset
== 60,
3191 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
3194 mAddedEndOffset
== 136, // 58 + (128 - 50)
3195 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
3196 "added text length by the new change");
3199 // Replacing text around start of replaced text (became longer) (not sure if
3201 MergeWith(TextChangeData(50, 60, 68, false, false));
3202 MergeWith(TextChangeData(43, 55, 65, false, false));
3203 MOZ_ASSERT(mStartOffset
== 43,
3204 "Test 5-5-1: mStartOffset should be the smallest offset");
3206 mRemovedEndOffset
== 60,
3207 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
3210 mAddedEndOffset
== 78, // 68 + (65 - 55)
3211 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
3212 "added text length by the new change");
3215 /****************************************************************************
3217 ****************************************************************************/
3219 // Appending text before already added text (not sure if actually occurs)
3220 MergeWith(TextChangeData(30, 30, 45, false, false));
3221 MergeWith(TextChangeData(10, 10, 20, false, false));
3222 MOZ_ASSERT(mStartOffset
== 10,
3223 "Test 6-1-1: mStartOffset should be the smallest offset");
3225 mRemovedEndOffset
== 30,
3226 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3229 mAddedEndOffset
== 55, // 45 + (20 - 10)
3230 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3231 "added text length by the new change");
3234 // Removing text before already removed text (not sure if actually occurs)
3235 MergeWith(TextChangeData(30, 35, 30, false, false));
3236 MergeWith(TextChangeData(10, 25, 10, false, false));
3237 MOZ_ASSERT(mStartOffset
== 10,
3238 "Test 6-2-1: mStartOffset should be the smallest offset");
3240 mRemovedEndOffset
== 35,
3241 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3244 mAddedEndOffset
== 15, // 30 - (25 - 10)
3245 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3246 "removed text length by the new change");
3249 // Replacing text before already replaced text (not sure if actually occurs)
3250 MergeWith(TextChangeData(50, 65, 70, false, false));
3251 MergeWith(TextChangeData(13, 24, 15, false, false));
3252 MOZ_ASSERT(mStartOffset
== 13,
3253 "Test 6-3-1: mStartOffset should be the smallest offset");
3255 mRemovedEndOffset
== 65,
3256 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3258 MOZ_ASSERT(mAddedEndOffset
== 61, // 70 + (15 - 24)
3259 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3261 "removed text length by the new change");
3264 // Replacing text before already replaced text (not sure if actually occurs)
3265 MergeWith(TextChangeData(50, 65, 70, false, false));
3266 MergeWith(TextChangeData(13, 24, 36, false, false));
3267 MOZ_ASSERT(mStartOffset
== 13,
3268 "Test 6-4-1: mStartOffset should be the smallest offset");
3270 mRemovedEndOffset
== 65,
3271 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3273 MOZ_ASSERT(mAddedEndOffset
== 82, // 70 + (36 - 24)
3274 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3276 "removed text length by the new change");
3280 #endif // #ifdef DEBUG
3282 } // namespace mozilla::widget
3285 //////////////////////////////////////////////////////////////
3287 // Convert a GUI event message code to a string.
3288 // Makes it a lot easier to debug events.
3290 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3291 // for a DebugPrintEvent() function that uses
3294 //////////////////////////////////////////////////////////////
3296 nsAutoString
nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent
* aGuiEvent
) {
3297 NS_ASSERTION(nullptr != aGuiEvent
, "cmon, null gui event.");
3299 nsAutoString
eventName(u
"UNKNOWN"_ns
);
3301 # define _ASSIGN_eventName(_value, _name) \
3303 eventName.AssignLiteral(_name); \
3306 switch (aGuiEvent
->mMessage
) {
3307 _ASSIGN_eventName(eBlur
, "eBlur");
3308 _ASSIGN_eventName(eDrop
, "eDrop");
3309 _ASSIGN_eventName(eDragEnter
, "eDragEnter");
3310 _ASSIGN_eventName(eDragExit
, "eDragExit");
3311 _ASSIGN_eventName(eDragOver
, "eDragOver");
3312 _ASSIGN_eventName(eEditorInput
, "eEditorInput");
3313 _ASSIGN_eventName(eFocus
, "eFocus");
3314 _ASSIGN_eventName(eFocusIn
, "eFocusIn");
3315 _ASSIGN_eventName(eFocusOut
, "eFocusOut");
3316 _ASSIGN_eventName(eFormSelect
, "eFormSelect");
3317 _ASSIGN_eventName(eFormChange
, "eFormChange");
3318 _ASSIGN_eventName(eFormReset
, "eFormReset");
3319 _ASSIGN_eventName(eFormSubmit
, "eFormSubmit");
3320 _ASSIGN_eventName(eImageAbort
, "eImageAbort");
3321 _ASSIGN_eventName(eLoadError
, "eLoadError");
3322 _ASSIGN_eventName(eKeyDown
, "eKeyDown");
3323 _ASSIGN_eventName(eKeyPress
, "eKeyPress");
3324 _ASSIGN_eventName(eKeyUp
, "eKeyUp");
3325 _ASSIGN_eventName(eMouseEnterIntoWidget
, "eMouseEnterIntoWidget");
3326 _ASSIGN_eventName(eMouseExitFromWidget
, "eMouseExitFromWidget");
3327 _ASSIGN_eventName(eMouseDown
, "eMouseDown");
3328 _ASSIGN_eventName(eMouseUp
, "eMouseUp");
3329 _ASSIGN_eventName(eMouseClick
, "eMouseClick");
3330 _ASSIGN_eventName(eMouseAuxClick
, "eMouseAuxClick");
3331 _ASSIGN_eventName(eMouseDoubleClick
, "eMouseDoubleClick");
3332 _ASSIGN_eventName(eMouseMove
, "eMouseMove");
3333 _ASSIGN_eventName(eLoad
, "eLoad");
3334 _ASSIGN_eventName(ePopState
, "ePopState");
3335 _ASSIGN_eventName(eBeforeScriptExecute
, "eBeforeScriptExecute");
3336 _ASSIGN_eventName(eAfterScriptExecute
, "eAfterScriptExecute");
3337 _ASSIGN_eventName(eUnload
, "eUnload");
3338 _ASSIGN_eventName(eHashChange
, "eHashChange");
3339 _ASSIGN_eventName(eReadyStateChange
, "eReadyStateChange");
3340 _ASSIGN_eventName(eXULBroadcast
, "eXULBroadcast");
3341 _ASSIGN_eventName(eXULCommandUpdate
, "eXULCommandUpdate");
3343 # undef _ASSIGN_eventName
3346 eventName
.AssignLiteral("UNKNOWN: ");
3347 eventName
.AppendInt(aGuiEvent
->mMessage
);
3351 return nsAutoString(eventName
);
3353 //////////////////////////////////////////////////////////////
3355 // Code to deal with paint and event debug prefs.
3357 //////////////////////////////////////////////////////////////
3363 static PrefPair debug_PrefValues
[] = {
3364 {"nglayout.debug.crossing_event_dumping", false},
3365 {"nglayout.debug.event_dumping", false},
3366 {"nglayout.debug.invalidate_dumping", false},
3367 {"nglayout.debug.motion_event_dumping", false},
3368 {"nglayout.debug.paint_dumping", false}};
3370 //////////////////////////////////////////////////////////////
3371 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName
) {
3372 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3374 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3375 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3376 return debug_PrefValues
[i
].value
;
3382 //////////////////////////////////////////////////////////////
3383 static void debug_SetCachedBoolPref(const char* aPrefName
, bool aValue
) {
3384 NS_ASSERTION(nullptr != aPrefName
, "cmon, pref name is null.");
3386 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3387 if (strcmp(debug_PrefValues
[i
].name
, aPrefName
) == 0) {
3388 debug_PrefValues
[i
].value
= aValue
;
3394 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3397 //////////////////////////////////////////////////////////////
3398 class Debug_PrefObserver final
: public nsIObserver
{
3399 ~Debug_PrefObserver() = default;
3406 NS_IMPL_ISUPPORTS(Debug_PrefObserver
, nsIObserver
)
3409 Debug_PrefObserver::Observe(nsISupports
* subject
, const char* topic
,
3410 const char16_t
* data
) {
3411 NS_ConvertUTF16toUTF8
prefName(data
);
3413 bool value
= Preferences::GetBool(prefName
.get(), false);
3414 debug_SetCachedBoolPref(prefName
.get(), value
);
3418 //////////////////////////////////////////////////////////////
3419 /* static */ void debug_RegisterPrefCallbacks() {
3420 static bool once
= true;
3428 nsCOMPtr
<nsIObserver
> obs(new Debug_PrefObserver());
3429 for (uint32_t i
= 0; i
< ArrayLength(debug_PrefValues
); i
++) {
3430 // Initialize the pref values
3431 debug_PrefValues
[i
].value
=
3432 Preferences::GetBool(debug_PrefValues
[i
].name
, false);
3435 // Register callbacks for when these change
3437 name
.AssignLiteral(debug_PrefValues
[i
].name
,
3438 strlen(debug_PrefValues
[i
].name
));
3439 Preferences::AddStrongObserver(obs
, name
);
3443 //////////////////////////////////////////////////////////////
3444 static int32_t _GetPrintCount() {
3445 static int32_t sCount
= 0;
3449 //////////////////////////////////////////////////////////////
3451 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3452 WidgetGUIEvent
* aGuiEvent
,
3453 const char* aWidgetName
, int32_t aWindowID
) {
3454 if (aGuiEvent
->mMessage
== eMouseMove
) {
3455 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3458 if (aGuiEvent
->mMessage
== eMouseEnterIntoWidget
||
3459 aGuiEvent
->mMessage
== eMouseExitFromWidget
) {
3460 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3464 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3466 NS_LossyConvertUTF16toASCII
tempString(
3467 debug_GuiEventToString(aGuiEvent
).get());
3469 fprintf(aFileOut
, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3470 _GetPrintCount(), tempString
.get(), (void*)aWidget
, aWidgetName
,
3471 aWindowID
, aGuiEvent
->mRefPoint
.x
.value
,
3472 aGuiEvent
->mRefPoint
.y
.value
);
3474 //////////////////////////////////////////////////////////////
3476 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut
, nsIWidget
* aWidget
,
3477 const nsIntRegion
& aRegion
,
3478 const char* aWidgetName
,
3479 int32_t aWindowID
) {
3480 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3481 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3483 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3485 nsIntRect rect
= aRegion
.GetBounds();
3487 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3489 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
, rect
.X(),
3490 rect
.Y(), rect
.Width(), rect
.Height());
3492 fprintf(aFileOut
, "\n");
3494 //////////////////////////////////////////////////////////////
3496 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut
, nsIWidget
* aWidget
,
3497 const LayoutDeviceIntRect
* aRect
,
3498 const char* aWidgetName
,
3499 int32_t aWindowID
) {
3500 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3502 NS_ASSERTION(nullptr != aFileOut
, "cmon, null output FILE");
3503 NS_ASSERTION(nullptr != aWidget
, "cmon, the widget is null");
3505 fprintf(aFileOut
, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3506 _GetPrintCount(), (void*)aWidget
, aWidgetName
, aWindowID
);
3509 fprintf(aFileOut
, " rect=%3d,%-3d %3d,%-3d", aRect
->X(), aRect
->Y(),
3510 aRect
->Width(), aRect
->Height());
3512 fprintf(aFileOut
, " rect=%-15s", "none");
3515 fprintf(aFileOut
, "\n");
3517 //////////////////////////////////////////////////////////////