Bug 1758713 [wpt PR 33128] - Clarify the status of the CSS build system, a=testonly
[gecko.git] / widget / nsBaseWidget.cpp
blobf8e4618af8b6aca27fb143c56753323378978815
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 "SwipeTracker.h"
16 #include "TouchEvents.h"
17 #include "X11UndefineNone.h"
18 #include "base/thread.h"
19 #include "mozilla/ArrayUtils.h"
20 #include "mozilla/Attributes.h"
21 #include "mozilla/GlobalKeyListener.h"
22 #include "mozilla/IMEStateManager.h"
23 #include "mozilla/MouseEvents.h"
24 #include "mozilla/NativeKeyBindingsType.h"
25 #include "mozilla/Preferences.h"
26 #include "mozilla/PresShell.h"
27 #include "mozilla/Sprintf.h"
28 #include "mozilla/StaticPrefs_apz.h"
29 #include "mozilla/StaticPrefs_dom.h"
30 #include "mozilla/StaticPrefs_gfx.h"
31 #include "mozilla/StaticPrefs_layers.h"
32 #include "mozilla/StaticPrefs_layout.h"
33 #include "mozilla/TextEventDispatcher.h"
34 #include "mozilla/TextEventDispatcherListener.h"
35 #include "mozilla/UniquePtr.h"
36 #include "mozilla/Unused.h"
37 #include "mozilla/VsyncDispatcher.h"
38 #include "mozilla/dom/BrowserParent.h"
39 #include "mozilla/dom/ContentChild.h"
40 #include "mozilla/dom/Document.h"
41 #include "mozilla/dom/SimpleGestureEventBinding.h"
42 #include "mozilla/gfx/2D.h"
43 #include "mozilla/gfx/GPUProcessManager.h"
44 #include "mozilla/gfx/gfxVars.h"
45 #include "mozilla/layers/APZCCallbackHelper.h"
46 #include "mozilla/layers/TouchActionHelper.h"
47 #include "mozilla/layers/APZEventState.h"
48 #include "mozilla/layers/APZInputBridge.h"
49 #include "mozilla/layers/APZThreadUtils.h"
50 #include "mozilla/layers/ChromeProcessController.h"
51 #include "mozilla/layers/Compositor.h"
52 #include "mozilla/layers/CompositorBridgeChild.h"
53 #include "mozilla/layers/CompositorBridgeParent.h"
54 #include "mozilla/layers/CompositorOptions.h"
55 #include "mozilla/layers/IAPZCTreeManager.h"
56 #include "mozilla/layers/ImageBridgeChild.h"
57 #include "mozilla/layers/InputAPZContext.h"
58 #include "mozilla/layers/WebRenderLayerManager.h"
59 #include "mozilla/webrender/WebRenderTypes.h"
60 #include "nsAppDirectoryServiceDefs.h"
61 #include "nsCOMPtr.h"
62 #include "nsContentUtils.h"
63 #include "nsDeviceContext.h"
64 #include "nsGfxCIID.h"
65 #include "nsIAppWindow.h"
66 #include "nsIBaseWindow.h"
67 #include "nsIContent.h"
68 #include "nsIScreenManager.h"
69 #include "nsISimpleEnumerator.h"
70 #include "nsIWidgetListener.h"
71 #include "nsRefPtrHashtable.h"
72 #include "nsServiceManagerUtils.h"
73 #include "nsWidgetsCID.h"
74 #include "nsXULPopupManager.h"
75 #include "prdtoa.h"
76 #include "prenv.h"
77 #ifdef ACCESSIBILITY
78 # include "nsAccessibilityService.h"
79 #endif
80 #include "gfxConfig.h"
81 #include "gfxUtils.h" // for ToDeviceColor
82 #include "mozilla/layers/CompositorSession.h"
83 #include "VRManagerChild.h"
84 #include "gfxConfig.h"
85 #include "nsView.h"
86 #include "nsViewManager.h"
88 #ifdef DEBUG
89 # include "nsIObserver.h"
91 static void debug_RegisterPrefCallbacks();
93 #endif
95 #ifdef NOISY_WIDGET_LEAKS
96 static int32_t gNumWidgets;
97 #endif
99 #ifdef XP_MACOSX
100 # include "nsCocoaFeatures.h"
101 #endif
103 nsIRollupListener* nsBaseWidget::gRollupListener = nullptr;
105 using namespace mozilla::dom;
106 using namespace mozilla::layers;
107 using namespace mozilla::ipc;
108 using namespace mozilla::widget;
109 using namespace mozilla;
111 // Async pump timer during injected long touch taps
112 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
113 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
114 int32_t nsIWidget::sPointerIdCounter = 0;
116 // Some statics from nsIWidget.h
117 /*static*/
118 uint64_t AutoObserverNotifier::sObserverId = 0;
119 /*static*/ nsTHashMap<uint64_t, nsCOMPtr<nsIObserver>>
120 AutoObserverNotifier::sSavedObservers;
122 // The maximum amount of time to let the EnableDragDrop runnable wait in the
123 // idle queue before timing out and moving it to the regular queue. Value is in
124 // milliseconds.
125 const uint32_t kAsyncDragDropTimeout = 1000;
127 NS_IMPL_ISUPPORTS(nsBaseWidget, nsIWidget, nsISupportsWeakReference)
129 //-------------------------------------------------------------------------
131 // nsBaseWidget constructor
133 //-------------------------------------------------------------------------
135 nsBaseWidget::nsBaseWidget() : nsBaseWidget(eBorderStyle_none) {}
137 nsBaseWidget::nsBaseWidget(nsBorderStyle aBorderStyle)
138 : mWidgetListener(nullptr),
139 mAttachedWidgetListener(nullptr),
140 mPreviouslyAttachedWidgetListener(nullptr),
141 mCompositorVsyncDispatcher(nullptr),
142 mBorderStyle(aBorderStyle),
143 mBounds(0, 0, 0, 0),
144 mOriginalBounds(nullptr),
145 mSizeMode(nsSizeMode_Normal),
146 mIsTiled(false),
147 mPopupLevel(ePopupLevelTop),
148 mPopupType(ePopupTypeAny),
149 mHasRemoteContent(false),
150 mFissionWindow(false),
151 mUpdateCursor(true),
152 mUseAttachedEvents(false),
153 mIMEHasFocus(false),
154 mIMEHasQuit(false),
155 mIsFullyOccluded(false),
156 mCurrentPanGestureBelongsToSwipe(false) {
157 #ifdef NOISY_WIDGET_LEAKS
158 gNumWidgets++;
159 printf("WIDGETS+ = %d\n", gNumWidgets);
160 #endif
162 #ifdef DEBUG
163 debug_RegisterPrefCallbacks();
164 #endif
166 mShutdownObserver = new WidgetShutdownObserver(this);
169 NS_IMPL_ISUPPORTS(WidgetShutdownObserver, nsIObserver)
171 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget* aWidget)
172 : mWidget(aWidget), mRegistered(false) {
173 Register();
176 WidgetShutdownObserver::~WidgetShutdownObserver() {
177 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
178 // gets torn down. The observer service and nsBaseWidget have a ref on us
179 // so nsBaseWidget has to call Unregister and then clear its ref.
182 NS_IMETHODIMP
183 WidgetShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
184 const char16_t* aData) {
185 if (!mWidget) {
186 return NS_OK;
188 if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
189 RefPtr<nsBaseWidget> widget(mWidget);
190 widget->Shutdown();
191 } else if (!strcmp(aTopic, "quit-application")) {
192 RefPtr<nsBaseWidget> widget(mWidget);
193 widget->QuitIME();
195 return NS_OK;
198 void WidgetShutdownObserver::Register() {
199 if (!mRegistered) {
200 mRegistered = true;
201 nsContentUtils::RegisterShutdownObserver(this);
203 #ifndef MOZ_WIDGET_ANDROID
204 // The primary purpose of observing quit-application is
205 // to avoid leaking a widget on Windows when nothing else
206 // breaks the circular reference between the widget and
207 // TSFTextStore. However, our Android IME code crashes if
208 // doing this on Android, so let's not do this on Android.
209 // Doing this on Gtk and Mac just in case.
210 nsCOMPtr<nsIObserverService> observerService =
211 mozilla::services::GetObserverService();
212 if (observerService) {
213 observerService->AddObserver(this, "quit-application", false);
215 #endif
219 void WidgetShutdownObserver::Unregister() {
220 if (mRegistered) {
221 mWidget = nullptr;
223 #ifndef MOZ_WIDGET_ANDROID
224 nsCOMPtr<nsIObserverService> observerService =
225 mozilla::services::GetObserverService();
226 if (observerService) {
227 observerService->RemoveObserver(this, "quit-application");
229 #endif
231 nsContentUtils::UnregisterShutdownObserver(this);
232 mRegistered = false;
236 #define INTL_APP_LOCALES_CHANGED "intl:app-locales-changed"
237 #define L10N_PSEUDO_PREF "intl.l10n.pseudo"
239 static const char* kObservedPrefs[] = {L10N_PSEUDO_PREF, nullptr};
241 NS_IMPL_ISUPPORTS(LocalesChangedObserver, nsIObserver)
243 LocalesChangedObserver::LocalesChangedObserver(nsBaseWidget* aWidget)
244 : mWidget(aWidget), mRegistered(false) {
245 Register();
248 LocalesChangedObserver::~LocalesChangedObserver() {
249 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
250 // gets torn down. The observer service and nsBaseWidget have a ref on us
251 // so nsBaseWidget has to call Unregister and then clear its ref.
254 NS_IMETHODIMP
255 LocalesChangedObserver::Observe(nsISupports* aSubject, const char* aTopic,
256 const char16_t* aData) {
257 if (!mWidget) {
258 return NS_OK;
260 if (!strcmp(aTopic, INTL_APP_LOCALES_CHANGED)) {
261 RefPtr<nsBaseWidget> widget(mWidget);
262 widget->LocalesChanged();
263 } else {
264 MOZ_ASSERT(!strcmp("nsPref:changed", aTopic));
265 nsDependentString pref(aData);
266 if (pref.EqualsLiteral(L10N_PSEUDO_PREF)) {
267 RefPtr<nsBaseWidget> widget(mWidget);
268 widget->LocalesChanged();
271 return NS_OK;
274 void LocalesChangedObserver::Register() {
275 if (mRegistered) {
276 return;
279 DebugOnly<nsresult> rv =
280 Preferences::AddStrongObservers(this, kObservedPrefs);
281 MOZ_ASSERT(NS_SUCCEEDED(rv), "Adding observers failed.");
283 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
284 if (obs) {
285 obs->AddObserver(this, INTL_APP_LOCALES_CHANGED, true);
288 // Locale might be update before registering
289 RefPtr<nsBaseWidget> widget(mWidget);
290 widget->LocalesChanged();
292 mRegistered = true;
295 void LocalesChangedObserver::Unregister() {
296 if (!mRegistered) {
297 return;
300 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
301 if (obs) {
302 obs->RemoveObserver(this, INTL_APP_LOCALES_CHANGED);
304 Preferences::RemoveObservers(this, kObservedPrefs);
306 mWidget = nullptr;
307 mRegistered = false;
310 void nsBaseWidget::Shutdown() {
311 NotifyLiveResizeStopped();
312 RevokeTransactionIdAllocator();
313 DestroyCompositor();
314 FreeLocalesChangedObserver();
315 FreeShutdownObserver();
318 void nsBaseWidget::QuitIME() {
319 IMEStateManager::WidgetOnQuit(this);
320 this->mIMEHasQuit = true;
323 void nsBaseWidget::DestroyCompositor() {
324 // We release this before releasing the compositor, since it may hold the
325 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
326 // trigger a paint, creating a new compositor, and we don't want to re-use
327 // the old vsync dispatcher.
328 if (mCompositorVsyncDispatcher) {
329 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
331 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
332 mCompositorVsyncDispatcher->Shutdown();
333 mCompositorVsyncDispatcher = nullptr;
336 // The compositor shutdown sequence looks like this:
337 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
338 // 2. CompositorBridgeChild synchronously sends WillClose.
339 // 3. CompositorBridgeParent releases some resources (such as the layer
340 // manager, compositor, and widget).
341 // 4. CompositorBridgeChild::Destroy returns.
342 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
343 // compositor thread when the I/O thread closes the IPC channel.
344 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
345 // releases the reference CompositorBridgeParent holds to itself.
347 // When CompositorSession::Shutdown returns, we assume the compositor is gone
348 // or will be gone very soon.
349 if (mCompositorSession) {
350 ReleaseContentController();
351 mAPZC = nullptr;
352 SetCompositorWidgetDelegate(nullptr);
353 mCompositorBridgeChild = nullptr;
354 mCompositorSession->Shutdown();
355 mCompositorSession = nullptr;
359 // This prevents the layer manager from starting a new transaction during
360 // shutdown.
361 void nsBaseWidget::RevokeTransactionIdAllocator() {
362 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
363 return;
365 mWindowRenderer->AsWebRender()->SetTransactionIdAllocator(nullptr);
368 void nsBaseWidget::ReleaseContentController() {
369 if (mRootContentController) {
370 mRootContentController->Destroy();
371 mRootContentController = nullptr;
375 void nsBaseWidget::DestroyLayerManager() {
376 if (mWindowRenderer) {
377 mWindowRenderer->Destroy();
378 mWindowRenderer = nullptr;
380 DestroyCompositor();
383 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
385 void nsBaseWidget::FreeShutdownObserver() {
386 if (mShutdownObserver) {
387 mShutdownObserver->Unregister();
389 mShutdownObserver = nullptr;
392 void nsBaseWidget::FreeLocalesChangedObserver() {
393 if (mLocalesChangedObserver) {
394 mLocalesChangedObserver->Unregister();
396 mLocalesChangedObserver = nullptr;
399 //-------------------------------------------------------------------------
401 // nsBaseWidget destructor
403 //-------------------------------------------------------------------------
405 nsBaseWidget::~nsBaseWidget() {
406 if (mSwipeTracker) {
407 mSwipeTracker->Destroy();
408 mSwipeTracker = nullptr;
411 IMEStateManager::WidgetDestroyed(this);
413 FreeLocalesChangedObserver();
414 FreeShutdownObserver();
415 RevokeTransactionIdAllocator();
416 DestroyLayerManager();
418 #ifdef NOISY_WIDGET_LEAKS
419 gNumWidgets--;
420 printf("WIDGETS- = %d\n", gNumWidgets);
421 #endif
423 delete mOriginalBounds;
426 //-------------------------------------------------------------------------
428 // Basic create.
430 //-------------------------------------------------------------------------
431 void nsBaseWidget::BaseCreate(nsIWidget* aParent, nsWidgetInitData* aInitData) {
432 // keep a reference to the device context
433 if (nullptr != aInitData) {
434 mWindowType = aInitData->mWindowType;
435 mBorderStyle = aInitData->mBorderStyle;
436 mPopupLevel = aInitData->mPopupLevel;
437 mPopupType = aInitData->mPopupHint;
438 mHasRemoteContent = aInitData->mHasRemoteContent;
439 mFissionWindow = aInitData->mFissionWindow;
442 if (aParent) {
443 aParent->AddChild(this);
447 //-------------------------------------------------------------------------
449 // Accessor functions to get/set the client data
451 //-------------------------------------------------------------------------
453 nsIWidgetListener* nsBaseWidget::GetWidgetListener() const {
454 return mWidgetListener;
457 void nsBaseWidget::SetWidgetListener(nsIWidgetListener* aWidgetListener) {
458 mWidgetListener = aWidgetListener;
461 already_AddRefed<nsIWidget> nsBaseWidget::CreateChild(
462 const LayoutDeviceIntRect& aRect, nsWidgetInitData* aInitData,
463 bool aForceUseIWidgetParent) {
464 nsIWidget* parent = this;
465 nsNativeWidget nativeParent = nullptr;
467 if (!aForceUseIWidgetParent) {
468 // Use only either parent or nativeParent, not both, to match
469 // existing code. Eventually Create() should be divested of its
470 // nativeWidget parameter.
471 nativeParent = parent ? parent->GetNativeData(NS_NATIVE_WIDGET) : nullptr;
472 parent = nativeParent ? nullptr : parent;
473 MOZ_ASSERT(!parent || !nativeParent, "messed up logic");
476 nsCOMPtr<nsIWidget> widget;
477 if (aInitData && aInitData->mWindowType == eWindowType_popup) {
478 widget = AllocateChildPopupWidget();
479 } else {
480 widget = nsIWidget::CreateChildWindow();
483 if (widget &&
484 NS_SUCCEEDED(widget->Create(parent, nativeParent, aRect, aInitData))) {
485 return widget.forget();
488 return nullptr;
491 // Attach a view to our widget which we'll send events to.
492 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents) {
493 NS_ASSERTION((mWindowType == eWindowType_toplevel ||
494 mWindowType == eWindowType_dialog ||
495 mWindowType == eWindowType_invisible ||
496 mWindowType == eWindowType_child),
497 "Can't attach to window of that type");
499 mUseAttachedEvents = aUseAttachedEvents;
502 nsIWidgetListener* nsBaseWidget::GetAttachedWidgetListener() const {
503 return mAttachedWidgetListener;
506 nsIWidgetListener* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
507 return mPreviouslyAttachedWidgetListener;
510 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
511 nsIWidgetListener* aListener) {
512 mPreviouslyAttachedWidgetListener = aListener;
515 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener* aListener) {
516 mAttachedWidgetListener = aListener;
519 //-------------------------------------------------------------------------
521 // Close this nsBaseWidget
523 //-------------------------------------------------------------------------
524 void nsBaseWidget::Destroy() {
525 // Just in case our parent is the only ref to us
526 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
527 // disconnect from the parent
528 nsIWidget* parent = GetParent();
529 if (parent) {
530 parent->RemoveChild(this);
534 //-------------------------------------------------------------------------
536 // Get this nsBaseWidget parent
538 //-------------------------------------------------------------------------
539 nsIWidget* nsBaseWidget::GetParent(void) { return nullptr; }
541 //-------------------------------------------------------------------------
543 // Get this nsBaseWidget top level widget
545 //-------------------------------------------------------------------------
546 nsIWidget* nsBaseWidget::GetTopLevelWidget() {
547 nsIWidget *topLevelWidget = nullptr, *widget = this;
548 while (widget) {
549 topLevelWidget = widget;
550 widget = widget->GetParent();
552 return topLevelWidget;
555 //-------------------------------------------------------------------------
557 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
559 //-------------------------------------------------------------------------
560 nsIWidget* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
562 float nsBaseWidget::GetDPI() { return 96.0f; }
564 CSSToLayoutDeviceScale nsIWidget::GetDefaultScale() {
565 double devPixelsPerCSSPixel = StaticPrefs::layout_css_devPixelsPerPx();
567 if (devPixelsPerCSSPixel <= 0.0) {
568 devPixelsPerCSSPixel = GetDefaultScaleInternal();
571 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel);
574 nsIntSize nsIWidget::CustomCursorSize(const Cursor& aCursor) {
575 MOZ_ASSERT(aCursor.IsCustom());
576 int32_t width = 0;
577 int32_t height = 0;
578 aCursor.mContainer->GetWidth(&width);
579 aCursor.mContainer->GetHeight(&height);
580 aCursor.mResolution.ApplyTo(width, height);
581 return {width, height};
584 //-------------------------------------------------------------------------
586 // Add a child to the list of children
588 //-------------------------------------------------------------------------
589 void nsBaseWidget::AddChild(nsIWidget* aChild) {
590 MOZ_ASSERT(!aChild->GetNextSibling() && !aChild->GetPrevSibling(),
591 "aChild not properly removed from its old child list");
593 if (!mFirstChild) {
594 mFirstChild = mLastChild = aChild;
595 } else {
596 // append to the list
597 MOZ_ASSERT(mLastChild);
598 MOZ_ASSERT(!mLastChild->GetNextSibling());
599 mLastChild->SetNextSibling(aChild);
600 aChild->SetPrevSibling(mLastChild);
601 mLastChild = aChild;
605 //-------------------------------------------------------------------------
607 // Remove a child from the list of children
609 //-------------------------------------------------------------------------
610 void nsBaseWidget::RemoveChild(nsIWidget* aChild) {
611 #ifdef DEBUG
612 # ifdef XP_MACOSX
613 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
614 // null and we'll just have to do without this assertion.
615 nsIWidget* parent = aChild->GetParent();
616 NS_ASSERTION(!parent || parent == this, "Not one of our kids!");
617 # else
618 MOZ_RELEASE_ASSERT(aChild->GetParent() == this, "Not one of our kids!");
619 # endif
620 #endif
622 if (mLastChild == aChild) {
623 mLastChild = mLastChild->GetPrevSibling();
625 if (mFirstChild == aChild) {
626 mFirstChild = mFirstChild->GetNextSibling();
629 // Now remove from the list. Make sure that we pass ownership of the tail
630 // of the list correctly before we have aChild let go of it.
631 nsIWidget* prev = aChild->GetPrevSibling();
632 nsIWidget* next = aChild->GetNextSibling();
633 if (prev) {
634 prev->SetNextSibling(next);
636 if (next) {
637 next->SetPrevSibling(prev);
640 aChild->SetNextSibling(nullptr);
641 aChild->SetPrevSibling(nullptr);
644 //-------------------------------------------------------------------------
646 // Sets widget's position within its parent's child list.
648 //-------------------------------------------------------------------------
649 void nsBaseWidget::SetZIndex(int32_t aZIndex) {
650 // Hold a ref to ourselves just in case, since we're going to remove
651 // from our parent.
652 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
654 mZIndex = aZIndex;
656 // reorder this child in its parent's list.
657 auto* parent = static_cast<nsBaseWidget*>(GetParent());
658 if (parent) {
659 parent->RemoveChild(this);
660 // Scope sib outside the for loop so we can check it afterward
661 nsIWidget* sib = parent->GetFirstChild();
662 for (; sib; sib = sib->GetNextSibling()) {
663 int32_t childZIndex = GetZIndex();
664 if (aZIndex < childZIndex) {
665 // Insert ourselves before sib
666 nsIWidget* prev = sib->GetPrevSibling();
667 mNextSibling = sib;
668 mPrevSibling = prev;
669 sib->SetPrevSibling(this);
670 if (prev) {
671 prev->SetNextSibling(this);
672 } else {
673 NS_ASSERTION(sib == parent->mFirstChild, "Broken child list");
674 // We've taken ownership of sib, so it's safe to have parent let
675 // go of it
676 parent->mFirstChild = this;
678 PlaceBehind(eZPlacementBelow, sib, false);
679 break;
682 // were we added to the list?
683 if (!sib) {
684 parent->AddChild(this);
689 //-------------------------------------------------------------------------
691 // Maximize, minimize or restore the window. The BaseWidget implementation
692 // merely stores the state.
694 //-------------------------------------------------------------------------
695 void nsBaseWidget::SetSizeMode(nsSizeMode aMode) {
696 MOZ_ASSERT(aMode == nsSizeMode_Normal || aMode == nsSizeMode_Minimized ||
697 aMode == nsSizeMode_Maximized || aMode == nsSizeMode_Fullscreen);
698 mSizeMode = aMode;
701 void nsBaseWidget::GetWorkspaceID(nsAString& workspaceID) {
702 workspaceID.Truncate();
705 void nsBaseWidget::MoveToWorkspace(const nsAString& workspaceID) {
706 // Noop.
709 //-------------------------------------------------------------------------
711 // Get this component cursor
713 //-------------------------------------------------------------------------
715 void nsBaseWidget::SetCursor(const Cursor& aCursor) { mCursor = aCursor; }
717 //-------------------------------------------------------------------------
719 // Window transparency methods
721 //-------------------------------------------------------------------------
723 void nsBaseWidget::SetTransparencyMode(nsTransparencyMode aMode) {}
725 nsTransparencyMode nsBaseWidget::GetTransparencyMode() {
726 return eTransparencyOpaque;
729 /* virtual */
730 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage,
731 uint16_t aDuration,
732 nsISupports* aData,
733 nsIRunnable* aCallback) {
734 MOZ_ASSERT_UNREACHABLE(
735 "Should never call PerformFullscreenTransition on nsBaseWidget");
738 //-------------------------------------------------------------------------
740 // Put the window into full-screen mode
742 //-------------------------------------------------------------------------
743 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen) {
744 HideWindowChrome(aFullScreen);
746 if (aFullScreen) {
747 if (!mOriginalBounds) {
748 mOriginalBounds = new LayoutDeviceIntRect();
750 *mOriginalBounds = GetScreenBounds();
752 // Move to top-left corner of screen and size to the screen dimensions
753 nsCOMPtr<nsIScreen> screen = GetWidgetScreen();
754 if (screen) {
755 int32_t left, top, width, height;
756 if (NS_SUCCEEDED(
757 screen->GetRectDisplayPix(&left, &top, &width, &height))) {
758 Resize(left, top, width, height, true);
761 } else if (mOriginalBounds) {
762 if (BoundsUseDesktopPixels()) {
763 DesktopRect deskRect = *mOriginalBounds / GetDesktopToDeviceScale();
764 Resize(deskRect.X(), deskRect.Y(), deskRect.Width(), deskRect.Height(),
765 true);
766 } else {
767 Resize(mOriginalBounds->X(), mOriginalBounds->Y(),
768 mOriginalBounds->Width(), mOriginalBounds->Height(), true);
773 nsresult nsBaseWidget::MakeFullScreen(bool aFullScreen) {
774 InfallibleMakeFullScreen(aFullScreen);
775 return NS_OK;
778 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
779 nsBaseWidget* aWidget, gfxContext* aTarget, BufferMode aDoubleBuffering)
780 : mWidget(aWidget) {
781 WindowRenderer* renderer = mWidget->GetWindowRenderer();
782 if (renderer->AsFallback()) {
783 mRenderer = renderer->AsFallback();
784 mRenderer->SetTarget(aTarget, aDoubleBuffering);
788 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
789 if (mRenderer) {
790 mRenderer->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE);
794 bool nsBaseWidget::IsSmallPopup() const {
795 return mWindowType == eWindowType_popup && mPopupType != ePopupTypePanel;
798 bool nsBaseWidget::ComputeShouldAccelerate() {
799 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING) &&
800 (WidgetTypeSupportsAcceleration() ||
801 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
804 bool nsBaseWidget::UseAPZ() {
805 return (gfxPlatform::AsyncPanZoomEnabled() &&
806 (WindowType() == eWindowType_toplevel ||
807 WindowType() == eWindowType_child ||
808 ((WindowType() == eWindowType_popup ||
809 WindowType() == eWindowType_dialog) &&
810 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
813 void nsBaseWidget::CreateCompositor() {
814 LayoutDeviceIntRect rect = GetBounds();
815 CreateCompositor(rect.Width(), rect.Height());
818 already_AddRefed<GeckoContentController>
819 nsBaseWidget::CreateRootContentController() {
820 RefPtr<GeckoContentController> controller =
821 new ChromeProcessController(this, mAPZEventState, mAPZC);
822 return controller.forget();
825 void nsBaseWidget::ConfigureAPZCTreeManager() {
826 MOZ_ASSERT(NS_IsMainThread());
827 MOZ_ASSERT(mAPZC);
829 mAPZC->SetDPI(GetDPI());
831 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
832 KeyboardMap map = RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
833 mAPZC->SetKeyboardMap(map);
836 ContentReceivedInputBlockCallback callback(
837 [treeManager = RefPtr{mAPZC.get()}](uint64_t aInputBlockId,
838 bool aPreventDefault) {
839 MOZ_ASSERT(NS_IsMainThread());
840 treeManager->ContentReceivedInputBlock(aInputBlockId, aPreventDefault);
842 mAPZEventState = new APZEventState(this, std::move(callback));
844 mRootContentController = CreateRootContentController();
845 if (mRootContentController) {
846 mCompositorSession->SetContentController(mRootContentController);
849 // When APZ is enabled, we can actually enable raw touch events because we
850 // have code that can deal with them properly. If APZ is not enabled, this
851 // function doesn't get called.
852 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
853 RegisterTouchWindow();
857 void nsBaseWidget::ConfigureAPZControllerThread() {
858 // By default the controller thread is the main thread.
859 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
862 void nsBaseWidget::SetConfirmedTargetAPZC(
863 uint64_t aInputBlockId,
864 const nsTArray<ScrollableLayerGuid>& aTargets) const {
865 mAPZC->SetTargetAPZC(aInputBlockId, aTargets);
868 void nsBaseWidget::UpdateZoomConstraints(
869 const uint32_t& aPresShellId, const ScrollableLayerGuid::ViewID& aViewId,
870 const Maybe<ZoomConstraints>& aConstraints) {
871 if (!mCompositorSession || !mAPZC) {
872 if (mInitialZoomConstraints) {
873 MOZ_ASSERT(mInitialZoomConstraints->mPresShellID == aPresShellId);
874 MOZ_ASSERT(mInitialZoomConstraints->mViewID == aViewId);
875 if (!aConstraints) {
876 mInitialZoomConstraints.reset();
880 if (aConstraints) {
881 // We have some constraints, but the compositor and APZC aren't created
882 // yet. Save these so we can use them later.
883 mInitialZoomConstraints = Some(
884 InitialZoomConstraints(aPresShellId, aViewId, aConstraints.ref()));
886 return;
888 LayersId layersId = mCompositorSession->RootLayerTreeId();
889 mAPZC->UpdateZoomConstraints(
890 ScrollableLayerGuid(layersId, aPresShellId, aViewId), aConstraints);
893 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC; }
895 nsEventStatus nsBaseWidget::ProcessUntransformedAPZEvent(
896 WidgetInputEvent* aEvent, const APZEventResult& aApzResult) {
897 MOZ_ASSERT(NS_IsMainThread());
898 ScrollableLayerGuid targetGuid = aApzResult.mTargetGuid;
899 uint64_t inputBlockId = aApzResult.mInputBlockId;
900 InputAPZContext context(aApzResult.mTargetGuid, inputBlockId,
901 aApzResult.GetStatus());
903 // Make a copy of the original event for the APZCCallbackHelper helpers that
904 // we call later, because the event passed to DispatchEvent can get mutated in
905 // ways that we don't want (i.e. touch points can get stripped out).
906 nsEventStatus status;
907 UniquePtr<WidgetEvent> original(aEvent->Duplicate());
908 DispatchEvent(aEvent, status);
910 if (mAPZC && !InputAPZContext::WasRoutedToChildProcess() && inputBlockId) {
911 // EventStateManager did not route the event into the child process.
912 // It's safe to communicate to APZ that the event has been processed.
913 // Note that here aGuid.mLayersId might be different from
914 // mCompositorSession->RootLayerTreeId() because the event might have gotten
915 // hit-tested by APZ to be targeted at a child process, but a parent process
916 // event listener called preventDefault on it. In that case aGuid.mLayersId
917 // would still be the layers id for the child process, but the event would
918 // not have actually gotten routed to the child process. The main-thread
919 // hit-test result therefore needs to use the parent process layers id.
920 LayersId rootLayersId = mCompositorSession->RootLayerTreeId();
922 RefPtr<DisplayportSetListener> postLayerization;
923 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
924 nsTArray<TouchBehaviorFlags> allowedTouchBehaviors;
925 if (touchEvent->mMessage == eTouchStart) {
926 auto& originalEvent = *original->AsTouchEvent();
927 MOZ_ASSERT(NS_IsMainThread());
928 allowedTouchBehaviors = TouchActionHelper::GetAllowedTouchBehavior(
929 this, GetDocument(), originalEvent);
930 if (!allowedTouchBehaviors.IsEmpty()) {
931 mAPZC->SetAllowedTouchBehavior(inputBlockId, allowedTouchBehaviors);
933 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
934 this, GetDocument(), originalEvent, rootLayersId, inputBlockId);
936 mAPZEventState->ProcessTouchEvent(*touchEvent, targetGuid, inputBlockId,
937 aApzResult.GetStatus(), status,
938 std::move(allowedTouchBehaviors));
939 } else if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
940 MOZ_ASSERT(wheelEvent->mFlags.mHandledByAPZ);
941 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
942 this, GetDocument(), *original->AsWheelEvent(), rootLayersId,
943 inputBlockId);
944 if (wheelEvent->mCanTriggerSwipe) {
945 ReportSwipeStarted(inputBlockId, wheelEvent->TriggersSwipe());
947 mAPZEventState->ProcessWheelEvent(*wheelEvent, inputBlockId);
948 } else if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
949 MOZ_ASSERT(mouseEvent->mFlags.mHandledByAPZ);
950 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
951 this, GetDocument(), *original->AsMouseEvent(), rootLayersId,
952 inputBlockId);
953 mAPZEventState->ProcessMouseEvent(*mouseEvent, inputBlockId);
955 if (postLayerization) {
956 postLayerization->Register();
960 return status;
963 template <class InputType, class EventType>
964 class DispatchEventOnMainThread : public Runnable {
965 public:
966 DispatchEventOnMainThread(const InputType& aInput, nsBaseWidget* aWidget,
967 const APZEventResult& aAPZResult)
968 : mozilla::Runnable("DispatchEventOnMainThread"),
969 mInput(aInput),
970 mWidget(aWidget),
971 mAPZResult(aAPZResult) {}
973 NS_IMETHOD Run() override {
974 EventType event = mInput.ToWidgetEvent(mWidget);
975 mWidget->ProcessUntransformedAPZEvent(&event, mAPZResult);
976 return NS_OK;
979 private:
980 InputType mInput;
981 nsBaseWidget* mWidget;
982 APZEventResult mAPZResult;
985 template <class InputType, class EventType>
986 class DispatchInputOnControllerThread : public Runnable {
987 public:
988 DispatchInputOnControllerThread(const EventType& aEvent,
989 IAPZCTreeManager* aAPZC,
990 nsBaseWidget* aWidget)
991 : mozilla::Runnable("DispatchInputOnControllerThread"),
992 mMainMessageLoop(MessageLoop::current()),
993 mInput(aEvent),
994 mAPZC(aAPZC),
995 mWidget(aWidget) {}
997 NS_IMETHOD Run() override {
998 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(mInput);
999 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1000 return NS_OK;
1002 RefPtr<Runnable> r = new DispatchEventOnMainThread<InputType, EventType>(
1003 mInput, mWidget, result);
1004 mMainMessageLoop->PostTask(r.forget());
1005 return NS_OK;
1008 private:
1009 MessageLoop* mMainMessageLoop;
1010 InputType mInput;
1011 RefPtr<IAPZCTreeManager> mAPZC;
1012 nsBaseWidget* mWidget;
1015 void nsBaseWidget::DispatchTouchInput(MultiTouchInput& aInput,
1016 uint16_t aInputSource) {
1017 MOZ_ASSERT(NS_IsMainThread());
1018 MOZ_ASSERT(aInputSource ==
1019 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH ||
1020 aInputSource == mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN);
1021 if (mAPZC) {
1022 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1024 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1025 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1026 return;
1029 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1030 ProcessUntransformedAPZEvent(&event, result);
1031 } else {
1032 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1034 nsEventStatus status;
1035 DispatchEvent(&event, status);
1039 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput& aInput) {
1040 MOZ_ASSERT(NS_IsMainThread());
1041 if (mAPZC) {
1042 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1044 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1045 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1046 return;
1049 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1050 ProcessUntransformedAPZEvent(&event, result);
1051 } else {
1052 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1053 nsEventStatus status;
1054 DispatchEvent(&event, status);
1058 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput& aInput) {
1059 MOZ_ASSERT(NS_IsMainThread());
1060 if (mAPZC) {
1061 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1062 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1064 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1065 return;
1067 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1068 ProcessUntransformedAPZEvent(&event, result);
1069 } else {
1070 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1071 nsEventStatus status;
1072 DispatchEvent(&event, status);
1076 nsIWidget::ContentAndAPZEventStatus nsBaseWidget::DispatchInputEvent(
1077 WidgetInputEvent* aEvent) {
1078 nsIWidget::ContentAndAPZEventStatus status;
1079 MOZ_ASSERT(NS_IsMainThread());
1080 if (mAPZC) {
1081 if (APZThreadUtils::IsControllerThread()) {
1082 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1083 status.mApzStatus = result.GetStatus();
1084 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1085 return status;
1087 status.mContentStatus = ProcessUntransformedAPZEvent(aEvent, result);
1088 return status;
1090 if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1091 RefPtr<Runnable> r =
1092 new DispatchInputOnControllerThread<ScrollWheelInput,
1093 WidgetWheelEvent>(*wheelEvent,
1094 mAPZC, this);
1095 APZThreadUtils::RunOnControllerThread(std::move(r));
1096 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1097 return status;
1099 if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1100 RefPtr<Runnable> r =
1101 new DispatchInputOnControllerThread<MouseInput, WidgetMouseEvent>(
1102 *mouseEvent, mAPZC, this);
1103 APZThreadUtils::RunOnControllerThread(std::move(r));
1104 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1105 return status;
1107 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
1108 RefPtr<Runnable> r =
1109 new DispatchInputOnControllerThread<MultiTouchInput,
1110 WidgetTouchEvent>(*touchEvent,
1111 mAPZC, this);
1112 APZThreadUtils::RunOnControllerThread(std::move(r));
1113 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1114 return status;
1116 // Allow dispatching keyboard events on Gecko thread.
1117 MOZ_ASSERT(aEvent->AsKeyboardEvent());
1120 DispatchEvent(aEvent, status.mContentStatus);
1121 return status;
1124 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent* aEvent) {
1125 MOZ_ASSERT(NS_IsMainThread());
1126 if (mAPZC) {
1127 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1128 mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1132 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent& event) {
1133 nsEventStatus status;
1134 DispatchEvent(&event, status);
1135 return ConvertStatus(status);
1138 Document* nsBaseWidget::GetDocument() const {
1139 if (mWidgetListener) {
1140 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1141 return presShell->GetDocument();
1144 return nullptr;
1147 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1148 // Parent directly listens to the vsync source whereas
1149 // child process communicate via IPC
1150 // Should be called AFTER gfxPlatform is initialized
1151 if (XRE_IsParentProcess()) {
1152 if (!mCompositorVsyncDispatcherLock) {
1153 mCompositorVsyncDispatcherLock =
1154 MakeUnique<Mutex>("mCompositorVsyncDispatcherLock");
1156 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1157 if (!mCompositorVsyncDispatcher) {
1158 mCompositorVsyncDispatcher = new CompositorVsyncDispatcher();
1163 already_AddRefed<CompositorVsyncDispatcher>
1164 nsBaseWidget::GetCompositorVsyncDispatcher() {
1165 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
1167 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1168 RefPtr<CompositorVsyncDispatcher> dispatcher = mCompositorVsyncDispatcher;
1169 return dispatcher.forget();
1172 already_AddRefed<WebRenderLayerManager> nsBaseWidget::CreateCompositorSession(
1173 int aWidth, int aHeight, CompositorOptions* aOptionsOut) {
1174 MOZ_ASSERT(aOptionsOut);
1176 do {
1177 CreateCompositorVsyncDispatcher();
1179 gfx::GPUProcessManager* gpu = gfx::GPUProcessManager::Get();
1180 // Make sure GPU process is ready for use.
1181 // If it failed to connect to GPU process, GPU process usage is disabled in
1182 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1183 gpu->EnsureGPUReady();
1185 // If widget type does not supports acceleration, we may be allowed to use
1186 // software WebRender instead. If not, then we use ClientLayerManager even
1187 // when gfxVars::UseWebRender() is true. WebRender could coexist only with
1188 // BasicCompositor.
1189 bool supportsAcceleration = WidgetTypeSupportsAcceleration();
1190 bool enableWR;
1191 bool enableSWWR;
1192 if (supportsAcceleration ||
1193 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1194 enableWR = gfx::gfxVars::UseWebRender();
1195 enableSWWR = gfx::gfxVars::UseSoftwareWebRender();
1196 } else {
1197 enableWR = enableSWWR = gfx::gfxVars::UseWebRender();
1199 MOZ_RELEASE_ASSERT(enableWR);
1200 bool enableAPZ = UseAPZ();
1201 CompositorOptions options(enableAPZ, enableSWWR);
1203 #ifdef XP_WIN
1204 if (supportsAcceleration) {
1205 options.SetAllowSoftwareWebRenderD3D11(
1206 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1208 #elif defined(MOZ_WIDGET_ANDROID)
1209 MOZ_ASSERT(supportsAcceleration);
1210 options.SetAllowSoftwareWebRenderOGL(
1211 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1212 #elif defined(MOZ_WIDGET_GTK)
1213 if (supportsAcceleration) {
1214 options.SetAllowSoftwareWebRenderOGL(
1215 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1217 #endif
1219 #ifdef MOZ_WIDGET_ANDROID
1220 // Unconditionally set the compositor as initially paused, as we have not
1221 // yet had a chance to send the compositor surface to the GPU process. We
1222 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1223 // where we will also resume the compositor if required.
1224 options.SetInitiallyPaused(true);
1225 #else
1226 options.SetInitiallyPaused(CompositorInitiallyPaused());
1227 #endif
1229 RefPtr<WebRenderLayerManager> lm = new WebRenderLayerManager(this);
1231 uint64_t innerWindowId = 0;
1232 if (Document* doc = GetDocument()) {
1233 innerWindowId = doc->InnerWindowID();
1236 bool retry = false;
1237 mCompositorSession = gpu->CreateTopLevelCompositor(
1238 this, lm, GetDefaultScale(), options, UseExternalCompositingSurface(),
1239 gfx::IntSize(aWidth, aHeight), innerWindowId, &retry);
1241 if (mCompositorSession) {
1242 TextureFactoryIdentifier textureFactoryIdentifier;
1243 nsCString error;
1244 lm->Initialize(mCompositorSession->GetCompositorBridgeChild(),
1245 wr::AsPipelineId(mCompositorSession->RootLayerTreeId()),
1246 &textureFactoryIdentifier, error);
1247 if (textureFactoryIdentifier.mParentBackend != LayersBackend::LAYERS_WR) {
1248 retry = true;
1249 DestroyCompositor();
1250 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1251 gfx::GPUProcessManager::Get()->DisableWebRender(
1252 wr::WebRenderError::INITIALIZE, error);
1256 // We need to retry in a loop because the act of failing to create the
1257 // compositor can change our state (e.g. disable WebRender).
1258 if (mCompositorSession || !retry) {
1259 *aOptionsOut = options;
1260 return lm.forget();
1262 } while (true);
1265 void nsBaseWidget::CreateCompositor(int aWidth, int aHeight) {
1266 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1267 gfxPlatform::GetPlatform();
1269 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1270 "This function assumes OMTC");
1272 MOZ_ASSERT(!mCompositorSession && !mCompositorBridgeChild,
1273 "Should have properly cleaned up the previous PCompositor pair "
1274 "beforehand");
1276 if (mCompositorBridgeChild) {
1277 mCompositorBridgeChild->Destroy();
1280 // Recreating this is tricky, as we may still have an old and we need
1281 // to make sure it's properly destroyed by calling DestroyCompositor!
1283 // If we've already received a shutdown notification, don't try
1284 // create a new compositor.
1285 if (!mShutdownObserver) {
1286 return;
1289 // The controller thread must be configured before the compositor
1290 // session is created, so that the input bridge runs on the right
1291 // thread.
1292 ConfigureAPZControllerThread();
1294 CompositorOptions options;
1295 RefPtr<WebRenderLayerManager> lm =
1296 CreateCompositorSession(aWidth, aHeight, &options);
1297 if (!lm) {
1298 return;
1301 MOZ_ASSERT(mCompositorSession);
1302 mCompositorBridgeChild = mCompositorSession->GetCompositorBridgeChild();
1303 SetCompositorWidgetDelegate(
1304 mCompositorSession->GetCompositorWidgetDelegate());
1306 if (options.UseAPZ()) {
1307 mAPZC = mCompositorSession->GetAPZCTreeManager();
1308 ConfigureAPZCTreeManager();
1309 } else {
1310 mAPZC = nullptr;
1313 if (mInitialZoomConstraints) {
1314 UpdateZoomConstraints(mInitialZoomConstraints->mPresShellID,
1315 mInitialZoomConstraints->mViewID,
1316 Some(mInitialZoomConstraints->mConstraints));
1317 mInitialZoomConstraints.reset();
1320 TextureFactoryIdentifier textureFactoryIdentifier =
1321 lm->GetTextureFactoryIdentifier();
1322 MOZ_ASSERT(textureFactoryIdentifier.mParentBackend ==
1323 LayersBackend::LAYERS_WR);
1324 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1325 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1327 WindowUsesOMTC();
1329 mWindowRenderer = std::move(lm);
1331 // Only track compositors for top-level windows, since other window types
1332 // may use the basic compositor. Except on the OS X - see bug 1306383
1333 #if defined(XP_MACOSX)
1334 bool getCompositorFromThisWindow = true;
1335 #else
1336 bool getCompositorFromThisWindow = (mWindowType == eWindowType_toplevel);
1337 #endif
1339 if (getCompositorFromThisWindow) {
1340 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1341 mWindowRenderer->GetCompositorBackendType());
1345 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession* aSession) {
1346 MOZ_ASSERT(aSession == mCompositorSession);
1347 DestroyLayerManager();
1350 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1351 return gfxPlatform::UsesOffMainThreadCompositing();
1354 WindowRenderer* nsBaseWidget::GetWindowRenderer() {
1355 if (!mWindowRenderer) {
1356 if (!mShutdownObserver) {
1357 // We are shutting down, do not try to re-create a LayerManager
1358 return nullptr;
1360 // Try to use an async compositor first, if possible
1361 if (ShouldUseOffMainThreadCompositing()) {
1362 CreateCompositor();
1365 if (!mWindowRenderer) {
1366 mWindowRenderer = CreateFallbackRenderer();
1369 return mWindowRenderer;
1372 WindowRenderer* nsBaseWidget::CreateFallbackRenderer() {
1373 return new FallbackRenderer;
1376 CompositorBridgeChild* nsBaseWidget::GetRemoteRenderer() {
1377 return mCompositorBridgeChild;
1380 void nsBaseWidget::ClearCachedWebrenderResources() {
1381 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
1382 return;
1384 mWindowRenderer->AsWebRender()->ClearCachedResources();
1387 already_AddRefed<gfx::DrawTarget> nsBaseWidget::StartRemoteDrawing() {
1388 return nullptr;
1391 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA; }
1393 //-------------------------------------------------------------------------
1395 // Destroy the window
1397 //-------------------------------------------------------------------------
1398 void nsBaseWidget::OnDestroy() {
1399 if (mTextEventDispatcher) {
1400 mTextEventDispatcher->OnDestroyWidget();
1401 // Don't release it until this widget actually released because after this
1402 // is called, TextEventDispatcher() may create it again.
1405 // If this widget is being destroyed, let the APZ code know to drop references
1406 // to this widget. Callers of this function all should be holding a deathgrip
1407 // on this widget already.
1408 ReleaseContentController();
1411 void nsBaseWidget::MoveClient(const DesktopPoint& aOffset) {
1412 LayoutDeviceIntPoint clientOffset(GetClientOffset());
1414 // GetClientOffset returns device pixels; scale back to desktop pixels
1415 // if that's what this widget uses for the Move/Resize APIs
1416 if (BoundsUseDesktopPixels()) {
1417 DesktopPoint desktopOffset = clientOffset / GetDesktopToDeviceScale();
1418 Move(aOffset.x - desktopOffset.x, aOffset.y - desktopOffset.y);
1419 } else {
1420 LayoutDevicePoint layoutOffset = aOffset * GetDesktopToDeviceScale();
1421 Move(layoutOffset.x - clientOffset.x, layoutOffset.y - clientOffset.y);
1425 void nsBaseWidget::ResizeClient(const DesktopSize& aSize, bool aRepaint) {
1426 NS_ASSERTION((aSize.width >= 0), "Negative width passed to ResizeClient");
1427 NS_ASSERTION((aSize.height >= 0), "Negative height passed to ResizeClient");
1429 LayoutDeviceIntRect clientBounds = GetClientBounds();
1431 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1432 // if that's what this widget uses for the Move/Resize APIs
1433 if (BoundsUseDesktopPixels()) {
1434 DesktopSize desktopDelta =
1435 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1436 clientBounds.Size()) /
1437 GetDesktopToDeviceScale();
1438 Resize(aSize.width + desktopDelta.width, aSize.height + desktopDelta.height,
1439 aRepaint);
1440 } else {
1441 LayoutDeviceSize layoutSize = aSize * GetDesktopToDeviceScale();
1442 Resize(mBounds.Width() + (layoutSize.width - clientBounds.Width()),
1443 mBounds.Height() + (layoutSize.height - clientBounds.Height()),
1444 aRepaint);
1448 void nsBaseWidget::ResizeClient(const DesktopRect& aRect, bool aRepaint) {
1449 NS_ASSERTION((aRect.Width() >= 0), "Negative width passed to ResizeClient");
1450 NS_ASSERTION((aRect.Height() >= 0), "Negative height passed to ResizeClient");
1452 LayoutDeviceIntRect clientBounds = GetClientBounds();
1453 LayoutDeviceIntPoint clientOffset = GetClientOffset();
1454 DesktopToLayoutDeviceScale scale = GetDesktopToDeviceScale();
1456 if (BoundsUseDesktopPixels()) {
1457 DesktopPoint desktopOffset = clientOffset / scale;
1458 DesktopSize desktopDelta =
1459 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1460 clientBounds.Size()) /
1461 scale;
1462 Resize(aRect.X() - desktopOffset.x, aRect.Y() - desktopOffset.y,
1463 aRect.Width() + desktopDelta.width,
1464 aRect.Height() + desktopDelta.height, aRepaint);
1465 } else {
1466 LayoutDeviceRect layoutRect = aRect * scale;
1467 Resize(layoutRect.X() - clientOffset.x, layoutRect.Y() - clientOffset.y,
1468 layoutRect.Width() + mBounds.Width() - clientBounds.Width(),
1469 layoutRect.Height() + mBounds.Height() - clientBounds.Height(),
1470 aRepaint);
1474 //-------------------------------------------------------------------------
1476 // Bounds
1478 //-------------------------------------------------------------------------
1481 * If the implementation of nsWindow supports borders this method MUST be
1482 * overridden
1485 LayoutDeviceIntRect nsBaseWidget::GetClientBounds() { return GetBounds(); }
1488 * If the implementation of nsWindow supports borders this method MUST be
1489 * overridden
1492 LayoutDeviceIntRect nsBaseWidget::GetBounds() { return mBounds; }
1495 * If the implementation of nsWindow uses a local coordinate system within the
1496 *window, this method must be overridden
1499 LayoutDeviceIntRect nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1501 nsresult nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect& aRect) {
1502 if (SizeMode() != nsSizeMode_Normal) {
1503 return NS_ERROR_FAILURE;
1505 aRect = GetScreenBounds();
1506 return NS_OK;
1509 LayoutDeviceIntPoint nsBaseWidget::GetClientOffset() {
1510 return LayoutDeviceIntPoint(0, 0);
1513 nsresult nsBaseWidget::SetNonClientMargins(LayoutDeviceIntMargin& margins) {
1514 return NS_ERROR_NOT_IMPLEMENTED;
1517 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin) {}
1519 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1521 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1523 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect* aResizerRect) {
1524 return false;
1528 * Modifies aFile to point at an icon file with the given name and suffix. The
1529 * suffix may correspond to a file extension with leading '.' if appropriate.
1530 * Returns true if the icon file exists and can be read.
1532 static bool ResolveIconNameHelper(nsIFile* aFile, const nsAString& aIconName,
1533 const nsAString& aIconSuffix) {
1534 aFile->Append(u"icons"_ns);
1535 aFile->Append(u"default"_ns);
1536 aFile->Append(aIconName + aIconSuffix);
1538 bool readable;
1539 return NS_SUCCEEDED(aFile->IsReadable(&readable)) && readable;
1543 * Resolve the given icon name into a local file object. This method is
1544 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1545 * platform specific icon file suffix (e.g., ".ico" under Win32).
1547 * If no file is found matching the given parameters, then null is returned.
1549 void nsBaseWidget::ResolveIconName(const nsAString& aIconName,
1550 const nsAString& aIconSuffix,
1551 nsIFile** aResult) {
1552 *aResult = nullptr;
1554 nsCOMPtr<nsIProperties> dirSvc =
1555 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
1556 if (!dirSvc) return;
1558 // first check auxilary chrome directories
1560 nsCOMPtr<nsISimpleEnumerator> dirs;
1561 dirSvc->Get(NS_APP_CHROME_DIR_LIST, NS_GET_IID(nsISimpleEnumerator),
1562 getter_AddRefs(dirs));
1563 if (dirs) {
1564 bool hasMore;
1565 while (NS_SUCCEEDED(dirs->HasMoreElements(&hasMore)) && hasMore) {
1566 nsCOMPtr<nsISupports> element;
1567 dirs->GetNext(getter_AddRefs(element));
1568 if (!element) continue;
1569 nsCOMPtr<nsIFile> file = do_QueryInterface(element);
1570 if (!file) continue;
1571 if (ResolveIconNameHelper(file, aIconName, aIconSuffix)) {
1572 NS_ADDREF(*aResult = file);
1573 return;
1578 // then check the main app chrome directory
1580 nsCOMPtr<nsIFile> file;
1581 dirSvc->Get(NS_APP_CHROME_DIR, NS_GET_IID(nsIFile), getter_AddRefs(file));
1582 if (file && ResolveIconNameHelper(file, aIconName, aIconSuffix))
1583 NS_ADDREF(*aResult = file);
1586 void nsBaseWidget::SetSizeConstraints(const SizeConstraints& aConstraints) {
1587 mSizeConstraints = aConstraints;
1589 // Popups are constrained during layout, and we don't want to synchronously
1590 // paint from reflow, so bail out... This is not great, but it's no worse than
1591 // what we used to do.
1593 // The right fix here is probably making constraint changes go through the
1594 // view manager and such.
1595 if (mWindowType == eWindowType_popup) {
1596 return;
1599 // If the current size doesn't meet the new constraints, trigger a
1600 // resize to apply it. Note that, we don't want to invoke Resize if
1601 // the new constraints don't affect the current size, because Resize
1602 // implementation on some platforms may touch other geometry even if
1603 // the size don't need to change.
1604 LayoutDeviceIntSize curSize = mBounds.Size();
1605 LayoutDeviceIntSize clampedSize =
1606 Max(aConstraints.mMinSize, Min(aConstraints.mMaxSize, curSize));
1607 if (clampedSize != curSize) {
1608 gfx::Size size;
1609 if (BoundsUseDesktopPixels()) {
1610 DesktopSize desktopSize = clampedSize / GetDesktopToDeviceScale();
1611 size = desktopSize.ToUnknownSize();
1612 } else {
1613 size = gfx::Size(clampedSize.ToUnknownSize());
1615 Resize(size.width, size.height, true);
1619 const widget::SizeConstraints nsBaseWidget::GetSizeConstraints() {
1620 return mSizeConstraints;
1623 // static
1624 nsIRollupListener* nsBaseWidget::GetActiveRollupListener() {
1625 // If set, then this is likely an <html:select> dropdown.
1626 if (gRollupListener) return gRollupListener;
1628 return nsXULPopupManager::GetInstance();
1631 void nsBaseWidget::NotifyWindowDestroyed() {
1632 if (!mWidgetListener) return;
1634 nsCOMPtr<nsIAppWindow> window = mWidgetListener->GetAppWindow();
1635 nsCOMPtr<nsIBaseWindow> appWindow(do_QueryInterface(window));
1636 if (appWindow) {
1637 appWindow->Destroy();
1641 void nsBaseWidget::NotifyWindowMoved(int32_t aX, int32_t aY) {
1642 if (mWidgetListener) {
1643 mWidgetListener->WindowMoved(this, aX, aY);
1646 if (mIMEHasFocus && IMENotificationRequestsRef().WantPositionChanged()) {
1647 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE));
1651 void nsBaseWidget::NotifySizeMoveDone() {
1652 if (!mWidgetListener) {
1653 return;
1655 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1656 presShell->WindowSizeMoveDone();
1660 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind) {
1661 LookAndFeel::NotifyChangedAllWindows(aKind);
1664 void nsBaseWidget::NotifyUIStateChanged(UIStateChangeType aShowFocusRings) {
1665 if (Document* doc = GetDocument()) {
1666 if (nsPIDOMWindowOuter* win = doc->GetWindow()) {
1667 win->SetKeyboardIndicators(aShowFocusRings);
1672 nsresult nsBaseWidget::NotifyIME(const IMENotification& aIMENotification) {
1673 if (mIMEHasQuit) {
1674 return NS_OK;
1676 switch (aIMENotification.mMessage) {
1677 case REQUEST_TO_COMMIT_COMPOSITION:
1678 case REQUEST_TO_CANCEL_COMPOSITION:
1679 // We should send request to IME only when there is a TextEventDispatcher
1680 // instance (this means that this widget has dispatched at least one
1681 // composition event or keyboard event) and the it has composition.
1682 // Otherwise, there is nothing to do.
1683 // Note that if current input transaction is for native input events,
1684 // TextEventDispatcher::NotifyIME() will call
1685 // TextEventDispatcherListener::NotifyIME().
1686 if (mTextEventDispatcher && mTextEventDispatcher->IsComposing()) {
1687 return mTextEventDispatcher->NotifyIME(aIMENotification);
1689 return NS_OK;
1690 default: {
1691 if (aIMENotification.mMessage == NOTIFY_IME_OF_FOCUS) {
1692 mIMEHasFocus = true;
1694 EnsureTextEventDispatcher();
1695 // TextEventDispatcher::NotifyIME() will always call
1696 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1697 // input transaction is for synthesized events for automated tests,
1698 // notifications will be sent to native IME.
1699 nsresult rv = mTextEventDispatcher->NotifyIME(aIMENotification);
1700 if (aIMENotification.mMessage == NOTIFY_IME_OF_BLUR) {
1701 mIMEHasFocus = false;
1703 return rv;
1708 void nsBaseWidget::EnsureTextEventDispatcher() {
1709 if (mTextEventDispatcher) {
1710 return;
1712 mTextEventDispatcher = new TextEventDispatcher(this);
1715 nsIWidget::NativeIMEContext nsBaseWidget::GetNativeIMEContext() {
1716 if (mTextEventDispatcher && mTextEventDispatcher->GetPseudoIMEContext()) {
1717 // If we already have a TextEventDispatcher and it's working with
1718 // a TextInputProcessor, we need to return pseudo IME context since
1719 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1720 // on the pseudo IME context in such case.
1721 NativeIMEContext pseudoIMEContext;
1722 pseudoIMEContext.InitWithRawNativeIMEContext(
1723 mTextEventDispatcher->GetPseudoIMEContext());
1724 return pseudoIMEContext;
1726 return NativeIMEContext(this);
1729 nsIWidget::TextEventDispatcher* nsBaseWidget::GetTextEventDispatcher() {
1730 EnsureTextEventDispatcher();
1731 return mTextEventDispatcher;
1734 void* nsBaseWidget::GetPseudoIMEContext() {
1735 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
1736 if (!dispatcher) {
1737 return nullptr;
1739 return dispatcher->GetPseudoIMEContext();
1742 TextEventDispatcherListener*
1743 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1744 // TODO: If all platforms supported use of TextEventDispatcher for handling
1745 // native IME and keyboard events, this method should be removed since
1746 // in such case, this is overridden by all the subclasses.
1747 return nullptr;
1750 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId,
1751 const ScrollableLayerGuid::ViewID& aViewId,
1752 const CSSRect& aRect, const uint32_t& aFlags) {
1753 if (!mCompositorSession || !mAPZC) {
1754 return;
1756 LayersId layerId = mCompositorSession->RootLayerTreeId();
1757 mAPZC->ZoomToRect(ScrollableLayerGuid(layerId, aPresShellId, aViewId),
1758 ZoomTarget{aRect}, aFlags);
1761 #ifdef ACCESSIBILITY
1763 a11y::LocalAccessible* nsBaseWidget::GetRootAccessible() {
1764 NS_ENSURE_TRUE(mWidgetListener, nullptr);
1766 PresShell* presShell = mWidgetListener->GetPresShell();
1767 NS_ENSURE_TRUE(presShell, nullptr);
1769 // If container is null then the presshell is not active. This often happens
1770 // when a preshell is being held onto for fastback.
1771 nsPresContext* presContext = presShell->GetPresContext();
1772 NS_ENSURE_TRUE(presContext->GetContainerWeak(), nullptr);
1774 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1775 // make sure it's not created at unsafe times.
1776 nsAccessibilityService* accService = GetOrCreateAccService();
1777 if (accService) {
1778 return accService->GetRootDocumentAccessible(
1779 presShell, nsContentUtils::IsSafeToRunScript());
1782 return nullptr;
1785 #endif // ACCESSIBILITY
1787 void nsBaseWidget::StartAsyncScrollbarDrag(
1788 const AsyncDragMetrics& aDragMetrics) {
1789 if (!AsyncPanZoomEnabled()) {
1790 return;
1793 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession);
1795 LayersId layersId = mCompositorSession->RootLayerTreeId();
1796 ScrollableLayerGuid guid(layersId, aDragMetrics.mPresShellId,
1797 aDragMetrics.mViewId);
1799 mAPZC->StartScrollbarDrag(guid, aDragMetrics);
1802 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
1803 const ScrollableLayerGuid& aGuid) {
1804 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1806 return mAPZC->StartAutoscroll(aGuid, aAnchorLocation);
1809 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid& aGuid) {
1810 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1812 mAPZC->StopAutoscroll(aGuid);
1815 LayersId nsBaseWidget::GetRootLayerTreeId() {
1816 return mCompositorSession ? mCompositorSession->RootLayerTreeId()
1817 : LayersId{0};
1820 already_AddRefed<nsIScreen> nsBaseWidget::GetWidgetScreen() {
1821 nsCOMPtr<nsIScreenManager> screenManager;
1822 screenManager = do_GetService("@mozilla.org/gfx/screenmanager;1");
1823 if (!screenManager) {
1824 return nullptr;
1827 LayoutDeviceIntRect bounds = GetScreenBounds();
1828 DesktopIntRect deskBounds = RoundedToInt(bounds / GetDesktopToDeviceScale());
1829 nsCOMPtr<nsIScreen> screen;
1830 screenManager->ScreenForRect(deskBounds.X(), deskBounds.Y(),
1831 deskBounds.Width(), deskBounds.Height(),
1832 getter_AddRefs(screen));
1833 return screen.forget();
1836 mozilla::DesktopToLayoutDeviceScale
1837 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
1838 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
1839 ->GetDesktopToDeviceScale();
1842 nsresult nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint,
1843 bool aLongTap,
1844 nsIObserver* aObserver) {
1845 AutoObserverNotifier notifier(aObserver, "touchtap");
1847 if (sPointerIdCounter > TOUCH_INJECT_MAX_POINTS) {
1848 sPointerIdCounter = 0;
1850 int pointerId = sPointerIdCounter;
1851 sPointerIdCounter++;
1852 nsresult rv = SynthesizeNativeTouchPoint(pointerId, TOUCH_CONTACT, aPoint,
1853 1.0, 90, nullptr);
1854 if (NS_FAILED(rv)) {
1855 return rv;
1858 if (!aLongTap) {
1859 return SynthesizeNativeTouchPoint(pointerId, TOUCH_REMOVE, aPoint, 0, 0,
1860 nullptr);
1863 // initiate a long tap
1864 int elapse = Preferences::GetInt("ui.click_hold_context_menus.delay",
1865 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC);
1866 if (!mLongTapTimer) {
1867 mLongTapTimer = NS_NewTimer();
1868 if (!mLongTapTimer) {
1869 SynthesizeNativeTouchPoint(pointerId, TOUCH_CANCEL, aPoint, 0, 0,
1870 nullptr);
1871 return NS_ERROR_UNEXPECTED;
1873 // Windows requires recuring events, so we set this to a smaller window
1874 // than the pref value.
1875 int timeout = elapse;
1876 if (timeout > TOUCH_INJECT_PUMP_TIMER_MSEC) {
1877 timeout = TOUCH_INJECT_PUMP_TIMER_MSEC;
1879 mLongTapTimer->InitWithNamedFuncCallback(
1880 OnLongTapTimerCallback, this, timeout, nsITimer::TYPE_REPEATING_SLACK,
1881 "nsIWidget::SynthesizeNativeTouchTap");
1884 // If we already have a long tap pending, cancel it. We only allow one long
1885 // tap to be active at a time.
1886 if (mLongTapTouchPoint) {
1887 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1888 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1891 mLongTapTouchPoint = MakeUnique<LongTapInfo>(
1892 pointerId, aPoint, TimeDuration::FromMilliseconds(elapse), aObserver);
1893 notifier.SkipNotification(); // we'll do it in the long-tap callback
1894 return NS_OK;
1897 // static
1898 void nsIWidget::OnLongTapTimerCallback(nsITimer* aTimer, void* aClosure) {
1899 auto* self = static_cast<nsIWidget*>(aClosure);
1901 if ((self->mLongTapTouchPoint->mStamp + self->mLongTapTouchPoint->mDuration) >
1902 TimeStamp::Now()) {
1903 #ifdef XP_WIN
1904 // Windows needs us to keep pumping feedback to the digitizer, so update
1905 // the pointer id with the same position.
1906 self->SynthesizeNativeTouchPoint(
1907 self->mLongTapTouchPoint->mPointerId, TOUCH_CONTACT,
1908 self->mLongTapTouchPoint->mPosition, 1.0, 90, nullptr);
1909 #endif
1910 return;
1913 AutoObserverNotifier notifier(self->mLongTapTouchPoint->mObserver,
1914 "touchtap");
1916 // finished, remove the touch point
1917 self->mLongTapTimer->Cancel();
1918 self->mLongTapTimer = nullptr;
1919 self->SynthesizeNativeTouchPoint(
1920 self->mLongTapTouchPoint->mPointerId, TOUCH_REMOVE,
1921 self->mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1922 self->mLongTapTouchPoint = nullptr;
1925 nsresult nsIWidget::ClearNativeTouchSequence(nsIObserver* aObserver) {
1926 AutoObserverNotifier notifier(aObserver, "cleartouch");
1928 if (!mLongTapTimer) {
1929 return NS_OK;
1931 mLongTapTimer->Cancel();
1932 mLongTapTimer = nullptr;
1933 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1934 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1935 mLongTapTouchPoint = nullptr;
1936 return NS_OK;
1939 MultiTouchInput nsBaseWidget::UpdateSynthesizedTouchState(
1940 MultiTouchInput* aState, uint32_t aTime, mozilla::TimeStamp aTimeStamp,
1941 uint32_t aPointerId, TouchPointerState aPointerState,
1942 LayoutDeviceIntPoint aPoint, double aPointerPressure,
1943 uint32_t aPointerOrientation) {
1944 ScreenIntPoint pointerScreenPoint = ViewAs<ScreenPixel>(
1945 aPoint, PixelCastJustification::LayoutDeviceIsScreenForBounds);
1947 // We can't dispatch *aState directly because (a) dispatching
1948 // it might inadvertently modify it and (b) in the case of touchend or
1949 // touchcancel events aState will hold the touches that are
1950 // still down whereas the input dispatched needs to hold the removed
1951 // touch(es). We use |inputToDispatch| for this purpose.
1952 MultiTouchInput inputToDispatch;
1953 inputToDispatch.mInputType = MULTITOUCH_INPUT;
1954 inputToDispatch.mTime = aTime;
1955 inputToDispatch.mTimeStamp = aTimeStamp;
1957 int32_t index = aState->IndexOfTouch((int32_t)aPointerId);
1958 if (aPointerState == TOUCH_CONTACT) {
1959 if (index >= 0) {
1960 // found an existing touch point, update it
1961 SingleTouchData& point = aState->mTouches[index];
1962 point.mScreenPoint = pointerScreenPoint;
1963 point.mRotationAngle = (float)aPointerOrientation;
1964 point.mForce = (float)aPointerPressure;
1965 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_MOVE;
1966 } else {
1967 // new touch point, add it
1968 aState->mTouches.AppendElement(SingleTouchData(
1969 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
1970 (float)aPointerOrientation, (float)aPointerPressure));
1971 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_START;
1973 inputToDispatch.mTouches = aState->mTouches;
1974 } else {
1975 MOZ_ASSERT(aPointerState == TOUCH_REMOVE || aPointerState == TOUCH_CANCEL);
1976 // a touch point is being lifted, so remove it from the stored list
1977 if (index >= 0) {
1978 aState->mTouches.RemoveElementAt(index);
1980 inputToDispatch.mType =
1981 (aPointerState == TOUCH_REMOVE ? MultiTouchInput::MULTITOUCH_END
1982 : MultiTouchInput::MULTITOUCH_CANCEL);
1983 inputToDispatch.mTouches.AppendElement(SingleTouchData(
1984 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
1985 (float)aPointerOrientation, (float)aPointerPressure));
1988 return inputToDispatch;
1991 void nsBaseWidget::NotifyLiveResizeStarted() {
1992 // If we have mLiveResizeListeners already non-empty, we should notify those
1993 // listeners that the resize stopped before starting anew. In theory this
1994 // should never happen because we shouldn't get nested live resize actions.
1995 NotifyLiveResizeStopped();
1996 MOZ_ASSERT(mLiveResizeListeners.IsEmpty());
1998 // If we can get the active remote tab for the current widget, suppress
1999 // the displayport on it during the live resize.
2000 if (!mWidgetListener) {
2001 return;
2003 nsCOMPtr<nsIAppWindow> appWindow = mWidgetListener->GetAppWindow();
2004 if (!appWindow) {
2005 return;
2007 mLiveResizeListeners = appWindow->GetLiveResizeListeners();
2008 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2009 mLiveResizeListeners[i]->LiveResizeStarted();
2013 void nsBaseWidget::NotifyLiveResizeStopped() {
2014 if (!mLiveResizeListeners.IsEmpty()) {
2015 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2016 mLiveResizeListeners[i]->LiveResizeStopped();
2018 mLiveResizeListeners.Clear();
2022 nsresult nsBaseWidget::AsyncEnableDragDrop(bool aEnable) {
2023 RefPtr<nsBaseWidget> kungFuDeathGrip = this;
2024 return NS_DispatchToCurrentThreadQueue(
2025 NS_NewRunnableFunction(
2026 "AsyncEnableDragDropFn",
2027 [this, aEnable, kungFuDeathGrip]() { EnableDragDrop(aEnable); }),
2028 kAsyncDragDropTimeout, EventQueuePriority::Idle);
2031 void nsBaseWidget::SwipeFinished() { mSwipeTracker = nullptr; }
2033 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId,
2034 bool aStartSwipe) {
2035 if (mSwipeEventQueue && mSwipeEventQueue->inputBlockId == aInputBlockId) {
2036 if (aStartSwipe) {
2037 PanGestureInput& startEvent = mSwipeEventQueue->queuedEvents[0];
2038 TrackScrollEventAsSwipe(startEvent, mSwipeEventQueue->allowedDirections);
2039 for (size_t i = 1; i < mSwipeEventQueue->queuedEvents.Length(); i++) {
2040 mSwipeTracker->ProcessEvent(mSwipeEventQueue->queuedEvents[i]);
2043 mSwipeEventQueue = nullptr;
2047 void nsBaseWidget::TrackScrollEventAsSwipe(
2048 const mozilla::PanGestureInput& aSwipeStartEvent,
2049 uint32_t aAllowedDirections) {
2050 // If a swipe is currently being tracked kill it -- it's been interrupted
2051 // by another gesture event.
2052 if (mSwipeTracker) {
2053 mSwipeTracker->CancelSwipe(aSwipeStartEvent.mTimeStamp);
2054 mSwipeTracker->Destroy();
2055 mSwipeTracker = nullptr;
2058 uint32_t direction =
2059 (aSwipeStartEvent.mPanDisplacement.x > 0.0)
2060 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2061 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT;
2063 mSwipeTracker =
2064 new SwipeTracker(*this, aSwipeStartEvent, aAllowedDirections, direction);
2066 if (!mAPZC) {
2067 mCurrentPanGestureBelongsToSwipe = true;
2071 nsBaseWidget::SwipeInfo nsBaseWidget::SendMayStartSwipe(
2072 const mozilla::PanGestureInput& aSwipeStartEvent) {
2073 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
2075 uint32_t direction =
2076 (aSwipeStartEvent.mPanDisplacement.x > 0.0)
2077 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2078 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT;
2080 // We're ready to start the animation. Tell Gecko about it, and at the same
2081 // time ask it if it really wants to start an animation for this event.
2082 // This event also reports back the directions that we can swipe in.
2083 LayoutDeviceIntPoint position = RoundedToInt(aSwipeStartEvent.mPanStartPoint *
2084 ScreenToLayoutDeviceScale(1));
2085 WidgetSimpleGestureEvent geckoEvent = SwipeTracker::CreateSwipeGestureEvent(
2086 eSwipeGestureMayStart, this, position, aSwipeStartEvent.mTimeStamp);
2087 geckoEvent.mDirection = direction;
2088 geckoEvent.mDelta = 0.0;
2089 geckoEvent.mAllowedDirections = 0;
2090 bool shouldStartSwipe =
2091 DispatchWindowEvent(geckoEvent); // event cancelled == swipe should start
2093 SwipeInfo result = {shouldStartSwipe, geckoEvent.mAllowedDirections};
2094 return result;
2097 WidgetWheelEvent nsBaseWidget::MayStartSwipeForAPZ(
2098 const PanGestureInput& aPanInput, const APZEventResult& aApzResult,
2099 CanTriggerSwipe aCanTriggerSwipe) {
2100 WidgetWheelEvent event = aPanInput.ToWidgetEvent(this);
2101 if (aCanTriggerSwipe == CanTriggerSwipe::Yes &&
2102 aPanInput.mOverscrollBehaviorAllowsSwipe) {
2103 SwipeInfo swipeInfo = SendMayStartSwipe(aPanInput);
2104 event.mCanTriggerSwipe = swipeInfo.wantsSwipe;
2105 if (swipeInfo.wantsSwipe) {
2106 if (aApzResult.GetStatus() == nsEventStatus_eIgnore) {
2107 // APZ has determined and that scrolling horizontally in the
2108 // requested direction is impossible, so it didn't do any
2109 // scrolling for the event.
2110 // We know now that MayStartSwipe wants a swipe, so we can start
2111 // the swipe now.
2112 TrackScrollEventAsSwipe(aPanInput, swipeInfo.allowedDirections);
2113 } else {
2114 // We don't know whether this event can start a swipe, so we need
2115 // to queue up events and wait for a call to ReportSwipeStarted.
2116 // APZ might already have started scrolling in response to the
2117 // event if it knew that it's the right thing to do. In that case
2118 // we'll still get a call to ReportSwipeStarted, and we will
2119 // discard the queued events at that point.
2120 mSwipeEventQueue = MakeUnique<SwipeEventQueue>(
2121 swipeInfo.allowedDirections, aApzResult.mInputBlockId);
2126 if (mSwipeEventQueue &&
2127 mSwipeEventQueue->inputBlockId == aApzResult.mInputBlockId) {
2128 mSwipeEventQueue->queuedEvents.AppendElement(aPanInput);
2131 return event;
2134 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput& aPanInput,
2135 CanTriggerSwipe aCanTriggerSwipe) {
2136 if (aPanInput.mType == PanGestureInput::PANGESTURE_MAYSTART ||
2137 aPanInput.mType == PanGestureInput::PANGESTURE_START) {
2138 mCurrentPanGestureBelongsToSwipe = false;
2140 if (mCurrentPanGestureBelongsToSwipe) {
2141 // Ignore this event. It's a momentum event from a scroll gesture
2142 // that was processed as a swipe, and the swipe animation has
2143 // already finished (so mSwipeTracker is already null).
2144 MOZ_ASSERT(aPanInput.IsMomentum(),
2145 "If the fingers are still on the touchpad, we should still have "
2146 "a SwipeTracker, "
2147 "and it should have consumed this event.");
2148 return true;
2151 if (aCanTriggerSwipe == CanTriggerSwipe::No) {
2152 return false;
2155 SwipeInfo swipeInfo = SendMayStartSwipe(aPanInput);
2157 // We're in the non-APZ case here, but we still want to know whether
2158 // the event was routed to a child process, so we use InputAPZContext
2159 // to get that piece of information.
2160 ScrollableLayerGuid guid;
2161 InputAPZContext context(guid, 0, nsEventStatus_eIgnore);
2163 WidgetWheelEvent event = aPanInput.ToWidgetEvent(this);
2164 event.mCanTriggerSwipe = swipeInfo.wantsSwipe;
2165 nsEventStatus status;
2166 DispatchEvent(&event, status);
2167 if (swipeInfo.wantsSwipe) {
2168 if (context.WasRoutedToChildProcess()) {
2169 // We don't know whether this event can start a swipe, so we need
2170 // to queue up events and wait for a call to ReportSwipeStarted.
2171 mSwipeEventQueue =
2172 MakeUnique<SwipeEventQueue>(swipeInfo.allowedDirections, 0);
2173 } else if (event.TriggersSwipe()) {
2174 TrackScrollEventAsSwipe(aPanInput, swipeInfo.allowedDirections);
2178 if (mSwipeEventQueue && mSwipeEventQueue->inputBlockId == 0) {
2179 mSwipeEventQueue->queuedEvents.AppendElement(aPanInput);
2182 return true;
2185 const IMENotificationRequests& nsIWidget::IMENotificationRequestsRef() {
2186 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
2187 return dispatcher->IMENotificationRequestsRef();
2190 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent* aEvent) {}
2192 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType,
2193 const WidgetKeyboardEvent& aEvent,
2194 nsTArray<CommandInt>& aCommands) {
2195 MOZ_ASSERT(aEvent.IsTrusted());
2196 MOZ_ASSERT(aCommands.IsEmpty());
2197 return true;
2200 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboard() {
2201 if (XRE_IsContentProcess()) {
2202 return CreateBidiKeyboardContentProcess();
2204 return CreateBidiKeyboardInner();
2207 #ifdef ANDROID
2208 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboardInner() {
2209 // no bidi keyboard implementation
2210 return nullptr;
2212 #endif
2214 namespace mozilla::widget {
2216 const char* ToChar(InputContext::Origin aOrigin) {
2217 switch (aOrigin) {
2218 case InputContext::ORIGIN_MAIN:
2219 return "ORIGIN_MAIN";
2220 case InputContext::ORIGIN_CONTENT:
2221 return "ORIGIN_CONTENT";
2222 default:
2223 return "Unexpected value";
2227 const char* ToChar(IMEMessage aIMEMessage) {
2228 switch (aIMEMessage) {
2229 case NOTIFY_IME_OF_NOTHING:
2230 return "NOTIFY_IME_OF_NOTHING";
2231 case NOTIFY_IME_OF_FOCUS:
2232 return "NOTIFY_IME_OF_FOCUS";
2233 case NOTIFY_IME_OF_BLUR:
2234 return "NOTIFY_IME_OF_BLUR";
2235 case NOTIFY_IME_OF_SELECTION_CHANGE:
2236 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2237 case NOTIFY_IME_OF_TEXT_CHANGE:
2238 return "NOTIFY_IME_OF_TEXT_CHANGE";
2239 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED:
2240 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2241 case NOTIFY_IME_OF_POSITION_CHANGE:
2242 return "NOTIFY_IME_OF_POSITION_CHANGE";
2243 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
2244 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2245 case REQUEST_TO_COMMIT_COMPOSITION:
2246 return "REQUEST_TO_COMMIT_COMPOSITION";
2247 case REQUEST_TO_CANCEL_COMPOSITION:
2248 return "REQUEST_TO_CANCEL_COMPOSITION";
2249 default:
2250 return "Unexpected value";
2254 void NativeIMEContext::Init(nsIWidget* aWidget) {
2255 if (!aWidget) {
2256 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2257 mOriginProcessID = static_cast<uint64_t>(-1);
2258 return;
2260 if (!XRE_IsContentProcess()) {
2261 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(
2262 aWidget->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT));
2263 mOriginProcessID = 0;
2264 return;
2266 // If this is created in a child process, aWidget is an instance of
2267 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2268 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2269 // native IME context of the parent process.
2270 *this = aWidget->GetNativeIMEContext();
2273 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext) {
2274 if (NS_WARN_IF(!aRawNativeIMEContext)) {
2275 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2276 mOriginProcessID = static_cast<uint64_t>(-1);
2277 return;
2279 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(aRawNativeIMEContext);
2280 mOriginProcessID =
2281 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2284 void IMENotification::TextChangeDataBase::MergeWith(
2285 const IMENotification::TextChangeDataBase& aOther) {
2286 MOZ_ASSERT(aOther.IsValid(), "Merging data must store valid data");
2287 MOZ_ASSERT(aOther.mStartOffset <= aOther.mRemovedEndOffset,
2288 "end of removed text must be same or larger than start");
2289 MOZ_ASSERT(aOther.mStartOffset <= aOther.mAddedEndOffset,
2290 "end of added text must be same or larger than start");
2292 if (!IsValid()) {
2293 *this = aOther;
2294 return;
2297 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2298 // text ranges. I.e., mStartOffset should be the smallest offset of all
2299 // modified text ranges in old text. |mRemovedEndOffset| should be the
2300 // largest end offset in old text of all modified text ranges.
2301 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2302 // I.e., only this is an offset in new text.
2303 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2304 // premodified text was already removed. And some text whose length is
2305 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2306 // this allows IME to mark dirty the modified text range with |mStartOffset|
2307 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2308 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2309 // Additionally, IME can retrieve only the text between |mStartOffset| and
2310 // |mAddedEndOffset| for updating stored text.
2312 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2313 // should be adjusted to be in same text. The |newData.mStartOffset| and
2314 // |newData.mRemovedEndOffset| should be computed as in old text because
2315 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2316 // in the old text but even if some text before the values of the newData
2317 // has already been modified, the values don't include the changes.
2319 // For comparing new and old |mAddedEndOffset| values, they should be
2320 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2321 // computed as in the new text because |mAddedEndOffset| indicates the end
2322 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2323 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2325 const TextChangeDataBase& newData = aOther;
2326 const TextChangeDataBase oldData = *this;
2328 // mCausedOnlyByComposition should be true only when all changes are caused
2329 // by composition.
2330 mCausedOnlyByComposition =
2331 newData.mCausedOnlyByComposition && oldData.mCausedOnlyByComposition;
2333 // mIncludingChangesWithoutComposition should be true if at least one of
2334 // merged changes occurred without composition.
2335 mIncludingChangesWithoutComposition =
2336 newData.mIncludingChangesWithoutComposition ||
2337 oldData.mIncludingChangesWithoutComposition;
2339 // mIncludingChangesDuringComposition should be true when at least one of
2340 // the merged non-composition changes occurred during the latest composition.
2341 if (!newData.mCausedOnlyByComposition &&
2342 !newData.mIncludingChangesDuringComposition) {
2343 MOZ_ASSERT(newData.mIncludingChangesWithoutComposition);
2344 MOZ_ASSERT(mIncludingChangesWithoutComposition);
2345 // If new change is neither caused by composition nor occurred during
2346 // composition, set mIncludingChangesDuringComposition to false because
2347 // IME doesn't want outdated text changes as text change during current
2348 // composition.
2349 mIncludingChangesDuringComposition = false;
2350 } else {
2351 // Otherwise, set mIncludingChangesDuringComposition to true if either
2352 // oldData or newData includes changes during composition.
2353 mIncludingChangesDuringComposition =
2354 newData.mIncludingChangesDuringComposition ||
2355 oldData.mIncludingChangesDuringComposition;
2358 if (newData.mStartOffset >= oldData.mAddedEndOffset) {
2359 // Case 1:
2360 // If new start is after old end offset of added text, it means that text
2361 // after the modified range is modified. Like:
2362 // added range of old change: +----------+
2363 // removed range of new change: +----------+
2364 // So, the old start offset is always the smaller offset.
2365 mStartOffset = oldData.mStartOffset;
2366 // The new end offset of removed text is moved by the old change and we
2367 // need to cancel the move of the old change for comparing the offsets in
2368 // same text because it doesn't make sensce to compare offsets in different
2369 // text.
2370 uint32_t newRemovedEndOffsetInOldText =
2371 newData.mRemovedEndOffset - oldData.Difference();
2372 mRemovedEndOffset =
2373 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2374 // The new end offset of added text is always the larger offset.
2375 mAddedEndOffset = newData.mAddedEndOffset;
2376 return;
2379 if (newData.mStartOffset >= oldData.mStartOffset) {
2380 // If new start is in the modified range, it means that new data changes
2381 // a part or all of the range.
2382 mStartOffset = oldData.mStartOffset;
2383 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2384 // Case 2:
2385 // If new end of removed text is greater than old end of added text, it
2386 // means that all or a part of modified range modified again and text
2387 // after the modified range is also modified. Like:
2388 // added range of old change: +----------+
2389 // removed range of new change: +----------+
2390 // So, the new removed end offset is moved by the old change and we need
2391 // to cancel the move of the old change for comparing the offsets in the
2392 // same text because it doesn't make sense to compare the offsets in
2393 // different text.
2394 uint32_t newRemovedEndOffsetInOldText =
2395 newData.mRemovedEndOffset - oldData.Difference();
2396 mRemovedEndOffset =
2397 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2398 // The old end of added text is replaced by new change. So, it should be
2399 // same as the new start. On the other hand, the new added end offset is
2400 // always same or larger. Therefore, the merged end offset of added
2401 // text should be the new end offset of added text.
2402 mAddedEndOffset = newData.mAddedEndOffset;
2403 return;
2406 // Case 3:
2407 // If new end of removed text is less than old end of added text, it means
2408 // that only a part of the modified range is modified again. Like:
2409 // added range of old change: +------------+
2410 // removed range of new change: +-----+
2411 // So, the new end offset of removed text should be same as the old end
2412 // offset of removed text. Therefore, the merged end offset of removed
2413 // text should be the old text change's |mRemovedEndOffset|.
2414 mRemovedEndOffset = oldData.mRemovedEndOffset;
2415 // The old end of added text is moved by new change. So, we need to cancel
2416 // the move of the new change for comparing the offsets in same text.
2417 uint32_t oldAddedEndOffsetInNewText =
2418 oldData.mAddedEndOffset + newData.Difference();
2419 mAddedEndOffset =
2420 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2421 return;
2424 if (newData.mRemovedEndOffset >= oldData.mStartOffset) {
2425 // If new end of removed text is greater than old start (and new start is
2426 // less than old start), it means that a part of modified range is modified
2427 // again and some new text before the modified range is also modified.
2428 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2429 "new start offset should be less than old one here");
2430 mStartOffset = newData.mStartOffset;
2431 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2432 // Case 4:
2433 // If new end of removed text is greater than old end of added text, it
2434 // means that all modified text and text after the modified range is
2435 // modified. Like:
2436 // added range of old change: +----------+
2437 // removed range of new change: +------------------+
2438 // So, the new end of removed text is moved by the old change. Therefore,
2439 // we need to cancel the move of the old change for comparing the offsets
2440 // in same text because it doesn't make sense to compare the offsets in
2441 // different text.
2442 uint32_t newRemovedEndOffsetInOldText =
2443 newData.mRemovedEndOffset - oldData.Difference();
2444 mRemovedEndOffset =
2445 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2446 // The old end of added text is replaced by new change. So, the old end
2447 // offset of added text is same as new text change's start offset. Then,
2448 // new change's end offset of added text is always same or larger than
2449 // it. Therefore, merged end offset of added text is always the new end
2450 // offset of added text.
2451 mAddedEndOffset = newData.mAddedEndOffset;
2452 return;
2455 // Case 5:
2456 // If new end of removed text is less than old end of added text, it
2457 // means that only a part of the modified range is modified again. Like:
2458 // added range of old change: +----------+
2459 // removed range of new change: +----------+
2460 // So, the new end of removed text should be same as old end of removed
2461 // text for preventing end of removed text to be modified. Therefore,
2462 // merged end offset of removed text is always the old end offset of removed
2463 // text.
2464 mRemovedEndOffset = oldData.mRemovedEndOffset;
2465 // The old end of added text is moved by this change. So, we need to
2466 // cancel the move of the new change for comparing the offsets in same text
2467 // because it doesn't make sense to compare the offsets in different text.
2468 uint32_t oldAddedEndOffsetInNewText =
2469 oldData.mAddedEndOffset + newData.Difference();
2470 mAddedEndOffset =
2471 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2472 return;
2475 // Case 6:
2476 // Otherwise, i.e., both new end of added text and new start are less than
2477 // old start, text before the modified range is modified. Like:
2478 // added range of old change: +----------+
2479 // removed range of new change: +----------+
2480 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2481 "new start offset should be less than old one here");
2482 mStartOffset = newData.mStartOffset;
2483 MOZ_ASSERT(newData.mRemovedEndOffset < oldData.mRemovedEndOffset,
2484 "new removed end offset should be less than old one here");
2485 mRemovedEndOffset = oldData.mRemovedEndOffset;
2486 // The end of added text should be adjusted with the new difference.
2487 uint32_t oldAddedEndOffsetInNewText =
2488 oldData.mAddedEndOffset + newData.Difference();
2489 mAddedEndOffset =
2490 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2493 #ifdef DEBUG
2495 // Let's test the code of merging multiple text change data in debug build
2496 // and crash if one of them fails because this feature is very complex but
2497 // cannot be tested with mochitest.
2498 void IMENotification::TextChangeDataBase::Test() {
2499 static bool gTestTextChangeEvent = true;
2500 if (!gTestTextChangeEvent) {
2501 return;
2503 gTestTextChangeEvent = false;
2505 /****************************************************************************
2506 * Case 1
2507 ****************************************************************************/
2509 // Appending text
2510 MergeWith(TextChangeData(10, 10, 20, false, false));
2511 MergeWith(TextChangeData(20, 20, 35, false, false));
2512 MOZ_ASSERT(mStartOffset == 10,
2513 "Test 1-1-1: mStartOffset should be the first offset");
2514 MOZ_ASSERT(
2515 mRemovedEndOffset == 10, // 20 - (20 - 10)
2516 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2517 MOZ_ASSERT(
2518 mAddedEndOffset == 35,
2519 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2520 Clear();
2522 // Removing text (longer line -> shorter line)
2523 MergeWith(TextChangeData(10, 20, 10, false, false));
2524 MergeWith(TextChangeData(10, 30, 10, false, false));
2525 MOZ_ASSERT(mStartOffset == 10,
2526 "Test 1-2-1: mStartOffset should be the first offset");
2527 MOZ_ASSERT(mRemovedEndOffset == 40, // 30 + (10 - 20)
2528 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2529 "removed text "
2530 "with already removed length");
2531 MOZ_ASSERT(
2532 mAddedEndOffset == 10,
2533 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2534 Clear();
2536 // Removing text (shorter line -> longer line)
2537 MergeWith(TextChangeData(10, 20, 10, false, false));
2538 MergeWith(TextChangeData(10, 15, 10, false, false));
2539 MOZ_ASSERT(mStartOffset == 10,
2540 "Test 1-3-1: mStartOffset should be the first offset");
2541 MOZ_ASSERT(mRemovedEndOffset == 25, // 15 + (10 - 20)
2542 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2543 "removed text "
2544 "with already removed length");
2545 MOZ_ASSERT(
2546 mAddedEndOffset == 10,
2547 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2548 Clear();
2550 // Appending text at different point (not sure if actually occurs)
2551 MergeWith(TextChangeData(10, 10, 20, false, false));
2552 MergeWith(TextChangeData(55, 55, 60, false, false));
2553 MOZ_ASSERT(mStartOffset == 10,
2554 "Test 1-4-1: mStartOffset should be the smallest offset");
2555 MOZ_ASSERT(
2556 mRemovedEndOffset == 45, // 55 - (10 - 20)
2557 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2558 "text without already added length");
2559 MOZ_ASSERT(
2560 mAddedEndOffset == 60,
2561 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2562 Clear();
2564 // Removing text at different point (not sure if actually occurs)
2565 MergeWith(TextChangeData(10, 20, 10, false, false));
2566 MergeWith(TextChangeData(55, 68, 55, false, false));
2567 MOZ_ASSERT(mStartOffset == 10,
2568 "Test 1-5-1: mStartOffset should be the smallest offset");
2569 MOZ_ASSERT(
2570 mRemovedEndOffset == 78, // 68 - (10 - 20)
2571 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2572 "text with already removed length");
2573 MOZ_ASSERT(
2574 mAddedEndOffset == 55,
2575 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2576 Clear();
2578 // Replacing text and append text (becomes longer)
2579 MergeWith(TextChangeData(30, 35, 32, false, false));
2580 MergeWith(TextChangeData(32, 32, 40, false, false));
2581 MOZ_ASSERT(mStartOffset == 30,
2582 "Test 1-6-1: mStartOffset should be the smallest offset");
2583 MOZ_ASSERT(
2584 mRemovedEndOffset == 35, // 32 - (32 - 35)
2585 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2586 "text");
2587 MOZ_ASSERT(
2588 mAddedEndOffset == 40,
2589 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2590 Clear();
2592 // Replacing text and append text (becomes shorter)
2593 MergeWith(TextChangeData(30, 35, 32, false, false));
2594 MergeWith(TextChangeData(32, 32, 33, false, false));
2595 MOZ_ASSERT(mStartOffset == 30,
2596 "Test 1-7-1: mStartOffset should be the smallest offset");
2597 MOZ_ASSERT(
2598 mRemovedEndOffset == 35, // 32 - (32 - 35)
2599 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2600 "text");
2601 MOZ_ASSERT(
2602 mAddedEndOffset == 33,
2603 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2604 Clear();
2606 // Removing text and replacing text after first range (not sure if actually
2607 // occurs)
2608 MergeWith(TextChangeData(30, 35, 30, false, false));
2609 MergeWith(TextChangeData(32, 34, 48, false, false));
2610 MOZ_ASSERT(mStartOffset == 30,
2611 "Test 1-8-1: mStartOffset should be the smallest offset");
2612 MOZ_ASSERT(mRemovedEndOffset == 39, // 34 - (30 - 35)
2613 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2614 "removed text "
2615 "without already removed text");
2616 MOZ_ASSERT(
2617 mAddedEndOffset == 48,
2618 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2619 Clear();
2621 // Removing text and replacing text after first range (not sure if actually
2622 // occurs)
2623 MergeWith(TextChangeData(30, 35, 30, false, false));
2624 MergeWith(TextChangeData(32, 38, 36, false, false));
2625 MOZ_ASSERT(mStartOffset == 30,
2626 "Test 1-9-1: mStartOffset should be the smallest offset");
2627 MOZ_ASSERT(mRemovedEndOffset == 43, // 38 - (30 - 35)
2628 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2629 "removed text "
2630 "without already removed text");
2631 MOZ_ASSERT(
2632 mAddedEndOffset == 36,
2633 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2634 Clear();
2636 /****************************************************************************
2637 * Case 2
2638 ****************************************************************************/
2640 // Replacing text in around end of added text (becomes shorter) (not sure
2641 // if actually occurs)
2642 MergeWith(TextChangeData(50, 50, 55, false, false));
2643 MergeWith(TextChangeData(53, 60, 54, false, false));
2644 MOZ_ASSERT(mStartOffset == 50,
2645 "Test 2-1-1: mStartOffset should be the smallest offset");
2646 MOZ_ASSERT(mRemovedEndOffset == 55, // 60 - (55 - 50)
2647 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2648 "removed text "
2649 "without already added text length");
2650 MOZ_ASSERT(
2651 mAddedEndOffset == 54,
2652 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2653 Clear();
2655 // Replacing text around end of added text (becomes longer) (not sure
2656 // if actually occurs)
2657 MergeWith(TextChangeData(50, 50, 55, false, false));
2658 MergeWith(TextChangeData(54, 62, 68, false, false));
2659 MOZ_ASSERT(mStartOffset == 50,
2660 "Test 2-2-1: mStartOffset should be the smallest offset");
2661 MOZ_ASSERT(mRemovedEndOffset == 57, // 62 - (55 - 50)
2662 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2663 "removed text "
2664 "without already added text length");
2665 MOZ_ASSERT(
2666 mAddedEndOffset == 68,
2667 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2668 Clear();
2670 // Replacing text around end of replaced text (became shorter) (not sure if
2671 // actually occurs)
2672 MergeWith(TextChangeData(36, 48, 45, false, false));
2673 MergeWith(TextChangeData(43, 50, 49, false, false));
2674 MOZ_ASSERT(mStartOffset == 36,
2675 "Test 2-3-1: mStartOffset should be the smallest offset");
2676 MOZ_ASSERT(mRemovedEndOffset == 53, // 50 - (45 - 48)
2677 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2678 "removed text "
2679 "without already removed text length");
2680 MOZ_ASSERT(
2681 mAddedEndOffset == 49,
2682 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2683 Clear();
2685 // Replacing text around end of replaced text (became longer) (not sure if
2686 // actually occurs)
2687 MergeWith(TextChangeData(36, 52, 53, false, false));
2688 MergeWith(TextChangeData(43, 68, 61, false, false));
2689 MOZ_ASSERT(mStartOffset == 36,
2690 "Test 2-4-1: mStartOffset should be the smallest offset");
2691 MOZ_ASSERT(mRemovedEndOffset == 67, // 68 - (53 - 52)
2692 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2693 "removed text "
2694 "without already added text length");
2695 MOZ_ASSERT(
2696 mAddedEndOffset == 61,
2697 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2698 Clear();
2700 /****************************************************************************
2701 * Case 3
2702 ****************************************************************************/
2704 // Appending text in already added text (not sure if actually occurs)
2705 MergeWith(TextChangeData(10, 10, 20, false, false));
2706 MergeWith(TextChangeData(15, 15, 30, false, false));
2707 MOZ_ASSERT(mStartOffset == 10,
2708 "Test 3-1-1: mStartOffset should be the smallest offset");
2709 MOZ_ASSERT(mRemovedEndOffset == 10,
2710 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2711 "removed text");
2712 MOZ_ASSERT(
2713 mAddedEndOffset == 35, // 20 + (30 - 15)
2714 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2715 "added text length by the new change");
2716 Clear();
2718 // Replacing text in added text (not sure if actually occurs)
2719 MergeWith(TextChangeData(50, 50, 55, false, false));
2720 MergeWith(TextChangeData(52, 53, 56, false, false));
2721 MOZ_ASSERT(mStartOffset == 50,
2722 "Test 3-2-1: mStartOffset should be the smallest offset");
2723 MOZ_ASSERT(mRemovedEndOffset == 50,
2724 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2725 "removed text");
2726 MOZ_ASSERT(
2727 mAddedEndOffset == 58, // 55 + (56 - 53)
2728 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2729 "added text length by the new change");
2730 Clear();
2732 // Replacing text in replaced text (became shorter) (not sure if actually
2733 // occurs)
2734 MergeWith(TextChangeData(36, 48, 45, false, false));
2735 MergeWith(TextChangeData(37, 38, 50, false, false));
2736 MOZ_ASSERT(mStartOffset == 36,
2737 "Test 3-3-1: mStartOffset should be the smallest offset");
2738 MOZ_ASSERT(mRemovedEndOffset == 48,
2739 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2740 "removed text");
2741 MOZ_ASSERT(
2742 mAddedEndOffset == 57, // 45 + (50 - 38)
2743 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2744 "added text length by the new change");
2745 Clear();
2747 // Replacing text in replaced text (became longer) (not sure if actually
2748 // occurs)
2749 MergeWith(TextChangeData(32, 48, 53, false, false));
2750 MergeWith(TextChangeData(43, 50, 52, false, false));
2751 MOZ_ASSERT(mStartOffset == 32,
2752 "Test 3-4-1: mStartOffset should be the smallest offset");
2753 MOZ_ASSERT(mRemovedEndOffset == 48,
2754 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2755 "removed text "
2756 "without already added text length");
2757 MOZ_ASSERT(
2758 mAddedEndOffset == 55, // 53 + (52 - 50)
2759 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2760 "added text length by the new change");
2761 Clear();
2763 // Replacing text in replaced text (became shorter) (not sure if actually
2764 // occurs)
2765 MergeWith(TextChangeData(36, 48, 50, false, false));
2766 MergeWith(TextChangeData(37, 49, 47, false, false));
2767 MOZ_ASSERT(mStartOffset == 36,
2768 "Test 3-5-1: mStartOffset should be the smallest offset");
2769 MOZ_ASSERT(
2770 mRemovedEndOffset == 48,
2771 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
2772 "text");
2773 MOZ_ASSERT(mAddedEndOffset == 48, // 50 + (47 - 49)
2774 "Test 3-5-3: mAddedEndOffset should be the first end of added "
2775 "text without "
2776 "removed text length by the new change");
2777 Clear();
2779 // Replacing text in replaced text (became longer) (not sure if actually
2780 // occurs)
2781 MergeWith(TextChangeData(32, 48, 53, false, false));
2782 MergeWith(TextChangeData(43, 50, 47, false, false));
2783 MOZ_ASSERT(mStartOffset == 32,
2784 "Test 3-6-1: mStartOffset should be the smallest offset");
2785 MOZ_ASSERT(mRemovedEndOffset == 48,
2786 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
2787 "removed text "
2788 "without already added text length");
2789 MOZ_ASSERT(mAddedEndOffset == 50, // 53 + (47 - 50)
2790 "Test 3-6-3: mAddedEndOffset should be the first end of added "
2791 "text without "
2792 "removed text length by the new change");
2793 Clear();
2795 /****************************************************************************
2796 * Case 4
2797 ****************************************************************************/
2799 // Replacing text all of already append text (not sure if actually occurs)
2800 MergeWith(TextChangeData(50, 50, 55, false, false));
2801 MergeWith(TextChangeData(44, 66, 68, false, false));
2802 MOZ_ASSERT(mStartOffset == 44,
2803 "Test 4-1-1: mStartOffset should be the smallest offset");
2804 MOZ_ASSERT(mRemovedEndOffset == 61, // 66 - (55 - 50)
2805 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
2806 "removed text "
2807 "without already added text length");
2808 MOZ_ASSERT(
2809 mAddedEndOffset == 68,
2810 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
2811 Clear();
2813 // Replacing text around a point in which text was removed (not sure if
2814 // actually occurs)
2815 MergeWith(TextChangeData(50, 62, 50, false, false));
2816 MergeWith(TextChangeData(44, 66, 68, false, false));
2817 MOZ_ASSERT(mStartOffset == 44,
2818 "Test 4-2-1: mStartOffset should be the smallest offset");
2819 MOZ_ASSERT(mRemovedEndOffset == 78, // 66 - (50 - 62)
2820 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
2821 "removed text "
2822 "without already removed text length");
2823 MOZ_ASSERT(
2824 mAddedEndOffset == 68,
2825 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
2826 Clear();
2828 // Replacing text all replaced text (became shorter) (not sure if actually
2829 // occurs)
2830 MergeWith(TextChangeData(50, 62, 60, false, false));
2831 MergeWith(TextChangeData(49, 128, 130, false, false));
2832 MOZ_ASSERT(mStartOffset == 49,
2833 "Test 4-3-1: mStartOffset should be the smallest offset");
2834 MOZ_ASSERT(mRemovedEndOffset == 130, // 128 - (60 - 62)
2835 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
2836 "removed text "
2837 "without already removed text length");
2838 MOZ_ASSERT(
2839 mAddedEndOffset == 130,
2840 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
2841 Clear();
2843 // Replacing text all replaced text (became longer) (not sure if actually
2844 // occurs)
2845 MergeWith(TextChangeData(50, 61, 73, false, false));
2846 MergeWith(TextChangeData(44, 100, 50, false, false));
2847 MOZ_ASSERT(mStartOffset == 44,
2848 "Test 4-4-1: mStartOffset should be the smallest offset");
2849 MOZ_ASSERT(mRemovedEndOffset == 88, // 100 - (73 - 61)
2850 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
2851 "removed text "
2852 "with already added text length");
2853 MOZ_ASSERT(
2854 mAddedEndOffset == 50,
2855 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
2856 Clear();
2858 /****************************************************************************
2859 * Case 5
2860 ****************************************************************************/
2862 // Replacing text around start of added text (not sure if actually occurs)
2863 MergeWith(TextChangeData(50, 50, 55, false, false));
2864 MergeWith(TextChangeData(48, 52, 49, false, false));
2865 MOZ_ASSERT(mStartOffset == 48,
2866 "Test 5-1-1: mStartOffset should be the smallest offset");
2867 MOZ_ASSERT(
2868 mRemovedEndOffset == 50,
2869 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
2870 "text");
2871 MOZ_ASSERT(
2872 mAddedEndOffset == 52, // 55 + (52 - 49)
2873 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
2874 "added text length by the new change");
2875 Clear();
2877 // Replacing text around start of replaced text (became shorter) (not sure if
2878 // actually occurs)
2879 MergeWith(TextChangeData(50, 60, 58, false, false));
2880 MergeWith(TextChangeData(43, 50, 48, false, false));
2881 MOZ_ASSERT(mStartOffset == 43,
2882 "Test 5-2-1: mStartOffset should be the smallest offset");
2883 MOZ_ASSERT(
2884 mRemovedEndOffset == 60,
2885 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
2886 "text");
2887 MOZ_ASSERT(mAddedEndOffset == 56, // 58 + (48 - 50)
2888 "Test 5-2-3: mAddedEndOffset should be the first end of added "
2889 "text without "
2890 "removed text length by the new change");
2891 Clear();
2893 // Replacing text around start of replaced text (became longer) (not sure if
2894 // actually occurs)
2895 MergeWith(TextChangeData(50, 60, 68, false, false));
2896 MergeWith(TextChangeData(43, 55, 53, false, false));
2897 MOZ_ASSERT(mStartOffset == 43,
2898 "Test 5-3-1: mStartOffset should be the smallest offset");
2899 MOZ_ASSERT(
2900 mRemovedEndOffset == 60,
2901 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
2902 "text");
2903 MOZ_ASSERT(mAddedEndOffset == 66, // 68 + (53 - 55)
2904 "Test 5-3-3: mAddedEndOffset should be the first end of added "
2905 "text without "
2906 "removed text length by the new change");
2907 Clear();
2909 // Replacing text around start of replaced text (became shorter) (not sure if
2910 // actually occurs)
2911 MergeWith(TextChangeData(50, 60, 58, false, false));
2912 MergeWith(TextChangeData(43, 50, 128, false, false));
2913 MOZ_ASSERT(mStartOffset == 43,
2914 "Test 5-4-1: mStartOffset should be the smallest offset");
2915 MOZ_ASSERT(
2916 mRemovedEndOffset == 60,
2917 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
2918 "text");
2919 MOZ_ASSERT(
2920 mAddedEndOffset == 136, // 58 + (128 - 50)
2921 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
2922 "added text length by the new change");
2923 Clear();
2925 // Replacing text around start of replaced text (became longer) (not sure if
2926 // actually occurs)
2927 MergeWith(TextChangeData(50, 60, 68, false, false));
2928 MergeWith(TextChangeData(43, 55, 65, false, false));
2929 MOZ_ASSERT(mStartOffset == 43,
2930 "Test 5-5-1: mStartOffset should be the smallest offset");
2931 MOZ_ASSERT(
2932 mRemovedEndOffset == 60,
2933 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
2934 "text");
2935 MOZ_ASSERT(
2936 mAddedEndOffset == 78, // 68 + (65 - 55)
2937 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
2938 "added text length by the new change");
2939 Clear();
2941 /****************************************************************************
2942 * Case 6
2943 ****************************************************************************/
2945 // Appending text before already added text (not sure if actually occurs)
2946 MergeWith(TextChangeData(30, 30, 45, false, false));
2947 MergeWith(TextChangeData(10, 10, 20, false, false));
2948 MOZ_ASSERT(mStartOffset == 10,
2949 "Test 6-1-1: mStartOffset should be the smallest offset");
2950 MOZ_ASSERT(
2951 mRemovedEndOffset == 30,
2952 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
2953 "text");
2954 MOZ_ASSERT(
2955 mAddedEndOffset == 55, // 45 + (20 - 10)
2956 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
2957 "added text length by the new change");
2958 Clear();
2960 // Removing text before already removed text (not sure if actually occurs)
2961 MergeWith(TextChangeData(30, 35, 30, false, false));
2962 MergeWith(TextChangeData(10, 25, 10, false, false));
2963 MOZ_ASSERT(mStartOffset == 10,
2964 "Test 6-2-1: mStartOffset should be the smallest offset");
2965 MOZ_ASSERT(
2966 mRemovedEndOffset == 35,
2967 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
2968 "text");
2969 MOZ_ASSERT(
2970 mAddedEndOffset == 15, // 30 - (25 - 10)
2971 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
2972 "removed text length by the new change");
2973 Clear();
2975 // Replacing text before already replaced text (not sure if actually occurs)
2976 MergeWith(TextChangeData(50, 65, 70, false, false));
2977 MergeWith(TextChangeData(13, 24, 15, false, false));
2978 MOZ_ASSERT(mStartOffset == 13,
2979 "Test 6-3-1: mStartOffset should be the smallest offset");
2980 MOZ_ASSERT(
2981 mRemovedEndOffset == 65,
2982 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
2983 "text");
2984 MOZ_ASSERT(mAddedEndOffset == 61, // 70 + (15 - 24)
2985 "Test 6-3-3: mAddedEndOffset should be the first end of added "
2986 "text without "
2987 "removed text length by the new change");
2988 Clear();
2990 // Replacing text before already replaced text (not sure if actually occurs)
2991 MergeWith(TextChangeData(50, 65, 70, false, false));
2992 MergeWith(TextChangeData(13, 24, 36, false, false));
2993 MOZ_ASSERT(mStartOffset == 13,
2994 "Test 6-4-1: mStartOffset should be the smallest offset");
2995 MOZ_ASSERT(
2996 mRemovedEndOffset == 65,
2997 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
2998 "text");
2999 MOZ_ASSERT(mAddedEndOffset == 82, // 70 + (36 - 24)
3000 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3001 "text without "
3002 "removed text length by the new change");
3003 Clear();
3006 #endif // #ifdef DEBUG
3008 } // namespace mozilla::widget
3010 #ifdef DEBUG
3011 //////////////////////////////////////////////////////////////
3013 // Convert a GUI event message code to a string.
3014 // Makes it a lot easier to debug events.
3016 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3017 // for a DebugPrintEvent() function that uses
3018 // this.
3020 //////////////////////////////////////////////////////////////
3021 /* static */
3022 nsAutoString nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent* aGuiEvent) {
3023 NS_ASSERTION(nullptr != aGuiEvent, "cmon, null gui event.");
3025 nsAutoString eventName(u"UNKNOWN"_ns);
3027 # define _ASSIGN_eventName(_value, _name) \
3028 case _value: \
3029 eventName.AssignLiteral(_name); \
3030 break
3032 switch (aGuiEvent->mMessage) {
3033 _ASSIGN_eventName(eBlur, "eBlur");
3034 _ASSIGN_eventName(eDrop, "eDrop");
3035 _ASSIGN_eventName(eDragEnter, "eDragEnter");
3036 _ASSIGN_eventName(eDragExit, "eDragExit");
3037 _ASSIGN_eventName(eDragOver, "eDragOver");
3038 _ASSIGN_eventName(eEditorInput, "eEditorInput");
3039 _ASSIGN_eventName(eFocus, "eFocus");
3040 _ASSIGN_eventName(eFocusIn, "eFocusIn");
3041 _ASSIGN_eventName(eFocusOut, "eFocusOut");
3042 _ASSIGN_eventName(eFormSelect, "eFormSelect");
3043 _ASSIGN_eventName(eFormChange, "eFormChange");
3044 _ASSIGN_eventName(eFormReset, "eFormReset");
3045 _ASSIGN_eventName(eFormSubmit, "eFormSubmit");
3046 _ASSIGN_eventName(eImageAbort, "eImageAbort");
3047 _ASSIGN_eventName(eLoadError, "eLoadError");
3048 _ASSIGN_eventName(eKeyDown, "eKeyDown");
3049 _ASSIGN_eventName(eKeyPress, "eKeyPress");
3050 _ASSIGN_eventName(eKeyUp, "eKeyUp");
3051 _ASSIGN_eventName(eMouseEnterIntoWidget, "eMouseEnterIntoWidget");
3052 _ASSIGN_eventName(eMouseExitFromWidget, "eMouseExitFromWidget");
3053 _ASSIGN_eventName(eMouseDown, "eMouseDown");
3054 _ASSIGN_eventName(eMouseUp, "eMouseUp");
3055 _ASSIGN_eventName(eMouseClick, "eMouseClick");
3056 _ASSIGN_eventName(eMouseAuxClick, "eMouseAuxClick");
3057 _ASSIGN_eventName(eMouseDoubleClick, "eMouseDoubleClick");
3058 _ASSIGN_eventName(eMouseMove, "eMouseMove");
3059 _ASSIGN_eventName(eLoad, "eLoad");
3060 _ASSIGN_eventName(ePopState, "ePopState");
3061 _ASSIGN_eventName(eBeforeScriptExecute, "eBeforeScriptExecute");
3062 _ASSIGN_eventName(eAfterScriptExecute, "eAfterScriptExecute");
3063 _ASSIGN_eventName(eUnload, "eUnload");
3064 _ASSIGN_eventName(eHashChange, "eHashChange");
3065 _ASSIGN_eventName(eReadyStateChange, "eReadyStateChange");
3066 _ASSIGN_eventName(eXULBroadcast, "eXULBroadcast");
3067 _ASSIGN_eventName(eXULCommandUpdate, "eXULCommandUpdate");
3069 # undef _ASSIGN_eventName
3071 default: {
3072 eventName.AssignLiteral("UNKNOWN: ");
3073 eventName.AppendInt(aGuiEvent->mMessage);
3074 } break;
3077 return nsAutoString(eventName);
3079 //////////////////////////////////////////////////////////////
3081 // Code to deal with paint and event debug prefs.
3083 //////////////////////////////////////////////////////////////
3084 struct PrefPair {
3085 const char* name;
3086 bool value;
3089 static PrefPair debug_PrefValues[] = {
3090 {"nglayout.debug.crossing_event_dumping", false},
3091 {"nglayout.debug.event_dumping", false},
3092 {"nglayout.debug.invalidate_dumping", false},
3093 {"nglayout.debug.motion_event_dumping", false},
3094 {"nglayout.debug.paint_dumping", false}};
3096 //////////////////////////////////////////////////////////////
3097 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName) {
3098 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3100 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3101 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3102 return debug_PrefValues[i].value;
3106 return false;
3108 //////////////////////////////////////////////////////////////
3109 static void debug_SetCachedBoolPref(const char* aPrefName, bool aValue) {
3110 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3112 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3113 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3114 debug_PrefValues[i].value = aValue;
3116 return;
3120 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3123 //////////////////////////////////////////////////////////////
3124 class Debug_PrefObserver final : public nsIObserver {
3125 ~Debug_PrefObserver() = default;
3127 public:
3128 NS_DECL_ISUPPORTS
3129 NS_DECL_NSIOBSERVER
3132 NS_IMPL_ISUPPORTS(Debug_PrefObserver, nsIObserver)
3134 NS_IMETHODIMP
3135 Debug_PrefObserver::Observe(nsISupports* subject, const char* topic,
3136 const char16_t* data) {
3137 NS_ConvertUTF16toUTF8 prefName(data);
3139 bool value = Preferences::GetBool(prefName.get(), false);
3140 debug_SetCachedBoolPref(prefName.get(), value);
3141 return NS_OK;
3144 //////////////////////////////////////////////////////////////
3145 /* static */ void debug_RegisterPrefCallbacks() {
3146 static bool once = true;
3148 if (!once) {
3149 return;
3152 once = false;
3154 nsCOMPtr<nsIObserver> obs(new Debug_PrefObserver());
3155 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3156 // Initialize the pref values
3157 debug_PrefValues[i].value =
3158 Preferences::GetBool(debug_PrefValues[i].name, false);
3160 if (obs) {
3161 // Register callbacks for when these change
3162 nsCString name;
3163 name.AssignLiteral(debug_PrefValues[i].name,
3164 strlen(debug_PrefValues[i].name));
3165 Preferences::AddStrongObserver(obs, name);
3169 //////////////////////////////////////////////////////////////
3170 static int32_t _GetPrintCount() {
3171 static int32_t sCount = 0;
3173 return ++sCount;
3175 //////////////////////////////////////////////////////////////
3176 /* static */
3177 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut, nsIWidget* aWidget,
3178 WidgetGUIEvent* aGuiEvent,
3179 const char* aWidgetName, int32_t aWindowID) {
3180 if (aGuiEvent->mMessage == eMouseMove) {
3181 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3184 if (aGuiEvent->mMessage == eMouseEnterIntoWidget ||
3185 aGuiEvent->mMessage == eMouseExitFromWidget) {
3186 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3187 return;
3190 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3192 NS_LossyConvertUTF16toASCII tempString(
3193 debug_GuiEventToString(aGuiEvent).get());
3195 fprintf(aFileOut, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3196 _GetPrintCount(), tempString.get(), (void*)aWidget, aWidgetName,
3197 aWindowID, aGuiEvent->mRefPoint.x, aGuiEvent->mRefPoint.y);
3199 //////////////////////////////////////////////////////////////
3200 /* static */
3201 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut, nsIWidget* aWidget,
3202 const nsIntRegion& aRegion,
3203 const char* aWidgetName,
3204 int32_t aWindowID) {
3205 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3206 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3208 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3210 nsIntRect rect = aRegion.GetBounds();
3211 fprintf(aFileOut,
3212 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3213 "%3d,%-3d",
3214 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID, rect.X(),
3215 rect.Y(), rect.Width(), rect.Height());
3217 fprintf(aFileOut, "\n");
3219 //////////////////////////////////////////////////////////////
3220 /* static */
3221 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut, nsIWidget* aWidget,
3222 const LayoutDeviceIntRect* aRect,
3223 const char* aWidgetName,
3224 int32_t aWindowID) {
3225 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3227 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3228 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3230 fprintf(aFileOut, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3231 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID);
3233 if (aRect) {
3234 fprintf(aFileOut, " rect=%3d,%-3d %3d,%-3d", aRect->X(), aRect->Y(),
3235 aRect->Width(), aRect->Height());
3236 } else {
3237 fprintf(aFileOut, " rect=%-15s", "none");
3240 fprintf(aFileOut, "\n");
3242 //////////////////////////////////////////////////////////////
3244 #endif // DEBUG