Bug 1700051: part 28) Refactor `WordSplitState<T>::GetDOMWordSeparatorOffset` to...
[gecko.git] / widget / nsBaseWidget.cpp
blob5e7251485384cd6d4227a622c95e24d1189771f1
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 "nsAppDirectoryServiceDefs.h"
62 #include "nsCOMPtr.h"
63 #include "nsContentUtils.h"
64 #include "nsDeviceContext.h"
65 #include "nsGfxCIID.h"
66 #include "nsIAppWindow.h"
67 #include "nsIBaseWindow.h"
68 #include "nsIContent.h"
69 #include "nsIScreenManager.h"
70 #include "nsISimpleEnumerator.h"
71 #include "nsIWidgetListener.h"
72 #include "nsRefPtrHashtable.h"
73 #include "nsServiceManagerUtils.h"
74 #include "nsWidgetsCID.h"
75 #include "nsXULPopupManager.h"
76 #include "prdtoa.h"
77 #include "prenv.h"
78 #ifdef ACCESSIBILITY
79 # include "nsAccessibilityService.h"
80 #endif
81 #include "gfxConfig.h"
82 #include "gfxUtils.h" // for ToDeviceColor
83 #include "mozilla/layers/CompositorSession.h"
84 #include "VRManagerChild.h"
85 #include "gfxConfig.h"
86 #include "nsView.h"
87 #include "nsViewManager.h"
89 #ifdef DEBUG
90 # include "nsIObserver.h"
92 static void debug_RegisterPrefCallbacks();
94 #endif
96 #ifdef NOISY_WIDGET_LEAKS
97 static int32_t gNumWidgets;
98 #endif
100 #ifdef XP_MACOSX
101 # include "nsCocoaFeatures.h"
102 #endif
104 #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
105 static nsRefPtrHashtable<nsVoidPtrHashKey, nsIWidget>* sPluginWidgetList;
106 #endif
108 nsIRollupListener* nsBaseWidget::gRollupListener = nullptr;
110 using namespace mozilla::dom;
111 using namespace mozilla::layers;
112 using namespace mozilla::ipc;
113 using namespace mozilla::widget;
114 using namespace mozilla;
116 // Async pump timer during injected long touch taps
117 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
118 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
119 int32_t nsIWidget::sPointerIdCounter = 0;
121 // Some statics from nsIWidget.h
122 /*static*/
123 uint64_t AutoObserverNotifier::sObserverId = 0;
124 /*static*/ nsTHashMap<uint64_t, nsCOMPtr<nsIObserver>>
125 AutoObserverNotifier::sSavedObservers;
127 // The maximum amount of time to let the EnableDragDrop runnable wait in the
128 // idle queue before timing out and moving it to the regular queue. Value is in
129 // milliseconds.
130 const uint32_t kAsyncDragDropTimeout = 1000;
132 namespace mozilla::widget {
134 void IMENotification::SelectionChangeDataBase::SetWritingMode(
135 const WritingMode& aWritingMode) {
136 mWritingMode = aWritingMode.mWritingMode.bits;
139 WritingMode IMENotification::SelectionChangeDataBase::GetWritingMode() const {
140 return WritingMode(mWritingMode);
143 } // namespace mozilla::widget
145 NS_IMPL_ISUPPORTS(nsBaseWidget, nsIWidget, nsISupportsWeakReference)
147 //-------------------------------------------------------------------------
149 // nsBaseWidget constructor
151 //-------------------------------------------------------------------------
153 nsBaseWidget::nsBaseWidget()
154 : mWidgetListener(nullptr),
155 mAttachedWidgetListener(nullptr),
156 mPreviouslyAttachedWidgetListener(nullptr),
157 mLayerManager(nullptr),
158 mCompositorVsyncDispatcher(nullptr),
159 mCursor(eCursor_standard),
160 mBorderStyle(eBorderStyle_none),
161 mBounds(0, 0, 0, 0),
162 mOriginalBounds(nullptr),
163 mClipRectCount(0),
164 mSizeMode(nsSizeMode_Normal),
165 mIsTiled(false),
166 mPopupLevel(ePopupLevelTop),
167 mPopupType(ePopupTypeAny),
168 mHasRemoteContent(false),
169 mFissionWindow(false),
170 mUpdateCursor(true),
171 mUseAttachedEvents(false),
172 mIMEHasFocus(false),
173 mIMEHasQuit(false),
174 mIsFullyOccluded(false) {
175 #ifdef NOISY_WIDGET_LEAKS
176 gNumWidgets++;
177 printf("WIDGETS+ = %d\n", gNumWidgets);
178 #endif
180 #ifdef DEBUG
181 debug_RegisterPrefCallbacks();
182 #endif
184 #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
185 if (!sPluginWidgetList) {
186 sPluginWidgetList = new nsRefPtrHashtable<nsVoidPtrHashKey, nsIWidget>();
188 #endif
189 mShutdownObserver = new WidgetShutdownObserver(this);
192 NS_IMPL_ISUPPORTS(WidgetShutdownObserver, nsIObserver)
194 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget* aWidget)
195 : mWidget(aWidget), mRegistered(false) {
196 Register();
199 WidgetShutdownObserver::~WidgetShutdownObserver() {
200 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
201 // gets torn down. The observer service and nsBaseWidget have a ref on us
202 // so nsBaseWidget has to call Unregister and then clear its ref.
205 NS_IMETHODIMP
206 WidgetShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
207 const char16_t* aData) {
208 if (!mWidget) {
209 return NS_OK;
211 if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
212 RefPtr<nsBaseWidget> widget(mWidget);
213 widget->Shutdown();
214 } else if (!strcmp(aTopic, "quit-application")) {
215 RefPtr<nsBaseWidget> widget(mWidget);
216 widget->QuitIME();
218 return NS_OK;
221 void WidgetShutdownObserver::Register() {
222 if (!mRegistered) {
223 mRegistered = true;
224 nsContentUtils::RegisterShutdownObserver(this);
226 #ifndef MOZ_WIDGET_ANDROID
227 // The primary purpose of observing quit-application is
228 // to avoid leaking a widget on Windows when nothing else
229 // breaks the circular reference between the widget and
230 // TSFTextStore. However, our Android IME code crashes if
231 // doing this on Android, so let's not do this on Android.
232 // Doing this on Gtk and Mac just in case.
233 nsCOMPtr<nsIObserverService> observerService =
234 mozilla::services::GetObserverService();
235 if (observerService) {
236 observerService->AddObserver(this, "quit-application", false);
238 #endif
242 void WidgetShutdownObserver::Unregister() {
243 if (mRegistered) {
244 mWidget = nullptr;
246 #ifndef MOZ_WIDGET_ANDROID
247 nsCOMPtr<nsIObserverService> observerService =
248 mozilla::services::GetObserverService();
249 if (observerService) {
250 observerService->RemoveObserver(this, "quit-application");
252 #endif
254 nsContentUtils::UnregisterShutdownObserver(this);
255 mRegistered = false;
259 void nsBaseWidget::Shutdown() {
260 NotifyLiveResizeStopped();
261 RevokeTransactionIdAllocator();
262 DestroyCompositor();
263 FreeShutdownObserver();
264 #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
265 if (sPluginWidgetList) {
266 delete sPluginWidgetList;
267 sPluginWidgetList = nullptr;
269 #endif
272 void nsBaseWidget::QuitIME() {
273 IMEStateManager::WidgetOnQuit(this);
274 this->mIMEHasQuit = true;
277 void nsBaseWidget::DestroyCompositor() {
278 // We release this before releasing the compositor, since it may hold the
279 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
280 // trigger a paint, creating a new compositor, and we don't want to re-use
281 // the old vsync dispatcher.
282 if (mCompositorVsyncDispatcher) {
283 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
285 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
286 mCompositorVsyncDispatcher->Shutdown();
287 mCompositorVsyncDispatcher = nullptr;
290 // The compositor shutdown sequence looks like this:
291 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
292 // 2. CompositorBridgeChild synchronously sends WillClose.
293 // 3. CompositorBridgeParent releases some resources (such as the layer
294 // manager, compositor, and widget).
295 // 4. CompositorBridgeChild::Destroy returns.
296 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
297 // compositor thread when the I/O thread closes the IPC channel.
298 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
299 // releases the reference CompositorBridgeParent holds to itself.
301 // When CompositorSession::Shutdown returns, we assume the compositor is gone
302 // or will be gone very soon.
303 if (mCompositorSession) {
304 ReleaseContentController();
305 mAPZC = nullptr;
306 SetCompositorWidgetDelegate(nullptr);
307 mCompositorBridgeChild = nullptr;
309 // XXX CompositorBridgeChild and CompositorBridgeParent might be re-created
310 // in ClientLayerManager destructor. See bug 1133426.
311 RefPtr<CompositorSession> session = std::move(mCompositorSession);
312 session->Shutdown();
316 // This prevents the layer manager from starting a new transaction during
317 // shutdown.
318 void nsBaseWidget::RevokeTransactionIdAllocator() {
319 if (!mLayerManager) {
320 return;
322 mLayerManager->SetTransactionIdAllocator(nullptr);
325 void nsBaseWidget::ReleaseContentController() {
326 if (mRootContentController) {
327 mRootContentController->Destroy();
328 mRootContentController = nullptr;
332 void nsBaseWidget::DestroyLayerManager() {
333 if (mLayerManager) {
334 mLayerManager->Destroy();
335 mLayerManager = nullptr;
337 DestroyCompositor();
340 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
342 void nsBaseWidget::FreeShutdownObserver() {
343 if (mShutdownObserver) {
344 mShutdownObserver->Unregister();
346 mShutdownObserver = nullptr;
349 //-------------------------------------------------------------------------
351 // nsBaseWidget destructor
353 //-------------------------------------------------------------------------
355 nsBaseWidget::~nsBaseWidget() {
356 IMEStateManager::WidgetDestroyed(this);
358 if (mLayerManager) {
359 if (BasicLayerManager* mgr = mLayerManager->AsBasicLayerManager()) {
360 mgr->ClearRetainerWidget();
364 FreeShutdownObserver();
365 RevokeTransactionIdAllocator();
366 DestroyLayerManager();
368 #ifdef NOISY_WIDGET_LEAKS
369 gNumWidgets--;
370 printf("WIDGETS- = %d\n", gNumWidgets);
371 #endif
373 delete mOriginalBounds;
376 //-------------------------------------------------------------------------
378 // Basic create.
380 //-------------------------------------------------------------------------
381 void nsBaseWidget::BaseCreate(nsIWidget* aParent, nsWidgetInitData* aInitData) {
382 // keep a reference to the device context
383 if (nullptr != aInitData) {
384 mWindowType = aInitData->mWindowType;
385 mBorderStyle = aInitData->mBorderStyle;
386 mPopupLevel = aInitData->mPopupLevel;
387 mPopupType = aInitData->mPopupHint;
388 mHasRemoteContent = aInitData->mHasRemoteContent;
389 mFissionWindow = aInitData->mFissionWindow;
392 if (aParent) {
393 aParent->AddChild(this);
397 //-------------------------------------------------------------------------
399 // Accessor functions to get/set the client data
401 //-------------------------------------------------------------------------
403 nsIWidgetListener* nsBaseWidget::GetWidgetListener() { return mWidgetListener; }
405 void nsBaseWidget::SetWidgetListener(nsIWidgetListener* aWidgetListener) {
406 mWidgetListener = aWidgetListener;
409 already_AddRefed<nsIWidget> nsBaseWidget::CreateChild(
410 const LayoutDeviceIntRect& aRect, nsWidgetInitData* aInitData,
411 bool aForceUseIWidgetParent) {
412 nsIWidget* parent = this;
413 nsNativeWidget nativeParent = nullptr;
415 if (!aForceUseIWidgetParent) {
416 // Use only either parent or nativeParent, not both, to match
417 // existing code. Eventually Create() should be divested of its
418 // nativeWidget parameter.
419 nativeParent = parent ? parent->GetNativeData(NS_NATIVE_WIDGET) : nullptr;
420 parent = nativeParent ? nullptr : parent;
421 MOZ_ASSERT(!parent || !nativeParent, "messed up logic");
424 nsCOMPtr<nsIWidget> widget;
425 if (aInitData && aInitData->mWindowType == eWindowType_popup) {
426 widget = AllocateChildPopupWidget();
427 } else {
428 widget = nsIWidget::CreateChildWindow();
431 if (widget &&
432 NS_SUCCEEDED(widget->Create(parent, nativeParent, aRect, aInitData))) {
433 return widget.forget();
436 return nullptr;
439 // Attach a view to our widget which we'll send events to.
440 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents) {
441 NS_ASSERTION((mWindowType == eWindowType_toplevel ||
442 mWindowType == eWindowType_dialog ||
443 mWindowType == eWindowType_invisible ||
444 mWindowType == eWindowType_child),
445 "Can't attach to window of that type");
447 mUseAttachedEvents = aUseAttachedEvents;
450 nsIWidgetListener* nsBaseWidget::GetAttachedWidgetListener() {
451 return mAttachedWidgetListener;
454 nsIWidgetListener* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
455 return mPreviouslyAttachedWidgetListener;
458 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
459 nsIWidgetListener* aListener) {
460 mPreviouslyAttachedWidgetListener = aListener;
463 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener* aListener) {
464 mAttachedWidgetListener = aListener;
467 //-------------------------------------------------------------------------
469 // Close this nsBaseWidget
471 //-------------------------------------------------------------------------
472 void nsBaseWidget::Destroy() {
473 // Just in case our parent is the only ref to us
474 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
475 // disconnect from the parent
476 nsIWidget* parent = GetParent();
477 if (parent) {
478 parent->RemoveChild(this);
481 #if defined(XP_WIN)
482 // Allow our scroll capture container to be cleaned up, if we have one.
483 mScrollCaptureContainer = nullptr;
484 #endif
487 //-------------------------------------------------------------------------
489 // Get this nsBaseWidget parent
491 //-------------------------------------------------------------------------
492 nsIWidget* nsBaseWidget::GetParent(void) { return nullptr; }
494 //-------------------------------------------------------------------------
496 // Get this nsBaseWidget top level widget
498 //-------------------------------------------------------------------------
499 nsIWidget* nsBaseWidget::GetTopLevelWidget() {
500 nsIWidget *topLevelWidget = nullptr, *widget = this;
501 while (widget) {
502 topLevelWidget = widget;
503 widget = widget->GetParent();
505 return topLevelWidget;
508 //-------------------------------------------------------------------------
510 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
512 //-------------------------------------------------------------------------
513 nsIWidget* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
515 float nsBaseWidget::GetDPI() { return 96.0f; }
517 CSSToLayoutDeviceScale nsIWidget::GetDefaultScale() {
518 double devPixelsPerCSSPixel = StaticPrefs::layout_css_devPixelsPerPx();
520 if (devPixelsPerCSSPixel <= 0.0) {
521 devPixelsPerCSSPixel = GetDefaultScaleInternal();
524 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel);
527 //-------------------------------------------------------------------------
529 // Add a child to the list of children
531 //-------------------------------------------------------------------------
532 void nsBaseWidget::AddChild(nsIWidget* aChild) {
533 MOZ_ASSERT(!aChild->GetNextSibling() && !aChild->GetPrevSibling(),
534 "aChild not properly removed from its old child list");
536 if (!mFirstChild) {
537 mFirstChild = mLastChild = aChild;
538 } else {
539 // append to the list
540 MOZ_ASSERT(mLastChild);
541 MOZ_ASSERT(!mLastChild->GetNextSibling());
542 mLastChild->SetNextSibling(aChild);
543 aChild->SetPrevSibling(mLastChild);
544 mLastChild = aChild;
548 //-------------------------------------------------------------------------
550 // Remove a child from the list of children
552 //-------------------------------------------------------------------------
553 void nsBaseWidget::RemoveChild(nsIWidget* aChild) {
554 #ifdef DEBUG
555 # ifdef XP_MACOSX
556 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
557 // null and we'll just have to do without this assertion.
558 nsIWidget* parent = aChild->GetParent();
559 NS_ASSERTION(!parent || parent == this, "Not one of our kids!");
560 # else
561 MOZ_RELEASE_ASSERT(aChild->GetParent() == this, "Not one of our kids!");
562 # endif
563 #endif
565 if (mLastChild == aChild) {
566 mLastChild = mLastChild->GetPrevSibling();
568 if (mFirstChild == aChild) {
569 mFirstChild = mFirstChild->GetNextSibling();
572 // Now remove from the list. Make sure that we pass ownership of the tail
573 // of the list correctly before we have aChild let go of it.
574 nsIWidget* prev = aChild->GetPrevSibling();
575 nsIWidget* next = aChild->GetNextSibling();
576 if (prev) {
577 prev->SetNextSibling(next);
579 if (next) {
580 next->SetPrevSibling(prev);
583 aChild->SetNextSibling(nullptr);
584 aChild->SetPrevSibling(nullptr);
587 //-------------------------------------------------------------------------
589 // Sets widget's position within its parent's child list.
591 //-------------------------------------------------------------------------
592 void nsBaseWidget::SetZIndex(int32_t aZIndex) {
593 // Hold a ref to ourselves just in case, since we're going to remove
594 // from our parent.
595 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
597 mZIndex = aZIndex;
599 // reorder this child in its parent's list.
600 auto* parent = static_cast<nsBaseWidget*>(GetParent());
601 if (parent) {
602 parent->RemoveChild(this);
603 // Scope sib outside the for loop so we can check it afterward
604 nsIWidget* sib = parent->GetFirstChild();
605 for (; sib; sib = sib->GetNextSibling()) {
606 int32_t childZIndex = GetZIndex();
607 if (aZIndex < childZIndex) {
608 // Insert ourselves before sib
609 nsIWidget* prev = sib->GetPrevSibling();
610 mNextSibling = sib;
611 mPrevSibling = prev;
612 sib->SetPrevSibling(this);
613 if (prev) {
614 prev->SetNextSibling(this);
615 } else {
616 NS_ASSERTION(sib == parent->mFirstChild, "Broken child list");
617 // We've taken ownership of sib, so it's safe to have parent let
618 // go of it
619 parent->mFirstChild = this;
621 PlaceBehind(eZPlacementBelow, sib, false);
622 break;
625 // were we added to the list?
626 if (!sib) {
627 parent->AddChild(this);
632 //-------------------------------------------------------------------------
634 // Maximize, minimize or restore the window. The BaseWidget implementation
635 // merely stores the state.
637 //-------------------------------------------------------------------------
638 void nsBaseWidget::SetSizeMode(nsSizeMode aMode) {
639 MOZ_ASSERT(aMode == nsSizeMode_Normal || aMode == nsSizeMode_Minimized ||
640 aMode == nsSizeMode_Maximized || aMode == nsSizeMode_Fullscreen);
641 mSizeMode = aMode;
644 void nsBaseWidget::GetWorkspaceID(nsAString& workspaceID) {
645 workspaceID.Truncate();
648 void nsBaseWidget::MoveToWorkspace(const nsAString& workspaceID) {
649 // Noop.
652 //-------------------------------------------------------------------------
654 // Get this component cursor
656 //-------------------------------------------------------------------------
658 void nsBaseWidget::SetCursor(nsCursor aCursor, imgIContainer*, uint32_t,
659 uint32_t) {
660 // We don't support the cursor image.
661 mCursor = aCursor;
664 //-------------------------------------------------------------------------
666 // Window transparency methods
668 //-------------------------------------------------------------------------
670 void nsBaseWidget::SetTransparencyMode(nsTransparencyMode aMode) {}
672 nsTransparencyMode nsBaseWidget::GetTransparencyMode() {
673 return eTransparencyOpaque;
676 bool nsBaseWidget::IsWindowClipRegionEqual(
677 const nsTArray<LayoutDeviceIntRect>& aRects) {
678 return mClipRects && mClipRectCount == aRects.Length() &&
679 memcmp(mClipRects.get(), aRects.Elements(),
680 sizeof(LayoutDeviceIntRect) * mClipRectCount) == 0;
683 void nsBaseWidget::StoreWindowClipRegion(
684 const nsTArray<LayoutDeviceIntRect>& aRects) {
685 mClipRectCount = aRects.Length();
686 mClipRects = MakeUnique<LayoutDeviceIntRect[]>(mClipRectCount);
687 if (mClipRects) {
688 memcpy(mClipRects.get(), aRects.Elements(),
689 sizeof(LayoutDeviceIntRect) * mClipRectCount);
693 void nsBaseWidget::GetWindowClipRegion(nsTArray<LayoutDeviceIntRect>* aRects) {
694 if (mClipRects) {
695 aRects->AppendElements(mClipRects.get(), mClipRectCount);
696 } else {
697 aRects->AppendElement(
698 LayoutDeviceIntRect(0, 0, mBounds.Width(), mBounds.Height()));
702 const LayoutDeviceIntRegion nsBaseWidget::RegionFromArray(
703 const nsTArray<LayoutDeviceIntRect>& aRects) {
704 LayoutDeviceIntRegion region;
705 for (uint32_t i = 0; i < aRects.Length(); ++i) {
706 region.Or(region, aRects[i]);
708 return region;
711 void nsBaseWidget::ArrayFromRegion(const LayoutDeviceIntRegion& aRegion,
712 nsTArray<LayoutDeviceIntRect>& aRects) {
713 for (auto iter = aRegion.RectIter(); !iter.Done(); iter.Next()) {
714 aRects.AppendElement(iter.Get());
718 nsresult nsBaseWidget::SetWindowClipRegion(
719 const nsTArray<LayoutDeviceIntRect>& aRects, bool aIntersectWithExisting) {
720 if (!aIntersectWithExisting) {
721 StoreWindowClipRegion(aRects);
722 } else {
723 // get current rects
724 nsTArray<LayoutDeviceIntRect> currentRects;
725 GetWindowClipRegion(&currentRects);
726 // create region from them
727 LayoutDeviceIntRegion currentRegion = RegionFromArray(currentRects);
728 // create region from new rects
729 LayoutDeviceIntRegion newRegion = RegionFromArray(aRects);
730 // intersect regions
731 LayoutDeviceIntRegion intersection;
732 intersection.And(currentRegion, newRegion);
733 // create int rect array from intersection
734 nsTArray<LayoutDeviceIntRect> rects;
735 ArrayFromRegion(intersection, rects);
736 // store
737 StoreWindowClipRegion(rects);
739 return NS_OK;
742 /* virtual */
743 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage,
744 uint16_t aDuration,
745 nsISupports* aData,
746 nsIRunnable* aCallback) {
747 MOZ_ASSERT_UNREACHABLE(
748 "Should never call PerformFullscreenTransition on nsBaseWidget");
751 //-------------------------------------------------------------------------
753 // Put the window into full-screen mode
755 //-------------------------------------------------------------------------
756 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen,
757 nsIScreen* aScreen) {
758 HideWindowChrome(aFullScreen);
760 if (aFullScreen) {
761 if (!mOriginalBounds) {
762 mOriginalBounds = new LayoutDeviceIntRect();
764 *mOriginalBounds = GetScreenBounds();
766 // Move to top-left corner of screen and size to the screen dimensions
767 nsCOMPtr<nsIScreen> screen = aScreen;
768 if (!screen) {
769 screen = GetWidgetScreen();
771 if (screen) {
772 int32_t left, top, width, height;
773 if (NS_SUCCEEDED(
774 screen->GetRectDisplayPix(&left, &top, &width, &height))) {
775 Resize(left, top, width, height, true);
778 } else if (mOriginalBounds) {
779 if (BoundsUseDesktopPixels()) {
780 DesktopRect deskRect = *mOriginalBounds / GetDesktopToDeviceScale();
781 Resize(deskRect.X(), deskRect.Y(), deskRect.Width(), deskRect.Height(),
782 true);
783 } else {
784 Resize(mOriginalBounds->X(), mOriginalBounds->Y(),
785 mOriginalBounds->Width(), mOriginalBounds->Height(), true);
790 nsresult nsBaseWidget::MakeFullScreen(bool aFullScreen, nsIScreen* aScreen) {
791 InfallibleMakeFullScreen(aFullScreen, aScreen);
792 return NS_OK;
795 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
796 nsBaseWidget* aWidget, gfxContext* aTarget, BufferMode aDoubleBuffering,
797 ScreenRotation aRotation)
798 : mWidget(aWidget) {
799 LayerManager* lm = mWidget->GetLayerManager();
800 NS_ASSERTION(
801 !lm || lm->GetBackendType() == LayersBackend::LAYERS_BASIC,
802 "AutoLayerManagerSetup instantiated for non-basic layer backend!");
803 if (lm) {
804 mLayerManager = lm->AsBasicLayerManager();
805 if (mLayerManager) {
806 mLayerManager->SetDefaultTarget(aTarget);
807 mLayerManager->SetDefaultTargetConfiguration(aDoubleBuffering, aRotation);
812 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
813 if (mLayerManager) {
814 mLayerManager->SetDefaultTarget(nullptr);
815 mLayerManager->SetDefaultTargetConfiguration(
816 mozilla::layers::BufferMode::BUFFER_NONE, ROTATION_0);
820 bool nsBaseWidget::IsSmallPopup() const {
821 return mWindowType == eWindowType_popup && mPopupType != ePopupTypePanel;
824 bool nsBaseWidget::ComputeShouldAccelerate() {
825 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING) &&
826 WidgetTypeSupportsAcceleration();
829 bool nsBaseWidget::UseAPZ() {
830 return (gfxPlatform::AsyncPanZoomEnabled() &&
831 (WindowType() == eWindowType_toplevel ||
832 WindowType() == eWindowType_child ||
833 (WindowType() == eWindowType_popup && HasRemoteContent() &&
834 StaticPrefs::apz_popups_enabled())));
837 void nsBaseWidget::CreateCompositor() {
838 LayoutDeviceIntRect rect = GetBounds();
839 CreateCompositor(rect.Width(), rect.Height());
842 already_AddRefed<GeckoContentController>
843 nsBaseWidget::CreateRootContentController() {
844 RefPtr<GeckoContentController> controller =
845 new ChromeProcessController(this, mAPZEventState, mAPZC);
846 return controller.forget();
849 void nsBaseWidget::ConfigureAPZCTreeManager() {
850 MOZ_ASSERT(NS_IsMainThread());
851 MOZ_ASSERT(mAPZC);
853 ConfigureAPZControllerThread();
855 float dpi = GetDPI();
856 // On Android the main thread is not the controller thread
857 APZThreadUtils::RunOnControllerThread(
858 NewRunnableMethod<float>("layers::IAPZCTreeManager::SetDPI", mAPZC,
859 &IAPZCTreeManager::SetDPI, dpi));
861 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
862 KeyboardMap map = RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
863 // On Android the main thread is not the controller thread
864 APZThreadUtils::RunOnControllerThread(NewRunnableMethod<KeyboardMap>(
865 "layers::IAPZCTreeManager::SetKeyboardMap", mAPZC,
866 &IAPZCTreeManager::SetKeyboardMap, map));
869 RefPtr<IAPZCTreeManager> treeManager = mAPZC; // for capture by the lambdas
871 ContentReceivedInputBlockCallback callback(
872 [treeManager](uint64_t aInputBlockId, bool aPreventDefault) {
873 MOZ_ASSERT(NS_IsMainThread());
874 APZThreadUtils::RunOnControllerThread(NewRunnableMethod<uint64_t, bool>(
875 "layers::IAPZCTreeManager::ContentReceivedInputBlock", treeManager,
876 &IAPZCTreeManager::ContentReceivedInputBlock, aInputBlockId,
877 aPreventDefault));
879 mAPZEventState = new APZEventState(this, std::move(callback));
881 mSetAllowedTouchBehaviorCallback =
882 [treeManager](uint64_t aInputBlockId,
883 const nsTArray<TouchBehaviorFlags>& aFlags) {
884 MOZ_ASSERT(NS_IsMainThread());
885 APZThreadUtils::RunOnControllerThread(
886 NewRunnableMethod<
887 uint64_t, StoreCopyPassByLRef<nsTArray<TouchBehaviorFlags>>>(
888 "layers::IAPZCTreeManager::SetAllowedTouchBehavior",
889 treeManager, &IAPZCTreeManager::SetAllowedTouchBehavior,
890 aInputBlockId, aFlags.Clone()));
893 mRootContentController = CreateRootContentController();
894 if (mRootContentController) {
895 mCompositorSession->SetContentController(mRootContentController);
898 // When APZ is enabled, we can actually enable raw touch events because we
899 // have code that can deal with them properly. If APZ is not enabled, this
900 // function doesn't get called.
901 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
902 RegisterTouchWindow();
906 void nsBaseWidget::ConfigureAPZControllerThread() {
907 // By default the controller thread is the main thread.
908 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
911 void nsBaseWidget::SetConfirmedTargetAPZC(
912 uint64_t aInputBlockId,
913 const nsTArray<ScrollableLayerGuid>& aTargets) const {
914 APZThreadUtils::RunOnControllerThread(
915 NewRunnableMethod<uint64_t,
916 StoreCopyPassByRRef<nsTArray<ScrollableLayerGuid>>>(
917 "layers::IAPZCTreeManager::SetTargetAPZC", mAPZC,
918 &IAPZCTreeManager::SetTargetAPZC, aInputBlockId, aTargets.Clone()));
921 void nsBaseWidget::UpdateZoomConstraints(
922 const uint32_t& aPresShellId, const ScrollableLayerGuid::ViewID& aViewId,
923 const Maybe<ZoomConstraints>& aConstraints) {
924 if (!mCompositorSession || !mAPZC) {
925 if (mInitialZoomConstraints) {
926 MOZ_ASSERT(mInitialZoomConstraints->mPresShellID == aPresShellId);
927 MOZ_ASSERT(mInitialZoomConstraints->mViewID == aViewId);
928 if (!aConstraints) {
929 mInitialZoomConstraints.reset();
933 if (aConstraints) {
934 // We have some constraints, but the compositor and APZC aren't created
935 // yet. Save these so we can use them later.
936 mInitialZoomConstraints = Some(
937 InitialZoomConstraints(aPresShellId, aViewId, aConstraints.ref()));
939 return;
941 LayersId layersId = mCompositorSession->RootLayerTreeId();
942 mAPZC->UpdateZoomConstraints(
943 ScrollableLayerGuid(layersId, aPresShellId, aViewId), aConstraints);
946 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC; }
948 nsEventStatus nsBaseWidget::ProcessUntransformedAPZEvent(
949 WidgetInputEvent* aEvent, const APZEventResult& aApzResult) {
950 MOZ_ASSERT(NS_IsMainThread());
951 ScrollableLayerGuid targetGuid = aApzResult.mTargetGuid;
952 uint64_t inputBlockId = aApzResult.mInputBlockId;
953 InputAPZContext context(aApzResult.mTargetGuid, inputBlockId,
954 aApzResult.GetStatus());
956 // Make a copy of the original event for the APZCCallbackHelper helpers that
957 // we call later, because the event passed to DispatchEvent can get mutated in
958 // ways that we don't want (i.e. touch points can get stripped out).
959 nsEventStatus status;
960 UniquePtr<WidgetEvent> original(aEvent->Duplicate());
961 DispatchEvent(aEvent, status);
963 if (mAPZC && !InputAPZContext::WasRoutedToChildProcess() && inputBlockId) {
964 // EventStateManager did not route the event into the child process.
965 // It's safe to communicate to APZ that the event has been processed.
966 // Note that here aGuid.mLayersId might be different from
967 // mCompositorSession->RootLayerTreeId() because the event might have gotten
968 // hit-tested by APZ to be targeted at a child process, but a parent process
969 // event listener called preventDefault on it. In that case aGuid.mLayersId
970 // would still be the layers id for the child process, but the event would
971 // not have actually gotten routed to the child process. The main-thread
972 // hit-test result therefore needs to use the parent process layers id.
973 LayersId rootLayersId = mCompositorSession->RootLayerTreeId();
975 RefPtr<DisplayportSetListener> postLayerization;
976 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
977 nsTArray<TouchBehaviorFlags> allowedTouchBehaviors;
978 if (touchEvent->mMessage == eTouchStart) {
979 if (StaticPrefs::layout_css_touch_action_enabled()) {
980 allowedTouchBehaviors =
981 APZCCallbackHelper::SendSetAllowedTouchBehaviorNotification(
982 this, GetDocument(), *(original->AsTouchEvent()),
983 inputBlockId, mSetAllowedTouchBehaviorCallback);
985 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
986 this, GetDocument(), *(original->AsTouchEvent()), rootLayersId,
987 inputBlockId);
989 mAPZEventState->ProcessTouchEvent(*touchEvent, targetGuid, inputBlockId,
990 aApzResult.GetStatus(), status,
991 std::move(allowedTouchBehaviors));
992 } else if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
993 MOZ_ASSERT(wheelEvent->mFlags.mHandledByAPZ);
994 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
995 this, GetDocument(), *(original->AsWheelEvent()), rootLayersId,
996 inputBlockId);
997 if (wheelEvent->mCanTriggerSwipe) {
998 ReportSwipeStarted(inputBlockId, wheelEvent->TriggersSwipe());
1000 mAPZEventState->ProcessWheelEvent(*wheelEvent, inputBlockId);
1001 } else if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1002 MOZ_ASSERT(mouseEvent->mFlags.mHandledByAPZ);
1003 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1004 this, GetDocument(), *(original->AsMouseEvent()), rootLayersId,
1005 inputBlockId);
1006 mAPZEventState->ProcessMouseEvent(*mouseEvent, inputBlockId);
1008 if (postLayerization) {
1009 postLayerization->TryRegister();
1013 return status;
1016 template <class InputType, class EventType>
1017 class DispatchEventOnMainThread : public Runnable {
1018 public:
1019 DispatchEventOnMainThread(const InputType& aInput, nsBaseWidget* aWidget,
1020 const APZEventResult& aAPZResult)
1021 : mozilla::Runnable("DispatchEventOnMainThread"),
1022 mInput(aInput),
1023 mWidget(aWidget),
1024 mAPZResult(aAPZResult) {}
1026 NS_IMETHOD Run() override {
1027 EventType event = mInput.ToWidgetEvent(mWidget);
1028 mWidget->ProcessUntransformedAPZEvent(&event, mAPZResult);
1029 return NS_OK;
1032 private:
1033 InputType mInput;
1034 nsBaseWidget* mWidget;
1035 APZEventResult mAPZResult;
1038 template <class InputType, class EventType>
1039 class DispatchInputOnControllerThread : public Runnable {
1040 public:
1041 DispatchInputOnControllerThread(const EventType& aEvent,
1042 IAPZCTreeManager* aAPZC,
1043 nsBaseWidget* aWidget)
1044 : mozilla::Runnable("DispatchInputOnControllerThread"),
1045 mMainMessageLoop(MessageLoop::current()),
1046 mInput(aEvent),
1047 mAPZC(aAPZC),
1048 mWidget(aWidget) {}
1050 NS_IMETHOD Run() override {
1051 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(mInput);
1052 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1053 return NS_OK;
1055 RefPtr<Runnable> r = new DispatchEventOnMainThread<InputType, EventType>(
1056 mInput, mWidget, result);
1057 mMainMessageLoop->PostTask(r.forget());
1058 return NS_OK;
1061 private:
1062 MessageLoop* mMainMessageLoop;
1063 InputType mInput;
1064 RefPtr<IAPZCTreeManager> mAPZC;
1065 nsBaseWidget* mWidget;
1068 void nsBaseWidget::DispatchTouchInput(MultiTouchInput& aInput) {
1069 MOZ_ASSERT(NS_IsMainThread());
1070 if (mAPZC) {
1071 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1073 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1074 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1075 return;
1078 WidgetTouchEvent event = aInput.ToWidgetTouchEvent(this);
1079 ProcessUntransformedAPZEvent(&event, result);
1080 } else {
1081 WidgetTouchEvent event = aInput.ToWidgetTouchEvent(this);
1083 nsEventStatus status;
1084 DispatchEvent(&event, status);
1088 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput& aInput) {
1089 MOZ_ASSERT(NS_IsMainThread());
1090 if (mAPZC) {
1091 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1093 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1094 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1095 return;
1098 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1099 ProcessUntransformedAPZEvent(&event, result);
1100 } else {
1101 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1102 nsEventStatus status;
1103 DispatchEvent(&event, status);
1107 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput& aInput) {
1108 MOZ_ASSERT(NS_IsMainThread());
1109 if (mAPZC) {
1110 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1111 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1113 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1114 return;
1116 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1117 ProcessUntransformedAPZEvent(&event, result);
1118 } else {
1119 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1120 nsEventStatus status;
1121 DispatchEvent(&event, status);
1125 nsIWidget::ContentAndAPZEventStatus nsBaseWidget::DispatchInputEvent(
1126 WidgetInputEvent* aEvent) {
1127 nsIWidget::ContentAndAPZEventStatus status;
1128 MOZ_ASSERT(NS_IsMainThread());
1129 if (mAPZC) {
1130 if (APZThreadUtils::IsControllerThread()) {
1131 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1132 status.mApzStatus = result.GetStatus();
1133 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1134 return status;
1136 status.mContentStatus = ProcessUntransformedAPZEvent(aEvent, result);
1137 return status;
1139 if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1140 RefPtr<Runnable> r =
1141 new DispatchInputOnControllerThread<ScrollWheelInput,
1142 WidgetWheelEvent>(*wheelEvent,
1143 mAPZC, this);
1144 APZThreadUtils::RunOnControllerThread(std::move(r));
1145 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1146 return status;
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 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1154 return status;
1156 // Allow dispatching keyboard events on Gecko thread.
1157 MOZ_ASSERT(aEvent->AsKeyboardEvent());
1160 DispatchEvent(aEvent, status.mContentStatus);
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 (gfxPlatform::DoesFissionForceWebRender() ||
1231 StaticPrefs::
1232 gfx_webrender_software_unaccelerated_widget_allow()) {
1233 enableWR = enableSWWR = gfx::gfxVars::UseWebRender();
1234 } else {
1235 enableWR = enableSWWR = false;
1237 bool enableAPZ = UseAPZ();
1238 CompositorOptions options(enableAPZ, enableWR, enableSWWR);
1240 #ifdef XP_WIN
1241 if (supportsAcceleration) {
1242 options.SetAllowSoftwareWebRenderD3D11(
1243 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1245 #elif defined(MOZ_WIDGET_ANDROID)
1246 MOZ_ASSERT(supportsAcceleration);
1247 options.SetAllowSoftwareWebRenderOGL(
1248 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1249 #elif defined(MOZ_WIDGET_GTK)
1250 if (supportsAcceleration) {
1251 options.SetAllowSoftwareWebRenderOGL(
1252 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1254 #endif
1256 #ifdef MOZ_WIDGET_ANDROID
1257 if (!GetNativeData(NS_JAVA_SURFACE)) {
1258 options.SetInitiallyPaused(true);
1260 #else
1261 options.SetInitiallyPaused(CompositorInitiallyPaused());
1262 #endif
1264 RefPtr<LayerManager> lm;
1265 if (options.UseWebRender()) {
1266 lm = new WebRenderLayerManager(this);
1267 } else {
1268 lm = new ClientLayerManager(this);
1271 bool retry = false;
1272 mCompositorSession = gpu->CreateTopLevelCompositor(
1273 this, lm, GetDefaultScale(), options, UseExternalCompositingSurface(),
1274 gfx::IntSize(aWidth, aHeight), &retry);
1276 if (lm->AsWebRenderLayerManager() && mCompositorSession) {
1277 TextureFactoryIdentifier textureFactoryIdentifier;
1278 nsCString error;
1279 lm->AsWebRenderLayerManager()->Initialize(
1280 mCompositorSession->GetCompositorBridgeChild(),
1281 wr::AsPipelineId(mCompositorSession->RootLayerTreeId()),
1282 &textureFactoryIdentifier, error);
1283 if (textureFactoryIdentifier.mParentBackend != LayersBackend::LAYERS_WR) {
1284 retry = true;
1285 DestroyCompositor();
1286 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1287 gfx::GPUProcessManager::Get()->DisableWebRender(
1288 wr::WebRenderError::INITIALIZE, error);
1290 } else if (lm->AsClientLayerManager() && mCompositorSession) {
1291 bool shouldAccelerate = ComputeShouldAccelerate();
1292 TextureFactoryIdentifier textureFactoryIdentifier;
1293 lm->AsClientLayerManager()->Initialize(
1294 mCompositorSession->GetCompositorBridgeChild(), shouldAccelerate,
1295 &textureFactoryIdentifier);
1296 if (textureFactoryIdentifier.mParentBackend ==
1297 LayersBackend::LAYERS_NONE) {
1298 DestroyCompositor();
1299 lm = nullptr;
1303 // We need to retry in a loop because the act of failing to create the
1304 // compositor can change our state (e.g. disable WebRender).
1305 if (mCompositorSession || !retry) {
1306 *aOptionsOut = options;
1307 return lm.forget();
1309 } while (true);
1312 void nsBaseWidget::CreateCompositor(int aWidth, int aHeight) {
1313 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1314 gfxPlatform::GetPlatform();
1316 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1317 "This function assumes OMTC");
1319 MOZ_ASSERT(!mCompositorSession && !mCompositorBridgeChild,
1320 "Should have properly cleaned up the previous PCompositor pair "
1321 "beforehand");
1323 if (mCompositorBridgeChild) {
1324 mCompositorBridgeChild->Destroy();
1327 // Recreating this is tricky, as we may still have an old and we need
1328 // to make sure it's properly destroyed by calling DestroyCompositor!
1330 // If we've already received a shutdown notification, don't try
1331 // create a new compositor.
1332 if (!mShutdownObserver) {
1333 return;
1336 CompositorOptions options;
1337 RefPtr<LayerManager> lm = CreateCompositorSession(aWidth, aHeight, &options);
1338 if (!lm) {
1339 return;
1342 MOZ_ASSERT(mCompositorSession);
1343 mCompositorBridgeChild = mCompositorSession->GetCompositorBridgeChild();
1344 SetCompositorWidgetDelegate(
1345 mCompositorSession->GetCompositorWidgetDelegate());
1347 if (options.UseAPZ()) {
1348 mAPZC = mCompositorSession->GetAPZCTreeManager();
1349 ConfigureAPZCTreeManager();
1350 } else {
1351 mAPZC = nullptr;
1354 if (mInitialZoomConstraints) {
1355 UpdateZoomConstraints(mInitialZoomConstraints->mPresShellID,
1356 mInitialZoomConstraints->mViewID,
1357 Some(mInitialZoomConstraints->mConstraints));
1358 mInitialZoomConstraints.reset();
1361 if (lm->AsWebRenderLayerManager()) {
1362 TextureFactoryIdentifier textureFactoryIdentifier =
1363 lm->GetTextureFactoryIdentifier();
1364 MOZ_ASSERT(textureFactoryIdentifier.mParentBackend ==
1365 LayersBackend::LAYERS_WR);
1366 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1367 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1368 } else if (lm->AsClientLayerManager()) {
1369 TextureFactoryIdentifier textureFactoryIdentifier =
1370 lm->GetTextureFactoryIdentifier();
1371 // Some popup or transparent widgets may use a different backend than the
1372 // compositors used with ImageBridge and VR (and more generally web
1373 // content).
1374 if (WidgetTypeSupportsAcceleration()) {
1375 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1376 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1380 WindowUsesOMTC();
1382 mLayerManager = std::move(lm);
1384 // Only track compositors for top-level windows, since other window types
1385 // may use the basic compositor. Except on the OS X - see bug 1306383
1386 #if defined(XP_MACOSX)
1387 bool getCompositorFromThisWindow = true;
1388 #else
1389 bool getCompositorFromThisWindow = (mWindowType == eWindowType_toplevel);
1390 #endif
1392 if (getCompositorFromThisWindow) {
1393 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1394 mLayerManager->GetCompositorBackendType());
1398 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession* aSession) {
1399 MOZ_ASSERT(aSession == mCompositorSession);
1400 DestroyLayerManager();
1403 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1404 return gfxPlatform::UsesOffMainThreadCompositing();
1407 LayerManager* nsBaseWidget::GetLayerManager(
1408 PLayerTransactionChild* aShadowManager, LayersBackend aBackendHint,
1409 LayerManagerPersistence aPersistence) {
1410 if (!mLayerManager) {
1411 if (!mShutdownObserver) {
1412 // We are shutting down, do not try to re-create a LayerManager
1413 return nullptr;
1415 // Try to use an async compositor first, if possible
1416 if (ShouldUseOffMainThreadCompositing()) {
1417 // e10s uses the parameter to pass in the shadow manager from the
1418 // BrowserChild so we don't expect to see it there since this doesn't
1419 // support e10s.
1420 NS_ASSERTION(aShadowManager == nullptr,
1421 "Async Compositor not supported with e10s");
1422 CreateCompositor();
1425 if (!mLayerManager) {
1426 mLayerManager = CreateBasicLayerManager();
1429 return mLayerManager;
1432 LayerManager* nsBaseWidget::CreateBasicLayerManager() {
1433 return new BasicLayerManager(this);
1436 CompositorBridgeChild* nsBaseWidget::GetRemoteRenderer() {
1437 return mCompositorBridgeChild;
1440 void nsBaseWidget::ClearCachedWebrenderResources() {
1441 if (!mLayerManager || !mLayerManager->AsWebRenderLayerManager()) {
1442 return;
1444 mLayerManager->ClearCachedResources();
1447 already_AddRefed<gfx::DrawTarget> nsBaseWidget::StartRemoteDrawing() {
1448 return nullptr;
1451 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA; }
1453 //-------------------------------------------------------------------------
1455 // Destroy the window
1457 //-------------------------------------------------------------------------
1458 void nsBaseWidget::OnDestroy() {
1459 if (mTextEventDispatcher) {
1460 mTextEventDispatcher->OnDestroyWidget();
1461 // Don't release it until this widget actually released because after this
1462 // is called, TextEventDispatcher() may create it again.
1465 // If this widget is being destroyed, let the APZ code know to drop references
1466 // to this widget. Callers of this function all should be holding a deathgrip
1467 // on this widget already.
1468 ReleaseContentController();
1471 void nsBaseWidget::MoveClient(const DesktopPoint& aOffset) {
1472 LayoutDeviceIntPoint clientOffset(GetClientOffset());
1474 // GetClientOffset returns device pixels; scale back to desktop pixels
1475 // if that's what this widget uses for the Move/Resize APIs
1476 if (BoundsUseDesktopPixels()) {
1477 DesktopPoint desktopOffset = clientOffset / GetDesktopToDeviceScale();
1478 Move(aOffset.x - desktopOffset.x, aOffset.y - desktopOffset.y);
1479 } else {
1480 LayoutDevicePoint layoutOffset = aOffset * GetDesktopToDeviceScale();
1481 Move(layoutOffset.x - clientOffset.x, layoutOffset.y - clientOffset.y);
1485 void nsBaseWidget::ResizeClient(const DesktopSize& aSize, bool aRepaint) {
1486 NS_ASSERTION((aSize.width >= 0), "Negative width passed to ResizeClient");
1487 NS_ASSERTION((aSize.height >= 0), "Negative height passed to ResizeClient");
1489 LayoutDeviceIntRect clientBounds = GetClientBounds();
1491 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1492 // if that's what this widget uses for the Move/Resize APIs
1493 if (BoundsUseDesktopPixels()) {
1494 DesktopSize desktopDelta =
1495 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1496 clientBounds.Size()) /
1497 GetDesktopToDeviceScale();
1498 Resize(aSize.width + desktopDelta.width, aSize.height + desktopDelta.height,
1499 aRepaint);
1500 } else {
1501 LayoutDeviceSize layoutSize = aSize * GetDesktopToDeviceScale();
1502 Resize(mBounds.Width() + (layoutSize.width - clientBounds.Width()),
1503 mBounds.Height() + (layoutSize.height - clientBounds.Height()),
1504 aRepaint);
1508 void nsBaseWidget::ResizeClient(const DesktopRect& aRect, bool aRepaint) {
1509 NS_ASSERTION((aRect.Width() >= 0), "Negative width passed to ResizeClient");
1510 NS_ASSERTION((aRect.Height() >= 0), "Negative height passed to ResizeClient");
1512 LayoutDeviceIntRect clientBounds = GetClientBounds();
1513 LayoutDeviceIntPoint clientOffset = GetClientOffset();
1514 DesktopToLayoutDeviceScale scale = GetDesktopToDeviceScale();
1516 if (BoundsUseDesktopPixels()) {
1517 DesktopPoint desktopOffset = clientOffset / scale;
1518 DesktopSize desktopDelta =
1519 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1520 clientBounds.Size()) /
1521 scale;
1522 Resize(aRect.X() - desktopOffset.x, aRect.Y() - desktopOffset.y,
1523 aRect.Width() + desktopDelta.width,
1524 aRect.Height() + desktopDelta.height, aRepaint);
1525 } else {
1526 LayoutDeviceRect layoutRect = aRect * scale;
1527 Resize(layoutRect.X() - clientOffset.x, layoutRect.Y() - clientOffset.y,
1528 layoutRect.Width() + mBounds.Width() - clientBounds.Width(),
1529 layoutRect.Height() + mBounds.Height() - clientBounds.Height(),
1530 aRepaint);
1534 //-------------------------------------------------------------------------
1536 // Bounds
1538 //-------------------------------------------------------------------------
1541 * If the implementation of nsWindow supports borders this method MUST be
1542 * overridden
1545 LayoutDeviceIntRect nsBaseWidget::GetClientBounds() { return GetBounds(); }
1548 * If the implementation of nsWindow supports borders this method MUST be
1549 * overridden
1552 LayoutDeviceIntRect nsBaseWidget::GetBounds() { return mBounds; }
1555 * If the implementation of nsWindow uses a local coordinate system within the
1556 *window, this method must be overridden
1559 LayoutDeviceIntRect nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1561 nsresult nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect& aRect) {
1562 if (SizeMode() != nsSizeMode_Normal) {
1563 return NS_ERROR_FAILURE;
1565 aRect = GetScreenBounds();
1566 return NS_OK;
1569 LayoutDeviceIntPoint nsBaseWidget::GetClientOffset() {
1570 return LayoutDeviceIntPoint(0, 0);
1573 nsresult nsBaseWidget::SetNonClientMargins(LayoutDeviceIntMargin& margins) {
1574 return NS_ERROR_NOT_IMPLEMENTED;
1577 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1579 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1581 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect* aResizerRect) {
1582 return false;
1586 * Modifies aFile to point at an icon file with the given name and suffix. The
1587 * suffix may correspond to a file extension with leading '.' if appropriate.
1588 * Returns true if the icon file exists and can be read.
1590 static bool ResolveIconNameHelper(nsIFile* aFile, const nsAString& aIconName,
1591 const nsAString& aIconSuffix) {
1592 aFile->Append(u"icons"_ns);
1593 aFile->Append(u"default"_ns);
1594 aFile->Append(aIconName + aIconSuffix);
1596 bool readable;
1597 return NS_SUCCEEDED(aFile->IsReadable(&readable)) && readable;
1601 * Resolve the given icon name into a local file object. This method is
1602 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1603 * platform specific icon file suffix (e.g., ".ico" under Win32).
1605 * If no file is found matching the given parameters, then null is returned.
1607 void nsBaseWidget::ResolveIconName(const nsAString& aIconName,
1608 const nsAString& aIconSuffix,
1609 nsIFile** aResult) {
1610 *aResult = nullptr;
1612 nsCOMPtr<nsIProperties> dirSvc =
1613 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
1614 if (!dirSvc) return;
1616 // first check auxilary chrome directories
1618 nsCOMPtr<nsISimpleEnumerator> dirs;
1619 dirSvc->Get(NS_APP_CHROME_DIR_LIST, NS_GET_IID(nsISimpleEnumerator),
1620 getter_AddRefs(dirs));
1621 if (dirs) {
1622 bool hasMore;
1623 while (NS_SUCCEEDED(dirs->HasMoreElements(&hasMore)) && hasMore) {
1624 nsCOMPtr<nsISupports> element;
1625 dirs->GetNext(getter_AddRefs(element));
1626 if (!element) continue;
1627 nsCOMPtr<nsIFile> file = do_QueryInterface(element);
1628 if (!file) continue;
1629 if (ResolveIconNameHelper(file, aIconName, aIconSuffix)) {
1630 NS_ADDREF(*aResult = file);
1631 return;
1636 // then check the main app chrome directory
1638 nsCOMPtr<nsIFile> file;
1639 dirSvc->Get(NS_APP_CHROME_DIR, NS_GET_IID(nsIFile), getter_AddRefs(file));
1640 if (file && ResolveIconNameHelper(file, aIconName, aIconSuffix))
1641 NS_ADDREF(*aResult = file);
1644 void nsBaseWidget::SetSizeConstraints(const SizeConstraints& aConstraints) {
1645 mSizeConstraints = aConstraints;
1647 // Popups are constrained during layout, and we don't want to synchronously
1648 // paint from reflow, so bail out... This is not great, but it's no worse than
1649 // what we used to do.
1651 // The right fix here is probably making constraint changes go through the
1652 // view manager and such.
1653 if (mWindowType == eWindowType_popup) {
1654 return;
1657 // If the current size doesn't meet the new constraints, trigger a
1658 // resize to apply it. Note that, we don't want to invoke Resize if
1659 // the new constraints don't affect the current size, because Resize
1660 // implementation on some platforms may touch other geometry even if
1661 // the size don't need to change.
1662 LayoutDeviceIntSize curSize = mBounds.Size();
1663 LayoutDeviceIntSize clampedSize =
1664 Max(aConstraints.mMinSize, Min(aConstraints.mMaxSize, curSize));
1665 if (clampedSize != curSize) {
1666 gfx::Size size;
1667 if (BoundsUseDesktopPixels()) {
1668 DesktopSize desktopSize = clampedSize / GetDesktopToDeviceScale();
1669 size = desktopSize.ToUnknownSize();
1670 } else {
1671 size = gfx::Size(clampedSize.ToUnknownSize());
1673 Resize(size.width, size.height, true);
1677 const widget::SizeConstraints nsBaseWidget::GetSizeConstraints() {
1678 return mSizeConstraints;
1681 // static
1682 nsIRollupListener* nsBaseWidget::GetActiveRollupListener() {
1683 // If set, then this is likely an <html:select> dropdown.
1684 if (gRollupListener) return gRollupListener;
1686 return nsXULPopupManager::GetInstance();
1689 void nsBaseWidget::NotifyWindowDestroyed() {
1690 if (!mWidgetListener) return;
1692 nsCOMPtr<nsIAppWindow> window = mWidgetListener->GetAppWindow();
1693 nsCOMPtr<nsIBaseWindow> appWindow(do_QueryInterface(window));
1694 if (appWindow) {
1695 appWindow->Destroy();
1699 void nsBaseWidget::NotifyWindowMoved(int32_t aX, int32_t aY) {
1700 if (mWidgetListener) {
1701 mWidgetListener->WindowMoved(this, aX, aY);
1704 if (mIMEHasFocus && IMENotificationRequestsRef().WantPositionChanged()) {
1705 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE));
1709 void nsBaseWidget::NotifySizeMoveDone() {
1710 if (!mWidgetListener) {
1711 return;
1713 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1714 presShell->WindowSizeMoveDone();
1718 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind) {
1719 if (!mWidgetListener) {
1720 return;
1722 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1723 presShell->ThemeChanged(aKind);
1727 void nsBaseWidget::NotifyUIStateChanged(UIStateChangeType aShowFocusRings) {
1728 if (Document* doc = GetDocument()) {
1729 if (nsPIDOMWindowOuter* win = doc->GetWindow()) {
1730 win->SetKeyboardIndicators(aShowFocusRings);
1735 nsresult nsBaseWidget::NotifyIME(const IMENotification& aIMENotification) {
1736 if (mIMEHasQuit) {
1737 return NS_OK;
1739 switch (aIMENotification.mMessage) {
1740 case REQUEST_TO_COMMIT_COMPOSITION:
1741 case REQUEST_TO_CANCEL_COMPOSITION:
1742 // We should send request to IME only when there is a TextEventDispatcher
1743 // instance (this means that this widget has dispatched at least one
1744 // composition event or keyboard event) and the it has composition.
1745 // Otherwise, there is nothing to do.
1746 // Note that if current input transaction is for native input events,
1747 // TextEventDispatcher::NotifyIME() will call
1748 // TextEventDispatcherListener::NotifyIME().
1749 if (mTextEventDispatcher && mTextEventDispatcher->IsComposing()) {
1750 return mTextEventDispatcher->NotifyIME(aIMENotification);
1752 return NS_OK;
1753 default: {
1754 if (aIMENotification.mMessage == NOTIFY_IME_OF_FOCUS) {
1755 mIMEHasFocus = true;
1757 EnsureTextEventDispatcher();
1758 // TextEventDispatcher::NotifyIME() will always call
1759 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1760 // input transaction is for synthesized events for automated tests,
1761 // notifications will be sent to native IME.
1762 nsresult rv = mTextEventDispatcher->NotifyIME(aIMENotification);
1763 if (aIMENotification.mMessage == NOTIFY_IME_OF_BLUR) {
1764 mIMEHasFocus = false;
1766 return rv;
1771 void nsBaseWidget::EnsureTextEventDispatcher() {
1772 if (mTextEventDispatcher) {
1773 return;
1775 mTextEventDispatcher = new TextEventDispatcher(this);
1778 nsIWidget::NativeIMEContext nsBaseWidget::GetNativeIMEContext() {
1779 if (mTextEventDispatcher && mTextEventDispatcher->GetPseudoIMEContext()) {
1780 // If we already have a TextEventDispatcher and it's working with
1781 // a TextInputProcessor, we need to return pseudo IME context since
1782 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1783 // on the pseudo IME context in such case.
1784 NativeIMEContext pseudoIMEContext;
1785 pseudoIMEContext.InitWithRawNativeIMEContext(
1786 mTextEventDispatcher->GetPseudoIMEContext());
1787 return pseudoIMEContext;
1789 return NativeIMEContext(this);
1792 nsIWidget::TextEventDispatcher* nsBaseWidget::GetTextEventDispatcher() {
1793 EnsureTextEventDispatcher();
1794 return mTextEventDispatcher;
1797 void* nsBaseWidget::GetPseudoIMEContext() {
1798 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
1799 if (!dispatcher) {
1800 return nullptr;
1802 return dispatcher->GetPseudoIMEContext();
1805 TextEventDispatcherListener*
1806 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1807 // TODO: If all platforms supported use of TextEventDispatcher for handling
1808 // native IME and keyboard events, this method should be removed since
1809 // in such case, this is overridden by all the subclasses.
1810 return nullptr;
1813 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId,
1814 const ScrollableLayerGuid::ViewID& aViewId,
1815 const CSSRect& aRect, const uint32_t& aFlags) {
1816 if (!mCompositorSession || !mAPZC) {
1817 return;
1819 LayersId layerId = mCompositorSession->RootLayerTreeId();
1820 APZThreadUtils::RunOnControllerThread(
1821 NewRunnableMethod<ScrollableLayerGuid, ZoomTarget, uint32_t>(
1822 "layers::IAPZCTreeManager::ZoomToRect", mAPZC,
1823 &IAPZCTreeManager::ZoomToRect,
1824 ScrollableLayerGuid(layerId, aPresShellId, aViewId),
1825 ZoomTarget{aRect, Nothing()}, aFlags));
1828 #ifdef ACCESSIBILITY
1830 a11y::LocalAccessible* nsBaseWidget::GetRootAccessible() {
1831 NS_ENSURE_TRUE(mWidgetListener, nullptr);
1833 PresShell* presShell = mWidgetListener->GetPresShell();
1834 NS_ENSURE_TRUE(presShell, nullptr);
1836 // If container is null then the presshell is not active. This often happens
1837 // when a preshell is being held onto for fastback.
1838 nsPresContext* presContext = presShell->GetPresContext();
1839 NS_ENSURE_TRUE(presContext->GetContainerWeak(), nullptr);
1841 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1842 // make sure it's not created at unsafe times.
1843 nsAccessibilityService* accService = GetOrCreateAccService();
1844 if (accService) {
1845 return accService->GetRootDocumentAccessible(
1846 presShell, nsContentUtils::IsSafeToRunScript());
1849 return nullptr;
1852 #endif // ACCESSIBILITY
1854 void nsBaseWidget::StartAsyncScrollbarDrag(
1855 const AsyncDragMetrics& aDragMetrics) {
1856 if (!AsyncPanZoomEnabled()) {
1857 return;
1860 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession);
1862 LayersId layersId = mCompositorSession->RootLayerTreeId();
1863 ScrollableLayerGuid guid(layersId, aDragMetrics.mPresShellId,
1864 aDragMetrics.mViewId);
1866 APZThreadUtils::RunOnControllerThread(
1867 NewRunnableMethod<ScrollableLayerGuid, AsyncDragMetrics>(
1868 "layers::IAPZCTreeManager::StartScrollbarDrag", mAPZC,
1869 &IAPZCTreeManager::StartScrollbarDrag, guid, aDragMetrics));
1872 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
1873 const ScrollableLayerGuid& aGuid) {
1874 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1876 return mAPZC->StartAutoscroll(aGuid, aAnchorLocation);
1879 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid& aGuid) {
1880 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1882 mAPZC->StopAutoscroll(aGuid);
1885 already_AddRefed<nsIScreen> nsBaseWidget::GetWidgetScreen() {
1886 nsCOMPtr<nsIScreenManager> screenManager;
1887 screenManager = do_GetService("@mozilla.org/gfx/screenmanager;1");
1888 if (!screenManager) {
1889 return nullptr;
1892 LayoutDeviceIntRect bounds = GetScreenBounds();
1893 DesktopIntRect deskBounds = RoundedToInt(bounds / GetDesktopToDeviceScale());
1894 nsCOMPtr<nsIScreen> screen;
1895 screenManager->ScreenForRect(deskBounds.X(), deskBounds.Y(),
1896 deskBounds.Width(), deskBounds.Height(),
1897 getter_AddRefs(screen));
1898 return screen.forget();
1901 mozilla::DesktopToLayoutDeviceScale
1902 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
1903 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
1904 ->GetDesktopToDeviceScale();
1907 nsresult nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint,
1908 bool aLongTap,
1909 nsIObserver* aObserver) {
1910 AutoObserverNotifier notifier(aObserver, "touchtap");
1912 if (sPointerIdCounter > TOUCH_INJECT_MAX_POINTS) {
1913 sPointerIdCounter = 0;
1915 int pointerId = sPointerIdCounter;
1916 sPointerIdCounter++;
1917 nsresult rv = SynthesizeNativeTouchPoint(pointerId, TOUCH_CONTACT, aPoint,
1918 1.0, 90, nullptr);
1919 if (NS_FAILED(rv)) {
1920 return rv;
1923 if (!aLongTap) {
1924 return SynthesizeNativeTouchPoint(pointerId, TOUCH_REMOVE, aPoint, 0, 0,
1925 nullptr);
1928 // initiate a long tap
1929 int elapse = Preferences::GetInt("ui.click_hold_context_menus.delay",
1930 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC);
1931 if (!mLongTapTimer) {
1932 mLongTapTimer = NS_NewTimer();
1933 if (!mLongTapTimer) {
1934 SynthesizeNativeTouchPoint(pointerId, TOUCH_CANCEL, aPoint, 0, 0,
1935 nullptr);
1936 return NS_ERROR_UNEXPECTED;
1938 // Windows requires recuring events, so we set this to a smaller window
1939 // than the pref value.
1940 int timeout = elapse;
1941 if (timeout > TOUCH_INJECT_PUMP_TIMER_MSEC) {
1942 timeout = TOUCH_INJECT_PUMP_TIMER_MSEC;
1944 mLongTapTimer->InitWithNamedFuncCallback(
1945 OnLongTapTimerCallback, this, timeout, nsITimer::TYPE_REPEATING_SLACK,
1946 "nsIWidget::SynthesizeNativeTouchTap");
1949 // If we already have a long tap pending, cancel it. We only allow one long
1950 // tap to be active at a time.
1951 if (mLongTapTouchPoint) {
1952 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1953 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1956 mLongTapTouchPoint = MakeUnique<LongTapInfo>(
1957 pointerId, aPoint, TimeDuration::FromMilliseconds(elapse), aObserver);
1958 notifier.SkipNotification(); // we'll do it in the long-tap callback
1959 return NS_OK;
1962 // static
1963 void nsIWidget::OnLongTapTimerCallback(nsITimer* aTimer, void* aClosure) {
1964 auto* self = static_cast<nsIWidget*>(aClosure);
1966 if ((self->mLongTapTouchPoint->mStamp + self->mLongTapTouchPoint->mDuration) >
1967 TimeStamp::Now()) {
1968 #ifdef XP_WIN
1969 // Windows needs us to keep pumping feedback to the digitizer, so update
1970 // the pointer id with the same position.
1971 self->SynthesizeNativeTouchPoint(
1972 self->mLongTapTouchPoint->mPointerId, TOUCH_CONTACT,
1973 self->mLongTapTouchPoint->mPosition, 1.0, 90, nullptr);
1974 #endif
1975 return;
1978 AutoObserverNotifier notifier(self->mLongTapTouchPoint->mObserver,
1979 "touchtap");
1981 // finished, remove the touch point
1982 self->mLongTapTimer->Cancel();
1983 self->mLongTapTimer = nullptr;
1984 self->SynthesizeNativeTouchPoint(
1985 self->mLongTapTouchPoint->mPointerId, TOUCH_REMOVE,
1986 self->mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1987 self->mLongTapTouchPoint = nullptr;
1990 nsresult nsIWidget::ClearNativeTouchSequence(nsIObserver* aObserver) {
1991 AutoObserverNotifier notifier(aObserver, "cleartouch");
1993 if (!mLongTapTimer) {
1994 return NS_OK;
1996 mLongTapTimer->Cancel();
1997 mLongTapTimer = nullptr;
1998 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1999 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
2000 mLongTapTouchPoint = nullptr;
2001 return NS_OK;
2004 MultiTouchInput nsBaseWidget::UpdateSynthesizedTouchState(
2005 MultiTouchInput* aState, uint32_t aTime, mozilla::TimeStamp aTimeStamp,
2006 uint32_t aPointerId, TouchPointerState aPointerState,
2007 LayoutDeviceIntPoint aPoint, double aPointerPressure,
2008 uint32_t aPointerOrientation) {
2009 ScreenIntPoint pointerScreenPoint = ViewAs<ScreenPixel>(
2010 aPoint, PixelCastJustification::LayoutDeviceIsScreenForBounds);
2012 // We can't dispatch *aState directly because (a) dispatching
2013 // it might inadvertently modify it and (b) in the case of touchend or
2014 // touchcancel events aState will hold the touches that are
2015 // still down whereas the input dispatched needs to hold the removed
2016 // touch(es). We use |inputToDispatch| for this purpose.
2017 MultiTouchInput inputToDispatch;
2018 inputToDispatch.mInputType = MULTITOUCH_INPUT;
2019 inputToDispatch.mTime = aTime;
2020 inputToDispatch.mTimeStamp = aTimeStamp;
2022 int32_t index = aState->IndexOfTouch((int32_t)aPointerId);
2023 if (aPointerState == TOUCH_CONTACT) {
2024 if (index >= 0) {
2025 // found an existing touch point, update it
2026 SingleTouchData& point = aState->mTouches[index];
2027 point.mScreenPoint = pointerScreenPoint;
2028 point.mRotationAngle = (float)aPointerOrientation;
2029 point.mForce = (float)aPointerPressure;
2030 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_MOVE;
2031 } else {
2032 // new touch point, add it
2033 aState->mTouches.AppendElement(SingleTouchData(
2034 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2035 (float)aPointerOrientation, (float)aPointerPressure));
2036 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_START;
2038 inputToDispatch.mTouches = aState->mTouches;
2039 } else {
2040 MOZ_ASSERT(aPointerState == TOUCH_REMOVE || aPointerState == TOUCH_CANCEL);
2041 // a touch point is being lifted, so remove it from the stored list
2042 if (index >= 0) {
2043 aState->mTouches.RemoveElementAt(index);
2045 inputToDispatch.mType =
2046 (aPointerState == TOUCH_REMOVE ? MultiTouchInput::MULTITOUCH_END
2047 : MultiTouchInput::MULTITOUCH_CANCEL);
2048 inputToDispatch.mTouches.AppendElement(SingleTouchData(
2049 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2050 (float)aPointerOrientation, (float)aPointerPressure));
2053 return inputToDispatch;
2056 void nsBaseWidget::NotifyLiveResizeStarted() {
2057 // If we have mLiveResizeListeners already non-empty, we should notify those
2058 // listeners that the resize stopped before starting anew. In theory this
2059 // should never happen because we shouldn't get nested live resize actions.
2060 NotifyLiveResizeStopped();
2061 MOZ_ASSERT(mLiveResizeListeners.IsEmpty());
2063 // If we can get the active remote tab for the current widget, suppress
2064 // the displayport on it during the live resize.
2065 if (!mWidgetListener) {
2066 return;
2068 nsCOMPtr<nsIAppWindow> appWindow = mWidgetListener->GetAppWindow();
2069 if (!appWindow) {
2070 return;
2072 mLiveResizeListeners = appWindow->GetLiveResizeListeners();
2073 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2074 mLiveResizeListeners[i]->LiveResizeStarted();
2078 void nsBaseWidget::NotifyLiveResizeStopped() {
2079 if (!mLiveResizeListeners.IsEmpty()) {
2080 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2081 mLiveResizeListeners[i]->LiveResizeStopped();
2083 mLiveResizeListeners.Clear();
2087 void nsBaseWidget::RegisterPluginWindowForRemoteUpdates() {
2088 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2089 MOZ_ASSERT_UNREACHABLE(
2090 "nsBaseWidget::RegisterPluginWindowForRemoteUpdates "
2091 "not implemented!");
2092 return;
2093 #else
2094 MOZ_ASSERT(NS_IsMainThread());
2095 void* id = GetNativeData(NS_NATIVE_PLUGIN_ID);
2096 if (!id) {
2097 NS_WARNING("This is not a valid native widget!");
2098 return;
2100 MOZ_ASSERT(sPluginWidgetList);
2101 sPluginWidgetList->InsertOrUpdate(id, RefPtr{this});
2102 #endif
2105 void nsBaseWidget::UnregisterPluginWindowForRemoteUpdates() {
2106 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2107 MOZ_ASSERT_UNREACHABLE(
2108 "nsBaseWidget::UnregisterPluginWindowForRemoteUpdates "
2109 "not implemented!");
2110 return;
2111 #else
2112 MOZ_ASSERT(NS_IsMainThread());
2113 void* id = GetNativeData(NS_NATIVE_PLUGIN_ID);
2114 if (!id) {
2115 NS_WARNING("This is not a valid native widget!");
2116 return;
2118 MOZ_ASSERT(sPluginWidgetList);
2119 sPluginWidgetList->Remove(id);
2120 #endif
2123 nsresult nsBaseWidget::AsyncEnableDragDrop(bool aEnable) {
2124 RefPtr<nsBaseWidget> kungFuDeathGrip = this;
2125 return NS_DispatchToCurrentThreadQueue(
2126 NS_NewRunnableFunction(
2127 "AsyncEnableDragDropFn",
2128 [this, aEnable, kungFuDeathGrip]() { EnableDragDrop(aEnable); }),
2129 kAsyncDragDropTimeout, EventQueuePriority::Idle);
2132 // static
2133 nsIWidget* nsIWidget::LookupRegisteredPluginWindow(uintptr_t aWindowID) {
2134 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2135 MOZ_ASSERT_UNREACHABLE(
2136 "nsBaseWidget::LookupRegisteredPluginWindow "
2137 "not implemented!");
2138 return nullptr;
2139 #else
2140 MOZ_ASSERT(NS_IsMainThread());
2141 MOZ_ASSERT(sPluginWidgetList);
2142 return sPluginWidgetList->GetWeak((void*)aWindowID);
2143 #endif
2146 // static
2147 void nsIWidget::UpdateRegisteredPluginWindowVisibility(
2148 uintptr_t aOwnerWidget, nsTArray<uintptr_t>& aPluginIds) {
2149 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2150 MOZ_ASSERT_UNREACHABLE(
2151 "nsBaseWidget::UpdateRegisteredPluginWindowVisibility"
2152 " not implemented!");
2153 return;
2154 #else
2155 MOZ_ASSERT(NS_IsMainThread());
2156 MOZ_ASSERT(sPluginWidgetList);
2158 // Our visible list is associated with a compositor which is associated with
2159 // a specific top level window. We use the parent widget during iteration
2160 // to skip the plugin widgets owned by other top level windows.
2161 for (const auto& entry : *sPluginWidgetList) {
2162 const void* windowId = entry.GetKey();
2163 nsIWidget* widget = entry.GetWeak();
2165 MOZ_ASSERT(windowId);
2166 MOZ_ASSERT(widget);
2168 if (!widget->Destroyed()) {
2169 if ((uintptr_t)widget->GetParent() == aOwnerWidget) {
2170 widget->Show(aPluginIds.Contains((uintptr_t)windowId));
2174 #endif
2177 #if defined(XP_WIN)
2178 // static
2179 void nsIWidget::CaptureRegisteredPlugins(uintptr_t aOwnerWidget) {
2180 MOZ_ASSERT(NS_IsMainThread());
2181 MOZ_ASSERT(sPluginWidgetList);
2183 // Our visible list is associated with a compositor which is associated with
2184 // a specific top level window. We use the parent widget during iteration
2185 // to skip the plugin widgets owned by other top level windows.
2186 for (const auto& entry : *sPluginWidgetList) {
2187 DebugOnly<const void*> windowId = entry.GetKey();
2188 nsIWidget* widget = entry.GetWeak();
2190 MOZ_ASSERT(windowId);
2191 MOZ_ASSERT(widget);
2193 if (!widget->Destroyed() && widget->IsVisible()) {
2194 if ((uintptr_t)widget->GetParent() == aOwnerWidget) {
2195 widget->UpdateScrollCapture();
2201 uint64_t nsBaseWidget::CreateScrollCaptureContainer() {
2202 mScrollCaptureContainer =
2203 LayerManager::CreateImageContainer(ImageContainer::ASYNCHRONOUS);
2204 if (!mScrollCaptureContainer) {
2205 NS_WARNING("Failed to create ImageContainer for widget image capture.");
2206 return ImageContainer::sInvalidAsyncContainerId;
2209 return mScrollCaptureContainer->GetAsyncContainerHandle().Value();
2212 void nsBaseWidget::UpdateScrollCapture() {
2213 // Don't capture if no container or no size.
2214 if (!mScrollCaptureContainer || mBounds.IsEmpty()) {
2215 return;
2218 // If the derived class cannot take a snapshot, for example due to clipping,
2219 // then it is responsible for creating a fallback. If null is returned, this
2220 // means that we want to keep the existing snapshot.
2221 RefPtr<gfx::SourceSurface> snapshot = CreateScrollSnapshot();
2222 if (!snapshot) {
2223 return;
2226 ImageContainer::NonOwningImage holder(new SourceSurfaceImage(snapshot));
2228 AutoTArray<ImageContainer::NonOwningImage, 1> imageList;
2229 imageList.AppendElement(holder);
2231 mScrollCaptureContainer->SetCurrentImages(imageList);
2234 void nsBaseWidget::DefaultFillScrollCapture(DrawTarget* aSnapshotDrawTarget) {
2235 gfx::IntSize dtSize = aSnapshotDrawTarget->GetSize();
2236 aSnapshotDrawTarget->FillRect(
2237 gfx::Rect(0, 0, dtSize.width, dtSize.height),
2238 gfx::ColorPattern(gfx::ToDeviceColor(kScrollCaptureFillColor)),
2239 gfx::DrawOptions(1.f, gfx::CompositionOp::OP_SOURCE));
2240 aSnapshotDrawTarget->Flush();
2242 #endif
2244 const IMENotificationRequests& nsIWidget::IMENotificationRequestsRef() {
2245 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
2246 return dispatcher->IMENotificationRequestsRef();
2249 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent* aEvent) {}
2251 bool nsIWidget::GetEditCommands(nsIWidget::NativeKeyBindingsType aType,
2252 const WidgetKeyboardEvent& aEvent,
2253 nsTArray<CommandInt>& aCommands) {
2254 MOZ_ASSERT(aEvent.IsTrusted());
2255 MOZ_ASSERT(aCommands.IsEmpty());
2256 return true;
2259 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboard() {
2260 if (XRE_IsContentProcess()) {
2261 return CreateBidiKeyboardContentProcess();
2263 return CreateBidiKeyboardInner();
2266 #ifdef ANDROID
2267 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboardInner() {
2268 // no bidi keyboard implementation
2269 return nullptr;
2271 #endif
2273 namespace mozilla::widget {
2275 const char* ToChar(InputContext::Origin aOrigin) {
2276 switch (aOrigin) {
2277 case InputContext::ORIGIN_MAIN:
2278 return "ORIGIN_MAIN";
2279 case InputContext::ORIGIN_CONTENT:
2280 return "ORIGIN_CONTENT";
2281 default:
2282 return "Unexpected value";
2286 const char* ToChar(IMEMessage aIMEMessage) {
2287 switch (aIMEMessage) {
2288 case NOTIFY_IME_OF_NOTHING:
2289 return "NOTIFY_IME_OF_NOTHING";
2290 case NOTIFY_IME_OF_FOCUS:
2291 return "NOTIFY_IME_OF_FOCUS";
2292 case NOTIFY_IME_OF_BLUR:
2293 return "NOTIFY_IME_OF_BLUR";
2294 case NOTIFY_IME_OF_SELECTION_CHANGE:
2295 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2296 case NOTIFY_IME_OF_TEXT_CHANGE:
2297 return "NOTIFY_IME_OF_TEXT_CHANGE";
2298 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED:
2299 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2300 case NOTIFY_IME_OF_POSITION_CHANGE:
2301 return "NOTIFY_IME_OF_POSITION_CHANGE";
2302 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
2303 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2304 case REQUEST_TO_COMMIT_COMPOSITION:
2305 return "REQUEST_TO_COMMIT_COMPOSITION";
2306 case REQUEST_TO_CANCEL_COMPOSITION:
2307 return "REQUEST_TO_CANCEL_COMPOSITION";
2308 default:
2309 return "Unexpected value";
2313 void NativeIMEContext::Init(nsIWidget* aWidget) {
2314 if (!aWidget) {
2315 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2316 mOriginProcessID = static_cast<uint64_t>(-1);
2317 return;
2319 if (!XRE_IsContentProcess()) {
2320 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(
2321 aWidget->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT));
2322 mOriginProcessID = 0;
2323 return;
2325 // If this is created in a child process, aWidget is an instance of
2326 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2327 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2328 // native IME context of the parent process.
2329 *this = aWidget->GetNativeIMEContext();
2332 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext) {
2333 if (NS_WARN_IF(!aRawNativeIMEContext)) {
2334 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2335 mOriginProcessID = static_cast<uint64_t>(-1);
2336 return;
2338 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(aRawNativeIMEContext);
2339 mOriginProcessID =
2340 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2343 void IMENotification::TextChangeDataBase::MergeWith(
2344 const IMENotification::TextChangeDataBase& aOther) {
2345 MOZ_ASSERT(aOther.IsValid(), "Merging data must store valid data");
2346 MOZ_ASSERT(aOther.mStartOffset <= aOther.mRemovedEndOffset,
2347 "end of removed text must be same or larger than start");
2348 MOZ_ASSERT(aOther.mStartOffset <= aOther.mAddedEndOffset,
2349 "end of added text must be same or larger than start");
2351 if (!IsValid()) {
2352 *this = aOther;
2353 return;
2356 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2357 // text ranges. I.e., mStartOffset should be the smallest offset of all
2358 // modified text ranges in old text. |mRemovedEndOffset| should be the
2359 // largest end offset in old text of all modified text ranges.
2360 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2361 // I.e., only this is an offset in new text.
2362 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2363 // premodified text was already removed. And some text whose length is
2364 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2365 // this allows IME to mark dirty the modified text range with |mStartOffset|
2366 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2367 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2368 // Additionally, IME can retrieve only the text between |mStartOffset| and
2369 // |mAddedEndOffset| for updating stored text.
2371 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2372 // should be adjusted to be in same text. The |newData.mStartOffset| and
2373 // |newData.mRemovedEndOffset| should be computed as in old text because
2374 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2375 // in the old text but even if some text before the values of the newData
2376 // has already been modified, the values don't include the changes.
2378 // For comparing new and old |mAddedEndOffset| values, they should be
2379 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2380 // computed as in the new text because |mAddedEndOffset| indicates the end
2381 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2382 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2384 const TextChangeDataBase& newData = aOther;
2385 const TextChangeDataBase oldData = *this;
2387 // mCausedOnlyByComposition should be true only when all changes are caused
2388 // by composition.
2389 mCausedOnlyByComposition =
2390 newData.mCausedOnlyByComposition && oldData.mCausedOnlyByComposition;
2392 // mIncludingChangesWithoutComposition should be true if at least one of
2393 // merged changes occurred without composition.
2394 mIncludingChangesWithoutComposition =
2395 newData.mIncludingChangesWithoutComposition ||
2396 oldData.mIncludingChangesWithoutComposition;
2398 // mIncludingChangesDuringComposition should be true when at least one of
2399 // the merged non-composition changes occurred during the latest composition.
2400 if (!newData.mCausedOnlyByComposition &&
2401 !newData.mIncludingChangesDuringComposition) {
2402 MOZ_ASSERT(newData.mIncludingChangesWithoutComposition);
2403 MOZ_ASSERT(mIncludingChangesWithoutComposition);
2404 // If new change is neither caused by composition nor occurred during
2405 // composition, set mIncludingChangesDuringComposition to false because
2406 // IME doesn't want outdated text changes as text change during current
2407 // composition.
2408 mIncludingChangesDuringComposition = false;
2409 } else {
2410 // Otherwise, set mIncludingChangesDuringComposition to true if either
2411 // oldData or newData includes changes during composition.
2412 mIncludingChangesDuringComposition =
2413 newData.mIncludingChangesDuringComposition ||
2414 oldData.mIncludingChangesDuringComposition;
2417 if (newData.mStartOffset >= oldData.mAddedEndOffset) {
2418 // Case 1:
2419 // If new start is after old end offset of added text, it means that text
2420 // after the modified range is modified. Like:
2421 // added range of old change: +----------+
2422 // removed range of new change: +----------+
2423 // So, the old start offset is always the smaller offset.
2424 mStartOffset = oldData.mStartOffset;
2425 // The new end offset of removed text is moved by the old change and we
2426 // need to cancel the move of the old change for comparing the offsets in
2427 // same text because it doesn't make sensce to compare offsets in different
2428 // text.
2429 uint32_t newRemovedEndOffsetInOldText =
2430 newData.mRemovedEndOffset - oldData.Difference();
2431 mRemovedEndOffset =
2432 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2433 // The new end offset of added text is always the larger offset.
2434 mAddedEndOffset = newData.mAddedEndOffset;
2435 return;
2438 if (newData.mStartOffset >= oldData.mStartOffset) {
2439 // If new start is in the modified range, it means that new data changes
2440 // a part or all of the range.
2441 mStartOffset = oldData.mStartOffset;
2442 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2443 // Case 2:
2444 // If new end of removed text is greater than old end of added text, it
2445 // means that all or a part of modified range modified again and text
2446 // after the modified range is also modified. Like:
2447 // added range of old change: +----------+
2448 // removed range of new change: +----------+
2449 // So, the new removed end offset is moved by the old change and we need
2450 // to cancel the move of the old change for comparing the offsets in the
2451 // same text because it doesn't make sense to compare the offsets in
2452 // different text.
2453 uint32_t newRemovedEndOffsetInOldText =
2454 newData.mRemovedEndOffset - oldData.Difference();
2455 mRemovedEndOffset =
2456 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2457 // The old end of added text is replaced by new change. So, it should be
2458 // same as the new start. On the other hand, the new added end offset is
2459 // always same or larger. Therefore, the merged end offset of added
2460 // text should be the new end offset of added text.
2461 mAddedEndOffset = newData.mAddedEndOffset;
2462 return;
2465 // Case 3:
2466 // If new end of removed text is less than old end of added text, it means
2467 // that only a part of the modified range is modified again. Like:
2468 // added range of old change: +------------+
2469 // removed range of new change: +-----+
2470 // So, the new end offset of removed text should be same as the old end
2471 // offset of removed text. Therefore, the merged end offset of removed
2472 // text should be the old text change's |mRemovedEndOffset|.
2473 mRemovedEndOffset = oldData.mRemovedEndOffset;
2474 // The old end of added text is moved by new change. So, we need to cancel
2475 // the move of the new change for comparing the offsets in same text.
2476 uint32_t oldAddedEndOffsetInNewText =
2477 oldData.mAddedEndOffset + newData.Difference();
2478 mAddedEndOffset =
2479 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2480 return;
2483 if (newData.mRemovedEndOffset >= oldData.mStartOffset) {
2484 // If new end of removed text is greater than old start (and new start is
2485 // less than old start), it means that a part of modified range is modified
2486 // again and some new text before the modified range is also modified.
2487 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2488 "new start offset should be less than old one here");
2489 mStartOffset = newData.mStartOffset;
2490 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2491 // Case 4:
2492 // If new end of removed text is greater than old end of added text, it
2493 // means that all modified text and text after the modified range is
2494 // modified. Like:
2495 // added range of old change: +----------+
2496 // removed range of new change: +------------------+
2497 // So, the new end of removed text is moved by the old change. Therefore,
2498 // we need to cancel the move of the old change for comparing the offsets
2499 // in same text because it doesn't make sense to compare the offsets in
2500 // different text.
2501 uint32_t newRemovedEndOffsetInOldText =
2502 newData.mRemovedEndOffset - oldData.Difference();
2503 mRemovedEndOffset =
2504 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2505 // The old end of added text is replaced by new change. So, the old end
2506 // offset of added text is same as new text change's start offset. Then,
2507 // new change's end offset of added text is always same or larger than
2508 // it. Therefore, merged end offset of added text is always the new end
2509 // offset of added text.
2510 mAddedEndOffset = newData.mAddedEndOffset;
2511 return;
2514 // Case 5:
2515 // If new end of removed text is less than old end of added text, it
2516 // means that only a part of the modified range is modified again. Like:
2517 // added range of old change: +----------+
2518 // removed range of new change: +----------+
2519 // So, the new end of removed text should be same as old end of removed
2520 // text for preventing end of removed text to be modified. Therefore,
2521 // merged end offset of removed text is always the old end offset of removed
2522 // text.
2523 mRemovedEndOffset = oldData.mRemovedEndOffset;
2524 // The old end of added text is moved by this change. So, we need to
2525 // cancel the move of the new change for comparing the offsets in same text
2526 // because it doesn't make sense to compare the offsets in different text.
2527 uint32_t oldAddedEndOffsetInNewText =
2528 oldData.mAddedEndOffset + newData.Difference();
2529 mAddedEndOffset =
2530 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2531 return;
2534 // Case 6:
2535 // Otherwise, i.e., both new end of added text and new start are less than
2536 // old start, text before the modified range is modified. Like:
2537 // added range of old change: +----------+
2538 // removed range of new change: +----------+
2539 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2540 "new start offset should be less than old one here");
2541 mStartOffset = newData.mStartOffset;
2542 MOZ_ASSERT(newData.mRemovedEndOffset < oldData.mRemovedEndOffset,
2543 "new removed end offset should be less than old one here");
2544 mRemovedEndOffset = oldData.mRemovedEndOffset;
2545 // The end of added text should be adjusted with the new difference.
2546 uint32_t oldAddedEndOffsetInNewText =
2547 oldData.mAddedEndOffset + newData.Difference();
2548 mAddedEndOffset =
2549 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2552 #ifdef DEBUG
2554 // Let's test the code of merging multiple text change data in debug build
2555 // and crash if one of them fails because this feature is very complex but
2556 // cannot be tested with mochitest.
2557 void IMENotification::TextChangeDataBase::Test() {
2558 static bool gTestTextChangeEvent = true;
2559 if (!gTestTextChangeEvent) {
2560 return;
2562 gTestTextChangeEvent = false;
2564 /****************************************************************************
2565 * Case 1
2566 ****************************************************************************/
2568 // Appending text
2569 MergeWith(TextChangeData(10, 10, 20, false, false));
2570 MergeWith(TextChangeData(20, 20, 35, false, false));
2571 MOZ_ASSERT(mStartOffset == 10,
2572 "Test 1-1-1: mStartOffset should be the first offset");
2573 MOZ_ASSERT(
2574 mRemovedEndOffset == 10, // 20 - (20 - 10)
2575 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2576 MOZ_ASSERT(
2577 mAddedEndOffset == 35,
2578 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2579 Clear();
2581 // Removing text (longer line -> shorter line)
2582 MergeWith(TextChangeData(10, 20, 10, false, false));
2583 MergeWith(TextChangeData(10, 30, 10, false, false));
2584 MOZ_ASSERT(mStartOffset == 10,
2585 "Test 1-2-1: mStartOffset should be the first offset");
2586 MOZ_ASSERT(mRemovedEndOffset == 40, // 30 + (10 - 20)
2587 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2588 "removed text "
2589 "with already removed length");
2590 MOZ_ASSERT(
2591 mAddedEndOffset == 10,
2592 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2593 Clear();
2595 // Removing text (shorter line -> longer line)
2596 MergeWith(TextChangeData(10, 20, 10, false, false));
2597 MergeWith(TextChangeData(10, 15, 10, false, false));
2598 MOZ_ASSERT(mStartOffset == 10,
2599 "Test 1-3-1: mStartOffset should be the first offset");
2600 MOZ_ASSERT(mRemovedEndOffset == 25, // 15 + (10 - 20)
2601 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2602 "removed text "
2603 "with already removed length");
2604 MOZ_ASSERT(
2605 mAddedEndOffset == 10,
2606 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2607 Clear();
2609 // Appending text at different point (not sure if actually occurs)
2610 MergeWith(TextChangeData(10, 10, 20, false, false));
2611 MergeWith(TextChangeData(55, 55, 60, false, false));
2612 MOZ_ASSERT(mStartOffset == 10,
2613 "Test 1-4-1: mStartOffset should be the smallest offset");
2614 MOZ_ASSERT(
2615 mRemovedEndOffset == 45, // 55 - (10 - 20)
2616 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2617 "text without already added length");
2618 MOZ_ASSERT(
2619 mAddedEndOffset == 60,
2620 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2621 Clear();
2623 // Removing text at different point (not sure if actually occurs)
2624 MergeWith(TextChangeData(10, 20, 10, false, false));
2625 MergeWith(TextChangeData(55, 68, 55, false, false));
2626 MOZ_ASSERT(mStartOffset == 10,
2627 "Test 1-5-1: mStartOffset should be the smallest offset");
2628 MOZ_ASSERT(
2629 mRemovedEndOffset == 78, // 68 - (10 - 20)
2630 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2631 "text with already removed length");
2632 MOZ_ASSERT(
2633 mAddedEndOffset == 55,
2634 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2635 Clear();
2637 // Replacing text and append text (becomes longer)
2638 MergeWith(TextChangeData(30, 35, 32, false, false));
2639 MergeWith(TextChangeData(32, 32, 40, false, false));
2640 MOZ_ASSERT(mStartOffset == 30,
2641 "Test 1-6-1: mStartOffset should be the smallest offset");
2642 MOZ_ASSERT(
2643 mRemovedEndOffset == 35, // 32 - (32 - 35)
2644 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2645 "text");
2646 MOZ_ASSERT(
2647 mAddedEndOffset == 40,
2648 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2649 Clear();
2651 // Replacing text and append text (becomes shorter)
2652 MergeWith(TextChangeData(30, 35, 32, false, false));
2653 MergeWith(TextChangeData(32, 32, 33, false, false));
2654 MOZ_ASSERT(mStartOffset == 30,
2655 "Test 1-7-1: mStartOffset should be the smallest offset");
2656 MOZ_ASSERT(
2657 mRemovedEndOffset == 35, // 32 - (32 - 35)
2658 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2659 "text");
2660 MOZ_ASSERT(
2661 mAddedEndOffset == 33,
2662 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2663 Clear();
2665 // Removing text and replacing text after first range (not sure if actually
2666 // occurs)
2667 MergeWith(TextChangeData(30, 35, 30, false, false));
2668 MergeWith(TextChangeData(32, 34, 48, false, false));
2669 MOZ_ASSERT(mStartOffset == 30,
2670 "Test 1-8-1: mStartOffset should be the smallest offset");
2671 MOZ_ASSERT(mRemovedEndOffset == 39, // 34 - (30 - 35)
2672 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2673 "removed text "
2674 "without already removed text");
2675 MOZ_ASSERT(
2676 mAddedEndOffset == 48,
2677 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2678 Clear();
2680 // Removing text and replacing text after first range (not sure if actually
2681 // occurs)
2682 MergeWith(TextChangeData(30, 35, 30, false, false));
2683 MergeWith(TextChangeData(32, 38, 36, false, false));
2684 MOZ_ASSERT(mStartOffset == 30,
2685 "Test 1-9-1: mStartOffset should be the smallest offset");
2686 MOZ_ASSERT(mRemovedEndOffset == 43, // 38 - (30 - 35)
2687 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2688 "removed text "
2689 "without already removed text");
2690 MOZ_ASSERT(
2691 mAddedEndOffset == 36,
2692 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2693 Clear();
2695 /****************************************************************************
2696 * Case 2
2697 ****************************************************************************/
2699 // Replacing text in around end of added text (becomes shorter) (not sure
2700 // if actually occurs)
2701 MergeWith(TextChangeData(50, 50, 55, false, false));
2702 MergeWith(TextChangeData(53, 60, 54, false, false));
2703 MOZ_ASSERT(mStartOffset == 50,
2704 "Test 2-1-1: mStartOffset should be the smallest offset");
2705 MOZ_ASSERT(mRemovedEndOffset == 55, // 60 - (55 - 50)
2706 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2707 "removed text "
2708 "without already added text length");
2709 MOZ_ASSERT(
2710 mAddedEndOffset == 54,
2711 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2712 Clear();
2714 // Replacing text around end of added text (becomes longer) (not sure
2715 // if actually occurs)
2716 MergeWith(TextChangeData(50, 50, 55, false, false));
2717 MergeWith(TextChangeData(54, 62, 68, false, false));
2718 MOZ_ASSERT(mStartOffset == 50,
2719 "Test 2-2-1: mStartOffset should be the smallest offset");
2720 MOZ_ASSERT(mRemovedEndOffset == 57, // 62 - (55 - 50)
2721 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2722 "removed text "
2723 "without already added text length");
2724 MOZ_ASSERT(
2725 mAddedEndOffset == 68,
2726 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2727 Clear();
2729 // Replacing text around end of replaced text (became shorter) (not sure if
2730 // actually occurs)
2731 MergeWith(TextChangeData(36, 48, 45, false, false));
2732 MergeWith(TextChangeData(43, 50, 49, false, false));
2733 MOZ_ASSERT(mStartOffset == 36,
2734 "Test 2-3-1: mStartOffset should be the smallest offset");
2735 MOZ_ASSERT(mRemovedEndOffset == 53, // 50 - (45 - 48)
2736 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2737 "removed text "
2738 "without already removed text length");
2739 MOZ_ASSERT(
2740 mAddedEndOffset == 49,
2741 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2742 Clear();
2744 // Replacing text around end of replaced text (became longer) (not sure if
2745 // actually occurs)
2746 MergeWith(TextChangeData(36, 52, 53, false, false));
2747 MergeWith(TextChangeData(43, 68, 61, false, false));
2748 MOZ_ASSERT(mStartOffset == 36,
2749 "Test 2-4-1: mStartOffset should be the smallest offset");
2750 MOZ_ASSERT(mRemovedEndOffset == 67, // 68 - (53 - 52)
2751 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2752 "removed text "
2753 "without already added text length");
2754 MOZ_ASSERT(
2755 mAddedEndOffset == 61,
2756 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2757 Clear();
2759 /****************************************************************************
2760 * Case 3
2761 ****************************************************************************/
2763 // Appending text in already added text (not sure if actually occurs)
2764 MergeWith(TextChangeData(10, 10, 20, false, false));
2765 MergeWith(TextChangeData(15, 15, 30, false, false));
2766 MOZ_ASSERT(mStartOffset == 10,
2767 "Test 3-1-1: mStartOffset should be the smallest offset");
2768 MOZ_ASSERT(mRemovedEndOffset == 10,
2769 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2770 "removed text");
2771 MOZ_ASSERT(
2772 mAddedEndOffset == 35, // 20 + (30 - 15)
2773 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2774 "added text length by the new change");
2775 Clear();
2777 // Replacing text in added text (not sure if actually occurs)
2778 MergeWith(TextChangeData(50, 50, 55, false, false));
2779 MergeWith(TextChangeData(52, 53, 56, false, false));
2780 MOZ_ASSERT(mStartOffset == 50,
2781 "Test 3-2-1: mStartOffset should be the smallest offset");
2782 MOZ_ASSERT(mRemovedEndOffset == 50,
2783 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2784 "removed text");
2785 MOZ_ASSERT(
2786 mAddedEndOffset == 58, // 55 + (56 - 53)
2787 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2788 "added text length by the new change");
2789 Clear();
2791 // Replacing text in replaced text (became shorter) (not sure if actually
2792 // occurs)
2793 MergeWith(TextChangeData(36, 48, 45, false, false));
2794 MergeWith(TextChangeData(37, 38, 50, false, false));
2795 MOZ_ASSERT(mStartOffset == 36,
2796 "Test 3-3-1: mStartOffset should be the smallest offset");
2797 MOZ_ASSERT(mRemovedEndOffset == 48,
2798 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2799 "removed text");
2800 MOZ_ASSERT(
2801 mAddedEndOffset == 57, // 45 + (50 - 38)
2802 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2803 "added text length by the new change");
2804 Clear();
2806 // Replacing text in replaced text (became longer) (not sure if actually
2807 // occurs)
2808 MergeWith(TextChangeData(32, 48, 53, false, false));
2809 MergeWith(TextChangeData(43, 50, 52, false, false));
2810 MOZ_ASSERT(mStartOffset == 32,
2811 "Test 3-4-1: mStartOffset should be the smallest offset");
2812 MOZ_ASSERT(mRemovedEndOffset == 48,
2813 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2814 "removed text "
2815 "without already added text length");
2816 MOZ_ASSERT(
2817 mAddedEndOffset == 55, // 53 + (52 - 50)
2818 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2819 "added text length by the new change");
2820 Clear();
2822 // Replacing text in replaced text (became shorter) (not sure if actually
2823 // occurs)
2824 MergeWith(TextChangeData(36, 48, 50, false, false));
2825 MergeWith(TextChangeData(37, 49, 47, false, false));
2826 MOZ_ASSERT(mStartOffset == 36,
2827 "Test 3-5-1: mStartOffset should be the smallest offset");
2828 MOZ_ASSERT(
2829 mRemovedEndOffset == 48,
2830 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
2831 "text");
2832 MOZ_ASSERT(mAddedEndOffset == 48, // 50 + (47 - 49)
2833 "Test 3-5-3: mAddedEndOffset should be the first end of added "
2834 "text without "
2835 "removed text length by the new change");
2836 Clear();
2838 // Replacing text in replaced text (became longer) (not sure if actually
2839 // occurs)
2840 MergeWith(TextChangeData(32, 48, 53, false, false));
2841 MergeWith(TextChangeData(43, 50, 47, false, false));
2842 MOZ_ASSERT(mStartOffset == 32,
2843 "Test 3-6-1: mStartOffset should be the smallest offset");
2844 MOZ_ASSERT(mRemovedEndOffset == 48,
2845 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
2846 "removed text "
2847 "without already added text length");
2848 MOZ_ASSERT(mAddedEndOffset == 50, // 53 + (47 - 50)
2849 "Test 3-6-3: mAddedEndOffset should be the first end of added "
2850 "text without "
2851 "removed text length by the new change");
2852 Clear();
2854 /****************************************************************************
2855 * Case 4
2856 ****************************************************************************/
2858 // Replacing text all of already append text (not sure if actually occurs)
2859 MergeWith(TextChangeData(50, 50, 55, false, false));
2860 MergeWith(TextChangeData(44, 66, 68, false, false));
2861 MOZ_ASSERT(mStartOffset == 44,
2862 "Test 4-1-1: mStartOffset should be the smallest offset");
2863 MOZ_ASSERT(mRemovedEndOffset == 61, // 66 - (55 - 50)
2864 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
2865 "removed text "
2866 "without already added text length");
2867 MOZ_ASSERT(
2868 mAddedEndOffset == 68,
2869 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
2870 Clear();
2872 // Replacing text around a point in which text was removed (not sure if
2873 // actually occurs)
2874 MergeWith(TextChangeData(50, 62, 50, false, false));
2875 MergeWith(TextChangeData(44, 66, 68, false, false));
2876 MOZ_ASSERT(mStartOffset == 44,
2877 "Test 4-2-1: mStartOffset should be the smallest offset");
2878 MOZ_ASSERT(mRemovedEndOffset == 78, // 66 - (50 - 62)
2879 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
2880 "removed text "
2881 "without already removed text length");
2882 MOZ_ASSERT(
2883 mAddedEndOffset == 68,
2884 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
2885 Clear();
2887 // Replacing text all replaced text (became shorter) (not sure if actually
2888 // occurs)
2889 MergeWith(TextChangeData(50, 62, 60, false, false));
2890 MergeWith(TextChangeData(49, 128, 130, false, false));
2891 MOZ_ASSERT(mStartOffset == 49,
2892 "Test 4-3-1: mStartOffset should be the smallest offset");
2893 MOZ_ASSERT(mRemovedEndOffset == 130, // 128 - (60 - 62)
2894 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
2895 "removed text "
2896 "without already removed text length");
2897 MOZ_ASSERT(
2898 mAddedEndOffset == 130,
2899 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
2900 Clear();
2902 // Replacing text all replaced text (became longer) (not sure if actually
2903 // occurs)
2904 MergeWith(TextChangeData(50, 61, 73, false, false));
2905 MergeWith(TextChangeData(44, 100, 50, false, false));
2906 MOZ_ASSERT(mStartOffset == 44,
2907 "Test 4-4-1: mStartOffset should be the smallest offset");
2908 MOZ_ASSERT(mRemovedEndOffset == 88, // 100 - (73 - 61)
2909 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
2910 "removed text "
2911 "with already added text length");
2912 MOZ_ASSERT(
2913 mAddedEndOffset == 50,
2914 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
2915 Clear();
2917 /****************************************************************************
2918 * Case 5
2919 ****************************************************************************/
2921 // Replacing text around start of added text (not sure if actually occurs)
2922 MergeWith(TextChangeData(50, 50, 55, false, false));
2923 MergeWith(TextChangeData(48, 52, 49, false, false));
2924 MOZ_ASSERT(mStartOffset == 48,
2925 "Test 5-1-1: mStartOffset should be the smallest offset");
2926 MOZ_ASSERT(
2927 mRemovedEndOffset == 50,
2928 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
2929 "text");
2930 MOZ_ASSERT(
2931 mAddedEndOffset == 52, // 55 + (52 - 49)
2932 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
2933 "added text length by the new change");
2934 Clear();
2936 // Replacing text around start of replaced text (became shorter) (not sure if
2937 // actually occurs)
2938 MergeWith(TextChangeData(50, 60, 58, false, false));
2939 MergeWith(TextChangeData(43, 50, 48, false, false));
2940 MOZ_ASSERT(mStartOffset == 43,
2941 "Test 5-2-1: mStartOffset should be the smallest offset");
2942 MOZ_ASSERT(
2943 mRemovedEndOffset == 60,
2944 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
2945 "text");
2946 MOZ_ASSERT(mAddedEndOffset == 56, // 58 + (48 - 50)
2947 "Test 5-2-3: mAddedEndOffset should be the first end of added "
2948 "text without "
2949 "removed text length by the new change");
2950 Clear();
2952 // Replacing text around start of replaced text (became longer) (not sure if
2953 // actually occurs)
2954 MergeWith(TextChangeData(50, 60, 68, false, false));
2955 MergeWith(TextChangeData(43, 55, 53, false, false));
2956 MOZ_ASSERT(mStartOffset == 43,
2957 "Test 5-3-1: mStartOffset should be the smallest offset");
2958 MOZ_ASSERT(
2959 mRemovedEndOffset == 60,
2960 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
2961 "text");
2962 MOZ_ASSERT(mAddedEndOffset == 66, // 68 + (53 - 55)
2963 "Test 5-3-3: mAddedEndOffset should be the first end of added "
2964 "text without "
2965 "removed text length by the new change");
2966 Clear();
2968 // Replacing text around start of replaced text (became shorter) (not sure if
2969 // actually occurs)
2970 MergeWith(TextChangeData(50, 60, 58, false, false));
2971 MergeWith(TextChangeData(43, 50, 128, false, false));
2972 MOZ_ASSERT(mStartOffset == 43,
2973 "Test 5-4-1: mStartOffset should be the smallest offset");
2974 MOZ_ASSERT(
2975 mRemovedEndOffset == 60,
2976 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
2977 "text");
2978 MOZ_ASSERT(
2979 mAddedEndOffset == 136, // 58 + (128 - 50)
2980 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
2981 "added text length by the new change");
2982 Clear();
2984 // Replacing text around start of replaced text (became longer) (not sure if
2985 // actually occurs)
2986 MergeWith(TextChangeData(50, 60, 68, false, false));
2987 MergeWith(TextChangeData(43, 55, 65, false, false));
2988 MOZ_ASSERT(mStartOffset == 43,
2989 "Test 5-5-1: mStartOffset should be the smallest offset");
2990 MOZ_ASSERT(
2991 mRemovedEndOffset == 60,
2992 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
2993 "text");
2994 MOZ_ASSERT(
2995 mAddedEndOffset == 78, // 68 + (65 - 55)
2996 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
2997 "added text length by the new change");
2998 Clear();
3000 /****************************************************************************
3001 * Case 6
3002 ****************************************************************************/
3004 // Appending text before already added text (not sure if actually occurs)
3005 MergeWith(TextChangeData(30, 30, 45, false, false));
3006 MergeWith(TextChangeData(10, 10, 20, false, false));
3007 MOZ_ASSERT(mStartOffset == 10,
3008 "Test 6-1-1: mStartOffset should be the smallest offset");
3009 MOZ_ASSERT(
3010 mRemovedEndOffset == 30,
3011 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3012 "text");
3013 MOZ_ASSERT(
3014 mAddedEndOffset == 55, // 45 + (20 - 10)
3015 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3016 "added text length by the new change");
3017 Clear();
3019 // Removing text before already removed text (not sure if actually occurs)
3020 MergeWith(TextChangeData(30, 35, 30, false, false));
3021 MergeWith(TextChangeData(10, 25, 10, false, false));
3022 MOZ_ASSERT(mStartOffset == 10,
3023 "Test 6-2-1: mStartOffset should be the smallest offset");
3024 MOZ_ASSERT(
3025 mRemovedEndOffset == 35,
3026 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3027 "text");
3028 MOZ_ASSERT(
3029 mAddedEndOffset == 15, // 30 - (25 - 10)
3030 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3031 "removed text length by the new change");
3032 Clear();
3034 // Replacing text before already replaced text (not sure if actually occurs)
3035 MergeWith(TextChangeData(50, 65, 70, false, false));
3036 MergeWith(TextChangeData(13, 24, 15, false, false));
3037 MOZ_ASSERT(mStartOffset == 13,
3038 "Test 6-3-1: mStartOffset should be the smallest offset");
3039 MOZ_ASSERT(
3040 mRemovedEndOffset == 65,
3041 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3042 "text");
3043 MOZ_ASSERT(mAddedEndOffset == 61, // 70 + (15 - 24)
3044 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3045 "text without "
3046 "removed text length by the new change");
3047 Clear();
3049 // Replacing text before already replaced text (not sure if actually occurs)
3050 MergeWith(TextChangeData(50, 65, 70, false, false));
3051 MergeWith(TextChangeData(13, 24, 36, false, false));
3052 MOZ_ASSERT(mStartOffset == 13,
3053 "Test 6-4-1: mStartOffset should be the smallest offset");
3054 MOZ_ASSERT(
3055 mRemovedEndOffset == 65,
3056 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3057 "text");
3058 MOZ_ASSERT(mAddedEndOffset == 82, // 70 + (36 - 24)
3059 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3060 "text without "
3061 "removed text length by the new change");
3062 Clear();
3065 #endif // #ifdef DEBUG
3067 } // namespace mozilla::widget
3069 #ifdef DEBUG
3070 //////////////////////////////////////////////////////////////
3072 // Convert a GUI event message code to a string.
3073 // Makes it a lot easier to debug events.
3075 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3076 // for a DebugPrintEvent() function that uses
3077 // this.
3079 //////////////////////////////////////////////////////////////
3080 /* static */
3081 nsAutoString nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent* aGuiEvent) {
3082 NS_ASSERTION(nullptr != aGuiEvent, "cmon, null gui event.");
3084 nsAutoString eventName(u"UNKNOWN"_ns);
3086 # define _ASSIGN_eventName(_value, _name) \
3087 case _value: \
3088 eventName.AssignLiteral(_name); \
3089 break
3091 switch (aGuiEvent->mMessage) {
3092 _ASSIGN_eventName(eBlur, "eBlur");
3093 _ASSIGN_eventName(eDrop, "eDrop");
3094 _ASSIGN_eventName(eDragEnter, "eDragEnter");
3095 _ASSIGN_eventName(eDragExit, "eDragExit");
3096 _ASSIGN_eventName(eDragOver, "eDragOver");
3097 _ASSIGN_eventName(eEditorInput, "eEditorInput");
3098 _ASSIGN_eventName(eFocus, "eFocus");
3099 _ASSIGN_eventName(eFocusIn, "eFocusIn");
3100 _ASSIGN_eventName(eFocusOut, "eFocusOut");
3101 _ASSIGN_eventName(eFormSelect, "eFormSelect");
3102 _ASSIGN_eventName(eFormChange, "eFormChange");
3103 _ASSIGN_eventName(eFormReset, "eFormReset");
3104 _ASSIGN_eventName(eFormSubmit, "eFormSubmit");
3105 _ASSIGN_eventName(eImageAbort, "eImageAbort");
3106 _ASSIGN_eventName(eLoadError, "eLoadError");
3107 _ASSIGN_eventName(eKeyDown, "eKeyDown");
3108 _ASSIGN_eventName(eKeyPress, "eKeyPress");
3109 _ASSIGN_eventName(eKeyUp, "eKeyUp");
3110 _ASSIGN_eventName(eMouseEnterIntoWidget, "eMouseEnterIntoWidget");
3111 _ASSIGN_eventName(eMouseExitFromWidget, "eMouseExitFromWidget");
3112 _ASSIGN_eventName(eMouseDown, "eMouseDown");
3113 _ASSIGN_eventName(eMouseUp, "eMouseUp");
3114 _ASSIGN_eventName(eMouseClick, "eMouseClick");
3115 _ASSIGN_eventName(eMouseAuxClick, "eMouseAuxClick");
3116 _ASSIGN_eventName(eMouseDoubleClick, "eMouseDoubleClick");
3117 _ASSIGN_eventName(eMouseMove, "eMouseMove");
3118 _ASSIGN_eventName(eLoad, "eLoad");
3119 _ASSIGN_eventName(ePopState, "ePopState");
3120 _ASSIGN_eventName(eBeforeScriptExecute, "eBeforeScriptExecute");
3121 _ASSIGN_eventName(eAfterScriptExecute, "eAfterScriptExecute");
3122 _ASSIGN_eventName(eUnload, "eUnload");
3123 _ASSIGN_eventName(eHashChange, "eHashChange");
3124 _ASSIGN_eventName(eReadyStateChange, "eReadyStateChange");
3125 _ASSIGN_eventName(eXULBroadcast, "eXULBroadcast");
3126 _ASSIGN_eventName(eXULCommandUpdate, "eXULCommandUpdate");
3128 # undef _ASSIGN_eventName
3130 default: {
3131 eventName.AssignLiteral("UNKNOWN: ");
3132 eventName.AppendInt(aGuiEvent->mMessage);
3133 } break;
3136 return nsAutoString(eventName);
3138 //////////////////////////////////////////////////////////////
3140 // Code to deal with paint and event debug prefs.
3142 //////////////////////////////////////////////////////////////
3143 struct PrefPair {
3144 const char* name;
3145 bool value;
3148 static PrefPair debug_PrefValues[] = {
3149 {"nglayout.debug.crossing_event_dumping", false},
3150 {"nglayout.debug.event_dumping", false},
3151 {"nglayout.debug.invalidate_dumping", false},
3152 {"nglayout.debug.motion_event_dumping", false},
3153 {"nglayout.debug.paint_dumping", false},
3154 {"nglayout.debug.paint_flashing", false},
3155 {"nglayout.debug.paint_flashing_chrome", false}};
3157 //////////////////////////////////////////////////////////////
3158 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName) {
3159 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3161 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3162 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3163 return debug_PrefValues[i].value;
3167 return false;
3169 //////////////////////////////////////////////////////////////
3170 static void debug_SetCachedBoolPref(const char* aPrefName, bool aValue) {
3171 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3173 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3174 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3175 debug_PrefValues[i].value = aValue;
3177 return;
3181 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3184 //////////////////////////////////////////////////////////////
3185 class Debug_PrefObserver final : public nsIObserver {
3186 ~Debug_PrefObserver() = default;
3188 public:
3189 NS_DECL_ISUPPORTS
3190 NS_DECL_NSIOBSERVER
3193 NS_IMPL_ISUPPORTS(Debug_PrefObserver, nsIObserver)
3195 NS_IMETHODIMP
3196 Debug_PrefObserver::Observe(nsISupports* subject, const char* topic,
3197 const char16_t* data) {
3198 NS_ConvertUTF16toUTF8 prefName(data);
3200 bool value = Preferences::GetBool(prefName.get(), false);
3201 debug_SetCachedBoolPref(prefName.get(), value);
3202 return NS_OK;
3205 //////////////////////////////////////////////////////////////
3206 /* static */ void debug_RegisterPrefCallbacks() {
3207 static bool once = true;
3209 if (!once) {
3210 return;
3213 once = false;
3215 nsCOMPtr<nsIObserver> obs(new Debug_PrefObserver());
3216 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3217 // Initialize the pref values
3218 debug_PrefValues[i].value =
3219 Preferences::GetBool(debug_PrefValues[i].name, false);
3221 if (obs) {
3222 // Register callbacks for when these change
3223 nsCString name;
3224 name.AssignLiteral(debug_PrefValues[i].name,
3225 strlen(debug_PrefValues[i].name));
3226 Preferences::AddStrongObserver(obs, name);
3230 //////////////////////////////////////////////////////////////
3231 static int32_t _GetPrintCount() {
3232 static int32_t sCount = 0;
3234 return ++sCount;
3236 //////////////////////////////////////////////////////////////
3237 /* static */
3238 bool nsBaseWidget::debug_WantPaintFlashing() {
3239 return debug_GetCachedBoolPref("nglayout.debug.paint_flashing");
3241 //////////////////////////////////////////////////////////////
3242 /* static */
3243 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut, nsIWidget* aWidget,
3244 WidgetGUIEvent* aGuiEvent,
3245 const char* aWidgetName, int32_t aWindowID) {
3246 if (aGuiEvent->mMessage == eMouseMove) {
3247 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3250 if (aGuiEvent->mMessage == eMouseEnterIntoWidget ||
3251 aGuiEvent->mMessage == eMouseExitFromWidget) {
3252 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3253 return;
3256 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3258 NS_LossyConvertUTF16toASCII tempString(
3259 debug_GuiEventToString(aGuiEvent).get());
3261 fprintf(aFileOut, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3262 _GetPrintCount(), tempString.get(), (void*)aWidget, aWidgetName,
3263 aWindowID, aGuiEvent->mRefPoint.x, aGuiEvent->mRefPoint.y);
3265 //////////////////////////////////////////////////////////////
3266 /* static */
3267 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut, nsIWidget* aWidget,
3268 const nsIntRegion& aRegion,
3269 const char* aWidgetName,
3270 int32_t aWindowID) {
3271 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3272 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3274 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3276 nsIntRect rect = aRegion.GetBounds();
3277 fprintf(aFileOut,
3278 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3279 "%3d,%-3d",
3280 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID, rect.X(),
3281 rect.Y(), rect.Width(), rect.Height());
3283 fprintf(aFileOut, "\n");
3285 //////////////////////////////////////////////////////////////
3286 /* static */
3287 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut, nsIWidget* aWidget,
3288 const LayoutDeviceIntRect* aRect,
3289 const char* aWidgetName,
3290 int32_t aWindowID) {
3291 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3293 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3294 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3296 fprintf(aFileOut, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3297 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID);
3299 if (aRect) {
3300 fprintf(aFileOut, " rect=%3d,%-3d %3d,%-3d", aRect->X(), aRect->Y(),
3301 aRect->Width(), aRect->Height());
3302 } else {
3303 fprintf(aFileOut, " rect=%-15s", "none");
3306 fprintf(aFileOut, "\n");
3308 //////////////////////////////////////////////////////////////
3310 #endif // DEBUG