Bug 1736912 [wpt PR 31334] - Fix CompositeAfterPaint backface-visibility regression...
[gecko.git] / widget / nsBaseWidget.cpp
blob16e1d99de462c869e5ec4abf2f3228f6303a4f42
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"
10 #include <utility>
12 #include "GLConsts.h"
13 #include "InputData.h"
14 #include "LiveResizeListener.h"
15 #include "TouchEvents.h"
16 #include "WritingModes.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/MouseEvents.h"
24 #include "mozilla/Preferences.h"
25 #include "mozilla/PresShell.h"
26 #include "mozilla/Sprintf.h"
27 #include "mozilla/StaticPrefs_apz.h"
28 #include "mozilla/StaticPrefs_dom.h"
29 #include "mozilla/StaticPrefs_gfx.h"
30 #include "mozilla/StaticPrefs_layers.h"
31 #include "mozilla/StaticPrefs_layout.h"
32 #include "mozilla/TextEventDispatcher.h"
33 #include "mozilla/TextEventDispatcherListener.h"
34 #include "mozilla/UniquePtr.h"
35 #include "mozilla/Unused.h"
36 #include "mozilla/VsyncDispatcher.h"
37 #include "mozilla/dom/BrowserParent.h"
38 #include "mozilla/dom/ContentChild.h"
39 #include "mozilla/dom/Document.h"
40 #include "mozilla/gfx/2D.h"
41 #include "mozilla/gfx/GPUProcessManager.h"
42 #include "mozilla/gfx/gfxVars.h"
43 #include "mozilla/layers/APZCCallbackHelper.h"
44 #include "mozilla/layers/APZEventState.h"
45 #include "mozilla/layers/APZInputBridge.h"
46 #include "mozilla/layers/APZThreadUtils.h"
47 #include "mozilla/layers/ChromeProcessController.h"
48 #include "mozilla/layers/Compositor.h"
49 #include "mozilla/layers/CompositorBridgeChild.h"
50 #include "mozilla/layers/CompositorBridgeParent.h"
51 #include "mozilla/layers/CompositorOptions.h"
52 #include "mozilla/layers/IAPZCTreeManager.h"
53 #include "mozilla/layers/ImageBridgeChild.h"
54 #include "mozilla/layers/InputAPZContext.h"
55 #include "mozilla/layers/WebRenderLayerManager.h"
56 #include "mozilla/webrender/WebRenderTypes.h"
57 #include "nsAppDirectoryServiceDefs.h"
58 #include "nsCOMPtr.h"
59 #include "nsContentUtils.h"
60 #include "nsDeviceContext.h"
61 #include "nsGfxCIID.h"
62 #include "nsIAppWindow.h"
63 #include "nsIBaseWindow.h"
64 #include "nsIContent.h"
65 #include "nsIScreenManager.h"
66 #include "nsISimpleEnumerator.h"
67 #include "nsIWidgetListener.h"
68 #include "nsRefPtrHashtable.h"
69 #include "nsServiceManagerUtils.h"
70 #include "nsWidgetsCID.h"
71 #include "nsXULPopupManager.h"
72 #include "prdtoa.h"
73 #include "prenv.h"
74 #ifdef ACCESSIBILITY
75 # include "nsAccessibilityService.h"
76 #endif
77 #include "gfxConfig.h"
78 #include "gfxUtils.h" // for ToDeviceColor
79 #include "mozilla/layers/CompositorSession.h"
80 #include "VRManagerChild.h"
81 #include "gfxConfig.h"
82 #include "nsView.h"
83 #include "nsViewManager.h"
85 #ifdef DEBUG
86 # include "nsIObserver.h"
88 static void debug_RegisterPrefCallbacks();
90 #endif
92 #ifdef NOISY_WIDGET_LEAKS
93 static int32_t gNumWidgets;
94 #endif
96 #ifdef XP_MACOSX
97 # include "nsCocoaFeatures.h"
98 #endif
100 nsIRollupListener* nsBaseWidget::gRollupListener = nullptr;
102 using namespace mozilla::dom;
103 using namespace mozilla::layers;
104 using namespace mozilla::ipc;
105 using namespace mozilla::widget;
106 using namespace mozilla;
108 // Async pump timer during injected long touch taps
109 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
110 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
111 int32_t nsIWidget::sPointerIdCounter = 0;
113 // Some statics from nsIWidget.h
114 /*static*/
115 uint64_t AutoObserverNotifier::sObserverId = 0;
116 /*static*/ nsTHashMap<uint64_t, nsCOMPtr<nsIObserver>>
117 AutoObserverNotifier::sSavedObservers;
119 // The maximum amount of time to let the EnableDragDrop runnable wait in the
120 // idle queue before timing out and moving it to the regular queue. Value is in
121 // milliseconds.
122 const uint32_t kAsyncDragDropTimeout = 1000;
124 namespace mozilla::widget {
126 void IMENotification::SelectionChangeDataBase::SetWritingMode(
127 const WritingMode& aWritingMode) {
128 mWritingMode = aWritingMode.mWritingMode.bits;
131 WritingMode IMENotification::SelectionChangeDataBase::GetWritingMode() const {
132 return WritingMode(mWritingMode);
135 } // namespace mozilla::widget
137 NS_IMPL_ISUPPORTS(nsBaseWidget, nsIWidget, nsISupportsWeakReference)
139 //-------------------------------------------------------------------------
141 // nsBaseWidget constructor
143 //-------------------------------------------------------------------------
145 nsBaseWidget::nsBaseWidget()
146 : mWidgetListener(nullptr),
147 mAttachedWidgetListener(nullptr),
148 mPreviouslyAttachedWidgetListener(nullptr),
149 mCompositorVsyncDispatcher(nullptr),
150 mBorderStyle(eBorderStyle_none),
151 mBounds(0, 0, 0, 0),
152 mOriginalBounds(nullptr),
153 mSizeMode(nsSizeMode_Normal),
154 mIsTiled(false),
155 mPopupLevel(ePopupLevelTop),
156 mPopupType(ePopupTypeAny),
157 mHasRemoteContent(false),
158 mFissionWindow(false),
159 mUpdateCursor(true),
160 mUseAttachedEvents(false),
161 mIMEHasFocus(false),
162 mIMEHasQuit(false),
163 mIsFullyOccluded(false) {
164 #ifdef NOISY_WIDGET_LEAKS
165 gNumWidgets++;
166 printf("WIDGETS+ = %d\n", gNumWidgets);
167 #endif
169 #ifdef DEBUG
170 debug_RegisterPrefCallbacks();
171 #endif
173 mShutdownObserver = new WidgetShutdownObserver(this);
176 NS_IMPL_ISUPPORTS(WidgetShutdownObserver, nsIObserver)
178 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget* aWidget)
179 : mWidget(aWidget), mRegistered(false) {
180 Register();
183 WidgetShutdownObserver::~WidgetShutdownObserver() {
184 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
185 // gets torn down. The observer service and nsBaseWidget have a ref on us
186 // so nsBaseWidget has to call Unregister and then clear its ref.
189 NS_IMETHODIMP
190 WidgetShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
191 const char16_t* aData) {
192 if (!mWidget) {
193 return NS_OK;
195 if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
196 RefPtr<nsBaseWidget> widget(mWidget);
197 widget->Shutdown();
198 } else if (!strcmp(aTopic, "quit-application")) {
199 RefPtr<nsBaseWidget> widget(mWidget);
200 widget->QuitIME();
202 return NS_OK;
205 void WidgetShutdownObserver::Register() {
206 if (!mRegistered) {
207 mRegistered = true;
208 nsContentUtils::RegisterShutdownObserver(this);
210 #ifndef MOZ_WIDGET_ANDROID
211 // The primary purpose of observing quit-application is
212 // to avoid leaking a widget on Windows when nothing else
213 // breaks the circular reference between the widget and
214 // TSFTextStore. However, our Android IME code crashes if
215 // doing this on Android, so let's not do this on Android.
216 // Doing this on Gtk and Mac just in case.
217 nsCOMPtr<nsIObserverService> observerService =
218 mozilla::services::GetObserverService();
219 if (observerService) {
220 observerService->AddObserver(this, "quit-application", false);
222 #endif
226 void WidgetShutdownObserver::Unregister() {
227 if (mRegistered) {
228 mWidget = nullptr;
230 #ifndef MOZ_WIDGET_ANDROID
231 nsCOMPtr<nsIObserverService> observerService =
232 mozilla::services::GetObserverService();
233 if (observerService) {
234 observerService->RemoveObserver(this, "quit-application");
236 #endif
238 nsContentUtils::UnregisterShutdownObserver(this);
239 mRegistered = false;
243 #define INTL_APP_LOCALES_CHANGED "intl:app-locales-changed"
244 #define L10N_PSEUDO_PREF "intl.l10n.pseudo"
246 static const char* kObservedPrefs[] = {L10N_PSEUDO_PREF, nullptr};
248 NS_IMPL_ISUPPORTS(LocalesChangedObserver, nsIObserver)
250 LocalesChangedObserver::LocalesChangedObserver(nsBaseWidget* aWidget)
251 : mWidget(aWidget), mRegistered(false) {
252 Register();
255 LocalesChangedObserver::~LocalesChangedObserver() {
256 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
257 // gets torn down. The observer service and nsBaseWidget have a ref on us
258 // so nsBaseWidget has to call Unregister and then clear its ref.
261 NS_IMETHODIMP
262 LocalesChangedObserver::Observe(nsISupports* aSubject, const char* aTopic,
263 const char16_t* aData) {
264 if (!mWidget) {
265 return NS_OK;
267 if (!strcmp(aTopic, INTL_APP_LOCALES_CHANGED)) {
268 RefPtr<nsBaseWidget> widget(mWidget);
269 widget->LocalesChanged();
270 } else {
271 MOZ_ASSERT(!strcmp("nsPref:changed", aTopic));
272 nsDependentString pref(aData);
273 if (pref.EqualsLiteral(L10N_PSEUDO_PREF)) {
274 RefPtr<nsBaseWidget> widget(mWidget);
275 widget->LocalesChanged();
278 return NS_OK;
281 void LocalesChangedObserver::Register() {
282 if (mRegistered) {
283 return;
286 DebugOnly<nsresult> rv =
287 Preferences::AddStrongObservers(this, kObservedPrefs);
288 MOZ_ASSERT(NS_SUCCEEDED(rv), "Adding observers failed.");
290 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
291 if (obs) {
292 obs->AddObserver(this, INTL_APP_LOCALES_CHANGED, true);
295 // Locale might be update before registering
296 RefPtr<nsBaseWidget> widget(mWidget);
297 widget->LocalesChanged();
299 mRegistered = true;
302 void LocalesChangedObserver::Unregister() {
303 if (!mRegistered) {
304 return;
307 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
308 if (obs) {
309 obs->RemoveObserver(this, INTL_APP_LOCALES_CHANGED);
311 Preferences::RemoveObservers(this, kObservedPrefs);
313 mWidget = nullptr;
314 mRegistered = false;
317 void nsBaseWidget::Shutdown() {
318 NotifyLiveResizeStopped();
319 RevokeTransactionIdAllocator();
320 DestroyCompositor();
321 FreeLocalesChangedObserver();
322 FreeShutdownObserver();
325 void nsBaseWidget::QuitIME() {
326 IMEStateManager::WidgetOnQuit(this);
327 this->mIMEHasQuit = true;
330 void nsBaseWidget::DestroyCompositor() {
331 // We release this before releasing the compositor, since it may hold the
332 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
333 // trigger a paint, creating a new compositor, and we don't want to re-use
334 // the old vsync dispatcher.
335 if (mCompositorVsyncDispatcher) {
336 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
338 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
339 mCompositorVsyncDispatcher->Shutdown();
340 mCompositorVsyncDispatcher = nullptr;
343 // The compositor shutdown sequence looks like this:
344 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
345 // 2. CompositorBridgeChild synchronously sends WillClose.
346 // 3. CompositorBridgeParent releases some resources (such as the layer
347 // manager, compositor, and widget).
348 // 4. CompositorBridgeChild::Destroy returns.
349 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
350 // compositor thread when the I/O thread closes the IPC channel.
351 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
352 // releases the reference CompositorBridgeParent holds to itself.
354 // When CompositorSession::Shutdown returns, we assume the compositor is gone
355 // or will be gone very soon.
356 if (mCompositorSession) {
357 ReleaseContentController();
358 mAPZC = nullptr;
359 SetCompositorWidgetDelegate(nullptr);
360 mCompositorBridgeChild = nullptr;
362 // XXX CompositorBridgeChild and CompositorBridgeParent might be re-created
363 // in ClientLayerManager destructor. See bug 1133426.
364 RefPtr<CompositorSession> session = std::move(mCompositorSession);
365 session->Shutdown();
369 // This prevents the layer manager from starting a new transaction during
370 // shutdown.
371 void nsBaseWidget::RevokeTransactionIdAllocator() {
372 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
373 return;
375 mWindowRenderer->AsWebRender()->SetTransactionIdAllocator(nullptr);
378 void nsBaseWidget::ReleaseContentController() {
379 if (mRootContentController) {
380 mRootContentController->Destroy();
381 mRootContentController = nullptr;
385 void nsBaseWidget::DestroyLayerManager() {
386 if (mWindowRenderer) {
387 mWindowRenderer->Destroy();
388 mWindowRenderer = nullptr;
390 DestroyCompositor();
393 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
395 void nsBaseWidget::FreeShutdownObserver() {
396 if (mShutdownObserver) {
397 mShutdownObserver->Unregister();
399 mShutdownObserver = nullptr;
402 void nsBaseWidget::FreeLocalesChangedObserver() {
403 if (mLocalesChangedObserver) {
404 mLocalesChangedObserver->Unregister();
406 mLocalesChangedObserver = nullptr;
409 //-------------------------------------------------------------------------
411 // nsBaseWidget destructor
413 //-------------------------------------------------------------------------
415 nsBaseWidget::~nsBaseWidget() {
416 IMEStateManager::WidgetDestroyed(this);
418 FreeLocalesChangedObserver();
419 FreeShutdownObserver();
420 RevokeTransactionIdAllocator();
421 DestroyLayerManager();
423 #ifdef NOISY_WIDGET_LEAKS
424 gNumWidgets--;
425 printf("WIDGETS- = %d\n", gNumWidgets);
426 #endif
428 delete mOriginalBounds;
431 //-------------------------------------------------------------------------
433 // Basic create.
435 //-------------------------------------------------------------------------
436 void nsBaseWidget::BaseCreate(nsIWidget* aParent, nsWidgetInitData* aInitData) {
437 // keep a reference to the device context
438 if (nullptr != aInitData) {
439 mWindowType = aInitData->mWindowType;
440 mBorderStyle = aInitData->mBorderStyle;
441 mPopupLevel = aInitData->mPopupLevel;
442 mPopupType = aInitData->mPopupHint;
443 mHasRemoteContent = aInitData->mHasRemoteContent;
444 mFissionWindow = aInitData->mFissionWindow;
447 if (aParent) {
448 aParent->AddChild(this);
452 //-------------------------------------------------------------------------
454 // Accessor functions to get/set the client data
456 //-------------------------------------------------------------------------
458 nsIWidgetListener* nsBaseWidget::GetWidgetListener() const {
459 return mWidgetListener;
462 void nsBaseWidget::SetWidgetListener(nsIWidgetListener* aWidgetListener) {
463 mWidgetListener = aWidgetListener;
466 already_AddRefed<nsIWidget> nsBaseWidget::CreateChild(
467 const LayoutDeviceIntRect& aRect, nsWidgetInitData* aInitData,
468 bool aForceUseIWidgetParent) {
469 nsIWidget* parent = this;
470 nsNativeWidget nativeParent = nullptr;
472 if (!aForceUseIWidgetParent) {
473 // Use only either parent or nativeParent, not both, to match
474 // existing code. Eventually Create() should be divested of its
475 // nativeWidget parameter.
476 nativeParent = parent ? parent->GetNativeData(NS_NATIVE_WIDGET) : nullptr;
477 parent = nativeParent ? nullptr : parent;
478 MOZ_ASSERT(!parent || !nativeParent, "messed up logic");
481 nsCOMPtr<nsIWidget> widget;
482 if (aInitData && aInitData->mWindowType == eWindowType_popup) {
483 widget = AllocateChildPopupWidget();
484 } else {
485 widget = nsIWidget::CreateChildWindow();
488 if (widget &&
489 NS_SUCCEEDED(widget->Create(parent, nativeParent, aRect, aInitData))) {
490 return widget.forget();
493 return nullptr;
496 // Attach a view to our widget which we'll send events to.
497 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents) {
498 NS_ASSERTION((mWindowType == eWindowType_toplevel ||
499 mWindowType == eWindowType_dialog ||
500 mWindowType == eWindowType_invisible ||
501 mWindowType == eWindowType_child),
502 "Can't attach to window of that type");
504 mUseAttachedEvents = aUseAttachedEvents;
507 nsIWidgetListener* nsBaseWidget::GetAttachedWidgetListener() const {
508 return mAttachedWidgetListener;
511 nsIWidgetListener* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
512 return mPreviouslyAttachedWidgetListener;
515 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
516 nsIWidgetListener* aListener) {
517 mPreviouslyAttachedWidgetListener = aListener;
520 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener* aListener) {
521 mAttachedWidgetListener = aListener;
524 //-------------------------------------------------------------------------
526 // Close this nsBaseWidget
528 //-------------------------------------------------------------------------
529 void nsBaseWidget::Destroy() {
530 // Just in case our parent is the only ref to us
531 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
532 // disconnect from the parent
533 nsIWidget* parent = GetParent();
534 if (parent) {
535 parent->RemoveChild(this);
539 //-------------------------------------------------------------------------
541 // Get this nsBaseWidget parent
543 //-------------------------------------------------------------------------
544 nsIWidget* nsBaseWidget::GetParent(void) { return nullptr; }
546 //-------------------------------------------------------------------------
548 // Get this nsBaseWidget top level widget
550 //-------------------------------------------------------------------------
551 nsIWidget* nsBaseWidget::GetTopLevelWidget() {
552 nsIWidget *topLevelWidget = nullptr, *widget = this;
553 while (widget) {
554 topLevelWidget = widget;
555 widget = widget->GetParent();
557 return topLevelWidget;
560 //-------------------------------------------------------------------------
562 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
564 //-------------------------------------------------------------------------
565 nsIWidget* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
567 float nsBaseWidget::GetDPI() { return 96.0f; }
569 CSSToLayoutDeviceScale nsIWidget::GetDefaultScale() {
570 double devPixelsPerCSSPixel = StaticPrefs::layout_css_devPixelsPerPx();
572 if (devPixelsPerCSSPixel <= 0.0) {
573 devPixelsPerCSSPixel = GetDefaultScaleInternal();
576 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel);
579 nsIntSize nsIWidget::CustomCursorSize(const Cursor& aCursor) {
580 MOZ_ASSERT(aCursor.IsCustom());
581 int32_t width = 0;
582 int32_t height = 0;
583 aCursor.mContainer->GetWidth(&width);
584 aCursor.mContainer->GetHeight(&height);
585 aCursor.mResolution.ApplyTo(width, height);
586 return {width, height};
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");
598 if (!mFirstChild) {
599 mFirstChild = mLastChild = aChild;
600 } else {
601 // append to the list
602 MOZ_ASSERT(mLastChild);
603 MOZ_ASSERT(!mLastChild->GetNextSibling());
604 mLastChild->SetNextSibling(aChild);
605 aChild->SetPrevSibling(mLastChild);
606 mLastChild = aChild;
610 //-------------------------------------------------------------------------
612 // Remove a child from the list of children
614 //-------------------------------------------------------------------------
615 void nsBaseWidget::RemoveChild(nsIWidget* aChild) {
616 #ifdef DEBUG
617 # ifdef XP_MACOSX
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!");
622 # else
623 MOZ_RELEASE_ASSERT(aChild->GetParent() == this, "Not one of our kids!");
624 # endif
625 #endif
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();
638 if (prev) {
639 prev->SetNextSibling(next);
641 if (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
656 // from our parent.
657 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
659 mZIndex = aZIndex;
661 // reorder this child in its parent's list.
662 auto* parent = static_cast<nsBaseWidget*>(GetParent());
663 if (parent) {
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();
672 mNextSibling = sib;
673 mPrevSibling = prev;
674 sib->SetPrevSibling(this);
675 if (prev) {
676 prev->SetNextSibling(this);
677 } else {
678 NS_ASSERTION(sib == parent->mFirstChild, "Broken child list");
679 // We've taken ownership of sib, so it's safe to have parent let
680 // go of it
681 parent->mFirstChild = this;
683 PlaceBehind(eZPlacementBelow, sib, false);
684 break;
687 // were we added to the list?
688 if (!sib) {
689 parent->AddChild(this);
694 //-------------------------------------------------------------------------
696 // Maximize, minimize or restore the window. The BaseWidget implementation
697 // merely stores the state.
699 //-------------------------------------------------------------------------
700 void nsBaseWidget::SetSizeMode(nsSizeMode aMode) {
701 MOZ_ASSERT(aMode == nsSizeMode_Normal || aMode == nsSizeMode_Minimized ||
702 aMode == nsSizeMode_Maximized || aMode == nsSizeMode_Fullscreen);
703 mSizeMode = aMode;
706 void nsBaseWidget::GetWorkspaceID(nsAString& workspaceID) {
707 workspaceID.Truncate();
710 void nsBaseWidget::MoveToWorkspace(const nsAString& workspaceID) {
711 // Noop.
714 //-------------------------------------------------------------------------
716 // Get this component cursor
718 //-------------------------------------------------------------------------
720 void nsBaseWidget::SetCursor(const Cursor& aCursor) { mCursor = aCursor; }
722 //-------------------------------------------------------------------------
724 // Window transparency methods
726 //-------------------------------------------------------------------------
728 void nsBaseWidget::SetTransparencyMode(nsTransparencyMode aMode) {}
730 nsTransparencyMode nsBaseWidget::GetTransparencyMode() {
731 return eTransparencyOpaque;
734 /* virtual */
735 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage,
736 uint16_t aDuration,
737 nsISupports* aData,
738 nsIRunnable* aCallback) {
739 MOZ_ASSERT_UNREACHABLE(
740 "Should never call PerformFullscreenTransition on nsBaseWidget");
743 //-------------------------------------------------------------------------
745 // Put the window into full-screen mode
747 //-------------------------------------------------------------------------
748 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen,
749 nsIScreen* aScreen) {
750 HideWindowChrome(aFullScreen);
752 if (aFullScreen) {
753 if (!mOriginalBounds) {
754 mOriginalBounds = new LayoutDeviceIntRect();
756 *mOriginalBounds = GetScreenBounds();
758 // Move to top-left corner of screen and size to the screen dimensions
759 nsCOMPtr<nsIScreen> screen = aScreen;
760 if (!screen) {
761 screen = GetWidgetScreen();
763 if (screen) {
764 int32_t left, top, width, height;
765 if (NS_SUCCEEDED(
766 screen->GetRectDisplayPix(&left, &top, &width, &height))) {
767 Resize(left, top, width, height, true);
770 } else if (mOriginalBounds) {
771 if (BoundsUseDesktopPixels()) {
772 DesktopRect deskRect = *mOriginalBounds / GetDesktopToDeviceScale();
773 Resize(deskRect.X(), deskRect.Y(), deskRect.Width(), deskRect.Height(),
774 true);
775 } else {
776 Resize(mOriginalBounds->X(), mOriginalBounds->Y(),
777 mOriginalBounds->Width(), mOriginalBounds->Height(), true);
782 nsresult nsBaseWidget::MakeFullScreen(bool aFullScreen, nsIScreen* aScreen) {
783 InfallibleMakeFullScreen(aFullScreen, aScreen);
784 return NS_OK;
787 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
788 nsBaseWidget* aWidget, gfxContext* aTarget, BufferMode aDoubleBuffering)
789 : mWidget(aWidget) {
790 WindowRenderer* renderer = mWidget->GetWindowRenderer();
791 if (renderer->AsFallback()) {
792 mRenderer = renderer->AsFallback();
793 mRenderer->SetTarget(aTarget, aDoubleBuffering);
797 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
798 if (mRenderer) {
799 mRenderer->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE);
803 bool nsBaseWidget::IsSmallPopup() const {
804 return mWindowType == eWindowType_popup && mPopupType != ePopupTypePanel;
807 bool nsBaseWidget::ComputeShouldAccelerate() {
808 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING) &&
809 (WidgetTypeSupportsAcceleration() ||
810 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
813 bool nsBaseWidget::UseAPZ() {
814 return (gfxPlatform::AsyncPanZoomEnabled() &&
815 (WindowType() == eWindowType_toplevel ||
816 WindowType() == eWindowType_child ||
817 ((WindowType() == eWindowType_popup ||
818 WindowType() == eWindowType_dialog) &&
819 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
822 void nsBaseWidget::CreateCompositor() {
823 LayoutDeviceIntRect rect = GetBounds();
824 CreateCompositor(rect.Width(), rect.Height());
827 already_AddRefed<GeckoContentController>
828 nsBaseWidget::CreateRootContentController() {
829 RefPtr<GeckoContentController> controller =
830 new ChromeProcessController(this, mAPZEventState, mAPZC);
831 return controller.forget();
834 void nsBaseWidget::ConfigureAPZCTreeManager() {
835 MOZ_ASSERT(NS_IsMainThread());
836 MOZ_ASSERT(mAPZC);
838 ConfigureAPZControllerThread();
840 float dpi = GetDPI();
841 // On Android the main thread is not the controller thread
842 APZThreadUtils::RunOnControllerThread(
843 NewRunnableMethod<float>("layers::IAPZCTreeManager::SetDPI", mAPZC,
844 &IAPZCTreeManager::SetDPI, dpi));
846 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
847 KeyboardMap map = RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
848 // On Android the main thread is not the controller thread
849 APZThreadUtils::RunOnControllerThread(NewRunnableMethod<KeyboardMap>(
850 "layers::IAPZCTreeManager::SetKeyboardMap", mAPZC,
851 &IAPZCTreeManager::SetKeyboardMap, map));
854 RefPtr<IAPZCTreeManager> treeManager = mAPZC; // for capture by the lambdas
856 ContentReceivedInputBlockCallback callback(
857 [treeManager](uint64_t aInputBlockId, bool aPreventDefault) {
858 MOZ_ASSERT(NS_IsMainThread());
859 APZThreadUtils::RunOnControllerThread(NewRunnableMethod<uint64_t, bool>(
860 "layers::IAPZCTreeManager::ContentReceivedInputBlock", treeManager,
861 &IAPZCTreeManager::ContentReceivedInputBlock, aInputBlockId,
862 aPreventDefault));
864 mAPZEventState = new APZEventState(this, std::move(callback));
866 mSetAllowedTouchBehaviorCallback =
867 [treeManager](uint64_t aInputBlockId,
868 const nsTArray<TouchBehaviorFlags>& aFlags) {
869 MOZ_ASSERT(NS_IsMainThread());
870 APZThreadUtils::RunOnControllerThread(
871 NewRunnableMethod<
872 uint64_t, StoreCopyPassByLRef<nsTArray<TouchBehaviorFlags>>>(
873 "layers::IAPZCTreeManager::SetAllowedTouchBehavior",
874 treeManager, &IAPZCTreeManager::SetAllowedTouchBehavior,
875 aInputBlockId, aFlags.Clone()));
878 mRootContentController = CreateRootContentController();
879 if (mRootContentController) {
880 mCompositorSession->SetContentController(mRootContentController);
883 // When APZ is enabled, we can actually enable raw touch events because we
884 // have code that can deal with them properly. If APZ is not enabled, this
885 // function doesn't get called.
886 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
887 RegisterTouchWindow();
891 void nsBaseWidget::ConfigureAPZControllerThread() {
892 // By default the controller thread is the main thread.
893 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
896 void nsBaseWidget::SetConfirmedTargetAPZC(
897 uint64_t aInputBlockId,
898 const nsTArray<ScrollableLayerGuid>& aTargets) const {
899 APZThreadUtils::RunOnControllerThread(
900 NewRunnableMethod<uint64_t,
901 StoreCopyPassByRRef<nsTArray<ScrollableLayerGuid>>>(
902 "layers::IAPZCTreeManager::SetTargetAPZC", mAPZC,
903 &IAPZCTreeManager::SetTargetAPZC, aInputBlockId, aTargets.Clone()));
906 void nsBaseWidget::UpdateZoomConstraints(
907 const uint32_t& aPresShellId, const ScrollableLayerGuid::ViewID& aViewId,
908 const Maybe<ZoomConstraints>& aConstraints) {
909 if (!mCompositorSession || !mAPZC) {
910 if (mInitialZoomConstraints) {
911 MOZ_ASSERT(mInitialZoomConstraints->mPresShellID == aPresShellId);
912 MOZ_ASSERT(mInitialZoomConstraints->mViewID == aViewId);
913 if (!aConstraints) {
914 mInitialZoomConstraints.reset();
918 if (aConstraints) {
919 // We have some constraints, but the compositor and APZC aren't created
920 // yet. Save these so we can use them later.
921 mInitialZoomConstraints = Some(
922 InitialZoomConstraints(aPresShellId, aViewId, aConstraints.ref()));
924 return;
926 LayersId layersId = mCompositorSession->RootLayerTreeId();
927 mAPZC->UpdateZoomConstraints(
928 ScrollableLayerGuid(layersId, aPresShellId, aViewId), aConstraints);
931 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC; }
933 nsEventStatus nsBaseWidget::ProcessUntransformedAPZEvent(
934 WidgetInputEvent* aEvent, const APZEventResult& aApzResult) {
935 MOZ_ASSERT(NS_IsMainThread());
936 ScrollableLayerGuid targetGuid = aApzResult.mTargetGuid;
937 uint64_t inputBlockId = aApzResult.mInputBlockId;
938 InputAPZContext context(aApzResult.mTargetGuid, inputBlockId,
939 aApzResult.GetStatus());
941 // Make a copy of the original event for the APZCCallbackHelper helpers that
942 // we call later, because the event passed to DispatchEvent can get mutated in
943 // ways that we don't want (i.e. touch points can get stripped out).
944 nsEventStatus status;
945 UniquePtr<WidgetEvent> original(aEvent->Duplicate());
946 DispatchEvent(aEvent, status);
948 if (mAPZC && !InputAPZContext::WasRoutedToChildProcess() && inputBlockId) {
949 // EventStateManager did not route the event into the child process.
950 // It's safe to communicate to APZ that the event has been processed.
951 // Note that here aGuid.mLayersId might be different from
952 // mCompositorSession->RootLayerTreeId() because the event might have gotten
953 // hit-tested by APZ to be targeted at a child process, but a parent process
954 // event listener called preventDefault on it. In that case aGuid.mLayersId
955 // would still be the layers id for the child process, but the event would
956 // not have actually gotten routed to the child process. The main-thread
957 // hit-test result therefore needs to use the parent process layers id.
958 LayersId rootLayersId = mCompositorSession->RootLayerTreeId();
960 RefPtr<DisplayportSetListener> postLayerization;
961 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
962 nsTArray<TouchBehaviorFlags> allowedTouchBehaviors;
963 if (touchEvent->mMessage == eTouchStart) {
964 if (StaticPrefs::layout_css_touch_action_enabled()) {
965 allowedTouchBehaviors =
966 APZCCallbackHelper::SendSetAllowedTouchBehaviorNotification(
967 this, GetDocument(), *(original->AsTouchEvent()),
968 inputBlockId, mSetAllowedTouchBehaviorCallback);
970 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
971 this, GetDocument(), *(original->AsTouchEvent()), rootLayersId,
972 inputBlockId);
974 mAPZEventState->ProcessTouchEvent(*touchEvent, targetGuid, inputBlockId,
975 aApzResult.GetStatus(), status,
976 std::move(allowedTouchBehaviors));
977 } else if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
978 MOZ_ASSERT(wheelEvent->mFlags.mHandledByAPZ);
979 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
980 this, GetDocument(), *(original->AsWheelEvent()), rootLayersId,
981 inputBlockId);
982 if (wheelEvent->mCanTriggerSwipe) {
983 ReportSwipeStarted(inputBlockId, wheelEvent->TriggersSwipe());
985 mAPZEventState->ProcessWheelEvent(*wheelEvent, inputBlockId);
986 } else if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
987 MOZ_ASSERT(mouseEvent->mFlags.mHandledByAPZ);
988 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
989 this, GetDocument(), *(original->AsMouseEvent()), rootLayersId,
990 inputBlockId);
991 mAPZEventState->ProcessMouseEvent(*mouseEvent, inputBlockId);
993 if (postLayerization) {
994 postLayerization->Register();
998 return status;
1001 template <class InputType, class EventType>
1002 class DispatchEventOnMainThread : public Runnable {
1003 public:
1004 DispatchEventOnMainThread(const InputType& aInput, nsBaseWidget* aWidget,
1005 const APZEventResult& aAPZResult)
1006 : mozilla::Runnable("DispatchEventOnMainThread"),
1007 mInput(aInput),
1008 mWidget(aWidget),
1009 mAPZResult(aAPZResult) {}
1011 NS_IMETHOD Run() override {
1012 EventType event = mInput.ToWidgetEvent(mWidget);
1013 mWidget->ProcessUntransformedAPZEvent(&event, mAPZResult);
1014 return NS_OK;
1017 private:
1018 InputType mInput;
1019 nsBaseWidget* mWidget;
1020 APZEventResult mAPZResult;
1023 template <class InputType, class EventType>
1024 class DispatchInputOnControllerThread : public Runnable {
1025 public:
1026 DispatchInputOnControllerThread(const EventType& aEvent,
1027 IAPZCTreeManager* aAPZC,
1028 nsBaseWidget* aWidget)
1029 : mozilla::Runnable("DispatchInputOnControllerThread"),
1030 mMainMessageLoop(MessageLoop::current()),
1031 mInput(aEvent),
1032 mAPZC(aAPZC),
1033 mWidget(aWidget) {}
1035 NS_IMETHOD Run() override {
1036 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(mInput);
1037 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1038 return NS_OK;
1040 RefPtr<Runnable> r = new DispatchEventOnMainThread<InputType, EventType>(
1041 mInput, mWidget, result);
1042 mMainMessageLoop->PostTask(r.forget());
1043 return NS_OK;
1046 private:
1047 MessageLoop* mMainMessageLoop;
1048 InputType mInput;
1049 RefPtr<IAPZCTreeManager> mAPZC;
1050 nsBaseWidget* mWidget;
1053 void nsBaseWidget::DispatchTouchInput(MultiTouchInput& aInput,
1054 uint16_t aInputSource) {
1055 MOZ_ASSERT(NS_IsMainThread());
1056 MOZ_ASSERT(aInputSource ==
1057 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH ||
1058 aInputSource == mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN);
1059 if (mAPZC) {
1060 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1062 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1063 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1064 return;
1067 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1068 ProcessUntransformedAPZEvent(&event, result);
1069 } else {
1070 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1072 nsEventStatus status;
1073 DispatchEvent(&event, status);
1077 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput& aInput) {
1078 MOZ_ASSERT(NS_IsMainThread());
1079 if (mAPZC) {
1080 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1082 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1083 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1084 return;
1087 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1088 ProcessUntransformedAPZEvent(&event, result);
1089 } else {
1090 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1091 nsEventStatus status;
1092 DispatchEvent(&event, status);
1096 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput& aInput) {
1097 MOZ_ASSERT(NS_IsMainThread());
1098 if (mAPZC) {
1099 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1100 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1102 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1103 return;
1105 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1106 ProcessUntransformedAPZEvent(&event, result);
1107 } else {
1108 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1109 nsEventStatus status;
1110 DispatchEvent(&event, status);
1114 nsIWidget::ContentAndAPZEventStatus nsBaseWidget::DispatchInputEvent(
1115 WidgetInputEvent* aEvent) {
1116 nsIWidget::ContentAndAPZEventStatus status;
1117 MOZ_ASSERT(NS_IsMainThread());
1118 if (mAPZC) {
1119 if (APZThreadUtils::IsControllerThread()) {
1120 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1121 status.mApzStatus = result.GetStatus();
1122 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1123 return status;
1125 status.mContentStatus = ProcessUntransformedAPZEvent(aEvent, result);
1126 return status;
1128 if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1129 RefPtr<Runnable> r =
1130 new DispatchInputOnControllerThread<ScrollWheelInput,
1131 WidgetWheelEvent>(*wheelEvent,
1132 mAPZC, this);
1133 APZThreadUtils::RunOnControllerThread(std::move(r));
1134 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1135 return status;
1137 if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1138 RefPtr<Runnable> r =
1139 new DispatchInputOnControllerThread<MouseInput, WidgetMouseEvent>(
1140 *mouseEvent, mAPZC, this);
1141 APZThreadUtils::RunOnControllerThread(std::move(r));
1142 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1143 return status;
1145 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
1146 RefPtr<Runnable> r =
1147 new DispatchInputOnControllerThread<MultiTouchInput,
1148 WidgetTouchEvent>(*touchEvent,
1149 mAPZC, this);
1150 APZThreadUtils::RunOnControllerThread(std::move(r));
1151 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1152 return status;
1154 // Allow dispatching keyboard events on Gecko thread.
1155 MOZ_ASSERT(aEvent->AsKeyboardEvent());
1158 DispatchEvent(aEvent, status.mContentStatus);
1159 return status;
1162 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent* aEvent) {
1163 MOZ_ASSERT(NS_IsMainThread());
1164 if (mAPZC) {
1165 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1166 mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1170 Document* nsBaseWidget::GetDocument() const {
1171 if (mWidgetListener) {
1172 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1173 return presShell->GetDocument();
1176 return nullptr;
1179 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1180 // Parent directly listens to the vsync source whereas
1181 // child process communicate via IPC
1182 // Should be called AFTER gfxPlatform is initialized
1183 if (XRE_IsParentProcess()) {
1184 if (!mCompositorVsyncDispatcherLock) {
1185 mCompositorVsyncDispatcherLock =
1186 MakeUnique<Mutex>("mCompositorVsyncDispatcherLock");
1188 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1189 if (!mCompositorVsyncDispatcher) {
1190 mCompositorVsyncDispatcher = new CompositorVsyncDispatcher();
1195 already_AddRefed<CompositorVsyncDispatcher>
1196 nsBaseWidget::GetCompositorVsyncDispatcher() {
1197 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
1199 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1200 RefPtr<CompositorVsyncDispatcher> dispatcher = mCompositorVsyncDispatcher;
1201 return dispatcher.forget();
1204 already_AddRefed<WebRenderLayerManager> nsBaseWidget::CreateCompositorSession(
1205 int aWidth, int aHeight, CompositorOptions* aOptionsOut) {
1206 MOZ_ASSERT(aOptionsOut);
1208 do {
1209 CreateCompositorVsyncDispatcher();
1211 gfx::GPUProcessManager* gpu = gfx::GPUProcessManager::Get();
1212 // Make sure GPU process is ready for use.
1213 // If it failed to connect to GPU process, GPU process usage is disabled in
1214 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1215 gpu->EnsureGPUReady();
1217 // If widget type does not supports acceleration, we may be allowed to use
1218 // software WebRender instead. If not, then we use ClientLayerManager even
1219 // when gfxVars::UseWebRender() is true. WebRender could coexist only with
1220 // BasicCompositor.
1221 bool supportsAcceleration = WidgetTypeSupportsAcceleration();
1222 bool enableWR;
1223 bool enableSWWR;
1224 if (supportsAcceleration ||
1225 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1226 enableWR = gfx::gfxVars::UseWebRender();
1227 enableSWWR = gfx::gfxVars::UseSoftwareWebRender();
1228 } else {
1229 enableWR = enableSWWR = gfx::gfxVars::UseWebRender();
1231 MOZ_RELEASE_ASSERT(enableWR);
1232 bool enableAPZ = UseAPZ();
1233 CompositorOptions options(enableAPZ, enableSWWR);
1235 #ifdef XP_WIN
1236 if (supportsAcceleration) {
1237 options.SetAllowSoftwareWebRenderD3D11(
1238 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1240 #elif defined(MOZ_WIDGET_ANDROID)
1241 MOZ_ASSERT(supportsAcceleration);
1242 options.SetAllowSoftwareWebRenderOGL(
1243 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1244 #elif defined(MOZ_WIDGET_GTK)
1245 if (supportsAcceleration) {
1246 options.SetAllowSoftwareWebRenderOGL(
1247 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1249 #endif
1251 options.SetUseWebGPU(StaticPrefs::dom_webgpu_enabled());
1253 #ifdef MOZ_WIDGET_ANDROID
1254 if (!GetNativeData(NS_JAVA_SURFACE)) {
1255 options.SetInitiallyPaused(true);
1257 #else
1258 options.SetInitiallyPaused(CompositorInitiallyPaused());
1259 #endif
1261 RefPtr<WebRenderLayerManager> lm = new WebRenderLayerManager(this);
1263 bool retry = false;
1264 mCompositorSession = gpu->CreateTopLevelCompositor(
1265 this, lm, GetDefaultScale(), options, UseExternalCompositingSurface(),
1266 gfx::IntSize(aWidth, aHeight), &retry);
1268 if (mCompositorSession) {
1269 TextureFactoryIdentifier textureFactoryIdentifier;
1270 nsCString error;
1271 lm->Initialize(mCompositorSession->GetCompositorBridgeChild(),
1272 wr::AsPipelineId(mCompositorSession->RootLayerTreeId()),
1273 &textureFactoryIdentifier, error);
1274 if (textureFactoryIdentifier.mParentBackend != LayersBackend::LAYERS_WR) {
1275 retry = true;
1276 DestroyCompositor();
1277 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1278 gfx::GPUProcessManager::Get()->DisableWebRender(
1279 wr::WebRenderError::INITIALIZE, error);
1283 // We need to retry in a loop because the act of failing to create the
1284 // compositor can change our state (e.g. disable WebRender).
1285 if (mCompositorSession || !retry) {
1286 *aOptionsOut = options;
1287 return lm.forget();
1289 } while (true);
1292 void nsBaseWidget::CreateCompositor(int aWidth, int aHeight) {
1293 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1294 gfxPlatform::GetPlatform();
1296 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1297 "This function assumes OMTC");
1299 MOZ_ASSERT(!mCompositorSession && !mCompositorBridgeChild,
1300 "Should have properly cleaned up the previous PCompositor pair "
1301 "beforehand");
1303 if (mCompositorBridgeChild) {
1304 mCompositorBridgeChild->Destroy();
1307 // Recreating this is tricky, as we may still have an old and we need
1308 // to make sure it's properly destroyed by calling DestroyCompositor!
1310 // If we've already received a shutdown notification, don't try
1311 // create a new compositor.
1312 if (!mShutdownObserver) {
1313 return;
1316 CompositorOptions options;
1317 RefPtr<WebRenderLayerManager> lm =
1318 CreateCompositorSession(aWidth, aHeight, &options);
1319 if (!lm) {
1320 return;
1323 MOZ_ASSERT(mCompositorSession);
1324 mCompositorBridgeChild = mCompositorSession->GetCompositorBridgeChild();
1325 SetCompositorWidgetDelegate(
1326 mCompositorSession->GetCompositorWidgetDelegate());
1328 if (options.UseAPZ()) {
1329 mAPZC = mCompositorSession->GetAPZCTreeManager();
1330 ConfigureAPZCTreeManager();
1331 } else {
1332 mAPZC = nullptr;
1335 if (mInitialZoomConstraints) {
1336 UpdateZoomConstraints(mInitialZoomConstraints->mPresShellID,
1337 mInitialZoomConstraints->mViewID,
1338 Some(mInitialZoomConstraints->mConstraints));
1339 mInitialZoomConstraints.reset();
1342 TextureFactoryIdentifier textureFactoryIdentifier =
1343 lm->GetTextureFactoryIdentifier();
1344 MOZ_ASSERT(textureFactoryIdentifier.mParentBackend ==
1345 LayersBackend::LAYERS_WR);
1346 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1347 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1349 WindowUsesOMTC();
1351 mWindowRenderer = std::move(lm);
1353 // Only track compositors for top-level windows, since other window types
1354 // may use the basic compositor. Except on the OS X - see bug 1306383
1355 #if defined(XP_MACOSX)
1356 bool getCompositorFromThisWindow = true;
1357 #else
1358 bool getCompositorFromThisWindow = (mWindowType == eWindowType_toplevel);
1359 #endif
1361 if (getCompositorFromThisWindow) {
1362 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1363 mWindowRenderer->GetCompositorBackendType());
1367 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession* aSession) {
1368 MOZ_ASSERT(aSession == mCompositorSession);
1369 DestroyLayerManager();
1372 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1373 return gfxPlatform::UsesOffMainThreadCompositing();
1376 WindowRenderer* nsBaseWidget::GetWindowRenderer() {
1377 if (!mWindowRenderer) {
1378 if (!mShutdownObserver) {
1379 // We are shutting down, do not try to re-create a LayerManager
1380 return nullptr;
1382 // Try to use an async compositor first, if possible
1383 if (ShouldUseOffMainThreadCompositing()) {
1384 CreateCompositor();
1387 if (!mWindowRenderer) {
1388 mWindowRenderer = CreateFallbackRenderer();
1391 return mWindowRenderer;
1394 WindowRenderer* nsBaseWidget::CreateFallbackRenderer() {
1395 return new FallbackRenderer;
1398 CompositorBridgeChild* nsBaseWidget::GetRemoteRenderer() {
1399 return mCompositorBridgeChild;
1402 void nsBaseWidget::ClearCachedWebrenderResources() {
1403 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
1404 return;
1406 mWindowRenderer->AsWebRender()->ClearCachedResources();
1409 already_AddRefed<gfx::DrawTarget> nsBaseWidget::StartRemoteDrawing() {
1410 return nullptr;
1413 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA; }
1415 //-------------------------------------------------------------------------
1417 // Destroy the window
1419 //-------------------------------------------------------------------------
1420 void nsBaseWidget::OnDestroy() {
1421 if (mTextEventDispatcher) {
1422 mTextEventDispatcher->OnDestroyWidget();
1423 // Don't release it until this widget actually released because after this
1424 // is called, TextEventDispatcher() may create it again.
1427 // If this widget is being destroyed, let the APZ code know to drop references
1428 // to this widget. Callers of this function all should be holding a deathgrip
1429 // on this widget already.
1430 ReleaseContentController();
1433 void nsBaseWidget::MoveClient(const DesktopPoint& aOffset) {
1434 LayoutDeviceIntPoint clientOffset(GetClientOffset());
1436 // GetClientOffset returns device pixels; scale back to desktop pixels
1437 // if that's what this widget uses for the Move/Resize APIs
1438 if (BoundsUseDesktopPixels()) {
1439 DesktopPoint desktopOffset = clientOffset / GetDesktopToDeviceScale();
1440 Move(aOffset.x - desktopOffset.x, aOffset.y - desktopOffset.y);
1441 } else {
1442 LayoutDevicePoint layoutOffset = aOffset * GetDesktopToDeviceScale();
1443 Move(layoutOffset.x - clientOffset.x, layoutOffset.y - clientOffset.y);
1447 void nsBaseWidget::ResizeClient(const DesktopSize& aSize, bool aRepaint) {
1448 NS_ASSERTION((aSize.width >= 0), "Negative width passed to ResizeClient");
1449 NS_ASSERTION((aSize.height >= 0), "Negative height passed to ResizeClient");
1451 LayoutDeviceIntRect clientBounds = GetClientBounds();
1453 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1454 // if that's what this widget uses for the Move/Resize APIs
1455 if (BoundsUseDesktopPixels()) {
1456 DesktopSize desktopDelta =
1457 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1458 clientBounds.Size()) /
1459 GetDesktopToDeviceScale();
1460 Resize(aSize.width + desktopDelta.width, aSize.height + desktopDelta.height,
1461 aRepaint);
1462 } else {
1463 LayoutDeviceSize layoutSize = aSize * GetDesktopToDeviceScale();
1464 Resize(mBounds.Width() + (layoutSize.width - clientBounds.Width()),
1465 mBounds.Height() + (layoutSize.height - clientBounds.Height()),
1466 aRepaint);
1470 void nsBaseWidget::ResizeClient(const DesktopRect& aRect, bool aRepaint) {
1471 NS_ASSERTION((aRect.Width() >= 0), "Negative width passed to ResizeClient");
1472 NS_ASSERTION((aRect.Height() >= 0), "Negative height passed to ResizeClient");
1474 LayoutDeviceIntRect clientBounds = GetClientBounds();
1475 LayoutDeviceIntPoint clientOffset = GetClientOffset();
1476 DesktopToLayoutDeviceScale scale = GetDesktopToDeviceScale();
1478 if (BoundsUseDesktopPixels()) {
1479 DesktopPoint desktopOffset = clientOffset / scale;
1480 DesktopSize desktopDelta =
1481 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1482 clientBounds.Size()) /
1483 scale;
1484 Resize(aRect.X() - desktopOffset.x, aRect.Y() - desktopOffset.y,
1485 aRect.Width() + desktopDelta.width,
1486 aRect.Height() + desktopDelta.height, aRepaint);
1487 } else {
1488 LayoutDeviceRect layoutRect = aRect * scale;
1489 Resize(layoutRect.X() - clientOffset.x, layoutRect.Y() - clientOffset.y,
1490 layoutRect.Width() + mBounds.Width() - clientBounds.Width(),
1491 layoutRect.Height() + mBounds.Height() - clientBounds.Height(),
1492 aRepaint);
1496 //-------------------------------------------------------------------------
1498 // Bounds
1500 //-------------------------------------------------------------------------
1503 * If the implementation of nsWindow supports borders this method MUST be
1504 * overridden
1507 LayoutDeviceIntRect nsBaseWidget::GetClientBounds() { return GetBounds(); }
1510 * If the implementation of nsWindow supports borders this method MUST be
1511 * overridden
1514 LayoutDeviceIntRect nsBaseWidget::GetBounds() { return mBounds; }
1517 * If the implementation of nsWindow uses a local coordinate system within the
1518 *window, this method must be overridden
1521 LayoutDeviceIntRect nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1523 nsresult nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect& aRect) {
1524 if (SizeMode() != nsSizeMode_Normal) {
1525 return NS_ERROR_FAILURE;
1527 aRect = GetScreenBounds();
1528 return NS_OK;
1531 LayoutDeviceIntPoint nsBaseWidget::GetClientOffset() {
1532 return LayoutDeviceIntPoint(0, 0);
1535 nsresult nsBaseWidget::SetNonClientMargins(LayoutDeviceIntMargin& margins) {
1536 return NS_ERROR_NOT_IMPLEMENTED;
1539 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1541 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1543 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect* aResizerRect) {
1544 return false;
1548 * Modifies aFile to point at an icon file with the given name and suffix. The
1549 * suffix may correspond to a file extension with leading '.' if appropriate.
1550 * Returns true if the icon file exists and can be read.
1552 static bool ResolveIconNameHelper(nsIFile* aFile, const nsAString& aIconName,
1553 const nsAString& aIconSuffix) {
1554 aFile->Append(u"icons"_ns);
1555 aFile->Append(u"default"_ns);
1556 aFile->Append(aIconName + aIconSuffix);
1558 bool readable;
1559 return NS_SUCCEEDED(aFile->IsReadable(&readable)) && readable;
1563 * Resolve the given icon name into a local file object. This method is
1564 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1565 * platform specific icon file suffix (e.g., ".ico" under Win32).
1567 * If no file is found matching the given parameters, then null is returned.
1569 void nsBaseWidget::ResolveIconName(const nsAString& aIconName,
1570 const nsAString& aIconSuffix,
1571 nsIFile** aResult) {
1572 *aResult = nullptr;
1574 nsCOMPtr<nsIProperties> dirSvc =
1575 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
1576 if (!dirSvc) return;
1578 // first check auxilary chrome directories
1580 nsCOMPtr<nsISimpleEnumerator> dirs;
1581 dirSvc->Get(NS_APP_CHROME_DIR_LIST, NS_GET_IID(nsISimpleEnumerator),
1582 getter_AddRefs(dirs));
1583 if (dirs) {
1584 bool hasMore;
1585 while (NS_SUCCEEDED(dirs->HasMoreElements(&hasMore)) && hasMore) {
1586 nsCOMPtr<nsISupports> element;
1587 dirs->GetNext(getter_AddRefs(element));
1588 if (!element) continue;
1589 nsCOMPtr<nsIFile> file = do_QueryInterface(element);
1590 if (!file) continue;
1591 if (ResolveIconNameHelper(file, aIconName, aIconSuffix)) {
1592 NS_ADDREF(*aResult = file);
1593 return;
1598 // then check the main app chrome directory
1600 nsCOMPtr<nsIFile> file;
1601 dirSvc->Get(NS_APP_CHROME_DIR, NS_GET_IID(nsIFile), getter_AddRefs(file));
1602 if (file && ResolveIconNameHelper(file, aIconName, aIconSuffix))
1603 NS_ADDREF(*aResult = file);
1606 void nsBaseWidget::SetSizeConstraints(const SizeConstraints& aConstraints) {
1607 mSizeConstraints = aConstraints;
1609 // Popups are constrained during layout, and we don't want to synchronously
1610 // paint from reflow, so bail out... This is not great, but it's no worse than
1611 // what we used to do.
1613 // The right fix here is probably making constraint changes go through the
1614 // view manager and such.
1615 if (mWindowType == eWindowType_popup) {
1616 return;
1619 // If the current size doesn't meet the new constraints, trigger a
1620 // resize to apply it. Note that, we don't want to invoke Resize if
1621 // the new constraints don't affect the current size, because Resize
1622 // implementation on some platforms may touch other geometry even if
1623 // the size don't need to change.
1624 LayoutDeviceIntSize curSize = mBounds.Size();
1625 LayoutDeviceIntSize clampedSize =
1626 Max(aConstraints.mMinSize, Min(aConstraints.mMaxSize, curSize));
1627 if (clampedSize != curSize) {
1628 gfx::Size size;
1629 if (BoundsUseDesktopPixels()) {
1630 DesktopSize desktopSize = clampedSize / GetDesktopToDeviceScale();
1631 size = desktopSize.ToUnknownSize();
1632 } else {
1633 size = gfx::Size(clampedSize.ToUnknownSize());
1635 Resize(size.width, size.height, true);
1639 const widget::SizeConstraints nsBaseWidget::GetSizeConstraints() {
1640 return mSizeConstraints;
1643 // static
1644 nsIRollupListener* nsBaseWidget::GetActiveRollupListener() {
1645 // If set, then this is likely an <html:select> dropdown.
1646 if (gRollupListener) return gRollupListener;
1648 return nsXULPopupManager::GetInstance();
1651 void nsBaseWidget::NotifyWindowDestroyed() {
1652 if (!mWidgetListener) return;
1654 nsCOMPtr<nsIAppWindow> window = mWidgetListener->GetAppWindow();
1655 nsCOMPtr<nsIBaseWindow> appWindow(do_QueryInterface(window));
1656 if (appWindow) {
1657 appWindow->Destroy();
1661 void nsBaseWidget::NotifyWindowMoved(int32_t aX, int32_t aY) {
1662 if (mWidgetListener) {
1663 mWidgetListener->WindowMoved(this, aX, aY);
1666 if (mIMEHasFocus && IMENotificationRequestsRef().WantPositionChanged()) {
1667 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE));
1671 void nsBaseWidget::NotifySizeMoveDone() {
1672 if (!mWidgetListener) {
1673 return;
1675 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1676 presShell->WindowSizeMoveDone();
1680 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind) {
1681 if (!mWidgetListener) {
1682 return;
1684 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1685 presShell->ThemeChanged(aKind);
1689 void nsBaseWidget::NotifyUIStateChanged(UIStateChangeType aShowFocusRings) {
1690 if (Document* doc = GetDocument()) {
1691 if (nsPIDOMWindowOuter* win = doc->GetWindow()) {
1692 win->SetKeyboardIndicators(aShowFocusRings);
1697 nsresult nsBaseWidget::NotifyIME(const IMENotification& aIMENotification) {
1698 if (mIMEHasQuit) {
1699 return NS_OK;
1701 switch (aIMENotification.mMessage) {
1702 case REQUEST_TO_COMMIT_COMPOSITION:
1703 case REQUEST_TO_CANCEL_COMPOSITION:
1704 // We should send request to IME only when there is a TextEventDispatcher
1705 // instance (this means that this widget has dispatched at least one
1706 // composition event or keyboard event) and the it has composition.
1707 // Otherwise, there is nothing to do.
1708 // Note that if current input transaction is for native input events,
1709 // TextEventDispatcher::NotifyIME() will call
1710 // TextEventDispatcherListener::NotifyIME().
1711 if (mTextEventDispatcher && mTextEventDispatcher->IsComposing()) {
1712 return mTextEventDispatcher->NotifyIME(aIMENotification);
1714 return NS_OK;
1715 default: {
1716 if (aIMENotification.mMessage == NOTIFY_IME_OF_FOCUS) {
1717 mIMEHasFocus = true;
1719 EnsureTextEventDispatcher();
1720 // TextEventDispatcher::NotifyIME() will always call
1721 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1722 // input transaction is for synthesized events for automated tests,
1723 // notifications will be sent to native IME.
1724 nsresult rv = mTextEventDispatcher->NotifyIME(aIMENotification);
1725 if (aIMENotification.mMessage == NOTIFY_IME_OF_BLUR) {
1726 mIMEHasFocus = false;
1728 return rv;
1733 void nsBaseWidget::EnsureTextEventDispatcher() {
1734 if (mTextEventDispatcher) {
1735 return;
1737 mTextEventDispatcher = new TextEventDispatcher(this);
1740 nsIWidget::NativeIMEContext nsBaseWidget::GetNativeIMEContext() {
1741 if (mTextEventDispatcher && mTextEventDispatcher->GetPseudoIMEContext()) {
1742 // If we already have a TextEventDispatcher and it's working with
1743 // a TextInputProcessor, we need to return pseudo IME context since
1744 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1745 // on the pseudo IME context in such case.
1746 NativeIMEContext pseudoIMEContext;
1747 pseudoIMEContext.InitWithRawNativeIMEContext(
1748 mTextEventDispatcher->GetPseudoIMEContext());
1749 return pseudoIMEContext;
1751 return NativeIMEContext(this);
1754 nsIWidget::TextEventDispatcher* nsBaseWidget::GetTextEventDispatcher() {
1755 EnsureTextEventDispatcher();
1756 return mTextEventDispatcher;
1759 void* nsBaseWidget::GetPseudoIMEContext() {
1760 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
1761 if (!dispatcher) {
1762 return nullptr;
1764 return dispatcher->GetPseudoIMEContext();
1767 TextEventDispatcherListener*
1768 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1769 // TODO: If all platforms supported use of TextEventDispatcher for handling
1770 // native IME and keyboard events, this method should be removed since
1771 // in such case, this is overridden by all the subclasses.
1772 return nullptr;
1775 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId,
1776 const ScrollableLayerGuid::ViewID& aViewId,
1777 const CSSRect& aRect, const uint32_t& aFlags) {
1778 if (!mCompositorSession || !mAPZC) {
1779 return;
1781 LayersId layerId = mCompositorSession->RootLayerTreeId();
1782 APZThreadUtils::RunOnControllerThread(
1783 NewRunnableMethod<ScrollableLayerGuid, ZoomTarget, uint32_t>(
1784 "layers::IAPZCTreeManager::ZoomToRect", mAPZC,
1785 &IAPZCTreeManager::ZoomToRect,
1786 ScrollableLayerGuid(layerId, aPresShellId, aViewId),
1787 ZoomTarget{aRect}, aFlags));
1790 #ifdef ACCESSIBILITY
1792 a11y::LocalAccessible* nsBaseWidget::GetRootAccessible() {
1793 NS_ENSURE_TRUE(mWidgetListener, nullptr);
1795 PresShell* presShell = mWidgetListener->GetPresShell();
1796 NS_ENSURE_TRUE(presShell, nullptr);
1798 // If container is null then the presshell is not active. This often happens
1799 // when a preshell is being held onto for fastback.
1800 nsPresContext* presContext = presShell->GetPresContext();
1801 NS_ENSURE_TRUE(presContext->GetContainerWeak(), nullptr);
1803 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1804 // make sure it's not created at unsafe times.
1805 nsAccessibilityService* accService = GetOrCreateAccService();
1806 if (accService) {
1807 return accService->GetRootDocumentAccessible(
1808 presShell, nsContentUtils::IsSafeToRunScript());
1811 return nullptr;
1814 #endif // ACCESSIBILITY
1816 void nsBaseWidget::StartAsyncScrollbarDrag(
1817 const AsyncDragMetrics& aDragMetrics) {
1818 if (!AsyncPanZoomEnabled()) {
1819 return;
1822 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession);
1824 LayersId layersId = mCompositorSession->RootLayerTreeId();
1825 ScrollableLayerGuid guid(layersId, aDragMetrics.mPresShellId,
1826 aDragMetrics.mViewId);
1828 APZThreadUtils::RunOnControllerThread(
1829 NewRunnableMethod<ScrollableLayerGuid, AsyncDragMetrics>(
1830 "layers::IAPZCTreeManager::StartScrollbarDrag", mAPZC,
1831 &IAPZCTreeManager::StartScrollbarDrag, guid, aDragMetrics));
1834 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
1835 const ScrollableLayerGuid& aGuid) {
1836 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1838 return mAPZC->StartAutoscroll(aGuid, aAnchorLocation);
1841 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid& aGuid) {
1842 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1844 mAPZC->StopAutoscroll(aGuid);
1847 LayersId nsBaseWidget::GetRootLayerTreeId() {
1848 return mCompositorSession ? mCompositorSession->RootLayerTreeId()
1849 : LayersId{0};
1852 already_AddRefed<nsIScreen> nsBaseWidget::GetWidgetScreen() {
1853 nsCOMPtr<nsIScreenManager> screenManager;
1854 screenManager = do_GetService("@mozilla.org/gfx/screenmanager;1");
1855 if (!screenManager) {
1856 return nullptr;
1859 LayoutDeviceIntRect bounds = GetScreenBounds();
1860 DesktopIntRect deskBounds = RoundedToInt(bounds / GetDesktopToDeviceScale());
1861 nsCOMPtr<nsIScreen> screen;
1862 screenManager->ScreenForRect(deskBounds.X(), deskBounds.Y(),
1863 deskBounds.Width(), deskBounds.Height(),
1864 getter_AddRefs(screen));
1865 return screen.forget();
1868 mozilla::DesktopToLayoutDeviceScale
1869 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
1870 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
1871 ->GetDesktopToDeviceScale();
1874 nsresult nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint,
1875 bool aLongTap,
1876 nsIObserver* aObserver) {
1877 AutoObserverNotifier notifier(aObserver, "touchtap");
1879 if (sPointerIdCounter > TOUCH_INJECT_MAX_POINTS) {
1880 sPointerIdCounter = 0;
1882 int pointerId = sPointerIdCounter;
1883 sPointerIdCounter++;
1884 nsresult rv = SynthesizeNativeTouchPoint(pointerId, TOUCH_CONTACT, aPoint,
1885 1.0, 90, nullptr);
1886 if (NS_FAILED(rv)) {
1887 return rv;
1890 if (!aLongTap) {
1891 return SynthesizeNativeTouchPoint(pointerId, TOUCH_REMOVE, aPoint, 0, 0,
1892 nullptr);
1895 // initiate a long tap
1896 int elapse = Preferences::GetInt("ui.click_hold_context_menus.delay",
1897 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC);
1898 if (!mLongTapTimer) {
1899 mLongTapTimer = NS_NewTimer();
1900 if (!mLongTapTimer) {
1901 SynthesizeNativeTouchPoint(pointerId, TOUCH_CANCEL, aPoint, 0, 0,
1902 nullptr);
1903 return NS_ERROR_UNEXPECTED;
1905 // Windows requires recuring events, so we set this to a smaller window
1906 // than the pref value.
1907 int timeout = elapse;
1908 if (timeout > TOUCH_INJECT_PUMP_TIMER_MSEC) {
1909 timeout = TOUCH_INJECT_PUMP_TIMER_MSEC;
1911 mLongTapTimer->InitWithNamedFuncCallback(
1912 OnLongTapTimerCallback, this, timeout, nsITimer::TYPE_REPEATING_SLACK,
1913 "nsIWidget::SynthesizeNativeTouchTap");
1916 // If we already have a long tap pending, cancel it. We only allow one long
1917 // tap to be active at a time.
1918 if (mLongTapTouchPoint) {
1919 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1920 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1923 mLongTapTouchPoint = MakeUnique<LongTapInfo>(
1924 pointerId, aPoint, TimeDuration::FromMilliseconds(elapse), aObserver);
1925 notifier.SkipNotification(); // we'll do it in the long-tap callback
1926 return NS_OK;
1929 // static
1930 void nsIWidget::OnLongTapTimerCallback(nsITimer* aTimer, void* aClosure) {
1931 auto* self = static_cast<nsIWidget*>(aClosure);
1933 if ((self->mLongTapTouchPoint->mStamp + self->mLongTapTouchPoint->mDuration) >
1934 TimeStamp::Now()) {
1935 #ifdef XP_WIN
1936 // Windows needs us to keep pumping feedback to the digitizer, so update
1937 // the pointer id with the same position.
1938 self->SynthesizeNativeTouchPoint(
1939 self->mLongTapTouchPoint->mPointerId, TOUCH_CONTACT,
1940 self->mLongTapTouchPoint->mPosition, 1.0, 90, nullptr);
1941 #endif
1942 return;
1945 AutoObserverNotifier notifier(self->mLongTapTouchPoint->mObserver,
1946 "touchtap");
1948 // finished, remove the touch point
1949 self->mLongTapTimer->Cancel();
1950 self->mLongTapTimer = nullptr;
1951 self->SynthesizeNativeTouchPoint(
1952 self->mLongTapTouchPoint->mPointerId, TOUCH_REMOVE,
1953 self->mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1954 self->mLongTapTouchPoint = nullptr;
1957 nsresult nsIWidget::ClearNativeTouchSequence(nsIObserver* aObserver) {
1958 AutoObserverNotifier notifier(aObserver, "cleartouch");
1960 if (!mLongTapTimer) {
1961 return NS_OK;
1963 mLongTapTimer->Cancel();
1964 mLongTapTimer = nullptr;
1965 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1966 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1967 mLongTapTouchPoint = nullptr;
1968 return NS_OK;
1971 MultiTouchInput nsBaseWidget::UpdateSynthesizedTouchState(
1972 MultiTouchInput* aState, uint32_t aTime, mozilla::TimeStamp aTimeStamp,
1973 uint32_t aPointerId, TouchPointerState aPointerState,
1974 LayoutDeviceIntPoint aPoint, double aPointerPressure,
1975 uint32_t aPointerOrientation) {
1976 ScreenIntPoint pointerScreenPoint = ViewAs<ScreenPixel>(
1977 aPoint, PixelCastJustification::LayoutDeviceIsScreenForBounds);
1979 // We can't dispatch *aState directly because (a) dispatching
1980 // it might inadvertently modify it and (b) in the case of touchend or
1981 // touchcancel events aState will hold the touches that are
1982 // still down whereas the input dispatched needs to hold the removed
1983 // touch(es). We use |inputToDispatch| for this purpose.
1984 MultiTouchInput inputToDispatch;
1985 inputToDispatch.mInputType = MULTITOUCH_INPUT;
1986 inputToDispatch.mTime = aTime;
1987 inputToDispatch.mTimeStamp = aTimeStamp;
1989 int32_t index = aState->IndexOfTouch((int32_t)aPointerId);
1990 if (aPointerState == TOUCH_CONTACT) {
1991 if (index >= 0) {
1992 // found an existing touch point, update it
1993 SingleTouchData& point = aState->mTouches[index];
1994 point.mScreenPoint = pointerScreenPoint;
1995 point.mRotationAngle = (float)aPointerOrientation;
1996 point.mForce = (float)aPointerPressure;
1997 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_MOVE;
1998 } else {
1999 // new touch point, add it
2000 aState->mTouches.AppendElement(SingleTouchData(
2001 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2002 (float)aPointerOrientation, (float)aPointerPressure));
2003 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_START;
2005 inputToDispatch.mTouches = aState->mTouches;
2006 } else {
2007 MOZ_ASSERT(aPointerState == TOUCH_REMOVE || aPointerState == TOUCH_CANCEL);
2008 // a touch point is being lifted, so remove it from the stored list
2009 if (index >= 0) {
2010 aState->mTouches.RemoveElementAt(index);
2012 inputToDispatch.mType =
2013 (aPointerState == TOUCH_REMOVE ? MultiTouchInput::MULTITOUCH_END
2014 : MultiTouchInput::MULTITOUCH_CANCEL);
2015 inputToDispatch.mTouches.AppendElement(SingleTouchData(
2016 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2017 (float)aPointerOrientation, (float)aPointerPressure));
2020 return inputToDispatch;
2023 void nsBaseWidget::NotifyLiveResizeStarted() {
2024 // If we have mLiveResizeListeners already non-empty, we should notify those
2025 // listeners that the resize stopped before starting anew. In theory this
2026 // should never happen because we shouldn't get nested live resize actions.
2027 NotifyLiveResizeStopped();
2028 MOZ_ASSERT(mLiveResizeListeners.IsEmpty());
2030 // If we can get the active remote tab for the current widget, suppress
2031 // the displayport on it during the live resize.
2032 if (!mWidgetListener) {
2033 return;
2035 nsCOMPtr<nsIAppWindow> appWindow = mWidgetListener->GetAppWindow();
2036 if (!appWindow) {
2037 return;
2039 mLiveResizeListeners = appWindow->GetLiveResizeListeners();
2040 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2041 mLiveResizeListeners[i]->LiveResizeStarted();
2045 void nsBaseWidget::NotifyLiveResizeStopped() {
2046 if (!mLiveResizeListeners.IsEmpty()) {
2047 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2048 mLiveResizeListeners[i]->LiveResizeStopped();
2050 mLiveResizeListeners.Clear();
2054 nsresult nsBaseWidget::AsyncEnableDragDrop(bool aEnable) {
2055 RefPtr<nsBaseWidget> kungFuDeathGrip = this;
2056 return NS_DispatchToCurrentThreadQueue(
2057 NS_NewRunnableFunction(
2058 "AsyncEnableDragDropFn",
2059 [this, aEnable, kungFuDeathGrip]() { EnableDragDrop(aEnable); }),
2060 kAsyncDragDropTimeout, EventQueuePriority::Idle);
2063 const IMENotificationRequests& nsIWidget::IMENotificationRequestsRef() {
2064 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
2065 return dispatcher->IMENotificationRequestsRef();
2068 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent* aEvent) {}
2070 bool nsIWidget::GetEditCommands(nsIWidget::NativeKeyBindingsType aType,
2071 const WidgetKeyboardEvent& aEvent,
2072 nsTArray<CommandInt>& aCommands) {
2073 MOZ_ASSERT(aEvent.IsTrusted());
2074 MOZ_ASSERT(aCommands.IsEmpty());
2075 return true;
2078 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboard() {
2079 if (XRE_IsContentProcess()) {
2080 return CreateBidiKeyboardContentProcess();
2082 return CreateBidiKeyboardInner();
2085 #ifdef ANDROID
2086 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboardInner() {
2087 // no bidi keyboard implementation
2088 return nullptr;
2090 #endif
2092 namespace mozilla::widget {
2094 const char* ToChar(InputContext::Origin aOrigin) {
2095 switch (aOrigin) {
2096 case InputContext::ORIGIN_MAIN:
2097 return "ORIGIN_MAIN";
2098 case InputContext::ORIGIN_CONTENT:
2099 return "ORIGIN_CONTENT";
2100 default:
2101 return "Unexpected value";
2105 const char* ToChar(IMEMessage aIMEMessage) {
2106 switch (aIMEMessage) {
2107 case NOTIFY_IME_OF_NOTHING:
2108 return "NOTIFY_IME_OF_NOTHING";
2109 case NOTIFY_IME_OF_FOCUS:
2110 return "NOTIFY_IME_OF_FOCUS";
2111 case NOTIFY_IME_OF_BLUR:
2112 return "NOTIFY_IME_OF_BLUR";
2113 case NOTIFY_IME_OF_SELECTION_CHANGE:
2114 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2115 case NOTIFY_IME_OF_TEXT_CHANGE:
2116 return "NOTIFY_IME_OF_TEXT_CHANGE";
2117 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED:
2118 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2119 case NOTIFY_IME_OF_POSITION_CHANGE:
2120 return "NOTIFY_IME_OF_POSITION_CHANGE";
2121 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
2122 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2123 case REQUEST_TO_COMMIT_COMPOSITION:
2124 return "REQUEST_TO_COMMIT_COMPOSITION";
2125 case REQUEST_TO_CANCEL_COMPOSITION:
2126 return "REQUEST_TO_CANCEL_COMPOSITION";
2127 default:
2128 return "Unexpected value";
2132 void NativeIMEContext::Init(nsIWidget* aWidget) {
2133 if (!aWidget) {
2134 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2135 mOriginProcessID = static_cast<uint64_t>(-1);
2136 return;
2138 if (!XRE_IsContentProcess()) {
2139 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(
2140 aWidget->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT));
2141 mOriginProcessID = 0;
2142 return;
2144 // If this is created in a child process, aWidget is an instance of
2145 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2146 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2147 // native IME context of the parent process.
2148 *this = aWidget->GetNativeIMEContext();
2151 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext) {
2152 if (NS_WARN_IF(!aRawNativeIMEContext)) {
2153 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2154 mOriginProcessID = static_cast<uint64_t>(-1);
2155 return;
2157 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(aRawNativeIMEContext);
2158 mOriginProcessID =
2159 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2162 void IMENotification::TextChangeDataBase::MergeWith(
2163 const IMENotification::TextChangeDataBase& aOther) {
2164 MOZ_ASSERT(aOther.IsValid(), "Merging data must store valid data");
2165 MOZ_ASSERT(aOther.mStartOffset <= aOther.mRemovedEndOffset,
2166 "end of removed text must be same or larger than start");
2167 MOZ_ASSERT(aOther.mStartOffset <= aOther.mAddedEndOffset,
2168 "end of added text must be same or larger than start");
2170 if (!IsValid()) {
2171 *this = aOther;
2172 return;
2175 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2176 // text ranges. I.e., mStartOffset should be the smallest offset of all
2177 // modified text ranges in old text. |mRemovedEndOffset| should be the
2178 // largest end offset in old text of all modified text ranges.
2179 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2180 // I.e., only this is an offset in new text.
2181 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2182 // premodified text was already removed. And some text whose length is
2183 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2184 // this allows IME to mark dirty the modified text range with |mStartOffset|
2185 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2186 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2187 // Additionally, IME can retrieve only the text between |mStartOffset| and
2188 // |mAddedEndOffset| for updating stored text.
2190 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2191 // should be adjusted to be in same text. The |newData.mStartOffset| and
2192 // |newData.mRemovedEndOffset| should be computed as in old text because
2193 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2194 // in the old text but even if some text before the values of the newData
2195 // has already been modified, the values don't include the changes.
2197 // For comparing new and old |mAddedEndOffset| values, they should be
2198 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2199 // computed as in the new text because |mAddedEndOffset| indicates the end
2200 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2201 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2203 const TextChangeDataBase& newData = aOther;
2204 const TextChangeDataBase oldData = *this;
2206 // mCausedOnlyByComposition should be true only when all changes are caused
2207 // by composition.
2208 mCausedOnlyByComposition =
2209 newData.mCausedOnlyByComposition && oldData.mCausedOnlyByComposition;
2211 // mIncludingChangesWithoutComposition should be true if at least one of
2212 // merged changes occurred without composition.
2213 mIncludingChangesWithoutComposition =
2214 newData.mIncludingChangesWithoutComposition ||
2215 oldData.mIncludingChangesWithoutComposition;
2217 // mIncludingChangesDuringComposition should be true when at least one of
2218 // the merged non-composition changes occurred during the latest composition.
2219 if (!newData.mCausedOnlyByComposition &&
2220 !newData.mIncludingChangesDuringComposition) {
2221 MOZ_ASSERT(newData.mIncludingChangesWithoutComposition);
2222 MOZ_ASSERT(mIncludingChangesWithoutComposition);
2223 // If new change is neither caused by composition nor occurred during
2224 // composition, set mIncludingChangesDuringComposition to false because
2225 // IME doesn't want outdated text changes as text change during current
2226 // composition.
2227 mIncludingChangesDuringComposition = false;
2228 } else {
2229 // Otherwise, set mIncludingChangesDuringComposition to true if either
2230 // oldData or newData includes changes during composition.
2231 mIncludingChangesDuringComposition =
2232 newData.mIncludingChangesDuringComposition ||
2233 oldData.mIncludingChangesDuringComposition;
2236 if (newData.mStartOffset >= oldData.mAddedEndOffset) {
2237 // Case 1:
2238 // If new start is after old end offset of added text, it means that text
2239 // after the modified range is modified. Like:
2240 // added range of old change: +----------+
2241 // removed range of new change: +----------+
2242 // So, the old start offset is always the smaller offset.
2243 mStartOffset = oldData.mStartOffset;
2244 // The new end offset of removed text is moved by the old change and we
2245 // need to cancel the move of the old change for comparing the offsets in
2246 // same text because it doesn't make sensce to compare offsets in different
2247 // text.
2248 uint32_t newRemovedEndOffsetInOldText =
2249 newData.mRemovedEndOffset - oldData.Difference();
2250 mRemovedEndOffset =
2251 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2252 // The new end offset of added text is always the larger offset.
2253 mAddedEndOffset = newData.mAddedEndOffset;
2254 return;
2257 if (newData.mStartOffset >= oldData.mStartOffset) {
2258 // If new start is in the modified range, it means that new data changes
2259 // a part or all of the range.
2260 mStartOffset = oldData.mStartOffset;
2261 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2262 // Case 2:
2263 // If new end of removed text is greater than old end of added text, it
2264 // means that all or a part of modified range modified again and text
2265 // after the modified range is also modified. Like:
2266 // added range of old change: +----------+
2267 // removed range of new change: +----------+
2268 // So, the new removed end offset is moved by the old change and we need
2269 // to cancel the move of the old change for comparing the offsets in the
2270 // same text because it doesn't make sense to compare the offsets in
2271 // different text.
2272 uint32_t newRemovedEndOffsetInOldText =
2273 newData.mRemovedEndOffset - oldData.Difference();
2274 mRemovedEndOffset =
2275 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2276 // The old end of added text is replaced by new change. So, it should be
2277 // same as the new start. On the other hand, the new added end offset is
2278 // always same or larger. Therefore, the merged end offset of added
2279 // text should be the new end offset of added text.
2280 mAddedEndOffset = newData.mAddedEndOffset;
2281 return;
2284 // Case 3:
2285 // If new end of removed text is less than old end of added text, it means
2286 // that only a part of the modified range is modified again. Like:
2287 // added range of old change: +------------+
2288 // removed range of new change: +-----+
2289 // So, the new end offset of removed text should be same as the old end
2290 // offset of removed text. Therefore, the merged end offset of removed
2291 // text should be the old text change's |mRemovedEndOffset|.
2292 mRemovedEndOffset = oldData.mRemovedEndOffset;
2293 // The old end of added text is moved by new change. So, we need to cancel
2294 // the move of the new change for comparing the offsets in same text.
2295 uint32_t oldAddedEndOffsetInNewText =
2296 oldData.mAddedEndOffset + newData.Difference();
2297 mAddedEndOffset =
2298 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2299 return;
2302 if (newData.mRemovedEndOffset >= oldData.mStartOffset) {
2303 // If new end of removed text is greater than old start (and new start is
2304 // less than old start), it means that a part of modified range is modified
2305 // again and some new text before the modified range is also modified.
2306 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2307 "new start offset should be less than old one here");
2308 mStartOffset = newData.mStartOffset;
2309 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2310 // Case 4:
2311 // If new end of removed text is greater than old end of added text, it
2312 // means that all modified text and text after the modified range is
2313 // modified. Like:
2314 // added range of old change: +----------+
2315 // removed range of new change: +------------------+
2316 // So, the new end of removed text is moved by the old change. Therefore,
2317 // we need to cancel the move of the old change for comparing the offsets
2318 // in same text because it doesn't make sense to compare the offsets in
2319 // different text.
2320 uint32_t newRemovedEndOffsetInOldText =
2321 newData.mRemovedEndOffset - oldData.Difference();
2322 mRemovedEndOffset =
2323 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2324 // The old end of added text is replaced by new change. So, the old end
2325 // offset of added text is same as new text change's start offset. Then,
2326 // new change's end offset of added text is always same or larger than
2327 // it. Therefore, merged end offset of added text is always the new end
2328 // offset of added text.
2329 mAddedEndOffset = newData.mAddedEndOffset;
2330 return;
2333 // Case 5:
2334 // If new end of removed text is less than old end of added text, it
2335 // means that only a part of the modified range is modified again. Like:
2336 // added range of old change: +----------+
2337 // removed range of new change: +----------+
2338 // So, the new end of removed text should be same as old end of removed
2339 // text for preventing end of removed text to be modified. Therefore,
2340 // merged end offset of removed text is always the old end offset of removed
2341 // text.
2342 mRemovedEndOffset = oldData.mRemovedEndOffset;
2343 // The old end of added text is moved by this change. So, we need to
2344 // cancel the move of the new change for comparing the offsets in same text
2345 // because it doesn't make sense to compare the offsets in different text.
2346 uint32_t oldAddedEndOffsetInNewText =
2347 oldData.mAddedEndOffset + newData.Difference();
2348 mAddedEndOffset =
2349 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2350 return;
2353 // Case 6:
2354 // Otherwise, i.e., both new end of added text and new start are less than
2355 // old start, text before the modified range is modified. Like:
2356 // added range of old change: +----------+
2357 // removed range of new change: +----------+
2358 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2359 "new start offset should be less than old one here");
2360 mStartOffset = newData.mStartOffset;
2361 MOZ_ASSERT(newData.mRemovedEndOffset < oldData.mRemovedEndOffset,
2362 "new removed end offset should be less than old one here");
2363 mRemovedEndOffset = oldData.mRemovedEndOffset;
2364 // The end of added text should be adjusted with the new difference.
2365 uint32_t oldAddedEndOffsetInNewText =
2366 oldData.mAddedEndOffset + newData.Difference();
2367 mAddedEndOffset =
2368 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2371 #ifdef DEBUG
2373 // Let's test the code of merging multiple text change data in debug build
2374 // and crash if one of them fails because this feature is very complex but
2375 // cannot be tested with mochitest.
2376 void IMENotification::TextChangeDataBase::Test() {
2377 static bool gTestTextChangeEvent = true;
2378 if (!gTestTextChangeEvent) {
2379 return;
2381 gTestTextChangeEvent = false;
2383 /****************************************************************************
2384 * Case 1
2385 ****************************************************************************/
2387 // Appending text
2388 MergeWith(TextChangeData(10, 10, 20, false, false));
2389 MergeWith(TextChangeData(20, 20, 35, false, false));
2390 MOZ_ASSERT(mStartOffset == 10,
2391 "Test 1-1-1: mStartOffset should be the first offset");
2392 MOZ_ASSERT(
2393 mRemovedEndOffset == 10, // 20 - (20 - 10)
2394 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2395 MOZ_ASSERT(
2396 mAddedEndOffset == 35,
2397 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2398 Clear();
2400 // Removing text (longer line -> shorter line)
2401 MergeWith(TextChangeData(10, 20, 10, false, false));
2402 MergeWith(TextChangeData(10, 30, 10, false, false));
2403 MOZ_ASSERT(mStartOffset == 10,
2404 "Test 1-2-1: mStartOffset should be the first offset");
2405 MOZ_ASSERT(mRemovedEndOffset == 40, // 30 + (10 - 20)
2406 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2407 "removed text "
2408 "with already removed length");
2409 MOZ_ASSERT(
2410 mAddedEndOffset == 10,
2411 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2412 Clear();
2414 // Removing text (shorter line -> longer line)
2415 MergeWith(TextChangeData(10, 20, 10, false, false));
2416 MergeWith(TextChangeData(10, 15, 10, false, false));
2417 MOZ_ASSERT(mStartOffset == 10,
2418 "Test 1-3-1: mStartOffset should be the first offset");
2419 MOZ_ASSERT(mRemovedEndOffset == 25, // 15 + (10 - 20)
2420 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2421 "removed text "
2422 "with already removed length");
2423 MOZ_ASSERT(
2424 mAddedEndOffset == 10,
2425 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2426 Clear();
2428 // Appending text at different point (not sure if actually occurs)
2429 MergeWith(TextChangeData(10, 10, 20, false, false));
2430 MergeWith(TextChangeData(55, 55, 60, false, false));
2431 MOZ_ASSERT(mStartOffset == 10,
2432 "Test 1-4-1: mStartOffset should be the smallest offset");
2433 MOZ_ASSERT(
2434 mRemovedEndOffset == 45, // 55 - (10 - 20)
2435 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2436 "text without already added length");
2437 MOZ_ASSERT(
2438 mAddedEndOffset == 60,
2439 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2440 Clear();
2442 // Removing text at different point (not sure if actually occurs)
2443 MergeWith(TextChangeData(10, 20, 10, false, false));
2444 MergeWith(TextChangeData(55, 68, 55, false, false));
2445 MOZ_ASSERT(mStartOffset == 10,
2446 "Test 1-5-1: mStartOffset should be the smallest offset");
2447 MOZ_ASSERT(
2448 mRemovedEndOffset == 78, // 68 - (10 - 20)
2449 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2450 "text with already removed length");
2451 MOZ_ASSERT(
2452 mAddedEndOffset == 55,
2453 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2454 Clear();
2456 // Replacing text and append text (becomes longer)
2457 MergeWith(TextChangeData(30, 35, 32, false, false));
2458 MergeWith(TextChangeData(32, 32, 40, false, false));
2459 MOZ_ASSERT(mStartOffset == 30,
2460 "Test 1-6-1: mStartOffset should be the smallest offset");
2461 MOZ_ASSERT(
2462 mRemovedEndOffset == 35, // 32 - (32 - 35)
2463 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2464 "text");
2465 MOZ_ASSERT(
2466 mAddedEndOffset == 40,
2467 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2468 Clear();
2470 // Replacing text and append text (becomes shorter)
2471 MergeWith(TextChangeData(30, 35, 32, false, false));
2472 MergeWith(TextChangeData(32, 32, 33, false, false));
2473 MOZ_ASSERT(mStartOffset == 30,
2474 "Test 1-7-1: mStartOffset should be the smallest offset");
2475 MOZ_ASSERT(
2476 mRemovedEndOffset == 35, // 32 - (32 - 35)
2477 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2478 "text");
2479 MOZ_ASSERT(
2480 mAddedEndOffset == 33,
2481 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2482 Clear();
2484 // Removing text and replacing text after first range (not sure if actually
2485 // occurs)
2486 MergeWith(TextChangeData(30, 35, 30, false, false));
2487 MergeWith(TextChangeData(32, 34, 48, false, false));
2488 MOZ_ASSERT(mStartOffset == 30,
2489 "Test 1-8-1: mStartOffset should be the smallest offset");
2490 MOZ_ASSERT(mRemovedEndOffset == 39, // 34 - (30 - 35)
2491 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2492 "removed text "
2493 "without already removed text");
2494 MOZ_ASSERT(
2495 mAddedEndOffset == 48,
2496 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2497 Clear();
2499 // Removing text and replacing text after first range (not sure if actually
2500 // occurs)
2501 MergeWith(TextChangeData(30, 35, 30, false, false));
2502 MergeWith(TextChangeData(32, 38, 36, false, false));
2503 MOZ_ASSERT(mStartOffset == 30,
2504 "Test 1-9-1: mStartOffset should be the smallest offset");
2505 MOZ_ASSERT(mRemovedEndOffset == 43, // 38 - (30 - 35)
2506 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2507 "removed text "
2508 "without already removed text");
2509 MOZ_ASSERT(
2510 mAddedEndOffset == 36,
2511 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2512 Clear();
2514 /****************************************************************************
2515 * Case 2
2516 ****************************************************************************/
2518 // Replacing text in around end of added text (becomes shorter) (not sure
2519 // if actually occurs)
2520 MergeWith(TextChangeData(50, 50, 55, false, false));
2521 MergeWith(TextChangeData(53, 60, 54, false, false));
2522 MOZ_ASSERT(mStartOffset == 50,
2523 "Test 2-1-1: mStartOffset should be the smallest offset");
2524 MOZ_ASSERT(mRemovedEndOffset == 55, // 60 - (55 - 50)
2525 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2526 "removed text "
2527 "without already added text length");
2528 MOZ_ASSERT(
2529 mAddedEndOffset == 54,
2530 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2531 Clear();
2533 // Replacing text around end of added text (becomes longer) (not sure
2534 // if actually occurs)
2535 MergeWith(TextChangeData(50, 50, 55, false, false));
2536 MergeWith(TextChangeData(54, 62, 68, false, false));
2537 MOZ_ASSERT(mStartOffset == 50,
2538 "Test 2-2-1: mStartOffset should be the smallest offset");
2539 MOZ_ASSERT(mRemovedEndOffset == 57, // 62 - (55 - 50)
2540 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2541 "removed text "
2542 "without already added text length");
2543 MOZ_ASSERT(
2544 mAddedEndOffset == 68,
2545 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2546 Clear();
2548 // Replacing text around end of replaced text (became shorter) (not sure if
2549 // actually occurs)
2550 MergeWith(TextChangeData(36, 48, 45, false, false));
2551 MergeWith(TextChangeData(43, 50, 49, false, false));
2552 MOZ_ASSERT(mStartOffset == 36,
2553 "Test 2-3-1: mStartOffset should be the smallest offset");
2554 MOZ_ASSERT(mRemovedEndOffset == 53, // 50 - (45 - 48)
2555 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2556 "removed text "
2557 "without already removed text length");
2558 MOZ_ASSERT(
2559 mAddedEndOffset == 49,
2560 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2561 Clear();
2563 // Replacing text around end of replaced text (became longer) (not sure if
2564 // actually occurs)
2565 MergeWith(TextChangeData(36, 52, 53, false, false));
2566 MergeWith(TextChangeData(43, 68, 61, false, false));
2567 MOZ_ASSERT(mStartOffset == 36,
2568 "Test 2-4-1: mStartOffset should be the smallest offset");
2569 MOZ_ASSERT(mRemovedEndOffset == 67, // 68 - (53 - 52)
2570 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2571 "removed text "
2572 "without already added text length");
2573 MOZ_ASSERT(
2574 mAddedEndOffset == 61,
2575 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2576 Clear();
2578 /****************************************************************************
2579 * Case 3
2580 ****************************************************************************/
2582 // Appending text in already added text (not sure if actually occurs)
2583 MergeWith(TextChangeData(10, 10, 20, false, false));
2584 MergeWith(TextChangeData(15, 15, 30, false, false));
2585 MOZ_ASSERT(mStartOffset == 10,
2586 "Test 3-1-1: mStartOffset should be the smallest offset");
2587 MOZ_ASSERT(mRemovedEndOffset == 10,
2588 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2589 "removed text");
2590 MOZ_ASSERT(
2591 mAddedEndOffset == 35, // 20 + (30 - 15)
2592 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2593 "added text length by the new change");
2594 Clear();
2596 // Replacing text in added text (not sure if actually occurs)
2597 MergeWith(TextChangeData(50, 50, 55, false, false));
2598 MergeWith(TextChangeData(52, 53, 56, false, false));
2599 MOZ_ASSERT(mStartOffset == 50,
2600 "Test 3-2-1: mStartOffset should be the smallest offset");
2601 MOZ_ASSERT(mRemovedEndOffset == 50,
2602 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2603 "removed text");
2604 MOZ_ASSERT(
2605 mAddedEndOffset == 58, // 55 + (56 - 53)
2606 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2607 "added text length by the new change");
2608 Clear();
2610 // Replacing text in replaced text (became shorter) (not sure if actually
2611 // occurs)
2612 MergeWith(TextChangeData(36, 48, 45, false, false));
2613 MergeWith(TextChangeData(37, 38, 50, false, false));
2614 MOZ_ASSERT(mStartOffset == 36,
2615 "Test 3-3-1: mStartOffset should be the smallest offset");
2616 MOZ_ASSERT(mRemovedEndOffset == 48,
2617 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2618 "removed text");
2619 MOZ_ASSERT(
2620 mAddedEndOffset == 57, // 45 + (50 - 38)
2621 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2622 "added text length by the new change");
2623 Clear();
2625 // Replacing text in replaced text (became longer) (not sure if actually
2626 // occurs)
2627 MergeWith(TextChangeData(32, 48, 53, false, false));
2628 MergeWith(TextChangeData(43, 50, 52, false, false));
2629 MOZ_ASSERT(mStartOffset == 32,
2630 "Test 3-4-1: mStartOffset should be the smallest offset");
2631 MOZ_ASSERT(mRemovedEndOffset == 48,
2632 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2633 "removed text "
2634 "without already added text length");
2635 MOZ_ASSERT(
2636 mAddedEndOffset == 55, // 53 + (52 - 50)
2637 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2638 "added text length by the new change");
2639 Clear();
2641 // Replacing text in replaced text (became shorter) (not sure if actually
2642 // occurs)
2643 MergeWith(TextChangeData(36, 48, 50, false, false));
2644 MergeWith(TextChangeData(37, 49, 47, false, false));
2645 MOZ_ASSERT(mStartOffset == 36,
2646 "Test 3-5-1: mStartOffset should be the smallest offset");
2647 MOZ_ASSERT(
2648 mRemovedEndOffset == 48,
2649 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
2650 "text");
2651 MOZ_ASSERT(mAddedEndOffset == 48, // 50 + (47 - 49)
2652 "Test 3-5-3: mAddedEndOffset should be the first end of added "
2653 "text without "
2654 "removed text length by the new change");
2655 Clear();
2657 // Replacing text in replaced text (became longer) (not sure if actually
2658 // occurs)
2659 MergeWith(TextChangeData(32, 48, 53, false, false));
2660 MergeWith(TextChangeData(43, 50, 47, false, false));
2661 MOZ_ASSERT(mStartOffset == 32,
2662 "Test 3-6-1: mStartOffset should be the smallest offset");
2663 MOZ_ASSERT(mRemovedEndOffset == 48,
2664 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
2665 "removed text "
2666 "without already added text length");
2667 MOZ_ASSERT(mAddedEndOffset == 50, // 53 + (47 - 50)
2668 "Test 3-6-3: mAddedEndOffset should be the first end of added "
2669 "text without "
2670 "removed text length by the new change");
2671 Clear();
2673 /****************************************************************************
2674 * Case 4
2675 ****************************************************************************/
2677 // Replacing text all of already append text (not sure if actually occurs)
2678 MergeWith(TextChangeData(50, 50, 55, false, false));
2679 MergeWith(TextChangeData(44, 66, 68, false, false));
2680 MOZ_ASSERT(mStartOffset == 44,
2681 "Test 4-1-1: mStartOffset should be the smallest offset");
2682 MOZ_ASSERT(mRemovedEndOffset == 61, // 66 - (55 - 50)
2683 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
2684 "removed text "
2685 "without already added text length");
2686 MOZ_ASSERT(
2687 mAddedEndOffset == 68,
2688 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
2689 Clear();
2691 // Replacing text around a point in which text was removed (not sure if
2692 // actually occurs)
2693 MergeWith(TextChangeData(50, 62, 50, false, false));
2694 MergeWith(TextChangeData(44, 66, 68, false, false));
2695 MOZ_ASSERT(mStartOffset == 44,
2696 "Test 4-2-1: mStartOffset should be the smallest offset");
2697 MOZ_ASSERT(mRemovedEndOffset == 78, // 66 - (50 - 62)
2698 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
2699 "removed text "
2700 "without already removed text length");
2701 MOZ_ASSERT(
2702 mAddedEndOffset == 68,
2703 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
2704 Clear();
2706 // Replacing text all replaced text (became shorter) (not sure if actually
2707 // occurs)
2708 MergeWith(TextChangeData(50, 62, 60, false, false));
2709 MergeWith(TextChangeData(49, 128, 130, false, false));
2710 MOZ_ASSERT(mStartOffset == 49,
2711 "Test 4-3-1: mStartOffset should be the smallest offset");
2712 MOZ_ASSERT(mRemovedEndOffset == 130, // 128 - (60 - 62)
2713 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
2714 "removed text "
2715 "without already removed text length");
2716 MOZ_ASSERT(
2717 mAddedEndOffset == 130,
2718 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
2719 Clear();
2721 // Replacing text all replaced text (became longer) (not sure if actually
2722 // occurs)
2723 MergeWith(TextChangeData(50, 61, 73, false, false));
2724 MergeWith(TextChangeData(44, 100, 50, false, false));
2725 MOZ_ASSERT(mStartOffset == 44,
2726 "Test 4-4-1: mStartOffset should be the smallest offset");
2727 MOZ_ASSERT(mRemovedEndOffset == 88, // 100 - (73 - 61)
2728 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
2729 "removed text "
2730 "with already added text length");
2731 MOZ_ASSERT(
2732 mAddedEndOffset == 50,
2733 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
2734 Clear();
2736 /****************************************************************************
2737 * Case 5
2738 ****************************************************************************/
2740 // Replacing text around start of added text (not sure if actually occurs)
2741 MergeWith(TextChangeData(50, 50, 55, false, false));
2742 MergeWith(TextChangeData(48, 52, 49, false, false));
2743 MOZ_ASSERT(mStartOffset == 48,
2744 "Test 5-1-1: mStartOffset should be the smallest offset");
2745 MOZ_ASSERT(
2746 mRemovedEndOffset == 50,
2747 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
2748 "text");
2749 MOZ_ASSERT(
2750 mAddedEndOffset == 52, // 55 + (52 - 49)
2751 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
2752 "added text length by the new change");
2753 Clear();
2755 // Replacing text around start of replaced text (became shorter) (not sure if
2756 // actually occurs)
2757 MergeWith(TextChangeData(50, 60, 58, false, false));
2758 MergeWith(TextChangeData(43, 50, 48, false, false));
2759 MOZ_ASSERT(mStartOffset == 43,
2760 "Test 5-2-1: mStartOffset should be the smallest offset");
2761 MOZ_ASSERT(
2762 mRemovedEndOffset == 60,
2763 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
2764 "text");
2765 MOZ_ASSERT(mAddedEndOffset == 56, // 58 + (48 - 50)
2766 "Test 5-2-3: mAddedEndOffset should be the first end of added "
2767 "text without "
2768 "removed text length by the new change");
2769 Clear();
2771 // Replacing text around start of replaced text (became longer) (not sure if
2772 // actually occurs)
2773 MergeWith(TextChangeData(50, 60, 68, false, false));
2774 MergeWith(TextChangeData(43, 55, 53, false, false));
2775 MOZ_ASSERT(mStartOffset == 43,
2776 "Test 5-3-1: mStartOffset should be the smallest offset");
2777 MOZ_ASSERT(
2778 mRemovedEndOffset == 60,
2779 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
2780 "text");
2781 MOZ_ASSERT(mAddedEndOffset == 66, // 68 + (53 - 55)
2782 "Test 5-3-3: mAddedEndOffset should be the first end of added "
2783 "text without "
2784 "removed text length by the new change");
2785 Clear();
2787 // Replacing text around start of replaced text (became shorter) (not sure if
2788 // actually occurs)
2789 MergeWith(TextChangeData(50, 60, 58, false, false));
2790 MergeWith(TextChangeData(43, 50, 128, false, false));
2791 MOZ_ASSERT(mStartOffset == 43,
2792 "Test 5-4-1: mStartOffset should be the smallest offset");
2793 MOZ_ASSERT(
2794 mRemovedEndOffset == 60,
2795 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
2796 "text");
2797 MOZ_ASSERT(
2798 mAddedEndOffset == 136, // 58 + (128 - 50)
2799 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
2800 "added text length by the new change");
2801 Clear();
2803 // Replacing text around start of replaced text (became longer) (not sure if
2804 // actually occurs)
2805 MergeWith(TextChangeData(50, 60, 68, false, false));
2806 MergeWith(TextChangeData(43, 55, 65, false, false));
2807 MOZ_ASSERT(mStartOffset == 43,
2808 "Test 5-5-1: mStartOffset should be the smallest offset");
2809 MOZ_ASSERT(
2810 mRemovedEndOffset == 60,
2811 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
2812 "text");
2813 MOZ_ASSERT(
2814 mAddedEndOffset == 78, // 68 + (65 - 55)
2815 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
2816 "added text length by the new change");
2817 Clear();
2819 /****************************************************************************
2820 * Case 6
2821 ****************************************************************************/
2823 // Appending text before already added text (not sure if actually occurs)
2824 MergeWith(TextChangeData(30, 30, 45, false, false));
2825 MergeWith(TextChangeData(10, 10, 20, false, false));
2826 MOZ_ASSERT(mStartOffset == 10,
2827 "Test 6-1-1: mStartOffset should be the smallest offset");
2828 MOZ_ASSERT(
2829 mRemovedEndOffset == 30,
2830 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
2831 "text");
2832 MOZ_ASSERT(
2833 mAddedEndOffset == 55, // 45 + (20 - 10)
2834 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
2835 "added text length by the new change");
2836 Clear();
2838 // Removing text before already removed text (not sure if actually occurs)
2839 MergeWith(TextChangeData(30, 35, 30, false, false));
2840 MergeWith(TextChangeData(10, 25, 10, false, false));
2841 MOZ_ASSERT(mStartOffset == 10,
2842 "Test 6-2-1: mStartOffset should be the smallest offset");
2843 MOZ_ASSERT(
2844 mRemovedEndOffset == 35,
2845 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
2846 "text");
2847 MOZ_ASSERT(
2848 mAddedEndOffset == 15, // 30 - (25 - 10)
2849 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
2850 "removed text length by the new change");
2851 Clear();
2853 // Replacing text before already replaced text (not sure if actually occurs)
2854 MergeWith(TextChangeData(50, 65, 70, false, false));
2855 MergeWith(TextChangeData(13, 24, 15, false, false));
2856 MOZ_ASSERT(mStartOffset == 13,
2857 "Test 6-3-1: mStartOffset should be the smallest offset");
2858 MOZ_ASSERT(
2859 mRemovedEndOffset == 65,
2860 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
2861 "text");
2862 MOZ_ASSERT(mAddedEndOffset == 61, // 70 + (15 - 24)
2863 "Test 6-3-3: mAddedEndOffset should be the first end of added "
2864 "text without "
2865 "removed text length by the new change");
2866 Clear();
2868 // Replacing text before already replaced text (not sure if actually occurs)
2869 MergeWith(TextChangeData(50, 65, 70, false, false));
2870 MergeWith(TextChangeData(13, 24, 36, false, false));
2871 MOZ_ASSERT(mStartOffset == 13,
2872 "Test 6-4-1: mStartOffset should be the smallest offset");
2873 MOZ_ASSERT(
2874 mRemovedEndOffset == 65,
2875 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
2876 "text");
2877 MOZ_ASSERT(mAddedEndOffset == 82, // 70 + (36 - 24)
2878 "Test 6-4-3: mAddedEndOffset should be the first end of added "
2879 "text without "
2880 "removed text length by the new change");
2881 Clear();
2884 #endif // #ifdef DEBUG
2886 } // namespace mozilla::widget
2888 #ifdef DEBUG
2889 //////////////////////////////////////////////////////////////
2891 // Convert a GUI event message code to a string.
2892 // Makes it a lot easier to debug events.
2894 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
2895 // for a DebugPrintEvent() function that uses
2896 // this.
2898 //////////////////////////////////////////////////////////////
2899 /* static */
2900 nsAutoString nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent* aGuiEvent) {
2901 NS_ASSERTION(nullptr != aGuiEvent, "cmon, null gui event.");
2903 nsAutoString eventName(u"UNKNOWN"_ns);
2905 # define _ASSIGN_eventName(_value, _name) \
2906 case _value: \
2907 eventName.AssignLiteral(_name); \
2908 break
2910 switch (aGuiEvent->mMessage) {
2911 _ASSIGN_eventName(eBlur, "eBlur");
2912 _ASSIGN_eventName(eDrop, "eDrop");
2913 _ASSIGN_eventName(eDragEnter, "eDragEnter");
2914 _ASSIGN_eventName(eDragExit, "eDragExit");
2915 _ASSIGN_eventName(eDragOver, "eDragOver");
2916 _ASSIGN_eventName(eEditorInput, "eEditorInput");
2917 _ASSIGN_eventName(eFocus, "eFocus");
2918 _ASSIGN_eventName(eFocusIn, "eFocusIn");
2919 _ASSIGN_eventName(eFocusOut, "eFocusOut");
2920 _ASSIGN_eventName(eFormSelect, "eFormSelect");
2921 _ASSIGN_eventName(eFormChange, "eFormChange");
2922 _ASSIGN_eventName(eFormReset, "eFormReset");
2923 _ASSIGN_eventName(eFormSubmit, "eFormSubmit");
2924 _ASSIGN_eventName(eImageAbort, "eImageAbort");
2925 _ASSIGN_eventName(eLoadError, "eLoadError");
2926 _ASSIGN_eventName(eKeyDown, "eKeyDown");
2927 _ASSIGN_eventName(eKeyPress, "eKeyPress");
2928 _ASSIGN_eventName(eKeyUp, "eKeyUp");
2929 _ASSIGN_eventName(eMouseEnterIntoWidget, "eMouseEnterIntoWidget");
2930 _ASSIGN_eventName(eMouseExitFromWidget, "eMouseExitFromWidget");
2931 _ASSIGN_eventName(eMouseDown, "eMouseDown");
2932 _ASSIGN_eventName(eMouseUp, "eMouseUp");
2933 _ASSIGN_eventName(eMouseClick, "eMouseClick");
2934 _ASSIGN_eventName(eMouseAuxClick, "eMouseAuxClick");
2935 _ASSIGN_eventName(eMouseDoubleClick, "eMouseDoubleClick");
2936 _ASSIGN_eventName(eMouseMove, "eMouseMove");
2937 _ASSIGN_eventName(eLoad, "eLoad");
2938 _ASSIGN_eventName(ePopState, "ePopState");
2939 _ASSIGN_eventName(eBeforeScriptExecute, "eBeforeScriptExecute");
2940 _ASSIGN_eventName(eAfterScriptExecute, "eAfterScriptExecute");
2941 _ASSIGN_eventName(eUnload, "eUnload");
2942 _ASSIGN_eventName(eHashChange, "eHashChange");
2943 _ASSIGN_eventName(eReadyStateChange, "eReadyStateChange");
2944 _ASSIGN_eventName(eXULBroadcast, "eXULBroadcast");
2945 _ASSIGN_eventName(eXULCommandUpdate, "eXULCommandUpdate");
2947 # undef _ASSIGN_eventName
2949 default: {
2950 eventName.AssignLiteral("UNKNOWN: ");
2951 eventName.AppendInt(aGuiEvent->mMessage);
2952 } break;
2955 return nsAutoString(eventName);
2957 //////////////////////////////////////////////////////////////
2959 // Code to deal with paint and event debug prefs.
2961 //////////////////////////////////////////////////////////////
2962 struct PrefPair {
2963 const char* name;
2964 bool value;
2967 static PrefPair debug_PrefValues[] = {
2968 {"nglayout.debug.crossing_event_dumping", false},
2969 {"nglayout.debug.event_dumping", false},
2970 {"nglayout.debug.invalidate_dumping", false},
2971 {"nglayout.debug.motion_event_dumping", false},
2972 {"nglayout.debug.paint_dumping", false},
2973 {"nglayout.debug.paint_flashing", false},
2974 {"nglayout.debug.paint_flashing_chrome", false}};
2976 //////////////////////////////////////////////////////////////
2977 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName) {
2978 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
2980 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
2981 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
2982 return debug_PrefValues[i].value;
2986 return false;
2988 //////////////////////////////////////////////////////////////
2989 static void debug_SetCachedBoolPref(const char* aPrefName, bool aValue) {
2990 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
2992 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
2993 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
2994 debug_PrefValues[i].value = aValue;
2996 return;
3000 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3003 //////////////////////////////////////////////////////////////
3004 class Debug_PrefObserver final : public nsIObserver {
3005 ~Debug_PrefObserver() = default;
3007 public:
3008 NS_DECL_ISUPPORTS
3009 NS_DECL_NSIOBSERVER
3012 NS_IMPL_ISUPPORTS(Debug_PrefObserver, nsIObserver)
3014 NS_IMETHODIMP
3015 Debug_PrefObserver::Observe(nsISupports* subject, const char* topic,
3016 const char16_t* data) {
3017 NS_ConvertUTF16toUTF8 prefName(data);
3019 bool value = Preferences::GetBool(prefName.get(), false);
3020 debug_SetCachedBoolPref(prefName.get(), value);
3021 return NS_OK;
3024 //////////////////////////////////////////////////////////////
3025 /* static */ void debug_RegisterPrefCallbacks() {
3026 static bool once = true;
3028 if (!once) {
3029 return;
3032 once = false;
3034 nsCOMPtr<nsIObserver> obs(new Debug_PrefObserver());
3035 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3036 // Initialize the pref values
3037 debug_PrefValues[i].value =
3038 Preferences::GetBool(debug_PrefValues[i].name, false);
3040 if (obs) {
3041 // Register callbacks for when these change
3042 nsCString name;
3043 name.AssignLiteral(debug_PrefValues[i].name,
3044 strlen(debug_PrefValues[i].name));
3045 Preferences::AddStrongObserver(obs, name);
3049 //////////////////////////////////////////////////////////////
3050 static int32_t _GetPrintCount() {
3051 static int32_t sCount = 0;
3053 return ++sCount;
3055 //////////////////////////////////////////////////////////////
3056 /* static */
3057 bool nsBaseWidget::debug_WantPaintFlashing() {
3058 return debug_GetCachedBoolPref("nglayout.debug.paint_flashing");
3060 //////////////////////////////////////////////////////////////
3061 /* static */
3062 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut, nsIWidget* aWidget,
3063 WidgetGUIEvent* aGuiEvent,
3064 const char* aWidgetName, int32_t aWindowID) {
3065 if (aGuiEvent->mMessage == eMouseMove) {
3066 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3069 if (aGuiEvent->mMessage == eMouseEnterIntoWidget ||
3070 aGuiEvent->mMessage == eMouseExitFromWidget) {
3071 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3072 return;
3075 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3077 NS_LossyConvertUTF16toASCII tempString(
3078 debug_GuiEventToString(aGuiEvent).get());
3080 fprintf(aFileOut, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3081 _GetPrintCount(), tempString.get(), (void*)aWidget, aWidgetName,
3082 aWindowID, aGuiEvent->mRefPoint.x, aGuiEvent->mRefPoint.y);
3084 //////////////////////////////////////////////////////////////
3085 /* static */
3086 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut, nsIWidget* aWidget,
3087 const nsIntRegion& aRegion,
3088 const char* aWidgetName,
3089 int32_t aWindowID) {
3090 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3091 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3093 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3095 nsIntRect rect = aRegion.GetBounds();
3096 fprintf(aFileOut,
3097 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3098 "%3d,%-3d",
3099 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID, rect.X(),
3100 rect.Y(), rect.Width(), rect.Height());
3102 fprintf(aFileOut, "\n");
3104 //////////////////////////////////////////////////////////////
3105 /* static */
3106 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut, nsIWidget* aWidget,
3107 const LayoutDeviceIntRect* aRect,
3108 const char* aWidgetName,
3109 int32_t aWindowID) {
3110 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3112 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3113 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3115 fprintf(aFileOut, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3116 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID);
3118 if (aRect) {
3119 fprintf(aFileOut, " rect=%3d,%-3d %3d,%-3d", aRect->X(), aRect->Y(),
3120 aRect->Width(), aRect->Height());
3121 } else {
3122 fprintf(aFileOut, " rect=%-15s", "none");
3125 fprintf(aFileOut, "\n");
3127 //////////////////////////////////////////////////////////////
3129 #endif // DEBUG