Bug 1835241 - Part 3: Concatenate nested namespaces in GC code as per the coding...
[gecko.git] / widget / nsBaseWidget.cpp
blobb723ebd4dfb41bc9ba0fa40b6e2c6bed77b333c2
2 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
3 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
4 /* This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
8 #include "nsBaseWidget.h"
10 #include <utility>
12 #include "GLConsts.h"
13 #include "InputData.h"
14 #include "LiveResizeListener.h"
15 #include "SwipeTracker.h"
16 #include "TouchEvents.h"
17 #include "X11UndefineNone.h"
18 #include "base/thread.h"
19 #include "mozilla/ArrayUtils.h"
20 #include "mozilla/Attributes.h"
21 #include "mozilla/GlobalKeyListener.h"
22 #include "mozilla/IMEStateManager.h"
23 #include "mozilla/Logging.h"
24 #include "mozilla/MouseEvents.h"
25 #include "mozilla/NativeKeyBindingsType.h"
26 #include "mozilla/Preferences.h"
27 #include "mozilla/PresShell.h"
28 #include "mozilla/ScopeExit.h"
29 #include "mozilla/Sprintf.h"
30 #include "mozilla/StaticPrefs_apz.h"
31 #include "mozilla/StaticPrefs_dom.h"
32 #include "mozilla/StaticPrefs_gfx.h"
33 #include "mozilla/StaticPrefs_layers.h"
34 #include "mozilla/StaticPrefs_layout.h"
35 #include "mozilla/TextEventDispatcher.h"
36 #include "mozilla/TextEventDispatcherListener.h"
37 #include "mozilla/UniquePtr.h"
38 #include "mozilla/Unused.h"
39 #include "mozilla/VsyncDispatcher.h"
40 #include "mozilla/dom/BrowserParent.h"
41 #include "mozilla/dom/ContentChild.h"
42 #include "mozilla/dom/Document.h"
43 #include "mozilla/dom/SimpleGestureEventBinding.h"
44 #include "mozilla/gfx/2D.h"
45 #include "mozilla/gfx/GPUProcessManager.h"
46 #include "mozilla/gfx/gfxVars.h"
47 #include "mozilla/layers/APZCCallbackHelper.h"
48 #include "mozilla/layers/TouchActionHelper.h"
49 #include "mozilla/layers/APZEventState.h"
50 #include "mozilla/layers/APZInputBridge.h"
51 #include "mozilla/layers/APZThreadUtils.h"
52 #include "mozilla/layers/ChromeProcessController.h"
53 #include "mozilla/layers/Compositor.h"
54 #include "mozilla/layers/CompositorBridgeChild.h"
55 #include "mozilla/layers/CompositorBridgeParent.h"
56 #include "mozilla/layers/CompositorOptions.h"
57 #include "mozilla/layers/IAPZCTreeManager.h"
58 #include "mozilla/layers/ImageBridgeChild.h"
59 #include "mozilla/layers/InputAPZContext.h"
60 #include "mozilla/layers/WebRenderLayerManager.h"
61 #include "mozilla/webrender/WebRenderTypes.h"
62 #include "mozilla/widget/ScreenManager.h"
63 #include "nsAppDirectoryServiceDefs.h"
64 #include "nsCOMPtr.h"
65 #include "nsContentUtils.h"
66 #include "nsDeviceContext.h"
67 #include "nsGfxCIID.h"
68 #include "nsIAppWindow.h"
69 #include "nsIBaseWindow.h"
70 #include "nsIContent.h"
71 #include "nsIScreenManager.h"
72 #include "nsISimpleEnumerator.h"
73 #include "nsIWidgetListener.h"
74 #include "nsRefPtrHashtable.h"
75 #include "nsServiceManagerUtils.h"
76 #include "nsWidgetsCID.h"
77 #include "nsXULPopupManager.h"
78 #include "prdtoa.h"
79 #include "prenv.h"
80 #ifdef ACCESSIBILITY
81 # include "nsAccessibilityService.h"
82 #endif
83 #include "gfxConfig.h"
84 #include "gfxUtils.h" // for ToDeviceColor
85 #include "mozilla/layers/CompositorSession.h"
86 #include "VRManagerChild.h"
87 #include "gfxConfig.h"
88 #include "nsView.h"
89 #include "nsViewManager.h"
91 static mozilla::LazyLogModule sBaseWidgetLog("BaseWidget");
93 #ifdef DEBUG
94 # include "nsIObserver.h"
96 static void debug_RegisterPrefCallbacks();
98 #endif
100 #ifdef NOISY_WIDGET_LEAKS
101 static int32_t gNumWidgets;
102 #endif
104 #ifdef XP_MACOSX
105 # include "nsCocoaFeatures.h"
106 #endif
108 using namespace mozilla::dom;
109 using namespace mozilla::layers;
110 using namespace mozilla::ipc;
111 using namespace mozilla::widget;
112 using namespace mozilla;
114 // Async pump timer during injected long touch taps
115 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
116 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
117 int32_t nsIWidget::sPointerIdCounter = 0;
119 // Some statics from nsIWidget.h
120 /*static*/
121 uint64_t AutoObserverNotifier::sObserverId = 0;
122 /*static*/ nsTHashMap<uint64_t, nsCOMPtr<nsIObserver>>
123 AutoObserverNotifier::sSavedObservers;
125 // The maximum amount of time to let the EnableDragDrop runnable wait in the
126 // idle queue before timing out and moving it to the regular queue. Value is in
127 // milliseconds.
128 const uint32_t kAsyncDragDropTimeout = 1000;
130 NS_IMPL_ISUPPORTS(nsBaseWidget, nsIWidget, nsISupportsWeakReference)
132 //-------------------------------------------------------------------------
134 // nsBaseWidget constructor
136 //-------------------------------------------------------------------------
138 nsBaseWidget::nsBaseWidget() : nsBaseWidget(BorderStyle::None) {}
140 nsBaseWidget::nsBaseWidget(BorderStyle aBorderStyle)
141 : mWidgetListener(nullptr),
142 mAttachedWidgetListener(nullptr),
143 mPreviouslyAttachedWidgetListener(nullptr),
144 mCompositorVsyncDispatcher(nullptr),
145 mBorderStyle(aBorderStyle),
146 mBounds(0, 0, 0, 0),
147 mIsTiled(false),
148 mPopupLevel(PopupLevel::Top),
149 mPopupType(PopupType::Any),
150 mHasRemoteContent(false),
151 mUpdateCursor(true),
152 mUseAttachedEvents(false),
153 mIMEHasFocus(false),
154 mIMEHasQuit(false),
155 mIsFullyOccluded(false),
156 mNeedFastSnaphot(false),
157 mCurrentPanGestureBelongsToSwipe(false) {
158 #ifdef NOISY_WIDGET_LEAKS
159 gNumWidgets++;
160 printf("WIDGETS+ = %d\n", gNumWidgets);
161 #endif
163 #ifdef DEBUG
164 debug_RegisterPrefCallbacks();
165 #endif
167 mShutdownObserver = new WidgetShutdownObserver(this);
170 NS_IMPL_ISUPPORTS(WidgetShutdownObserver, nsIObserver)
172 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget* aWidget)
173 : mWidget(aWidget), mRegistered(false) {
174 Register();
177 WidgetShutdownObserver::~WidgetShutdownObserver() {
178 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
179 // gets torn down. The observer service and nsBaseWidget have a ref on us
180 // so nsBaseWidget has to call Unregister and then clear its ref.
183 NS_IMETHODIMP
184 WidgetShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
185 const char16_t* aData) {
186 if (!mWidget) {
187 return NS_OK;
189 if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
190 RefPtr<nsBaseWidget> widget(mWidget);
191 widget->Shutdown();
192 } else if (!strcmp(aTopic, "quit-application")) {
193 RefPtr<nsBaseWidget> widget(mWidget);
194 widget->QuitIME();
196 return NS_OK;
199 void WidgetShutdownObserver::Register() {
200 if (!mRegistered) {
201 mRegistered = true;
202 nsContentUtils::RegisterShutdownObserver(this);
204 #ifndef MOZ_WIDGET_ANDROID
205 // The primary purpose of observing quit-application is
206 // to avoid leaking a widget on Windows when nothing else
207 // breaks the circular reference between the widget and
208 // TSFTextStore. However, our Android IME code crashes if
209 // doing this on Android, so let's not do this on Android.
210 // Doing this on Gtk and Mac just in case.
211 nsCOMPtr<nsIObserverService> observerService =
212 mozilla::services::GetObserverService();
213 if (observerService) {
214 observerService->AddObserver(this, "quit-application", false);
216 #endif
220 void WidgetShutdownObserver::Unregister() {
221 if (mRegistered) {
222 mWidget = nullptr;
224 #ifndef MOZ_WIDGET_ANDROID
225 nsCOMPtr<nsIObserverService> observerService =
226 mozilla::services::GetObserverService();
227 if (observerService) {
228 observerService->RemoveObserver(this, "quit-application");
230 #endif
232 nsContentUtils::UnregisterShutdownObserver(this);
233 mRegistered = false;
237 #define INTL_APP_LOCALES_CHANGED "intl:app-locales-changed"
239 NS_IMPL_ISUPPORTS(LocalesChangedObserver, nsIObserver)
241 LocalesChangedObserver::LocalesChangedObserver(nsBaseWidget* aWidget)
242 : mWidget(aWidget), mRegistered(false) {
243 Register();
246 LocalesChangedObserver::~LocalesChangedObserver() {
247 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
248 // gets torn down. The observer service and nsBaseWidget have a ref on us
249 // so nsBaseWidget has to call Unregister and then clear its ref.
252 NS_IMETHODIMP
253 LocalesChangedObserver::Observe(nsISupports* aSubject, const char* aTopic,
254 const char16_t* aData) {
255 if (!mWidget) {
256 return NS_OK;
258 if (!strcmp(aTopic, INTL_APP_LOCALES_CHANGED)) {
259 RefPtr<nsBaseWidget> widget(mWidget);
260 widget->LocalesChanged();
262 return NS_OK;
265 void LocalesChangedObserver::Register() {
266 if (mRegistered) {
267 return;
270 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
271 if (obs) {
272 obs->AddObserver(this, INTL_APP_LOCALES_CHANGED, true);
275 // Locale might be update before registering
276 RefPtr<nsBaseWidget> widget(mWidget);
277 widget->LocalesChanged();
279 mRegistered = true;
282 void LocalesChangedObserver::Unregister() {
283 if (!mRegistered) {
284 return;
287 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
288 if (obs) {
289 obs->RemoveObserver(this, INTL_APP_LOCALES_CHANGED);
292 mWidget = nullptr;
293 mRegistered = false;
296 void nsBaseWidget::Shutdown() {
297 NotifyLiveResizeStopped();
298 DestroyCompositor();
299 FreeLocalesChangedObserver();
300 FreeShutdownObserver();
303 void nsBaseWidget::QuitIME() {
304 IMEStateManager::WidgetOnQuit(this);
305 this->mIMEHasQuit = true;
308 void nsBaseWidget::DestroyCompositor() {
309 RevokeTransactionIdAllocator();
311 // We release this before releasing the compositor, since it may hold the
312 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
313 // trigger a paint, creating a new compositor, and we don't want to re-use
314 // the old vsync dispatcher.
315 if (mCompositorVsyncDispatcher) {
316 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
318 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
319 mCompositorVsyncDispatcher->Shutdown();
320 mCompositorVsyncDispatcher = nullptr;
323 // The compositor shutdown sequence looks like this:
324 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
325 // 2. CompositorBridgeChild synchronously sends WillClose.
326 // 3. CompositorBridgeParent releases some resources (such as the layer
327 // manager, compositor, and widget).
328 // 4. CompositorBridgeChild::Destroy returns.
329 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
330 // compositor thread when the I/O thread closes the IPC channel.
331 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
332 // releases the reference CompositorBridgeParent holds to itself.
334 // When CompositorSession::Shutdown returns, we assume the compositor is gone
335 // or will be gone very soon.
336 if (mCompositorSession) {
337 ReleaseContentController();
338 mAPZC = nullptr;
339 SetCompositorWidgetDelegate(nullptr);
340 mCompositorBridgeChild = nullptr;
341 mCompositorSession->Shutdown();
342 mCompositorSession = nullptr;
346 // This prevents the layer manager from starting a new transaction during
347 // shutdown.
348 void nsBaseWidget::RevokeTransactionIdAllocator() {
349 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
350 return;
352 mWindowRenderer->AsWebRender()->SetTransactionIdAllocator(nullptr);
355 void nsBaseWidget::ReleaseContentController() {
356 if (mRootContentController) {
357 mRootContentController->Destroy();
358 mRootContentController = nullptr;
362 void nsBaseWidget::DestroyLayerManager() {
363 if (mWindowRenderer) {
364 mWindowRenderer->Destroy();
365 mWindowRenderer = nullptr;
367 DestroyCompositor();
370 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
372 void nsBaseWidget::FreeShutdownObserver() {
373 if (mShutdownObserver) {
374 mShutdownObserver->Unregister();
376 mShutdownObserver = nullptr;
379 void nsBaseWidget::FreeLocalesChangedObserver() {
380 if (mLocalesChangedObserver) {
381 mLocalesChangedObserver->Unregister();
383 mLocalesChangedObserver = nullptr;
386 //-------------------------------------------------------------------------
388 // nsBaseWidget destructor
390 //-------------------------------------------------------------------------
392 nsBaseWidget::~nsBaseWidget() {
393 if (mSwipeTracker) {
394 mSwipeTracker->Destroy();
395 mSwipeTracker = nullptr;
398 IMEStateManager::WidgetDestroyed(this);
400 FreeLocalesChangedObserver();
401 FreeShutdownObserver();
402 DestroyLayerManager();
404 #ifdef NOISY_WIDGET_LEAKS
405 gNumWidgets--;
406 printf("WIDGETS- = %d\n", gNumWidgets);
407 #endif
410 //-------------------------------------------------------------------------
412 // Basic create.
414 //-------------------------------------------------------------------------
415 void nsBaseWidget::BaseCreate(nsIWidget* aParent, widget::InitData* aInitData) {
416 if (aInitData) {
417 mWindowType = aInitData->mWindowType;
418 mBorderStyle = aInitData->mBorderStyle;
419 mPopupLevel = aInitData->mPopupLevel;
420 mPopupType = aInitData->mPopupHint;
421 mHasRemoteContent = aInitData->mHasRemoteContent;
424 if (aParent) {
425 aParent->AddChild(this);
429 //-------------------------------------------------------------------------
431 // Accessor functions to get/set the client data
433 //-------------------------------------------------------------------------
435 nsIWidgetListener* nsBaseWidget::GetWidgetListener() const {
436 return mWidgetListener;
439 void nsBaseWidget::SetWidgetListener(nsIWidgetListener* aWidgetListener) {
440 mWidgetListener = aWidgetListener;
443 already_AddRefed<nsIWidget> nsBaseWidget::CreateChild(
444 const LayoutDeviceIntRect& aRect, widget::InitData* aInitData,
445 bool aForceUseIWidgetParent) {
446 nsIWidget* parent = this;
447 nsNativeWidget nativeParent = nullptr;
449 if (!aForceUseIWidgetParent) {
450 // Use only either parent or nativeParent, not both, to match
451 // existing code. Eventually Create() should be divested of its
452 // nativeWidget parameter.
453 nativeParent = parent ? parent->GetNativeData(NS_NATIVE_WIDGET) : nullptr;
454 parent = nativeParent ? nullptr : parent;
455 MOZ_ASSERT(!parent || !nativeParent, "messed up logic");
458 nsCOMPtr<nsIWidget> widget;
459 if (aInitData && aInitData->mWindowType == WindowType::Popup) {
460 widget = AllocateChildPopupWidget();
461 } else {
462 widget = nsIWidget::CreateChildWindow();
465 if (widget && mNeedFastSnaphot) {
466 widget->SetNeedFastSnaphot();
469 if (widget &&
470 NS_SUCCEEDED(widget->Create(parent, nativeParent, aRect, aInitData))) {
471 return widget.forget();
474 return nullptr;
477 // Attach a view to our widget which we'll send events to.
478 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents) {
479 NS_ASSERTION((mWindowType == WindowType::TopLevel ||
480 mWindowType == WindowType::Dialog ||
481 mWindowType == WindowType::Invisible ||
482 mWindowType == WindowType::Child),
483 "Can't attach to window of that type");
485 mUseAttachedEvents = aUseAttachedEvents;
488 nsIWidgetListener* nsBaseWidget::GetAttachedWidgetListener() const {
489 return mAttachedWidgetListener;
492 nsIWidgetListener* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
493 return mPreviouslyAttachedWidgetListener;
496 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
497 nsIWidgetListener* aListener) {
498 mPreviouslyAttachedWidgetListener = aListener;
501 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener* aListener) {
502 mAttachedWidgetListener = aListener;
505 //-------------------------------------------------------------------------
507 // Close this nsBaseWidget
509 //-------------------------------------------------------------------------
510 void nsBaseWidget::Destroy() {
511 DestroyCompositor();
513 // Just in case our parent is the only ref to us
514 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
515 // disconnect from the parent
516 nsIWidget* parent = GetParent();
517 if (parent) {
518 parent->RemoveChild(this);
522 //-------------------------------------------------------------------------
524 // Get this nsBaseWidget parent
526 //-------------------------------------------------------------------------
527 nsIWidget* nsBaseWidget::GetParent(void) { return nullptr; }
529 //-------------------------------------------------------------------------
531 // Get this nsBaseWidget top level widget
533 //-------------------------------------------------------------------------
534 nsIWidget* nsBaseWidget::GetTopLevelWidget() {
535 nsIWidget *topLevelWidget = nullptr, *widget = this;
536 while (widget) {
537 topLevelWidget = widget;
538 widget = widget->GetParent();
540 return topLevelWidget;
543 //-------------------------------------------------------------------------
545 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
547 //-------------------------------------------------------------------------
548 nsIWidget* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
550 float nsBaseWidget::GetDPI() { return 96.0f; }
552 CSSToLayoutDeviceScale nsIWidget::GetDefaultScale() {
553 double devPixelsPerCSSPixel = StaticPrefs::layout_css_devPixelsPerPx();
555 if (devPixelsPerCSSPixel <= 0.0) {
556 devPixelsPerCSSPixel = GetDefaultScaleInternal();
559 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel);
562 nsIntSize nsIWidget::CustomCursorSize(const Cursor& aCursor) {
563 MOZ_ASSERT(aCursor.IsCustom());
564 int32_t width = 0;
565 int32_t height = 0;
566 aCursor.mContainer->GetWidth(&width);
567 aCursor.mContainer->GetHeight(&height);
568 aCursor.mResolution.ApplyTo(width, height);
569 return {width, height};
572 LayoutDeviceIntSize nsIWidget::ClientToWindowSizeDifference() {
573 auto margin = ClientToWindowMargin();
574 MOZ_ASSERT(margin.top >= 0, "Window should be bigger than client area");
575 MOZ_ASSERT(margin.left >= 0, "Window should be bigger than client area");
576 MOZ_ASSERT(margin.right >= 0, "Window should be bigger than client area");
577 MOZ_ASSERT(margin.bottom >= 0, "Window should be bigger than client area");
578 return {margin.LeftRight(), margin.TopBottom()};
581 RefPtr<mozilla::VsyncDispatcher> nsIWidget::GetVsyncDispatcher() {
582 return nullptr;
585 //-------------------------------------------------------------------------
587 // Add a child to the list of children
589 //-------------------------------------------------------------------------
590 void nsBaseWidget::AddChild(nsIWidget* aChild) {
591 MOZ_ASSERT(!aChild->GetNextSibling() && !aChild->GetPrevSibling(),
592 "aChild not properly removed from its old child list");
594 if (!mFirstChild) {
595 mFirstChild = mLastChild = aChild;
596 } else {
597 // append to the list
598 MOZ_ASSERT(mLastChild);
599 MOZ_ASSERT(!mLastChild->GetNextSibling());
600 mLastChild->SetNextSibling(aChild);
601 aChild->SetPrevSibling(mLastChild);
602 mLastChild = aChild;
606 //-------------------------------------------------------------------------
608 // Remove a child from the list of children
610 //-------------------------------------------------------------------------
611 void nsBaseWidget::RemoveChild(nsIWidget* aChild) {
612 #ifdef DEBUG
613 # ifdef XP_MACOSX
614 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
615 // null and we'll just have to do without this assertion.
616 nsIWidget* parent = aChild->GetParent();
617 NS_ASSERTION(!parent || parent == this, "Not one of our kids!");
618 # else
619 MOZ_RELEASE_ASSERT(aChild->GetParent() == this, "Not one of our kids!");
620 # endif
621 #endif
623 if (mLastChild == aChild) {
624 mLastChild = mLastChild->GetPrevSibling();
626 if (mFirstChild == aChild) {
627 mFirstChild = mFirstChild->GetNextSibling();
630 // Now remove from the list. Make sure that we pass ownership of the tail
631 // of the list correctly before we have aChild let go of it.
632 nsIWidget* prev = aChild->GetPrevSibling();
633 nsIWidget* next = aChild->GetNextSibling();
634 if (prev) {
635 prev->SetNextSibling(next);
637 if (next) {
638 next->SetPrevSibling(prev);
641 aChild->SetNextSibling(nullptr);
642 aChild->SetPrevSibling(nullptr);
645 //-------------------------------------------------------------------------
647 // Sets widget's position within its parent's child list.
649 //-------------------------------------------------------------------------
650 void nsBaseWidget::SetZIndex(int32_t aZIndex) {
651 // Hold a ref to ourselves just in case, since we're going to remove
652 // from our parent.
653 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
655 mZIndex = aZIndex;
657 // reorder this child in its parent's list.
658 auto* parent = static_cast<nsBaseWidget*>(GetParent());
659 if (parent) {
660 parent->RemoveChild(this);
661 // Scope sib outside the for loop so we can check it afterward
662 nsIWidget* sib = parent->GetFirstChild();
663 for (; sib; sib = sib->GetNextSibling()) {
664 int32_t childZIndex = GetZIndex();
665 if (aZIndex < childZIndex) {
666 // Insert ourselves before sib
667 nsIWidget* prev = sib->GetPrevSibling();
668 mNextSibling = sib;
669 mPrevSibling = prev;
670 sib->SetPrevSibling(this);
671 if (prev) {
672 prev->SetNextSibling(this);
673 } else {
674 NS_ASSERTION(sib == parent->mFirstChild, "Broken child list");
675 // We've taken ownership of sib, so it's safe to have parent let
676 // go of it
677 parent->mFirstChild = this;
679 PlaceBehind(eZPlacementBelow, sib, false);
680 break;
683 // were we added to the list?
684 if (!sib) {
685 parent->AddChild(this);
690 void nsBaseWidget::GetWorkspaceID(nsAString& workspaceID) {
691 workspaceID.Truncate();
694 void nsBaseWidget::MoveToWorkspace(const nsAString& workspaceID) {
695 // Noop.
698 //-------------------------------------------------------------------------
700 // Get this component cursor
702 //-------------------------------------------------------------------------
704 void nsBaseWidget::SetCursor(const Cursor& aCursor) { mCursor = aCursor; }
706 //-------------------------------------------------------------------------
708 // Window transparency methods
710 //-------------------------------------------------------------------------
712 void nsBaseWidget::SetTransparencyMode(TransparencyMode aMode) {}
714 TransparencyMode nsBaseWidget::GetTransparencyMode() {
715 return TransparencyMode::Opaque;
718 /* virtual */
719 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage,
720 uint16_t aDuration,
721 nsISupports* aData,
722 nsIRunnable* aCallback) {
723 MOZ_ASSERT_UNREACHABLE(
724 "Should never call PerformFullscreenTransition on nsBaseWidget");
727 //-------------------------------------------------------------------------
729 // Put the window into full-screen mode
731 //-------------------------------------------------------------------------
732 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen) {
733 #define MOZ_FORMAT_RECT(fmtstr) "[" fmtstr "," fmtstr " " fmtstr "x" fmtstr "]"
734 #define MOZ_SPLAT_RECT(rect) \
735 (rect).X(), (rect).Y(), (rect).Width(), (rect).Height()
737 // Windows which can be made fullscreen are exactly those which are located on
738 // the desktop, rather than being a child of some other window.
739 MOZ_DIAGNOSTIC_ASSERT(BoundsUseDesktopPixels(),
740 "non-desktop windows cannot be made fullscreen");
742 // Ensure that the OS chrome is hidden/shown before we resize and/or exit the
743 // function.
745 // HideWindowChrome() may (depending on platform, implementation details, and
746 // OS-level user preferences) alter the reported size of the window. The
747 // obvious and principled solution is socks-and-shoes:
748 // - On entering fullscreen mode: hide window chrome, then perform resize.
749 // - On leaving fullscreen mode: unperform resize, then show window chrome.
751 // ... unfortunately, HideWindowChrome() requires Resize() to be called
752 // afterwards (see bug 498835), which prevents this from being done in a
753 // straightforward way.
755 // Instead, we always call HideWindowChrome() just before we call Resize().
756 // This at least ensures that our measurements are consistently taken in a
757 // pre-transition state.
759 // ... unfortunately again, coupling HideWindowChrome() to Resize() means that
760 // we have to worry about the possibility of control flows that don't call
761 // Resize() at all. (That shouldn't happen, but it's not trivial to rule out.)
762 // We therefore set up a fallback to fix up the OS chrome if it hasn't been
763 // done at exit time.
764 bool hasAdjustedOSChrome = false;
765 const auto adjustOSChrome = [&]() {
766 if (hasAdjustedOSChrome) {
767 MOZ_ASSERT_UNREACHABLE("window chrome should only be adjusted once");
768 return;
770 HideWindowChrome(aFullScreen);
771 hasAdjustedOSChrome = true;
773 const auto adjustChromeOnScopeExit = MakeScopeExit([&]() {
774 if (hasAdjustedOSChrome) {
775 return;
778 MOZ_LOG(sBaseWidgetLog, LogLevel::Warning,
779 ("window was not resized within InfallibleMakeFullScreen()"));
781 // Hide chrome and "resize" the window to its current size.
782 auto rect = GetBounds();
783 adjustOSChrome();
784 Resize(rect.X(), rect.Y(), rect.Width(), rect.Height(), true);
787 // Attempt to resize to `rect`.
789 // Returns the actual rectangle resized to. (This may differ from `rect`, if
790 // the OS is unhappy with it. See bug 1786226.)
791 const auto doReposition = [&](auto rect) -> void {
792 static_assert(std::is_base_of_v<DesktopPixel,
793 std::remove_reference_t<decltype(rect)>>,
794 "doReposition requires a rectangle using desktop pixels");
796 if (MOZ_LOG_TEST(sBaseWidgetLog, LogLevel::Debug)) {
797 const DesktopRect previousSize =
798 GetScreenBounds() / GetDesktopToDeviceScale();
799 MOZ_LOG(sBaseWidgetLog, LogLevel::Debug,
800 ("before resize: " MOZ_FORMAT_RECT("%f"),
801 MOZ_SPLAT_RECT(previousSize)));
804 adjustOSChrome();
805 Resize(rect.X(), rect.Y(), rect.Width(), rect.Height(), true);
807 if (MOZ_LOG_TEST(sBaseWidgetLog, LogLevel::Warning)) {
808 // `rect` may have any underlying data type; coerce to float to
809 // simplify printf-style logging
810 const gfx::RectTyped<DesktopPixel, float> rectAsFloat{rect};
812 // The OS may have objected to the target position. That's not necessarily
813 // a problem -- it'll happen regularly on Macs with camera notches in the
814 // monitor, for instance (see bug 1786226) -- but it probably deserves to
815 // be called out.
817 // Since there's floating-point math involved, the actual values may be
818 // off by a few ulps -- as an upper bound, perhaps 8 * FLT_EPSILON *
819 // max(MOZ_SPLAT_RECT(rect)) -- but 0.01 should be several orders of
820 // magnitude bigger than that.
822 const auto postResizeRectRaw = GetScreenBounds();
823 const auto postResizeRect = postResizeRectRaw / GetDesktopToDeviceScale();
824 const bool succeeded = postResizeRect.WithinEpsilonOf(rectAsFloat, 0.01);
826 if (succeeded) {
827 MOZ_LOG(sBaseWidgetLog, LogLevel::Debug,
828 ("resized to: " MOZ_FORMAT_RECT("%f"),
829 MOZ_SPLAT_RECT(rectAsFloat)));
830 } else {
831 MOZ_LOG(sBaseWidgetLog, LogLevel::Warning,
832 ("attempted to resize to: " MOZ_FORMAT_RECT("%f"),
833 MOZ_SPLAT_RECT(rectAsFloat)));
834 MOZ_LOG(sBaseWidgetLog, LogLevel::Warning,
835 ("... but ended up at: " MOZ_FORMAT_RECT("%f"),
836 MOZ_SPLAT_RECT(postResizeRect)));
839 MOZ_LOG(
840 sBaseWidgetLog, LogLevel::Verbose,
841 ("(... which, before DPI adjustment, is:" MOZ_FORMAT_RECT("%d") ")",
842 MOZ_SPLAT_RECT(postResizeRectRaw)));
846 if (aFullScreen) {
847 if (!mSavedBounds) {
848 mSavedBounds = Some(FullscreenSavedState());
850 // save current position
851 mSavedBounds->windowRect = GetScreenBounds() / GetDesktopToDeviceScale();
853 nsCOMPtr<nsIScreen> screen = GetWidgetScreen();
854 if (!screen) {
855 return;
858 // Move to fill the screen.
859 doReposition(screen->GetRectDisplayPix());
860 // Save off the new position. (This may differ from GetRectDisplayPix(), if
861 // the OS was unhappy with it. See bug 1786226.)
862 mSavedBounds->screenRect = GetScreenBounds() / GetDesktopToDeviceScale();
863 } else {
864 if (!mSavedBounds) {
865 // This should never happen, at present, since we don't make windows
866 // fullscreen at their creation time; but it's not logically impossible.
867 MOZ_ASSERT(false, "fullscreen window did not have saved position");
868 return;
871 // Figure out where to go from here.
873 // Fortunately, since we're currently fullscreen (and other code should be
874 // handling _keeping_ us fullscreen even after display-layout changes),
875 // there's an obvious choice for which display we should attach to; all we
876 // need to determine is where on that display we should go.
878 const DesktopRect currentWinRect =
879 GetScreenBounds() / GetDesktopToDeviceScale();
881 // Optimization: if where we are is where we were, then where we originally
882 // came from is where we're going to go.
883 if (currentWinRect == DesktopRect(mSavedBounds->screenRect)) {
884 MOZ_LOG(sBaseWidgetLog, LogLevel::Debug,
885 ("no location change detected; returning to saved location"));
886 doReposition(mSavedBounds->windowRect);
887 return;
891 General case: figure out where we're going to go by dividing where we are
892 by where we were, and then multiplying by where we originally came from.
894 Less abstrusely: resize so that we occupy the same proportional position
895 on our current display after leaving fullscreen as we occupied on our
896 previous display before entering fullscreen.
898 (N.B.: We do not clamp. If we were only partially on the old display,
899 we'll be only partially on the new one, too.)
902 MOZ_LOG(sBaseWidgetLog, LogLevel::Debug,
903 ("location change detected; computing new destination"));
905 // splat: convert an arbitrary Rect into a tuple, for syntactic convenience.
906 const auto splat = [](auto rect) {
907 return std::tuple(rect.X(), rect.Y(), rect.Width(), rect.Height());
910 // remap: find the unique affine mapping which transforms `src` to `dst`,
911 // and apply it to `val`.
912 using Range = std::pair<float, float>;
913 const auto remap = [](Range dst, Range src, float val) {
914 // linear interpolation and its inverse: lerp(a, b, invlerp(a, b, t)) == t
915 const auto lerp = [](float lo, float hi, float t) {
916 return lo + t * (hi - lo);
918 const auto invlerp = [](float lo, float hi, float mid) {
919 return (mid - lo) / (hi - lo);
922 const auto [dst_a, dst_b] = dst;
923 const auto [src_a, src_b] = src;
924 return lerp(dst_a, dst_b, invlerp(src_a, src_b, val));
927 // original position
928 const auto [px, py, pw, ph] = splat(mSavedBounds->windowRect);
929 // source desktop rect
930 const auto [sx, sy, sw, sh] = splat(mSavedBounds->screenRect);
931 // target desktop rect
932 const auto [tx, ty, tw, th] = splat(currentWinRect);
934 const float nx = remap({tx, tx + tw}, {sx, sx + sw}, px);
935 const float ny = remap({ty, ty + th}, {sy, sy + sh}, py);
936 const float nw = remap({0, tw}, {0, sw}, pw);
937 const float nh = remap({0, th}, {0, sh}, ph);
939 doReposition(DesktopRect{nx, ny, nw, nh});
942 #undef MOZ_SPLAT_RECT
943 #undef MOZ_FORMAT_RECT
946 nsresult nsBaseWidget::MakeFullScreen(bool aFullScreen) {
947 InfallibleMakeFullScreen(aFullScreen);
948 return NS_OK;
951 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
952 nsBaseWidget* aWidget, gfxContext* aTarget, BufferMode aDoubleBuffering)
953 : mWidget(aWidget) {
954 WindowRenderer* renderer = mWidget->GetWindowRenderer();
955 if (renderer->AsFallback()) {
956 mRenderer = renderer->AsFallback();
957 mRenderer->SetTarget(aTarget, aDoubleBuffering);
961 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
962 if (mRenderer) {
963 mRenderer->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE);
967 bool nsBaseWidget::IsSmallPopup() const {
968 return mWindowType == WindowType::Popup && mPopupType != PopupType::Panel;
971 bool nsBaseWidget::ComputeShouldAccelerate() {
972 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING) &&
973 (WidgetTypeSupportsAcceleration() ||
974 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
977 bool nsBaseWidget::UseAPZ() {
978 return (gfxPlatform::AsyncPanZoomEnabled() &&
979 (mWindowType == WindowType::TopLevel ||
980 mWindowType == WindowType::Child ||
981 ((mWindowType == WindowType::Popup ||
982 mWindowType == WindowType::Dialog) &&
983 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
986 void nsBaseWidget::CreateCompositor() {
987 LayoutDeviceIntRect rect = GetBounds();
988 CreateCompositor(rect.Width(), rect.Height());
991 void nsIWidget::PauseOrResumeCompositor(bool aPause) {
992 auto* renderer = GetRemoteRenderer();
993 if (!renderer) {
994 return;
996 if (aPause) {
997 renderer->SendPause();
998 } else {
999 renderer->SendResume();
1003 already_AddRefed<GeckoContentController>
1004 nsBaseWidget::CreateRootContentController() {
1005 RefPtr<GeckoContentController> controller =
1006 new ChromeProcessController(this, mAPZEventState, mAPZC);
1007 return controller.forget();
1010 void nsBaseWidget::ConfigureAPZCTreeManager() {
1011 MOZ_ASSERT(NS_IsMainThread());
1012 MOZ_ASSERT(mAPZC);
1014 mAPZC->SetDPI(GetDPI());
1016 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
1017 KeyboardMap map = RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
1018 mAPZC->SetKeyboardMap(map);
1021 ContentReceivedInputBlockCallback callback(
1022 [treeManager = RefPtr{mAPZC.get()}](uint64_t aInputBlockId,
1023 bool aPreventDefault) {
1024 MOZ_ASSERT(NS_IsMainThread());
1025 treeManager->ContentReceivedInputBlock(aInputBlockId, aPreventDefault);
1027 mAPZEventState = new APZEventState(this, std::move(callback));
1029 mRootContentController = CreateRootContentController();
1030 if (mRootContentController) {
1031 mCompositorSession->SetContentController(mRootContentController);
1034 // When APZ is enabled, we can actually enable raw touch events because we
1035 // have code that can deal with them properly. If APZ is not enabled, this
1036 // function doesn't get called.
1037 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
1038 RegisterTouchWindow();
1042 void nsBaseWidget::ConfigureAPZControllerThread() {
1043 // By default the controller thread is the main thread.
1044 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
1047 void nsBaseWidget::SetConfirmedTargetAPZC(
1048 uint64_t aInputBlockId,
1049 const nsTArray<ScrollableLayerGuid>& aTargets) const {
1050 mAPZC->SetTargetAPZC(aInputBlockId, aTargets);
1053 void nsBaseWidget::UpdateZoomConstraints(
1054 const uint32_t& aPresShellId, const ScrollableLayerGuid::ViewID& aViewId,
1055 const Maybe<ZoomConstraints>& aConstraints) {
1056 if (!mCompositorSession || !mAPZC) {
1057 if (mInitialZoomConstraints) {
1058 MOZ_ASSERT(mInitialZoomConstraints->mPresShellID == aPresShellId);
1059 MOZ_ASSERT(mInitialZoomConstraints->mViewID == aViewId);
1060 if (!aConstraints) {
1061 mInitialZoomConstraints.reset();
1065 if (aConstraints) {
1066 // We have some constraints, but the compositor and APZC aren't created
1067 // yet. Save these so we can use them later.
1068 mInitialZoomConstraints = Some(
1069 InitialZoomConstraints(aPresShellId, aViewId, aConstraints.ref()));
1071 return;
1073 LayersId layersId = mCompositorSession->RootLayerTreeId();
1074 mAPZC->UpdateZoomConstraints(
1075 ScrollableLayerGuid(layersId, aPresShellId, aViewId), aConstraints);
1078 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC; }
1080 nsEventStatus nsBaseWidget::ProcessUntransformedAPZEvent(
1081 WidgetInputEvent* aEvent, const APZEventResult& aApzResult) {
1082 MOZ_ASSERT(NS_IsMainThread());
1083 ScrollableLayerGuid targetGuid = aApzResult.mTargetGuid;
1084 uint64_t inputBlockId = aApzResult.mInputBlockId;
1085 InputAPZContext context(aApzResult.mTargetGuid, inputBlockId,
1086 aApzResult.GetStatus());
1088 // Make a copy of the original event for the APZCCallbackHelper helpers that
1089 // we call later, because the event passed to DispatchEvent can get mutated in
1090 // ways that we don't want (i.e. touch points can get stripped out).
1091 nsEventStatus status;
1092 UniquePtr<WidgetEvent> original(aEvent->Duplicate());
1093 DispatchEvent(aEvent, status);
1095 if (mAPZC && !InputAPZContext::WasRoutedToChildProcess() &&
1096 !InputAPZContext::WasDropped() && inputBlockId) {
1097 // EventStateManager did not route the event into the child process and
1098 // the event was dispatched in the parent process.
1099 // It's safe to communicate to APZ that the event has been processed.
1100 // Note that here aGuid.mLayersId might be different from
1101 // mCompositorSession->RootLayerTreeId() because the event might have gotten
1102 // hit-tested by APZ to be targeted at a child process, but a parent process
1103 // event listener called preventDefault on it. In that case aGuid.mLayersId
1104 // would still be the layers id for the child process, but the event would
1105 // not have actually gotten routed to the child process. The main-thread
1106 // hit-test result therefore needs to use the parent process layers id.
1107 LayersId rootLayersId = mCompositorSession->RootLayerTreeId();
1109 RefPtr<DisplayportSetListener> postLayerization;
1110 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
1111 nsTArray<TouchBehaviorFlags> allowedTouchBehaviors;
1112 if (touchEvent->mMessage == eTouchStart) {
1113 auto& originalEvent = *original->AsTouchEvent();
1114 MOZ_ASSERT(NS_IsMainThread());
1115 allowedTouchBehaviors = TouchActionHelper::GetAllowedTouchBehavior(
1116 this, GetDocument(), originalEvent);
1117 if (!allowedTouchBehaviors.IsEmpty()) {
1118 mAPZC->SetAllowedTouchBehavior(inputBlockId, allowedTouchBehaviors);
1120 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1121 this, GetDocument(), originalEvent, rootLayersId, inputBlockId);
1123 mAPZEventState->ProcessTouchEvent(*touchEvent, targetGuid, inputBlockId,
1124 aApzResult.GetStatus(), status,
1125 std::move(allowedTouchBehaviors));
1126 } else if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1127 MOZ_ASSERT(wheelEvent->mFlags.mHandledByAPZ);
1128 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1129 this, GetDocument(), *original->AsWheelEvent(), rootLayersId,
1130 inputBlockId);
1131 if (wheelEvent->mCanTriggerSwipe) {
1132 ReportSwipeStarted(inputBlockId, wheelEvent->TriggersSwipe());
1134 mAPZEventState->ProcessWheelEvent(*wheelEvent, inputBlockId);
1135 } else if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1136 MOZ_ASSERT(mouseEvent->mFlags.mHandledByAPZ);
1137 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1138 this, GetDocument(), *original->AsMouseEvent(), rootLayersId,
1139 inputBlockId);
1140 mAPZEventState->ProcessMouseEvent(*mouseEvent, inputBlockId);
1142 if (postLayerization) {
1143 postLayerization->Register();
1147 return status;
1150 template <class InputType, class EventType>
1151 class DispatchEventOnMainThread : public Runnable {
1152 public:
1153 DispatchEventOnMainThread(const InputType& aInput, nsBaseWidget* aWidget,
1154 const APZEventResult& aAPZResult)
1155 : mozilla::Runnable("DispatchEventOnMainThread"),
1156 mInput(aInput),
1157 mWidget(aWidget),
1158 mAPZResult(aAPZResult) {}
1160 NS_IMETHOD Run() override {
1161 EventType event = mInput.ToWidgetEvent(mWidget);
1162 mWidget->ProcessUntransformedAPZEvent(&event, mAPZResult);
1163 return NS_OK;
1166 private:
1167 InputType mInput;
1168 nsBaseWidget* mWidget;
1169 APZEventResult mAPZResult;
1172 template <class InputType, class EventType>
1173 class DispatchInputOnControllerThread : public Runnable {
1174 public:
1175 DispatchInputOnControllerThread(const EventType& aEvent,
1176 IAPZCTreeManager* aAPZC,
1177 nsBaseWidget* aWidget)
1178 : mozilla::Runnable("DispatchInputOnControllerThread"),
1179 mMainMessageLoop(MessageLoop::current()),
1180 mInput(aEvent),
1181 mAPZC(aAPZC),
1182 mWidget(aWidget) {}
1184 NS_IMETHOD Run() override {
1185 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(mInput);
1186 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1187 return NS_OK;
1189 RefPtr<Runnable> r = new DispatchEventOnMainThread<InputType, EventType>(
1190 mInput, mWidget, result);
1191 mMainMessageLoop->PostTask(r.forget());
1192 return NS_OK;
1195 private:
1196 MessageLoop* mMainMessageLoop;
1197 InputType mInput;
1198 RefPtr<IAPZCTreeManager> mAPZC;
1199 nsBaseWidget* mWidget;
1202 void nsBaseWidget::DispatchTouchInput(MultiTouchInput& aInput,
1203 uint16_t aInputSource) {
1204 MOZ_ASSERT(NS_IsMainThread());
1205 MOZ_ASSERT(aInputSource ==
1206 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH ||
1207 aInputSource == mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN);
1208 if (mAPZC) {
1209 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1211 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1212 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1213 return;
1216 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1217 ProcessUntransformedAPZEvent(&event, result);
1218 } else {
1219 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1221 nsEventStatus status;
1222 DispatchEvent(&event, status);
1226 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput& aInput) {
1227 MOZ_ASSERT(NS_IsMainThread());
1228 if (mAPZC) {
1229 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1231 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1232 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1233 return;
1236 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1237 ProcessUntransformedAPZEvent(&event, result);
1238 } else {
1239 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1240 nsEventStatus status;
1241 DispatchEvent(&event, status);
1245 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput& aInput) {
1246 MOZ_ASSERT(NS_IsMainThread());
1247 if (mAPZC) {
1248 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1249 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1251 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1252 return;
1254 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1255 ProcessUntransformedAPZEvent(&event, result);
1256 } else {
1257 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1258 nsEventStatus status;
1259 DispatchEvent(&event, status);
1263 nsIWidget::ContentAndAPZEventStatus nsBaseWidget::DispatchInputEvent(
1264 WidgetInputEvent* aEvent) {
1265 nsIWidget::ContentAndAPZEventStatus status;
1266 MOZ_ASSERT(NS_IsMainThread());
1267 if (mAPZC) {
1268 if (APZThreadUtils::IsControllerThread()) {
1269 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1270 status.mApzStatus = result.GetStatus();
1271 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1272 return status;
1274 status.mContentStatus = ProcessUntransformedAPZEvent(aEvent, result);
1275 return status;
1277 if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1278 RefPtr<Runnable> r =
1279 new DispatchInputOnControllerThread<ScrollWheelInput,
1280 WidgetWheelEvent>(*wheelEvent,
1281 mAPZC, this);
1282 APZThreadUtils::RunOnControllerThread(std::move(r));
1283 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1284 return status;
1286 if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1287 RefPtr<Runnable> r =
1288 new DispatchInputOnControllerThread<MouseInput, WidgetMouseEvent>(
1289 *mouseEvent, mAPZC, this);
1290 APZThreadUtils::RunOnControllerThread(std::move(r));
1291 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1292 return status;
1294 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
1295 RefPtr<Runnable> r =
1296 new DispatchInputOnControllerThread<MultiTouchInput,
1297 WidgetTouchEvent>(*touchEvent,
1298 mAPZC, this);
1299 APZThreadUtils::RunOnControllerThread(std::move(r));
1300 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1301 return status;
1303 // Allow dispatching keyboard events on Gecko thread.
1304 MOZ_ASSERT(aEvent->AsKeyboardEvent());
1307 DispatchEvent(aEvent, status.mContentStatus);
1308 return status;
1311 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent* aEvent) {
1312 MOZ_ASSERT(NS_IsMainThread());
1313 if (mAPZC) {
1314 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1315 mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1319 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent& event) {
1320 nsEventStatus status;
1321 DispatchEvent(&event, status);
1322 return ConvertStatus(status);
1325 Document* nsBaseWidget::GetDocument() const {
1326 if (mWidgetListener) {
1327 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1328 return presShell->GetDocument();
1331 return nullptr;
1334 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1335 // Parent directly listens to the vsync source whereas
1336 // child process communicate via IPC
1337 // Should be called AFTER gfxPlatform is initialized
1338 if (XRE_IsParentProcess()) {
1339 if (!mCompositorVsyncDispatcherLock) {
1340 mCompositorVsyncDispatcherLock =
1341 MakeUnique<Mutex>("mCompositorVsyncDispatcherLock");
1343 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1344 if (!mCompositorVsyncDispatcher) {
1345 RefPtr<VsyncDispatcher> vsyncDispatcher =
1346 gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
1347 mCompositorVsyncDispatcher =
1348 new CompositorVsyncDispatcher(std::move(vsyncDispatcher));
1353 already_AddRefed<CompositorVsyncDispatcher>
1354 nsBaseWidget::GetCompositorVsyncDispatcher() {
1355 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
1357 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1358 RefPtr<CompositorVsyncDispatcher> dispatcher = mCompositorVsyncDispatcher;
1359 return dispatcher.forget();
1362 already_AddRefed<WebRenderLayerManager> nsBaseWidget::CreateCompositorSession(
1363 int aWidth, int aHeight, CompositorOptions* aOptionsOut) {
1364 MOZ_ASSERT(aOptionsOut);
1366 do {
1367 CreateCompositorVsyncDispatcher();
1369 gfx::GPUProcessManager* gpu = gfx::GPUProcessManager::Get();
1370 // Make sure GPU process is ready for use.
1371 // If it failed to connect to GPU process, GPU process usage is disabled in
1372 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1373 nsresult rv = gpu->EnsureGPUReady();
1374 if (NS_WARN_IF(rv == NS_ERROR_ILLEGAL_DURING_SHUTDOWN)) {
1375 return nullptr;
1378 // If widget type does not supports acceleration, we may be allowed to use
1379 // software WebRender instead.
1380 bool supportsAcceleration = WidgetTypeSupportsAcceleration();
1381 bool enableSWWR = true;
1382 if (supportsAcceleration ||
1383 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1384 enableSWWR = gfx::gfxVars::UseSoftwareWebRender();
1386 bool enableAPZ = UseAPZ();
1387 CompositorOptions options(enableAPZ, enableSWWR);
1389 #ifdef XP_WIN
1390 if (supportsAcceleration) {
1391 options.SetAllowSoftwareWebRenderD3D11(
1392 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1394 if (mNeedFastSnaphot) {
1395 options.SetNeedFastSnaphot(true);
1397 #elif defined(MOZ_WIDGET_ANDROID)
1398 MOZ_ASSERT(supportsAcceleration);
1399 options.SetAllowSoftwareWebRenderOGL(
1400 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1401 #elif defined(MOZ_WIDGET_GTK)
1402 if (supportsAcceleration) {
1403 options.SetAllowSoftwareWebRenderOGL(
1404 gfx::gfxVars::AllowSoftwareWebRenderOGL());
1406 #endif
1408 #ifdef MOZ_WIDGET_ANDROID
1409 // Unconditionally set the compositor as initially paused, as we have not
1410 // yet had a chance to send the compositor surface to the GPU process. We
1411 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1412 // where we will also resume the compositor if required.
1413 options.SetInitiallyPaused(true);
1414 #else
1415 options.SetInitiallyPaused(CompositorInitiallyPaused());
1416 #endif
1418 RefPtr<WebRenderLayerManager> lm = new WebRenderLayerManager(this);
1420 uint64_t innerWindowId = 0;
1421 if (Document* doc = GetDocument()) {
1422 innerWindowId = doc->InnerWindowID();
1425 bool retry = false;
1426 mCompositorSession = gpu->CreateTopLevelCompositor(
1427 this, lm, GetDefaultScale(), options, UseExternalCompositingSurface(),
1428 gfx::IntSize(aWidth, aHeight), innerWindowId, &retry);
1430 if (mCompositorSession) {
1431 TextureFactoryIdentifier textureFactoryIdentifier;
1432 nsCString error;
1433 lm->Initialize(mCompositorSession->GetCompositorBridgeChild(),
1434 wr::AsPipelineId(mCompositorSession->RootLayerTreeId()),
1435 &textureFactoryIdentifier, error);
1436 if (textureFactoryIdentifier.mParentBackend != LayersBackend::LAYERS_WR) {
1437 retry = true;
1438 DestroyCompositor();
1439 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1440 gfx::GPUProcessManager::Get()->DisableWebRender(
1441 wr::WebRenderError::INITIALIZE, error);
1445 // We need to retry in a loop because the act of failing to create the
1446 // compositor can change our state (e.g. disable WebRender).
1447 if (mCompositorSession || !retry) {
1448 *aOptionsOut = options;
1449 return lm.forget();
1451 } while (true);
1454 void nsBaseWidget::CreateCompositor(int aWidth, int aHeight) {
1455 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1456 gfxPlatform::GetPlatform();
1458 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1459 "This function assumes OMTC");
1461 MOZ_ASSERT(!mCompositorSession && !mCompositorBridgeChild,
1462 "Should have properly cleaned up the previous PCompositor pair "
1463 "beforehand");
1465 if (mCompositorBridgeChild) {
1466 mCompositorBridgeChild->Destroy();
1469 // Recreating this is tricky, as we may still have an old and we need
1470 // to make sure it's properly destroyed by calling DestroyCompositor!
1472 // If we've already received a shutdown notification, don't try
1473 // create a new compositor.
1474 if (!mShutdownObserver) {
1475 return;
1478 // The controller thread must be configured before the compositor
1479 // session is created, so that the input bridge runs on the right
1480 // thread.
1481 ConfigureAPZControllerThread();
1483 CompositorOptions options;
1484 RefPtr<WebRenderLayerManager> lm =
1485 CreateCompositorSession(aWidth, aHeight, &options);
1486 if (!lm) {
1487 return;
1490 MOZ_ASSERT(mCompositorSession);
1491 mCompositorBridgeChild = mCompositorSession->GetCompositorBridgeChild();
1492 SetCompositorWidgetDelegate(
1493 mCompositorSession->GetCompositorWidgetDelegate());
1495 if (options.UseAPZ()) {
1496 mAPZC = mCompositorSession->GetAPZCTreeManager();
1497 ConfigureAPZCTreeManager();
1498 } else {
1499 mAPZC = nullptr;
1502 if (mInitialZoomConstraints) {
1503 UpdateZoomConstraints(mInitialZoomConstraints->mPresShellID,
1504 mInitialZoomConstraints->mViewID,
1505 Some(mInitialZoomConstraints->mConstraints));
1506 mInitialZoomConstraints.reset();
1509 TextureFactoryIdentifier textureFactoryIdentifier =
1510 lm->GetTextureFactoryIdentifier();
1511 MOZ_ASSERT(textureFactoryIdentifier.mParentBackend ==
1512 LayersBackend::LAYERS_WR);
1513 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1514 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1516 WindowUsesOMTC();
1518 mWindowRenderer = std::move(lm);
1520 // Only track compositors for top-level windows, since other window types
1521 // may use the basic compositor. Except on the OS X - see bug 1306383
1522 #if defined(XP_MACOSX)
1523 bool getCompositorFromThisWindow = true;
1524 #else
1525 bool getCompositorFromThisWindow = mWindowType == WindowType::TopLevel;
1526 #endif
1528 if (getCompositorFromThisWindow) {
1529 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1530 mWindowRenderer->GetCompositorBackendType());
1534 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession* aSession) {
1535 MOZ_ASSERT(aSession == mCompositorSession);
1536 DestroyLayerManager();
1539 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1540 return gfxPlatform::UsesOffMainThreadCompositing();
1543 WindowRenderer* nsBaseWidget::GetWindowRenderer() {
1544 if (!mWindowRenderer) {
1545 if (!mShutdownObserver) {
1546 // We are shutting down, do not try to re-create a LayerManager
1547 return nullptr;
1549 // Try to use an async compositor first, if possible
1550 if (ShouldUseOffMainThreadCompositing()) {
1551 CreateCompositor();
1554 if (!mWindowRenderer) {
1555 mWindowRenderer = CreateFallbackRenderer();
1558 return mWindowRenderer;
1561 WindowRenderer* nsBaseWidget::CreateFallbackRenderer() {
1562 return new FallbackRenderer;
1565 CompositorBridgeChild* nsBaseWidget::GetRemoteRenderer() {
1566 return mCompositorBridgeChild;
1569 void nsBaseWidget::ClearCachedWebrenderResources() {
1570 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
1571 return;
1573 mWindowRenderer->AsWebRender()->ClearCachedResources();
1576 void nsBaseWidget::ClearWebrenderAnimationResources() {
1577 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
1578 return;
1580 mWindowRenderer->AsWebRender()->ClearAnimationResources();
1583 bool nsBaseWidget::SetNeedFastSnaphot() {
1584 MOZ_ASSERT(XRE_IsParentProcess());
1585 MOZ_ASSERT(!mCompositorSession);
1587 if (!XRE_IsParentProcess() || mCompositorSession) {
1588 return false;
1591 mNeedFastSnaphot = true;
1592 return true;
1595 already_AddRefed<gfx::DrawTarget> nsBaseWidget::StartRemoteDrawing() {
1596 return nullptr;
1599 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA; }
1601 //-------------------------------------------------------------------------
1603 // Destroy the window
1605 //-------------------------------------------------------------------------
1606 void nsBaseWidget::OnDestroy() {
1607 if (mTextEventDispatcher) {
1608 mTextEventDispatcher->OnDestroyWidget();
1609 // Don't release it until this widget actually released because after this
1610 // is called, TextEventDispatcher() may create it again.
1613 // If this widget is being destroyed, let the APZ code know to drop references
1614 // to this widget. Callers of this function all should be holding a deathgrip
1615 // on this widget already.
1616 ReleaseContentController();
1619 void nsBaseWidget::MoveClient(const DesktopPoint& aOffset) {
1620 LayoutDeviceIntPoint clientOffset(GetClientOffset());
1622 // GetClientOffset returns device pixels; scale back to desktop pixels
1623 // if that's what this widget uses for the Move/Resize APIs
1624 if (BoundsUseDesktopPixels()) {
1625 DesktopPoint desktopOffset = clientOffset / GetDesktopToDeviceScale();
1626 Move(aOffset.x - desktopOffset.x, aOffset.y - desktopOffset.y);
1627 } else {
1628 LayoutDevicePoint layoutOffset = aOffset * GetDesktopToDeviceScale();
1629 Move(layoutOffset.x - LayoutDeviceCoord(clientOffset.x),
1630 layoutOffset.y - LayoutDeviceCoord(clientOffset.y));
1634 void nsBaseWidget::ResizeClient(const DesktopSize& aSize, bool aRepaint) {
1635 NS_ASSERTION((aSize.width >= 0), "Negative width passed to ResizeClient");
1636 NS_ASSERTION((aSize.height >= 0), "Negative height passed to ResizeClient");
1638 LayoutDeviceIntRect clientBounds = GetClientBounds();
1640 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1641 // if that's what this widget uses for the Move/Resize APIs
1642 if (BoundsUseDesktopPixels()) {
1643 DesktopSize desktopDelta =
1644 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1645 clientBounds.Size()) /
1646 GetDesktopToDeviceScale();
1647 Resize(aSize.width + desktopDelta.width, aSize.height + desktopDelta.height,
1648 aRepaint);
1649 } else {
1650 LayoutDeviceSize layoutSize = aSize * GetDesktopToDeviceScale();
1651 Resize(mBounds.Width() + (layoutSize.width - clientBounds.Width()),
1652 mBounds.Height() + (layoutSize.height - clientBounds.Height()),
1653 aRepaint);
1657 void nsBaseWidget::ResizeClient(const DesktopRect& aRect, bool aRepaint) {
1658 NS_ASSERTION((aRect.Width() >= 0), "Negative width passed to ResizeClient");
1659 NS_ASSERTION((aRect.Height() >= 0), "Negative height passed to ResizeClient");
1661 LayoutDeviceIntRect clientBounds = GetClientBounds();
1662 LayoutDeviceIntPoint clientOffset = GetClientOffset();
1663 DesktopToLayoutDeviceScale scale = GetDesktopToDeviceScale();
1665 if (BoundsUseDesktopPixels()) {
1666 DesktopPoint desktopOffset = clientOffset / scale;
1667 DesktopSize desktopDelta =
1668 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1669 clientBounds.Size()) /
1670 scale;
1671 Resize(aRect.X() - desktopOffset.x, aRect.Y() - desktopOffset.y,
1672 aRect.Width() + desktopDelta.width,
1673 aRect.Height() + desktopDelta.height, aRepaint);
1674 } else {
1675 LayoutDeviceRect layoutRect = aRect * scale;
1676 Resize(layoutRect.X() - clientOffset.x, layoutRect.Y() - clientOffset.y,
1677 layoutRect.Width() + mBounds.Width() - clientBounds.Width(),
1678 layoutRect.Height() + mBounds.Height() - clientBounds.Height(),
1679 aRepaint);
1683 //-------------------------------------------------------------------------
1685 // Bounds
1687 //-------------------------------------------------------------------------
1690 * If the implementation of nsWindow supports borders this method MUST be
1691 * overridden
1694 LayoutDeviceIntRect nsBaseWidget::GetClientBounds() { return GetBounds(); }
1697 * If the implementation of nsWindow supports borders this method MUST be
1698 * overridden
1701 LayoutDeviceIntRect nsBaseWidget::GetBounds() { return mBounds; }
1704 * If the implementation of nsWindow uses a local coordinate system within the
1705 *window, this method must be overridden
1708 LayoutDeviceIntRect nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1710 nsresult nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect& aRect) {
1711 if (SizeMode() != nsSizeMode_Normal) {
1712 return NS_ERROR_FAILURE;
1714 aRect = GetScreenBounds();
1715 return NS_OK;
1718 LayoutDeviceIntPoint nsBaseWidget::GetClientOffset() {
1719 return LayoutDeviceIntPoint(0, 0);
1722 nsresult nsBaseWidget::SetNonClientMargins(const LayoutDeviceIntMargin&) {
1723 return NS_ERROR_NOT_IMPLEMENTED;
1726 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin) {}
1728 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1730 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1732 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect* aResizerRect) {
1733 return false;
1737 * Modifies aFile to point at an icon file with the given name and suffix. The
1738 * suffix may correspond to a file extension with leading '.' if appropriate.
1739 * Returns true if the icon file exists and can be read.
1741 static bool ResolveIconNameHelper(nsIFile* aFile, const nsAString& aIconName,
1742 const nsAString& aIconSuffix) {
1743 aFile->Append(u"icons"_ns);
1744 aFile->Append(u"default"_ns);
1745 aFile->Append(aIconName + aIconSuffix);
1747 bool readable;
1748 return NS_SUCCEEDED(aFile->IsReadable(&readable)) && readable;
1752 * Resolve the given icon name into a local file object. This method is
1753 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1754 * platform specific icon file suffix (e.g., ".ico" under Win32).
1756 * If no file is found matching the given parameters, then null is returned.
1758 void nsBaseWidget::ResolveIconName(const nsAString& aIconName,
1759 const nsAString& aIconSuffix,
1760 nsIFile** aResult) {
1761 *aResult = nullptr;
1763 nsCOMPtr<nsIProperties> dirSvc =
1764 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
1765 if (!dirSvc) return;
1767 // first check auxilary chrome directories
1769 nsCOMPtr<nsISimpleEnumerator> dirs;
1770 dirSvc->Get(NS_APP_CHROME_DIR_LIST, NS_GET_IID(nsISimpleEnumerator),
1771 getter_AddRefs(dirs));
1772 if (dirs) {
1773 bool hasMore;
1774 while (NS_SUCCEEDED(dirs->HasMoreElements(&hasMore)) && hasMore) {
1775 nsCOMPtr<nsISupports> element;
1776 dirs->GetNext(getter_AddRefs(element));
1777 if (!element) continue;
1778 nsCOMPtr<nsIFile> file = do_QueryInterface(element);
1779 if (!file) continue;
1780 if (ResolveIconNameHelper(file, aIconName, aIconSuffix)) {
1781 NS_ADDREF(*aResult = file);
1782 return;
1787 // then check the main app chrome directory
1789 nsCOMPtr<nsIFile> file;
1790 dirSvc->Get(NS_APP_CHROME_DIR, NS_GET_IID(nsIFile), getter_AddRefs(file));
1791 if (file && ResolveIconNameHelper(file, aIconName, aIconSuffix))
1792 NS_ADDREF(*aResult = file);
1795 void nsBaseWidget::SetSizeConstraints(const SizeConstraints& aConstraints) {
1796 mSizeConstraints = aConstraints;
1798 // Popups are constrained during layout, and we don't want to synchronously
1799 // paint from reflow, so bail out... This is not great, but it's no worse than
1800 // what we used to do.
1802 // The right fix here is probably making constraint changes go through the
1803 // view manager and such.
1804 if (mWindowType == WindowType::Popup) {
1805 return;
1808 // If the current size doesn't meet the new constraints, trigger a
1809 // resize to apply it. Note that, we don't want to invoke Resize if
1810 // the new constraints don't affect the current size, because Resize
1811 // implementation on some platforms may touch other geometry even if
1812 // the size don't need to change.
1813 LayoutDeviceIntSize curSize = mBounds.Size();
1814 LayoutDeviceIntSize clampedSize =
1815 Max(aConstraints.mMinSize, Min(aConstraints.mMaxSize, curSize));
1816 if (clampedSize != curSize) {
1817 gfx::Size size;
1818 if (BoundsUseDesktopPixels()) {
1819 DesktopSize desktopSize = clampedSize / GetDesktopToDeviceScale();
1820 size = desktopSize.ToUnknownSize();
1821 } else {
1822 size = gfx::Size(clampedSize.ToUnknownSize());
1824 Resize(size.width, size.height, true);
1828 const widget::SizeConstraints nsBaseWidget::GetSizeConstraints() {
1829 return mSizeConstraints;
1832 // static
1833 nsIRollupListener* nsBaseWidget::GetActiveRollupListener() {
1834 // TODO: Simplify this.
1835 return nsXULPopupManager::GetInstance();
1838 void nsBaseWidget::NotifyWindowDestroyed() {
1839 if (!mWidgetListener) return;
1841 nsCOMPtr<nsIAppWindow> window = mWidgetListener->GetAppWindow();
1842 nsCOMPtr<nsIBaseWindow> appWindow(do_QueryInterface(window));
1843 if (appWindow) {
1844 appWindow->Destroy();
1848 void nsBaseWidget::NotifyWindowMoved(int32_t aX, int32_t aY,
1849 ByMoveToRect aByMoveToRect) {
1850 if (mWidgetListener) {
1851 mWidgetListener->WindowMoved(this, aX, aY, aByMoveToRect);
1854 if (mIMEHasFocus && IMENotificationRequestsRef().WantPositionChanged()) {
1855 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE));
1859 void nsBaseWidget::NotifySizeMoveDone() {
1860 if (!mWidgetListener) {
1861 return;
1863 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1864 presShell->WindowSizeMoveDone();
1868 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind) {
1869 LookAndFeel::NotifyChangedAllWindows(aKind);
1872 nsresult nsBaseWidget::NotifyIME(const IMENotification& aIMENotification) {
1873 if (mIMEHasQuit) {
1874 return NS_OK;
1876 switch (aIMENotification.mMessage) {
1877 case REQUEST_TO_COMMIT_COMPOSITION:
1878 case REQUEST_TO_CANCEL_COMPOSITION:
1879 // We should send request to IME only when there is a TextEventDispatcher
1880 // instance (this means that this widget has dispatched at least one
1881 // composition event or keyboard event) and the it has composition.
1882 // Otherwise, there is nothing to do.
1883 // Note that if current input transaction is for native input events,
1884 // TextEventDispatcher::NotifyIME() will call
1885 // TextEventDispatcherListener::NotifyIME().
1886 if (mTextEventDispatcher && mTextEventDispatcher->IsComposing()) {
1887 return mTextEventDispatcher->NotifyIME(aIMENotification);
1889 return NS_OK;
1890 default: {
1891 if (aIMENotification.mMessage == NOTIFY_IME_OF_FOCUS) {
1892 mIMEHasFocus = true;
1894 EnsureTextEventDispatcher();
1895 // TextEventDispatcher::NotifyIME() will always call
1896 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1897 // input transaction is for synthesized events for automated tests,
1898 // notifications will be sent to native IME.
1899 nsresult rv = mTextEventDispatcher->NotifyIME(aIMENotification);
1900 if (aIMENotification.mMessage == NOTIFY_IME_OF_BLUR) {
1901 mIMEHasFocus = false;
1903 return rv;
1908 void nsBaseWidget::EnsureTextEventDispatcher() {
1909 if (mTextEventDispatcher) {
1910 return;
1912 mTextEventDispatcher = new TextEventDispatcher(this);
1915 nsIWidget::NativeIMEContext nsBaseWidget::GetNativeIMEContext() {
1916 if (mTextEventDispatcher && mTextEventDispatcher->GetPseudoIMEContext()) {
1917 // If we already have a TextEventDispatcher and it's working with
1918 // a TextInputProcessor, we need to return pseudo IME context since
1919 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1920 // on the pseudo IME context in such case.
1921 NativeIMEContext pseudoIMEContext;
1922 pseudoIMEContext.InitWithRawNativeIMEContext(
1923 mTextEventDispatcher->GetPseudoIMEContext());
1924 return pseudoIMEContext;
1926 return NativeIMEContext(this);
1929 nsIWidget::TextEventDispatcher* nsBaseWidget::GetTextEventDispatcher() {
1930 EnsureTextEventDispatcher();
1931 return mTextEventDispatcher;
1934 void* nsBaseWidget::GetPseudoIMEContext() {
1935 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
1936 if (!dispatcher) {
1937 return nullptr;
1939 return dispatcher->GetPseudoIMEContext();
1942 TextEventDispatcherListener*
1943 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1944 // TODO: If all platforms supported use of TextEventDispatcher for handling
1945 // native IME and keyboard events, this method should be removed since
1946 // in such case, this is overridden by all the subclasses.
1947 return nullptr;
1950 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId,
1951 const ScrollableLayerGuid::ViewID& aViewId,
1952 const CSSRect& aRect, const uint32_t& aFlags) {
1953 if (!mCompositorSession || !mAPZC) {
1954 return;
1956 LayersId layerId = mCompositorSession->RootLayerTreeId();
1957 mAPZC->ZoomToRect(ScrollableLayerGuid(layerId, aPresShellId, aViewId),
1958 ZoomTarget{aRect}, aFlags);
1961 #ifdef ACCESSIBILITY
1963 a11y::LocalAccessible* nsBaseWidget::GetRootAccessible() {
1964 NS_ENSURE_TRUE(mWidgetListener, nullptr);
1966 PresShell* presShell = mWidgetListener->GetPresShell();
1967 NS_ENSURE_TRUE(presShell, nullptr);
1969 // If container is null then the presshell is not active. This often happens
1970 // when a preshell is being held onto for fastback.
1971 nsPresContext* presContext = presShell->GetPresContext();
1972 NS_ENSURE_TRUE(presContext->GetContainerWeak(), nullptr);
1974 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1975 // make sure it's not created at unsafe times.
1976 nsAccessibilityService* accService = GetOrCreateAccService();
1977 if (accService) {
1978 return accService->GetRootDocumentAccessible(
1979 presShell, nsContentUtils::IsSafeToRunScript());
1982 return nullptr;
1985 #endif // ACCESSIBILITY
1987 void nsBaseWidget::StartAsyncScrollbarDrag(
1988 const AsyncDragMetrics& aDragMetrics) {
1989 if (!AsyncPanZoomEnabled()) {
1990 return;
1993 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession);
1995 LayersId layersId = mCompositorSession->RootLayerTreeId();
1996 ScrollableLayerGuid guid(layersId, aDragMetrics.mPresShellId,
1997 aDragMetrics.mViewId);
1999 mAPZC->StartScrollbarDrag(guid, aDragMetrics);
2002 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
2003 const ScrollableLayerGuid& aGuid) {
2004 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2006 return mAPZC->StartAutoscroll(aGuid, aAnchorLocation);
2009 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid& aGuid) {
2010 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2012 mAPZC->StopAutoscroll(aGuid);
2015 LayersId nsBaseWidget::GetRootLayerTreeId() {
2016 return mCompositorSession ? mCompositorSession->RootLayerTreeId()
2017 : LayersId{0};
2020 already_AddRefed<widget::Screen> nsBaseWidget::GetWidgetScreen() {
2021 ScreenManager& screenManager = ScreenManager::GetSingleton();
2022 LayoutDeviceIntRect bounds = GetScreenBounds();
2023 DesktopIntRect deskBounds = RoundedToInt(bounds / GetDesktopToDeviceScale());
2024 return screenManager.ScreenForRect(deskBounds);
2027 mozilla::DesktopToLayoutDeviceScale
2028 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
2029 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
2030 ->GetDesktopToDeviceScale();
2033 nsresult nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint,
2034 bool aLongTap,
2035 nsIObserver* aObserver) {
2036 AutoObserverNotifier notifier(aObserver, "touchtap");
2038 if (sPointerIdCounter > TOUCH_INJECT_MAX_POINTS) {
2039 sPointerIdCounter = 0;
2041 int pointerId = sPointerIdCounter;
2042 sPointerIdCounter++;
2043 nsresult rv = SynthesizeNativeTouchPoint(pointerId, TOUCH_CONTACT, aPoint,
2044 1.0, 90, nullptr);
2045 if (NS_FAILED(rv)) {
2046 return rv;
2049 if (!aLongTap) {
2050 return SynthesizeNativeTouchPoint(pointerId, TOUCH_REMOVE, aPoint, 0, 0,
2051 nullptr);
2054 // initiate a long tap
2055 int elapse = Preferences::GetInt("ui.click_hold_context_menus.delay",
2056 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC);
2057 if (!mLongTapTimer) {
2058 mLongTapTimer = NS_NewTimer();
2059 if (!mLongTapTimer) {
2060 SynthesizeNativeTouchPoint(pointerId, TOUCH_CANCEL, aPoint, 0, 0,
2061 nullptr);
2062 return NS_ERROR_UNEXPECTED;
2064 // Windows requires recuring events, so we set this to a smaller window
2065 // than the pref value.
2066 int timeout = elapse;
2067 if (timeout > TOUCH_INJECT_PUMP_TIMER_MSEC) {
2068 timeout = TOUCH_INJECT_PUMP_TIMER_MSEC;
2070 mLongTapTimer->InitWithNamedFuncCallback(
2071 OnLongTapTimerCallback, this, timeout, nsITimer::TYPE_REPEATING_SLACK,
2072 "nsIWidget::SynthesizeNativeTouchTap");
2075 // If we already have a long tap pending, cancel it. We only allow one long
2076 // tap to be active at a time.
2077 if (mLongTapTouchPoint) {
2078 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
2079 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
2082 mLongTapTouchPoint = MakeUnique<LongTapInfo>(
2083 pointerId, aPoint, TimeDuration::FromMilliseconds(elapse), aObserver);
2084 notifier.SkipNotification(); // we'll do it in the long-tap callback
2085 return NS_OK;
2088 // static
2089 void nsIWidget::OnLongTapTimerCallback(nsITimer* aTimer, void* aClosure) {
2090 auto* self = static_cast<nsIWidget*>(aClosure);
2092 if ((self->mLongTapTouchPoint->mStamp + self->mLongTapTouchPoint->mDuration) >
2093 TimeStamp::Now()) {
2094 #ifdef XP_WIN
2095 // Windows needs us to keep pumping feedback to the digitizer, so update
2096 // the pointer id with the same position.
2097 self->SynthesizeNativeTouchPoint(
2098 self->mLongTapTouchPoint->mPointerId, TOUCH_CONTACT,
2099 self->mLongTapTouchPoint->mPosition, 1.0, 90, nullptr);
2100 #endif
2101 return;
2104 AutoObserverNotifier notifier(self->mLongTapTouchPoint->mObserver,
2105 "touchtap");
2107 // finished, remove the touch point
2108 self->mLongTapTimer->Cancel();
2109 self->mLongTapTimer = nullptr;
2110 self->SynthesizeNativeTouchPoint(
2111 self->mLongTapTouchPoint->mPointerId, TOUCH_REMOVE,
2112 self->mLongTapTouchPoint->mPosition, 0, 0, nullptr);
2113 self->mLongTapTouchPoint = nullptr;
2116 float nsIWidget::GetFallbackDPI() {
2117 RefPtr<const Screen> primaryScreen =
2118 ScreenManager::GetSingleton().GetPrimaryScreen();
2119 return primaryScreen->GetDPI();
2122 CSSToLayoutDeviceScale nsIWidget::GetFallbackDefaultScale() {
2123 RefPtr<const Screen> s = ScreenManager::GetSingleton().GetPrimaryScreen();
2124 return s->GetCSSToLayoutDeviceScale(Screen::IncludeOSZoom::No);
2127 nsresult nsIWidget::ClearNativeTouchSequence(nsIObserver* aObserver) {
2128 AutoObserverNotifier notifier(aObserver, "cleartouch");
2130 // XXX This is odd. This is called by the constructor of nsIWidget. However,
2131 // at that point, nsIWidget::mLongTapTimer must be nullptr. Therefore,
2132 // this must do nothing at initializing the instance.
2133 if (!mLongTapTimer) {
2134 return NS_OK;
2136 mLongTapTimer->Cancel();
2137 mLongTapTimer = nullptr;
2138 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
2139 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
2140 mLongTapTouchPoint = nullptr;
2141 return NS_OK;
2144 MultiTouchInput nsBaseWidget::UpdateSynthesizedTouchState(
2145 MultiTouchInput* aState, mozilla::TimeStamp aTimeStamp, uint32_t aPointerId,
2146 TouchPointerState aPointerState, LayoutDeviceIntPoint aPoint,
2147 double aPointerPressure, uint32_t aPointerOrientation) {
2148 ScreenIntPoint pointerScreenPoint = ViewAs<ScreenPixel>(
2149 aPoint, PixelCastJustification::LayoutDeviceIsScreenForBounds);
2151 // We can't dispatch *aState directly because (a) dispatching
2152 // it might inadvertently modify it and (b) in the case of touchend or
2153 // touchcancel events aState will hold the touches that are
2154 // still down whereas the input dispatched needs to hold the removed
2155 // touch(es). We use |inputToDispatch| for this purpose.
2156 MultiTouchInput inputToDispatch;
2157 inputToDispatch.mInputType = MULTITOUCH_INPUT;
2158 inputToDispatch.mTimeStamp = aTimeStamp;
2160 int32_t index = aState->IndexOfTouch((int32_t)aPointerId);
2161 if (aPointerState == TOUCH_CONTACT) {
2162 if (index >= 0) {
2163 // found an existing touch point, update it
2164 SingleTouchData& point = aState->mTouches[index];
2165 point.mScreenPoint = pointerScreenPoint;
2166 point.mRotationAngle = (float)aPointerOrientation;
2167 point.mForce = (float)aPointerPressure;
2168 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_MOVE;
2169 } else {
2170 // new touch point, add it
2171 aState->mTouches.AppendElement(SingleTouchData(
2172 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2173 (float)aPointerOrientation, (float)aPointerPressure));
2174 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_START;
2176 inputToDispatch.mTouches = aState->mTouches;
2177 } else {
2178 MOZ_ASSERT(aPointerState == TOUCH_REMOVE || aPointerState == TOUCH_CANCEL);
2179 // a touch point is being lifted, so remove it from the stored list
2180 if (index >= 0) {
2181 aState->mTouches.RemoveElementAt(index);
2183 inputToDispatch.mType =
2184 (aPointerState == TOUCH_REMOVE ? MultiTouchInput::MULTITOUCH_END
2185 : MultiTouchInput::MULTITOUCH_CANCEL);
2186 inputToDispatch.mTouches.AppendElement(SingleTouchData(
2187 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2188 (float)aPointerOrientation, (float)aPointerPressure));
2191 return inputToDispatch;
2194 void nsBaseWidget::NotifyLiveResizeStarted() {
2195 // If we have mLiveResizeListeners already non-empty, we should notify those
2196 // listeners that the resize stopped before starting anew. In theory this
2197 // should never happen because we shouldn't get nested live resize actions.
2198 NotifyLiveResizeStopped();
2199 MOZ_ASSERT(mLiveResizeListeners.IsEmpty());
2201 // If we can get the active remote tab for the current widget, suppress
2202 // the displayport on it during the live resize.
2203 if (!mWidgetListener) {
2204 return;
2206 nsCOMPtr<nsIAppWindow> appWindow = mWidgetListener->GetAppWindow();
2207 if (!appWindow) {
2208 return;
2210 mLiveResizeListeners = appWindow->GetLiveResizeListeners();
2211 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2212 mLiveResizeListeners[i]->LiveResizeStarted();
2216 void nsBaseWidget::NotifyLiveResizeStopped() {
2217 if (!mLiveResizeListeners.IsEmpty()) {
2218 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2219 mLiveResizeListeners[i]->LiveResizeStopped();
2221 mLiveResizeListeners.Clear();
2225 nsresult nsBaseWidget::AsyncEnableDragDrop(bool aEnable) {
2226 RefPtr<nsBaseWidget> kungFuDeathGrip = this;
2227 return NS_DispatchToCurrentThreadQueue(
2228 NS_NewRunnableFunction(
2229 "AsyncEnableDragDropFn",
2230 [this, aEnable, kungFuDeathGrip]() { EnableDragDrop(aEnable); }),
2231 kAsyncDragDropTimeout, EventQueuePriority::Idle);
2234 void nsBaseWidget::SwipeFinished() {
2235 mSwipeTracker->Destroy();
2236 mSwipeTracker = nullptr;
2239 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId,
2240 bool aStartSwipe) {
2241 if (mSwipeEventQueue && mSwipeEventQueue->inputBlockId == aInputBlockId) {
2242 if (aStartSwipe) {
2243 PanGestureInput& startEvent = mSwipeEventQueue->queuedEvents[0];
2244 TrackScrollEventAsSwipe(startEvent, mSwipeEventQueue->allowedDirections,
2245 aInputBlockId);
2246 for (size_t i = 1; i < mSwipeEventQueue->queuedEvents.Length(); i++) {
2247 mSwipeTracker->ProcessEvent(mSwipeEventQueue->queuedEvents[i]);
2249 } else if (mAPZC) {
2250 // If the event wasn't start swipe, we need to notify it to APZ.
2251 mAPZC->SetBrowserGestureResponse(aInputBlockId,
2252 BrowserGestureResponse::NotConsumed);
2254 mSwipeEventQueue = nullptr;
2258 void nsBaseWidget::TrackScrollEventAsSwipe(
2259 const mozilla::PanGestureInput& aSwipeStartEvent,
2260 uint32_t aAllowedDirections, uint64_t aInputBlockId) {
2261 // If a swipe is currently being tracked kill it -- it's been interrupted
2262 // by another gesture event.
2263 if (mSwipeTracker) {
2264 mSwipeTracker->CancelSwipe(aSwipeStartEvent.mTimeStamp);
2265 mSwipeTracker->Destroy();
2266 mSwipeTracker = nullptr;
2269 uint32_t direction =
2270 (aSwipeStartEvent.mPanDisplacement.x > 0.0)
2271 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2272 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT;
2274 mSwipeTracker =
2275 new SwipeTracker(*this, aSwipeStartEvent, aAllowedDirections, direction);
2277 if (!mAPZC) {
2278 mCurrentPanGestureBelongsToSwipe = true;
2279 } else {
2280 // Now SwipeTracker has started consuming pan events, notify it to APZ so
2281 // that APZ can discard queued events.
2282 mAPZC->SetBrowserGestureResponse(aInputBlockId,
2283 BrowserGestureResponse::Consumed);
2287 nsBaseWidget::SwipeInfo nsBaseWidget::SendMayStartSwipe(
2288 const mozilla::PanGestureInput& aSwipeStartEvent) {
2289 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
2291 uint32_t direction =
2292 (aSwipeStartEvent.mPanDisplacement.x > 0.0)
2293 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2294 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT;
2296 // We're ready to start the animation. Tell Gecko about it, and at the same
2297 // time ask it if it really wants to start an animation for this event.
2298 // This event also reports back the directions that we can swipe in.
2299 LayoutDeviceIntPoint position = RoundedToInt(aSwipeStartEvent.mPanStartPoint *
2300 ScreenToLayoutDeviceScale(1));
2301 WidgetSimpleGestureEvent geckoEvent = SwipeTracker::CreateSwipeGestureEvent(
2302 eSwipeGestureMayStart, this, position, aSwipeStartEvent.mTimeStamp);
2303 geckoEvent.mDirection = direction;
2304 geckoEvent.mDelta = 0.0;
2305 geckoEvent.mAllowedDirections = 0;
2306 bool shouldStartSwipe =
2307 DispatchWindowEvent(geckoEvent); // event cancelled == swipe should start
2309 SwipeInfo result = {shouldStartSwipe, geckoEvent.mAllowedDirections};
2310 return result;
2313 WidgetWheelEvent nsBaseWidget::MayStartSwipeForAPZ(
2314 const PanGestureInput& aPanInput, const APZEventResult& aApzResult) {
2315 WidgetWheelEvent event = aPanInput.ToWidgetEvent(this);
2316 if (aPanInput.AllowsSwipe()) {
2317 SwipeInfo swipeInfo = SendMayStartSwipe(aPanInput);
2318 event.mCanTriggerSwipe = swipeInfo.wantsSwipe;
2319 if (swipeInfo.wantsSwipe) {
2320 if (aApzResult.GetStatus() == nsEventStatus_eIgnore) {
2321 // APZ has determined and that scrolling horizontally in the
2322 // requested direction is impossible, so it didn't do any
2323 // scrolling for the event.
2324 // We know now that MayStartSwipe wants a swipe, so we can start
2325 // the swipe now.
2326 TrackScrollEventAsSwipe(aPanInput, swipeInfo.allowedDirections,
2327 aApzResult.mInputBlockId);
2328 } else if (!aApzResult.GetHandledResult() ||
2329 !aApzResult.GetHandledResult()->IsHandledByRoot()) {
2330 // We don't know whether this event can start a swipe, so we need
2331 // to queue up events and wait for a call to ReportSwipeStarted.
2332 // APZ might already have started scrolling in response to the
2333 // event if it knew that it's the right thing to do. In that case
2334 // we'll still get a call to ReportSwipeStarted, and we will
2335 // discard the queued events at that point.
2336 mSwipeEventQueue = MakeUnique<SwipeEventQueue>(
2337 swipeInfo.allowedDirections, aApzResult.mInputBlockId);
2339 } else {
2340 // Inform that the browser gesture didn't use the pan event (pan-start
2341 // precisely), so that APZ can now start using the event for
2342 // scrolling/overscrolling.
2343 mAPZC->SetBrowserGestureResponse(aApzResult.mInputBlockId,
2344 BrowserGestureResponse::NotConsumed);
2348 if (mSwipeEventQueue &&
2349 mSwipeEventQueue->inputBlockId == aApzResult.mInputBlockId) {
2350 mSwipeEventQueue->queuedEvents.AppendElement(aPanInput);
2353 return event;
2356 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput& aPanInput) {
2357 if (aPanInput.mType == PanGestureInput::PANGESTURE_MAYSTART ||
2358 aPanInput.mType == PanGestureInput::PANGESTURE_START) {
2359 mCurrentPanGestureBelongsToSwipe = false;
2361 if (mCurrentPanGestureBelongsToSwipe) {
2362 // Ignore this event. It's a momentum event from a scroll gesture
2363 // that was processed as a swipe, and the swipe animation has
2364 // already finished (so mSwipeTracker is already null).
2365 MOZ_ASSERT(aPanInput.IsMomentum(),
2366 "If the fingers are still on the touchpad, we should still have "
2367 "a SwipeTracker, "
2368 "and it should have consumed this event.");
2369 return true;
2372 if (!aPanInput.MayTriggerSwipe()) {
2373 return false;
2376 SwipeInfo swipeInfo = SendMayStartSwipe(aPanInput);
2378 // We're in the non-APZ case here, but we still want to know whether
2379 // the event was routed to a child process, so we use InputAPZContext
2380 // to get that piece of information.
2381 ScrollableLayerGuid guid;
2382 uint64_t blockId = 0;
2383 InputAPZContext context(guid, blockId, nsEventStatus_eIgnore);
2385 WidgetWheelEvent event = aPanInput.ToWidgetEvent(this);
2386 event.mCanTriggerSwipe = swipeInfo.wantsSwipe;
2387 nsEventStatus status;
2388 DispatchEvent(&event, status);
2389 if (swipeInfo.wantsSwipe) {
2390 if (context.WasRoutedToChildProcess()) {
2391 // We don't know whether this event can start a swipe, so we need
2392 // to queue up events and wait for a call to ReportSwipeStarted.
2393 mSwipeEventQueue =
2394 MakeUnique<SwipeEventQueue>(swipeInfo.allowedDirections, blockId);
2395 } else if (event.TriggersSwipe()) {
2396 TrackScrollEventAsSwipe(aPanInput, swipeInfo.allowedDirections, blockId);
2400 if (mSwipeEventQueue && mSwipeEventQueue->inputBlockId == 0) {
2401 mSwipeEventQueue->queuedEvents.AppendElement(aPanInput);
2404 return true;
2407 const IMENotificationRequests& nsIWidget::IMENotificationRequestsRef() {
2408 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
2409 return dispatcher->IMENotificationRequestsRef();
2412 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent* aEvent) {}
2414 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType,
2415 const WidgetKeyboardEvent& aEvent,
2416 nsTArray<CommandInt>& aCommands) {
2417 MOZ_ASSERT(aEvent.IsTrusted());
2418 MOZ_ASSERT(aCommands.IsEmpty());
2419 return true;
2422 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboard() {
2423 if (XRE_IsContentProcess()) {
2424 return CreateBidiKeyboardContentProcess();
2426 return CreateBidiKeyboardInner();
2429 #ifdef ANDROID
2430 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboardInner() {
2431 // no bidi keyboard implementation
2432 return nullptr;
2434 #endif
2436 namespace mozilla::widget {
2438 const char* ToChar(InputContext::Origin aOrigin) {
2439 switch (aOrigin) {
2440 case InputContext::ORIGIN_MAIN:
2441 return "ORIGIN_MAIN";
2442 case InputContext::ORIGIN_CONTENT:
2443 return "ORIGIN_CONTENT";
2444 default:
2445 return "Unexpected value";
2449 const char* ToChar(IMEMessage aIMEMessage) {
2450 switch (aIMEMessage) {
2451 case NOTIFY_IME_OF_NOTHING:
2452 return "NOTIFY_IME_OF_NOTHING";
2453 case NOTIFY_IME_OF_FOCUS:
2454 return "NOTIFY_IME_OF_FOCUS";
2455 case NOTIFY_IME_OF_BLUR:
2456 return "NOTIFY_IME_OF_BLUR";
2457 case NOTIFY_IME_OF_SELECTION_CHANGE:
2458 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2459 case NOTIFY_IME_OF_TEXT_CHANGE:
2460 return "NOTIFY_IME_OF_TEXT_CHANGE";
2461 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED:
2462 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2463 case NOTIFY_IME_OF_POSITION_CHANGE:
2464 return "NOTIFY_IME_OF_POSITION_CHANGE";
2465 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
2466 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2467 case REQUEST_TO_COMMIT_COMPOSITION:
2468 return "REQUEST_TO_COMMIT_COMPOSITION";
2469 case REQUEST_TO_CANCEL_COMPOSITION:
2470 return "REQUEST_TO_CANCEL_COMPOSITION";
2471 default:
2472 return "Unexpected value";
2476 void NativeIMEContext::Init(nsIWidget* aWidget) {
2477 if (!aWidget) {
2478 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2479 mOriginProcessID = static_cast<uint64_t>(-1);
2480 return;
2482 if (!XRE_IsContentProcess()) {
2483 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(
2484 aWidget->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT));
2485 mOriginProcessID = 0;
2486 return;
2488 // If this is created in a child process, aWidget is an instance of
2489 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2490 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2491 // native IME context of the parent process.
2492 *this = aWidget->GetNativeIMEContext();
2495 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext) {
2496 if (NS_WARN_IF(!aRawNativeIMEContext)) {
2497 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2498 mOriginProcessID = static_cast<uint64_t>(-1);
2499 return;
2501 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(aRawNativeIMEContext);
2502 mOriginProcessID =
2503 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2506 void IMENotification::TextChangeDataBase::MergeWith(
2507 const IMENotification::TextChangeDataBase& aOther) {
2508 MOZ_ASSERT(aOther.IsValid(), "Merging data must store valid data");
2509 MOZ_ASSERT(aOther.mStartOffset <= aOther.mRemovedEndOffset,
2510 "end of removed text must be same or larger than start");
2511 MOZ_ASSERT(aOther.mStartOffset <= aOther.mAddedEndOffset,
2512 "end of added text must be same or larger than start");
2514 if (!IsValid()) {
2515 *this = aOther;
2516 return;
2519 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2520 // text ranges. I.e., mStartOffset should be the smallest offset of all
2521 // modified text ranges in old text. |mRemovedEndOffset| should be the
2522 // largest end offset in old text of all modified text ranges.
2523 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2524 // I.e., only this is an offset in new text.
2525 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2526 // premodified text was already removed. And some text whose length is
2527 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2528 // this allows IME to mark dirty the modified text range with |mStartOffset|
2529 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2530 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2531 // Additionally, IME can retrieve only the text between |mStartOffset| and
2532 // |mAddedEndOffset| for updating stored text.
2534 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2535 // should be adjusted to be in same text. The |newData.mStartOffset| and
2536 // |newData.mRemovedEndOffset| should be computed as in old text because
2537 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2538 // in the old text but even if some text before the values of the newData
2539 // has already been modified, the values don't include the changes.
2541 // For comparing new and old |mAddedEndOffset| values, they should be
2542 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2543 // computed as in the new text because |mAddedEndOffset| indicates the end
2544 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2545 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2547 const TextChangeDataBase& newData = aOther;
2548 const TextChangeDataBase oldData = *this;
2550 // mCausedOnlyByComposition should be true only when all changes are caused
2551 // by composition.
2552 mCausedOnlyByComposition =
2553 newData.mCausedOnlyByComposition && oldData.mCausedOnlyByComposition;
2555 // mIncludingChangesWithoutComposition should be true if at least one of
2556 // merged changes occurred without composition.
2557 mIncludingChangesWithoutComposition =
2558 newData.mIncludingChangesWithoutComposition ||
2559 oldData.mIncludingChangesWithoutComposition;
2561 // mIncludingChangesDuringComposition should be true when at least one of
2562 // the merged non-composition changes occurred during the latest composition.
2563 if (!newData.mCausedOnlyByComposition &&
2564 !newData.mIncludingChangesDuringComposition) {
2565 MOZ_ASSERT(newData.mIncludingChangesWithoutComposition);
2566 MOZ_ASSERT(mIncludingChangesWithoutComposition);
2567 // If new change is neither caused by composition nor occurred during
2568 // composition, set mIncludingChangesDuringComposition to false because
2569 // IME doesn't want outdated text changes as text change during current
2570 // composition.
2571 mIncludingChangesDuringComposition = false;
2572 } else {
2573 // Otherwise, set mIncludingChangesDuringComposition to true if either
2574 // oldData or newData includes changes during composition.
2575 mIncludingChangesDuringComposition =
2576 newData.mIncludingChangesDuringComposition ||
2577 oldData.mIncludingChangesDuringComposition;
2580 if (newData.mStartOffset >= oldData.mAddedEndOffset) {
2581 // Case 1:
2582 // If new start is after old end offset of added text, it means that text
2583 // after the modified range is modified. Like:
2584 // added range of old change: +----------+
2585 // removed range of new change: +----------+
2586 // So, the old start offset is always the smaller offset.
2587 mStartOffset = oldData.mStartOffset;
2588 // The new end offset of removed text is moved by the old change and we
2589 // need to cancel the move of the old change for comparing the offsets in
2590 // same text because it doesn't make sensce to compare offsets in different
2591 // text.
2592 uint32_t newRemovedEndOffsetInOldText =
2593 newData.mRemovedEndOffset - oldData.Difference();
2594 mRemovedEndOffset =
2595 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2596 // The new end offset of added text is always the larger offset.
2597 mAddedEndOffset = newData.mAddedEndOffset;
2598 return;
2601 if (newData.mStartOffset >= oldData.mStartOffset) {
2602 // If new start is in the modified range, it means that new data changes
2603 // a part or all of the range.
2604 mStartOffset = oldData.mStartOffset;
2605 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2606 // Case 2:
2607 // If new end of removed text is greater than old end of added text, it
2608 // means that all or a part of modified range modified again and text
2609 // after the modified range is also modified. Like:
2610 // added range of old change: +----------+
2611 // removed range of new change: +----------+
2612 // So, the new removed end offset is moved by the old change and we need
2613 // to cancel the move of the old change for comparing the offsets in the
2614 // same text because it doesn't make sense to compare the offsets in
2615 // different text.
2616 uint32_t newRemovedEndOffsetInOldText =
2617 newData.mRemovedEndOffset - oldData.Difference();
2618 mRemovedEndOffset =
2619 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2620 // The old end of added text is replaced by new change. So, it should be
2621 // same as the new start. On the other hand, the new added end offset is
2622 // always same or larger. Therefore, the merged end offset of added
2623 // text should be the new end offset of added text.
2624 mAddedEndOffset = newData.mAddedEndOffset;
2625 return;
2628 // Case 3:
2629 // If new end of removed text is less than old end of added text, it means
2630 // that only a part of the modified range is modified again. Like:
2631 // added range of old change: +------------+
2632 // removed range of new change: +-----+
2633 // So, the new end offset of removed text should be same as the old end
2634 // offset of removed text. Therefore, the merged end offset of removed
2635 // text should be the old text change's |mRemovedEndOffset|.
2636 mRemovedEndOffset = oldData.mRemovedEndOffset;
2637 // The old end of added text is moved by new change. So, we need to cancel
2638 // the move of the new change for comparing the offsets in same text.
2639 uint32_t oldAddedEndOffsetInNewText =
2640 oldData.mAddedEndOffset + newData.Difference();
2641 mAddedEndOffset =
2642 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2643 return;
2646 if (newData.mRemovedEndOffset >= oldData.mStartOffset) {
2647 // If new end of removed text is greater than old start (and new start is
2648 // less than old start), it means that a part of modified range is modified
2649 // again and some new text before the modified range is also modified.
2650 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2651 "new start offset should be less than old one here");
2652 mStartOffset = newData.mStartOffset;
2653 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2654 // Case 4:
2655 // If new end of removed text is greater than old end of added text, it
2656 // means that all modified text and text after the modified range is
2657 // modified. Like:
2658 // added range of old change: +----------+
2659 // removed range of new change: +------------------+
2660 // So, the new end of removed text is moved by the old change. Therefore,
2661 // we need to cancel the move of the old change for comparing the offsets
2662 // in same text because it doesn't make sense to compare the offsets in
2663 // different text.
2664 uint32_t newRemovedEndOffsetInOldText =
2665 newData.mRemovedEndOffset - oldData.Difference();
2666 mRemovedEndOffset =
2667 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2668 // The old end of added text is replaced by new change. So, the old end
2669 // offset of added text is same as new text change's start offset. Then,
2670 // new change's end offset of added text is always same or larger than
2671 // it. Therefore, merged end offset of added text is always the new end
2672 // offset of added text.
2673 mAddedEndOffset = newData.mAddedEndOffset;
2674 return;
2677 // Case 5:
2678 // If new end of removed text is less than old end of added text, it
2679 // means that only a part of the modified range is modified again. Like:
2680 // added range of old change: +----------+
2681 // removed range of new change: +----------+
2682 // So, the new end of removed text should be same as old end of removed
2683 // text for preventing end of removed text to be modified. Therefore,
2684 // merged end offset of removed text is always the old end offset of removed
2685 // text.
2686 mRemovedEndOffset = oldData.mRemovedEndOffset;
2687 // The old end of added text is moved by this change. So, we need to
2688 // cancel the move of the new change for comparing the offsets in same text
2689 // because it doesn't make sense to compare the offsets in different text.
2690 uint32_t oldAddedEndOffsetInNewText =
2691 oldData.mAddedEndOffset + newData.Difference();
2692 mAddedEndOffset =
2693 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2694 return;
2697 // Case 6:
2698 // Otherwise, i.e., both new end of added text and new start are less than
2699 // old start, text before the modified range is modified. Like:
2700 // added range of old change: +----------+
2701 // removed range of new change: +----------+
2702 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2703 "new start offset should be less than old one here");
2704 mStartOffset = newData.mStartOffset;
2705 MOZ_ASSERT(newData.mRemovedEndOffset < oldData.mRemovedEndOffset,
2706 "new removed end offset should be less than old one here");
2707 mRemovedEndOffset = oldData.mRemovedEndOffset;
2708 // The end of added text should be adjusted with the new difference.
2709 uint32_t oldAddedEndOffsetInNewText =
2710 oldData.mAddedEndOffset + newData.Difference();
2711 mAddedEndOffset =
2712 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2715 #ifdef DEBUG
2717 // Let's test the code of merging multiple text change data in debug build
2718 // and crash if one of them fails because this feature is very complex but
2719 // cannot be tested with mochitest.
2720 void IMENotification::TextChangeDataBase::Test() {
2721 static bool gTestTextChangeEvent = true;
2722 if (!gTestTextChangeEvent) {
2723 return;
2725 gTestTextChangeEvent = false;
2727 /****************************************************************************
2728 * Case 1
2729 ****************************************************************************/
2731 // Appending text
2732 MergeWith(TextChangeData(10, 10, 20, false, false));
2733 MergeWith(TextChangeData(20, 20, 35, false, false));
2734 MOZ_ASSERT(mStartOffset == 10,
2735 "Test 1-1-1: mStartOffset should be the first offset");
2736 MOZ_ASSERT(
2737 mRemovedEndOffset == 10, // 20 - (20 - 10)
2738 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2739 MOZ_ASSERT(
2740 mAddedEndOffset == 35,
2741 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2742 Clear();
2744 // Removing text (longer line -> shorter line)
2745 MergeWith(TextChangeData(10, 20, 10, false, false));
2746 MergeWith(TextChangeData(10, 30, 10, false, false));
2747 MOZ_ASSERT(mStartOffset == 10,
2748 "Test 1-2-1: mStartOffset should be the first offset");
2749 MOZ_ASSERT(mRemovedEndOffset == 40, // 30 + (10 - 20)
2750 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2751 "removed text "
2752 "with already removed length");
2753 MOZ_ASSERT(
2754 mAddedEndOffset == 10,
2755 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2756 Clear();
2758 // Removing text (shorter line -> longer line)
2759 MergeWith(TextChangeData(10, 20, 10, false, false));
2760 MergeWith(TextChangeData(10, 15, 10, false, false));
2761 MOZ_ASSERT(mStartOffset == 10,
2762 "Test 1-3-1: mStartOffset should be the first offset");
2763 MOZ_ASSERT(mRemovedEndOffset == 25, // 15 + (10 - 20)
2764 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2765 "removed text "
2766 "with already removed length");
2767 MOZ_ASSERT(
2768 mAddedEndOffset == 10,
2769 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2770 Clear();
2772 // Appending text at different point (not sure if actually occurs)
2773 MergeWith(TextChangeData(10, 10, 20, false, false));
2774 MergeWith(TextChangeData(55, 55, 60, false, false));
2775 MOZ_ASSERT(mStartOffset == 10,
2776 "Test 1-4-1: mStartOffset should be the smallest offset");
2777 MOZ_ASSERT(
2778 mRemovedEndOffset == 45, // 55 - (10 - 20)
2779 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2780 "text without already added length");
2781 MOZ_ASSERT(
2782 mAddedEndOffset == 60,
2783 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2784 Clear();
2786 // Removing text at different point (not sure if actually occurs)
2787 MergeWith(TextChangeData(10, 20, 10, false, false));
2788 MergeWith(TextChangeData(55, 68, 55, false, false));
2789 MOZ_ASSERT(mStartOffset == 10,
2790 "Test 1-5-1: mStartOffset should be the smallest offset");
2791 MOZ_ASSERT(
2792 mRemovedEndOffset == 78, // 68 - (10 - 20)
2793 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2794 "text with already removed length");
2795 MOZ_ASSERT(
2796 mAddedEndOffset == 55,
2797 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2798 Clear();
2800 // Replacing text and append text (becomes longer)
2801 MergeWith(TextChangeData(30, 35, 32, false, false));
2802 MergeWith(TextChangeData(32, 32, 40, false, false));
2803 MOZ_ASSERT(mStartOffset == 30,
2804 "Test 1-6-1: mStartOffset should be the smallest offset");
2805 MOZ_ASSERT(
2806 mRemovedEndOffset == 35, // 32 - (32 - 35)
2807 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2808 "text");
2809 MOZ_ASSERT(
2810 mAddedEndOffset == 40,
2811 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2812 Clear();
2814 // Replacing text and append text (becomes shorter)
2815 MergeWith(TextChangeData(30, 35, 32, false, false));
2816 MergeWith(TextChangeData(32, 32, 33, false, false));
2817 MOZ_ASSERT(mStartOffset == 30,
2818 "Test 1-7-1: mStartOffset should be the smallest offset");
2819 MOZ_ASSERT(
2820 mRemovedEndOffset == 35, // 32 - (32 - 35)
2821 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2822 "text");
2823 MOZ_ASSERT(
2824 mAddedEndOffset == 33,
2825 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2826 Clear();
2828 // Removing text and replacing text after first range (not sure if actually
2829 // occurs)
2830 MergeWith(TextChangeData(30, 35, 30, false, false));
2831 MergeWith(TextChangeData(32, 34, 48, false, false));
2832 MOZ_ASSERT(mStartOffset == 30,
2833 "Test 1-8-1: mStartOffset should be the smallest offset");
2834 MOZ_ASSERT(mRemovedEndOffset == 39, // 34 - (30 - 35)
2835 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2836 "removed text "
2837 "without already removed text");
2838 MOZ_ASSERT(
2839 mAddedEndOffset == 48,
2840 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2841 Clear();
2843 // Removing text and replacing text after first range (not sure if actually
2844 // occurs)
2845 MergeWith(TextChangeData(30, 35, 30, false, false));
2846 MergeWith(TextChangeData(32, 38, 36, false, false));
2847 MOZ_ASSERT(mStartOffset == 30,
2848 "Test 1-9-1: mStartOffset should be the smallest offset");
2849 MOZ_ASSERT(mRemovedEndOffset == 43, // 38 - (30 - 35)
2850 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2851 "removed text "
2852 "without already removed text");
2853 MOZ_ASSERT(
2854 mAddedEndOffset == 36,
2855 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2856 Clear();
2858 /****************************************************************************
2859 * Case 2
2860 ****************************************************************************/
2862 // Replacing text in around end of added text (becomes shorter) (not sure
2863 // if actually occurs)
2864 MergeWith(TextChangeData(50, 50, 55, false, false));
2865 MergeWith(TextChangeData(53, 60, 54, false, false));
2866 MOZ_ASSERT(mStartOffset == 50,
2867 "Test 2-1-1: mStartOffset should be the smallest offset");
2868 MOZ_ASSERT(mRemovedEndOffset == 55, // 60 - (55 - 50)
2869 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2870 "removed text "
2871 "without already added text length");
2872 MOZ_ASSERT(
2873 mAddedEndOffset == 54,
2874 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2875 Clear();
2877 // Replacing text around end of added text (becomes longer) (not sure
2878 // if actually occurs)
2879 MergeWith(TextChangeData(50, 50, 55, false, false));
2880 MergeWith(TextChangeData(54, 62, 68, false, false));
2881 MOZ_ASSERT(mStartOffset == 50,
2882 "Test 2-2-1: mStartOffset should be the smallest offset");
2883 MOZ_ASSERT(mRemovedEndOffset == 57, // 62 - (55 - 50)
2884 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2885 "removed text "
2886 "without already added text length");
2887 MOZ_ASSERT(
2888 mAddedEndOffset == 68,
2889 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2890 Clear();
2892 // Replacing text around end of replaced text (became shorter) (not sure if
2893 // actually occurs)
2894 MergeWith(TextChangeData(36, 48, 45, false, false));
2895 MergeWith(TextChangeData(43, 50, 49, false, false));
2896 MOZ_ASSERT(mStartOffset == 36,
2897 "Test 2-3-1: mStartOffset should be the smallest offset");
2898 MOZ_ASSERT(mRemovedEndOffset == 53, // 50 - (45 - 48)
2899 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2900 "removed text "
2901 "without already removed text length");
2902 MOZ_ASSERT(
2903 mAddedEndOffset == 49,
2904 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2905 Clear();
2907 // Replacing text around end of replaced text (became longer) (not sure if
2908 // actually occurs)
2909 MergeWith(TextChangeData(36, 52, 53, false, false));
2910 MergeWith(TextChangeData(43, 68, 61, false, false));
2911 MOZ_ASSERT(mStartOffset == 36,
2912 "Test 2-4-1: mStartOffset should be the smallest offset");
2913 MOZ_ASSERT(mRemovedEndOffset == 67, // 68 - (53 - 52)
2914 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2915 "removed text "
2916 "without already added text length");
2917 MOZ_ASSERT(
2918 mAddedEndOffset == 61,
2919 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2920 Clear();
2922 /****************************************************************************
2923 * Case 3
2924 ****************************************************************************/
2926 // Appending text in already added text (not sure if actually occurs)
2927 MergeWith(TextChangeData(10, 10, 20, false, false));
2928 MergeWith(TextChangeData(15, 15, 30, false, false));
2929 MOZ_ASSERT(mStartOffset == 10,
2930 "Test 3-1-1: mStartOffset should be the smallest offset");
2931 MOZ_ASSERT(mRemovedEndOffset == 10,
2932 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2933 "removed text");
2934 MOZ_ASSERT(
2935 mAddedEndOffset == 35, // 20 + (30 - 15)
2936 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2937 "added text length by the new change");
2938 Clear();
2940 // Replacing text in added text (not sure if actually occurs)
2941 MergeWith(TextChangeData(50, 50, 55, false, false));
2942 MergeWith(TextChangeData(52, 53, 56, false, false));
2943 MOZ_ASSERT(mStartOffset == 50,
2944 "Test 3-2-1: mStartOffset should be the smallest offset");
2945 MOZ_ASSERT(mRemovedEndOffset == 50,
2946 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2947 "removed text");
2948 MOZ_ASSERT(
2949 mAddedEndOffset == 58, // 55 + (56 - 53)
2950 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2951 "added text length by the new change");
2952 Clear();
2954 // Replacing text in replaced text (became shorter) (not sure if actually
2955 // occurs)
2956 MergeWith(TextChangeData(36, 48, 45, false, false));
2957 MergeWith(TextChangeData(37, 38, 50, false, false));
2958 MOZ_ASSERT(mStartOffset == 36,
2959 "Test 3-3-1: mStartOffset should be the smallest offset");
2960 MOZ_ASSERT(mRemovedEndOffset == 48,
2961 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2962 "removed text");
2963 MOZ_ASSERT(
2964 mAddedEndOffset == 57, // 45 + (50 - 38)
2965 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2966 "added text length by the new change");
2967 Clear();
2969 // Replacing text in replaced text (became longer) (not sure if actually
2970 // occurs)
2971 MergeWith(TextChangeData(32, 48, 53, false, false));
2972 MergeWith(TextChangeData(43, 50, 52, false, false));
2973 MOZ_ASSERT(mStartOffset == 32,
2974 "Test 3-4-1: mStartOffset should be the smallest offset");
2975 MOZ_ASSERT(mRemovedEndOffset == 48,
2976 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2977 "removed text "
2978 "without already added text length");
2979 MOZ_ASSERT(
2980 mAddedEndOffset == 55, // 53 + (52 - 50)
2981 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2982 "added text length by the new change");
2983 Clear();
2985 // Replacing text in replaced text (became shorter) (not sure if actually
2986 // occurs)
2987 MergeWith(TextChangeData(36, 48, 50, false, false));
2988 MergeWith(TextChangeData(37, 49, 47, false, false));
2989 MOZ_ASSERT(mStartOffset == 36,
2990 "Test 3-5-1: mStartOffset should be the smallest offset");
2991 MOZ_ASSERT(
2992 mRemovedEndOffset == 48,
2993 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
2994 "text");
2995 MOZ_ASSERT(mAddedEndOffset == 48, // 50 + (47 - 49)
2996 "Test 3-5-3: mAddedEndOffset should be the first end of added "
2997 "text without "
2998 "removed text length by the new change");
2999 Clear();
3001 // Replacing text in replaced text (became longer) (not sure if actually
3002 // occurs)
3003 MergeWith(TextChangeData(32, 48, 53, false, false));
3004 MergeWith(TextChangeData(43, 50, 47, false, false));
3005 MOZ_ASSERT(mStartOffset == 32,
3006 "Test 3-6-1: mStartOffset should be the smallest offset");
3007 MOZ_ASSERT(mRemovedEndOffset == 48,
3008 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
3009 "removed text "
3010 "without already added text length");
3011 MOZ_ASSERT(mAddedEndOffset == 50, // 53 + (47 - 50)
3012 "Test 3-6-3: mAddedEndOffset should be the first end of added "
3013 "text without "
3014 "removed text length by the new change");
3015 Clear();
3017 /****************************************************************************
3018 * Case 4
3019 ****************************************************************************/
3021 // Replacing text all of already append text (not sure if actually occurs)
3022 MergeWith(TextChangeData(50, 50, 55, false, false));
3023 MergeWith(TextChangeData(44, 66, 68, false, false));
3024 MOZ_ASSERT(mStartOffset == 44,
3025 "Test 4-1-1: mStartOffset should be the smallest offset");
3026 MOZ_ASSERT(mRemovedEndOffset == 61, // 66 - (55 - 50)
3027 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
3028 "removed text "
3029 "without already added text length");
3030 MOZ_ASSERT(
3031 mAddedEndOffset == 68,
3032 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3033 Clear();
3035 // Replacing text around a point in which text was removed (not sure if
3036 // actually occurs)
3037 MergeWith(TextChangeData(50, 62, 50, false, false));
3038 MergeWith(TextChangeData(44, 66, 68, false, false));
3039 MOZ_ASSERT(mStartOffset == 44,
3040 "Test 4-2-1: mStartOffset should be the smallest offset");
3041 MOZ_ASSERT(mRemovedEndOffset == 78, // 66 - (50 - 62)
3042 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
3043 "removed text "
3044 "without already removed text length");
3045 MOZ_ASSERT(
3046 mAddedEndOffset == 68,
3047 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3048 Clear();
3050 // Replacing text all replaced text (became shorter) (not sure if actually
3051 // occurs)
3052 MergeWith(TextChangeData(50, 62, 60, false, false));
3053 MergeWith(TextChangeData(49, 128, 130, false, false));
3054 MOZ_ASSERT(mStartOffset == 49,
3055 "Test 4-3-1: mStartOffset should be the smallest offset");
3056 MOZ_ASSERT(mRemovedEndOffset == 130, // 128 - (60 - 62)
3057 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
3058 "removed text "
3059 "without already removed text length");
3060 MOZ_ASSERT(
3061 mAddedEndOffset == 130,
3062 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3063 Clear();
3065 // Replacing text all replaced text (became longer) (not sure if actually
3066 // occurs)
3067 MergeWith(TextChangeData(50, 61, 73, false, false));
3068 MergeWith(TextChangeData(44, 100, 50, false, false));
3069 MOZ_ASSERT(mStartOffset == 44,
3070 "Test 4-4-1: mStartOffset should be the smallest offset");
3071 MOZ_ASSERT(mRemovedEndOffset == 88, // 100 - (73 - 61)
3072 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
3073 "removed text "
3074 "with already added text length");
3075 MOZ_ASSERT(
3076 mAddedEndOffset == 50,
3077 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3078 Clear();
3080 /****************************************************************************
3081 * Case 5
3082 ****************************************************************************/
3084 // Replacing text around start of added text (not sure if actually occurs)
3085 MergeWith(TextChangeData(50, 50, 55, false, false));
3086 MergeWith(TextChangeData(48, 52, 49, false, false));
3087 MOZ_ASSERT(mStartOffset == 48,
3088 "Test 5-1-1: mStartOffset should be the smallest offset");
3089 MOZ_ASSERT(
3090 mRemovedEndOffset == 50,
3091 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
3092 "text");
3093 MOZ_ASSERT(
3094 mAddedEndOffset == 52, // 55 + (52 - 49)
3095 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
3096 "added text length by the new change");
3097 Clear();
3099 // Replacing text around start of replaced text (became shorter) (not sure if
3100 // actually occurs)
3101 MergeWith(TextChangeData(50, 60, 58, false, false));
3102 MergeWith(TextChangeData(43, 50, 48, false, false));
3103 MOZ_ASSERT(mStartOffset == 43,
3104 "Test 5-2-1: mStartOffset should be the smallest offset");
3105 MOZ_ASSERT(
3106 mRemovedEndOffset == 60,
3107 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3108 "text");
3109 MOZ_ASSERT(mAddedEndOffset == 56, // 58 + (48 - 50)
3110 "Test 5-2-3: mAddedEndOffset should be the first end of added "
3111 "text without "
3112 "removed text length by the new change");
3113 Clear();
3115 // Replacing text around start of replaced text (became longer) (not sure if
3116 // actually occurs)
3117 MergeWith(TextChangeData(50, 60, 68, false, false));
3118 MergeWith(TextChangeData(43, 55, 53, false, false));
3119 MOZ_ASSERT(mStartOffset == 43,
3120 "Test 5-3-1: mStartOffset should be the smallest offset");
3121 MOZ_ASSERT(
3122 mRemovedEndOffset == 60,
3123 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3124 "text");
3125 MOZ_ASSERT(mAddedEndOffset == 66, // 68 + (53 - 55)
3126 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3127 "text without "
3128 "removed text length by the new change");
3129 Clear();
3131 // Replacing text around start of replaced text (became shorter) (not sure if
3132 // actually occurs)
3133 MergeWith(TextChangeData(50, 60, 58, false, false));
3134 MergeWith(TextChangeData(43, 50, 128, false, false));
3135 MOZ_ASSERT(mStartOffset == 43,
3136 "Test 5-4-1: mStartOffset should be the smallest offset");
3137 MOZ_ASSERT(
3138 mRemovedEndOffset == 60,
3139 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
3140 "text");
3141 MOZ_ASSERT(
3142 mAddedEndOffset == 136, // 58 + (128 - 50)
3143 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
3144 "added text length by the new change");
3145 Clear();
3147 // Replacing text around start of replaced text (became longer) (not sure if
3148 // actually occurs)
3149 MergeWith(TextChangeData(50, 60, 68, false, false));
3150 MergeWith(TextChangeData(43, 55, 65, false, false));
3151 MOZ_ASSERT(mStartOffset == 43,
3152 "Test 5-5-1: mStartOffset should be the smallest offset");
3153 MOZ_ASSERT(
3154 mRemovedEndOffset == 60,
3155 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
3156 "text");
3157 MOZ_ASSERT(
3158 mAddedEndOffset == 78, // 68 + (65 - 55)
3159 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
3160 "added text length by the new change");
3161 Clear();
3163 /****************************************************************************
3164 * Case 6
3165 ****************************************************************************/
3167 // Appending text before already added text (not sure if actually occurs)
3168 MergeWith(TextChangeData(30, 30, 45, false, false));
3169 MergeWith(TextChangeData(10, 10, 20, false, false));
3170 MOZ_ASSERT(mStartOffset == 10,
3171 "Test 6-1-1: mStartOffset should be the smallest offset");
3172 MOZ_ASSERT(
3173 mRemovedEndOffset == 30,
3174 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3175 "text");
3176 MOZ_ASSERT(
3177 mAddedEndOffset == 55, // 45 + (20 - 10)
3178 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3179 "added text length by the new change");
3180 Clear();
3182 // Removing text before already removed text (not sure if actually occurs)
3183 MergeWith(TextChangeData(30, 35, 30, false, false));
3184 MergeWith(TextChangeData(10, 25, 10, false, false));
3185 MOZ_ASSERT(mStartOffset == 10,
3186 "Test 6-2-1: mStartOffset should be the smallest offset");
3187 MOZ_ASSERT(
3188 mRemovedEndOffset == 35,
3189 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3190 "text");
3191 MOZ_ASSERT(
3192 mAddedEndOffset == 15, // 30 - (25 - 10)
3193 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3194 "removed text length by the new change");
3195 Clear();
3197 // Replacing text before already replaced text (not sure if actually occurs)
3198 MergeWith(TextChangeData(50, 65, 70, false, false));
3199 MergeWith(TextChangeData(13, 24, 15, false, false));
3200 MOZ_ASSERT(mStartOffset == 13,
3201 "Test 6-3-1: mStartOffset should be the smallest offset");
3202 MOZ_ASSERT(
3203 mRemovedEndOffset == 65,
3204 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3205 "text");
3206 MOZ_ASSERT(mAddedEndOffset == 61, // 70 + (15 - 24)
3207 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3208 "text without "
3209 "removed text length by the new change");
3210 Clear();
3212 // Replacing text before already replaced text (not sure if actually occurs)
3213 MergeWith(TextChangeData(50, 65, 70, false, false));
3214 MergeWith(TextChangeData(13, 24, 36, false, false));
3215 MOZ_ASSERT(mStartOffset == 13,
3216 "Test 6-4-1: mStartOffset should be the smallest offset");
3217 MOZ_ASSERT(
3218 mRemovedEndOffset == 65,
3219 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3220 "text");
3221 MOZ_ASSERT(mAddedEndOffset == 82, // 70 + (36 - 24)
3222 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3223 "text without "
3224 "removed text length by the new change");
3225 Clear();
3228 #endif // #ifdef DEBUG
3230 } // namespace mozilla::widget
3232 #ifdef DEBUG
3233 //////////////////////////////////////////////////////////////
3235 // Convert a GUI event message code to a string.
3236 // Makes it a lot easier to debug events.
3238 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3239 // for a DebugPrintEvent() function that uses
3240 // this.
3242 //////////////////////////////////////////////////////////////
3243 /* static */
3244 nsAutoString nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent* aGuiEvent) {
3245 NS_ASSERTION(nullptr != aGuiEvent, "cmon, null gui event.");
3247 nsAutoString eventName(u"UNKNOWN"_ns);
3249 # define _ASSIGN_eventName(_value, _name) \
3250 case _value: \
3251 eventName.AssignLiteral(_name); \
3252 break
3254 switch (aGuiEvent->mMessage) {
3255 _ASSIGN_eventName(eBlur, "eBlur");
3256 _ASSIGN_eventName(eDrop, "eDrop");
3257 _ASSIGN_eventName(eDragEnter, "eDragEnter");
3258 _ASSIGN_eventName(eDragExit, "eDragExit");
3259 _ASSIGN_eventName(eDragOver, "eDragOver");
3260 _ASSIGN_eventName(eEditorInput, "eEditorInput");
3261 _ASSIGN_eventName(eFocus, "eFocus");
3262 _ASSIGN_eventName(eFocusIn, "eFocusIn");
3263 _ASSIGN_eventName(eFocusOut, "eFocusOut");
3264 _ASSIGN_eventName(eFormSelect, "eFormSelect");
3265 _ASSIGN_eventName(eFormChange, "eFormChange");
3266 _ASSIGN_eventName(eFormReset, "eFormReset");
3267 _ASSIGN_eventName(eFormSubmit, "eFormSubmit");
3268 _ASSIGN_eventName(eImageAbort, "eImageAbort");
3269 _ASSIGN_eventName(eLoadError, "eLoadError");
3270 _ASSIGN_eventName(eKeyDown, "eKeyDown");
3271 _ASSIGN_eventName(eKeyPress, "eKeyPress");
3272 _ASSIGN_eventName(eKeyUp, "eKeyUp");
3273 _ASSIGN_eventName(eMouseEnterIntoWidget, "eMouseEnterIntoWidget");
3274 _ASSIGN_eventName(eMouseExitFromWidget, "eMouseExitFromWidget");
3275 _ASSIGN_eventName(eMouseDown, "eMouseDown");
3276 _ASSIGN_eventName(eMouseUp, "eMouseUp");
3277 _ASSIGN_eventName(eMouseClick, "eMouseClick");
3278 _ASSIGN_eventName(eMouseAuxClick, "eMouseAuxClick");
3279 _ASSIGN_eventName(eMouseDoubleClick, "eMouseDoubleClick");
3280 _ASSIGN_eventName(eMouseMove, "eMouseMove");
3281 _ASSIGN_eventName(eLoad, "eLoad");
3282 _ASSIGN_eventName(ePopState, "ePopState");
3283 _ASSIGN_eventName(eBeforeScriptExecute, "eBeforeScriptExecute");
3284 _ASSIGN_eventName(eAfterScriptExecute, "eAfterScriptExecute");
3285 _ASSIGN_eventName(eUnload, "eUnload");
3286 _ASSIGN_eventName(eHashChange, "eHashChange");
3287 _ASSIGN_eventName(eReadyStateChange, "eReadyStateChange");
3288 _ASSIGN_eventName(eXULBroadcast, "eXULBroadcast");
3289 _ASSIGN_eventName(eXULCommandUpdate, "eXULCommandUpdate");
3291 # undef _ASSIGN_eventName
3293 default: {
3294 eventName.AssignLiteral("UNKNOWN: ");
3295 eventName.AppendInt(aGuiEvent->mMessage);
3296 } break;
3299 return nsAutoString(eventName);
3301 //////////////////////////////////////////////////////////////
3303 // Code to deal with paint and event debug prefs.
3305 //////////////////////////////////////////////////////////////
3306 struct PrefPair {
3307 const char* name;
3308 bool value;
3311 static PrefPair debug_PrefValues[] = {
3312 {"nglayout.debug.crossing_event_dumping", false},
3313 {"nglayout.debug.event_dumping", false},
3314 {"nglayout.debug.invalidate_dumping", false},
3315 {"nglayout.debug.motion_event_dumping", false},
3316 {"nglayout.debug.paint_dumping", false}};
3318 //////////////////////////////////////////////////////////////
3319 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName) {
3320 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3322 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3323 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3324 return debug_PrefValues[i].value;
3328 return false;
3330 //////////////////////////////////////////////////////////////
3331 static void debug_SetCachedBoolPref(const char* aPrefName, bool aValue) {
3332 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3334 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3335 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3336 debug_PrefValues[i].value = aValue;
3338 return;
3342 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3345 //////////////////////////////////////////////////////////////
3346 class Debug_PrefObserver final : public nsIObserver {
3347 ~Debug_PrefObserver() = default;
3349 public:
3350 NS_DECL_ISUPPORTS
3351 NS_DECL_NSIOBSERVER
3354 NS_IMPL_ISUPPORTS(Debug_PrefObserver, nsIObserver)
3356 NS_IMETHODIMP
3357 Debug_PrefObserver::Observe(nsISupports* subject, const char* topic,
3358 const char16_t* data) {
3359 NS_ConvertUTF16toUTF8 prefName(data);
3361 bool value = Preferences::GetBool(prefName.get(), false);
3362 debug_SetCachedBoolPref(prefName.get(), value);
3363 return NS_OK;
3366 //////////////////////////////////////////////////////////////
3367 /* static */ void debug_RegisterPrefCallbacks() {
3368 static bool once = true;
3370 if (!once) {
3371 return;
3374 once = false;
3376 nsCOMPtr<nsIObserver> obs(new Debug_PrefObserver());
3377 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3378 // Initialize the pref values
3379 debug_PrefValues[i].value =
3380 Preferences::GetBool(debug_PrefValues[i].name, false);
3382 if (obs) {
3383 // Register callbacks for when these change
3384 nsCString name;
3385 name.AssignLiteral(debug_PrefValues[i].name,
3386 strlen(debug_PrefValues[i].name));
3387 Preferences::AddStrongObserver(obs, name);
3391 //////////////////////////////////////////////////////////////
3392 static int32_t _GetPrintCount() {
3393 static int32_t sCount = 0;
3395 return ++sCount;
3397 //////////////////////////////////////////////////////////////
3398 /* static */
3399 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut, nsIWidget* aWidget,
3400 WidgetGUIEvent* aGuiEvent,
3401 const char* aWidgetName, int32_t aWindowID) {
3402 if (aGuiEvent->mMessage == eMouseMove) {
3403 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3406 if (aGuiEvent->mMessage == eMouseEnterIntoWidget ||
3407 aGuiEvent->mMessage == eMouseExitFromWidget) {
3408 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3409 return;
3412 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3414 NS_LossyConvertUTF16toASCII tempString(
3415 debug_GuiEventToString(aGuiEvent).get());
3417 fprintf(aFileOut, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3418 _GetPrintCount(), tempString.get(), (void*)aWidget, aWidgetName,
3419 aWindowID, aGuiEvent->mRefPoint.x.value,
3420 aGuiEvent->mRefPoint.y.value);
3422 //////////////////////////////////////////////////////////////
3423 /* static */
3424 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut, nsIWidget* aWidget,
3425 const nsIntRegion& aRegion,
3426 const char* aWidgetName,
3427 int32_t aWindowID) {
3428 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3429 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3431 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3433 nsIntRect rect = aRegion.GetBounds();
3434 fprintf(aFileOut,
3435 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3436 "%3d,%-3d",
3437 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID, rect.X(),
3438 rect.Y(), rect.Width(), rect.Height());
3440 fprintf(aFileOut, "\n");
3442 //////////////////////////////////////////////////////////////
3443 /* static */
3444 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut, nsIWidget* aWidget,
3445 const LayoutDeviceIntRect* aRect,
3446 const char* aWidgetName,
3447 int32_t aWindowID) {
3448 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3450 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3451 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3453 fprintf(aFileOut, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3454 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID);
3456 if (aRect) {
3457 fprintf(aFileOut, " rect=%3d,%-3d %3d,%-3d", aRect->X(), aRect->Y(),
3458 aRect->Width(), aRect->Height());
3459 } else {
3460 fprintf(aFileOut, " rect=%-15s", "none");
3463 fprintf(aFileOut, "\n");
3465 //////////////////////////////////////////////////////////////
3467 #endif // DEBUG