Bug 1608587 [wpt PR 21137] - Update wpt metadata, a=testonly
[gecko.git] / widget / nsBaseWidget.cpp
blob713f85db286fc50d8728f85c7d444f4a8e71cae7
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 "mozilla/ArrayUtils.h"
9 #include "mozilla/PresShell.h"
10 #include "mozilla/TextEventDispatcher.h"
11 #include "mozilla/TextEventDispatcherListener.h"
12 #include "mozilla/UniquePtr.h"
14 #include "mozilla/layers/CompositorBridgeChild.h"
15 #include "mozilla/layers/CompositorBridgeParent.h"
16 #include "mozilla/layers/PLayerTransactionChild.h"
17 #include "mozilla/layers/ImageBridgeChild.h"
18 #include "LiveResizeListener.h"
19 #include "nsBaseWidget.h"
20 #include "nsDeviceContext.h"
21 #include "nsCOMPtr.h"
22 #include "nsGfxCIID.h"
23 #include "nsWidgetsCID.h"
24 #include "nsServiceManagerUtils.h"
25 #include "nsIKeyEventInPluginCallback.h"
26 #include "nsIScreenManager.h"
27 #include "nsAppDirectoryServiceDefs.h"
28 #include "nsISimpleEnumerator.h"
29 #include "nsIContent.h"
30 #include "mozilla/dom/Document.h"
31 #include "mozilla/Preferences.h"
32 #include "BasicLayers.h"
33 #include "ClientLayerManager.h"
34 #include "mozilla/layers/Compositor.h"
35 #include "nsIAppWindow.h"
36 #include "nsIBaseWindow.h"
37 #include "nsXULPopupManager.h"
38 #include "nsIWidgetListener.h"
39 #include "npapi.h"
40 #include "X11UndefineNone.h"
41 #include "base/thread.h"
42 #include "prdtoa.h"
43 #include "prenv.h"
44 #include "mozilla/Attributes.h"
45 #include "mozilla/Unused.h"
46 #include "nsContentUtils.h"
47 #include "mozilla/gfx/2D.h"
48 #include "mozilla/MouseEvents.h"
49 #include "GLConsts.h"
50 #include "mozilla/GlobalKeyListener.h"
51 #include "mozilla/StaticPrefs_apz.h"
52 #include "mozilla/StaticPrefs_dom.h"
53 #include "mozilla/StaticPrefs_layout.h"
54 #include "mozilla/StaticPrefs_layers.h"
55 #include "mozilla/Unused.h"
56 #include "mozilla/IMEStateManager.h"
57 #include "mozilla/VsyncDispatcher.h"
58 #include "mozilla/layers/IAPZCTreeManager.h"
59 #include "mozilla/layers/APZEventState.h"
60 #include "mozilla/layers/APZInputBridge.h"
61 #include "mozilla/layers/APZThreadUtils.h"
62 #include "mozilla/layers/ChromeProcessController.h"
63 #include "mozilla/layers/CompositorOptions.h"
64 #include "mozilla/layers/InputAPZContext.h"
65 #include "mozilla/layers/APZCCallbackHelper.h"
66 #include "mozilla/layers/WebRenderLayerManager.h"
67 #include "mozilla/dom/ContentChild.h"
68 #include "mozilla/dom/BrowserParent.h"
69 #include "mozilla/gfx/GPUProcessManager.h"
70 #include "mozilla/gfx/gfxVars.h"
71 #include "mozilla/Move.h"
72 #include "mozilla/Sprintf.h"
73 #include "mozilla/webrender/WebRenderTypes.h"
74 #include "nsRefPtrHashtable.h"
75 #include "TouchEvents.h"
76 #include "WritingModes.h"
77 #include "InputData.h"
78 #include "FrameLayerBuilder.h"
79 #ifdef ACCESSIBILITY
80 # include "nsAccessibilityService.h"
81 #endif
82 #include "gfxConfig.h"
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;
115 using base::Thread;
117 // Async pump timer during injected long touch taps
118 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
119 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
120 int32_t nsIWidget::sPointerIdCounter = 0;
122 // Some statics from nsIWidget.h
123 /*static*/
124 uint64_t AutoObserverNotifier::sObserverId = 0;
125 /*static*/ nsDataHashtable<nsUint64HashKey, nsCOMPtr<nsIObserver>>
126 AutoObserverNotifier::sSavedObservers;
128 // The maximum amount of time to let the EnableDragDrop runnable wait in the
129 // idle queue before timing out and moving it to the regular queue. Value is in
130 // milliseconds.
131 const uint32_t kAsyncDragDropTimeout = 1000;
133 namespace mozilla::widget {
135 void IMENotification::SelectionChangeDataBase::SetWritingMode(
136 const WritingMode& aWritingMode) {
137 mWritingMode = aWritingMode.mWritingMode.bits;
140 WritingMode IMENotification::SelectionChangeDataBase::GetWritingMode() const {
141 return WritingMode(mWritingMode);
144 } // namespace mozilla::widget
146 NS_IMPL_ISUPPORTS(nsBaseWidget, nsIWidget, nsISupportsWeakReference)
148 //-------------------------------------------------------------------------
150 // nsBaseWidget constructor
152 //-------------------------------------------------------------------------
154 nsBaseWidget::nsBaseWidget()
155 : mWidgetListener(nullptr),
156 mAttachedWidgetListener(nullptr),
157 mPreviouslyAttachedWidgetListener(nullptr),
158 mLayerManager(nullptr),
159 mCompositorVsyncDispatcher(nullptr),
160 mCursor(eCursor_standard),
161 mBorderStyle(eBorderStyle_none),
162 mBounds(0, 0, 0, 0),
163 mOriginalBounds(nullptr),
164 mClipRectCount(0),
165 mSizeMode(nsSizeMode_Normal),
166 mIsTiled(false),
167 mPopupLevel(ePopupLevelTop),
168 mPopupType(ePopupTypeAny),
169 mHasRemoteContent(false),
170 mFissionWindow(false),
171 mUpdateCursor(true),
172 mUseAttachedEvents(false),
173 mIMEHasFocus(false),
174 mIMEHasQuit(false),
175 mIsFullyOccluded(false) {
176 #ifdef NOISY_WIDGET_LEAKS
177 gNumWidgets++;
178 printf("WIDGETS+ = %d\n", gNumWidgets);
179 #endif
181 #ifdef DEBUG
182 debug_RegisterPrefCallbacks();
183 #endif
185 #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
186 if (!sPluginWidgetList) {
187 sPluginWidgetList = new nsRefPtrHashtable<nsVoidPtrHashKey, nsIWidget>();
189 #endif
190 mShutdownObserver = new WidgetShutdownObserver(this);
193 NS_IMPL_ISUPPORTS(WidgetShutdownObserver, nsIObserver)
195 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget* aWidget)
196 : mWidget(aWidget), mRegistered(false) {
197 Register();
200 WidgetShutdownObserver::~WidgetShutdownObserver() {
201 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
202 // gets torn down. The observer service and nsBaseWidget have a ref on us
203 // so nsBaseWidget has to call Unregister and then clear its ref.
206 NS_IMETHODIMP
207 WidgetShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
208 const char16_t* aData) {
209 if (!mWidget) {
210 return NS_OK;
212 if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
213 RefPtr<nsBaseWidget> widget(mWidget);
214 widget->Shutdown();
215 } else if (!strcmp(aTopic, "quit-application")) {
216 RefPtr<nsBaseWidget> widget(mWidget);
217 widget->QuitIME();
219 return NS_OK;
222 void WidgetShutdownObserver::Register() {
223 if (!mRegistered) {
224 mRegistered = true;
225 nsContentUtils::RegisterShutdownObserver(this);
227 #ifndef MOZ_WIDGET_ANDROID
228 // The primary purpose of observing quit-application is
229 // to avoid leaking a widget on Windows when nothing else
230 // breaks the circular reference between the widget and
231 // TSFTextStore. However, our Android IME code crashes if
232 // doing this on Android, so let's not do this on Android.
233 // Doing this on Gtk and Mac just in case.
234 nsCOMPtr<nsIObserverService> observerService =
235 mozilla::services::GetObserverService();
236 if (observerService) {
237 observerService->AddObserver(this, "quit-application", false);
239 #endif
243 void WidgetShutdownObserver::Unregister() {
244 if (mRegistered) {
245 mWidget = nullptr;
247 #ifndef MOZ_WIDGET_ANDROID
248 nsCOMPtr<nsIObserverService> observerService =
249 mozilla::services::GetObserverService();
250 if (observerService) {
251 observerService->RemoveObserver(this, "quit-application");
253 #endif
255 nsContentUtils::UnregisterShutdownObserver(this);
256 mRegistered = false;
260 void nsBaseWidget::Shutdown() {
261 NotifyLiveResizeStopped();
262 RevokeTransactionIdAllocator();
263 DestroyCompositor();
264 FreeShutdownObserver();
265 #if defined(XP_WIN) || defined(MOZ_WIDGET_GTK)
266 if (sPluginWidgetList) {
267 delete sPluginWidgetList;
268 sPluginWidgetList = nullptr;
270 #endif
273 void nsBaseWidget::QuitIME() {
274 IMEStateManager::WidgetOnQuit(this);
275 this->mIMEHasQuit = true;
278 void nsBaseWidget::DestroyCompositor() {
279 // We release this before releasing the compositor, since it may hold the
280 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
281 // trigger a paint, creating a new compositor, and we don't want to re-use
282 // the old vsync dispatcher.
283 if (mCompositorVsyncDispatcher) {
284 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
286 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
287 mCompositorVsyncDispatcher->Shutdown();
288 mCompositorVsyncDispatcher = nullptr;
291 // The compositor shutdown sequence looks like this:
292 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
293 // 2. CompositorBridgeChild synchronously sends WillClose.
294 // 3. CompositorBridgeParent releases some resources (such as the layer
295 // manager, compositor, and widget).
296 // 4. CompositorBridgeChild::Destroy returns.
297 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
298 // compositor thread when the I/O thread closes the IPC channel.
299 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
300 // releases the reference CompositorBridgeParent holds to itself.
302 // When CompositorSession::Shutdown returns, we assume the compositor is gone
303 // or will be gone very soon.
304 if (mCompositorSession) {
305 ReleaseContentController();
306 mAPZC = nullptr;
307 SetCompositorWidgetDelegate(nullptr);
308 mCompositorBridgeChild = nullptr;
310 // XXX CompositorBridgeChild and CompositorBridgeParent might be re-created
311 // in ClientLayerManager destructor. See bug 1133426.
312 RefPtr<CompositorSession> session = mCompositorSession.forget();
313 session->Shutdown();
317 // This prevents the layer manager from starting a new transaction during
318 // shutdown.
319 void nsBaseWidget::RevokeTransactionIdAllocator() {
320 if (!mLayerManager) {
321 return;
323 mLayerManager->SetTransactionIdAllocator(nullptr);
326 void nsBaseWidget::ReleaseContentController() {
327 if (mRootContentController) {
328 mRootContentController->Destroy();
329 mRootContentController = nullptr;
333 void nsBaseWidget::DestroyLayerManager() {
334 if (mLayerManager) {
335 mLayerManager->Destroy();
336 mLayerManager = nullptr;
338 DestroyCompositor();
341 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
343 void nsBaseWidget::FreeShutdownObserver() {
344 if (mShutdownObserver) {
345 mShutdownObserver->Unregister();
347 mShutdownObserver = nullptr;
350 //-------------------------------------------------------------------------
352 // nsBaseWidget destructor
354 //-------------------------------------------------------------------------
356 nsBaseWidget::~nsBaseWidget() {
357 IMEStateManager::WidgetDestroyed(this);
359 if (mLayerManager) {
360 if (BasicLayerManager* mgr = mLayerManager->AsBasicLayerManager()) {
361 mgr->ClearRetainerWidget();
365 FreeShutdownObserver();
366 RevokeTransactionIdAllocator();
367 DestroyLayerManager();
369 #ifdef NOISY_WIDGET_LEAKS
370 gNumWidgets--;
371 printf("WIDGETS- = %d\n", gNumWidgets);
372 #endif
374 delete mOriginalBounds;
377 //-------------------------------------------------------------------------
379 // Basic create.
381 //-------------------------------------------------------------------------
382 void nsBaseWidget::BaseCreate(nsIWidget* aParent, nsWidgetInitData* aInitData) {
383 // keep a reference to the device context
384 if (nullptr != aInitData) {
385 mWindowType = aInitData->mWindowType;
386 mBorderStyle = aInitData->mBorderStyle;
387 mPopupLevel = aInitData->mPopupLevel;
388 mPopupType = aInitData->mPopupHint;
389 mHasRemoteContent = aInitData->mHasRemoteContent;
390 mFissionWindow = aInitData->mFissionWindow;
393 if (aParent) {
394 aParent->AddChild(this);
398 //-------------------------------------------------------------------------
400 // Accessor functions to get/set the client data
402 //-------------------------------------------------------------------------
404 nsIWidgetListener* nsBaseWidget::GetWidgetListener() { return mWidgetListener; }
406 void nsBaseWidget::SetWidgetListener(nsIWidgetListener* aWidgetListener) {
407 mWidgetListener = aWidgetListener;
410 already_AddRefed<nsIWidget> nsBaseWidget::CreateChild(
411 const LayoutDeviceIntRect& aRect, nsWidgetInitData* aInitData,
412 bool aForceUseIWidgetParent) {
413 nsIWidget* parent = this;
414 nsNativeWidget nativeParent = nullptr;
416 if (!aForceUseIWidgetParent) {
417 // Use only either parent or nativeParent, not both, to match
418 // existing code. Eventually Create() should be divested of its
419 // nativeWidget parameter.
420 nativeParent = parent ? parent->GetNativeData(NS_NATIVE_WIDGET) : nullptr;
421 parent = nativeParent ? nullptr : parent;
422 MOZ_ASSERT(!parent || !nativeParent, "messed up logic");
425 nsCOMPtr<nsIWidget> widget;
426 if (aInitData && aInitData->mWindowType == eWindowType_popup) {
427 widget = AllocateChildPopupWidget();
428 } else {
429 widget = nsIWidget::CreateChildWindow();
432 if (widget &&
433 NS_SUCCEEDED(widget->Create(parent, nativeParent, aRect, aInitData))) {
434 return widget.forget();
437 return nullptr;
440 // Attach a view to our widget which we'll send events to.
441 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents) {
442 NS_ASSERTION((mWindowType == eWindowType_toplevel ||
443 mWindowType == eWindowType_dialog ||
444 mWindowType == eWindowType_invisible ||
445 mWindowType == eWindowType_child),
446 "Can't attach to window of that type");
448 mUseAttachedEvents = aUseAttachedEvents;
451 nsIWidgetListener* nsBaseWidget::GetAttachedWidgetListener() {
452 return mAttachedWidgetListener;
455 nsIWidgetListener* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
456 return mPreviouslyAttachedWidgetListener;
459 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
460 nsIWidgetListener* aListener) {
461 mPreviouslyAttachedWidgetListener = aListener;
464 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener* aListener) {
465 mAttachedWidgetListener = aListener;
468 //-------------------------------------------------------------------------
470 // Close this nsBaseWidget
472 //-------------------------------------------------------------------------
473 void nsBaseWidget::Destroy() {
474 // Just in case our parent is the only ref to us
475 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
476 // disconnect from the parent
477 nsIWidget* parent = GetParent();
478 if (parent) {
479 parent->RemoveChild(this);
482 #if defined(XP_WIN)
483 // Allow our scroll capture container to be cleaned up, if we have one.
484 mScrollCaptureContainer = nullptr;
485 #endif
488 //-------------------------------------------------------------------------
490 // Get this nsBaseWidget parent
492 //-------------------------------------------------------------------------
493 nsIWidget* nsBaseWidget::GetParent(void) { return nullptr; }
495 //-------------------------------------------------------------------------
497 // Get this nsBaseWidget top level widget
499 //-------------------------------------------------------------------------
500 nsIWidget* nsBaseWidget::GetTopLevelWidget() {
501 nsIWidget *topLevelWidget = nullptr, *widget = this;
502 while (widget) {
503 topLevelWidget = widget;
504 widget = widget->GetParent();
506 return topLevelWidget;
509 //-------------------------------------------------------------------------
511 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
513 //-------------------------------------------------------------------------
514 nsIWidget* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
516 float nsBaseWidget::GetDPI() { return 96.0f; }
518 CSSToLayoutDeviceScale nsIWidget::GetDefaultScale() {
519 double devPixelsPerCSSPixel = StaticPrefs::layout_css_devPixelsPerPx();
521 if (devPixelsPerCSSPixel <= 0.0) {
522 devPixelsPerCSSPixel = GetDefaultScaleInternal();
525 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel);
528 //-------------------------------------------------------------------------
530 // Add a child to the list of children
532 //-------------------------------------------------------------------------
533 void nsBaseWidget::AddChild(nsIWidget* aChild) {
534 MOZ_ASSERT(!aChild->GetNextSibling() && !aChild->GetPrevSibling(),
535 "aChild not properly removed from its old child list");
537 if (!mFirstChild) {
538 mFirstChild = mLastChild = aChild;
539 } else {
540 // append to the list
541 MOZ_ASSERT(mLastChild);
542 MOZ_ASSERT(!mLastChild->GetNextSibling());
543 mLastChild->SetNextSibling(aChild);
544 aChild->SetPrevSibling(mLastChild);
545 mLastChild = aChild;
549 //-------------------------------------------------------------------------
551 // Remove a child from the list of children
553 //-------------------------------------------------------------------------
554 void nsBaseWidget::RemoveChild(nsIWidget* aChild) {
555 #ifdef DEBUG
556 # ifdef XP_MACOSX
557 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
558 // null and we'll just have to do without this assertion.
559 nsIWidget* parent = aChild->GetParent();
560 NS_ASSERTION(!parent || parent == this, "Not one of our kids!");
561 # else
562 MOZ_RELEASE_ASSERT(aChild->GetParent() == this, "Not one of our kids!");
563 # endif
564 #endif
566 if (mLastChild == aChild) {
567 mLastChild = mLastChild->GetPrevSibling();
569 if (mFirstChild == aChild) {
570 mFirstChild = mFirstChild->GetNextSibling();
573 // Now remove from the list. Make sure that we pass ownership of the tail
574 // of the list correctly before we have aChild let go of it.
575 nsIWidget* prev = aChild->GetPrevSibling();
576 nsIWidget* next = aChild->GetNextSibling();
577 if (prev) {
578 prev->SetNextSibling(next);
580 if (next) {
581 next->SetPrevSibling(prev);
584 aChild->SetNextSibling(nullptr);
585 aChild->SetPrevSibling(nullptr);
588 //-------------------------------------------------------------------------
590 // Sets widget's position within its parent's child list.
592 //-------------------------------------------------------------------------
593 void nsBaseWidget::SetZIndex(int32_t aZIndex) {
594 // Hold a ref to ourselves just in case, since we're going to remove
595 // from our parent.
596 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
598 mZIndex = aZIndex;
600 // reorder this child in its parent's list.
601 auto* parent = static_cast<nsBaseWidget*>(GetParent());
602 if (parent) {
603 parent->RemoveChild(this);
604 // Scope sib outside the for loop so we can check it afterward
605 nsIWidget* sib = parent->GetFirstChild();
606 for (; sib; sib = sib->GetNextSibling()) {
607 int32_t childZIndex = GetZIndex();
608 if (aZIndex < childZIndex) {
609 // Insert ourselves before sib
610 nsIWidget* prev = sib->GetPrevSibling();
611 mNextSibling = sib;
612 mPrevSibling = prev;
613 sib->SetPrevSibling(this);
614 if (prev) {
615 prev->SetNextSibling(this);
616 } else {
617 NS_ASSERTION(sib == parent->mFirstChild, "Broken child list");
618 // We've taken ownership of sib, so it's safe to have parent let
619 // go of it
620 parent->mFirstChild = this;
622 PlaceBehind(eZPlacementBelow, sib, false);
623 break;
626 // were we added to the list?
627 if (!sib) {
628 parent->AddChild(this);
633 //-------------------------------------------------------------------------
635 // Maximize, minimize or restore the window. The BaseWidget implementation
636 // merely stores the state.
638 //-------------------------------------------------------------------------
639 void nsBaseWidget::SetSizeMode(nsSizeMode aMode) {
640 MOZ_ASSERT(aMode == nsSizeMode_Normal || aMode == nsSizeMode_Minimized ||
641 aMode == nsSizeMode_Maximized || aMode == nsSizeMode_Fullscreen);
642 mSizeMode = aMode;
645 //-------------------------------------------------------------------------
647 // Get this component cursor
649 //-------------------------------------------------------------------------
651 void nsBaseWidget::SetCursor(nsCursor aCursor, imgIContainer*, uint32_t,
652 uint32_t) {
653 // We don't support the cursor image.
654 mCursor = aCursor;
657 //-------------------------------------------------------------------------
659 // Window transparency methods
661 //-------------------------------------------------------------------------
663 void nsBaseWidget::SetTransparencyMode(nsTransparencyMode aMode) {}
665 nsTransparencyMode nsBaseWidget::GetTransparencyMode() {
666 return eTransparencyOpaque;
669 bool nsBaseWidget::IsWindowClipRegionEqual(
670 const nsTArray<LayoutDeviceIntRect>& aRects) {
671 return mClipRects && mClipRectCount == aRects.Length() &&
672 memcmp(mClipRects.get(), aRects.Elements(),
673 sizeof(LayoutDeviceIntRect) * mClipRectCount) == 0;
676 void nsBaseWidget::StoreWindowClipRegion(
677 const nsTArray<LayoutDeviceIntRect>& aRects) {
678 mClipRectCount = aRects.Length();
679 mClipRects = MakeUnique<LayoutDeviceIntRect[]>(mClipRectCount);
680 if (mClipRects) {
681 memcpy(mClipRects.get(), aRects.Elements(),
682 sizeof(LayoutDeviceIntRect) * mClipRectCount);
686 void nsBaseWidget::GetWindowClipRegion(nsTArray<LayoutDeviceIntRect>* aRects) {
687 if (mClipRects) {
688 aRects->AppendElements(mClipRects.get(), mClipRectCount);
689 } else {
690 aRects->AppendElement(
691 LayoutDeviceIntRect(0, 0, mBounds.Width(), mBounds.Height()));
695 const LayoutDeviceIntRegion nsBaseWidget::RegionFromArray(
696 const nsTArray<LayoutDeviceIntRect>& aRects) {
697 LayoutDeviceIntRegion region;
698 for (uint32_t i = 0; i < aRects.Length(); ++i) {
699 region.Or(region, aRects[i]);
701 return region;
704 void nsBaseWidget::ArrayFromRegion(const LayoutDeviceIntRegion& aRegion,
705 nsTArray<LayoutDeviceIntRect>& aRects) {
706 for (auto iter = aRegion.RectIter(); !iter.Done(); iter.Next()) {
707 aRects.AppendElement(iter.Get());
711 nsresult nsBaseWidget::SetWindowClipRegion(
712 const nsTArray<LayoutDeviceIntRect>& aRects, bool aIntersectWithExisting) {
713 if (!aIntersectWithExisting) {
714 StoreWindowClipRegion(aRects);
715 } else {
716 // get current rects
717 nsTArray<LayoutDeviceIntRect> currentRects;
718 GetWindowClipRegion(&currentRects);
719 // create region from them
720 LayoutDeviceIntRegion currentRegion = RegionFromArray(currentRects);
721 // create region from new rects
722 LayoutDeviceIntRegion newRegion = RegionFromArray(aRects);
723 // intersect regions
724 LayoutDeviceIntRegion intersection;
725 intersection.And(currentRegion, newRegion);
726 // create int rect array from intersection
727 nsTArray<LayoutDeviceIntRect> rects;
728 ArrayFromRegion(intersection, rects);
729 // store
730 StoreWindowClipRegion(rects);
732 return NS_OK;
735 /* virtual */
736 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage,
737 uint16_t aDuration,
738 nsISupports* aData,
739 nsIRunnable* aCallback) {
740 MOZ_ASSERT_UNREACHABLE(
741 "Should never call PerformFullscreenTransition on nsBaseWidget");
744 //-------------------------------------------------------------------------
746 // Put the window into full-screen mode
748 //-------------------------------------------------------------------------
749 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen,
750 nsIScreen* aScreen) {
751 HideWindowChrome(aFullScreen);
753 if (aFullScreen) {
754 if (!mOriginalBounds) {
755 mOriginalBounds = new LayoutDeviceIntRect();
757 *mOriginalBounds = GetScreenBounds();
759 // Move to top-left corner of screen and size to the screen dimensions
760 nsCOMPtr<nsIScreen> screen = aScreen;
761 if (!screen) {
762 screen = GetWidgetScreen();
764 if (screen) {
765 int32_t left, top, width, height;
766 if (NS_SUCCEEDED(
767 screen->GetRectDisplayPix(&left, &top, &width, &height))) {
768 Resize(left, top, width, height, true);
771 } else if (mOriginalBounds) {
772 if (BoundsUseDesktopPixels()) {
773 DesktopRect deskRect = *mOriginalBounds / GetDesktopToDeviceScale();
774 Resize(deskRect.X(), deskRect.Y(), deskRect.Width(), deskRect.Height(),
775 true);
776 } else {
777 Resize(mOriginalBounds->X(), mOriginalBounds->Y(),
778 mOriginalBounds->Width(), mOriginalBounds->Height(), true);
783 nsresult nsBaseWidget::MakeFullScreen(bool aFullScreen, nsIScreen* aScreen) {
784 InfallibleMakeFullScreen(aFullScreen, aScreen);
785 return NS_OK;
788 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
789 nsBaseWidget* aWidget, gfxContext* aTarget, BufferMode aDoubleBuffering,
790 ScreenRotation aRotation)
791 : mWidget(aWidget) {
792 LayerManager* lm = mWidget->GetLayerManager();
793 NS_ASSERTION(
794 !lm || lm->GetBackendType() == LayersBackend::LAYERS_BASIC,
795 "AutoLayerManagerSetup instantiated for non-basic layer backend!");
796 if (lm) {
797 mLayerManager = lm->AsBasicLayerManager();
798 if (mLayerManager) {
799 mLayerManager->SetDefaultTarget(aTarget);
800 mLayerManager->SetDefaultTargetConfiguration(aDoubleBuffering, aRotation);
805 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
806 if (mLayerManager) {
807 mLayerManager->SetDefaultTarget(nullptr);
808 mLayerManager->SetDefaultTargetConfiguration(
809 mozilla::layers::BufferMode::BUFFER_NONE, ROTATION_0);
813 bool nsBaseWidget::IsSmallPopup() const {
814 return mWindowType == eWindowType_popup && mPopupType != ePopupTypePanel;
817 bool nsBaseWidget::ComputeShouldAccelerate() {
818 if (gfx::gfxVars::UseWebRender() && !AllowWebRenderForThisWindow()) {
819 // If WebRender is enabled, non-WebRender widgets use the basic compositor
820 // (at least for now), even though they would get an accelerated compositor
821 // if WebRender wasn't enabled.
822 return false;
824 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING) &&
825 WidgetTypeSupportsAcceleration();
828 bool nsBaseWidget::UseAPZ() {
829 return (gfxPlatform::AsyncPanZoomEnabled() &&
830 (WindowType() == eWindowType_toplevel ||
831 WindowType() == eWindowType_child ||
832 (WindowType() == eWindowType_popup && HasRemoteContent() &&
833 StaticPrefs::apz_popups_enabled())));
836 bool nsBaseWidget::AllowWebRenderForThisWindow() {
837 return WindowType() == eWindowType_toplevel ||
838 WindowType() == eWindowType_child ||
839 WindowType() == eWindowType_dialog ||
840 (WindowType() == eWindowType_popup && HasRemoteContent());
843 void nsBaseWidget::CreateCompositor() {
844 LayoutDeviceIntRect rect = GetBounds();
845 CreateCompositor(rect.Width(), rect.Height());
848 already_AddRefed<GeckoContentController>
849 nsBaseWidget::CreateRootContentController() {
850 RefPtr<GeckoContentController> controller =
851 new ChromeProcessController(this, mAPZEventState, mAPZC);
852 return controller.forget();
855 void nsBaseWidget::ConfigureAPZCTreeManager() {
856 MOZ_ASSERT(NS_IsMainThread());
857 MOZ_ASSERT(mAPZC);
859 ConfigureAPZControllerThread();
861 float dpi = GetDPI();
862 // On Android the main thread is not the controller thread
863 APZThreadUtils::RunOnControllerThread(
864 NewRunnableMethod<float>("layers::IAPZCTreeManager::SetDPI", mAPZC,
865 &IAPZCTreeManager::SetDPI, dpi));
867 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
868 KeyboardMap map = RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
869 // On Android the main thread is not the controller thread
870 APZThreadUtils::RunOnControllerThread(NewRunnableMethod<KeyboardMap>(
871 "layers::IAPZCTreeManager::SetKeyboardMap", mAPZC,
872 &IAPZCTreeManager::SetKeyboardMap, map));
875 RefPtr<IAPZCTreeManager> treeManager = mAPZC; // for capture by the lambdas
877 ContentReceivedInputBlockCallback callback(
878 [treeManager](uint64_t aInputBlockId, bool aPreventDefault) {
879 MOZ_ASSERT(NS_IsMainThread());
880 APZThreadUtils::RunOnControllerThread(NewRunnableMethod<uint64_t, bool>(
881 "layers::IAPZCTreeManager::ContentReceivedInputBlock", treeManager,
882 &IAPZCTreeManager::ContentReceivedInputBlock, aInputBlockId,
883 aPreventDefault));
885 mAPZEventState = new APZEventState(this, std::move(callback));
887 mSetAllowedTouchBehaviorCallback =
888 [treeManager](uint64_t aInputBlockId,
889 const nsTArray<TouchBehaviorFlags>& aFlags) {
890 MOZ_ASSERT(NS_IsMainThread());
891 APZThreadUtils::RunOnControllerThread(
892 NewRunnableMethod<
893 uint64_t, StoreCopyPassByLRef<nsTArray<TouchBehaviorFlags>>>(
894 "layers::IAPZCTreeManager::SetAllowedTouchBehavior",
895 treeManager, &IAPZCTreeManager::SetAllowedTouchBehavior,
896 aInputBlockId, aFlags));
899 mRootContentController = CreateRootContentController();
900 if (mRootContentController) {
901 mCompositorSession->SetContentController(mRootContentController);
904 // When APZ is enabled, we can actually enable raw touch events because we
905 // have code that can deal with them properly. If APZ is not enabled, this
906 // function doesn't get called.
907 if (StaticPrefs::dom_w3c_touch_events_enabled() ||
908 StaticPrefs::dom_w3c_pointer_events_enabled()) {
909 RegisterTouchWindow();
913 void nsBaseWidget::ConfigureAPZControllerThread() {
914 // By default the controller thread is the main thread.
915 APZThreadUtils::SetControllerThread(MessageLoop::current());
918 void nsBaseWidget::SetConfirmedTargetAPZC(
919 uint64_t aInputBlockId,
920 const nsTArray<SLGuidAndRenderRoot>& aTargets) const {
921 APZThreadUtils::RunOnControllerThread(
922 NewRunnableMethod<uint64_t,
923 StoreCopyPassByRRef<nsTArray<SLGuidAndRenderRoot>>>(
924 "layers::IAPZCTreeManager::SetTargetAPZC", mAPZC,
925 &IAPZCTreeManager::SetTargetAPZC, aInputBlockId, aTargets));
928 void nsBaseWidget::UpdateZoomConstraints(
929 const uint32_t& aPresShellId, const ScrollableLayerGuid::ViewID& aViewId,
930 const Maybe<ZoomConstraints>& aConstraints) {
931 if (!mCompositorSession || !mAPZC) {
932 if (mInitialZoomConstraints) {
933 MOZ_ASSERT(mInitialZoomConstraints->mPresShellID == aPresShellId);
934 MOZ_ASSERT(mInitialZoomConstraints->mViewID == aViewId);
935 if (!aConstraints) {
936 mInitialZoomConstraints.reset();
940 if (aConstraints) {
941 // We have some constraints, but the compositor and APZC aren't created
942 // yet. Save these so we can use them later.
943 mInitialZoomConstraints = Some(
944 InitialZoomConstraints(aPresShellId, aViewId, aConstraints.ref()));
946 return;
948 LayersId layersId = mCompositorSession->RootLayerTreeId();
949 mAPZC->UpdateZoomConstraints(
950 SLGuidAndRenderRoot(layersId, aPresShellId, aViewId,
951 wr::RenderRoot::Default),
952 aConstraints);
955 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC; }
957 nsEventStatus nsBaseWidget::ProcessUntransformedAPZEvent(
958 WidgetInputEvent* aEvent, const APZEventResult& aApzResult) {
959 MOZ_ASSERT(NS_IsMainThread());
960 ScrollableLayerGuid targetGuid = aApzResult.mTargetGuid;
961 uint64_t inputBlockId = aApzResult.mInputBlockId;
962 InputAPZContext context(aApzResult.mTargetGuid, inputBlockId,
963 aApzResult.mStatus);
965 // If this is an event that the APZ has targeted to an APZC in the root
966 // process, apply that APZC's callback-transform before dispatching the
967 // event. If the event is instead targeted to an APZC in the child process,
968 // the transform will be applied in the child process before dispatching
969 // the event there (see e.g. BrowserChild::RecvRealTouchEvent()).
970 if (aApzResult.mTargetGuid.mLayersId ==
971 mCompositorSession->RootLayerTreeId()) {
972 APZCCallbackHelper::ApplyCallbackTransform(*aEvent, targetGuid,
973 GetDefaultScale());
976 // Make a copy of the original event for the APZCCallbackHelper helpers that
977 // we call later, because the event passed to DispatchEvent can get mutated in
978 // ways that we don't want (i.e. touch points can get stripped out).
979 nsEventStatus status;
980 UniquePtr<WidgetEvent> original(aEvent->Duplicate());
981 DispatchEvent(aEvent, status);
983 if (mAPZC && !InputAPZContext::WasRoutedToChildProcess() && inputBlockId) {
984 // EventStateManager did not route the event into the child process.
985 // It's safe to communicate to APZ that the event has been processed.
986 // Note that here aGuid.mLayersId might be different from
987 // mCompositorSession->RootLayerTreeId() because the event might have gotten
988 // hit-tested by APZ to be targeted at a child process, but a parent process
989 // event listener called preventDefault on it. In that case aGuid.mLayersId
990 // would still be the layers id for the child process, but the event would
991 // not have actually gotten routed to the child process. The main-thread
992 // hit-test result therefore needs to use the parent process layers id.
993 LayersId rootLayersId = mCompositorSession->RootLayerTreeId();
995 UniquePtr<DisplayportSetListener> postLayerization;
996 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
997 if (touchEvent->mMessage == eTouchStart) {
998 if (StaticPrefs::layout_css_touch_action_enabled()) {
999 APZCCallbackHelper::SendSetAllowedTouchBehaviorNotification(
1000 this, GetDocument(), *(original->AsTouchEvent()), inputBlockId,
1001 mSetAllowedTouchBehaviorCallback);
1003 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1004 this, GetDocument(), *(original->AsTouchEvent()), rootLayersId,
1005 inputBlockId);
1007 mAPZEventState->ProcessTouchEvent(*touchEvent, targetGuid, inputBlockId,
1008 aApzResult.mStatus, status);
1009 } else if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1010 MOZ_ASSERT(wheelEvent->mFlags.mHandledByAPZ);
1011 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1012 this, GetDocument(), *(original->AsWheelEvent()), rootLayersId,
1013 inputBlockId);
1014 if (wheelEvent->mCanTriggerSwipe) {
1015 ReportSwipeStarted(inputBlockId, wheelEvent->TriggersSwipe());
1017 mAPZEventState->ProcessWheelEvent(*wheelEvent, inputBlockId);
1018 } else if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1019 MOZ_ASSERT(mouseEvent->mFlags.mHandledByAPZ);
1020 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1021 this, GetDocument(), *(original->AsMouseEvent()), rootLayersId,
1022 inputBlockId);
1023 mAPZEventState->ProcessMouseEvent(*mouseEvent, inputBlockId);
1025 if (postLayerization && postLayerization->Register()) {
1026 Unused << postLayerization.release();
1030 return status;
1033 class DispatchWheelEventOnMainThread : public Runnable {
1034 public:
1035 DispatchWheelEventOnMainThread(const ScrollWheelInput& aWheelInput,
1036 nsBaseWidget* aWidget,
1037 const APZEventResult& aAPZResult)
1038 : mozilla::Runnable("DispatchWheelEventOnMainThread"),
1039 mWheelInput(aWheelInput),
1040 mWidget(aWidget),
1041 mAPZResult(aAPZResult) {}
1043 NS_IMETHOD Run() override {
1044 WidgetWheelEvent wheelEvent = mWheelInput.ToWidgetWheelEvent(mWidget);
1045 mWidget->ProcessUntransformedAPZEvent(&wheelEvent, mAPZResult);
1046 return NS_OK;
1049 private:
1050 ScrollWheelInput mWheelInput;
1051 nsBaseWidget* mWidget;
1052 APZEventResult mAPZResult;
1055 class DispatchWheelInputOnControllerThread : public Runnable {
1056 public:
1057 DispatchWheelInputOnControllerThread(const WidgetWheelEvent& aWheelEvent,
1058 IAPZCTreeManager* aAPZC,
1059 nsBaseWidget* aWidget)
1060 : mozilla::Runnable("DispatchWheelInputOnControllerThread"),
1061 mMainMessageLoop(MessageLoop::current()),
1062 mWheelInput(aWheelEvent),
1063 mAPZC(aAPZC),
1064 mWidget(aWidget) {}
1066 NS_IMETHOD Run() override {
1067 APZEventResult result =
1068 mAPZC->InputBridge()->ReceiveInputEvent(mWheelInput);
1069 if (result.mStatus == nsEventStatus_eConsumeNoDefault) {
1070 return NS_OK;
1072 RefPtr<Runnable> r =
1073 new DispatchWheelEventOnMainThread(mWheelInput, mWidget, result);
1074 mMainMessageLoop->PostTask(r.forget());
1075 return NS_OK;
1078 private:
1079 MessageLoop* mMainMessageLoop;
1080 ScrollWheelInput mWheelInput;
1081 RefPtr<IAPZCTreeManager> mAPZC;
1082 nsBaseWidget* mWidget;
1085 void nsBaseWidget::DispatchTouchInput(MultiTouchInput& aInput) {
1086 MOZ_ASSERT(NS_IsMainThread());
1087 if (mAPZC) {
1088 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1090 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1091 if (result.mStatus == nsEventStatus_eConsumeNoDefault) {
1092 return;
1095 WidgetTouchEvent event = aInput.ToWidgetTouchEvent(this);
1096 ProcessUntransformedAPZEvent(&event, result);
1097 } else {
1098 WidgetTouchEvent event = aInput.ToWidgetTouchEvent(this);
1100 nsEventStatus status;
1101 DispatchEvent(&event, status);
1105 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput& aInput) {
1106 MOZ_ASSERT(NS_IsMainThread());
1107 if (mAPZC) {
1108 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1110 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1111 if (result.mStatus == nsEventStatus_eConsumeNoDefault) {
1112 return;
1115 WidgetWheelEvent event = aInput.ToWidgetWheelEvent(this);
1116 ProcessUntransformedAPZEvent(&event, result);
1117 } else {
1118 WidgetWheelEvent event = aInput.ToWidgetWheelEvent(this);
1120 nsEventStatus status;
1121 DispatchEvent(&event, status);
1125 nsEventStatus nsBaseWidget::DispatchInputEvent(WidgetInputEvent* aEvent) {
1126 MOZ_ASSERT(NS_IsMainThread());
1127 if (mAPZC) {
1128 if (APZThreadUtils::IsControllerThread()) {
1129 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1130 if (result.mStatus == nsEventStatus_eConsumeNoDefault) {
1131 return result.mStatus;
1133 return ProcessUntransformedAPZEvent(aEvent, result);
1135 WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent();
1136 if (wheelEvent) {
1137 RefPtr<Runnable> r =
1138 new DispatchWheelInputOnControllerThread(*wheelEvent, mAPZC, this);
1139 APZThreadUtils::RunOnControllerThread(r.forget());
1140 return nsEventStatus_eConsumeDoDefault;
1142 // Allow dispatching keyboard events on Gecko thread.
1143 MOZ_ASSERT(aEvent->AsKeyboardEvent());
1146 nsEventStatus status;
1147 DispatchEvent(aEvent, status);
1148 return status;
1151 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent* aEvent) {
1152 MOZ_ASSERT(NS_IsMainThread());
1153 if (mAPZC) {
1154 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1155 mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1159 Document* nsBaseWidget::GetDocument() const {
1160 if (mWidgetListener) {
1161 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1162 return presShell->GetDocument();
1165 return nullptr;
1168 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1169 // Parent directly listens to the vsync source whereas
1170 // child process communicate via IPC
1171 // Should be called AFTER gfxPlatform is initialized
1172 if (XRE_IsParentProcess()) {
1173 if (!mCompositorVsyncDispatcherLock) {
1174 mCompositorVsyncDispatcherLock =
1175 MakeUnique<Mutex>("mCompositorVsyncDispatcherLock");
1177 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1178 if (!mCompositorVsyncDispatcher) {
1179 mCompositorVsyncDispatcher = new CompositorVsyncDispatcher();
1184 already_AddRefed<CompositorVsyncDispatcher>
1185 nsBaseWidget::GetCompositorVsyncDispatcher() {
1186 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
1188 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1189 RefPtr<CompositorVsyncDispatcher> dispatcher = mCompositorVsyncDispatcher;
1190 return dispatcher.forget();
1193 already_AddRefed<LayerManager> nsBaseWidget::CreateCompositorSession(
1194 int aWidth, int aHeight, CompositorOptions* aOptionsOut) {
1195 MOZ_ASSERT(aOptionsOut);
1197 do {
1198 CreateCompositorVsyncDispatcher();
1200 gfx::GPUProcessManager* gpu = gfx::GPUProcessManager::Get();
1201 // Make sure GPU process is ready for use.
1202 // If it failed to connect to GPU process, GPU process usage is disabled in
1203 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1204 gpu->EnsureGPUReady();
1206 // If widget type does not supports acceleration, we use ClientLayerManager
1207 // even when gfxVars::UseWebRender() is true. WebRender could coexist only
1208 // with BasicCompositor.
1209 bool enableWR = gfx::gfxVars::UseWebRender() &&
1210 WidgetTypeSupportsAcceleration() &&
1211 AllowWebRenderForThisWindow();
1212 bool enableAPZ = UseAPZ();
1213 CompositorOptions options(enableAPZ, enableWR);
1215 // Bug 1588484 - Advanced Layers is currently disabled for fission windows,
1216 // since it doesn't properly support nested RefLayers.
1217 bool enableAL =
1218 gfx::gfxConfig::IsEnabled(gfx::Feature::ADVANCED_LAYERS) &&
1219 (!mFissionWindow || StaticPrefs::layers_advanced_fission_enabled());
1220 options.SetUseAdvancedLayers(enableAL);
1222 #ifdef MOZ_WIDGET_ANDROID
1223 if (!GetNativeData(NS_JAVA_SURFACE)) {
1224 options.SetInitiallyPaused(true);
1226 #else
1227 options.SetInitiallyPaused(CompositorInitiallyPaused());
1228 #endif
1230 RefPtr<LayerManager> lm;
1231 if (options.UseWebRender()) {
1232 lm = new WebRenderLayerManager(this);
1233 } else {
1234 lm = new ClientLayerManager(this);
1237 bool retry = false;
1238 mCompositorSession = gpu->CreateTopLevelCompositor(
1239 this, lm, GetDefaultScale(), options, UseExternalCompositingSurface(),
1240 gfx::IntSize(aWidth, aHeight), &retry);
1242 if (lm->AsWebRenderLayerManager() && mCompositorSession) {
1243 TextureFactoryIdentifier textureFactoryIdentifier;
1244 lm->AsWebRenderLayerManager()->Initialize(
1245 mCompositorSession->GetCompositorBridgeChild(),
1246 wr::AsPipelineId(mCompositorSession->RootLayerTreeId()),
1247 &textureFactoryIdentifier);
1248 if (textureFactoryIdentifier.mParentBackend != LayersBackend::LAYERS_WR) {
1249 retry = true;
1250 DestroyCompositor();
1251 gfx::GPUProcessManager::Get()->DisableWebRender(
1252 wr::WebRenderError::INITIALIZE);
1254 } else if (lm->AsClientLayerManager() && mCompositorSession) {
1255 bool shouldAccelerate = ComputeShouldAccelerate();
1256 TextureFactoryIdentifier textureFactoryIdentifier;
1257 lm->AsClientLayerManager()->Initialize(
1258 mCompositorSession->GetCompositorBridgeChild(), shouldAccelerate,
1259 &textureFactoryIdentifier);
1260 if (textureFactoryIdentifier.mParentBackend ==
1261 LayersBackend::LAYERS_NONE) {
1262 DestroyCompositor();
1263 lm = nullptr;
1267 // We need to retry in a loop because the act of failing to create the
1268 // compositor can change our state (e.g. disable WebRender).
1269 if (mCompositorSession || !retry) {
1270 *aOptionsOut = options;
1271 return lm.forget();
1273 } while (true);
1276 void nsBaseWidget::CreateCompositor(int aWidth, int aHeight) {
1277 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1278 gfxPlatform::GetPlatform();
1280 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1281 "This function assumes OMTC");
1283 MOZ_ASSERT(!mCompositorSession && !mCompositorBridgeChild,
1284 "Should have properly cleaned up the previous PCompositor pair "
1285 "beforehand");
1287 if (mCompositorBridgeChild) {
1288 mCompositorBridgeChild->Destroy();
1291 // Recreating this is tricky, as we may still have an old and we need
1292 // to make sure it's properly destroyed by calling DestroyCompositor!
1294 // If we've already received a shutdown notification, don't try
1295 // create a new compositor.
1296 if (!mShutdownObserver) {
1297 return;
1300 CompositorOptions options;
1301 RefPtr<LayerManager> lm = CreateCompositorSession(aWidth, aHeight, &options);
1302 if (!lm) {
1303 return;
1306 MOZ_ASSERT(mCompositorSession);
1307 mCompositorBridgeChild = mCompositorSession->GetCompositorBridgeChild();
1308 SetCompositorWidgetDelegate(
1309 mCompositorSession->GetCompositorWidgetDelegate());
1311 if (options.UseAPZ()) {
1312 mAPZC = mCompositorSession->GetAPZCTreeManager();
1313 ConfigureAPZCTreeManager();
1314 } else {
1315 mAPZC = nullptr;
1318 if (mInitialZoomConstraints) {
1319 UpdateZoomConstraints(mInitialZoomConstraints->mPresShellID,
1320 mInitialZoomConstraints->mViewID,
1321 Some(mInitialZoomConstraints->mConstraints));
1322 mInitialZoomConstraints.reset();
1325 if (lm->AsWebRenderLayerManager()) {
1326 TextureFactoryIdentifier textureFactoryIdentifier =
1327 lm->GetTextureFactoryIdentifier();
1328 MOZ_ASSERT(textureFactoryIdentifier.mParentBackend ==
1329 LayersBackend::LAYERS_WR);
1330 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1331 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1332 } else if (lm->AsClientLayerManager()) {
1333 TextureFactoryIdentifier textureFactoryIdentifier =
1334 lm->GetTextureFactoryIdentifier();
1335 // Some popup or transparent widgets may use a different backend than the
1336 // compositors used with ImageBridge and VR (and more generally web
1337 // content).
1338 if (WidgetTypeSupportsAcceleration()) {
1339 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1340 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1344 WindowUsesOMTC();
1346 mLayerManager = lm.forget();
1348 // Only track compositors for top-level windows, since other window types
1349 // may use the basic compositor. Except on the OS X - see bug 1306383
1350 #if defined(XP_MACOSX)
1351 bool getCompositorFromThisWindow = true;
1352 #else
1353 bool getCompositorFromThisWindow = (mWindowType == eWindowType_toplevel);
1354 #endif
1356 if (getCompositorFromThisWindow) {
1357 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1358 mLayerManager->GetCompositorBackendType());
1362 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession* aSession) {
1363 MOZ_ASSERT(aSession == mCompositorSession);
1364 DestroyLayerManager();
1367 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1368 return gfxPlatform::UsesOffMainThreadCompositing();
1371 LayerManager* nsBaseWidget::GetLayerManager(
1372 PLayerTransactionChild* aShadowManager, LayersBackend aBackendHint,
1373 LayerManagerPersistence aPersistence) {
1374 if (!mLayerManager) {
1375 if (!mShutdownObserver) {
1376 // We are shutting down, do not try to re-create a LayerManager
1377 return nullptr;
1379 // Try to use an async compositor first, if possible
1380 if (ShouldUseOffMainThreadCompositing()) {
1381 // e10s uses the parameter to pass in the shadow manager from the
1382 // BrowserChild so we don't expect to see it there since this doesn't
1383 // support e10s.
1384 NS_ASSERTION(aShadowManager == nullptr,
1385 "Async Compositor not supported with e10s");
1386 CreateCompositor();
1389 if (!mLayerManager) {
1390 mLayerManager = CreateBasicLayerManager();
1393 return mLayerManager;
1396 LayerManager* nsBaseWidget::CreateBasicLayerManager() {
1397 return new BasicLayerManager(this);
1400 CompositorBridgeChild* nsBaseWidget::GetRemoteRenderer() {
1401 return mCompositorBridgeChild;
1404 already_AddRefed<gfx::DrawTarget> nsBaseWidget::StartRemoteDrawing() {
1405 if (recordreplay::IsRecordingOrReplaying()) {
1406 return recordreplay::child::DrawTargetForRemoteDrawing(mBounds.Size());
1408 return nullptr;
1411 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA; }
1413 //-------------------------------------------------------------------------
1415 // Destroy the window
1417 //-------------------------------------------------------------------------
1418 void nsBaseWidget::OnDestroy() {
1419 if (mTextEventDispatcher) {
1420 mTextEventDispatcher->OnDestroyWidget();
1421 // Don't release it until this widget actually released because after this
1422 // is called, TextEventDispatcher() may create it again.
1425 // If this widget is being destroyed, let the APZ code know to drop references
1426 // to this widget. Callers of this function all should be holding a deathgrip
1427 // on this widget already.
1428 ReleaseContentController();
1431 void nsBaseWidget::MoveClient(double aX, double aY) {
1432 LayoutDeviceIntPoint clientOffset(GetClientOffset());
1434 // GetClientOffset returns device pixels; scale back to desktop pixels
1435 // if that's what this widget uses for the Move/Resize APIs
1436 if (BoundsUseDesktopPixels()) {
1437 DesktopPoint desktopOffset = clientOffset / GetDesktopToDeviceScale();
1438 Move(aX - desktopOffset.x, aY - desktopOffset.y);
1439 } else {
1440 Move(aX - clientOffset.x, aY - clientOffset.y);
1444 void nsBaseWidget::ResizeClient(double aWidth, double aHeight, bool aRepaint) {
1445 NS_ASSERTION((aWidth >= 0), "Negative width passed to ResizeClient");
1446 NS_ASSERTION((aHeight >= 0), "Negative height passed to ResizeClient");
1448 LayoutDeviceIntRect clientBounds = GetClientBounds();
1450 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1451 // if that's what this widget uses for the Move/Resize APIs
1452 if (BoundsUseDesktopPixels()) {
1453 DesktopSize desktopDelta =
1454 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1455 clientBounds.Size()) /
1456 GetDesktopToDeviceScale();
1457 Resize(aWidth + desktopDelta.width, aHeight + desktopDelta.height,
1458 aRepaint);
1459 } else {
1460 Resize(mBounds.Width() + (aWidth - clientBounds.Width()),
1461 mBounds.Height() + (aHeight - clientBounds.Height()), aRepaint);
1465 void nsBaseWidget::ResizeClient(double aX, double aY, double aWidth,
1466 double aHeight, bool aRepaint) {
1467 NS_ASSERTION((aWidth >= 0), "Negative width passed to ResizeClient");
1468 NS_ASSERTION((aHeight >= 0), "Negative height passed to ResizeClient");
1470 LayoutDeviceIntRect clientBounds = GetClientBounds();
1471 LayoutDeviceIntPoint clientOffset = GetClientOffset();
1473 if (BoundsUseDesktopPixels()) {
1474 DesktopToLayoutDeviceScale scale = GetDesktopToDeviceScale();
1475 DesktopPoint desktopOffset = clientOffset / scale;
1476 DesktopSize desktopDelta =
1477 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1478 clientBounds.Size()) /
1479 scale;
1480 Resize(aX - desktopOffset.x, aY - desktopOffset.y,
1481 aWidth + desktopDelta.width, aHeight + desktopDelta.height,
1482 aRepaint);
1483 } else {
1484 Resize(aX - clientOffset.x, aY - clientOffset.y,
1485 aWidth + mBounds.Width() - clientBounds.Width(),
1486 aHeight + mBounds.Height() - clientBounds.Height(), aRepaint);
1490 //-------------------------------------------------------------------------
1492 // Bounds
1494 //-------------------------------------------------------------------------
1497 * If the implementation of nsWindow supports borders this method MUST be
1498 * overridden
1501 LayoutDeviceIntRect nsBaseWidget::GetClientBounds() { return GetBounds(); }
1504 * If the implementation of nsWindow supports borders this method MUST be
1505 * overridden
1508 LayoutDeviceIntRect nsBaseWidget::GetBounds() { return mBounds; }
1511 * If the implementation of nsWindow uses a local coordinate system within the
1512 *window, this method must be overridden
1515 LayoutDeviceIntRect nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1517 nsresult nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect& aRect) {
1518 if (SizeMode() != nsSizeMode_Normal) {
1519 return NS_ERROR_FAILURE;
1521 aRect = GetScreenBounds();
1522 return NS_OK;
1525 LayoutDeviceIntPoint nsBaseWidget::GetClientOffset() {
1526 return LayoutDeviceIntPoint(0, 0);
1529 nsresult nsBaseWidget::SetNonClientMargins(LayoutDeviceIntMargin& margins) {
1530 return NS_ERROR_NOT_IMPLEMENTED;
1533 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1535 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1537 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect* aResizerRect) {
1538 return false;
1542 * Modifies aFile to point at an icon file with the given name and suffix. The
1543 * suffix may correspond to a file extension with leading '.' if appropriate.
1544 * Returns true if the icon file exists and can be read.
1546 static bool ResolveIconNameHelper(nsIFile* aFile, const nsAString& aIconName,
1547 const nsAString& aIconSuffix) {
1548 aFile->Append(NS_LITERAL_STRING("icons"));
1549 aFile->Append(NS_LITERAL_STRING("default"));
1550 aFile->Append(aIconName + aIconSuffix);
1552 bool readable;
1553 return NS_SUCCEEDED(aFile->IsReadable(&readable)) && readable;
1557 * Resolve the given icon name into a local file object. This method is
1558 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1559 * platform specific icon file suffix (e.g., ".ico" under Win32).
1561 * If no file is found matching the given parameters, then null is returned.
1563 void nsBaseWidget::ResolveIconName(const nsAString& aIconName,
1564 const nsAString& aIconSuffix,
1565 nsIFile** aResult) {
1566 *aResult = nullptr;
1568 nsCOMPtr<nsIProperties> dirSvc =
1569 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
1570 if (!dirSvc) return;
1572 // first check auxilary chrome directories
1574 nsCOMPtr<nsISimpleEnumerator> dirs;
1575 dirSvc->Get(NS_APP_CHROME_DIR_LIST, NS_GET_IID(nsISimpleEnumerator),
1576 getter_AddRefs(dirs));
1577 if (dirs) {
1578 bool hasMore;
1579 while (NS_SUCCEEDED(dirs->HasMoreElements(&hasMore)) && hasMore) {
1580 nsCOMPtr<nsISupports> element;
1581 dirs->GetNext(getter_AddRefs(element));
1582 if (!element) continue;
1583 nsCOMPtr<nsIFile> file = do_QueryInterface(element);
1584 if (!file) continue;
1585 if (ResolveIconNameHelper(file, aIconName, aIconSuffix)) {
1586 NS_ADDREF(*aResult = file);
1587 return;
1592 // then check the main app chrome directory
1594 nsCOMPtr<nsIFile> file;
1595 dirSvc->Get(NS_APP_CHROME_DIR, NS_GET_IID(nsIFile), getter_AddRefs(file));
1596 if (file && ResolveIconNameHelper(file, aIconName, aIconSuffix))
1597 NS_ADDREF(*aResult = file);
1600 void nsBaseWidget::SetSizeConstraints(const SizeConstraints& aConstraints) {
1601 mSizeConstraints = aConstraints;
1603 // Popups are constrained during layout, and we don't want to synchronously
1604 // paint from reflow, so bail out... This is not great, but it's no worse than
1605 // what we used to do.
1607 // The right fix here is probably making constraint changes go through the
1608 // view manager and such.
1609 if (mWindowType == eWindowType_popup) {
1610 return;
1613 // If the current size doesn't meet the new constraints, trigger a
1614 // resize to apply it. Note that, we don't want to invoke Resize if
1615 // the new constraints don't affect the current size, because Resize
1616 // implementation on some platforms may touch other geometry even if
1617 // the size don't need to change.
1618 LayoutDeviceIntSize curSize = mBounds.Size();
1619 LayoutDeviceIntSize clampedSize =
1620 Max(aConstraints.mMinSize, Min(aConstraints.mMaxSize, curSize));
1621 if (clampedSize != curSize) {
1622 gfx::Size size;
1623 if (BoundsUseDesktopPixels()) {
1624 DesktopSize desktopSize = clampedSize / GetDesktopToDeviceScale();
1625 size = desktopSize.ToUnknownSize();
1626 } else {
1627 size = gfx::Size(clampedSize.ToUnknownSize());
1629 Resize(size.width, size.height, true);
1633 const widget::SizeConstraints nsBaseWidget::GetSizeConstraints() {
1634 return mSizeConstraints;
1637 // static
1638 nsIRollupListener* nsBaseWidget::GetActiveRollupListener() {
1639 // If set, then this is likely an <html:select> dropdown.
1640 if (gRollupListener) return gRollupListener;
1642 return nsXULPopupManager::GetInstance();
1645 void nsBaseWidget::NotifyWindowDestroyed() {
1646 if (!mWidgetListener) return;
1648 nsCOMPtr<nsIAppWindow> window = mWidgetListener->GetAppWindow();
1649 nsCOMPtr<nsIBaseWindow> appWindow(do_QueryInterface(window));
1650 if (appWindow) {
1651 appWindow->Destroy();
1655 void nsBaseWidget::NotifyWindowMoved(int32_t aX, int32_t aY) {
1656 if (mWidgetListener) {
1657 mWidgetListener->WindowMoved(this, aX, aY);
1660 if (mIMEHasFocus && IMENotificationRequestsRef().WantPositionChanged()) {
1661 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE));
1665 void nsBaseWidget::NotifySizeMoveDone() {
1666 if (!mWidgetListener) {
1667 return;
1669 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1670 presShell->WindowSizeMoveDone();
1674 void nsBaseWidget::NotifySysColorChanged() {
1675 if (!mWidgetListener) {
1676 return;
1678 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1679 presShell->SysColorChanged();
1683 void nsBaseWidget::NotifyThemeChanged() {
1684 if (!mWidgetListener) {
1685 return;
1687 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1688 presShell->ThemeChanged();
1692 void nsBaseWidget::NotifyUIStateChanged(UIStateChangeType aShowFocusRings) {
1693 if (Document* doc = GetDocument()) {
1694 if (nsPIDOMWindowOuter* win = doc->GetWindow()) {
1695 win->SetKeyboardIndicators(aShowFocusRings);
1700 nsresult nsBaseWidget::NotifyIME(const IMENotification& aIMENotification) {
1701 if (mIMEHasQuit) {
1702 return NS_OK;
1704 switch (aIMENotification.mMessage) {
1705 case REQUEST_TO_COMMIT_COMPOSITION:
1706 case REQUEST_TO_CANCEL_COMPOSITION:
1707 // We should send request to IME only when there is a TextEventDispatcher
1708 // instance (this means that this widget has dispatched at least one
1709 // composition event or keyboard event) and the it has composition.
1710 // Otherwise, there is nothing to do.
1711 // Note that if current input transaction is for native input events,
1712 // TextEventDispatcher::NotifyIME() will call
1713 // TextEventDispatcherListener::NotifyIME().
1714 if (mTextEventDispatcher && mTextEventDispatcher->IsComposing()) {
1715 return mTextEventDispatcher->NotifyIME(aIMENotification);
1717 return NS_OK;
1718 default: {
1719 if (aIMENotification.mMessage == NOTIFY_IME_OF_FOCUS) {
1720 mIMEHasFocus = true;
1722 EnsureTextEventDispatcher();
1723 // TextEventDispatcher::NotifyIME() will always call
1724 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1725 // input transaction is for synthesized events for automated tests,
1726 // notifications will be sent to native IME.
1727 nsresult rv = mTextEventDispatcher->NotifyIME(aIMENotification);
1728 if (aIMENotification.mMessage == NOTIFY_IME_OF_BLUR) {
1729 mIMEHasFocus = false;
1731 return rv;
1736 void nsBaseWidget::EnsureTextEventDispatcher() {
1737 if (mTextEventDispatcher) {
1738 return;
1740 mTextEventDispatcher = new TextEventDispatcher(this);
1743 nsIWidget::NativeIMEContext nsBaseWidget::GetNativeIMEContext() {
1744 if (mTextEventDispatcher && mTextEventDispatcher->GetPseudoIMEContext()) {
1745 // If we already have a TextEventDispatcher and it's working with
1746 // a TextInputProcessor, we need to return pseudo IME context since
1747 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1748 // on the pseudo IME context in such case.
1749 NativeIMEContext pseudoIMEContext;
1750 pseudoIMEContext.InitWithRawNativeIMEContext(
1751 mTextEventDispatcher->GetPseudoIMEContext());
1752 return pseudoIMEContext;
1754 return NativeIMEContext(this);
1757 nsIWidget::TextEventDispatcher* nsBaseWidget::GetTextEventDispatcher() {
1758 EnsureTextEventDispatcher();
1759 return mTextEventDispatcher;
1762 void* nsBaseWidget::GetPseudoIMEContext() {
1763 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
1764 if (!dispatcher) {
1765 return nullptr;
1767 return dispatcher->GetPseudoIMEContext();
1770 TextEventDispatcherListener*
1771 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1772 // TODO: If all platforms supported use of TextEventDispatcher for handling
1773 // native IME and keyboard events, this method should be removed since
1774 // in such case, this is overridden by all the subclasses.
1775 return nullptr;
1778 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId,
1779 const ScrollableLayerGuid::ViewID& aViewId,
1780 const CSSRect& aRect, const uint32_t& aFlags) {
1781 if (!mCompositorSession || !mAPZC) {
1782 return;
1784 LayersId layerId = mCompositorSession->RootLayerTreeId();
1785 APZThreadUtils::RunOnControllerThread(
1786 NewRunnableMethod<SLGuidAndRenderRoot, CSSRect, uint32_t>(
1787 "layers::IAPZCTreeManager::ZoomToRect", mAPZC,
1788 &IAPZCTreeManager::ZoomToRect,
1789 SLGuidAndRenderRoot(layerId, aPresShellId, aViewId,
1790 wr::RenderRoot::Default),
1791 aRect, aFlags));
1794 #ifdef ACCESSIBILITY
1796 a11y::Accessible* nsBaseWidget::GetRootAccessible() {
1797 NS_ENSURE_TRUE(mWidgetListener, nullptr);
1799 PresShell* presShell = mWidgetListener->GetPresShell();
1800 NS_ENSURE_TRUE(presShell, nullptr);
1802 // If container is null then the presshell is not active. This often happens
1803 // when a preshell is being held onto for fastback.
1804 nsPresContext* presContext = presShell->GetPresContext();
1805 NS_ENSURE_TRUE(presContext->GetContainerWeak(), nullptr);
1807 // Accessible creation might be not safe so use IsSafeToRunScript to
1808 // make sure it's not created at unsafe times.
1809 nsAccessibilityService* accService = GetOrCreateAccService();
1810 if (accService) {
1811 return accService->GetRootDocumentAccessible(
1812 presShell, nsContentUtils::IsSafeToRunScript());
1815 return nullptr;
1818 #endif // ACCESSIBILITY
1820 void nsBaseWidget::StartAsyncScrollbarDrag(
1821 const AsyncDragMetrics& aDragMetrics) {
1822 if (!AsyncPanZoomEnabled()) {
1823 return;
1826 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession);
1828 LayersId layersId = mCompositorSession->RootLayerTreeId();
1829 SLGuidAndRenderRoot guid(layersId, aDragMetrics.mPresShellId,
1830 aDragMetrics.mViewId, wr::RenderRoot::Default);
1832 APZThreadUtils::RunOnControllerThread(
1833 NewRunnableMethod<SLGuidAndRenderRoot, AsyncDragMetrics>(
1834 "layers::IAPZCTreeManager::StartScrollbarDrag", mAPZC,
1835 &IAPZCTreeManager::StartScrollbarDrag, guid, aDragMetrics));
1838 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
1839 const SLGuidAndRenderRoot& aGuid) {
1840 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1842 return mAPZC->StartAutoscroll(aGuid, aAnchorLocation);
1845 void nsBaseWidget::StopAsyncAutoscroll(const SLGuidAndRenderRoot& aGuid) {
1846 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1848 mAPZC->StopAutoscroll(aGuid);
1851 already_AddRefed<nsIScreen> nsBaseWidget::GetWidgetScreen() {
1852 nsCOMPtr<nsIScreenManager> screenManager;
1853 screenManager = do_GetService("@mozilla.org/gfx/screenmanager;1");
1854 if (!screenManager) {
1855 return nullptr;
1858 LayoutDeviceIntRect bounds = GetScreenBounds();
1859 DesktopIntRect deskBounds = RoundedToInt(bounds / GetDesktopToDeviceScale());
1860 nsCOMPtr<nsIScreen> screen;
1861 screenManager->ScreenForRect(deskBounds.X(), deskBounds.Y(),
1862 deskBounds.Width(), deskBounds.Height(),
1863 getter_AddRefs(screen));
1864 return screen.forget();
1867 mozilla::DesktopToLayoutDeviceScale
1868 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
1869 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
1870 ->GetDesktopToDeviceScale();
1873 nsresult nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint,
1874 bool aLongTap,
1875 nsIObserver* aObserver) {
1876 AutoObserverNotifier notifier(aObserver, "touchtap");
1878 if (sPointerIdCounter > TOUCH_INJECT_MAX_POINTS) {
1879 sPointerIdCounter = 0;
1881 int pointerId = sPointerIdCounter;
1882 sPointerIdCounter++;
1883 nsresult rv = SynthesizeNativeTouchPoint(pointerId, TOUCH_CONTACT, aPoint,
1884 1.0, 90, nullptr);
1885 if (NS_FAILED(rv)) {
1886 return rv;
1889 if (!aLongTap) {
1890 return SynthesizeNativeTouchPoint(pointerId, TOUCH_REMOVE, aPoint, 0, 0,
1891 nullptr);
1894 // initiate a long tap
1895 int elapse = Preferences::GetInt("ui.click_hold_context_menus.delay",
1896 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC);
1897 if (!mLongTapTimer) {
1898 mLongTapTimer = NS_NewTimer();
1899 if (!mLongTapTimer) {
1900 SynthesizeNativeTouchPoint(pointerId, TOUCH_CANCEL, aPoint, 0, 0,
1901 nullptr);
1902 return NS_ERROR_UNEXPECTED;
1904 // Windows requires recuring events, so we set this to a smaller window
1905 // than the pref value.
1906 int timeout = elapse;
1907 if (timeout > TOUCH_INJECT_PUMP_TIMER_MSEC) {
1908 timeout = TOUCH_INJECT_PUMP_TIMER_MSEC;
1910 mLongTapTimer->InitWithNamedFuncCallback(
1911 OnLongTapTimerCallback, this, timeout, nsITimer::TYPE_REPEATING_SLACK,
1912 "nsIWidget::SynthesizeNativeTouchTap");
1915 // If we already have a long tap pending, cancel it. We only allow one long
1916 // tap to be active at a time.
1917 if (mLongTapTouchPoint) {
1918 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1919 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1922 mLongTapTouchPoint = MakeUnique<LongTapInfo>(
1923 pointerId, aPoint, TimeDuration::FromMilliseconds(elapse), aObserver);
1924 notifier.SkipNotification(); // we'll do it in the long-tap callback
1925 return NS_OK;
1928 // static
1929 void nsIWidget::OnLongTapTimerCallback(nsITimer* aTimer, void* aClosure) {
1930 auto* self = static_cast<nsIWidget*>(aClosure);
1932 if ((self->mLongTapTouchPoint->mStamp + self->mLongTapTouchPoint->mDuration) >
1933 TimeStamp::Now()) {
1934 #ifdef XP_WIN
1935 // Windows needs us to keep pumping feedback to the digitizer, so update
1936 // the pointer id with the same position.
1937 self->SynthesizeNativeTouchPoint(
1938 self->mLongTapTouchPoint->mPointerId, TOUCH_CONTACT,
1939 self->mLongTapTouchPoint->mPosition, 1.0, 90, nullptr);
1940 #endif
1941 return;
1944 AutoObserverNotifier notifier(self->mLongTapTouchPoint->mObserver,
1945 "touchtap");
1947 // finished, remove the touch point
1948 self->mLongTapTimer->Cancel();
1949 self->mLongTapTimer = nullptr;
1950 self->SynthesizeNativeTouchPoint(
1951 self->mLongTapTouchPoint->mPointerId, TOUCH_REMOVE,
1952 self->mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1953 self->mLongTapTouchPoint = nullptr;
1956 nsresult nsIWidget::ClearNativeTouchSequence(nsIObserver* aObserver) {
1957 AutoObserverNotifier notifier(aObserver, "cleartouch");
1959 if (!mLongTapTimer) {
1960 return NS_OK;
1962 mLongTapTimer->Cancel();
1963 mLongTapTimer = nullptr;
1964 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1965 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1966 mLongTapTouchPoint = nullptr;
1967 return NS_OK;
1970 MultiTouchInput nsBaseWidget::UpdateSynthesizedTouchState(
1971 MultiTouchInput* aState, uint32_t aTime, mozilla::TimeStamp aTimeStamp,
1972 uint32_t aPointerId, TouchPointerState aPointerState,
1973 LayoutDeviceIntPoint aPoint, double aPointerPressure,
1974 uint32_t aPointerOrientation) {
1975 ScreenIntPoint pointerScreenPoint = ViewAs<ScreenPixel>(
1976 aPoint, PixelCastJustification::LayoutDeviceIsScreenForBounds);
1978 // We can't dispatch *aState directly because (a) dispatching
1979 // it might inadvertently modify it and (b) in the case of touchend or
1980 // touchcancel events aState will hold the touches that are
1981 // still down whereas the input dispatched needs to hold the removed
1982 // touch(es). We use |inputToDispatch| for this purpose.
1983 MultiTouchInput inputToDispatch;
1984 inputToDispatch.mInputType = MULTITOUCH_INPUT;
1985 inputToDispatch.mTime = aTime;
1986 inputToDispatch.mTimeStamp = aTimeStamp;
1988 int32_t index = aState->IndexOfTouch((int32_t)aPointerId);
1989 if (aPointerState == TOUCH_CONTACT) {
1990 if (index >= 0) {
1991 // found an existing touch point, update it
1992 SingleTouchData& point = aState->mTouches[index];
1993 point.mScreenPoint = pointerScreenPoint;
1994 point.mRotationAngle = (float)aPointerOrientation;
1995 point.mForce = (float)aPointerPressure;
1996 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_MOVE;
1997 } else {
1998 // new touch point, add it
1999 aState->mTouches.AppendElement(SingleTouchData(
2000 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2001 (float)aPointerOrientation, (float)aPointerPressure));
2002 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_START;
2004 inputToDispatch.mTouches = aState->mTouches;
2005 } else {
2006 MOZ_ASSERT(aPointerState == TOUCH_REMOVE || aPointerState == TOUCH_CANCEL);
2007 // a touch point is being lifted, so remove it from the stored list
2008 if (index >= 0) {
2009 aState->mTouches.RemoveElementAt(index);
2011 inputToDispatch.mType =
2012 (aPointerState == TOUCH_REMOVE ? MultiTouchInput::MULTITOUCH_END
2013 : MultiTouchInput::MULTITOUCH_CANCEL);
2014 inputToDispatch.mTouches.AppendElement(SingleTouchData(
2015 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2016 (float)aPointerOrientation, (float)aPointerPressure));
2019 return inputToDispatch;
2022 void nsBaseWidget::NotifyLiveResizeStarted() {
2023 // If we have mLiveResizeListeners already non-empty, we should notify those
2024 // listeners that the resize stopped before starting anew. In theory this
2025 // should never happen because we shouldn't get nested live resize actions.
2026 NotifyLiveResizeStopped();
2027 MOZ_ASSERT(mLiveResizeListeners.IsEmpty());
2029 // If we can get the active remote tab for the current widget, suppress
2030 // the displayport on it during the live resize.
2031 if (!mWidgetListener) {
2032 return;
2034 nsCOMPtr<nsIAppWindow> appWindow = mWidgetListener->GetAppWindow();
2035 if (!appWindow) {
2036 return;
2038 mLiveResizeListeners = appWindow->GetLiveResizeListeners();
2039 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2040 mLiveResizeListeners[i]->LiveResizeStarted();
2044 void nsBaseWidget::NotifyLiveResizeStopped() {
2045 if (!mLiveResizeListeners.IsEmpty()) {
2046 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2047 mLiveResizeListeners[i]->LiveResizeStopped();
2049 mLiveResizeListeners.Clear();
2053 void nsBaseWidget::RegisterPluginWindowForRemoteUpdates() {
2054 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2055 MOZ_ASSERT_UNREACHABLE(
2056 "nsBaseWidget::RegisterPluginWindowForRemoteUpdates "
2057 "not implemented!");
2058 return;
2059 #else
2060 MOZ_ASSERT(NS_IsMainThread());
2061 void* id = GetNativeData(NS_NATIVE_PLUGIN_ID);
2062 if (!id) {
2063 NS_WARNING("This is not a valid native widget!");
2064 return;
2066 MOZ_ASSERT(sPluginWidgetList);
2067 sPluginWidgetList->Put(id, this);
2068 #endif
2071 void nsBaseWidget::UnregisterPluginWindowForRemoteUpdates() {
2072 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2073 MOZ_ASSERT_UNREACHABLE(
2074 "nsBaseWidget::UnregisterPluginWindowForRemoteUpdates "
2075 "not implemented!");
2076 return;
2077 #else
2078 MOZ_ASSERT(NS_IsMainThread());
2079 void* id = GetNativeData(NS_NATIVE_PLUGIN_ID);
2080 if (!id) {
2081 NS_WARNING("This is not a valid native widget!");
2082 return;
2084 MOZ_ASSERT(sPluginWidgetList);
2085 sPluginWidgetList->Remove(id);
2086 #endif
2089 nsresult nsBaseWidget::AsyncEnableDragDrop(bool aEnable) {
2090 RefPtr<nsBaseWidget> kungFuDeathGrip = this;
2091 return NS_DispatchToCurrentThreadQueue(
2092 NS_NewRunnableFunction(
2093 "AsyncEnableDragDropFn",
2094 [this, aEnable, kungFuDeathGrip]() { EnableDragDrop(aEnable); }),
2095 kAsyncDragDropTimeout, EventQueuePriority::Idle);
2098 // static
2099 nsIWidget* nsIWidget::LookupRegisteredPluginWindow(uintptr_t aWindowID) {
2100 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2101 MOZ_ASSERT_UNREACHABLE(
2102 "nsBaseWidget::LookupRegisteredPluginWindow "
2103 "not implemented!");
2104 return nullptr;
2105 #else
2106 MOZ_ASSERT(NS_IsMainThread());
2107 MOZ_ASSERT(sPluginWidgetList);
2108 return sPluginWidgetList->GetWeak((void*)aWindowID);
2109 #endif
2112 // static
2113 void nsIWidget::UpdateRegisteredPluginWindowVisibility(
2114 uintptr_t aOwnerWidget, nsTArray<uintptr_t>& aPluginIds) {
2115 #if !defined(XP_WIN) && !defined(MOZ_WIDGET_GTK)
2116 MOZ_ASSERT_UNREACHABLE(
2117 "nsBaseWidget::UpdateRegisteredPluginWindowVisibility"
2118 " not implemented!");
2119 return;
2120 #else
2121 MOZ_ASSERT(NS_IsMainThread());
2122 MOZ_ASSERT(sPluginWidgetList);
2124 // Our visible list is associated with a compositor which is associated with
2125 // a specific top level window. We use the parent widget during iteration
2126 // to skip the plugin widgets owned by other top level windows.
2127 for (auto iter = sPluginWidgetList->Iter(); !iter.Done(); iter.Next()) {
2128 const void* windowId = iter.Key();
2129 nsIWidget* widget = iter.UserData();
2131 MOZ_ASSERT(windowId);
2132 MOZ_ASSERT(widget);
2134 if (!widget->Destroyed()) {
2135 if ((uintptr_t)widget->GetParent() == aOwnerWidget) {
2136 widget->Show(aPluginIds.Contains((uintptr_t)windowId));
2140 #endif
2143 #if defined(XP_WIN)
2144 // static
2145 void nsIWidget::CaptureRegisteredPlugins(uintptr_t aOwnerWidget) {
2146 MOZ_ASSERT(NS_IsMainThread());
2147 MOZ_ASSERT(sPluginWidgetList);
2149 // Our visible list is associated with a compositor which is associated with
2150 // a specific top level window. We use the parent widget during iteration
2151 // to skip the plugin widgets owned by other top level windows.
2152 for (auto iter = sPluginWidgetList->Iter(); !iter.Done(); iter.Next()) {
2153 DebugOnly<const void*> windowId = iter.Key();
2154 nsIWidget* widget = iter.UserData();
2156 MOZ_ASSERT(windowId);
2157 MOZ_ASSERT(widget);
2159 if (!widget->Destroyed() && widget->IsVisible()) {
2160 if ((uintptr_t)widget->GetParent() == aOwnerWidget) {
2161 widget->UpdateScrollCapture();
2167 uint64_t nsBaseWidget::CreateScrollCaptureContainer() {
2168 mScrollCaptureContainer =
2169 LayerManager::CreateImageContainer(ImageContainer::ASYNCHRONOUS);
2170 if (!mScrollCaptureContainer) {
2171 NS_WARNING("Failed to create ImageContainer for widget image capture.");
2172 return ImageContainer::sInvalidAsyncContainerId;
2175 return mScrollCaptureContainer->GetAsyncContainerHandle().Value();
2178 void nsBaseWidget::UpdateScrollCapture() {
2179 // Don't capture if no container or no size.
2180 if (!mScrollCaptureContainer || mBounds.IsEmpty()) {
2181 return;
2184 // If the derived class cannot take a snapshot, for example due to clipping,
2185 // then it is responsible for creating a fallback. If null is returned, this
2186 // means that we want to keep the existing snapshot.
2187 RefPtr<gfx::SourceSurface> snapshot = CreateScrollSnapshot();
2188 if (!snapshot) {
2189 return;
2192 ImageContainer::NonOwningImage holder(new SourceSurfaceImage(snapshot));
2194 AutoTArray<ImageContainer::NonOwningImage, 1> imageList;
2195 imageList.AppendElement(holder);
2197 mScrollCaptureContainer->SetCurrentImages(imageList);
2200 void nsBaseWidget::DefaultFillScrollCapture(DrawTarget* aSnapshotDrawTarget) {
2201 gfx::IntSize dtSize = aSnapshotDrawTarget->GetSize();
2202 aSnapshotDrawTarget->FillRect(
2203 gfx::Rect(0, 0, dtSize.width, dtSize.height),
2204 gfx::ColorPattern(gfx::Color::FromABGR(kScrollCaptureFillColor)),
2205 gfx::DrawOptions(1.f, gfx::CompositionOp::OP_SOURCE));
2206 aSnapshotDrawTarget->Flush();
2208 #endif
2210 const IMENotificationRequests& nsIWidget::IMENotificationRequestsRef() {
2211 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
2212 return dispatcher->IMENotificationRequestsRef();
2215 nsresult nsIWidget::OnWindowedPluginKeyEvent(
2216 const NativeEventData& aKeyEventData,
2217 nsIKeyEventInPluginCallback* aCallback) {
2218 return NS_ERROR_NOT_IMPLEMENTED;
2221 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent* aEvent) {}
2223 bool nsIWidget::GetEditCommands(nsIWidget::NativeKeyBindingsType aType,
2224 const WidgetKeyboardEvent& aEvent,
2225 nsTArray<CommandInt>& aCommands) {
2226 MOZ_ASSERT(aEvent.IsTrusted());
2227 MOZ_ASSERT(aCommands.IsEmpty());
2228 return true;
2231 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboard() {
2232 if (XRE_IsContentProcess()) {
2233 return CreateBidiKeyboardContentProcess();
2235 return CreateBidiKeyboardInner();
2238 #ifdef ANDROID
2239 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboardInner() {
2240 // no bidi keyboard implementation
2241 return nullptr;
2243 #endif
2245 namespace mozilla::widget {
2247 const char* ToChar(InputContext::Origin aOrigin) {
2248 switch (aOrigin) {
2249 case InputContext::ORIGIN_MAIN:
2250 return "ORIGIN_MAIN";
2251 case InputContext::ORIGIN_CONTENT:
2252 return "ORIGIN_CONTENT";
2253 default:
2254 return "Unexpected value";
2258 const char* ToChar(IMEMessage aIMEMessage) {
2259 switch (aIMEMessage) {
2260 case NOTIFY_IME_OF_NOTHING:
2261 return "NOTIFY_IME_OF_NOTHING";
2262 case NOTIFY_IME_OF_FOCUS:
2263 return "NOTIFY_IME_OF_FOCUS";
2264 case NOTIFY_IME_OF_BLUR:
2265 return "NOTIFY_IME_OF_BLUR";
2266 case NOTIFY_IME_OF_SELECTION_CHANGE:
2267 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2268 case NOTIFY_IME_OF_TEXT_CHANGE:
2269 return "NOTIFY_IME_OF_TEXT_CHANGE";
2270 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED:
2271 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2272 case NOTIFY_IME_OF_POSITION_CHANGE:
2273 return "NOTIFY_IME_OF_POSITION_CHANGE";
2274 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
2275 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2276 case REQUEST_TO_COMMIT_COMPOSITION:
2277 return "REQUEST_TO_COMMIT_COMPOSITION";
2278 case REQUEST_TO_CANCEL_COMPOSITION:
2279 return "REQUEST_TO_CANCEL_COMPOSITION";
2280 default:
2281 return "Unexpected value";
2285 void NativeIMEContext::Init(nsIWidget* aWidget) {
2286 if (!aWidget) {
2287 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2288 mOriginProcessID = static_cast<uint64_t>(-1);
2289 return;
2291 if (!XRE_IsContentProcess()) {
2292 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(
2293 aWidget->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT));
2294 mOriginProcessID = 0;
2295 return;
2297 // If this is created in a child process, aWidget is an instance of
2298 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2299 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2300 // native IME context of the parent process.
2301 *this = aWidget->GetNativeIMEContext();
2304 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext) {
2305 if (NS_WARN_IF(!aRawNativeIMEContext)) {
2306 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2307 mOriginProcessID = static_cast<uint64_t>(-1);
2308 return;
2310 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(aRawNativeIMEContext);
2311 mOriginProcessID =
2312 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2315 void IMENotification::TextChangeDataBase::MergeWith(
2316 const IMENotification::TextChangeDataBase& aOther) {
2317 MOZ_ASSERT(aOther.IsValid(), "Merging data must store valid data");
2318 MOZ_ASSERT(aOther.mStartOffset <= aOther.mRemovedEndOffset,
2319 "end of removed text must be same or larger than start");
2320 MOZ_ASSERT(aOther.mStartOffset <= aOther.mAddedEndOffset,
2321 "end of added text must be same or larger than start");
2323 if (!IsValid()) {
2324 *this = aOther;
2325 return;
2328 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2329 // text ranges. I.e., mStartOffset should be the smallest offset of all
2330 // modified text ranges in old text. |mRemovedEndOffset| should be the
2331 // largest end offset in old text of all modified text ranges.
2332 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2333 // I.e., only this is an offset in new text.
2334 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2335 // premodified text was already removed. And some text whose length is
2336 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2337 // this allows IME to mark dirty the modified text range with |mStartOffset|
2338 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2339 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2340 // Additionally, IME can retrieve only the text between |mStartOffset| and
2341 // |mAddedEndOffset| for updating stored text.
2343 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2344 // should be adjusted to be in same text. The |newData.mStartOffset| and
2345 // |newData.mRemovedEndOffset| should be computed as in old text because
2346 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2347 // in the old text but even if some text before the values of the newData
2348 // has already been modified, the values don't include the changes.
2350 // For comparing new and old |mAddedEndOffset| values, they should be
2351 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2352 // computed as in the new text because |mAddedEndOffset| indicates the end
2353 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2354 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2356 const TextChangeDataBase& newData = aOther;
2357 const TextChangeDataBase oldData = *this;
2359 // mCausedOnlyByComposition should be true only when all changes are caused
2360 // by composition.
2361 mCausedOnlyByComposition =
2362 newData.mCausedOnlyByComposition && oldData.mCausedOnlyByComposition;
2364 // mIncludingChangesWithoutComposition should be true if at least one of
2365 // merged changes occurred without composition.
2366 mIncludingChangesWithoutComposition =
2367 newData.mIncludingChangesWithoutComposition ||
2368 oldData.mIncludingChangesWithoutComposition;
2370 // mIncludingChangesDuringComposition should be true when at least one of
2371 // the merged non-composition changes occurred during the latest composition.
2372 if (!newData.mCausedOnlyByComposition &&
2373 !newData.mIncludingChangesDuringComposition) {
2374 MOZ_ASSERT(newData.mIncludingChangesWithoutComposition);
2375 MOZ_ASSERT(mIncludingChangesWithoutComposition);
2376 // If new change is neither caused by composition nor occurred during
2377 // composition, set mIncludingChangesDuringComposition to false because
2378 // IME doesn't want outdated text changes as text change during current
2379 // composition.
2380 mIncludingChangesDuringComposition = false;
2381 } else {
2382 // Otherwise, set mIncludingChangesDuringComposition to true if either
2383 // oldData or newData includes changes during composition.
2384 mIncludingChangesDuringComposition =
2385 newData.mIncludingChangesDuringComposition ||
2386 oldData.mIncludingChangesDuringComposition;
2389 if (newData.mStartOffset >= oldData.mAddedEndOffset) {
2390 // Case 1:
2391 // If new start is after old end offset of added text, it means that text
2392 // after the modified range is modified. Like:
2393 // added range of old change: +----------+
2394 // removed range of new change: +----------+
2395 // So, the old start offset is always the smaller offset.
2396 mStartOffset = oldData.mStartOffset;
2397 // The new end offset of removed text is moved by the old change and we
2398 // need to cancel the move of the old change for comparing the offsets in
2399 // same text because it doesn't make sensce to compare offsets in different
2400 // text.
2401 uint32_t newRemovedEndOffsetInOldText =
2402 newData.mRemovedEndOffset - oldData.Difference();
2403 mRemovedEndOffset =
2404 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2405 // The new end offset of added text is always the larger offset.
2406 mAddedEndOffset = newData.mAddedEndOffset;
2407 return;
2410 if (newData.mStartOffset >= oldData.mStartOffset) {
2411 // If new start is in the modified range, it means that new data changes
2412 // a part or all of the range.
2413 mStartOffset = oldData.mStartOffset;
2414 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2415 // Case 2:
2416 // If new end of removed text is greater than old end of added text, it
2417 // means that all or a part of modified range modified again and text
2418 // after the modified range is also modified. Like:
2419 // added range of old change: +----------+
2420 // removed range of new change: +----------+
2421 // So, the new removed end offset is moved by the old change and we need
2422 // to cancel the move of the old change for comparing the offsets in the
2423 // same text because it doesn't make sense to compare the offsets in
2424 // different text.
2425 uint32_t newRemovedEndOffsetInOldText =
2426 newData.mRemovedEndOffset - oldData.Difference();
2427 mRemovedEndOffset =
2428 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2429 // The old end of added text is replaced by new change. So, it should be
2430 // same as the new start. On the other hand, the new added end offset is
2431 // always same or larger. Therefore, the merged end offset of added
2432 // text should be the new end offset of added text.
2433 mAddedEndOffset = newData.mAddedEndOffset;
2434 return;
2437 // Case 3:
2438 // If new end of removed text is less than old end of added text, it means
2439 // that only a part of the modified range is modified again. Like:
2440 // added range of old change: +------------+
2441 // removed range of new change: +-----+
2442 // So, the new end offset of removed text should be same as the old end
2443 // offset of removed text. Therefore, the merged end offset of removed
2444 // text should be the old text change's |mRemovedEndOffset|.
2445 mRemovedEndOffset = oldData.mRemovedEndOffset;
2446 // The old end of added text is moved by new change. So, we need to cancel
2447 // the move of the new change for comparing the offsets in same text.
2448 uint32_t oldAddedEndOffsetInNewText =
2449 oldData.mAddedEndOffset + newData.Difference();
2450 mAddedEndOffset =
2451 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2452 return;
2455 if (newData.mRemovedEndOffset >= oldData.mStartOffset) {
2456 // If new end of removed text is greater than old start (and new start is
2457 // less than old start), it means that a part of modified range is modified
2458 // again and some new text before the modified range is also modified.
2459 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2460 "new start offset should be less than old one here");
2461 mStartOffset = newData.mStartOffset;
2462 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2463 // Case 4:
2464 // If new end of removed text is greater than old end of added text, it
2465 // means that all modified text and text after the modified range is
2466 // modified. Like:
2467 // added range of old change: +----------+
2468 // removed range of new change: +------------------+
2469 // So, the new end of removed text is moved by the old change. Therefore,
2470 // we need to cancel the move of the old change for comparing the offsets
2471 // in same text because it doesn't make sense to compare the offsets in
2472 // different text.
2473 uint32_t newRemovedEndOffsetInOldText =
2474 newData.mRemovedEndOffset - oldData.Difference();
2475 mRemovedEndOffset =
2476 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2477 // The old end of added text is replaced by new change. So, the old end
2478 // offset of added text is same as new text change's start offset. Then,
2479 // new change's end offset of added text is always same or larger than
2480 // it. Therefore, merged end offset of added text is always the new end
2481 // offset of added text.
2482 mAddedEndOffset = newData.mAddedEndOffset;
2483 return;
2486 // Case 5:
2487 // If new end of removed text is less than old end of added text, it
2488 // means that only a part of the modified range is modified again. Like:
2489 // added range of old change: +----------+
2490 // removed range of new change: +----------+
2491 // So, the new end of removed text should be same as old end of removed
2492 // text for preventing end of removed text to be modified. Therefore,
2493 // merged end offset of removed text is always the old end offset of removed
2494 // text.
2495 mRemovedEndOffset = oldData.mRemovedEndOffset;
2496 // The old end of added text is moved by this change. So, we need to
2497 // cancel the move of the new change for comparing the offsets in same text
2498 // because it doesn't make sense to compare the offsets in different text.
2499 uint32_t oldAddedEndOffsetInNewText =
2500 oldData.mAddedEndOffset + newData.Difference();
2501 mAddedEndOffset =
2502 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2503 return;
2506 // Case 6:
2507 // Otherwise, i.e., both new end of added text and new start are less than
2508 // old start, text before the modified range is modified. Like:
2509 // added range of old change: +----------+
2510 // removed range of new change: +----------+
2511 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2512 "new start offset should be less than old one here");
2513 mStartOffset = newData.mStartOffset;
2514 MOZ_ASSERT(newData.mRemovedEndOffset < oldData.mRemovedEndOffset,
2515 "new removed end offset should be less than old one here");
2516 mRemovedEndOffset = oldData.mRemovedEndOffset;
2517 // The end of added text should be adjusted with the new difference.
2518 uint32_t oldAddedEndOffsetInNewText =
2519 oldData.mAddedEndOffset + newData.Difference();
2520 mAddedEndOffset =
2521 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2524 #ifdef DEBUG
2526 // Let's test the code of merging multiple text change data in debug build
2527 // and crash if one of them fails because this feature is very complex but
2528 // cannot be tested with mochitest.
2529 void IMENotification::TextChangeDataBase::Test() {
2530 static bool gTestTextChangeEvent = true;
2531 if (!gTestTextChangeEvent) {
2532 return;
2534 gTestTextChangeEvent = false;
2536 /****************************************************************************
2537 * Case 1
2538 ****************************************************************************/
2540 // Appending text
2541 MergeWith(TextChangeData(10, 10, 20, false, false));
2542 MergeWith(TextChangeData(20, 20, 35, false, false));
2543 MOZ_ASSERT(mStartOffset == 10,
2544 "Test 1-1-1: mStartOffset should be the first offset");
2545 MOZ_ASSERT(
2546 mRemovedEndOffset == 10, // 20 - (20 - 10)
2547 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2548 MOZ_ASSERT(
2549 mAddedEndOffset == 35,
2550 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2551 Clear();
2553 // Removing text (longer line -> shorter line)
2554 MergeWith(TextChangeData(10, 20, 10, false, false));
2555 MergeWith(TextChangeData(10, 30, 10, false, false));
2556 MOZ_ASSERT(mStartOffset == 10,
2557 "Test 1-2-1: mStartOffset should be the first offset");
2558 MOZ_ASSERT(mRemovedEndOffset == 40, // 30 + (10 - 20)
2559 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2560 "removed text "
2561 "with already removed length");
2562 MOZ_ASSERT(
2563 mAddedEndOffset == 10,
2564 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2565 Clear();
2567 // Removing text (shorter line -> longer line)
2568 MergeWith(TextChangeData(10, 20, 10, false, false));
2569 MergeWith(TextChangeData(10, 15, 10, false, false));
2570 MOZ_ASSERT(mStartOffset == 10,
2571 "Test 1-3-1: mStartOffset should be the first offset");
2572 MOZ_ASSERT(mRemovedEndOffset == 25, // 15 + (10 - 20)
2573 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2574 "removed text "
2575 "with already removed length");
2576 MOZ_ASSERT(
2577 mAddedEndOffset == 10,
2578 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2579 Clear();
2581 // Appending text at different point (not sure if actually occurs)
2582 MergeWith(TextChangeData(10, 10, 20, false, false));
2583 MergeWith(TextChangeData(55, 55, 60, false, false));
2584 MOZ_ASSERT(mStartOffset == 10,
2585 "Test 1-4-1: mStartOffset should be the smallest offset");
2586 MOZ_ASSERT(
2587 mRemovedEndOffset == 45, // 55 - (10 - 20)
2588 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2589 "text without already added length");
2590 MOZ_ASSERT(
2591 mAddedEndOffset == 60,
2592 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2593 Clear();
2595 // Removing text at different point (not sure if actually occurs)
2596 MergeWith(TextChangeData(10, 20, 10, false, false));
2597 MergeWith(TextChangeData(55, 68, 55, false, false));
2598 MOZ_ASSERT(mStartOffset == 10,
2599 "Test 1-5-1: mStartOffset should be the smallest offset");
2600 MOZ_ASSERT(
2601 mRemovedEndOffset == 78, // 68 - (10 - 20)
2602 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2603 "text with already removed length");
2604 MOZ_ASSERT(
2605 mAddedEndOffset == 55,
2606 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2607 Clear();
2609 // Replacing text and append text (becomes longer)
2610 MergeWith(TextChangeData(30, 35, 32, false, false));
2611 MergeWith(TextChangeData(32, 32, 40, false, false));
2612 MOZ_ASSERT(mStartOffset == 30,
2613 "Test 1-6-1: mStartOffset should be the smallest offset");
2614 MOZ_ASSERT(
2615 mRemovedEndOffset == 35, // 32 - (32 - 35)
2616 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2617 "text");
2618 MOZ_ASSERT(
2619 mAddedEndOffset == 40,
2620 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2621 Clear();
2623 // Replacing text and append text (becomes shorter)
2624 MergeWith(TextChangeData(30, 35, 32, false, false));
2625 MergeWith(TextChangeData(32, 32, 33, false, false));
2626 MOZ_ASSERT(mStartOffset == 30,
2627 "Test 1-7-1: mStartOffset should be the smallest offset");
2628 MOZ_ASSERT(
2629 mRemovedEndOffset == 35, // 32 - (32 - 35)
2630 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2631 "text");
2632 MOZ_ASSERT(
2633 mAddedEndOffset == 33,
2634 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2635 Clear();
2637 // Removing text and replacing text after first range (not sure if actually
2638 // occurs)
2639 MergeWith(TextChangeData(30, 35, 30, false, false));
2640 MergeWith(TextChangeData(32, 34, 48, false, false));
2641 MOZ_ASSERT(mStartOffset == 30,
2642 "Test 1-8-1: mStartOffset should be the smallest offset");
2643 MOZ_ASSERT(mRemovedEndOffset == 39, // 34 - (30 - 35)
2644 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2645 "removed text "
2646 "without already removed text");
2647 MOZ_ASSERT(
2648 mAddedEndOffset == 48,
2649 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2650 Clear();
2652 // Removing text and replacing text after first range (not sure if actually
2653 // occurs)
2654 MergeWith(TextChangeData(30, 35, 30, false, false));
2655 MergeWith(TextChangeData(32, 38, 36, false, false));
2656 MOZ_ASSERT(mStartOffset == 30,
2657 "Test 1-9-1: mStartOffset should be the smallest offset");
2658 MOZ_ASSERT(mRemovedEndOffset == 43, // 38 - (30 - 35)
2659 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2660 "removed text "
2661 "without already removed text");
2662 MOZ_ASSERT(
2663 mAddedEndOffset == 36,
2664 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2665 Clear();
2667 /****************************************************************************
2668 * Case 2
2669 ****************************************************************************/
2671 // Replacing text in around end of added text (becomes shorter) (not sure
2672 // if actually occurs)
2673 MergeWith(TextChangeData(50, 50, 55, false, false));
2674 MergeWith(TextChangeData(53, 60, 54, false, false));
2675 MOZ_ASSERT(mStartOffset == 50,
2676 "Test 2-1-1: mStartOffset should be the smallest offset");
2677 MOZ_ASSERT(mRemovedEndOffset == 55, // 60 - (55 - 50)
2678 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2679 "removed text "
2680 "without already added text length");
2681 MOZ_ASSERT(
2682 mAddedEndOffset == 54,
2683 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2684 Clear();
2686 // Replacing text around end of added text (becomes longer) (not sure
2687 // if actually occurs)
2688 MergeWith(TextChangeData(50, 50, 55, false, false));
2689 MergeWith(TextChangeData(54, 62, 68, false, false));
2690 MOZ_ASSERT(mStartOffset == 50,
2691 "Test 2-2-1: mStartOffset should be the smallest offset");
2692 MOZ_ASSERT(mRemovedEndOffset == 57, // 62 - (55 - 50)
2693 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2694 "removed text "
2695 "without already added text length");
2696 MOZ_ASSERT(
2697 mAddedEndOffset == 68,
2698 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2699 Clear();
2701 // Replacing text around end of replaced text (became shorter) (not sure if
2702 // actually occurs)
2703 MergeWith(TextChangeData(36, 48, 45, false, false));
2704 MergeWith(TextChangeData(43, 50, 49, false, false));
2705 MOZ_ASSERT(mStartOffset == 36,
2706 "Test 2-3-1: mStartOffset should be the smallest offset");
2707 MOZ_ASSERT(mRemovedEndOffset == 53, // 50 - (45 - 48)
2708 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2709 "removed text "
2710 "without already removed text length");
2711 MOZ_ASSERT(
2712 mAddedEndOffset == 49,
2713 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2714 Clear();
2716 // Replacing text around end of replaced text (became longer) (not sure if
2717 // actually occurs)
2718 MergeWith(TextChangeData(36, 52, 53, false, false));
2719 MergeWith(TextChangeData(43, 68, 61, false, false));
2720 MOZ_ASSERT(mStartOffset == 36,
2721 "Test 2-4-1: mStartOffset should be the smallest offset");
2722 MOZ_ASSERT(mRemovedEndOffset == 67, // 68 - (53 - 52)
2723 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2724 "removed text "
2725 "without already added text length");
2726 MOZ_ASSERT(
2727 mAddedEndOffset == 61,
2728 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2729 Clear();
2731 /****************************************************************************
2732 * Case 3
2733 ****************************************************************************/
2735 // Appending text in already added text (not sure if actually occurs)
2736 MergeWith(TextChangeData(10, 10, 20, false, false));
2737 MergeWith(TextChangeData(15, 15, 30, false, false));
2738 MOZ_ASSERT(mStartOffset == 10,
2739 "Test 3-1-1: mStartOffset should be the smallest offset");
2740 MOZ_ASSERT(mRemovedEndOffset == 10,
2741 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2742 "removed text");
2743 MOZ_ASSERT(
2744 mAddedEndOffset == 35, // 20 + (30 - 15)
2745 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2746 "added text length by the new change");
2747 Clear();
2749 // Replacing text in added text (not sure if actually occurs)
2750 MergeWith(TextChangeData(50, 50, 55, false, false));
2751 MergeWith(TextChangeData(52, 53, 56, false, false));
2752 MOZ_ASSERT(mStartOffset == 50,
2753 "Test 3-2-1: mStartOffset should be the smallest offset");
2754 MOZ_ASSERT(mRemovedEndOffset == 50,
2755 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2756 "removed text");
2757 MOZ_ASSERT(
2758 mAddedEndOffset == 58, // 55 + (56 - 53)
2759 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2760 "added text length by the new change");
2761 Clear();
2763 // Replacing text in replaced text (became shorter) (not sure if actually
2764 // occurs)
2765 MergeWith(TextChangeData(36, 48, 45, false, false));
2766 MergeWith(TextChangeData(37, 38, 50, false, false));
2767 MOZ_ASSERT(mStartOffset == 36,
2768 "Test 3-3-1: mStartOffset should be the smallest offset");
2769 MOZ_ASSERT(mRemovedEndOffset == 48,
2770 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2771 "removed text");
2772 MOZ_ASSERT(
2773 mAddedEndOffset == 57, // 45 + (50 - 38)
2774 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2775 "added text length by the new change");
2776 Clear();
2778 // Replacing text in replaced text (became longer) (not sure if actually
2779 // occurs)
2780 MergeWith(TextChangeData(32, 48, 53, false, false));
2781 MergeWith(TextChangeData(43, 50, 52, false, false));
2782 MOZ_ASSERT(mStartOffset == 32,
2783 "Test 3-4-1: mStartOffset should be the smallest offset");
2784 MOZ_ASSERT(mRemovedEndOffset == 48,
2785 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2786 "removed text "
2787 "without already added text length");
2788 MOZ_ASSERT(
2789 mAddedEndOffset == 55, // 53 + (52 - 50)
2790 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2791 "added text length by the new change");
2792 Clear();
2794 // Replacing text in replaced text (became shorter) (not sure if actually
2795 // occurs)
2796 MergeWith(TextChangeData(36, 48, 50, false, false));
2797 MergeWith(TextChangeData(37, 49, 47, false, false));
2798 MOZ_ASSERT(mStartOffset == 36,
2799 "Test 3-5-1: mStartOffset should be the smallest offset");
2800 MOZ_ASSERT(
2801 mRemovedEndOffset == 48,
2802 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
2803 "text");
2804 MOZ_ASSERT(mAddedEndOffset == 48, // 50 + (47 - 49)
2805 "Test 3-5-3: mAddedEndOffset should be the first end of added "
2806 "text without "
2807 "removed text length by the new change");
2808 Clear();
2810 // Replacing text in replaced text (became longer) (not sure if actually
2811 // occurs)
2812 MergeWith(TextChangeData(32, 48, 53, false, false));
2813 MergeWith(TextChangeData(43, 50, 47, false, false));
2814 MOZ_ASSERT(mStartOffset == 32,
2815 "Test 3-6-1: mStartOffset should be the smallest offset");
2816 MOZ_ASSERT(mRemovedEndOffset == 48,
2817 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
2818 "removed text "
2819 "without already added text length");
2820 MOZ_ASSERT(mAddedEndOffset == 50, // 53 + (47 - 50)
2821 "Test 3-6-3: mAddedEndOffset should be the first end of added "
2822 "text without "
2823 "removed text length by the new change");
2824 Clear();
2826 /****************************************************************************
2827 * Case 4
2828 ****************************************************************************/
2830 // Replacing text all of already append text (not sure if actually occurs)
2831 MergeWith(TextChangeData(50, 50, 55, false, false));
2832 MergeWith(TextChangeData(44, 66, 68, false, false));
2833 MOZ_ASSERT(mStartOffset == 44,
2834 "Test 4-1-1: mStartOffset should be the smallest offset");
2835 MOZ_ASSERT(mRemovedEndOffset == 61, // 66 - (55 - 50)
2836 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
2837 "removed text "
2838 "without already added text length");
2839 MOZ_ASSERT(
2840 mAddedEndOffset == 68,
2841 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
2842 Clear();
2844 // Replacing text around a point in which text was removed (not sure if
2845 // actually occurs)
2846 MergeWith(TextChangeData(50, 62, 50, false, false));
2847 MergeWith(TextChangeData(44, 66, 68, false, false));
2848 MOZ_ASSERT(mStartOffset == 44,
2849 "Test 4-2-1: mStartOffset should be the smallest offset");
2850 MOZ_ASSERT(mRemovedEndOffset == 78, // 66 - (50 - 62)
2851 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
2852 "removed text "
2853 "without already removed text length");
2854 MOZ_ASSERT(
2855 mAddedEndOffset == 68,
2856 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
2857 Clear();
2859 // Replacing text all replaced text (became shorter) (not sure if actually
2860 // occurs)
2861 MergeWith(TextChangeData(50, 62, 60, false, false));
2862 MergeWith(TextChangeData(49, 128, 130, false, false));
2863 MOZ_ASSERT(mStartOffset == 49,
2864 "Test 4-3-1: mStartOffset should be the smallest offset");
2865 MOZ_ASSERT(mRemovedEndOffset == 130, // 128 - (60 - 62)
2866 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
2867 "removed text "
2868 "without already removed text length");
2869 MOZ_ASSERT(
2870 mAddedEndOffset == 130,
2871 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
2872 Clear();
2874 // Replacing text all replaced text (became longer) (not sure if actually
2875 // occurs)
2876 MergeWith(TextChangeData(50, 61, 73, false, false));
2877 MergeWith(TextChangeData(44, 100, 50, false, false));
2878 MOZ_ASSERT(mStartOffset == 44,
2879 "Test 4-4-1: mStartOffset should be the smallest offset");
2880 MOZ_ASSERT(mRemovedEndOffset == 88, // 100 - (73 - 61)
2881 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
2882 "removed text "
2883 "with already added text length");
2884 MOZ_ASSERT(
2885 mAddedEndOffset == 50,
2886 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
2887 Clear();
2889 /****************************************************************************
2890 * Case 5
2891 ****************************************************************************/
2893 // Replacing text around start of added text (not sure if actually occurs)
2894 MergeWith(TextChangeData(50, 50, 55, false, false));
2895 MergeWith(TextChangeData(48, 52, 49, false, false));
2896 MOZ_ASSERT(mStartOffset == 48,
2897 "Test 5-1-1: mStartOffset should be the smallest offset");
2898 MOZ_ASSERT(
2899 mRemovedEndOffset == 50,
2900 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
2901 "text");
2902 MOZ_ASSERT(
2903 mAddedEndOffset == 52, // 55 + (52 - 49)
2904 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
2905 "added text length by the new change");
2906 Clear();
2908 // Replacing text around start of replaced text (became shorter) (not sure if
2909 // actually occurs)
2910 MergeWith(TextChangeData(50, 60, 58, false, false));
2911 MergeWith(TextChangeData(43, 50, 48, false, false));
2912 MOZ_ASSERT(mStartOffset == 43,
2913 "Test 5-2-1: mStartOffset should be the smallest offset");
2914 MOZ_ASSERT(
2915 mRemovedEndOffset == 60,
2916 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
2917 "text");
2918 MOZ_ASSERT(mAddedEndOffset == 56, // 58 + (48 - 50)
2919 "Test 5-2-3: mAddedEndOffset should be the first end of added "
2920 "text without "
2921 "removed text length by the new change");
2922 Clear();
2924 // Replacing text around start of replaced text (became longer) (not sure if
2925 // actually occurs)
2926 MergeWith(TextChangeData(50, 60, 68, false, false));
2927 MergeWith(TextChangeData(43, 55, 53, false, false));
2928 MOZ_ASSERT(mStartOffset == 43,
2929 "Test 5-3-1: mStartOffset should be the smallest offset");
2930 MOZ_ASSERT(
2931 mRemovedEndOffset == 60,
2932 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
2933 "text");
2934 MOZ_ASSERT(mAddedEndOffset == 66, // 68 + (53 - 55)
2935 "Test 5-3-3: mAddedEndOffset should be the first end of added "
2936 "text without "
2937 "removed text length by the new change");
2938 Clear();
2940 // Replacing text around start of replaced text (became shorter) (not sure if
2941 // actually occurs)
2942 MergeWith(TextChangeData(50, 60, 58, false, false));
2943 MergeWith(TextChangeData(43, 50, 128, false, false));
2944 MOZ_ASSERT(mStartOffset == 43,
2945 "Test 5-4-1: mStartOffset should be the smallest offset");
2946 MOZ_ASSERT(
2947 mRemovedEndOffset == 60,
2948 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
2949 "text");
2950 MOZ_ASSERT(
2951 mAddedEndOffset == 136, // 58 + (128 - 50)
2952 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
2953 "added text length by the new change");
2954 Clear();
2956 // Replacing text around start of replaced text (became longer) (not sure if
2957 // actually occurs)
2958 MergeWith(TextChangeData(50, 60, 68, false, false));
2959 MergeWith(TextChangeData(43, 55, 65, false, false));
2960 MOZ_ASSERT(mStartOffset == 43,
2961 "Test 5-5-1: mStartOffset should be the smallest offset");
2962 MOZ_ASSERT(
2963 mRemovedEndOffset == 60,
2964 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
2965 "text");
2966 MOZ_ASSERT(
2967 mAddedEndOffset == 78, // 68 + (65 - 55)
2968 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
2969 "added text length by the new change");
2970 Clear();
2972 /****************************************************************************
2973 * Case 6
2974 ****************************************************************************/
2976 // Appending text before already added text (not sure if actually occurs)
2977 MergeWith(TextChangeData(30, 30, 45, false, false));
2978 MergeWith(TextChangeData(10, 10, 20, false, false));
2979 MOZ_ASSERT(mStartOffset == 10,
2980 "Test 6-1-1: mStartOffset should be the smallest offset");
2981 MOZ_ASSERT(
2982 mRemovedEndOffset == 30,
2983 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
2984 "text");
2985 MOZ_ASSERT(
2986 mAddedEndOffset == 55, // 45 + (20 - 10)
2987 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
2988 "added text length by the new change");
2989 Clear();
2991 // Removing text before already removed text (not sure if actually occurs)
2992 MergeWith(TextChangeData(30, 35, 30, false, false));
2993 MergeWith(TextChangeData(10, 25, 10, false, false));
2994 MOZ_ASSERT(mStartOffset == 10,
2995 "Test 6-2-1: mStartOffset should be the smallest offset");
2996 MOZ_ASSERT(
2997 mRemovedEndOffset == 35,
2998 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
2999 "text");
3000 MOZ_ASSERT(
3001 mAddedEndOffset == 15, // 30 - (25 - 10)
3002 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3003 "removed text length by the new change");
3004 Clear();
3006 // Replacing text before already replaced text (not sure if actually occurs)
3007 MergeWith(TextChangeData(50, 65, 70, false, false));
3008 MergeWith(TextChangeData(13, 24, 15, false, false));
3009 MOZ_ASSERT(mStartOffset == 13,
3010 "Test 6-3-1: mStartOffset should be the smallest offset");
3011 MOZ_ASSERT(
3012 mRemovedEndOffset == 65,
3013 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3014 "text");
3015 MOZ_ASSERT(mAddedEndOffset == 61, // 70 + (15 - 24)
3016 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3017 "text without "
3018 "removed text length by the new change");
3019 Clear();
3021 // Replacing text before already replaced text (not sure if actually occurs)
3022 MergeWith(TextChangeData(50, 65, 70, false, false));
3023 MergeWith(TextChangeData(13, 24, 36, false, false));
3024 MOZ_ASSERT(mStartOffset == 13,
3025 "Test 6-4-1: mStartOffset should be the smallest offset");
3026 MOZ_ASSERT(
3027 mRemovedEndOffset == 65,
3028 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3029 "text");
3030 MOZ_ASSERT(mAddedEndOffset == 82, // 70 + (36 - 24)
3031 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3032 "text without "
3033 "removed text length by the new change");
3034 Clear();
3037 #endif // #ifdef DEBUG
3039 } // namespace mozilla::widget
3041 #ifdef DEBUG
3042 //////////////////////////////////////////////////////////////
3044 // Convert a GUI event message code to a string.
3045 // Makes it a lot easier to debug events.
3047 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3048 // for a DebugPrintEvent() function that uses
3049 // this.
3051 //////////////////////////////////////////////////////////////
3052 /* static */
3053 nsAutoString nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent* aGuiEvent) {
3054 NS_ASSERTION(nullptr != aGuiEvent, "cmon, null gui event.");
3056 nsAutoString eventName(NS_LITERAL_STRING("UNKNOWN"));
3058 # define _ASSIGN_eventName(_value, _name) \
3059 case _value: \
3060 eventName.AssignLiteral(_name); \
3061 break
3063 switch (aGuiEvent->mMessage) {
3064 _ASSIGN_eventName(eBlur, "eBlur");
3065 _ASSIGN_eventName(eDrop, "eDrop");
3066 _ASSIGN_eventName(eDragEnter, "eDragEnter");
3067 _ASSIGN_eventName(eDragExit, "eDragExit");
3068 _ASSIGN_eventName(eDragOver, "eDragOver");
3069 _ASSIGN_eventName(eEditorInput, "eEditorInput");
3070 _ASSIGN_eventName(eFocus, "eFocus");
3071 _ASSIGN_eventName(eFocusIn, "eFocusIn");
3072 _ASSIGN_eventName(eFocusOut, "eFocusOut");
3073 _ASSIGN_eventName(eFormSelect, "eFormSelect");
3074 _ASSIGN_eventName(eFormChange, "eFormChange");
3075 _ASSIGN_eventName(eFormReset, "eFormReset");
3076 _ASSIGN_eventName(eFormSubmit, "eFormSubmit");
3077 _ASSIGN_eventName(eImageAbort, "eImageAbort");
3078 _ASSIGN_eventName(eLoadError, "eLoadError");
3079 _ASSIGN_eventName(eKeyDown, "eKeyDown");
3080 _ASSIGN_eventName(eKeyPress, "eKeyPress");
3081 _ASSIGN_eventName(eKeyUp, "eKeyUp");
3082 _ASSIGN_eventName(eMouseEnterIntoWidget, "eMouseEnterIntoWidget");
3083 _ASSIGN_eventName(eMouseExitFromWidget, "eMouseExitFromWidget");
3084 _ASSIGN_eventName(eMouseDown, "eMouseDown");
3085 _ASSIGN_eventName(eMouseUp, "eMouseUp");
3086 _ASSIGN_eventName(eMouseClick, "eMouseClick");
3087 _ASSIGN_eventName(eMouseAuxClick, "eMouseAuxClick");
3088 _ASSIGN_eventName(eMouseDoubleClick, "eMouseDoubleClick");
3089 _ASSIGN_eventName(eMouseMove, "eMouseMove");
3090 _ASSIGN_eventName(eLoad, "eLoad");
3091 _ASSIGN_eventName(ePopState, "ePopState");
3092 _ASSIGN_eventName(eBeforeScriptExecute, "eBeforeScriptExecute");
3093 _ASSIGN_eventName(eAfterScriptExecute, "eAfterScriptExecute");
3094 _ASSIGN_eventName(eUnload, "eUnload");
3095 _ASSIGN_eventName(eHashChange, "eHashChange");
3096 _ASSIGN_eventName(eReadyStateChange, "eReadyStateChange");
3097 _ASSIGN_eventName(eXULBroadcast, "eXULBroadcast");
3098 _ASSIGN_eventName(eXULCommandUpdate, "eXULCommandUpdate");
3100 # undef _ASSIGN_eventName
3102 default: {
3103 eventName.AssignLiteral("UNKNOWN: ");
3104 eventName.AppendInt(aGuiEvent->mMessage);
3105 } break;
3108 return nsAutoString(eventName);
3110 //////////////////////////////////////////////////////////////
3112 // Code to deal with paint and event debug prefs.
3114 //////////////////////////////////////////////////////////////
3115 struct PrefPair {
3116 const char* name;
3117 bool value;
3120 static PrefPair debug_PrefValues[] = {
3121 {"nglayout.debug.crossing_event_dumping", false},
3122 {"nglayout.debug.event_dumping", false},
3123 {"nglayout.debug.invalidate_dumping", false},
3124 {"nglayout.debug.motion_event_dumping", false},
3125 {"nglayout.debug.paint_dumping", false},
3126 {"nglayout.debug.paint_flashing", false},
3127 {"nglayout.debug.paint_flashing_chrome", false}};
3129 //////////////////////////////////////////////////////////////
3130 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName) {
3131 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3133 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3134 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3135 return debug_PrefValues[i].value;
3139 return false;
3141 //////////////////////////////////////////////////////////////
3142 static void debug_SetCachedBoolPref(const char* aPrefName, bool aValue) {
3143 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3145 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3146 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3147 debug_PrefValues[i].value = aValue;
3149 return;
3153 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3156 //////////////////////////////////////////////////////////////
3157 class Debug_PrefObserver final : public nsIObserver {
3158 ~Debug_PrefObserver() {}
3160 public:
3161 NS_DECL_ISUPPORTS
3162 NS_DECL_NSIOBSERVER
3165 NS_IMPL_ISUPPORTS(Debug_PrefObserver, nsIObserver)
3167 NS_IMETHODIMP
3168 Debug_PrefObserver::Observe(nsISupports* subject, const char* topic,
3169 const char16_t* data) {
3170 NS_ConvertUTF16toUTF8 prefName(data);
3172 bool value = Preferences::GetBool(prefName.get(), false);
3173 debug_SetCachedBoolPref(prefName.get(), value);
3174 return NS_OK;
3177 //////////////////////////////////////////////////////////////
3178 /* static */ void debug_RegisterPrefCallbacks() {
3179 static bool once = true;
3181 if (!once) {
3182 return;
3185 once = false;
3187 nsCOMPtr<nsIObserver> obs(new Debug_PrefObserver());
3188 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3189 // Initialize the pref values
3190 debug_PrefValues[i].value =
3191 Preferences::GetBool(debug_PrefValues[i].name, false);
3193 if (obs) {
3194 // Register callbacks for when these change
3195 nsCString name;
3196 name.AssignLiteral(debug_PrefValues[i].name,
3197 strlen(debug_PrefValues[i].name));
3198 Preferences::AddStrongObserver(obs, name);
3202 //////////////////////////////////////////////////////////////
3203 static int32_t _GetPrintCount() {
3204 static int32_t sCount = 0;
3206 return ++sCount;
3208 //////////////////////////////////////////////////////////////
3209 /* static */
3210 bool nsBaseWidget::debug_WantPaintFlashing() {
3211 return debug_GetCachedBoolPref("nglayout.debug.paint_flashing");
3213 //////////////////////////////////////////////////////////////
3214 /* static */
3215 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut, nsIWidget* aWidget,
3216 WidgetGUIEvent* aGuiEvent,
3217 const char* aWidgetName, int32_t aWindowID) {
3218 if (aGuiEvent->mMessage == eMouseMove) {
3219 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3222 if (aGuiEvent->mMessage == eMouseEnterIntoWidget ||
3223 aGuiEvent->mMessage == eMouseExitFromWidget) {
3224 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3225 return;
3228 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3230 NS_LossyConvertUTF16toASCII tempString(
3231 debug_GuiEventToString(aGuiEvent).get());
3233 fprintf(aFileOut, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3234 _GetPrintCount(), tempString.get(), (void*)aWidget, aWidgetName,
3235 aWindowID, aGuiEvent->mRefPoint.x, aGuiEvent->mRefPoint.y);
3237 //////////////////////////////////////////////////////////////
3238 /* static */
3239 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut, nsIWidget* aWidget,
3240 const nsIntRegion& aRegion,
3241 const char* aWidgetName,
3242 int32_t aWindowID) {
3243 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3244 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3246 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3248 nsIntRect rect = aRegion.GetBounds();
3249 fprintf(aFileOut,
3250 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3251 "%3d,%-3d",
3252 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID, rect.X(),
3253 rect.Y(), rect.Width(), rect.Height());
3255 fprintf(aFileOut, "\n");
3257 //////////////////////////////////////////////////////////////
3258 /* static */
3259 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut, nsIWidget* aWidget,
3260 const LayoutDeviceIntRect* aRect,
3261 const char* aWidgetName,
3262 int32_t aWindowID) {
3263 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3265 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3266 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3268 fprintf(aFileOut, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3269 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID);
3271 if (aRect) {
3272 fprintf(aFileOut, " rect=%3d,%-3d %3d,%-3d", aRect->X(), aRect->Y(),
3273 aRect->Width(), aRect->Height());
3274 } else {
3275 fprintf(aFileOut, " rect=%-15s", "none");
3278 fprintf(aFileOut, "\n");
3280 //////////////////////////////////////////////////////////////
3282 #endif // DEBUG