Bug 1697672 [wpt PR 28012] - Disable SVG composited animation if effective zoom is...
[gecko.git] / widget / nsBaseWidget.cpp
blobb7ee6ad74b9ca6d202c06436c9eb925cf113cc3c
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 "BasicLayers.h"
13 #include "ClientLayerManager.h"
14 #include "FrameLayerBuilder.h"
15 #include "GLConsts.h"
16 #include "InputData.h"
17 #include "LiveResizeListener.h"
18 #include "TouchEvents.h"
19 #include "WritingModes.h"
20 #include "X11UndefineNone.h"
21 #include "base/thread.h"
22 #include "mozilla/ArrayUtils.h"
23 #include "mozilla/Attributes.h"
24 #include "mozilla/GlobalKeyListener.h"
25 #include "mozilla/IMEStateManager.h"
26 #include "mozilla/MouseEvents.h"
27 #include "mozilla/Preferences.h"
28 #include "mozilla/PresShell.h"
29 #include "mozilla/Sprintf.h"
30 #include "mozilla/StaticPrefs_apz.h"
31 #include "mozilla/StaticPrefs_dom.h"
32 #include "mozilla/StaticPrefs_gfx.h"
33 #include "mozilla/StaticPrefs_layers.h"
34 #include "mozilla/StaticPrefs_layout.h"
35 #include "mozilla/TextEventDispatcher.h"
36 #include "mozilla/TextEventDispatcherListener.h"
37 #include "mozilla/UniquePtr.h"
38 #include "mozilla/Unused.h"
39 #include "mozilla/VsyncDispatcher.h"
40 #include "mozilla/dom/BrowserParent.h"
41 #include "mozilla/dom/ContentChild.h"
42 #include "mozilla/dom/Document.h"
43 #include "mozilla/gfx/2D.h"
44 #include "mozilla/gfx/GPUProcessManager.h"
45 #include "mozilla/gfx/gfxVars.h"
46 #include "mozilla/layers/APZCCallbackHelper.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/PLayerTransactionChild.h"
59 #include "mozilla/layers/WebRenderLayerManager.h"
60 #include "mozilla/webrender/WebRenderTypes.h"
61 #include "npapi.h"
62 #include "nsAppDirectoryServiceDefs.h"
63 #include "nsCOMPtr.h"
64 #include "nsContentUtils.h"
65 #include "nsDeviceContext.h"
66 #include "nsGfxCIID.h"
67 #include "nsIAppWindow.h"
68 #include "nsIBaseWindow.h"
69 #include "nsIContent.h"
70 #include "nsIScreenManager.h"
71 #include "nsISimpleEnumerator.h"
72 #include "nsIWidgetListener.h"
73 #include "nsRefPtrHashtable.h"
74 #include "nsServiceManagerUtils.h"
75 #include "nsWidgetsCID.h"
76 #include "nsXULPopupManager.h"
77 #include "prdtoa.h"
78 #include "prenv.h"
79 #ifdef ACCESSIBILITY
80 # include "nsAccessibilityService.h"
81 #endif
82 #include "gfxConfig.h"
83 #include "gfxUtils.h" // for ToDeviceColor
84 #include "mozilla/layers/CompositorSession.h"
85 #include "VRManagerChild.h"
86 #include "gfxConfig.h"
87 #include "nsView.h"
88 #include "nsViewManager.h"
90 #ifdef DEBUG
91 # include "nsIObserver.h"
93 static void debug_RegisterPrefCallbacks();
95 #endif
97 #ifdef NOISY_WIDGET_LEAKS
98 static int32_t gNumWidgets;
99 #endif
101 #ifdef XP_MACOSX
102 # include "nsCocoaFeatures.h"
103 #endif
105 #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
106 static nsRefPtrHashtable<nsVoidPtrHashKey, nsIWidget>* sPluginWidgetList;
107 #endif
109 nsIRollupListener* nsBaseWidget::gRollupListener = nullptr;
111 using namespace mozilla::dom;
112 using namespace mozilla::layers;
113 using namespace mozilla::ipc;
114 using namespace mozilla::widget;
115 using namespace mozilla;
117 // Async pump timer during injected long touch taps
118 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
119 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
120 int32_t nsIWidget::sPointerIdCounter = 0;
122 // Some statics from nsIWidget.h
123 /*static*/
124 uint64_t AutoObserverNotifier::sObserverId = 0;
125 /*static*/ nsTHashMap<uint64_t, nsCOMPtr<nsIObserver>>
126 AutoObserverNotifier::sSavedObservers;
128 // The maximum amount of time to let the EnableDragDrop runnable wait in the
129 // idle queue before timing out and moving it to the regular queue. Value is in
130 // milliseconds.
131 const uint32_t kAsyncDragDropTimeout = 1000;
133 namespace mozilla::widget {
135 void IMENotification::SelectionChangeDataBase::SetWritingMode(
136 const WritingMode& aWritingMode) {
137 mWritingMode = aWritingMode.mWritingMode.bits;
140 WritingMode IMENotification::SelectionChangeDataBase::GetWritingMode() const {
141 return WritingMode(mWritingMode);
144 } // namespace mozilla::widget
146 NS_IMPL_ISUPPORTS(nsBaseWidget, nsIWidget, nsISupportsWeakReference)
148 //-------------------------------------------------------------------------
150 // nsBaseWidget constructor
152 //-------------------------------------------------------------------------
154 nsBaseWidget::nsBaseWidget()
155 : mWidgetListener(nullptr),
156 mAttachedWidgetListener(nullptr),
157 mPreviouslyAttachedWidgetListener(nullptr),
158 mLayerManager(nullptr),
159 mCompositorVsyncDispatcher(nullptr),
160 mCursor(eCursor_standard),
161 mBorderStyle(eBorderStyle_none),
162 mBounds(0, 0, 0, 0),
163 mOriginalBounds(nullptr),
164 mClipRectCount(0),
165 mSizeMode(nsSizeMode_Normal),
166 mIsTiled(false),
167 mPopupLevel(ePopupLevelTop),
168 mPopupType(ePopupTypeAny),
169 mHasRemoteContent(false),
170 mFissionWindow(false),
171 mUpdateCursor(true),
172 mUseAttachedEvents(false),
173 mIMEHasFocus(false),
174 mIMEHasQuit(false),
175 mIsFullyOccluded(false) {
176 #ifdef NOISY_WIDGET_LEAKS
177 gNumWidgets++;
178 printf("WIDGETS+ = %d\n", gNumWidgets);
179 #endif
181 #ifdef DEBUG
182 debug_RegisterPrefCallbacks();
183 #endif
185 #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
186 if (!sPluginWidgetList) {
187 sPluginWidgetList = new nsRefPtrHashtable<nsVoidPtrHashKey, nsIWidget>();
189 #endif
190 mShutdownObserver = new WidgetShutdownObserver(this);
193 NS_IMPL_ISUPPORTS(WidgetShutdownObserver, nsIObserver)
195 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget* aWidget)
196 : mWidget(aWidget), mRegistered(false) {
197 Register();
200 WidgetShutdownObserver::~WidgetShutdownObserver() {
201 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
202 // gets torn down. The observer service and nsBaseWidget have a ref on us
203 // so nsBaseWidget has to call Unregister and then clear its ref.
206 NS_IMETHODIMP
207 WidgetShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
208 const char16_t* aData) {
209 if (!mWidget) {
210 return NS_OK;
212 if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
213 RefPtr<nsBaseWidget> widget(mWidget);
214 widget->Shutdown();
215 } else if (!strcmp(aTopic, "quit-application")) {
216 RefPtr<nsBaseWidget> widget(mWidget);
217 widget->QuitIME();
219 return NS_OK;
222 void WidgetShutdownObserver::Register() {
223 if (!mRegistered) {
224 mRegistered = true;
225 nsContentUtils::RegisterShutdownObserver(this);
227 #ifndef MOZ_WIDGET_ANDROID
228 // The primary purpose of observing quit-application is
229 // to avoid leaking a widget on Windows when nothing else
230 // breaks the circular reference between the widget and
231 // TSFTextStore. However, our Android IME code crashes if
232 // doing this on Android, so let's not do this on Android.
233 // Doing this on Gtk and Mac just in case.
234 nsCOMPtr<nsIObserverService> observerService =
235 mozilla::services::GetObserverService();
236 if (observerService) {
237 observerService->AddObserver(this, "quit-application", false);
239 #endif
243 void WidgetShutdownObserver::Unregister() {
244 if (mRegistered) {
245 mWidget = nullptr;
247 #ifndef MOZ_WIDGET_ANDROID
248 nsCOMPtr<nsIObserverService> observerService =
249 mozilla::services::GetObserverService();
250 if (observerService) {
251 observerService->RemoveObserver(this, "quit-application");
253 #endif
255 nsContentUtils::UnregisterShutdownObserver(this);
256 mRegistered = false;
260 void nsBaseWidget::Shutdown() {
261 NotifyLiveResizeStopped();
262 RevokeTransactionIdAllocator();
263 DestroyCompositor();
264 FreeShutdownObserver();
265 #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
266 if (sPluginWidgetList) {
267 delete sPluginWidgetList;
268 sPluginWidgetList = nullptr;
270 #endif
273 void nsBaseWidget::QuitIME() {
274 IMEStateManager::WidgetOnQuit(this);
275 this->mIMEHasQuit = true;
278 void nsBaseWidget::DestroyCompositor() {
279 // We release this before releasing the compositor, since it may hold the
280 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
281 // trigger a paint, creating a new compositor, and we don't want to re-use
282 // the old vsync dispatcher.
283 if (mCompositorVsyncDispatcher) {
284 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
286 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
287 mCompositorVsyncDispatcher->Shutdown();
288 mCompositorVsyncDispatcher = nullptr;
291 // The compositor shutdown sequence looks like this:
292 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
293 // 2. CompositorBridgeChild synchronously sends WillClose.
294 // 3. CompositorBridgeParent releases some resources (such as the layer
295 // manager, compositor, and widget).
296 // 4. CompositorBridgeChild::Destroy returns.
297 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
298 // compositor thread when the I/O thread closes the IPC channel.
299 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
300 // releases the reference CompositorBridgeParent holds to itself.
302 // When CompositorSession::Shutdown returns, we assume the compositor is gone
303 // or will be gone very soon.
304 if (mCompositorSession) {
305 ReleaseContentController();
306 mAPZC = nullptr;
307 SetCompositorWidgetDelegate(nullptr);
308 mCompositorBridgeChild = nullptr;
310 // XXX CompositorBridgeChild and CompositorBridgeParent might be re-created
311 // in ClientLayerManager destructor. See bug 1133426.
312 RefPtr<CompositorSession> session = std::move(mCompositorSession);
313 session->Shutdown();
317 // This prevents the layer manager from starting a new transaction during
318 // shutdown.
319 void nsBaseWidget::RevokeTransactionIdAllocator() {
320 if (!mLayerManager) {
321 return;
323 mLayerManager->SetTransactionIdAllocator(nullptr);
326 void nsBaseWidget::ReleaseContentController() {
327 if (mRootContentController) {
328 mRootContentController->Destroy();
329 mRootContentController = nullptr;
333 void nsBaseWidget::DestroyLayerManager() {
334 if (mLayerManager) {
335 mLayerManager->Destroy();
336 mLayerManager = nullptr;
338 DestroyCompositor();
341 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
343 void nsBaseWidget::FreeShutdownObserver() {
344 if (mShutdownObserver) {
345 mShutdownObserver->Unregister();
347 mShutdownObserver = nullptr;
350 //-------------------------------------------------------------------------
352 // nsBaseWidget destructor
354 //-------------------------------------------------------------------------
356 nsBaseWidget::~nsBaseWidget() {
357 IMEStateManager::WidgetDestroyed(this);
359 if (mLayerManager) {
360 if (BasicLayerManager* mgr = mLayerManager->AsBasicLayerManager()) {
361 mgr->ClearRetainerWidget();
365 FreeShutdownObserver();
366 RevokeTransactionIdAllocator();
367 DestroyLayerManager();
369 #ifdef NOISY_WIDGET_LEAKS
370 gNumWidgets--;
371 printf("WIDGETS- = %d\n", gNumWidgets);
372 #endif
374 delete mOriginalBounds;
377 //-------------------------------------------------------------------------
379 // Basic create.
381 //-------------------------------------------------------------------------
382 void nsBaseWidget::BaseCreate(nsIWidget* aParent, nsWidgetInitData* aInitData) {
383 // keep a reference to the device context
384 if (nullptr != aInitData) {
385 mWindowType = aInitData->mWindowType;
386 mBorderStyle = aInitData->mBorderStyle;
387 mPopupLevel = aInitData->mPopupLevel;
388 mPopupType = aInitData->mPopupHint;
389 mHasRemoteContent = aInitData->mHasRemoteContent;
390 mFissionWindow = aInitData->mFissionWindow;
393 if (aParent) {
394 aParent->AddChild(this);
398 //-------------------------------------------------------------------------
400 // Accessor functions to get/set the client data
402 //-------------------------------------------------------------------------
404 nsIWidgetListener* nsBaseWidget::GetWidgetListener() { return mWidgetListener; }
406 void nsBaseWidget::SetWidgetListener(nsIWidgetListener* aWidgetListener) {
407 mWidgetListener = aWidgetListener;
410 already_AddRefed<nsIWidget> nsBaseWidget::CreateChild(
411 const LayoutDeviceIntRect& aRect, nsWidgetInitData* aInitData,
412 bool aForceUseIWidgetParent) {
413 nsIWidget* parent = this;
414 nsNativeWidget nativeParent = nullptr;
416 if (!aForceUseIWidgetParent) {
417 // Use only either parent or nativeParent, not both, to match
418 // existing code. Eventually Create() should be divested of its
419 // nativeWidget parameter.
420 nativeParent = parent ? parent->GetNativeData(NS_NATIVE_WIDGET) : nullptr;
421 parent = nativeParent ? nullptr : parent;
422 MOZ_ASSERT(!parent || !nativeParent, "messed up logic");
425 nsCOMPtr<nsIWidget> widget;
426 if (aInitData && aInitData->mWindowType == eWindowType_popup) {
427 widget = AllocateChildPopupWidget();
428 } else {
429 widget = nsIWidget::CreateChildWindow();
432 if (widget &&
433 NS_SUCCEEDED(widget->Create(parent, nativeParent, aRect, aInitData))) {
434 return widget.forget();
437 return nullptr;
440 // Attach a view to our widget which we'll send events to.
441 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents) {
442 NS_ASSERTION((mWindowType == eWindowType_toplevel ||
443 mWindowType == eWindowType_dialog ||
444 mWindowType == eWindowType_invisible ||
445 mWindowType == eWindowType_child),
446 "Can't attach to window of that type");
448 mUseAttachedEvents = aUseAttachedEvents;
451 nsIWidgetListener* nsBaseWidget::GetAttachedWidgetListener() {
452 return mAttachedWidgetListener;
455 nsIWidgetListener* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
456 return mPreviouslyAttachedWidgetListener;
459 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
460 nsIWidgetListener* aListener) {
461 mPreviouslyAttachedWidgetListener = aListener;
464 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener* aListener) {
465 mAttachedWidgetListener = aListener;
468 //-------------------------------------------------------------------------
470 // Close this nsBaseWidget
472 //-------------------------------------------------------------------------
473 void nsBaseWidget::Destroy() {
474 // Just in case our parent is the only ref to us
475 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
476 // disconnect from the parent
477 nsIWidget* parent = GetParent();
478 if (parent) {
479 parent->RemoveChild(this);
482 #if defined(XP_WIN)
483 // Allow our scroll capture container to be cleaned up, if we have one.
484 mScrollCaptureContainer = nullptr;
485 #endif
488 //-------------------------------------------------------------------------
490 // Get this nsBaseWidget parent
492 //-------------------------------------------------------------------------
493 nsIWidget* nsBaseWidget::GetParent(void) { return nullptr; }
495 //-------------------------------------------------------------------------
497 // Get this nsBaseWidget top level widget
499 //-------------------------------------------------------------------------
500 nsIWidget* nsBaseWidget::GetTopLevelWidget() {
501 nsIWidget *topLevelWidget = nullptr, *widget = this;
502 while (widget) {
503 topLevelWidget = widget;
504 widget = widget->GetParent();
506 return topLevelWidget;
509 //-------------------------------------------------------------------------
511 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
513 //-------------------------------------------------------------------------
514 nsIWidget* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
516 float nsBaseWidget::GetDPI() { return 96.0f; }
518 CSSToLayoutDeviceScale nsIWidget::GetDefaultScale() {
519 double devPixelsPerCSSPixel = StaticPrefs::layout_css_devPixelsPerPx();
521 if (devPixelsPerCSSPixel <= 0.0) {
522 devPixelsPerCSSPixel = GetDefaultScaleInternal();
525 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel);
528 //-------------------------------------------------------------------------
530 // Add a child to the list of children
532 //-------------------------------------------------------------------------
533 void nsBaseWidget::AddChild(nsIWidget* aChild) {
534 MOZ_ASSERT(!aChild->GetNextSibling() && !aChild->GetPrevSibling(),
535 "aChild not properly removed from its old child list");
537 if (!mFirstChild) {
538 mFirstChild = mLastChild = aChild;
539 } else {
540 // append to the list
541 MOZ_ASSERT(mLastChild);
542 MOZ_ASSERT(!mLastChild->GetNextSibling());
543 mLastChild->SetNextSibling(aChild);
544 aChild->SetPrevSibling(mLastChild);
545 mLastChild = aChild;
549 //-------------------------------------------------------------------------
551 // Remove a child from the list of children
553 //-------------------------------------------------------------------------
554 void nsBaseWidget::RemoveChild(nsIWidget* aChild) {
555 #ifdef DEBUG
556 # ifdef XP_MACOSX
557 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
558 // null and we'll just have to do without this assertion.
559 nsIWidget* parent = aChild->GetParent();
560 NS_ASSERTION(!parent || parent == this, "Not one of our kids!");
561 # else
562 MOZ_RELEASE_ASSERT(aChild->GetParent() == this, "Not one of our kids!");
563 # endif
564 #endif
566 if (mLastChild == aChild) {
567 mLastChild = mLastChild->GetPrevSibling();
569 if (mFirstChild == aChild) {
570 mFirstChild = mFirstChild->GetNextSibling();
573 // Now remove from the list. Make sure that we pass ownership of the tail
574 // of the list correctly before we have aChild let go of it.
575 nsIWidget* prev = aChild->GetPrevSibling();
576 nsIWidget* next = aChild->GetNextSibling();
577 if (prev) {
578 prev->SetNextSibling(next);
580 if (next) {
581 next->SetPrevSibling(prev);
584 aChild->SetNextSibling(nullptr);
585 aChild->SetPrevSibling(nullptr);
588 //-------------------------------------------------------------------------
590 // Sets widget's position within its parent's child list.
592 //-------------------------------------------------------------------------
593 void nsBaseWidget::SetZIndex(int32_t aZIndex) {
594 // Hold a ref to ourselves just in case, since we're going to remove
595 // from our parent.
596 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
598 mZIndex = aZIndex;
600 // reorder this child in its parent's list.
601 auto* parent = static_cast<nsBaseWidget*>(GetParent());
602 if (parent) {
603 parent->RemoveChild(this);
604 // Scope sib outside the for loop so we can check it afterward
605 nsIWidget* sib = parent->GetFirstChild();
606 for (; sib; sib = sib->GetNextSibling()) {
607 int32_t childZIndex = GetZIndex();
608 if (aZIndex < childZIndex) {
609 // Insert ourselves before sib
610 nsIWidget* prev = sib->GetPrevSibling();
611 mNextSibling = sib;
612 mPrevSibling = prev;
613 sib->SetPrevSibling(this);
614 if (prev) {
615 prev->SetNextSibling(this);
616 } else {
617 NS_ASSERTION(sib == parent->mFirstChild, "Broken child list");
618 // We've taken ownership of sib, so it's safe to have parent let
619 // go of it
620 parent->mFirstChild = this;
622 PlaceBehind(eZPlacementBelow, sib, false);
623 break;
626 // were we added to the list?
627 if (!sib) {
628 parent->AddChild(this);
633 //-------------------------------------------------------------------------
635 // Maximize, minimize or restore the window. The BaseWidget implementation
636 // merely stores the state.
638 //-------------------------------------------------------------------------
639 void nsBaseWidget::SetSizeMode(nsSizeMode aMode) {
640 MOZ_ASSERT(aMode == nsSizeMode_Normal || aMode == nsSizeMode_Minimized ||
641 aMode == nsSizeMode_Maximized || aMode == nsSizeMode_Fullscreen);
642 mSizeMode = aMode;
645 void nsBaseWidget::GetWorkspaceID(nsAString& workspaceID) {
646 workspaceID.Truncate();
649 void nsBaseWidget::MoveToWorkspace(const nsAString& workspaceID) {
650 // Noop.
653 //-------------------------------------------------------------------------
655 // Get this component cursor
657 //-------------------------------------------------------------------------
659 void nsBaseWidget::SetCursor(nsCursor aCursor, imgIContainer*, uint32_t,
660 uint32_t) {
661 // We don't support the cursor image.
662 mCursor = aCursor;
665 //-------------------------------------------------------------------------
667 // Window transparency methods
669 //-------------------------------------------------------------------------
671 void nsBaseWidget::SetTransparencyMode(nsTransparencyMode aMode) {}
673 nsTransparencyMode nsBaseWidget::GetTransparencyMode() {
674 return eTransparencyOpaque;
677 bool nsBaseWidget::IsWindowClipRegionEqual(
678 const nsTArray<LayoutDeviceIntRect>& aRects) {
679 return mClipRects && mClipRectCount == aRects.Length() &&
680 memcmp(mClipRects.get(), aRects.Elements(),
681 sizeof(LayoutDeviceIntRect) * mClipRectCount) == 0;
684 void nsBaseWidget::StoreWindowClipRegion(
685 const nsTArray<LayoutDeviceIntRect>& aRects) {
686 mClipRectCount = aRects.Length();
687 mClipRects = MakeUnique<LayoutDeviceIntRect[]>(mClipRectCount);
688 if (mClipRects) {
689 memcpy(mClipRects.get(), aRects.Elements(),
690 sizeof(LayoutDeviceIntRect) * mClipRectCount);
694 void nsBaseWidget::GetWindowClipRegion(nsTArray<LayoutDeviceIntRect>* aRects) {
695 if (mClipRects) {
696 aRects->AppendElements(mClipRects.get(), mClipRectCount);
697 } else {
698 aRects->AppendElement(
699 LayoutDeviceIntRect(0, 0, mBounds.Width(), mBounds.Height()));
703 const LayoutDeviceIntRegion nsBaseWidget::RegionFromArray(
704 const nsTArray<LayoutDeviceIntRect>& aRects) {
705 LayoutDeviceIntRegion region;
706 for (uint32_t i = 0; i < aRects.Length(); ++i) {
707 region.Or(region, aRects[i]);
709 return region;
712 void nsBaseWidget::ArrayFromRegion(const LayoutDeviceIntRegion& aRegion,
713 nsTArray<LayoutDeviceIntRect>& aRects) {
714 for (auto iter = aRegion.RectIter(); !iter.Done(); iter.Next()) {
715 aRects.AppendElement(iter.Get());
719 nsresult nsBaseWidget::SetWindowClipRegion(
720 const nsTArray<LayoutDeviceIntRect>& aRects, bool aIntersectWithExisting) {
721 if (!aIntersectWithExisting) {
722 StoreWindowClipRegion(aRects);
723 } else {
724 // get current rects
725 nsTArray<LayoutDeviceIntRect> currentRects;
726 GetWindowClipRegion(&currentRects);
727 // create region from them
728 LayoutDeviceIntRegion currentRegion = RegionFromArray(currentRects);
729 // create region from new rects
730 LayoutDeviceIntRegion newRegion = RegionFromArray(aRects);
731 // intersect regions
732 LayoutDeviceIntRegion intersection;
733 intersection.And(currentRegion, newRegion);
734 // create int rect array from intersection
735 nsTArray<LayoutDeviceIntRect> rects;
736 ArrayFromRegion(intersection, rects);
737 // store
738 StoreWindowClipRegion(rects);
740 return NS_OK;
743 /* virtual */
744 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage,
745 uint16_t aDuration,
746 nsISupports* aData,
747 nsIRunnable* aCallback) {
748 MOZ_ASSERT_UNREACHABLE(
749 "Should never call PerformFullscreenTransition on nsBaseWidget");
752 //-------------------------------------------------------------------------
754 // Put the window into full-screen mode
756 //-------------------------------------------------------------------------
757 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen,
758 nsIScreen* aScreen) {
759 HideWindowChrome(aFullScreen);
761 if (aFullScreen) {
762 if (!mOriginalBounds) {
763 mOriginalBounds = new LayoutDeviceIntRect();
765 *mOriginalBounds = GetScreenBounds();
767 // Move to top-left corner of screen and size to the screen dimensions
768 nsCOMPtr<nsIScreen> screen = aScreen;
769 if (!screen) {
770 screen = GetWidgetScreen();
772 if (screen) {
773 int32_t left, top, width, height;
774 if (NS_SUCCEEDED(
775 screen->GetRectDisplayPix(&left, &top, &width, &height))) {
776 Resize(left, top, width, height, true);
779 } else if (mOriginalBounds) {
780 if (BoundsUseDesktopPixels()) {
781 DesktopRect deskRect = *mOriginalBounds / GetDesktopToDeviceScale();
782 Resize(deskRect.X(), deskRect.Y(), deskRect.Width(), deskRect.Height(),
783 true);
784 } else {
785 Resize(mOriginalBounds->X(), mOriginalBounds->Y(),
786 mOriginalBounds->Width(), mOriginalBounds->Height(), true);
791 nsresult nsBaseWidget::MakeFullScreen(bool aFullScreen, nsIScreen* aScreen) {
792 InfallibleMakeFullScreen(aFullScreen, aScreen);
793 return NS_OK;
796 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
797 nsBaseWidget* aWidget, gfxContext* aTarget, BufferMode aDoubleBuffering,
798 ScreenRotation aRotation)
799 : mWidget(aWidget) {
800 LayerManager* lm = mWidget->GetLayerManager();
801 NS_ASSERTION(
802 !lm || lm->GetBackendType() == LayersBackend::LAYERS_BASIC,
803 "AutoLayerManagerSetup instantiated for non-basic layer backend!");
804 if (lm) {
805 mLayerManager = lm->AsBasicLayerManager();
806 if (mLayerManager) {
807 mLayerManager->SetDefaultTarget(aTarget);
808 mLayerManager->SetDefaultTargetConfiguration(aDoubleBuffering, aRotation);
813 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
814 if (mLayerManager) {
815 mLayerManager->SetDefaultTarget(nullptr);
816 mLayerManager->SetDefaultTargetConfiguration(
817 mozilla::layers::BufferMode::BUFFER_NONE, ROTATION_0);
821 bool nsBaseWidget::IsSmallPopup() const {
822 return mWindowType == eWindowType_popup && mPopupType != ePopupTypePanel;
825 bool nsBaseWidget::ComputeShouldAccelerate() {
826 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING) &&
827 WidgetTypeSupportsAcceleration();
830 bool nsBaseWidget::WidgetTypePrefersSoftwareWebRender() const {
831 return StaticPrefs::gfx_webrender_software_unaccelerated_widget_force();
834 bool nsBaseWidget::UseAPZ() {
835 return (gfxPlatform::AsyncPanZoomEnabled() &&
836 (WindowType() == eWindowType_toplevel ||
837 WindowType() == eWindowType_child ||
838 (WindowType() == eWindowType_popup && HasRemoteContent() &&
839 StaticPrefs::apz_popups_enabled())));
842 void nsBaseWidget::CreateCompositor() {
843 LayoutDeviceIntRect rect = GetBounds();
844 CreateCompositor(rect.Width(), rect.Height());
847 already_AddRefed<GeckoContentController>
848 nsBaseWidget::CreateRootContentController() {
849 RefPtr<GeckoContentController> controller =
850 new ChromeProcessController(this, mAPZEventState, mAPZC);
851 return controller.forget();
854 void nsBaseWidget::ConfigureAPZCTreeManager() {
855 MOZ_ASSERT(NS_IsMainThread());
856 MOZ_ASSERT(mAPZC);
858 ConfigureAPZControllerThread();
860 float dpi = GetDPI();
861 // On Android the main thread is not the controller thread
862 APZThreadUtils::RunOnControllerThread(
863 NewRunnableMethod<float>("layers::IAPZCTreeManager::SetDPI", mAPZC,
864 &IAPZCTreeManager::SetDPI, dpi));
866 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
867 KeyboardMap map = RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
868 // On Android the main thread is not the controller thread
869 APZThreadUtils::RunOnControllerThread(NewRunnableMethod<KeyboardMap>(
870 "layers::IAPZCTreeManager::SetKeyboardMap", mAPZC,
871 &IAPZCTreeManager::SetKeyboardMap, map));
874 RefPtr<IAPZCTreeManager> treeManager = mAPZC; // for capture by the lambdas
876 ContentReceivedInputBlockCallback callback(
877 [treeManager](uint64_t aInputBlockId, bool aPreventDefault) {
878 MOZ_ASSERT(NS_IsMainThread());
879 APZThreadUtils::RunOnControllerThread(NewRunnableMethod<uint64_t, bool>(
880 "layers::IAPZCTreeManager::ContentReceivedInputBlock", treeManager,
881 &IAPZCTreeManager::ContentReceivedInputBlock, aInputBlockId,
882 aPreventDefault));
884 mAPZEventState = new APZEventState(this, std::move(callback));
886 mSetAllowedTouchBehaviorCallback =
887 [treeManager](uint64_t aInputBlockId,
888 const nsTArray<TouchBehaviorFlags>& aFlags) {
889 MOZ_ASSERT(NS_IsMainThread());
890 APZThreadUtils::RunOnControllerThread(
891 NewRunnableMethod<
892 uint64_t, StoreCopyPassByLRef<nsTArray<TouchBehaviorFlags>>>(
893 "layers::IAPZCTreeManager::SetAllowedTouchBehavior",
894 treeManager, &IAPZCTreeManager::SetAllowedTouchBehavior,
895 aInputBlockId, aFlags.Clone()));
898 mRootContentController = CreateRootContentController();
899 if (mRootContentController) {
900 mCompositorSession->SetContentController(mRootContentController);
903 // When APZ is enabled, we can actually enable raw touch events because we
904 // have code that can deal with them properly. If APZ is not enabled, this
905 // function doesn't get called.
906 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
907 RegisterTouchWindow();
911 void nsBaseWidget::ConfigureAPZControllerThread() {
912 // By default the controller thread is the main thread.
913 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
916 void nsBaseWidget::SetConfirmedTargetAPZC(
917 uint64_t aInputBlockId,
918 const nsTArray<ScrollableLayerGuid>& aTargets) const {
919 APZThreadUtils::RunOnControllerThread(
920 NewRunnableMethod<uint64_t,
921 StoreCopyPassByRRef<nsTArray<ScrollableLayerGuid>>>(
922 "layers::IAPZCTreeManager::SetTargetAPZC", mAPZC,
923 &IAPZCTreeManager::SetTargetAPZC, aInputBlockId, aTargets.Clone()));
926 void nsBaseWidget::UpdateZoomConstraints(
927 const uint32_t& aPresShellId, const ScrollableLayerGuid::ViewID& aViewId,
928 const Maybe<ZoomConstraints>& aConstraints) {
929 if (!mCompositorSession || !mAPZC) {
930 if (mInitialZoomConstraints) {
931 MOZ_ASSERT(mInitialZoomConstraints->mPresShellID == aPresShellId);
932 MOZ_ASSERT(mInitialZoomConstraints->mViewID == aViewId);
933 if (!aConstraints) {
934 mInitialZoomConstraints.reset();
938 if (aConstraints) {
939 // We have some constraints, but the compositor and APZC aren't created
940 // yet. Save these so we can use them later.
941 mInitialZoomConstraints = Some(
942 InitialZoomConstraints(aPresShellId, aViewId, aConstraints.ref()));
944 return;
946 LayersId layersId = mCompositorSession->RootLayerTreeId();
947 mAPZC->UpdateZoomConstraints(
948 ScrollableLayerGuid(layersId, aPresShellId, aViewId), aConstraints);
951 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC; }
953 nsEventStatus nsBaseWidget::ProcessUntransformedAPZEvent(
954 WidgetInputEvent* aEvent, const APZEventResult& aApzResult) {
955 MOZ_ASSERT(NS_IsMainThread());
956 ScrollableLayerGuid targetGuid = aApzResult.mTargetGuid;
957 uint64_t inputBlockId = aApzResult.mInputBlockId;
958 InputAPZContext context(aApzResult.mTargetGuid, inputBlockId,
959 aApzResult.GetStatus());
961 // Make a copy of the original event for the APZCCallbackHelper helpers that
962 // we call later, because the event passed to DispatchEvent can get mutated in
963 // ways that we don't want (i.e. touch points can get stripped out).
964 nsEventStatus status;
965 UniquePtr<WidgetEvent> original(aEvent->Duplicate());
966 DispatchEvent(aEvent, status);
968 if (mAPZC && !InputAPZContext::WasRoutedToChildProcess() && inputBlockId) {
969 // EventStateManager did not route the event into the child process.
970 // It's safe to communicate to APZ that the event has been processed.
971 // Note that here aGuid.mLayersId might be different from
972 // mCompositorSession->RootLayerTreeId() because the event might have gotten
973 // hit-tested by APZ to be targeted at a child process, but a parent process
974 // event listener called preventDefault on it. In that case aGuid.mLayersId
975 // would still be the layers id for the child process, but the event would
976 // not have actually gotten routed to the child process. The main-thread
977 // hit-test result therefore needs to use the parent process layers id.
978 LayersId rootLayersId = mCompositorSession->RootLayerTreeId();
980 UniquePtr<DisplayportSetListener> postLayerization;
981 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
982 nsTArray<TouchBehaviorFlags> allowedTouchBehaviors;
983 if (touchEvent->mMessage == eTouchStart) {
984 if (StaticPrefs::layout_css_touch_action_enabled()) {
985 allowedTouchBehaviors =
986 APZCCallbackHelper::SendSetAllowedTouchBehaviorNotification(
987 this, GetDocument(), *(original->AsTouchEvent()),
988 inputBlockId, mSetAllowedTouchBehaviorCallback);
990 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
991 this, GetDocument(), *(original->AsTouchEvent()), rootLayersId,
992 inputBlockId);
994 mAPZEventState->ProcessTouchEvent(*touchEvent, targetGuid, inputBlockId,
995 aApzResult.GetStatus(), status,
996 std::move(allowedTouchBehaviors));
997 } else if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
998 MOZ_ASSERT(wheelEvent->mFlags.mHandledByAPZ);
999 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1000 this, GetDocument(), *(original->AsWheelEvent()), rootLayersId,
1001 inputBlockId);
1002 if (wheelEvent->mCanTriggerSwipe) {
1003 ReportSwipeStarted(inputBlockId, wheelEvent->TriggersSwipe());
1005 mAPZEventState->ProcessWheelEvent(*wheelEvent, inputBlockId);
1006 } else if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1007 MOZ_ASSERT(mouseEvent->mFlags.mHandledByAPZ);
1008 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1009 this, GetDocument(), *(original->AsMouseEvent()), rootLayersId,
1010 inputBlockId);
1011 mAPZEventState->ProcessMouseEvent(*mouseEvent, inputBlockId);
1013 if (postLayerization && postLayerization->Register()) {
1014 Unused << postLayerization.release();
1018 return status;
1021 template <class InputType, class EventType>
1022 class DispatchEventOnMainThread : public Runnable {
1023 public:
1024 DispatchEventOnMainThread(const InputType& aInput, nsBaseWidget* aWidget,
1025 const APZEventResult& aAPZResult)
1026 : mozilla::Runnable("DispatchEventOnMainThread"),
1027 mInput(aInput),
1028 mWidget(aWidget),
1029 mAPZResult(aAPZResult) {}
1031 NS_IMETHOD Run() override {
1032 EventType event = mInput.ToWidgetEvent(mWidget);
1033 mWidget->ProcessUntransformedAPZEvent(&event, mAPZResult);
1034 return NS_OK;
1037 private:
1038 InputType mInput;
1039 nsBaseWidget* mWidget;
1040 APZEventResult mAPZResult;
1043 template <class InputType, class EventType>
1044 class DispatchInputOnControllerThread : public Runnable {
1045 public:
1046 DispatchInputOnControllerThread(const EventType& aEvent,
1047 IAPZCTreeManager* aAPZC,
1048 nsBaseWidget* aWidget)
1049 : mozilla::Runnable("DispatchInputOnControllerThread"),
1050 mMainMessageLoop(MessageLoop::current()),
1051 mInput(aEvent),
1052 mAPZC(aAPZC),
1053 mWidget(aWidget) {}
1055 NS_IMETHOD Run() override {
1056 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(mInput);
1057 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1058 return NS_OK;
1060 RefPtr<Runnable> r = new DispatchEventOnMainThread<InputType, EventType>(
1061 mInput, mWidget, result);
1062 mMainMessageLoop->PostTask(r.forget());
1063 return NS_OK;
1066 private:
1067 MessageLoop* mMainMessageLoop;
1068 InputType mInput;
1069 RefPtr<IAPZCTreeManager> mAPZC;
1070 nsBaseWidget* mWidget;
1073 void nsBaseWidget::DispatchTouchInput(MultiTouchInput& aInput) {
1074 MOZ_ASSERT(NS_IsMainThread());
1075 if (mAPZC) {
1076 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1078 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1079 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1080 return;
1083 WidgetTouchEvent event = aInput.ToWidgetTouchEvent(this);
1084 ProcessUntransformedAPZEvent(&event, result);
1085 } else {
1086 WidgetTouchEvent event = aInput.ToWidgetTouchEvent(this);
1088 nsEventStatus status;
1089 DispatchEvent(&event, status);
1093 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput& aInput) {
1094 MOZ_ASSERT(NS_IsMainThread());
1095 if (mAPZC) {
1096 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1098 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1099 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1100 return;
1103 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1104 ProcessUntransformedAPZEvent(&event, result);
1105 } else {
1106 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1107 nsEventStatus status;
1108 DispatchEvent(&event, status);
1112 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput& aInput) {
1113 MOZ_ASSERT(NS_IsMainThread());
1114 if (mAPZC) {
1115 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1116 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1118 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1119 return;
1121 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1122 ProcessUntransformedAPZEvent(&event, result);
1123 } else {
1124 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1125 nsEventStatus status;
1126 DispatchEvent(&event, status);
1130 nsEventStatus nsBaseWidget::DispatchInputEvent(WidgetInputEvent* aEvent) {
1131 MOZ_ASSERT(NS_IsMainThread());
1132 if (mAPZC) {
1133 if (APZThreadUtils::IsControllerThread()) {
1134 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1135 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1136 return result.GetStatus();
1138 return ProcessUntransformedAPZEvent(aEvent, result);
1140 if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1141 RefPtr<Runnable> r =
1142 new DispatchInputOnControllerThread<ScrollWheelInput,
1143 WidgetWheelEvent>(*wheelEvent,
1144 mAPZC, this);
1145 APZThreadUtils::RunOnControllerThread(std::move(r));
1146 return nsEventStatus_eConsumeDoDefault;
1148 if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1149 RefPtr<Runnable> r =
1150 new DispatchInputOnControllerThread<MouseInput, WidgetMouseEvent>(
1151 *mouseEvent, mAPZC, this);
1152 APZThreadUtils::RunOnControllerThread(std::move(r));
1153 return nsEventStatus_eConsumeDoDefault;
1155 // Allow dispatching keyboard events on Gecko thread.
1156 MOZ_ASSERT(aEvent->AsKeyboardEvent());
1159 nsEventStatus status;
1160 DispatchEvent(aEvent, status);
1161 return status;
1164 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent* aEvent) {
1165 MOZ_ASSERT(NS_IsMainThread());
1166 if (mAPZC) {
1167 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1168 mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1172 Document* nsBaseWidget::GetDocument() const {
1173 if (mWidgetListener) {
1174 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1175 return presShell->GetDocument();
1178 return nullptr;
1181 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1182 // Parent directly listens to the vsync source whereas
1183 // child process communicate via IPC
1184 // Should be called AFTER gfxPlatform is initialized
1185 if (XRE_IsParentProcess()) {
1186 if (!mCompositorVsyncDispatcherLock) {
1187 mCompositorVsyncDispatcherLock =
1188 MakeUnique<Mutex>("mCompositorVsyncDispatcherLock");
1190 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1191 if (!mCompositorVsyncDispatcher) {
1192 mCompositorVsyncDispatcher = new CompositorVsyncDispatcher();
1197 already_AddRefed<CompositorVsyncDispatcher>
1198 nsBaseWidget::GetCompositorVsyncDispatcher() {
1199 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
1201 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1202 RefPtr<CompositorVsyncDispatcher> dispatcher = mCompositorVsyncDispatcher;
1203 return dispatcher.forget();
1206 already_AddRefed<LayerManager> nsBaseWidget::CreateCompositorSession(
1207 int aWidth, int aHeight, CompositorOptions* aOptionsOut) {
1208 MOZ_ASSERT(aOptionsOut);
1210 do {
1211 CreateCompositorVsyncDispatcher();
1213 gfx::GPUProcessManager* gpu = gfx::GPUProcessManager::Get();
1214 // Make sure GPU process is ready for use.
1215 // If it failed to connect to GPU process, GPU process usage is disabled in
1216 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1217 gpu->EnsureGPUReady();
1219 // If widget type does not supports acceleration, we may be allowed to use
1220 // software WebRender instead. If not, then we use ClientLayerManager even
1221 // when gfxVars::UseWebRender() is true. WebRender could coexist only with
1222 // BasicCompositor.
1223 bool supportsAcceleration = WidgetTypeSupportsAcceleration();
1224 bool enableWR;
1225 bool enableSWWR;
1226 if (supportsAcceleration ||
1227 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1228 enableWR = gfx::gfxVars::UseWebRender();
1229 enableSWWR = gfx::gfxVars::UseSoftwareWebRender();
1230 } else if (WidgetTypePrefersSoftwareWebRender()) {
1231 enableWR = enableSWWR = gfx::gfxVars::UseWebRender();
1232 } else {
1233 enableWR = enableSWWR = false;
1235 bool enableAPZ = UseAPZ();
1236 CompositorOptions options(enableAPZ, enableWR, enableSWWR);
1238 #ifdef XP_WIN
1239 if (supportsAcceleration) {
1240 options.SetAllowSoftwareWebRenderD3D11(
1241 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1243 #elif defined(MOZ_WIDGET_ANDROID)
1244 MOZ_ASSERT(supportsAcceleration);
1245 options.SetAllowSoftwareWebRenderOGL(
1246 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1247 #elif defined(MOZ_WIDGET_GTK)
1248 if (supportsAcceleration) {
1249 options.SetAllowSoftwareWebRenderOGL(
1250 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1252 #endif
1254 #ifdef MOZ_WIDGET_ANDROID
1255 if (!GetNativeData(NS_JAVA_SURFACE)) {
1256 options.SetInitiallyPaused(true);
1258 #else
1259 options.SetInitiallyPaused(CompositorInitiallyPaused());
1260 #endif
1262 RefPtr<LayerManager> lm;
1263 if (options.UseWebRender()) {
1264 lm = new WebRenderLayerManager(this);
1265 } else {
1266 lm = new ClientLayerManager(this);
1269 bool retry = false;
1270 mCompositorSession = gpu->CreateTopLevelCompositor(
1271 this, lm, GetDefaultScale(), options, UseExternalCompositingSurface(),
1272 gfx::IntSize(aWidth, aHeight), &retry);
1274 if (lm->AsWebRenderLayerManager() && mCompositorSession) {
1275 TextureFactoryIdentifier textureFactoryIdentifier;
1276 nsCString error;
1277 lm->AsWebRenderLayerManager()->Initialize(
1278 mCompositorSession->GetCompositorBridgeChild(),
1279 wr::AsPipelineId(mCompositorSession->RootLayerTreeId()),
1280 &textureFactoryIdentifier, error);
1281 if (textureFactoryIdentifier.mParentBackend != LayersBackend::LAYERS_WR) {
1282 retry = true;
1283 DestroyCompositor();
1284 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1285 gfx::GPUProcessManager::Get()->DisableWebRender(
1286 wr::WebRenderError::INITIALIZE, error);
1288 } else if (lm->AsClientLayerManager() && mCompositorSession) {
1289 bool shouldAccelerate = ComputeShouldAccelerate();
1290 TextureFactoryIdentifier textureFactoryIdentifier;
1291 lm->AsClientLayerManager()->Initialize(
1292 mCompositorSession->GetCompositorBridgeChild(), shouldAccelerate,
1293 &textureFactoryIdentifier);
1294 if (textureFactoryIdentifier.mParentBackend ==
1295 LayersBackend::LAYERS_NONE) {
1296 DestroyCompositor();
1297 lm = nullptr;
1301 // We need to retry in a loop because the act of failing to create the
1302 // compositor can change our state (e.g. disable WebRender).
1303 if (mCompositorSession || !retry) {
1304 *aOptionsOut = options;
1305 return lm.forget();
1307 } while (true);
1310 void nsBaseWidget::CreateCompositor(int aWidth, int aHeight) {
1311 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1312 gfxPlatform::GetPlatform();
1314 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1315 "This function assumes OMTC");
1317 MOZ_ASSERT(!mCompositorSession && !mCompositorBridgeChild,
1318 "Should have properly cleaned up the previous PCompositor pair "
1319 "beforehand");
1321 if (mCompositorBridgeChild) {
1322 mCompositorBridgeChild->Destroy();
1325 // Recreating this is tricky, as we may still have an old and we need
1326 // to make sure it's properly destroyed by calling DestroyCompositor!
1328 // If we've already received a shutdown notification, don't try
1329 // create a new compositor.
1330 if (!mShutdownObserver) {
1331 return;
1334 CompositorOptions options;
1335 RefPtr<LayerManager> lm = CreateCompositorSession(aWidth, aHeight, &options);
1336 if (!lm) {
1337 return;
1340 MOZ_ASSERT(mCompositorSession);
1341 mCompositorBridgeChild = mCompositorSession->GetCompositorBridgeChild();
1342 SetCompositorWidgetDelegate(
1343 mCompositorSession->GetCompositorWidgetDelegate());
1345 if (options.UseAPZ()) {
1346 mAPZC = mCompositorSession->GetAPZCTreeManager();
1347 ConfigureAPZCTreeManager();
1348 } else {
1349 mAPZC = nullptr;
1352 if (mInitialZoomConstraints) {
1353 UpdateZoomConstraints(mInitialZoomConstraints->mPresShellID,
1354 mInitialZoomConstraints->mViewID,
1355 Some(mInitialZoomConstraints->mConstraints));
1356 mInitialZoomConstraints.reset();
1359 if (lm->AsWebRenderLayerManager()) {
1360 TextureFactoryIdentifier textureFactoryIdentifier =
1361 lm->GetTextureFactoryIdentifier();
1362 MOZ_ASSERT(textureFactoryIdentifier.mParentBackend ==
1363 LayersBackend::LAYERS_WR);
1364 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1365 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1366 } else if (lm->AsClientLayerManager()) {
1367 TextureFactoryIdentifier textureFactoryIdentifier =
1368 lm->GetTextureFactoryIdentifier();
1369 // Some popup or transparent widgets may use a different backend than the
1370 // compositors used with ImageBridge and VR (and more generally web
1371 // content).
1372 if (WidgetTypeSupportsAcceleration()) {
1373 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1374 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1378 WindowUsesOMTC();
1380 mLayerManager = std::move(lm);
1382 // Only track compositors for top-level windows, since other window types
1383 // may use the basic compositor. Except on the OS X - see bug 1306383
1384 #if defined(XP_MACOSX)
1385 bool getCompositorFromThisWindow = true;
1386 #else
1387 bool getCompositorFromThisWindow = (mWindowType == eWindowType_toplevel);
1388 #endif
1390 if (getCompositorFromThisWindow) {
1391 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1392 mLayerManager->GetCompositorBackendType());
1396 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession* aSession) {
1397 MOZ_ASSERT(aSession == mCompositorSession);
1398 DestroyLayerManager();
1401 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1402 return gfxPlatform::UsesOffMainThreadCompositing();
1405 LayerManager* nsBaseWidget::GetLayerManager(
1406 PLayerTransactionChild* aShadowManager, LayersBackend aBackendHint,
1407 LayerManagerPersistence aPersistence) {
1408 if (!mLayerManager) {
1409 if (!mShutdownObserver) {
1410 // We are shutting down, do not try to re-create a LayerManager
1411 return nullptr;
1413 // Try to use an async compositor first, if possible
1414 if (ShouldUseOffMainThreadCompositing()) {
1415 // e10s uses the parameter to pass in the shadow manager from the
1416 // BrowserChild so we don't expect to see it there since this doesn't
1417 // support e10s.
1418 NS_ASSERTION(aShadowManager == nullptr,
1419 "Async Compositor not supported with e10s");
1420 CreateCompositor();
1423 if (!mLayerManager) {
1424 mLayerManager = CreateBasicLayerManager();
1427 return mLayerManager;
1430 LayerManager* nsBaseWidget::CreateBasicLayerManager() {
1431 return new BasicLayerManager(this);
1434 CompositorBridgeChild* nsBaseWidget::GetRemoteRenderer() {
1435 return mCompositorBridgeChild;
1438 void nsBaseWidget::ClearCachedWebrenderResources() {
1439 if (!mLayerManager || !mLayerManager->AsWebRenderLayerManager()) {
1440 return;
1442 mLayerManager->ClearCachedResources();
1445 already_AddRefed<gfx::DrawTarget> nsBaseWidget::StartRemoteDrawing() {
1446 return nullptr;
1449 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA; }
1451 //-------------------------------------------------------------------------
1453 // Destroy the window
1455 //-------------------------------------------------------------------------
1456 void nsBaseWidget::OnDestroy() {
1457 if (mTextEventDispatcher) {
1458 mTextEventDispatcher->OnDestroyWidget();
1459 // Don't release it until this widget actually released because after this
1460 // is called, TextEventDispatcher() may create it again.
1463 // If this widget is being destroyed, let the APZ code know to drop references
1464 // to this widget. Callers of this function all should be holding a deathgrip
1465 // on this widget already.
1466 ReleaseContentController();
1469 void nsBaseWidget::MoveClient(const DesktopPoint& aOffset) {
1470 LayoutDeviceIntPoint clientOffset(GetClientOffset());
1472 // GetClientOffset returns device pixels; scale back to desktop pixels
1473 // if that's what this widget uses for the Move/Resize APIs
1474 if (BoundsUseDesktopPixels()) {
1475 DesktopPoint desktopOffset = clientOffset / GetDesktopToDeviceScale();
1476 Move(aOffset.x - desktopOffset.x, aOffset.y - desktopOffset.y);
1477 } else {
1478 LayoutDevicePoint layoutOffset = aOffset * GetDesktopToDeviceScale();
1479 Move(layoutOffset.x - clientOffset.x, layoutOffset.y - clientOffset.y);
1483 void nsBaseWidget::ResizeClient(const DesktopSize& aSize, bool aRepaint) {
1484 NS_ASSERTION((aSize.width >= 0), "Negative width passed to ResizeClient");
1485 NS_ASSERTION((aSize.height >= 0), "Negative height passed to ResizeClient");
1487 LayoutDeviceIntRect clientBounds = GetClientBounds();
1489 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1490 // if that's what this widget uses for the Move/Resize APIs
1491 if (BoundsUseDesktopPixels()) {
1492 DesktopSize desktopDelta =
1493 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1494 clientBounds.Size()) /
1495 GetDesktopToDeviceScale();
1496 Resize(aSize.width + desktopDelta.width, aSize.height + desktopDelta.height,
1497 aRepaint);
1498 } else {
1499 LayoutDeviceSize layoutSize = aSize * GetDesktopToDeviceScale();
1500 Resize(mBounds.Width() + (layoutSize.width - clientBounds.Width()),
1501 mBounds.Height() + (layoutSize.height - clientBounds.Height()),
1502 aRepaint);
1506 void nsBaseWidget::ResizeClient(const DesktopRect& aRect, bool aRepaint) {
1507 NS_ASSERTION((aRect.Width() >= 0), "Negative width passed to ResizeClient");
1508 NS_ASSERTION((aRect.Height() >= 0), "Negative height passed to ResizeClient");
1510 LayoutDeviceIntRect clientBounds = GetClientBounds();
1511 LayoutDeviceIntPoint clientOffset = GetClientOffset();
1512 DesktopToLayoutDeviceScale scale = GetDesktopToDeviceScale();
1514 if (BoundsUseDesktopPixels()) {
1515 DesktopPoint desktopOffset = clientOffset / scale;
1516 DesktopSize desktopDelta =
1517 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1518 clientBounds.Size()) /
1519 scale;
1520 Resize(aRect.X() - desktopOffset.x, aRect.Y() - desktopOffset.y,
1521 aRect.Width() + desktopDelta.width,
1522 aRect.Height() + desktopDelta.height, aRepaint);
1523 } else {
1524 LayoutDeviceRect layoutRect = aRect * scale;
1525 Resize(layoutRect.X() - clientOffset.x, layoutRect.Y() - clientOffset.y,
1526 layoutRect.Width() + mBounds.Width() - clientBounds.Width(),
1527 layoutRect.Height() + mBounds.Height() - clientBounds.Height(),
1528 aRepaint);
1532 //-------------------------------------------------------------------------
1534 // Bounds
1536 //-------------------------------------------------------------------------
1539 * If the implementation of nsWindow supports borders this method MUST be
1540 * overridden
1543 LayoutDeviceIntRect nsBaseWidget::GetClientBounds() { return GetBounds(); }
1546 * If the implementation of nsWindow supports borders this method MUST be
1547 * overridden
1550 LayoutDeviceIntRect nsBaseWidget::GetBounds() { return mBounds; }
1553 * If the implementation of nsWindow uses a local coordinate system within the
1554 *window, this method must be overridden
1557 LayoutDeviceIntRect nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1559 nsresult nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect& aRect) {
1560 if (SizeMode() != nsSizeMode_Normal) {
1561 return NS_ERROR_FAILURE;
1563 aRect = GetScreenBounds();
1564 return NS_OK;
1567 LayoutDeviceIntPoint nsBaseWidget::GetClientOffset() {
1568 return LayoutDeviceIntPoint(0, 0);
1571 nsresult nsBaseWidget::SetNonClientMargins(LayoutDeviceIntMargin& margins) {
1572 return NS_ERROR_NOT_IMPLEMENTED;
1575 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1577 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1579 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect* aResizerRect) {
1580 return false;
1584 * Modifies aFile to point at an icon file with the given name and suffix. The
1585 * suffix may correspond to a file extension with leading '.' if appropriate.
1586 * Returns true if the icon file exists and can be read.
1588 static bool ResolveIconNameHelper(nsIFile* aFile, const nsAString& aIconName,
1589 const nsAString& aIconSuffix) {
1590 aFile->Append(u"icons"_ns);
1591 aFile->Append(u"default"_ns);
1592 aFile->Append(aIconName + aIconSuffix);
1594 bool readable;
1595 return NS_SUCCEEDED(aFile->IsReadable(&readable)) && readable;
1599 * Resolve the given icon name into a local file object. This method is
1600 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1601 * platform specific icon file suffix (e.g., ".ico" under Win32).
1603 * If no file is found matching the given parameters, then null is returned.
1605 void nsBaseWidget::ResolveIconName(const nsAString& aIconName,
1606 const nsAString& aIconSuffix,
1607 nsIFile** aResult) {
1608 *aResult = nullptr;
1610 nsCOMPtr<nsIProperties> dirSvc =
1611 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
1612 if (!dirSvc) return;
1614 // first check auxilary chrome directories
1616 nsCOMPtr<nsISimpleEnumerator> dirs;
1617 dirSvc->Get(NS_APP_CHROME_DIR_LIST, NS_GET_IID(nsISimpleEnumerator),
1618 getter_AddRefs(dirs));
1619 if (dirs) {
1620 bool hasMore;
1621 while (NS_SUCCEEDED(dirs->HasMoreElements(&hasMore)) && hasMore) {
1622 nsCOMPtr<nsISupports> element;
1623 dirs->GetNext(getter_AddRefs(element));
1624 if (!element) continue;
1625 nsCOMPtr<nsIFile> file = do_QueryInterface(element);
1626 if (!file) continue;
1627 if (ResolveIconNameHelper(file, aIconName, aIconSuffix)) {
1628 NS_ADDREF(*aResult = file);
1629 return;
1634 // then check the main app chrome directory
1636 nsCOMPtr<nsIFile> file;
1637 dirSvc->Get(NS_APP_CHROME_DIR, NS_GET_IID(nsIFile), getter_AddRefs(file));
1638 if (file && ResolveIconNameHelper(file, aIconName, aIconSuffix))
1639 NS_ADDREF(*aResult = file);
1642 void nsBaseWidget::SetSizeConstraints(const SizeConstraints& aConstraints) {
1643 mSizeConstraints = aConstraints;
1645 // Popups are constrained during layout, and we don't want to synchronously
1646 // paint from reflow, so bail out... This is not great, but it's no worse than
1647 // what we used to do.
1649 // The right fix here is probably making constraint changes go through the
1650 // view manager and such.
1651 if (mWindowType == eWindowType_popup) {
1652 return;
1655 // If the current size doesn't meet the new constraints, trigger a
1656 // resize to apply it. Note that, we don't want to invoke Resize if
1657 // the new constraints don't affect the current size, because Resize
1658 // implementation on some platforms may touch other geometry even if
1659 // the size don't need to change.
1660 LayoutDeviceIntSize curSize = mBounds.Size();
1661 LayoutDeviceIntSize clampedSize =
1662 Max(aConstraints.mMinSize, Min(aConstraints.mMaxSize, curSize));
1663 if (clampedSize != curSize) {
1664 gfx::Size size;
1665 if (BoundsUseDesktopPixels()) {
1666 DesktopSize desktopSize = clampedSize / GetDesktopToDeviceScale();
1667 size = desktopSize.ToUnknownSize();
1668 } else {
1669 size = gfx::Size(clampedSize.ToUnknownSize());
1671 Resize(size.width, size.height, true);
1675 const widget::SizeConstraints nsBaseWidget::GetSizeConstraints() {
1676 return mSizeConstraints;
1679 // static
1680 nsIRollupListener* nsBaseWidget::GetActiveRollupListener() {
1681 // If set, then this is likely an <html:select> dropdown.
1682 if (gRollupListener) return gRollupListener;
1684 return nsXULPopupManager::GetInstance();
1687 void nsBaseWidget::NotifyWindowDestroyed() {
1688 if (!mWidgetListener) return;
1690 nsCOMPtr<nsIAppWindow> window = mWidgetListener->GetAppWindow();
1691 nsCOMPtr<nsIBaseWindow> appWindow(do_QueryInterface(window));
1692 if (appWindow) {
1693 appWindow->Destroy();
1697 void nsBaseWidget::NotifyWindowMoved(int32_t aX, int32_t aY) {
1698 if (mWidgetListener) {
1699 mWidgetListener->WindowMoved(this, aX, aY);
1702 if (mIMEHasFocus && IMENotificationRequestsRef().WantPositionChanged()) {
1703 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE));
1707 void nsBaseWidget::NotifySizeMoveDone() {
1708 if (!mWidgetListener) {
1709 return;
1711 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1712 presShell->WindowSizeMoveDone();
1716 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind) {
1717 if (!mWidgetListener) {
1718 return;
1720 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1721 presShell->ThemeChanged(aKind);
1725 void nsBaseWidget::NotifyUIStateChanged(UIStateChangeType aShowFocusRings) {
1726 if (Document* doc = GetDocument()) {
1727 if (nsPIDOMWindowOuter* win = doc->GetWindow()) {
1728 win->SetKeyboardIndicators(aShowFocusRings);
1733 nsresult nsBaseWidget::NotifyIME(const IMENotification& aIMENotification) {
1734 if (mIMEHasQuit) {
1735 return NS_OK;
1737 switch (aIMENotification.mMessage) {
1738 case REQUEST_TO_COMMIT_COMPOSITION:
1739 case REQUEST_TO_CANCEL_COMPOSITION:
1740 // We should send request to IME only when there is a TextEventDispatcher
1741 // instance (this means that this widget has dispatched at least one
1742 // composition event or keyboard event) and the it has composition.
1743 // Otherwise, there is nothing to do.
1744 // Note that if current input transaction is for native input events,
1745 // TextEventDispatcher::NotifyIME() will call
1746 // TextEventDispatcherListener::NotifyIME().
1747 if (mTextEventDispatcher && mTextEventDispatcher->IsComposing()) {
1748 return mTextEventDispatcher->NotifyIME(aIMENotification);
1750 return NS_OK;
1751 default: {
1752 if (aIMENotification.mMessage == NOTIFY_IME_OF_FOCUS) {
1753 mIMEHasFocus = true;
1755 EnsureTextEventDispatcher();
1756 // TextEventDispatcher::NotifyIME() will always call
1757 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1758 // input transaction is for synthesized events for automated tests,
1759 // notifications will be sent to native IME.
1760 nsresult rv = mTextEventDispatcher->NotifyIME(aIMENotification);
1761 if (aIMENotification.mMessage == NOTIFY_IME_OF_BLUR) {
1762 mIMEHasFocus = false;
1764 return rv;
1769 void nsBaseWidget::EnsureTextEventDispatcher() {
1770 if (mTextEventDispatcher) {
1771 return;
1773 mTextEventDispatcher = new TextEventDispatcher(this);
1776 nsIWidget::NativeIMEContext nsBaseWidget::GetNativeIMEContext() {
1777 if (mTextEventDispatcher && mTextEventDispatcher->GetPseudoIMEContext()) {
1778 // If we already have a TextEventDispatcher and it's working with
1779 // a TextInputProcessor, we need to return pseudo IME context since
1780 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1781 // on the pseudo IME context in such case.
1782 NativeIMEContext pseudoIMEContext;
1783 pseudoIMEContext.InitWithRawNativeIMEContext(
1784 mTextEventDispatcher->GetPseudoIMEContext());
1785 return pseudoIMEContext;
1787 return NativeIMEContext(this);
1790 nsIWidget::TextEventDispatcher* nsBaseWidget::GetTextEventDispatcher() {
1791 EnsureTextEventDispatcher();
1792 return mTextEventDispatcher;
1795 void* nsBaseWidget::GetPseudoIMEContext() {
1796 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
1797 if (!dispatcher) {
1798 return nullptr;
1800 return dispatcher->GetPseudoIMEContext();
1803 TextEventDispatcherListener*
1804 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1805 // TODO: If all platforms supported use of TextEventDispatcher for handling
1806 // native IME and keyboard events, this method should be removed since
1807 // in such case, this is overridden by all the subclasses.
1808 return nullptr;
1811 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId,
1812 const ScrollableLayerGuid::ViewID& aViewId,
1813 const CSSRect& aRect, const uint32_t& aFlags) {
1814 if (!mCompositorSession || !mAPZC) {
1815 return;
1817 LayersId layerId = mCompositorSession->RootLayerTreeId();
1818 APZThreadUtils::RunOnControllerThread(
1819 NewRunnableMethod<ScrollableLayerGuid, CSSRect, uint32_t>(
1820 "layers::IAPZCTreeManager::ZoomToRect", mAPZC,
1821 &IAPZCTreeManager::ZoomToRect,
1822 ScrollableLayerGuid(layerId, aPresShellId, aViewId), aRect, aFlags));
1825 #ifdef ACCESSIBILITY
1827 a11y::LocalAccessible* nsBaseWidget::GetRootAccessible() {
1828 NS_ENSURE_TRUE(mWidgetListener, nullptr);
1830 PresShell* presShell = mWidgetListener->GetPresShell();
1831 NS_ENSURE_TRUE(presShell, nullptr);
1833 // If container is null then the presshell is not active. This often happens
1834 // when a preshell is being held onto for fastback.
1835 nsPresContext* presContext = presShell->GetPresContext();
1836 NS_ENSURE_TRUE(presContext->GetContainerWeak(), nullptr);
1838 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1839 // make sure it's not created at unsafe times.
1840 nsAccessibilityService* accService = GetOrCreateAccService();
1841 if (accService) {
1842 return accService->GetRootDocumentAccessible(
1843 presShell, nsContentUtils::IsSafeToRunScript());
1846 return nullptr;
1849 #endif // ACCESSIBILITY
1851 void nsBaseWidget::StartAsyncScrollbarDrag(
1852 const AsyncDragMetrics& aDragMetrics) {
1853 if (!AsyncPanZoomEnabled()) {
1854 return;
1857 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession);
1859 LayersId layersId = mCompositorSession->RootLayerTreeId();
1860 ScrollableLayerGuid guid(layersId, aDragMetrics.mPresShellId,
1861 aDragMetrics.mViewId);
1863 APZThreadUtils::RunOnControllerThread(
1864 NewRunnableMethod<ScrollableLayerGuid, AsyncDragMetrics>(
1865 "layers::IAPZCTreeManager::StartScrollbarDrag", mAPZC,
1866 &IAPZCTreeManager::StartScrollbarDrag, guid, aDragMetrics));
1869 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
1870 const ScrollableLayerGuid& aGuid) {
1871 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1873 return mAPZC->StartAutoscroll(aGuid, aAnchorLocation);
1876 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid& aGuid) {
1877 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1879 mAPZC->StopAutoscroll(aGuid);
1882 already_AddRefed<nsIScreen> nsBaseWidget::GetWidgetScreen() {
1883 nsCOMPtr<nsIScreenManager> screenManager;
1884 screenManager = do_GetService("@mozilla.org/gfx/screenmanager;1");
1885 if (!screenManager) {
1886 return nullptr;
1889 LayoutDeviceIntRect bounds = GetScreenBounds();
1890 DesktopIntRect deskBounds = RoundedToInt(bounds / GetDesktopToDeviceScale());
1891 nsCOMPtr<nsIScreen> screen;
1892 screenManager->ScreenForRect(deskBounds.X(), deskBounds.Y(),
1893 deskBounds.Width(), deskBounds.Height(),
1894 getter_AddRefs(screen));
1895 return screen.forget();
1898 mozilla::DesktopToLayoutDeviceScale
1899 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
1900 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
1901 ->GetDesktopToDeviceScale();
1904 nsresult nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint,
1905 bool aLongTap,
1906 nsIObserver* aObserver) {
1907 AutoObserverNotifier notifier(aObserver, "touchtap");
1909 if (sPointerIdCounter > TOUCH_INJECT_MAX_POINTS) {
1910 sPointerIdCounter = 0;
1912 int pointerId = sPointerIdCounter;
1913 sPointerIdCounter++;
1914 nsresult rv = SynthesizeNativeTouchPoint(pointerId, TOUCH_CONTACT, aPoint,
1915 1.0, 90, nullptr);
1916 if (NS_FAILED(rv)) {
1917 return rv;
1920 if (!aLongTap) {
1921 return SynthesizeNativeTouchPoint(pointerId, TOUCH_REMOVE, aPoint, 0, 0,
1922 nullptr);
1925 // initiate a long tap
1926 int elapse = Preferences::GetInt("ui.click_hold_context_menus.delay",
1927 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC);
1928 if (!mLongTapTimer) {
1929 mLongTapTimer = NS_NewTimer();
1930 if (!mLongTapTimer) {
1931 SynthesizeNativeTouchPoint(pointerId, TOUCH_CANCEL, aPoint, 0, 0,
1932 nullptr);
1933 return NS_ERROR_UNEXPECTED;
1935 // Windows requires recuring events, so we set this to a smaller window
1936 // than the pref value.
1937 int timeout = elapse;
1938 if (timeout > TOUCH_INJECT_PUMP_TIMER_MSEC) {
1939 timeout = TOUCH_INJECT_PUMP_TIMER_MSEC;
1941 mLongTapTimer->InitWithNamedFuncCallback(
1942 OnLongTapTimerCallback, this, timeout, nsITimer::TYPE_REPEATING_SLACK,
1943 "nsIWidget::SynthesizeNativeTouchTap");
1946 // If we already have a long tap pending, cancel it. We only allow one long
1947 // tap to be active at a time.
1948 if (mLongTapTouchPoint) {
1949 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1950 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1953 mLongTapTouchPoint = MakeUnique<LongTapInfo>(
1954 pointerId, aPoint, TimeDuration::FromMilliseconds(elapse), aObserver);
1955 notifier.SkipNotification(); // we'll do it in the long-tap callback
1956 return NS_OK;
1959 // static
1960 void nsIWidget::OnLongTapTimerCallback(nsITimer* aTimer, void* aClosure) {
1961 auto* self = static_cast<nsIWidget*>(aClosure);
1963 if ((self->mLongTapTouchPoint->mStamp + self->mLongTapTouchPoint->mDuration) >
1964 TimeStamp::Now()) {
1965 #ifdef XP_WIN
1966 // Windows needs us to keep pumping feedback to the digitizer, so update
1967 // the pointer id with the same position.
1968 self->SynthesizeNativeTouchPoint(
1969 self->mLongTapTouchPoint->mPointerId, TOUCH_CONTACT,
1970 self->mLongTapTouchPoint->mPosition, 1.0, 90, nullptr);
1971 #endif
1972 return;
1975 AutoObserverNotifier notifier(self->mLongTapTouchPoint->mObserver,
1976 "touchtap");
1978 // finished, remove the touch point
1979 self->mLongTapTimer->Cancel();
1980 self->mLongTapTimer = nullptr;
1981 self->SynthesizeNativeTouchPoint(
1982 self->mLongTapTouchPoint->mPointerId, TOUCH_REMOVE,
1983 self->mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1984 self->mLongTapTouchPoint = nullptr;
1987 nsresult nsIWidget::ClearNativeTouchSequence(nsIObserver* aObserver) {
1988 AutoObserverNotifier notifier(aObserver, "cleartouch");
1990 if (!mLongTapTimer) {
1991 return NS_OK;
1993 mLongTapTimer->Cancel();
1994 mLongTapTimer = nullptr;
1995 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1996 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1997 mLongTapTouchPoint = nullptr;
1998 return NS_OK;
2001 MultiTouchInput nsBaseWidget::UpdateSynthesizedTouchState(
2002 MultiTouchInput* aState, uint32_t aTime, mozilla::TimeStamp aTimeStamp,
2003 uint32_t aPointerId, TouchPointerState aPointerState,
2004 LayoutDeviceIntPoint aPoint, double aPointerPressure,
2005 uint32_t aPointerOrientation) {
2006 ScreenIntPoint pointerScreenPoint = ViewAs<ScreenPixel>(
2007 aPoint, PixelCastJustification::LayoutDeviceIsScreenForBounds);
2009 // We can't dispatch *aState directly because (a) dispatching
2010 // it might inadvertently modify it and (b) in the case of touchend or
2011 // touchcancel events aState will hold the touches that are
2012 // still down whereas the input dispatched needs to hold the removed
2013 // touch(es). We use |inputToDispatch| for this purpose.
2014 MultiTouchInput inputToDispatch;
2015 inputToDispatch.mInputType = MULTITOUCH_INPUT;
2016 inputToDispatch.mTime = aTime;
2017 inputToDispatch.mTimeStamp = aTimeStamp;
2019 int32_t index = aState->IndexOfTouch((int32_t)aPointerId);
2020 if (aPointerState == TOUCH_CONTACT) {
2021 if (index >= 0) {
2022 // found an existing touch point, update it
2023 SingleTouchData& point = aState->mTouches[index];
2024 point.mScreenPoint = pointerScreenPoint;
2025 point.mRotationAngle = (float)aPointerOrientation;
2026 point.mForce = (float)aPointerPressure;
2027 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_MOVE;
2028 } else {
2029 // new touch point, add it
2030 aState->mTouches.AppendElement(SingleTouchData(
2031 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2032 (float)aPointerOrientation, (float)aPointerPressure));
2033 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_START;
2035 inputToDispatch.mTouches = aState->mTouches;
2036 } else {
2037 MOZ_ASSERT(aPointerState == TOUCH_REMOVE || aPointerState == TOUCH_CANCEL);
2038 // a touch point is being lifted, so remove it from the stored list
2039 if (index >= 0) {
2040 aState->mTouches.RemoveElementAt(index);
2042 inputToDispatch.mType =
2043 (aPointerState == TOUCH_REMOVE ? MultiTouchInput::MULTITOUCH_END
2044 : MultiTouchInput::MULTITOUCH_CANCEL);
2045 inputToDispatch.mTouches.AppendElement(SingleTouchData(
2046 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2047 (float)aPointerOrientation, (float)aPointerPressure));
2050 return inputToDispatch;
2053 void nsBaseWidget::NotifyLiveResizeStarted() {
2054 // If we have mLiveResizeListeners already non-empty, we should notify those
2055 // listeners that the resize stopped before starting anew. In theory this
2056 // should never happen because we shouldn't get nested live resize actions.
2057 NotifyLiveResizeStopped();
2058 MOZ_ASSERT(mLiveResizeListeners.IsEmpty());
2060 // If we can get the active remote tab for the current widget, suppress
2061 // the displayport on it during the live resize.
2062 if (!mWidgetListener) {
2063 return;
2065 nsCOMPtr<nsIAppWindow> appWindow = mWidgetListener->GetAppWindow();
2066 if (!appWindow) {
2067 return;
2069 mLiveResizeListeners = appWindow->GetLiveResizeListeners();
2070 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2071 mLiveResizeListeners[i]->LiveResizeStarted();
2075 void nsBaseWidget::NotifyLiveResizeStopped() {
2076 if (!mLiveResizeListeners.IsEmpty()) {
2077 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2078 mLiveResizeListeners[i]->LiveResizeStopped();
2080 mLiveResizeListeners.Clear();
2084 void nsBaseWidget::RegisterPluginWindowForRemoteUpdates() {
2085 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2086 MOZ_ASSERT_UNREACHABLE(
2087 "nsBaseWidget::RegisterPluginWindowForRemoteUpdates "
2088 "not implemented!");
2089 return;
2090 #else
2091 MOZ_ASSERT(NS_IsMainThread());
2092 void* id = GetNativeData(NS_NATIVE_PLUGIN_ID);
2093 if (!id) {
2094 NS_WARNING("This is not a valid native widget!");
2095 return;
2097 MOZ_ASSERT(sPluginWidgetList);
2098 sPluginWidgetList->InsertOrUpdate(id, RefPtr{this});
2099 #endif
2102 void nsBaseWidget::UnregisterPluginWindowForRemoteUpdates() {
2103 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2104 MOZ_ASSERT_UNREACHABLE(
2105 "nsBaseWidget::UnregisterPluginWindowForRemoteUpdates "
2106 "not implemented!");
2107 return;
2108 #else
2109 MOZ_ASSERT(NS_IsMainThread());
2110 void* id = GetNativeData(NS_NATIVE_PLUGIN_ID);
2111 if (!id) {
2112 NS_WARNING("This is not a valid native widget!");
2113 return;
2115 MOZ_ASSERT(sPluginWidgetList);
2116 sPluginWidgetList->Remove(id);
2117 #endif
2120 nsresult nsBaseWidget::AsyncEnableDragDrop(bool aEnable) {
2121 RefPtr<nsBaseWidget> kungFuDeathGrip = this;
2122 return NS_DispatchToCurrentThreadQueue(
2123 NS_NewRunnableFunction(
2124 "AsyncEnableDragDropFn",
2125 [this, aEnable, kungFuDeathGrip]() { EnableDragDrop(aEnable); }),
2126 kAsyncDragDropTimeout, EventQueuePriority::Idle);
2129 // static
2130 nsIWidget* nsIWidget::LookupRegisteredPluginWindow(uintptr_t aWindowID) {
2131 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2132 MOZ_ASSERT_UNREACHABLE(
2133 "nsBaseWidget::LookupRegisteredPluginWindow "
2134 "not implemented!");
2135 return nullptr;
2136 #else
2137 MOZ_ASSERT(NS_IsMainThread());
2138 MOZ_ASSERT(sPluginWidgetList);
2139 return sPluginWidgetList->GetWeak((void*)aWindowID);
2140 #endif
2143 // static
2144 void nsIWidget::UpdateRegisteredPluginWindowVisibility(
2145 uintptr_t aOwnerWidget, nsTArray<uintptr_t>& aPluginIds) {
2146 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2147 MOZ_ASSERT_UNREACHABLE(
2148 "nsBaseWidget::UpdateRegisteredPluginWindowVisibility"
2149 " not implemented!");
2150 return;
2151 #else
2152 MOZ_ASSERT(NS_IsMainThread());
2153 MOZ_ASSERT(sPluginWidgetList);
2155 // Our visible list is associated with a compositor which is associated with
2156 // a specific top level window. We use the parent widget during iteration
2157 // to skip the plugin widgets owned by other top level windows.
2158 for (const auto& entry : *sPluginWidgetList) {
2159 const void* windowId = entry.GetKey();
2160 nsIWidget* widget = entry.GetWeak();
2162 MOZ_ASSERT(windowId);
2163 MOZ_ASSERT(widget);
2165 if (!widget->Destroyed()) {
2166 if ((uintptr_t)widget->GetParent() == aOwnerWidget) {
2167 widget->Show(aPluginIds.Contains((uintptr_t)windowId));
2171 #endif
2174 #if defined(XP_WIN)
2175 // static
2176 void nsIWidget::CaptureRegisteredPlugins(uintptr_t aOwnerWidget) {
2177 MOZ_ASSERT(NS_IsMainThread());
2178 MOZ_ASSERT(sPluginWidgetList);
2180 // Our visible list is associated with a compositor which is associated with
2181 // a specific top level window. We use the parent widget during iteration
2182 // to skip the plugin widgets owned by other top level windows.
2183 for (const auto& entry : *sPluginWidgetList) {
2184 DebugOnly<const void*> windowId = entry.GetKey();
2185 nsIWidget* widget = entry.GetWeak();
2187 MOZ_ASSERT(windowId);
2188 MOZ_ASSERT(widget);
2190 if (!widget->Destroyed() && widget->IsVisible()) {
2191 if ((uintptr_t)widget->GetParent() == aOwnerWidget) {
2192 widget->UpdateScrollCapture();
2198 uint64_t nsBaseWidget::CreateScrollCaptureContainer() {
2199 mScrollCaptureContainer =
2200 LayerManager::CreateImageContainer(ImageContainer::ASYNCHRONOUS);
2201 if (!mScrollCaptureContainer) {
2202 NS_WARNING("Failed to create ImageContainer for widget image capture.");
2203 return ImageContainer::sInvalidAsyncContainerId;
2206 return mScrollCaptureContainer->GetAsyncContainerHandle().Value();
2209 void nsBaseWidget::UpdateScrollCapture() {
2210 // Don't capture if no container or no size.
2211 if (!mScrollCaptureContainer || mBounds.IsEmpty()) {
2212 return;
2215 // If the derived class cannot take a snapshot, for example due to clipping,
2216 // then it is responsible for creating a fallback. If null is returned, this
2217 // means that we want to keep the existing snapshot.
2218 RefPtr<gfx::SourceSurface> snapshot = CreateScrollSnapshot();
2219 if (!snapshot) {
2220 return;
2223 ImageContainer::NonOwningImage holder(new SourceSurfaceImage(snapshot));
2225 AutoTArray<ImageContainer::NonOwningImage, 1> imageList;
2226 imageList.AppendElement(holder);
2228 mScrollCaptureContainer->SetCurrentImages(imageList);
2231 void nsBaseWidget::DefaultFillScrollCapture(DrawTarget* aSnapshotDrawTarget) {
2232 gfx::IntSize dtSize = aSnapshotDrawTarget->GetSize();
2233 aSnapshotDrawTarget->FillRect(
2234 gfx::Rect(0, 0, dtSize.width, dtSize.height),
2235 gfx::ColorPattern(gfx::ToDeviceColor(kScrollCaptureFillColor)),
2236 gfx::DrawOptions(1.f, gfx::CompositionOp::OP_SOURCE));
2237 aSnapshotDrawTarget->Flush();
2239 #endif
2241 const IMENotificationRequests& nsIWidget::IMENotificationRequestsRef() {
2242 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
2243 return dispatcher->IMENotificationRequestsRef();
2246 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent* aEvent) {}
2248 bool nsIWidget::GetEditCommands(nsIWidget::NativeKeyBindingsType aType,
2249 const WidgetKeyboardEvent& aEvent,
2250 nsTArray<CommandInt>& aCommands) {
2251 MOZ_ASSERT(aEvent.IsTrusted());
2252 MOZ_ASSERT(aCommands.IsEmpty());
2253 return true;
2256 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboard() {
2257 if (XRE_IsContentProcess()) {
2258 return CreateBidiKeyboardContentProcess();
2260 return CreateBidiKeyboardInner();
2263 #ifdef ANDROID
2264 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboardInner() {
2265 // no bidi keyboard implementation
2266 return nullptr;
2268 #endif
2270 namespace mozilla::widget {
2272 const char* ToChar(InputContext::Origin aOrigin) {
2273 switch (aOrigin) {
2274 case InputContext::ORIGIN_MAIN:
2275 return "ORIGIN_MAIN";
2276 case InputContext::ORIGIN_CONTENT:
2277 return "ORIGIN_CONTENT";
2278 default:
2279 return "Unexpected value";
2283 const char* ToChar(IMEMessage aIMEMessage) {
2284 switch (aIMEMessage) {
2285 case NOTIFY_IME_OF_NOTHING:
2286 return "NOTIFY_IME_OF_NOTHING";
2287 case NOTIFY_IME_OF_FOCUS:
2288 return "NOTIFY_IME_OF_FOCUS";
2289 case NOTIFY_IME_OF_BLUR:
2290 return "NOTIFY_IME_OF_BLUR";
2291 case NOTIFY_IME_OF_SELECTION_CHANGE:
2292 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2293 case NOTIFY_IME_OF_TEXT_CHANGE:
2294 return "NOTIFY_IME_OF_TEXT_CHANGE";
2295 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED:
2296 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2297 case NOTIFY_IME_OF_POSITION_CHANGE:
2298 return "NOTIFY_IME_OF_POSITION_CHANGE";
2299 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
2300 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2301 case REQUEST_TO_COMMIT_COMPOSITION:
2302 return "REQUEST_TO_COMMIT_COMPOSITION";
2303 case REQUEST_TO_CANCEL_COMPOSITION:
2304 return "REQUEST_TO_CANCEL_COMPOSITION";
2305 default:
2306 return "Unexpected value";
2310 void NativeIMEContext::Init(nsIWidget* aWidget) {
2311 if (!aWidget) {
2312 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2313 mOriginProcessID = static_cast<uint64_t>(-1);
2314 return;
2316 if (!XRE_IsContentProcess()) {
2317 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(
2318 aWidget->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT));
2319 mOriginProcessID = 0;
2320 return;
2322 // If this is created in a child process, aWidget is an instance of
2323 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2324 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2325 // native IME context of the parent process.
2326 *this = aWidget->GetNativeIMEContext();
2329 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext) {
2330 if (NS_WARN_IF(!aRawNativeIMEContext)) {
2331 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2332 mOriginProcessID = static_cast<uint64_t>(-1);
2333 return;
2335 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(aRawNativeIMEContext);
2336 mOriginProcessID =
2337 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2340 void IMENotification::TextChangeDataBase::MergeWith(
2341 const IMENotification::TextChangeDataBase& aOther) {
2342 MOZ_ASSERT(aOther.IsValid(), "Merging data must store valid data");
2343 MOZ_ASSERT(aOther.mStartOffset <= aOther.mRemovedEndOffset,
2344 "end of removed text must be same or larger than start");
2345 MOZ_ASSERT(aOther.mStartOffset <= aOther.mAddedEndOffset,
2346 "end of added text must be same or larger than start");
2348 if (!IsValid()) {
2349 *this = aOther;
2350 return;
2353 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2354 // text ranges. I.e., mStartOffset should be the smallest offset of all
2355 // modified text ranges in old text. |mRemovedEndOffset| should be the
2356 // largest end offset in old text of all modified text ranges.
2357 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2358 // I.e., only this is an offset in new text.
2359 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2360 // premodified text was already removed. And some text whose length is
2361 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2362 // this allows IME to mark dirty the modified text range with |mStartOffset|
2363 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2364 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2365 // Additionally, IME can retrieve only the text between |mStartOffset| and
2366 // |mAddedEndOffset| for updating stored text.
2368 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2369 // should be adjusted to be in same text. The |newData.mStartOffset| and
2370 // |newData.mRemovedEndOffset| should be computed as in old text because
2371 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2372 // in the old text but even if some text before the values of the newData
2373 // has already been modified, the values don't include the changes.
2375 // For comparing new and old |mAddedEndOffset| values, they should be
2376 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2377 // computed as in the new text because |mAddedEndOffset| indicates the end
2378 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2379 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2381 const TextChangeDataBase& newData = aOther;
2382 const TextChangeDataBase oldData = *this;
2384 // mCausedOnlyByComposition should be true only when all changes are caused
2385 // by composition.
2386 mCausedOnlyByComposition =
2387 newData.mCausedOnlyByComposition && oldData.mCausedOnlyByComposition;
2389 // mIncludingChangesWithoutComposition should be true if at least one of
2390 // merged changes occurred without composition.
2391 mIncludingChangesWithoutComposition =
2392 newData.mIncludingChangesWithoutComposition ||
2393 oldData.mIncludingChangesWithoutComposition;
2395 // mIncludingChangesDuringComposition should be true when at least one of
2396 // the merged non-composition changes occurred during the latest composition.
2397 if (!newData.mCausedOnlyByComposition &&
2398 !newData.mIncludingChangesDuringComposition) {
2399 MOZ_ASSERT(newData.mIncludingChangesWithoutComposition);
2400 MOZ_ASSERT(mIncludingChangesWithoutComposition);
2401 // If new change is neither caused by composition nor occurred during
2402 // composition, set mIncludingChangesDuringComposition to false because
2403 // IME doesn't want outdated text changes as text change during current
2404 // composition.
2405 mIncludingChangesDuringComposition = false;
2406 } else {
2407 // Otherwise, set mIncludingChangesDuringComposition to true if either
2408 // oldData or newData includes changes during composition.
2409 mIncludingChangesDuringComposition =
2410 newData.mIncludingChangesDuringComposition ||
2411 oldData.mIncludingChangesDuringComposition;
2414 if (newData.mStartOffset >= oldData.mAddedEndOffset) {
2415 // Case 1:
2416 // If new start is after old end offset of added text, it means that text
2417 // after the modified range is modified. Like:
2418 // added range of old change: +----------+
2419 // removed range of new change: +----------+
2420 // So, the old start offset is always the smaller offset.
2421 mStartOffset = oldData.mStartOffset;
2422 // The new end offset of removed text is moved by the old change and we
2423 // need to cancel the move of the old change for comparing the offsets in
2424 // same text because it doesn't make sensce to compare offsets in different
2425 // text.
2426 uint32_t newRemovedEndOffsetInOldText =
2427 newData.mRemovedEndOffset - oldData.Difference();
2428 mRemovedEndOffset =
2429 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2430 // The new end offset of added text is always the larger offset.
2431 mAddedEndOffset = newData.mAddedEndOffset;
2432 return;
2435 if (newData.mStartOffset >= oldData.mStartOffset) {
2436 // If new start is in the modified range, it means that new data changes
2437 // a part or all of the range.
2438 mStartOffset = oldData.mStartOffset;
2439 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2440 // Case 2:
2441 // If new end of removed text is greater than old end of added text, it
2442 // means that all or a part of modified range modified again and text
2443 // after the modified range is also modified. Like:
2444 // added range of old change: +----------+
2445 // removed range of new change: +----------+
2446 // So, the new removed end offset is moved by the old change and we need
2447 // to cancel the move of the old change for comparing the offsets in the
2448 // same text because it doesn't make sense to compare the offsets in
2449 // different text.
2450 uint32_t newRemovedEndOffsetInOldText =
2451 newData.mRemovedEndOffset - oldData.Difference();
2452 mRemovedEndOffset =
2453 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2454 // The old end of added text is replaced by new change. So, it should be
2455 // same as the new start. On the other hand, the new added end offset is
2456 // always same or larger. Therefore, the merged end offset of added
2457 // text should be the new end offset of added text.
2458 mAddedEndOffset = newData.mAddedEndOffset;
2459 return;
2462 // Case 3:
2463 // If new end of removed text is less than old end of added text, it means
2464 // that only a part of the modified range is modified again. Like:
2465 // added range of old change: +------------+
2466 // removed range of new change: +-----+
2467 // So, the new end offset of removed text should be same as the old end
2468 // offset of removed text. Therefore, the merged end offset of removed
2469 // text should be the old text change's |mRemovedEndOffset|.
2470 mRemovedEndOffset = oldData.mRemovedEndOffset;
2471 // The old end of added text is moved by new change. So, we need to cancel
2472 // the move of the new change for comparing the offsets in same text.
2473 uint32_t oldAddedEndOffsetInNewText =
2474 oldData.mAddedEndOffset + newData.Difference();
2475 mAddedEndOffset =
2476 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2477 return;
2480 if (newData.mRemovedEndOffset >= oldData.mStartOffset) {
2481 // If new end of removed text is greater than old start (and new start is
2482 // less than old start), it means that a part of modified range is modified
2483 // again and some new text before the modified range is also modified.
2484 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2485 "new start offset should be less than old one here");
2486 mStartOffset = newData.mStartOffset;
2487 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2488 // Case 4:
2489 // If new end of removed text is greater than old end of added text, it
2490 // means that all modified text and text after the modified range is
2491 // modified. Like:
2492 // added range of old change: +----------+
2493 // removed range of new change: +------------------+
2494 // So, the new end of removed text is moved by the old change. Therefore,
2495 // we need to cancel the move of the old change for comparing the offsets
2496 // in same text because it doesn't make sense to compare the offsets in
2497 // different text.
2498 uint32_t newRemovedEndOffsetInOldText =
2499 newData.mRemovedEndOffset - oldData.Difference();
2500 mRemovedEndOffset =
2501 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2502 // The old end of added text is replaced by new change. So, the old end
2503 // offset of added text is same as new text change's start offset. Then,
2504 // new change's end offset of added text is always same or larger than
2505 // it. Therefore, merged end offset of added text is always the new end
2506 // offset of added text.
2507 mAddedEndOffset = newData.mAddedEndOffset;
2508 return;
2511 // Case 5:
2512 // If new end of removed text is less than old end of added text, it
2513 // means that only a part of the modified range is modified again. Like:
2514 // added range of old change: +----------+
2515 // removed range of new change: +----------+
2516 // So, the new end of removed text should be same as old end of removed
2517 // text for preventing end of removed text to be modified. Therefore,
2518 // merged end offset of removed text is always the old end offset of removed
2519 // text.
2520 mRemovedEndOffset = oldData.mRemovedEndOffset;
2521 // The old end of added text is moved by this change. So, we need to
2522 // cancel the move of the new change for comparing the offsets in same text
2523 // because it doesn't make sense to compare the offsets in different text.
2524 uint32_t oldAddedEndOffsetInNewText =
2525 oldData.mAddedEndOffset + newData.Difference();
2526 mAddedEndOffset =
2527 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2528 return;
2531 // Case 6:
2532 // Otherwise, i.e., both new end of added text and new start are less than
2533 // old start, text before the modified range is modified. Like:
2534 // added range of old change: +----------+
2535 // removed range of new change: +----------+
2536 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2537 "new start offset should be less than old one here");
2538 mStartOffset = newData.mStartOffset;
2539 MOZ_ASSERT(newData.mRemovedEndOffset < oldData.mRemovedEndOffset,
2540 "new removed end offset should be less than old one here");
2541 mRemovedEndOffset = oldData.mRemovedEndOffset;
2542 // The end of added text should be adjusted with the new difference.
2543 uint32_t oldAddedEndOffsetInNewText =
2544 oldData.mAddedEndOffset + newData.Difference();
2545 mAddedEndOffset =
2546 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2549 #ifdef DEBUG
2551 // Let's test the code of merging multiple text change data in debug build
2552 // and crash if one of them fails because this feature is very complex but
2553 // cannot be tested with mochitest.
2554 void IMENotification::TextChangeDataBase::Test() {
2555 static bool gTestTextChangeEvent = true;
2556 if (!gTestTextChangeEvent) {
2557 return;
2559 gTestTextChangeEvent = false;
2561 /****************************************************************************
2562 * Case 1
2563 ****************************************************************************/
2565 // Appending text
2566 MergeWith(TextChangeData(10, 10, 20, false, false));
2567 MergeWith(TextChangeData(20, 20, 35, false, false));
2568 MOZ_ASSERT(mStartOffset == 10,
2569 "Test 1-1-1: mStartOffset should be the first offset");
2570 MOZ_ASSERT(
2571 mRemovedEndOffset == 10, // 20 - (20 - 10)
2572 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2573 MOZ_ASSERT(
2574 mAddedEndOffset == 35,
2575 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2576 Clear();
2578 // Removing text (longer line -> shorter line)
2579 MergeWith(TextChangeData(10, 20, 10, false, false));
2580 MergeWith(TextChangeData(10, 30, 10, false, false));
2581 MOZ_ASSERT(mStartOffset == 10,
2582 "Test 1-2-1: mStartOffset should be the first offset");
2583 MOZ_ASSERT(mRemovedEndOffset == 40, // 30 + (10 - 20)
2584 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2585 "removed text "
2586 "with already removed length");
2587 MOZ_ASSERT(
2588 mAddedEndOffset == 10,
2589 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2590 Clear();
2592 // Removing text (shorter line -> longer line)
2593 MergeWith(TextChangeData(10, 20, 10, false, false));
2594 MergeWith(TextChangeData(10, 15, 10, false, false));
2595 MOZ_ASSERT(mStartOffset == 10,
2596 "Test 1-3-1: mStartOffset should be the first offset");
2597 MOZ_ASSERT(mRemovedEndOffset == 25, // 15 + (10 - 20)
2598 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2599 "removed text "
2600 "with already removed length");
2601 MOZ_ASSERT(
2602 mAddedEndOffset == 10,
2603 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2604 Clear();
2606 // Appending text at different point (not sure if actually occurs)
2607 MergeWith(TextChangeData(10, 10, 20, false, false));
2608 MergeWith(TextChangeData(55, 55, 60, false, false));
2609 MOZ_ASSERT(mStartOffset == 10,
2610 "Test 1-4-1: mStartOffset should be the smallest offset");
2611 MOZ_ASSERT(
2612 mRemovedEndOffset == 45, // 55 - (10 - 20)
2613 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2614 "text without already added length");
2615 MOZ_ASSERT(
2616 mAddedEndOffset == 60,
2617 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2618 Clear();
2620 // Removing text at different point (not sure if actually occurs)
2621 MergeWith(TextChangeData(10, 20, 10, false, false));
2622 MergeWith(TextChangeData(55, 68, 55, false, false));
2623 MOZ_ASSERT(mStartOffset == 10,
2624 "Test 1-5-1: mStartOffset should be the smallest offset");
2625 MOZ_ASSERT(
2626 mRemovedEndOffset == 78, // 68 - (10 - 20)
2627 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2628 "text with already removed length");
2629 MOZ_ASSERT(
2630 mAddedEndOffset == 55,
2631 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2632 Clear();
2634 // Replacing text and append text (becomes longer)
2635 MergeWith(TextChangeData(30, 35, 32, false, false));
2636 MergeWith(TextChangeData(32, 32, 40, false, false));
2637 MOZ_ASSERT(mStartOffset == 30,
2638 "Test 1-6-1: mStartOffset should be the smallest offset");
2639 MOZ_ASSERT(
2640 mRemovedEndOffset == 35, // 32 - (32 - 35)
2641 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2642 "text");
2643 MOZ_ASSERT(
2644 mAddedEndOffset == 40,
2645 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2646 Clear();
2648 // Replacing text and append text (becomes shorter)
2649 MergeWith(TextChangeData(30, 35, 32, false, false));
2650 MergeWith(TextChangeData(32, 32, 33, false, false));
2651 MOZ_ASSERT(mStartOffset == 30,
2652 "Test 1-7-1: mStartOffset should be the smallest offset");
2653 MOZ_ASSERT(
2654 mRemovedEndOffset == 35, // 32 - (32 - 35)
2655 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2656 "text");
2657 MOZ_ASSERT(
2658 mAddedEndOffset == 33,
2659 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2660 Clear();
2662 // Removing text and replacing text after first range (not sure if actually
2663 // occurs)
2664 MergeWith(TextChangeData(30, 35, 30, false, false));
2665 MergeWith(TextChangeData(32, 34, 48, false, false));
2666 MOZ_ASSERT(mStartOffset == 30,
2667 "Test 1-8-1: mStartOffset should be the smallest offset");
2668 MOZ_ASSERT(mRemovedEndOffset == 39, // 34 - (30 - 35)
2669 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2670 "removed text "
2671 "without already removed text");
2672 MOZ_ASSERT(
2673 mAddedEndOffset == 48,
2674 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2675 Clear();
2677 // Removing text and replacing text after first range (not sure if actually
2678 // occurs)
2679 MergeWith(TextChangeData(30, 35, 30, false, false));
2680 MergeWith(TextChangeData(32, 38, 36, false, false));
2681 MOZ_ASSERT(mStartOffset == 30,
2682 "Test 1-9-1: mStartOffset should be the smallest offset");
2683 MOZ_ASSERT(mRemovedEndOffset == 43, // 38 - (30 - 35)
2684 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2685 "removed text "
2686 "without already removed text");
2687 MOZ_ASSERT(
2688 mAddedEndOffset == 36,
2689 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2690 Clear();
2692 /****************************************************************************
2693 * Case 2
2694 ****************************************************************************/
2696 // Replacing text in around end of added text (becomes shorter) (not sure
2697 // if actually occurs)
2698 MergeWith(TextChangeData(50, 50, 55, false, false));
2699 MergeWith(TextChangeData(53, 60, 54, false, false));
2700 MOZ_ASSERT(mStartOffset == 50,
2701 "Test 2-1-1: mStartOffset should be the smallest offset");
2702 MOZ_ASSERT(mRemovedEndOffset == 55, // 60 - (55 - 50)
2703 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2704 "removed text "
2705 "without already added text length");
2706 MOZ_ASSERT(
2707 mAddedEndOffset == 54,
2708 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2709 Clear();
2711 // Replacing text around end of added text (becomes longer) (not sure
2712 // if actually occurs)
2713 MergeWith(TextChangeData(50, 50, 55, false, false));
2714 MergeWith(TextChangeData(54, 62, 68, false, false));
2715 MOZ_ASSERT(mStartOffset == 50,
2716 "Test 2-2-1: mStartOffset should be the smallest offset");
2717 MOZ_ASSERT(mRemovedEndOffset == 57, // 62 - (55 - 50)
2718 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2719 "removed text "
2720 "without already added text length");
2721 MOZ_ASSERT(
2722 mAddedEndOffset == 68,
2723 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2724 Clear();
2726 // Replacing text around end of replaced text (became shorter) (not sure if
2727 // actually occurs)
2728 MergeWith(TextChangeData(36, 48, 45, false, false));
2729 MergeWith(TextChangeData(43, 50, 49, false, false));
2730 MOZ_ASSERT(mStartOffset == 36,
2731 "Test 2-3-1: mStartOffset should be the smallest offset");
2732 MOZ_ASSERT(mRemovedEndOffset == 53, // 50 - (45 - 48)
2733 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2734 "removed text "
2735 "without already removed text length");
2736 MOZ_ASSERT(
2737 mAddedEndOffset == 49,
2738 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2739 Clear();
2741 // Replacing text around end of replaced text (became longer) (not sure if
2742 // actually occurs)
2743 MergeWith(TextChangeData(36, 52, 53, false, false));
2744 MergeWith(TextChangeData(43, 68, 61, false, false));
2745 MOZ_ASSERT(mStartOffset == 36,
2746 "Test 2-4-1: mStartOffset should be the smallest offset");
2747 MOZ_ASSERT(mRemovedEndOffset == 67, // 68 - (53 - 52)
2748 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2749 "removed text "
2750 "without already added text length");
2751 MOZ_ASSERT(
2752 mAddedEndOffset == 61,
2753 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2754 Clear();
2756 /****************************************************************************
2757 * Case 3
2758 ****************************************************************************/
2760 // Appending text in already added text (not sure if actually occurs)
2761 MergeWith(TextChangeData(10, 10, 20, false, false));
2762 MergeWith(TextChangeData(15, 15, 30, false, false));
2763 MOZ_ASSERT(mStartOffset == 10,
2764 "Test 3-1-1: mStartOffset should be the smallest offset");
2765 MOZ_ASSERT(mRemovedEndOffset == 10,
2766 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2767 "removed text");
2768 MOZ_ASSERT(
2769 mAddedEndOffset == 35, // 20 + (30 - 15)
2770 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2771 "added text length by the new change");
2772 Clear();
2774 // Replacing text in added text (not sure if actually occurs)
2775 MergeWith(TextChangeData(50, 50, 55, false, false));
2776 MergeWith(TextChangeData(52, 53, 56, false, false));
2777 MOZ_ASSERT(mStartOffset == 50,
2778 "Test 3-2-1: mStartOffset should be the smallest offset");
2779 MOZ_ASSERT(mRemovedEndOffset == 50,
2780 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2781 "removed text");
2782 MOZ_ASSERT(
2783 mAddedEndOffset == 58, // 55 + (56 - 53)
2784 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2785 "added text length by the new change");
2786 Clear();
2788 // Replacing text in replaced text (became shorter) (not sure if actually
2789 // occurs)
2790 MergeWith(TextChangeData(36, 48, 45, false, false));
2791 MergeWith(TextChangeData(37, 38, 50, false, false));
2792 MOZ_ASSERT(mStartOffset == 36,
2793 "Test 3-3-1: mStartOffset should be the smallest offset");
2794 MOZ_ASSERT(mRemovedEndOffset == 48,
2795 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2796 "removed text");
2797 MOZ_ASSERT(
2798 mAddedEndOffset == 57, // 45 + (50 - 38)
2799 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2800 "added text length by the new change");
2801 Clear();
2803 // Replacing text in replaced text (became longer) (not sure if actually
2804 // occurs)
2805 MergeWith(TextChangeData(32, 48, 53, false, false));
2806 MergeWith(TextChangeData(43, 50, 52, false, false));
2807 MOZ_ASSERT(mStartOffset == 32,
2808 "Test 3-4-1: mStartOffset should be the smallest offset");
2809 MOZ_ASSERT(mRemovedEndOffset == 48,
2810 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2811 "removed text "
2812 "without already added text length");
2813 MOZ_ASSERT(
2814 mAddedEndOffset == 55, // 53 + (52 - 50)
2815 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2816 "added text length by the new change");
2817 Clear();
2819 // Replacing text in replaced text (became shorter) (not sure if actually
2820 // occurs)
2821 MergeWith(TextChangeData(36, 48, 50, false, false));
2822 MergeWith(TextChangeData(37, 49, 47, false, false));
2823 MOZ_ASSERT(mStartOffset == 36,
2824 "Test 3-5-1: mStartOffset should be the smallest offset");
2825 MOZ_ASSERT(
2826 mRemovedEndOffset == 48,
2827 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
2828 "text");
2829 MOZ_ASSERT(mAddedEndOffset == 48, // 50 + (47 - 49)
2830 "Test 3-5-3: mAddedEndOffset should be the first end of added "
2831 "text without "
2832 "removed text length by the new change");
2833 Clear();
2835 // Replacing text in replaced text (became longer) (not sure if actually
2836 // occurs)
2837 MergeWith(TextChangeData(32, 48, 53, false, false));
2838 MergeWith(TextChangeData(43, 50, 47, false, false));
2839 MOZ_ASSERT(mStartOffset == 32,
2840 "Test 3-6-1: mStartOffset should be the smallest offset");
2841 MOZ_ASSERT(mRemovedEndOffset == 48,
2842 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
2843 "removed text "
2844 "without already added text length");
2845 MOZ_ASSERT(mAddedEndOffset == 50, // 53 + (47 - 50)
2846 "Test 3-6-3: mAddedEndOffset should be the first end of added "
2847 "text without "
2848 "removed text length by the new change");
2849 Clear();
2851 /****************************************************************************
2852 * Case 4
2853 ****************************************************************************/
2855 // Replacing text all of already append text (not sure if actually occurs)
2856 MergeWith(TextChangeData(50, 50, 55, false, false));
2857 MergeWith(TextChangeData(44, 66, 68, false, false));
2858 MOZ_ASSERT(mStartOffset == 44,
2859 "Test 4-1-1: mStartOffset should be the smallest offset");
2860 MOZ_ASSERT(mRemovedEndOffset == 61, // 66 - (55 - 50)
2861 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
2862 "removed text "
2863 "without already added text length");
2864 MOZ_ASSERT(
2865 mAddedEndOffset == 68,
2866 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
2867 Clear();
2869 // Replacing text around a point in which text was removed (not sure if
2870 // actually occurs)
2871 MergeWith(TextChangeData(50, 62, 50, false, false));
2872 MergeWith(TextChangeData(44, 66, 68, false, false));
2873 MOZ_ASSERT(mStartOffset == 44,
2874 "Test 4-2-1: mStartOffset should be the smallest offset");
2875 MOZ_ASSERT(mRemovedEndOffset == 78, // 66 - (50 - 62)
2876 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
2877 "removed text "
2878 "without already removed text length");
2879 MOZ_ASSERT(
2880 mAddedEndOffset == 68,
2881 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
2882 Clear();
2884 // Replacing text all replaced text (became shorter) (not sure if actually
2885 // occurs)
2886 MergeWith(TextChangeData(50, 62, 60, false, false));
2887 MergeWith(TextChangeData(49, 128, 130, false, false));
2888 MOZ_ASSERT(mStartOffset == 49,
2889 "Test 4-3-1: mStartOffset should be the smallest offset");
2890 MOZ_ASSERT(mRemovedEndOffset == 130, // 128 - (60 - 62)
2891 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
2892 "removed text "
2893 "without already removed text length");
2894 MOZ_ASSERT(
2895 mAddedEndOffset == 130,
2896 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
2897 Clear();
2899 // Replacing text all replaced text (became longer) (not sure if actually
2900 // occurs)
2901 MergeWith(TextChangeData(50, 61, 73, false, false));
2902 MergeWith(TextChangeData(44, 100, 50, false, false));
2903 MOZ_ASSERT(mStartOffset == 44,
2904 "Test 4-4-1: mStartOffset should be the smallest offset");
2905 MOZ_ASSERT(mRemovedEndOffset == 88, // 100 - (73 - 61)
2906 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
2907 "removed text "
2908 "with already added text length");
2909 MOZ_ASSERT(
2910 mAddedEndOffset == 50,
2911 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
2912 Clear();
2914 /****************************************************************************
2915 * Case 5
2916 ****************************************************************************/
2918 // Replacing text around start of added text (not sure if actually occurs)
2919 MergeWith(TextChangeData(50, 50, 55, false, false));
2920 MergeWith(TextChangeData(48, 52, 49, false, false));
2921 MOZ_ASSERT(mStartOffset == 48,
2922 "Test 5-1-1: mStartOffset should be the smallest offset");
2923 MOZ_ASSERT(
2924 mRemovedEndOffset == 50,
2925 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
2926 "text");
2927 MOZ_ASSERT(
2928 mAddedEndOffset == 52, // 55 + (52 - 49)
2929 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
2930 "added text length by the new change");
2931 Clear();
2933 // Replacing text around start of replaced text (became shorter) (not sure if
2934 // actually occurs)
2935 MergeWith(TextChangeData(50, 60, 58, false, false));
2936 MergeWith(TextChangeData(43, 50, 48, false, false));
2937 MOZ_ASSERT(mStartOffset == 43,
2938 "Test 5-2-1: mStartOffset should be the smallest offset");
2939 MOZ_ASSERT(
2940 mRemovedEndOffset == 60,
2941 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
2942 "text");
2943 MOZ_ASSERT(mAddedEndOffset == 56, // 58 + (48 - 50)
2944 "Test 5-2-3: mAddedEndOffset should be the first end of added "
2945 "text without "
2946 "removed text length by the new change");
2947 Clear();
2949 // Replacing text around start of replaced text (became longer) (not sure if
2950 // actually occurs)
2951 MergeWith(TextChangeData(50, 60, 68, false, false));
2952 MergeWith(TextChangeData(43, 55, 53, false, false));
2953 MOZ_ASSERT(mStartOffset == 43,
2954 "Test 5-3-1: mStartOffset should be the smallest offset");
2955 MOZ_ASSERT(
2956 mRemovedEndOffset == 60,
2957 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
2958 "text");
2959 MOZ_ASSERT(mAddedEndOffset == 66, // 68 + (53 - 55)
2960 "Test 5-3-3: mAddedEndOffset should be the first end of added "
2961 "text without "
2962 "removed text length by the new change");
2963 Clear();
2965 // Replacing text around start of replaced text (became shorter) (not sure if
2966 // actually occurs)
2967 MergeWith(TextChangeData(50, 60, 58, false, false));
2968 MergeWith(TextChangeData(43, 50, 128, false, false));
2969 MOZ_ASSERT(mStartOffset == 43,
2970 "Test 5-4-1: mStartOffset should be the smallest offset");
2971 MOZ_ASSERT(
2972 mRemovedEndOffset == 60,
2973 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
2974 "text");
2975 MOZ_ASSERT(
2976 mAddedEndOffset == 136, // 58 + (128 - 50)
2977 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
2978 "added text length by the new change");
2979 Clear();
2981 // Replacing text around start of replaced text (became longer) (not sure if
2982 // actually occurs)
2983 MergeWith(TextChangeData(50, 60, 68, false, false));
2984 MergeWith(TextChangeData(43, 55, 65, false, false));
2985 MOZ_ASSERT(mStartOffset == 43,
2986 "Test 5-5-1: mStartOffset should be the smallest offset");
2987 MOZ_ASSERT(
2988 mRemovedEndOffset == 60,
2989 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
2990 "text");
2991 MOZ_ASSERT(
2992 mAddedEndOffset == 78, // 68 + (65 - 55)
2993 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
2994 "added text length by the new change");
2995 Clear();
2997 /****************************************************************************
2998 * Case 6
2999 ****************************************************************************/
3001 // Appending text before already added text (not sure if actually occurs)
3002 MergeWith(TextChangeData(30, 30, 45, false, false));
3003 MergeWith(TextChangeData(10, 10, 20, false, false));
3004 MOZ_ASSERT(mStartOffset == 10,
3005 "Test 6-1-1: mStartOffset should be the smallest offset");
3006 MOZ_ASSERT(
3007 mRemovedEndOffset == 30,
3008 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3009 "text");
3010 MOZ_ASSERT(
3011 mAddedEndOffset == 55, // 45 + (20 - 10)
3012 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3013 "added text length by the new change");
3014 Clear();
3016 // Removing text before already removed text (not sure if actually occurs)
3017 MergeWith(TextChangeData(30, 35, 30, false, false));
3018 MergeWith(TextChangeData(10, 25, 10, false, false));
3019 MOZ_ASSERT(mStartOffset == 10,
3020 "Test 6-2-1: mStartOffset should be the smallest offset");
3021 MOZ_ASSERT(
3022 mRemovedEndOffset == 35,
3023 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3024 "text");
3025 MOZ_ASSERT(
3026 mAddedEndOffset == 15, // 30 - (25 - 10)
3027 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3028 "removed text length by the new change");
3029 Clear();
3031 // Replacing text before already replaced text (not sure if actually occurs)
3032 MergeWith(TextChangeData(50, 65, 70, false, false));
3033 MergeWith(TextChangeData(13, 24, 15, false, false));
3034 MOZ_ASSERT(mStartOffset == 13,
3035 "Test 6-3-1: mStartOffset should be the smallest offset");
3036 MOZ_ASSERT(
3037 mRemovedEndOffset == 65,
3038 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3039 "text");
3040 MOZ_ASSERT(mAddedEndOffset == 61, // 70 + (15 - 24)
3041 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3042 "text without "
3043 "removed text length by the new change");
3044 Clear();
3046 // Replacing text before already replaced text (not sure if actually occurs)
3047 MergeWith(TextChangeData(50, 65, 70, false, false));
3048 MergeWith(TextChangeData(13, 24, 36, false, false));
3049 MOZ_ASSERT(mStartOffset == 13,
3050 "Test 6-4-1: mStartOffset should be the smallest offset");
3051 MOZ_ASSERT(
3052 mRemovedEndOffset == 65,
3053 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3054 "text");
3055 MOZ_ASSERT(mAddedEndOffset == 82, // 70 + (36 - 24)
3056 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3057 "text without "
3058 "removed text length by the new change");
3059 Clear();
3062 #endif // #ifdef DEBUG
3064 } // namespace mozilla::widget
3066 #ifdef DEBUG
3067 //////////////////////////////////////////////////////////////
3069 // Convert a GUI event message code to a string.
3070 // Makes it a lot easier to debug events.
3072 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3073 // for a DebugPrintEvent() function that uses
3074 // this.
3076 //////////////////////////////////////////////////////////////
3077 /* static */
3078 nsAutoString nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent* aGuiEvent) {
3079 NS_ASSERTION(nullptr != aGuiEvent, "cmon, null gui event.");
3081 nsAutoString eventName(u"UNKNOWN"_ns);
3083 # define _ASSIGN_eventName(_value, _name) \
3084 case _value: \
3085 eventName.AssignLiteral(_name); \
3086 break
3088 switch (aGuiEvent->mMessage) {
3089 _ASSIGN_eventName(eBlur, "eBlur");
3090 _ASSIGN_eventName(eDrop, "eDrop");
3091 _ASSIGN_eventName(eDragEnter, "eDragEnter");
3092 _ASSIGN_eventName(eDragExit, "eDragExit");
3093 _ASSIGN_eventName(eDragOver, "eDragOver");
3094 _ASSIGN_eventName(eEditorInput, "eEditorInput");
3095 _ASSIGN_eventName(eFocus, "eFocus");
3096 _ASSIGN_eventName(eFocusIn, "eFocusIn");
3097 _ASSIGN_eventName(eFocusOut, "eFocusOut");
3098 _ASSIGN_eventName(eFormSelect, "eFormSelect");
3099 _ASSIGN_eventName(eFormChange, "eFormChange");
3100 _ASSIGN_eventName(eFormReset, "eFormReset");
3101 _ASSIGN_eventName(eFormSubmit, "eFormSubmit");
3102 _ASSIGN_eventName(eImageAbort, "eImageAbort");
3103 _ASSIGN_eventName(eLoadError, "eLoadError");
3104 _ASSIGN_eventName(eKeyDown, "eKeyDown");
3105 _ASSIGN_eventName(eKeyPress, "eKeyPress");
3106 _ASSIGN_eventName(eKeyUp, "eKeyUp");
3107 _ASSIGN_eventName(eMouseEnterIntoWidget, "eMouseEnterIntoWidget");
3108 _ASSIGN_eventName(eMouseExitFromWidget, "eMouseExitFromWidget");
3109 _ASSIGN_eventName(eMouseDown, "eMouseDown");
3110 _ASSIGN_eventName(eMouseUp, "eMouseUp");
3111 _ASSIGN_eventName(eMouseClick, "eMouseClick");
3112 _ASSIGN_eventName(eMouseAuxClick, "eMouseAuxClick");
3113 _ASSIGN_eventName(eMouseDoubleClick, "eMouseDoubleClick");
3114 _ASSIGN_eventName(eMouseMove, "eMouseMove");
3115 _ASSIGN_eventName(eLoad, "eLoad");
3116 _ASSIGN_eventName(ePopState, "ePopState");
3117 _ASSIGN_eventName(eBeforeScriptExecute, "eBeforeScriptExecute");
3118 _ASSIGN_eventName(eAfterScriptExecute, "eAfterScriptExecute");
3119 _ASSIGN_eventName(eUnload, "eUnload");
3120 _ASSIGN_eventName(eHashChange, "eHashChange");
3121 _ASSIGN_eventName(eReadyStateChange, "eReadyStateChange");
3122 _ASSIGN_eventName(eXULBroadcast, "eXULBroadcast");
3123 _ASSIGN_eventName(eXULCommandUpdate, "eXULCommandUpdate");
3125 # undef _ASSIGN_eventName
3127 default: {
3128 eventName.AssignLiteral("UNKNOWN: ");
3129 eventName.AppendInt(aGuiEvent->mMessage);
3130 } break;
3133 return nsAutoString(eventName);
3135 //////////////////////////////////////////////////////////////
3137 // Code to deal with paint and event debug prefs.
3139 //////////////////////////////////////////////////////////////
3140 struct PrefPair {
3141 const char* name;
3142 bool value;
3145 static PrefPair debug_PrefValues[] = {
3146 {"nglayout.debug.crossing_event_dumping", false},
3147 {"nglayout.debug.event_dumping", false},
3148 {"nglayout.debug.invalidate_dumping", false},
3149 {"nglayout.debug.motion_event_dumping", false},
3150 {"nglayout.debug.paint_dumping", false},
3151 {"nglayout.debug.paint_flashing", false},
3152 {"nglayout.debug.paint_flashing_chrome", false}};
3154 //////////////////////////////////////////////////////////////
3155 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName) {
3156 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3158 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3159 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3160 return debug_PrefValues[i].value;
3164 return false;
3166 //////////////////////////////////////////////////////////////
3167 static void debug_SetCachedBoolPref(const char* aPrefName, bool aValue) {
3168 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3170 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3171 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3172 debug_PrefValues[i].value = aValue;
3174 return;
3178 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3181 //////////////////////////////////////////////////////////////
3182 class Debug_PrefObserver final : public nsIObserver {
3183 ~Debug_PrefObserver() = default;
3185 public:
3186 NS_DECL_ISUPPORTS
3187 NS_DECL_NSIOBSERVER
3190 NS_IMPL_ISUPPORTS(Debug_PrefObserver, nsIObserver)
3192 NS_IMETHODIMP
3193 Debug_PrefObserver::Observe(nsISupports* subject, const char* topic,
3194 const char16_t* data) {
3195 NS_ConvertUTF16toUTF8 prefName(data);
3197 bool value = Preferences::GetBool(prefName.get(), false);
3198 debug_SetCachedBoolPref(prefName.get(), value);
3199 return NS_OK;
3202 //////////////////////////////////////////////////////////////
3203 /* static */ void debug_RegisterPrefCallbacks() {
3204 static bool once = true;
3206 if (!once) {
3207 return;
3210 once = false;
3212 nsCOMPtr<nsIObserver> obs(new Debug_PrefObserver());
3213 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3214 // Initialize the pref values
3215 debug_PrefValues[i].value =
3216 Preferences::GetBool(debug_PrefValues[i].name, false);
3218 if (obs) {
3219 // Register callbacks for when these change
3220 nsCString name;
3221 name.AssignLiteral(debug_PrefValues[i].name,
3222 strlen(debug_PrefValues[i].name));
3223 Preferences::AddStrongObserver(obs, name);
3227 //////////////////////////////////////////////////////////////
3228 static int32_t _GetPrintCount() {
3229 static int32_t sCount = 0;
3231 return ++sCount;
3233 //////////////////////////////////////////////////////////////
3234 /* static */
3235 bool nsBaseWidget::debug_WantPaintFlashing() {
3236 return debug_GetCachedBoolPref("nglayout.debug.paint_flashing");
3238 //////////////////////////////////////////////////////////////
3239 /* static */
3240 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut, nsIWidget* aWidget,
3241 WidgetGUIEvent* aGuiEvent,
3242 const char* aWidgetName, int32_t aWindowID) {
3243 if (aGuiEvent->mMessage == eMouseMove) {
3244 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3247 if (aGuiEvent->mMessage == eMouseEnterIntoWidget ||
3248 aGuiEvent->mMessage == eMouseExitFromWidget) {
3249 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3250 return;
3253 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3255 NS_LossyConvertUTF16toASCII tempString(
3256 debug_GuiEventToString(aGuiEvent).get());
3258 fprintf(aFileOut, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3259 _GetPrintCount(), tempString.get(), (void*)aWidget, aWidgetName,
3260 aWindowID, aGuiEvent->mRefPoint.x, aGuiEvent->mRefPoint.y);
3262 //////////////////////////////////////////////////////////////
3263 /* static */
3264 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut, nsIWidget* aWidget,
3265 const nsIntRegion& aRegion,
3266 const char* aWidgetName,
3267 int32_t aWindowID) {
3268 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3269 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3271 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3273 nsIntRect rect = aRegion.GetBounds();
3274 fprintf(aFileOut,
3275 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3276 "%3d,%-3d",
3277 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID, rect.X(),
3278 rect.Y(), rect.Width(), rect.Height());
3280 fprintf(aFileOut, "\n");
3282 //////////////////////////////////////////////////////////////
3283 /* static */
3284 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut, nsIWidget* aWidget,
3285 const LayoutDeviceIntRect* aRect,
3286 const char* aWidgetName,
3287 int32_t aWindowID) {
3288 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3290 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3291 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3293 fprintf(aFileOut, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3294 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID);
3296 if (aRect) {
3297 fprintf(aFileOut, " rect=%3d,%-3d %3d,%-3d", aRect->X(), aRect->Y(),
3298 aRect->Width(), aRect->Height());
3299 } else {
3300 fprintf(aFileOut, " rect=%-15s", "none");
3303 fprintf(aFileOut, "\n");
3305 //////////////////////////////////////////////////////////////
3307 #endif // DEBUG