Bug 1784772 - Queue SwipeEventQueue only if we don't know whether the pan event wasn...
[gecko.git] / widget / nsBaseWidget.cpp
blobc2a902ac72e5590452fa159aaf4d10f4888032c4
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() && inputBlockId) {
1096 // EventStateManager did not route the event into the child process.
1097 // It's safe to communicate to APZ that the event has been processed.
1098 // Note that here aGuid.mLayersId might be different from
1099 // mCompositorSession->RootLayerTreeId() because the event might have gotten
1100 // hit-tested by APZ to be targeted at a child process, but a parent process
1101 // event listener called preventDefault on it. In that case aGuid.mLayersId
1102 // would still be the layers id for the child process, but the event would
1103 // not have actually gotten routed to the child process. The main-thread
1104 // hit-test result therefore needs to use the parent process layers id.
1105 LayersId rootLayersId = mCompositorSession->RootLayerTreeId();
1107 RefPtr<DisplayportSetListener> postLayerization;
1108 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
1109 nsTArray<TouchBehaviorFlags> allowedTouchBehaviors;
1110 if (touchEvent->mMessage == eTouchStart) {
1111 auto& originalEvent = *original->AsTouchEvent();
1112 MOZ_ASSERT(NS_IsMainThread());
1113 allowedTouchBehaviors = TouchActionHelper::GetAllowedTouchBehavior(
1114 this, GetDocument(), originalEvent);
1115 if (!allowedTouchBehaviors.IsEmpty()) {
1116 mAPZC->SetAllowedTouchBehavior(inputBlockId, allowedTouchBehaviors);
1118 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1119 this, GetDocument(), originalEvent, rootLayersId, inputBlockId);
1121 mAPZEventState->ProcessTouchEvent(*touchEvent, targetGuid, inputBlockId,
1122 aApzResult.GetStatus(), status,
1123 std::move(allowedTouchBehaviors));
1124 } else if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1125 MOZ_ASSERT(wheelEvent->mFlags.mHandledByAPZ);
1126 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1127 this, GetDocument(), *original->AsWheelEvent(), rootLayersId,
1128 inputBlockId);
1129 if (wheelEvent->mCanTriggerSwipe) {
1130 ReportSwipeStarted(inputBlockId, wheelEvent->TriggersSwipe());
1132 mAPZEventState->ProcessWheelEvent(*wheelEvent, inputBlockId);
1133 } else if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1134 MOZ_ASSERT(mouseEvent->mFlags.mHandledByAPZ);
1135 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
1136 this, GetDocument(), *original->AsMouseEvent(), rootLayersId,
1137 inputBlockId);
1138 mAPZEventState->ProcessMouseEvent(*mouseEvent, inputBlockId);
1140 if (postLayerization) {
1141 postLayerization->Register();
1145 return status;
1148 template <class InputType, class EventType>
1149 class DispatchEventOnMainThread : public Runnable {
1150 public:
1151 DispatchEventOnMainThread(const InputType& aInput, nsBaseWidget* aWidget,
1152 const APZEventResult& aAPZResult)
1153 : mozilla::Runnable("DispatchEventOnMainThread"),
1154 mInput(aInput),
1155 mWidget(aWidget),
1156 mAPZResult(aAPZResult) {}
1158 NS_IMETHOD Run() override {
1159 EventType event = mInput.ToWidgetEvent(mWidget);
1160 mWidget->ProcessUntransformedAPZEvent(&event, mAPZResult);
1161 return NS_OK;
1164 private:
1165 InputType mInput;
1166 nsBaseWidget* mWidget;
1167 APZEventResult mAPZResult;
1170 template <class InputType, class EventType>
1171 class DispatchInputOnControllerThread : public Runnable {
1172 public:
1173 DispatchInputOnControllerThread(const EventType& aEvent,
1174 IAPZCTreeManager* aAPZC,
1175 nsBaseWidget* aWidget)
1176 : mozilla::Runnable("DispatchInputOnControllerThread"),
1177 mMainMessageLoop(MessageLoop::current()),
1178 mInput(aEvent),
1179 mAPZC(aAPZC),
1180 mWidget(aWidget) {}
1182 NS_IMETHOD Run() override {
1183 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(mInput);
1184 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1185 return NS_OK;
1187 RefPtr<Runnable> r = new DispatchEventOnMainThread<InputType, EventType>(
1188 mInput, mWidget, result);
1189 mMainMessageLoop->PostTask(r.forget());
1190 return NS_OK;
1193 private:
1194 MessageLoop* mMainMessageLoop;
1195 InputType mInput;
1196 RefPtr<IAPZCTreeManager> mAPZC;
1197 nsBaseWidget* mWidget;
1200 void nsBaseWidget::DispatchTouchInput(MultiTouchInput& aInput,
1201 uint16_t aInputSource) {
1202 MOZ_ASSERT(NS_IsMainThread());
1203 MOZ_ASSERT(aInputSource ==
1204 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH ||
1205 aInputSource == mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN);
1206 if (mAPZC) {
1207 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1209 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1210 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1211 return;
1214 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1215 ProcessUntransformedAPZEvent(&event, result);
1216 } else {
1217 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1219 nsEventStatus status;
1220 DispatchEvent(&event, status);
1224 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput& aInput) {
1225 MOZ_ASSERT(NS_IsMainThread());
1226 if (mAPZC) {
1227 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1229 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1230 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1231 return;
1234 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1235 ProcessUntransformedAPZEvent(&event, result);
1236 } else {
1237 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1238 nsEventStatus status;
1239 DispatchEvent(&event, status);
1243 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput& aInput) {
1244 MOZ_ASSERT(NS_IsMainThread());
1245 if (mAPZC) {
1246 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1247 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1249 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1250 return;
1252 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1253 ProcessUntransformedAPZEvent(&event, result);
1254 } else {
1255 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1256 nsEventStatus status;
1257 DispatchEvent(&event, status);
1261 nsIWidget::ContentAndAPZEventStatus nsBaseWidget::DispatchInputEvent(
1262 WidgetInputEvent* aEvent) {
1263 nsIWidget::ContentAndAPZEventStatus status;
1264 MOZ_ASSERT(NS_IsMainThread());
1265 if (mAPZC) {
1266 if (APZThreadUtils::IsControllerThread()) {
1267 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1268 status.mApzStatus = result.GetStatus();
1269 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1270 return status;
1272 status.mContentStatus = ProcessUntransformedAPZEvent(aEvent, result);
1273 return status;
1275 if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1276 RefPtr<Runnable> r =
1277 new DispatchInputOnControllerThread<ScrollWheelInput,
1278 WidgetWheelEvent>(*wheelEvent,
1279 mAPZC, this);
1280 APZThreadUtils::RunOnControllerThread(std::move(r));
1281 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1282 return status;
1284 if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1285 RefPtr<Runnable> r =
1286 new DispatchInputOnControllerThread<MouseInput, WidgetMouseEvent>(
1287 *mouseEvent, mAPZC, this);
1288 APZThreadUtils::RunOnControllerThread(std::move(r));
1289 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1290 return status;
1292 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
1293 RefPtr<Runnable> r =
1294 new DispatchInputOnControllerThread<MultiTouchInput,
1295 WidgetTouchEvent>(*touchEvent,
1296 mAPZC, this);
1297 APZThreadUtils::RunOnControllerThread(std::move(r));
1298 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1299 return status;
1301 // Allow dispatching keyboard events on Gecko thread.
1302 MOZ_ASSERT(aEvent->AsKeyboardEvent());
1305 DispatchEvent(aEvent, status.mContentStatus);
1306 return status;
1309 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent* aEvent) {
1310 MOZ_ASSERT(NS_IsMainThread());
1311 if (mAPZC) {
1312 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1313 mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1317 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent& event) {
1318 nsEventStatus status;
1319 DispatchEvent(&event, status);
1320 return ConvertStatus(status);
1323 Document* nsBaseWidget::GetDocument() const {
1324 if (mWidgetListener) {
1325 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1326 return presShell->GetDocument();
1329 return nullptr;
1332 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1333 // Parent directly listens to the vsync source whereas
1334 // child process communicate via IPC
1335 // Should be called AFTER gfxPlatform is initialized
1336 if (XRE_IsParentProcess()) {
1337 if (!mCompositorVsyncDispatcherLock) {
1338 mCompositorVsyncDispatcherLock =
1339 MakeUnique<Mutex>("mCompositorVsyncDispatcherLock");
1341 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1342 if (!mCompositorVsyncDispatcher) {
1343 RefPtr<VsyncDispatcher> vsyncDispatcher =
1344 gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
1345 mCompositorVsyncDispatcher =
1346 new CompositorVsyncDispatcher(std::move(vsyncDispatcher));
1351 already_AddRefed<CompositorVsyncDispatcher>
1352 nsBaseWidget::GetCompositorVsyncDispatcher() {
1353 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
1355 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1356 RefPtr<CompositorVsyncDispatcher> dispatcher = mCompositorVsyncDispatcher;
1357 return dispatcher.forget();
1360 already_AddRefed<WebRenderLayerManager> nsBaseWidget::CreateCompositorSession(
1361 int aWidth, int aHeight, CompositorOptions* aOptionsOut) {
1362 MOZ_ASSERT(aOptionsOut);
1364 do {
1365 CreateCompositorVsyncDispatcher();
1367 gfx::GPUProcessManager* gpu = gfx::GPUProcessManager::Get();
1368 // Make sure GPU process is ready for use.
1369 // If it failed to connect to GPU process, GPU process usage is disabled in
1370 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1371 gpu->EnsureGPUReady();
1373 // If widget type does not supports acceleration, we may be allowed to use
1374 // software WebRender instead.
1375 bool supportsAcceleration = WidgetTypeSupportsAcceleration();
1376 bool enableSWWR = true;
1377 if (supportsAcceleration ||
1378 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1379 enableSWWR = gfx::gfxVars::UseSoftwareWebRender();
1381 bool enableAPZ = UseAPZ();
1382 CompositorOptions options(enableAPZ, enableSWWR);
1384 #ifdef XP_WIN
1385 if (supportsAcceleration) {
1386 options.SetAllowSoftwareWebRenderD3D11(
1387 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1389 if (mNeedFastSnaphot) {
1390 options.SetNeedFastSnaphot(true);
1392 #elif defined(MOZ_WIDGET_ANDROID)
1393 MOZ_ASSERT(supportsAcceleration);
1394 options.SetAllowSoftwareWebRenderOGL(
1395 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1396 #elif defined(MOZ_WIDGET_GTK)
1397 if (supportsAcceleration) {
1398 options.SetAllowSoftwareWebRenderOGL(
1399 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1401 #endif
1403 #ifdef MOZ_WIDGET_ANDROID
1404 // Unconditionally set the compositor as initially paused, as we have not
1405 // yet had a chance to send the compositor surface to the GPU process. We
1406 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1407 // where we will also resume the compositor if required.
1408 options.SetInitiallyPaused(true);
1409 #else
1410 options.SetInitiallyPaused(CompositorInitiallyPaused());
1411 #endif
1413 RefPtr<WebRenderLayerManager> lm = new WebRenderLayerManager(this);
1415 uint64_t innerWindowId = 0;
1416 if (Document* doc = GetDocument()) {
1417 innerWindowId = doc->InnerWindowID();
1420 bool retry = false;
1421 mCompositorSession = gpu->CreateTopLevelCompositor(
1422 this, lm, GetDefaultScale(), options, UseExternalCompositingSurface(),
1423 gfx::IntSize(aWidth, aHeight), innerWindowId, &retry);
1425 if (mCompositorSession) {
1426 TextureFactoryIdentifier textureFactoryIdentifier;
1427 nsCString error;
1428 lm->Initialize(mCompositorSession->GetCompositorBridgeChild(),
1429 wr::AsPipelineId(mCompositorSession->RootLayerTreeId()),
1430 &textureFactoryIdentifier, error);
1431 if (textureFactoryIdentifier.mParentBackend != LayersBackend::LAYERS_WR) {
1432 retry = true;
1433 DestroyCompositor();
1434 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1435 gfx::GPUProcessManager::Get()->DisableWebRender(
1436 wr::WebRenderError::INITIALIZE, error);
1440 // We need to retry in a loop because the act of failing to create the
1441 // compositor can change our state (e.g. disable WebRender).
1442 if (mCompositorSession || !retry) {
1443 *aOptionsOut = options;
1444 return lm.forget();
1446 } while (true);
1449 void nsBaseWidget::CreateCompositor(int aWidth, int aHeight) {
1450 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1451 gfxPlatform::GetPlatform();
1453 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1454 "This function assumes OMTC");
1456 MOZ_ASSERT(!mCompositorSession && !mCompositorBridgeChild,
1457 "Should have properly cleaned up the previous PCompositor pair "
1458 "beforehand");
1460 if (mCompositorBridgeChild) {
1461 mCompositorBridgeChild->Destroy();
1464 // Recreating this is tricky, as we may still have an old and we need
1465 // to make sure it's properly destroyed by calling DestroyCompositor!
1467 // If we've already received a shutdown notification, don't try
1468 // create a new compositor.
1469 if (!mShutdownObserver) {
1470 return;
1473 // The controller thread must be configured before the compositor
1474 // session is created, so that the input bridge runs on the right
1475 // thread.
1476 ConfigureAPZControllerThread();
1478 CompositorOptions options;
1479 RefPtr<WebRenderLayerManager> lm =
1480 CreateCompositorSession(aWidth, aHeight, &options);
1481 if (!lm) {
1482 return;
1485 MOZ_ASSERT(mCompositorSession);
1486 mCompositorBridgeChild = mCompositorSession->GetCompositorBridgeChild();
1487 SetCompositorWidgetDelegate(
1488 mCompositorSession->GetCompositorWidgetDelegate());
1490 if (options.UseAPZ()) {
1491 mAPZC = mCompositorSession->GetAPZCTreeManager();
1492 ConfigureAPZCTreeManager();
1493 } else {
1494 mAPZC = nullptr;
1497 if (mInitialZoomConstraints) {
1498 UpdateZoomConstraints(mInitialZoomConstraints->mPresShellID,
1499 mInitialZoomConstraints->mViewID,
1500 Some(mInitialZoomConstraints->mConstraints));
1501 mInitialZoomConstraints.reset();
1504 TextureFactoryIdentifier textureFactoryIdentifier =
1505 lm->GetTextureFactoryIdentifier();
1506 MOZ_ASSERT(textureFactoryIdentifier.mParentBackend ==
1507 LayersBackend::LAYERS_WR);
1508 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1509 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1511 WindowUsesOMTC();
1513 mWindowRenderer = std::move(lm);
1515 // Only track compositors for top-level windows, since other window types
1516 // may use the basic compositor. Except on the OS X - see bug 1306383
1517 #if defined(XP_MACOSX)
1518 bool getCompositorFromThisWindow = true;
1519 #else
1520 bool getCompositorFromThisWindow = mWindowType == WindowType::TopLevel;
1521 #endif
1523 if (getCompositorFromThisWindow) {
1524 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1525 mWindowRenderer->GetCompositorBackendType());
1529 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession* aSession) {
1530 MOZ_ASSERT(aSession == mCompositorSession);
1531 DestroyLayerManager();
1534 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1535 return gfxPlatform::UsesOffMainThreadCompositing();
1538 WindowRenderer* nsBaseWidget::GetWindowRenderer() {
1539 if (!mWindowRenderer) {
1540 if (!mShutdownObserver) {
1541 // We are shutting down, do not try to re-create a LayerManager
1542 return nullptr;
1544 // Try to use an async compositor first, if possible
1545 if (ShouldUseOffMainThreadCompositing()) {
1546 CreateCompositor();
1549 if (!mWindowRenderer) {
1550 mWindowRenderer = CreateFallbackRenderer();
1553 return mWindowRenderer;
1556 WindowRenderer* nsBaseWidget::CreateFallbackRenderer() {
1557 return new FallbackRenderer;
1560 CompositorBridgeChild* nsBaseWidget::GetRemoteRenderer() {
1561 return mCompositorBridgeChild;
1564 void nsBaseWidget::ClearCachedWebrenderResources() {
1565 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
1566 return;
1568 mWindowRenderer->AsWebRender()->ClearCachedResources();
1571 void nsBaseWidget::ClearWebrenderAnimationResources() {
1572 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
1573 return;
1575 mWindowRenderer->AsWebRender()->ClearAnimationResources();
1578 bool nsBaseWidget::SetNeedFastSnaphot() {
1579 MOZ_ASSERT(XRE_IsParentProcess());
1580 MOZ_ASSERT(!mCompositorSession);
1582 if (!XRE_IsParentProcess() || mCompositorSession) {
1583 return false;
1586 mNeedFastSnaphot = true;
1587 return true;
1590 already_AddRefed<gfx::DrawTarget> nsBaseWidget::StartRemoteDrawing() {
1591 return nullptr;
1594 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA; }
1596 //-------------------------------------------------------------------------
1598 // Destroy the window
1600 //-------------------------------------------------------------------------
1601 void nsBaseWidget::OnDestroy() {
1602 if (mTextEventDispatcher) {
1603 mTextEventDispatcher->OnDestroyWidget();
1604 // Don't release it until this widget actually released because after this
1605 // is called, TextEventDispatcher() may create it again.
1608 // If this widget is being destroyed, let the APZ code know to drop references
1609 // to this widget. Callers of this function all should be holding a deathgrip
1610 // on this widget already.
1611 ReleaseContentController();
1614 void nsBaseWidget::MoveClient(const DesktopPoint& aOffset) {
1615 LayoutDeviceIntPoint clientOffset(GetClientOffset());
1617 // GetClientOffset returns device pixels; scale back to desktop pixels
1618 // if that's what this widget uses for the Move/Resize APIs
1619 if (BoundsUseDesktopPixels()) {
1620 DesktopPoint desktopOffset = clientOffset / GetDesktopToDeviceScale();
1621 Move(aOffset.x - desktopOffset.x, aOffset.y - desktopOffset.y);
1622 } else {
1623 LayoutDevicePoint layoutOffset = aOffset * GetDesktopToDeviceScale();
1624 Move(layoutOffset.x - LayoutDeviceCoord(clientOffset.x),
1625 layoutOffset.y - LayoutDeviceCoord(clientOffset.y));
1629 void nsBaseWidget::ResizeClient(const DesktopSize& aSize, bool aRepaint) {
1630 NS_ASSERTION((aSize.width >= 0), "Negative width passed to ResizeClient");
1631 NS_ASSERTION((aSize.height >= 0), "Negative height passed to ResizeClient");
1633 LayoutDeviceIntRect clientBounds = GetClientBounds();
1635 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1636 // if that's what this widget uses for the Move/Resize APIs
1637 if (BoundsUseDesktopPixels()) {
1638 DesktopSize desktopDelta =
1639 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1640 clientBounds.Size()) /
1641 GetDesktopToDeviceScale();
1642 Resize(aSize.width + desktopDelta.width, aSize.height + desktopDelta.height,
1643 aRepaint);
1644 } else {
1645 LayoutDeviceSize layoutSize = aSize * GetDesktopToDeviceScale();
1646 Resize(mBounds.Width() + (layoutSize.width - clientBounds.Width()),
1647 mBounds.Height() + (layoutSize.height - clientBounds.Height()),
1648 aRepaint);
1652 void nsBaseWidget::ResizeClient(const DesktopRect& aRect, bool aRepaint) {
1653 NS_ASSERTION((aRect.Width() >= 0), "Negative width passed to ResizeClient");
1654 NS_ASSERTION((aRect.Height() >= 0), "Negative height passed to ResizeClient");
1656 LayoutDeviceIntRect clientBounds = GetClientBounds();
1657 LayoutDeviceIntPoint clientOffset = GetClientOffset();
1658 DesktopToLayoutDeviceScale scale = GetDesktopToDeviceScale();
1660 if (BoundsUseDesktopPixels()) {
1661 DesktopPoint desktopOffset = clientOffset / scale;
1662 DesktopSize desktopDelta =
1663 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1664 clientBounds.Size()) /
1665 scale;
1666 Resize(aRect.X() - desktopOffset.x, aRect.Y() - desktopOffset.y,
1667 aRect.Width() + desktopDelta.width,
1668 aRect.Height() + desktopDelta.height, aRepaint);
1669 } else {
1670 LayoutDeviceRect layoutRect = aRect * scale;
1671 Resize(layoutRect.X() - clientOffset.x, layoutRect.Y() - clientOffset.y,
1672 layoutRect.Width() + mBounds.Width() - clientBounds.Width(),
1673 layoutRect.Height() + mBounds.Height() - clientBounds.Height(),
1674 aRepaint);
1678 //-------------------------------------------------------------------------
1680 // Bounds
1682 //-------------------------------------------------------------------------
1685 * If the implementation of nsWindow supports borders this method MUST be
1686 * overridden
1689 LayoutDeviceIntRect nsBaseWidget::GetClientBounds() { return GetBounds(); }
1692 * If the implementation of nsWindow supports borders this method MUST be
1693 * overridden
1696 LayoutDeviceIntRect nsBaseWidget::GetBounds() { return mBounds; }
1699 * If the implementation of nsWindow uses a local coordinate system within the
1700 *window, this method must be overridden
1703 LayoutDeviceIntRect nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1705 nsresult nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect& aRect) {
1706 if (SizeMode() != nsSizeMode_Normal) {
1707 return NS_ERROR_FAILURE;
1709 aRect = GetScreenBounds();
1710 return NS_OK;
1713 LayoutDeviceIntPoint nsBaseWidget::GetClientOffset() {
1714 return LayoutDeviceIntPoint(0, 0);
1717 nsresult nsBaseWidget::SetNonClientMargins(const LayoutDeviceIntMargin&) {
1718 return NS_ERROR_NOT_IMPLEMENTED;
1721 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin) {}
1723 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1725 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1727 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect* aResizerRect) {
1728 return false;
1732 * Modifies aFile to point at an icon file with the given name and suffix. The
1733 * suffix may correspond to a file extension with leading '.' if appropriate.
1734 * Returns true if the icon file exists and can be read.
1736 static bool ResolveIconNameHelper(nsIFile* aFile, const nsAString& aIconName,
1737 const nsAString& aIconSuffix) {
1738 aFile->Append(u"icons"_ns);
1739 aFile->Append(u"default"_ns);
1740 aFile->Append(aIconName + aIconSuffix);
1742 bool readable;
1743 return NS_SUCCEEDED(aFile->IsReadable(&readable)) && readable;
1747 * Resolve the given icon name into a local file object. This method is
1748 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1749 * platform specific icon file suffix (e.g., ".ico" under Win32).
1751 * If no file is found matching the given parameters, then null is returned.
1753 void nsBaseWidget::ResolveIconName(const nsAString& aIconName,
1754 const nsAString& aIconSuffix,
1755 nsIFile** aResult) {
1756 *aResult = nullptr;
1758 nsCOMPtr<nsIProperties> dirSvc =
1759 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
1760 if (!dirSvc) return;
1762 // first check auxilary chrome directories
1764 nsCOMPtr<nsISimpleEnumerator> dirs;
1765 dirSvc->Get(NS_APP_CHROME_DIR_LIST, NS_GET_IID(nsISimpleEnumerator),
1766 getter_AddRefs(dirs));
1767 if (dirs) {
1768 bool hasMore;
1769 while (NS_SUCCEEDED(dirs->HasMoreElements(&hasMore)) && hasMore) {
1770 nsCOMPtr<nsISupports> element;
1771 dirs->GetNext(getter_AddRefs(element));
1772 if (!element) continue;
1773 nsCOMPtr<nsIFile> file = do_QueryInterface(element);
1774 if (!file) continue;
1775 if (ResolveIconNameHelper(file, aIconName, aIconSuffix)) {
1776 NS_ADDREF(*aResult = file);
1777 return;
1782 // then check the main app chrome directory
1784 nsCOMPtr<nsIFile> file;
1785 dirSvc->Get(NS_APP_CHROME_DIR, NS_GET_IID(nsIFile), getter_AddRefs(file));
1786 if (file && ResolveIconNameHelper(file, aIconName, aIconSuffix))
1787 NS_ADDREF(*aResult = file);
1790 void nsBaseWidget::SetSizeConstraints(const SizeConstraints& aConstraints) {
1791 mSizeConstraints = aConstraints;
1793 // Popups are constrained during layout, and we don't want to synchronously
1794 // paint from reflow, so bail out... This is not great, but it's no worse than
1795 // what we used to do.
1797 // The right fix here is probably making constraint changes go through the
1798 // view manager and such.
1799 if (mWindowType == WindowType::Popup) {
1800 return;
1803 // If the current size doesn't meet the new constraints, trigger a
1804 // resize to apply it. Note that, we don't want to invoke Resize if
1805 // the new constraints don't affect the current size, because Resize
1806 // implementation on some platforms may touch other geometry even if
1807 // the size don't need to change.
1808 LayoutDeviceIntSize curSize = mBounds.Size();
1809 LayoutDeviceIntSize clampedSize =
1810 Max(aConstraints.mMinSize, Min(aConstraints.mMaxSize, curSize));
1811 if (clampedSize != curSize) {
1812 gfx::Size size;
1813 if (BoundsUseDesktopPixels()) {
1814 DesktopSize desktopSize = clampedSize / GetDesktopToDeviceScale();
1815 size = desktopSize.ToUnknownSize();
1816 } else {
1817 size = gfx::Size(clampedSize.ToUnknownSize());
1819 Resize(size.width, size.height, true);
1823 const widget::SizeConstraints nsBaseWidget::GetSizeConstraints() {
1824 return mSizeConstraints;
1827 // static
1828 nsIRollupListener* nsBaseWidget::GetActiveRollupListener() {
1829 // TODO: Simplify this.
1830 return nsXULPopupManager::GetInstance();
1833 void nsBaseWidget::NotifyWindowDestroyed() {
1834 if (!mWidgetListener) return;
1836 nsCOMPtr<nsIAppWindow> window = mWidgetListener->GetAppWindow();
1837 nsCOMPtr<nsIBaseWindow> appWindow(do_QueryInterface(window));
1838 if (appWindow) {
1839 appWindow->Destroy();
1843 void nsBaseWidget::NotifyWindowMoved(int32_t aX, int32_t aY,
1844 ByMoveToRect aByMoveToRect) {
1845 if (mWidgetListener) {
1846 mWidgetListener->WindowMoved(this, aX, aY, aByMoveToRect);
1849 if (mIMEHasFocus && IMENotificationRequestsRef().WantPositionChanged()) {
1850 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE));
1854 void nsBaseWidget::NotifySizeMoveDone() {
1855 if (!mWidgetListener) {
1856 return;
1858 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1859 presShell->WindowSizeMoveDone();
1863 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind) {
1864 LookAndFeel::NotifyChangedAllWindows(aKind);
1867 nsresult nsBaseWidget::NotifyIME(const IMENotification& aIMENotification) {
1868 if (mIMEHasQuit) {
1869 return NS_OK;
1871 switch (aIMENotification.mMessage) {
1872 case REQUEST_TO_COMMIT_COMPOSITION:
1873 case REQUEST_TO_CANCEL_COMPOSITION:
1874 // We should send request to IME only when there is a TextEventDispatcher
1875 // instance (this means that this widget has dispatched at least one
1876 // composition event or keyboard event) and the it has composition.
1877 // Otherwise, there is nothing to do.
1878 // Note that if current input transaction is for native input events,
1879 // TextEventDispatcher::NotifyIME() will call
1880 // TextEventDispatcherListener::NotifyIME().
1881 if (mTextEventDispatcher && mTextEventDispatcher->IsComposing()) {
1882 return mTextEventDispatcher->NotifyIME(aIMENotification);
1884 return NS_OK;
1885 default: {
1886 if (aIMENotification.mMessage == NOTIFY_IME_OF_FOCUS) {
1887 mIMEHasFocus = true;
1889 EnsureTextEventDispatcher();
1890 // TextEventDispatcher::NotifyIME() will always call
1891 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1892 // input transaction is for synthesized events for automated tests,
1893 // notifications will be sent to native IME.
1894 nsresult rv = mTextEventDispatcher->NotifyIME(aIMENotification);
1895 if (aIMENotification.mMessage == NOTIFY_IME_OF_BLUR) {
1896 mIMEHasFocus = false;
1898 return rv;
1903 void nsBaseWidget::EnsureTextEventDispatcher() {
1904 if (mTextEventDispatcher) {
1905 return;
1907 mTextEventDispatcher = new TextEventDispatcher(this);
1910 nsIWidget::NativeIMEContext nsBaseWidget::GetNativeIMEContext() {
1911 if (mTextEventDispatcher && mTextEventDispatcher->GetPseudoIMEContext()) {
1912 // If we already have a TextEventDispatcher and it's working with
1913 // a TextInputProcessor, we need to return pseudo IME context since
1914 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1915 // on the pseudo IME context in such case.
1916 NativeIMEContext pseudoIMEContext;
1917 pseudoIMEContext.InitWithRawNativeIMEContext(
1918 mTextEventDispatcher->GetPseudoIMEContext());
1919 return pseudoIMEContext;
1921 return NativeIMEContext(this);
1924 nsIWidget::TextEventDispatcher* nsBaseWidget::GetTextEventDispatcher() {
1925 EnsureTextEventDispatcher();
1926 return mTextEventDispatcher;
1929 void* nsBaseWidget::GetPseudoIMEContext() {
1930 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
1931 if (!dispatcher) {
1932 return nullptr;
1934 return dispatcher->GetPseudoIMEContext();
1937 TextEventDispatcherListener*
1938 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1939 // TODO: If all platforms supported use of TextEventDispatcher for handling
1940 // native IME and keyboard events, this method should be removed since
1941 // in such case, this is overridden by all the subclasses.
1942 return nullptr;
1945 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId,
1946 const ScrollableLayerGuid::ViewID& aViewId,
1947 const CSSRect& aRect, const uint32_t& aFlags) {
1948 if (!mCompositorSession || !mAPZC) {
1949 return;
1951 LayersId layerId = mCompositorSession->RootLayerTreeId();
1952 mAPZC->ZoomToRect(ScrollableLayerGuid(layerId, aPresShellId, aViewId),
1953 ZoomTarget{aRect}, aFlags);
1956 #ifdef ACCESSIBILITY
1958 a11y::LocalAccessible* nsBaseWidget::GetRootAccessible() {
1959 NS_ENSURE_TRUE(mWidgetListener, nullptr);
1961 PresShell* presShell = mWidgetListener->GetPresShell();
1962 NS_ENSURE_TRUE(presShell, nullptr);
1964 // If container is null then the presshell is not active. This often happens
1965 // when a preshell is being held onto for fastback.
1966 nsPresContext* presContext = presShell->GetPresContext();
1967 NS_ENSURE_TRUE(presContext->GetContainerWeak(), nullptr);
1969 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1970 // make sure it's not created at unsafe times.
1971 nsAccessibilityService* accService = GetOrCreateAccService();
1972 if (accService) {
1973 return accService->GetRootDocumentAccessible(
1974 presShell, nsContentUtils::IsSafeToRunScript());
1977 return nullptr;
1980 #endif // ACCESSIBILITY
1982 void nsBaseWidget::StartAsyncScrollbarDrag(
1983 const AsyncDragMetrics& aDragMetrics) {
1984 if (!AsyncPanZoomEnabled()) {
1985 return;
1988 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession);
1990 LayersId layersId = mCompositorSession->RootLayerTreeId();
1991 ScrollableLayerGuid guid(layersId, aDragMetrics.mPresShellId,
1992 aDragMetrics.mViewId);
1994 mAPZC->StartScrollbarDrag(guid, aDragMetrics);
1997 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
1998 const ScrollableLayerGuid& aGuid) {
1999 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2001 return mAPZC->StartAutoscroll(aGuid, aAnchorLocation);
2004 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid& aGuid) {
2005 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
2007 mAPZC->StopAutoscroll(aGuid);
2010 LayersId nsBaseWidget::GetRootLayerTreeId() {
2011 return mCompositorSession ? mCompositorSession->RootLayerTreeId()
2012 : LayersId{0};
2015 already_AddRefed<widget::Screen> nsBaseWidget::GetWidgetScreen() {
2016 ScreenManager& screenManager = ScreenManager::GetSingleton();
2017 LayoutDeviceIntRect bounds = GetScreenBounds();
2018 DesktopIntRect deskBounds = RoundedToInt(bounds / GetDesktopToDeviceScale());
2019 return screenManager.ScreenForRect(deskBounds);
2022 mozilla::DesktopToLayoutDeviceScale
2023 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
2024 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
2025 ->GetDesktopToDeviceScale();
2028 nsresult nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint,
2029 bool aLongTap,
2030 nsIObserver* aObserver) {
2031 AutoObserverNotifier notifier(aObserver, "touchtap");
2033 if (sPointerIdCounter > TOUCH_INJECT_MAX_POINTS) {
2034 sPointerIdCounter = 0;
2036 int pointerId = sPointerIdCounter;
2037 sPointerIdCounter++;
2038 nsresult rv = SynthesizeNativeTouchPoint(pointerId, TOUCH_CONTACT, aPoint,
2039 1.0, 90, nullptr);
2040 if (NS_FAILED(rv)) {
2041 return rv;
2044 if (!aLongTap) {
2045 return SynthesizeNativeTouchPoint(pointerId, TOUCH_REMOVE, aPoint, 0, 0,
2046 nullptr);
2049 // initiate a long tap
2050 int elapse = Preferences::GetInt("ui.click_hold_context_menus.delay",
2051 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC);
2052 if (!mLongTapTimer) {
2053 mLongTapTimer = NS_NewTimer();
2054 if (!mLongTapTimer) {
2055 SynthesizeNativeTouchPoint(pointerId, TOUCH_CANCEL, aPoint, 0, 0,
2056 nullptr);
2057 return NS_ERROR_UNEXPECTED;
2059 // Windows requires recuring events, so we set this to a smaller window
2060 // than the pref value.
2061 int timeout = elapse;
2062 if (timeout > TOUCH_INJECT_PUMP_TIMER_MSEC) {
2063 timeout = TOUCH_INJECT_PUMP_TIMER_MSEC;
2065 mLongTapTimer->InitWithNamedFuncCallback(
2066 OnLongTapTimerCallback, this, timeout, nsITimer::TYPE_REPEATING_SLACK,
2067 "nsIWidget::SynthesizeNativeTouchTap");
2070 // If we already have a long tap pending, cancel it. We only allow one long
2071 // tap to be active at a time.
2072 if (mLongTapTouchPoint) {
2073 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
2074 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
2077 mLongTapTouchPoint = MakeUnique<LongTapInfo>(
2078 pointerId, aPoint, TimeDuration::FromMilliseconds(elapse), aObserver);
2079 notifier.SkipNotification(); // we'll do it in the long-tap callback
2080 return NS_OK;
2083 // static
2084 void nsIWidget::OnLongTapTimerCallback(nsITimer* aTimer, void* aClosure) {
2085 auto* self = static_cast<nsIWidget*>(aClosure);
2087 if ((self->mLongTapTouchPoint->mStamp + self->mLongTapTouchPoint->mDuration) >
2088 TimeStamp::Now()) {
2089 #ifdef XP_WIN
2090 // Windows needs us to keep pumping feedback to the digitizer, so update
2091 // the pointer id with the same position.
2092 self->SynthesizeNativeTouchPoint(
2093 self->mLongTapTouchPoint->mPointerId, TOUCH_CONTACT,
2094 self->mLongTapTouchPoint->mPosition, 1.0, 90, nullptr);
2095 #endif
2096 return;
2099 AutoObserverNotifier notifier(self->mLongTapTouchPoint->mObserver,
2100 "touchtap");
2102 // finished, remove the touch point
2103 self->mLongTapTimer->Cancel();
2104 self->mLongTapTimer = nullptr;
2105 self->SynthesizeNativeTouchPoint(
2106 self->mLongTapTouchPoint->mPointerId, TOUCH_REMOVE,
2107 self->mLongTapTouchPoint->mPosition, 0, 0, nullptr);
2108 self->mLongTapTouchPoint = nullptr;
2111 float nsIWidget::GetFallbackDPI() {
2112 RefPtr<const Screen> primaryScreen =
2113 ScreenManager::GetSingleton().GetPrimaryScreen();
2114 return primaryScreen->GetDPI();
2117 CSSToLayoutDeviceScale nsIWidget::GetFallbackDefaultScale() {
2118 RefPtr<const Screen> s = ScreenManager::GetSingleton().GetPrimaryScreen();
2119 return s->GetCSSToLayoutDeviceScale(Screen::IncludeOSZoom::No);
2122 nsresult nsIWidget::ClearNativeTouchSequence(nsIObserver* aObserver) {
2123 AutoObserverNotifier notifier(aObserver, "cleartouch");
2125 // XXX This is odd. This is called by the constructor of nsIWidget. However,
2126 // at that point, nsIWidget::mLongTapTimer must be nullptr. Therefore,
2127 // this must do nothing at initializing the instance.
2128 if (!mLongTapTimer) {
2129 return NS_OK;
2131 mLongTapTimer->Cancel();
2132 mLongTapTimer = nullptr;
2133 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
2134 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
2135 mLongTapTouchPoint = nullptr;
2136 return NS_OK;
2139 MultiTouchInput nsBaseWidget::UpdateSynthesizedTouchState(
2140 MultiTouchInput* aState, mozilla::TimeStamp aTimeStamp, uint32_t aPointerId,
2141 TouchPointerState aPointerState, LayoutDeviceIntPoint aPoint,
2142 double aPointerPressure, uint32_t aPointerOrientation) {
2143 ScreenIntPoint pointerScreenPoint = ViewAs<ScreenPixel>(
2144 aPoint, PixelCastJustification::LayoutDeviceIsScreenForBounds);
2146 // We can't dispatch *aState directly because (a) dispatching
2147 // it might inadvertently modify it and (b) in the case of touchend or
2148 // touchcancel events aState will hold the touches that are
2149 // still down whereas the input dispatched needs to hold the removed
2150 // touch(es). We use |inputToDispatch| for this purpose.
2151 MultiTouchInput inputToDispatch;
2152 inputToDispatch.mInputType = MULTITOUCH_INPUT;
2153 inputToDispatch.mTimeStamp = aTimeStamp;
2155 int32_t index = aState->IndexOfTouch((int32_t)aPointerId);
2156 if (aPointerState == TOUCH_CONTACT) {
2157 if (index >= 0) {
2158 // found an existing touch point, update it
2159 SingleTouchData& point = aState->mTouches[index];
2160 point.mScreenPoint = pointerScreenPoint;
2161 point.mRotationAngle = (float)aPointerOrientation;
2162 point.mForce = (float)aPointerPressure;
2163 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_MOVE;
2164 } else {
2165 // new touch point, add it
2166 aState->mTouches.AppendElement(SingleTouchData(
2167 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2168 (float)aPointerOrientation, (float)aPointerPressure));
2169 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_START;
2171 inputToDispatch.mTouches = aState->mTouches;
2172 } else {
2173 MOZ_ASSERT(aPointerState == TOUCH_REMOVE || aPointerState == TOUCH_CANCEL);
2174 // a touch point is being lifted, so remove it from the stored list
2175 if (index >= 0) {
2176 aState->mTouches.RemoveElementAt(index);
2178 inputToDispatch.mType =
2179 (aPointerState == TOUCH_REMOVE ? MultiTouchInput::MULTITOUCH_END
2180 : MultiTouchInput::MULTITOUCH_CANCEL);
2181 inputToDispatch.mTouches.AppendElement(SingleTouchData(
2182 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
2183 (float)aPointerOrientation, (float)aPointerPressure));
2186 return inputToDispatch;
2189 void nsBaseWidget::NotifyLiveResizeStarted() {
2190 // If we have mLiveResizeListeners already non-empty, we should notify those
2191 // listeners that the resize stopped before starting anew. In theory this
2192 // should never happen because we shouldn't get nested live resize actions.
2193 NotifyLiveResizeStopped();
2194 MOZ_ASSERT(mLiveResizeListeners.IsEmpty());
2196 // If we can get the active remote tab for the current widget, suppress
2197 // the displayport on it during the live resize.
2198 if (!mWidgetListener) {
2199 return;
2201 nsCOMPtr<nsIAppWindow> appWindow = mWidgetListener->GetAppWindow();
2202 if (!appWindow) {
2203 return;
2205 mLiveResizeListeners = appWindow->GetLiveResizeListeners();
2206 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2207 mLiveResizeListeners[i]->LiveResizeStarted();
2211 void nsBaseWidget::NotifyLiveResizeStopped() {
2212 if (!mLiveResizeListeners.IsEmpty()) {
2213 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2214 mLiveResizeListeners[i]->LiveResizeStopped();
2216 mLiveResizeListeners.Clear();
2220 nsresult nsBaseWidget::AsyncEnableDragDrop(bool aEnable) {
2221 RefPtr<nsBaseWidget> kungFuDeathGrip = this;
2222 return NS_DispatchToCurrentThreadQueue(
2223 NS_NewRunnableFunction(
2224 "AsyncEnableDragDropFn",
2225 [this, aEnable, kungFuDeathGrip]() { EnableDragDrop(aEnable); }),
2226 kAsyncDragDropTimeout, EventQueuePriority::Idle);
2229 void nsBaseWidget::SwipeFinished() { mSwipeTracker = nullptr; }
2231 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId,
2232 bool aStartSwipe) {
2233 if (mSwipeEventQueue && mSwipeEventQueue->inputBlockId == aInputBlockId) {
2234 if (aStartSwipe) {
2235 PanGestureInput& startEvent = mSwipeEventQueue->queuedEvents[0];
2236 TrackScrollEventAsSwipe(startEvent, mSwipeEventQueue->allowedDirections,
2237 aInputBlockId);
2238 for (size_t i = 1; i < mSwipeEventQueue->queuedEvents.Length(); i++) {
2239 mSwipeTracker->ProcessEvent(mSwipeEventQueue->queuedEvents[i]);
2241 } else if (mAPZC) {
2242 // If the event wasn't start swipe, we need to notify it to APZ.
2243 mAPZC->SetBrowserGestureResponse(aInputBlockId,
2244 BrowserGestureResponse::NotConsumed);
2246 mSwipeEventQueue = nullptr;
2250 void nsBaseWidget::TrackScrollEventAsSwipe(
2251 const mozilla::PanGestureInput& aSwipeStartEvent,
2252 uint32_t aAllowedDirections, uint64_t aInputBlockId) {
2253 // If a swipe is currently being tracked kill it -- it's been interrupted
2254 // by another gesture event.
2255 if (mSwipeTracker) {
2256 mSwipeTracker->CancelSwipe(aSwipeStartEvent.mTimeStamp);
2257 mSwipeTracker->Destroy();
2258 mSwipeTracker = nullptr;
2261 uint32_t direction =
2262 (aSwipeStartEvent.mPanDisplacement.x > 0.0)
2263 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2264 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT;
2266 mSwipeTracker =
2267 new SwipeTracker(*this, aSwipeStartEvent, aAllowedDirections, direction);
2269 if (!mAPZC) {
2270 mCurrentPanGestureBelongsToSwipe = true;
2271 } else {
2272 // Now SwipeTracker has started consuming pan events, notify it to APZ so
2273 // that APZ can discard queued events.
2274 mAPZC->SetBrowserGestureResponse(aInputBlockId,
2275 BrowserGestureResponse::Consumed);
2279 nsBaseWidget::SwipeInfo nsBaseWidget::SendMayStartSwipe(
2280 const mozilla::PanGestureInput& aSwipeStartEvent) {
2281 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
2283 uint32_t direction =
2284 (aSwipeStartEvent.mPanDisplacement.x > 0.0)
2285 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2286 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT;
2288 // We're ready to start the animation. Tell Gecko about it, and at the same
2289 // time ask it if it really wants to start an animation for this event.
2290 // This event also reports back the directions that we can swipe in.
2291 LayoutDeviceIntPoint position = RoundedToInt(aSwipeStartEvent.mPanStartPoint *
2292 ScreenToLayoutDeviceScale(1));
2293 WidgetSimpleGestureEvent geckoEvent = SwipeTracker::CreateSwipeGestureEvent(
2294 eSwipeGestureMayStart, this, position, aSwipeStartEvent.mTimeStamp);
2295 geckoEvent.mDirection = direction;
2296 geckoEvent.mDelta = 0.0;
2297 geckoEvent.mAllowedDirections = 0;
2298 bool shouldStartSwipe =
2299 DispatchWindowEvent(geckoEvent); // event cancelled == swipe should start
2301 SwipeInfo result = {shouldStartSwipe, geckoEvent.mAllowedDirections};
2302 return result;
2305 WidgetWheelEvent nsBaseWidget::MayStartSwipeForAPZ(
2306 const PanGestureInput& aPanInput, const APZEventResult& aApzResult) {
2307 WidgetWheelEvent event = aPanInput.ToWidgetEvent(this);
2308 if (aPanInput.AllowsSwipe()) {
2309 SwipeInfo swipeInfo = SendMayStartSwipe(aPanInput);
2310 event.mCanTriggerSwipe = swipeInfo.wantsSwipe;
2311 if (swipeInfo.wantsSwipe) {
2312 if (aApzResult.GetStatus() == nsEventStatus_eIgnore) {
2313 // APZ has determined and that scrolling horizontally in the
2314 // requested direction is impossible, so it didn't do any
2315 // scrolling for the event.
2316 // We know now that MayStartSwipe wants a swipe, so we can start
2317 // the swipe now.
2318 TrackScrollEventAsSwipe(aPanInput, swipeInfo.allowedDirections,
2319 aApzResult.mInputBlockId);
2320 } else if (!aApzResult.GetHandledResult() ||
2321 !aApzResult.GetHandledResult()->IsHandledByRoot()) {
2322 // We don't know whether this event can start a swipe, so we need
2323 // to queue up events and wait for a call to ReportSwipeStarted.
2324 // APZ might already have started scrolling in response to the
2325 // event if it knew that it's the right thing to do. In that case
2326 // we'll still get a call to ReportSwipeStarted, and we will
2327 // discard the queued events at that point.
2328 mSwipeEventQueue = MakeUnique<SwipeEventQueue>(
2329 swipeInfo.allowedDirections, aApzResult.mInputBlockId);
2331 } else {
2332 // Inform that the browser gesture didn't use the pan event (pan-start
2333 // precisely), so that APZ can now start using the event for
2334 // scrolling/overscrolling.
2335 mAPZC->SetBrowserGestureResponse(aApzResult.mInputBlockId,
2336 BrowserGestureResponse::NotConsumed);
2340 if (mSwipeEventQueue &&
2341 mSwipeEventQueue->inputBlockId == aApzResult.mInputBlockId) {
2342 mSwipeEventQueue->queuedEvents.AppendElement(aPanInput);
2345 return event;
2348 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput& aPanInput) {
2349 if (aPanInput.mType == PanGestureInput::PANGESTURE_MAYSTART ||
2350 aPanInput.mType == PanGestureInput::PANGESTURE_START) {
2351 mCurrentPanGestureBelongsToSwipe = false;
2353 if (mCurrentPanGestureBelongsToSwipe) {
2354 // Ignore this event. It's a momentum event from a scroll gesture
2355 // that was processed as a swipe, and the swipe animation has
2356 // already finished (so mSwipeTracker is already null).
2357 MOZ_ASSERT(aPanInput.IsMomentum(),
2358 "If the fingers are still on the touchpad, we should still have "
2359 "a SwipeTracker, "
2360 "and it should have consumed this event.");
2361 return true;
2364 if (!aPanInput.MayTriggerSwipe()) {
2365 return false;
2368 SwipeInfo swipeInfo = SendMayStartSwipe(aPanInput);
2370 // We're in the non-APZ case here, but we still want to know whether
2371 // the event was routed to a child process, so we use InputAPZContext
2372 // to get that piece of information.
2373 ScrollableLayerGuid guid;
2374 uint64_t blockId = 0;
2375 InputAPZContext context(guid, blockId, nsEventStatus_eIgnore);
2377 WidgetWheelEvent event = aPanInput.ToWidgetEvent(this);
2378 event.mCanTriggerSwipe = swipeInfo.wantsSwipe;
2379 nsEventStatus status;
2380 DispatchEvent(&event, status);
2381 if (swipeInfo.wantsSwipe) {
2382 if (context.WasRoutedToChildProcess()) {
2383 // We don't know whether this event can start a swipe, so we need
2384 // to queue up events and wait for a call to ReportSwipeStarted.
2385 mSwipeEventQueue =
2386 MakeUnique<SwipeEventQueue>(swipeInfo.allowedDirections, blockId);
2387 } else if (event.TriggersSwipe()) {
2388 TrackScrollEventAsSwipe(aPanInput, swipeInfo.allowedDirections, blockId);
2392 if (mSwipeEventQueue && mSwipeEventQueue->inputBlockId == 0) {
2393 mSwipeEventQueue->queuedEvents.AppendElement(aPanInput);
2396 return true;
2399 const IMENotificationRequests& nsIWidget::IMENotificationRequestsRef() {
2400 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
2401 return dispatcher->IMENotificationRequestsRef();
2404 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent* aEvent) {}
2406 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType,
2407 const WidgetKeyboardEvent& aEvent,
2408 nsTArray<CommandInt>& aCommands) {
2409 MOZ_ASSERT(aEvent.IsTrusted());
2410 MOZ_ASSERT(aCommands.IsEmpty());
2411 return true;
2414 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboard() {
2415 if (XRE_IsContentProcess()) {
2416 return CreateBidiKeyboardContentProcess();
2418 return CreateBidiKeyboardInner();
2421 #ifdef ANDROID
2422 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboardInner() {
2423 // no bidi keyboard implementation
2424 return nullptr;
2426 #endif
2428 namespace mozilla::widget {
2430 const char* ToChar(InputContext::Origin aOrigin) {
2431 switch (aOrigin) {
2432 case InputContext::ORIGIN_MAIN:
2433 return "ORIGIN_MAIN";
2434 case InputContext::ORIGIN_CONTENT:
2435 return "ORIGIN_CONTENT";
2436 default:
2437 return "Unexpected value";
2441 const char* ToChar(IMEMessage aIMEMessage) {
2442 switch (aIMEMessage) {
2443 case NOTIFY_IME_OF_NOTHING:
2444 return "NOTIFY_IME_OF_NOTHING";
2445 case NOTIFY_IME_OF_FOCUS:
2446 return "NOTIFY_IME_OF_FOCUS";
2447 case NOTIFY_IME_OF_BLUR:
2448 return "NOTIFY_IME_OF_BLUR";
2449 case NOTIFY_IME_OF_SELECTION_CHANGE:
2450 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2451 case NOTIFY_IME_OF_TEXT_CHANGE:
2452 return "NOTIFY_IME_OF_TEXT_CHANGE";
2453 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED:
2454 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2455 case NOTIFY_IME_OF_POSITION_CHANGE:
2456 return "NOTIFY_IME_OF_POSITION_CHANGE";
2457 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
2458 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2459 case REQUEST_TO_COMMIT_COMPOSITION:
2460 return "REQUEST_TO_COMMIT_COMPOSITION";
2461 case REQUEST_TO_CANCEL_COMPOSITION:
2462 return "REQUEST_TO_CANCEL_COMPOSITION";
2463 default:
2464 return "Unexpected value";
2468 void NativeIMEContext::Init(nsIWidget* aWidget) {
2469 if (!aWidget) {
2470 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2471 mOriginProcessID = static_cast<uint64_t>(-1);
2472 return;
2474 if (!XRE_IsContentProcess()) {
2475 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(
2476 aWidget->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT));
2477 mOriginProcessID = 0;
2478 return;
2480 // If this is created in a child process, aWidget is an instance of
2481 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2482 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2483 // native IME context of the parent process.
2484 *this = aWidget->GetNativeIMEContext();
2487 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext) {
2488 if (NS_WARN_IF(!aRawNativeIMEContext)) {
2489 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2490 mOriginProcessID = static_cast<uint64_t>(-1);
2491 return;
2493 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(aRawNativeIMEContext);
2494 mOriginProcessID =
2495 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2498 void IMENotification::TextChangeDataBase::MergeWith(
2499 const IMENotification::TextChangeDataBase& aOther) {
2500 MOZ_ASSERT(aOther.IsValid(), "Merging data must store valid data");
2501 MOZ_ASSERT(aOther.mStartOffset <= aOther.mRemovedEndOffset,
2502 "end of removed text must be same or larger than start");
2503 MOZ_ASSERT(aOther.mStartOffset <= aOther.mAddedEndOffset,
2504 "end of added text must be same or larger than start");
2506 if (!IsValid()) {
2507 *this = aOther;
2508 return;
2511 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2512 // text ranges. I.e., mStartOffset should be the smallest offset of all
2513 // modified text ranges in old text. |mRemovedEndOffset| should be the
2514 // largest end offset in old text of all modified text ranges.
2515 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2516 // I.e., only this is an offset in new text.
2517 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2518 // premodified text was already removed. And some text whose length is
2519 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2520 // this allows IME to mark dirty the modified text range with |mStartOffset|
2521 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2522 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2523 // Additionally, IME can retrieve only the text between |mStartOffset| and
2524 // |mAddedEndOffset| for updating stored text.
2526 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2527 // should be adjusted to be in same text. The |newData.mStartOffset| and
2528 // |newData.mRemovedEndOffset| should be computed as in old text because
2529 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2530 // in the old text but even if some text before the values of the newData
2531 // has already been modified, the values don't include the changes.
2533 // For comparing new and old |mAddedEndOffset| values, they should be
2534 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2535 // computed as in the new text because |mAddedEndOffset| indicates the end
2536 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2537 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2539 const TextChangeDataBase& newData = aOther;
2540 const TextChangeDataBase oldData = *this;
2542 // mCausedOnlyByComposition should be true only when all changes are caused
2543 // by composition.
2544 mCausedOnlyByComposition =
2545 newData.mCausedOnlyByComposition && oldData.mCausedOnlyByComposition;
2547 // mIncludingChangesWithoutComposition should be true if at least one of
2548 // merged changes occurred without composition.
2549 mIncludingChangesWithoutComposition =
2550 newData.mIncludingChangesWithoutComposition ||
2551 oldData.mIncludingChangesWithoutComposition;
2553 // mIncludingChangesDuringComposition should be true when at least one of
2554 // the merged non-composition changes occurred during the latest composition.
2555 if (!newData.mCausedOnlyByComposition &&
2556 !newData.mIncludingChangesDuringComposition) {
2557 MOZ_ASSERT(newData.mIncludingChangesWithoutComposition);
2558 MOZ_ASSERT(mIncludingChangesWithoutComposition);
2559 // If new change is neither caused by composition nor occurred during
2560 // composition, set mIncludingChangesDuringComposition to false because
2561 // IME doesn't want outdated text changes as text change during current
2562 // composition.
2563 mIncludingChangesDuringComposition = false;
2564 } else {
2565 // Otherwise, set mIncludingChangesDuringComposition to true if either
2566 // oldData or newData includes changes during composition.
2567 mIncludingChangesDuringComposition =
2568 newData.mIncludingChangesDuringComposition ||
2569 oldData.mIncludingChangesDuringComposition;
2572 if (newData.mStartOffset >= oldData.mAddedEndOffset) {
2573 // Case 1:
2574 // If new start is after old end offset of added text, it means that text
2575 // after the modified range is modified. Like:
2576 // added range of old change: +----------+
2577 // removed range of new change: +----------+
2578 // So, the old start offset is always the smaller offset.
2579 mStartOffset = oldData.mStartOffset;
2580 // The new end offset of removed text is moved by the old change and we
2581 // need to cancel the move of the old change for comparing the offsets in
2582 // same text because it doesn't make sensce to compare offsets in different
2583 // text.
2584 uint32_t newRemovedEndOffsetInOldText =
2585 newData.mRemovedEndOffset - oldData.Difference();
2586 mRemovedEndOffset =
2587 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2588 // The new end offset of added text is always the larger offset.
2589 mAddedEndOffset = newData.mAddedEndOffset;
2590 return;
2593 if (newData.mStartOffset >= oldData.mStartOffset) {
2594 // If new start is in the modified range, it means that new data changes
2595 // a part or all of the range.
2596 mStartOffset = oldData.mStartOffset;
2597 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2598 // Case 2:
2599 // If new end of removed text is greater than old end of added text, it
2600 // means that all or a part of modified range modified again and text
2601 // after the modified range is also modified. Like:
2602 // added range of old change: +----------+
2603 // removed range of new change: +----------+
2604 // So, the new removed end offset is moved by the old change and we need
2605 // to cancel the move of the old change for comparing the offsets in the
2606 // same text because it doesn't make sense to compare the offsets in
2607 // different text.
2608 uint32_t newRemovedEndOffsetInOldText =
2609 newData.mRemovedEndOffset - oldData.Difference();
2610 mRemovedEndOffset =
2611 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2612 // The old end of added text is replaced by new change. So, it should be
2613 // same as the new start. On the other hand, the new added end offset is
2614 // always same or larger. Therefore, the merged end offset of added
2615 // text should be the new end offset of added text.
2616 mAddedEndOffset = newData.mAddedEndOffset;
2617 return;
2620 // Case 3:
2621 // If new end of removed text is less than old end of added text, it means
2622 // that only a part of the modified range is modified again. Like:
2623 // added range of old change: +------------+
2624 // removed range of new change: +-----+
2625 // So, the new end offset of removed text should be same as the old end
2626 // offset of removed text. Therefore, the merged end offset of removed
2627 // text should be the old text change's |mRemovedEndOffset|.
2628 mRemovedEndOffset = oldData.mRemovedEndOffset;
2629 // The old end of added text is moved by new change. So, we need to cancel
2630 // the move of the new change for comparing the offsets in same text.
2631 uint32_t oldAddedEndOffsetInNewText =
2632 oldData.mAddedEndOffset + newData.Difference();
2633 mAddedEndOffset =
2634 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2635 return;
2638 if (newData.mRemovedEndOffset >= oldData.mStartOffset) {
2639 // If new end of removed text is greater than old start (and new start is
2640 // less than old start), it means that a part of modified range is modified
2641 // again and some new text before the modified range is also modified.
2642 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2643 "new start offset should be less than old one here");
2644 mStartOffset = newData.mStartOffset;
2645 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2646 // Case 4:
2647 // If new end of removed text is greater than old end of added text, it
2648 // means that all modified text and text after the modified range is
2649 // modified. Like:
2650 // added range of old change: +----------+
2651 // removed range of new change: +------------------+
2652 // So, the new end of removed text is moved by the old change. Therefore,
2653 // we need to cancel the move of the old change for comparing the offsets
2654 // in same text because it doesn't make sense to compare the offsets in
2655 // different text.
2656 uint32_t newRemovedEndOffsetInOldText =
2657 newData.mRemovedEndOffset - oldData.Difference();
2658 mRemovedEndOffset =
2659 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2660 // The old end of added text is replaced by new change. So, the old end
2661 // offset of added text is same as new text change's start offset. Then,
2662 // new change's end offset of added text is always same or larger than
2663 // it. Therefore, merged end offset of added text is always the new end
2664 // offset of added text.
2665 mAddedEndOffset = newData.mAddedEndOffset;
2666 return;
2669 // Case 5:
2670 // If new end of removed text is less than old end of added text, it
2671 // means that only a part of the modified range is modified again. Like:
2672 // added range of old change: +----------+
2673 // removed range of new change: +----------+
2674 // So, the new end of removed text should be same as old end of removed
2675 // text for preventing end of removed text to be modified. Therefore,
2676 // merged end offset of removed text is always the old end offset of removed
2677 // text.
2678 mRemovedEndOffset = oldData.mRemovedEndOffset;
2679 // The old end of added text is moved by this change. So, we need to
2680 // cancel the move of the new change for comparing the offsets in same text
2681 // because it doesn't make sense to compare the offsets in different text.
2682 uint32_t oldAddedEndOffsetInNewText =
2683 oldData.mAddedEndOffset + newData.Difference();
2684 mAddedEndOffset =
2685 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2686 return;
2689 // Case 6:
2690 // Otherwise, i.e., both new end of added text and new start are less than
2691 // old start, text before the modified range is modified. Like:
2692 // added range of old change: +----------+
2693 // removed range of new change: +----------+
2694 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2695 "new start offset should be less than old one here");
2696 mStartOffset = newData.mStartOffset;
2697 MOZ_ASSERT(newData.mRemovedEndOffset < oldData.mRemovedEndOffset,
2698 "new removed end offset should be less than old one here");
2699 mRemovedEndOffset = oldData.mRemovedEndOffset;
2700 // The end of added text should be adjusted with the new difference.
2701 uint32_t oldAddedEndOffsetInNewText =
2702 oldData.mAddedEndOffset + newData.Difference();
2703 mAddedEndOffset =
2704 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2707 #ifdef DEBUG
2709 // Let's test the code of merging multiple text change data in debug build
2710 // and crash if one of them fails because this feature is very complex but
2711 // cannot be tested with mochitest.
2712 void IMENotification::TextChangeDataBase::Test() {
2713 static bool gTestTextChangeEvent = true;
2714 if (!gTestTextChangeEvent) {
2715 return;
2717 gTestTextChangeEvent = false;
2719 /****************************************************************************
2720 * Case 1
2721 ****************************************************************************/
2723 // Appending text
2724 MergeWith(TextChangeData(10, 10, 20, false, false));
2725 MergeWith(TextChangeData(20, 20, 35, false, false));
2726 MOZ_ASSERT(mStartOffset == 10,
2727 "Test 1-1-1: mStartOffset should be the first offset");
2728 MOZ_ASSERT(
2729 mRemovedEndOffset == 10, // 20 - (20 - 10)
2730 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2731 MOZ_ASSERT(
2732 mAddedEndOffset == 35,
2733 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2734 Clear();
2736 // Removing text (longer line -> shorter line)
2737 MergeWith(TextChangeData(10, 20, 10, false, false));
2738 MergeWith(TextChangeData(10, 30, 10, false, false));
2739 MOZ_ASSERT(mStartOffset == 10,
2740 "Test 1-2-1: mStartOffset should be the first offset");
2741 MOZ_ASSERT(mRemovedEndOffset == 40, // 30 + (10 - 20)
2742 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2743 "removed text "
2744 "with already removed length");
2745 MOZ_ASSERT(
2746 mAddedEndOffset == 10,
2747 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2748 Clear();
2750 // Removing text (shorter line -> longer line)
2751 MergeWith(TextChangeData(10, 20, 10, false, false));
2752 MergeWith(TextChangeData(10, 15, 10, false, false));
2753 MOZ_ASSERT(mStartOffset == 10,
2754 "Test 1-3-1: mStartOffset should be the first offset");
2755 MOZ_ASSERT(mRemovedEndOffset == 25, // 15 + (10 - 20)
2756 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2757 "removed text "
2758 "with already removed length");
2759 MOZ_ASSERT(
2760 mAddedEndOffset == 10,
2761 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2762 Clear();
2764 // Appending text at different point (not sure if actually occurs)
2765 MergeWith(TextChangeData(10, 10, 20, false, false));
2766 MergeWith(TextChangeData(55, 55, 60, false, false));
2767 MOZ_ASSERT(mStartOffset == 10,
2768 "Test 1-4-1: mStartOffset should be the smallest offset");
2769 MOZ_ASSERT(
2770 mRemovedEndOffset == 45, // 55 - (10 - 20)
2771 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2772 "text without already added length");
2773 MOZ_ASSERT(
2774 mAddedEndOffset == 60,
2775 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2776 Clear();
2778 // Removing text at different point (not sure if actually occurs)
2779 MergeWith(TextChangeData(10, 20, 10, false, false));
2780 MergeWith(TextChangeData(55, 68, 55, false, false));
2781 MOZ_ASSERT(mStartOffset == 10,
2782 "Test 1-5-1: mStartOffset should be the smallest offset");
2783 MOZ_ASSERT(
2784 mRemovedEndOffset == 78, // 68 - (10 - 20)
2785 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2786 "text with already removed length");
2787 MOZ_ASSERT(
2788 mAddedEndOffset == 55,
2789 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2790 Clear();
2792 // Replacing text and append text (becomes longer)
2793 MergeWith(TextChangeData(30, 35, 32, false, false));
2794 MergeWith(TextChangeData(32, 32, 40, false, false));
2795 MOZ_ASSERT(mStartOffset == 30,
2796 "Test 1-6-1: mStartOffset should be the smallest offset");
2797 MOZ_ASSERT(
2798 mRemovedEndOffset == 35, // 32 - (32 - 35)
2799 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2800 "text");
2801 MOZ_ASSERT(
2802 mAddedEndOffset == 40,
2803 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2804 Clear();
2806 // Replacing text and append text (becomes shorter)
2807 MergeWith(TextChangeData(30, 35, 32, false, false));
2808 MergeWith(TextChangeData(32, 32, 33, false, false));
2809 MOZ_ASSERT(mStartOffset == 30,
2810 "Test 1-7-1: mStartOffset should be the smallest offset");
2811 MOZ_ASSERT(
2812 mRemovedEndOffset == 35, // 32 - (32 - 35)
2813 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2814 "text");
2815 MOZ_ASSERT(
2816 mAddedEndOffset == 33,
2817 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2818 Clear();
2820 // Removing text and replacing text after first range (not sure if actually
2821 // occurs)
2822 MergeWith(TextChangeData(30, 35, 30, false, false));
2823 MergeWith(TextChangeData(32, 34, 48, false, false));
2824 MOZ_ASSERT(mStartOffset == 30,
2825 "Test 1-8-1: mStartOffset should be the smallest offset");
2826 MOZ_ASSERT(mRemovedEndOffset == 39, // 34 - (30 - 35)
2827 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2828 "removed text "
2829 "without already removed text");
2830 MOZ_ASSERT(
2831 mAddedEndOffset == 48,
2832 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2833 Clear();
2835 // Removing text and replacing text after first range (not sure if actually
2836 // occurs)
2837 MergeWith(TextChangeData(30, 35, 30, false, false));
2838 MergeWith(TextChangeData(32, 38, 36, false, false));
2839 MOZ_ASSERT(mStartOffset == 30,
2840 "Test 1-9-1: mStartOffset should be the smallest offset");
2841 MOZ_ASSERT(mRemovedEndOffset == 43, // 38 - (30 - 35)
2842 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2843 "removed text "
2844 "without already removed text");
2845 MOZ_ASSERT(
2846 mAddedEndOffset == 36,
2847 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2848 Clear();
2850 /****************************************************************************
2851 * Case 2
2852 ****************************************************************************/
2854 // Replacing text in around end of added text (becomes shorter) (not sure
2855 // if actually occurs)
2856 MergeWith(TextChangeData(50, 50, 55, false, false));
2857 MergeWith(TextChangeData(53, 60, 54, false, false));
2858 MOZ_ASSERT(mStartOffset == 50,
2859 "Test 2-1-1: mStartOffset should be the smallest offset");
2860 MOZ_ASSERT(mRemovedEndOffset == 55, // 60 - (55 - 50)
2861 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2862 "removed text "
2863 "without already added text length");
2864 MOZ_ASSERT(
2865 mAddedEndOffset == 54,
2866 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2867 Clear();
2869 // Replacing text around end of added text (becomes longer) (not sure
2870 // if actually occurs)
2871 MergeWith(TextChangeData(50, 50, 55, false, false));
2872 MergeWith(TextChangeData(54, 62, 68, false, false));
2873 MOZ_ASSERT(mStartOffset == 50,
2874 "Test 2-2-1: mStartOffset should be the smallest offset");
2875 MOZ_ASSERT(mRemovedEndOffset == 57, // 62 - (55 - 50)
2876 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2877 "removed text "
2878 "without already added text length");
2879 MOZ_ASSERT(
2880 mAddedEndOffset == 68,
2881 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2882 Clear();
2884 // Replacing text around end of replaced text (became shorter) (not sure if
2885 // actually occurs)
2886 MergeWith(TextChangeData(36, 48, 45, false, false));
2887 MergeWith(TextChangeData(43, 50, 49, false, false));
2888 MOZ_ASSERT(mStartOffset == 36,
2889 "Test 2-3-1: mStartOffset should be the smallest offset");
2890 MOZ_ASSERT(mRemovedEndOffset == 53, // 50 - (45 - 48)
2891 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2892 "removed text "
2893 "without already removed text length");
2894 MOZ_ASSERT(
2895 mAddedEndOffset == 49,
2896 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2897 Clear();
2899 // Replacing text around end of replaced text (became longer) (not sure if
2900 // actually occurs)
2901 MergeWith(TextChangeData(36, 52, 53, false, false));
2902 MergeWith(TextChangeData(43, 68, 61, false, false));
2903 MOZ_ASSERT(mStartOffset == 36,
2904 "Test 2-4-1: mStartOffset should be the smallest offset");
2905 MOZ_ASSERT(mRemovedEndOffset == 67, // 68 - (53 - 52)
2906 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2907 "removed text "
2908 "without already added text length");
2909 MOZ_ASSERT(
2910 mAddedEndOffset == 61,
2911 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2912 Clear();
2914 /****************************************************************************
2915 * Case 3
2916 ****************************************************************************/
2918 // Appending text in already added text (not sure if actually occurs)
2919 MergeWith(TextChangeData(10, 10, 20, false, false));
2920 MergeWith(TextChangeData(15, 15, 30, false, false));
2921 MOZ_ASSERT(mStartOffset == 10,
2922 "Test 3-1-1: mStartOffset should be the smallest offset");
2923 MOZ_ASSERT(mRemovedEndOffset == 10,
2924 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2925 "removed text");
2926 MOZ_ASSERT(
2927 mAddedEndOffset == 35, // 20 + (30 - 15)
2928 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2929 "added text length by the new change");
2930 Clear();
2932 // Replacing text in added text (not sure if actually occurs)
2933 MergeWith(TextChangeData(50, 50, 55, false, false));
2934 MergeWith(TextChangeData(52, 53, 56, false, false));
2935 MOZ_ASSERT(mStartOffset == 50,
2936 "Test 3-2-1: mStartOffset should be the smallest offset");
2937 MOZ_ASSERT(mRemovedEndOffset == 50,
2938 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2939 "removed text");
2940 MOZ_ASSERT(
2941 mAddedEndOffset == 58, // 55 + (56 - 53)
2942 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2943 "added text length by the new change");
2944 Clear();
2946 // Replacing text in replaced text (became shorter) (not sure if actually
2947 // occurs)
2948 MergeWith(TextChangeData(36, 48, 45, false, false));
2949 MergeWith(TextChangeData(37, 38, 50, false, false));
2950 MOZ_ASSERT(mStartOffset == 36,
2951 "Test 3-3-1: mStartOffset should be the smallest offset");
2952 MOZ_ASSERT(mRemovedEndOffset == 48,
2953 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2954 "removed text");
2955 MOZ_ASSERT(
2956 mAddedEndOffset == 57, // 45 + (50 - 38)
2957 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2958 "added text length by the new change");
2959 Clear();
2961 // Replacing text in replaced text (became longer) (not sure if actually
2962 // occurs)
2963 MergeWith(TextChangeData(32, 48, 53, false, false));
2964 MergeWith(TextChangeData(43, 50, 52, false, false));
2965 MOZ_ASSERT(mStartOffset == 32,
2966 "Test 3-4-1: mStartOffset should be the smallest offset");
2967 MOZ_ASSERT(mRemovedEndOffset == 48,
2968 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2969 "removed text "
2970 "without already added text length");
2971 MOZ_ASSERT(
2972 mAddedEndOffset == 55, // 53 + (52 - 50)
2973 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2974 "added text length by the new change");
2975 Clear();
2977 // Replacing text in replaced text (became shorter) (not sure if actually
2978 // occurs)
2979 MergeWith(TextChangeData(36, 48, 50, false, false));
2980 MergeWith(TextChangeData(37, 49, 47, false, false));
2981 MOZ_ASSERT(mStartOffset == 36,
2982 "Test 3-5-1: mStartOffset should be the smallest offset");
2983 MOZ_ASSERT(
2984 mRemovedEndOffset == 48,
2985 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
2986 "text");
2987 MOZ_ASSERT(mAddedEndOffset == 48, // 50 + (47 - 49)
2988 "Test 3-5-3: mAddedEndOffset should be the first end of added "
2989 "text without "
2990 "removed text length by the new change");
2991 Clear();
2993 // Replacing text in replaced text (became longer) (not sure if actually
2994 // occurs)
2995 MergeWith(TextChangeData(32, 48, 53, false, false));
2996 MergeWith(TextChangeData(43, 50, 47, false, false));
2997 MOZ_ASSERT(mStartOffset == 32,
2998 "Test 3-6-1: mStartOffset should be the smallest offset");
2999 MOZ_ASSERT(mRemovedEndOffset == 48,
3000 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
3001 "removed text "
3002 "without already added text length");
3003 MOZ_ASSERT(mAddedEndOffset == 50, // 53 + (47 - 50)
3004 "Test 3-6-3: mAddedEndOffset should be the first end of added "
3005 "text without "
3006 "removed text length by the new change");
3007 Clear();
3009 /****************************************************************************
3010 * Case 4
3011 ****************************************************************************/
3013 // Replacing text all of already append text (not sure if actually occurs)
3014 MergeWith(TextChangeData(50, 50, 55, false, false));
3015 MergeWith(TextChangeData(44, 66, 68, false, false));
3016 MOZ_ASSERT(mStartOffset == 44,
3017 "Test 4-1-1: mStartOffset should be the smallest offset");
3018 MOZ_ASSERT(mRemovedEndOffset == 61, // 66 - (55 - 50)
3019 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
3020 "removed text "
3021 "without already added text length");
3022 MOZ_ASSERT(
3023 mAddedEndOffset == 68,
3024 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
3025 Clear();
3027 // Replacing text around a point in which text was removed (not sure if
3028 // actually occurs)
3029 MergeWith(TextChangeData(50, 62, 50, false, false));
3030 MergeWith(TextChangeData(44, 66, 68, false, false));
3031 MOZ_ASSERT(mStartOffset == 44,
3032 "Test 4-2-1: mStartOffset should be the smallest offset");
3033 MOZ_ASSERT(mRemovedEndOffset == 78, // 66 - (50 - 62)
3034 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
3035 "removed text "
3036 "without already removed text length");
3037 MOZ_ASSERT(
3038 mAddedEndOffset == 68,
3039 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
3040 Clear();
3042 // Replacing text all replaced text (became shorter) (not sure if actually
3043 // occurs)
3044 MergeWith(TextChangeData(50, 62, 60, false, false));
3045 MergeWith(TextChangeData(49, 128, 130, false, false));
3046 MOZ_ASSERT(mStartOffset == 49,
3047 "Test 4-3-1: mStartOffset should be the smallest offset");
3048 MOZ_ASSERT(mRemovedEndOffset == 130, // 128 - (60 - 62)
3049 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
3050 "removed text "
3051 "without already removed text length");
3052 MOZ_ASSERT(
3053 mAddedEndOffset == 130,
3054 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
3055 Clear();
3057 // Replacing text all replaced text (became longer) (not sure if actually
3058 // occurs)
3059 MergeWith(TextChangeData(50, 61, 73, false, false));
3060 MergeWith(TextChangeData(44, 100, 50, false, false));
3061 MOZ_ASSERT(mStartOffset == 44,
3062 "Test 4-4-1: mStartOffset should be the smallest offset");
3063 MOZ_ASSERT(mRemovedEndOffset == 88, // 100 - (73 - 61)
3064 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
3065 "removed text "
3066 "with already added text length");
3067 MOZ_ASSERT(
3068 mAddedEndOffset == 50,
3069 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
3070 Clear();
3072 /****************************************************************************
3073 * Case 5
3074 ****************************************************************************/
3076 // Replacing text around start of added text (not sure if actually occurs)
3077 MergeWith(TextChangeData(50, 50, 55, false, false));
3078 MergeWith(TextChangeData(48, 52, 49, false, false));
3079 MOZ_ASSERT(mStartOffset == 48,
3080 "Test 5-1-1: mStartOffset should be the smallest offset");
3081 MOZ_ASSERT(
3082 mRemovedEndOffset == 50,
3083 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
3084 "text");
3085 MOZ_ASSERT(
3086 mAddedEndOffset == 52, // 55 + (52 - 49)
3087 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
3088 "added text length by the new change");
3089 Clear();
3091 // Replacing text around start of replaced text (became shorter) (not sure if
3092 // actually occurs)
3093 MergeWith(TextChangeData(50, 60, 58, false, false));
3094 MergeWith(TextChangeData(43, 50, 48, false, false));
3095 MOZ_ASSERT(mStartOffset == 43,
3096 "Test 5-2-1: mStartOffset should be the smallest offset");
3097 MOZ_ASSERT(
3098 mRemovedEndOffset == 60,
3099 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
3100 "text");
3101 MOZ_ASSERT(mAddedEndOffset == 56, // 58 + (48 - 50)
3102 "Test 5-2-3: mAddedEndOffset should be the first end of added "
3103 "text without "
3104 "removed text length by the new change");
3105 Clear();
3107 // Replacing text around start of replaced text (became longer) (not sure if
3108 // actually occurs)
3109 MergeWith(TextChangeData(50, 60, 68, false, false));
3110 MergeWith(TextChangeData(43, 55, 53, false, false));
3111 MOZ_ASSERT(mStartOffset == 43,
3112 "Test 5-3-1: mStartOffset should be the smallest offset");
3113 MOZ_ASSERT(
3114 mRemovedEndOffset == 60,
3115 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
3116 "text");
3117 MOZ_ASSERT(mAddedEndOffset == 66, // 68 + (53 - 55)
3118 "Test 5-3-3: mAddedEndOffset should be the first end of added "
3119 "text without "
3120 "removed text length by the new change");
3121 Clear();
3123 // Replacing text around start of replaced text (became shorter) (not sure if
3124 // actually occurs)
3125 MergeWith(TextChangeData(50, 60, 58, false, false));
3126 MergeWith(TextChangeData(43, 50, 128, false, false));
3127 MOZ_ASSERT(mStartOffset == 43,
3128 "Test 5-4-1: mStartOffset should be the smallest offset");
3129 MOZ_ASSERT(
3130 mRemovedEndOffset == 60,
3131 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
3132 "text");
3133 MOZ_ASSERT(
3134 mAddedEndOffset == 136, // 58 + (128 - 50)
3135 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
3136 "added text length by the new change");
3137 Clear();
3139 // Replacing text around start of replaced text (became longer) (not sure if
3140 // actually occurs)
3141 MergeWith(TextChangeData(50, 60, 68, false, false));
3142 MergeWith(TextChangeData(43, 55, 65, false, false));
3143 MOZ_ASSERT(mStartOffset == 43,
3144 "Test 5-5-1: mStartOffset should be the smallest offset");
3145 MOZ_ASSERT(
3146 mRemovedEndOffset == 60,
3147 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
3148 "text");
3149 MOZ_ASSERT(
3150 mAddedEndOffset == 78, // 68 + (65 - 55)
3151 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
3152 "added text length by the new change");
3153 Clear();
3155 /****************************************************************************
3156 * Case 6
3157 ****************************************************************************/
3159 // Appending text before already added text (not sure if actually occurs)
3160 MergeWith(TextChangeData(30, 30, 45, false, false));
3161 MergeWith(TextChangeData(10, 10, 20, false, false));
3162 MOZ_ASSERT(mStartOffset == 10,
3163 "Test 6-1-1: mStartOffset should be the smallest offset");
3164 MOZ_ASSERT(
3165 mRemovedEndOffset == 30,
3166 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
3167 "text");
3168 MOZ_ASSERT(
3169 mAddedEndOffset == 55, // 45 + (20 - 10)
3170 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
3171 "added text length by the new change");
3172 Clear();
3174 // Removing text before already removed text (not sure if actually occurs)
3175 MergeWith(TextChangeData(30, 35, 30, false, false));
3176 MergeWith(TextChangeData(10, 25, 10, false, false));
3177 MOZ_ASSERT(mStartOffset == 10,
3178 "Test 6-2-1: mStartOffset should be the smallest offset");
3179 MOZ_ASSERT(
3180 mRemovedEndOffset == 35,
3181 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
3182 "text");
3183 MOZ_ASSERT(
3184 mAddedEndOffset == 15, // 30 - (25 - 10)
3185 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
3186 "removed text length by the new change");
3187 Clear();
3189 // Replacing text before already replaced text (not sure if actually occurs)
3190 MergeWith(TextChangeData(50, 65, 70, false, false));
3191 MergeWith(TextChangeData(13, 24, 15, false, false));
3192 MOZ_ASSERT(mStartOffset == 13,
3193 "Test 6-3-1: mStartOffset should be the smallest offset");
3194 MOZ_ASSERT(
3195 mRemovedEndOffset == 65,
3196 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
3197 "text");
3198 MOZ_ASSERT(mAddedEndOffset == 61, // 70 + (15 - 24)
3199 "Test 6-3-3: mAddedEndOffset should be the first end of added "
3200 "text without "
3201 "removed text length by the new change");
3202 Clear();
3204 // Replacing text before already replaced text (not sure if actually occurs)
3205 MergeWith(TextChangeData(50, 65, 70, false, false));
3206 MergeWith(TextChangeData(13, 24, 36, false, false));
3207 MOZ_ASSERT(mStartOffset == 13,
3208 "Test 6-4-1: mStartOffset should be the smallest offset");
3209 MOZ_ASSERT(
3210 mRemovedEndOffset == 65,
3211 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
3212 "text");
3213 MOZ_ASSERT(mAddedEndOffset == 82, // 70 + (36 - 24)
3214 "Test 6-4-3: mAddedEndOffset should be the first end of added "
3215 "text without "
3216 "removed text length by the new change");
3217 Clear();
3220 #endif // #ifdef DEBUG
3222 } // namespace mozilla::widget
3224 #ifdef DEBUG
3225 //////////////////////////////////////////////////////////////
3227 // Convert a GUI event message code to a string.
3228 // Makes it a lot easier to debug events.
3230 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3231 // for a DebugPrintEvent() function that uses
3232 // this.
3234 //////////////////////////////////////////////////////////////
3235 /* static */
3236 nsAutoString nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent* aGuiEvent) {
3237 NS_ASSERTION(nullptr != aGuiEvent, "cmon, null gui event.");
3239 nsAutoString eventName(u"UNKNOWN"_ns);
3241 # define _ASSIGN_eventName(_value, _name) \
3242 case _value: \
3243 eventName.AssignLiteral(_name); \
3244 break
3246 switch (aGuiEvent->mMessage) {
3247 _ASSIGN_eventName(eBlur, "eBlur");
3248 _ASSIGN_eventName(eDrop, "eDrop");
3249 _ASSIGN_eventName(eDragEnter, "eDragEnter");
3250 _ASSIGN_eventName(eDragExit, "eDragExit");
3251 _ASSIGN_eventName(eDragOver, "eDragOver");
3252 _ASSIGN_eventName(eEditorInput, "eEditorInput");
3253 _ASSIGN_eventName(eFocus, "eFocus");
3254 _ASSIGN_eventName(eFocusIn, "eFocusIn");
3255 _ASSIGN_eventName(eFocusOut, "eFocusOut");
3256 _ASSIGN_eventName(eFormSelect, "eFormSelect");
3257 _ASSIGN_eventName(eFormChange, "eFormChange");
3258 _ASSIGN_eventName(eFormReset, "eFormReset");
3259 _ASSIGN_eventName(eFormSubmit, "eFormSubmit");
3260 _ASSIGN_eventName(eImageAbort, "eImageAbort");
3261 _ASSIGN_eventName(eLoadError, "eLoadError");
3262 _ASSIGN_eventName(eKeyDown, "eKeyDown");
3263 _ASSIGN_eventName(eKeyPress, "eKeyPress");
3264 _ASSIGN_eventName(eKeyUp, "eKeyUp");
3265 _ASSIGN_eventName(eMouseEnterIntoWidget, "eMouseEnterIntoWidget");
3266 _ASSIGN_eventName(eMouseExitFromWidget, "eMouseExitFromWidget");
3267 _ASSIGN_eventName(eMouseDown, "eMouseDown");
3268 _ASSIGN_eventName(eMouseUp, "eMouseUp");
3269 _ASSIGN_eventName(eMouseClick, "eMouseClick");
3270 _ASSIGN_eventName(eMouseAuxClick, "eMouseAuxClick");
3271 _ASSIGN_eventName(eMouseDoubleClick, "eMouseDoubleClick");
3272 _ASSIGN_eventName(eMouseMove, "eMouseMove");
3273 _ASSIGN_eventName(eLoad, "eLoad");
3274 _ASSIGN_eventName(ePopState, "ePopState");
3275 _ASSIGN_eventName(eBeforeScriptExecute, "eBeforeScriptExecute");
3276 _ASSIGN_eventName(eAfterScriptExecute, "eAfterScriptExecute");
3277 _ASSIGN_eventName(eUnload, "eUnload");
3278 _ASSIGN_eventName(eHashChange, "eHashChange");
3279 _ASSIGN_eventName(eReadyStateChange, "eReadyStateChange");
3280 _ASSIGN_eventName(eXULBroadcast, "eXULBroadcast");
3281 _ASSIGN_eventName(eXULCommandUpdate, "eXULCommandUpdate");
3283 # undef _ASSIGN_eventName
3285 default: {
3286 eventName.AssignLiteral("UNKNOWN: ");
3287 eventName.AppendInt(aGuiEvent->mMessage);
3288 } break;
3291 return nsAutoString(eventName);
3293 //////////////////////////////////////////////////////////////
3295 // Code to deal with paint and event debug prefs.
3297 //////////////////////////////////////////////////////////////
3298 struct PrefPair {
3299 const char* name;
3300 bool value;
3303 static PrefPair debug_PrefValues[] = {
3304 {"nglayout.debug.crossing_event_dumping", false},
3305 {"nglayout.debug.event_dumping", false},
3306 {"nglayout.debug.invalidate_dumping", false},
3307 {"nglayout.debug.motion_event_dumping", false},
3308 {"nglayout.debug.paint_dumping", false}};
3310 //////////////////////////////////////////////////////////////
3311 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName) {
3312 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3314 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3315 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3316 return debug_PrefValues[i].value;
3320 return false;
3322 //////////////////////////////////////////////////////////////
3323 static void debug_SetCachedBoolPref(const char* aPrefName, bool aValue) {
3324 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3326 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3327 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3328 debug_PrefValues[i].value = aValue;
3330 return;
3334 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3337 //////////////////////////////////////////////////////////////
3338 class Debug_PrefObserver final : public nsIObserver {
3339 ~Debug_PrefObserver() = default;
3341 public:
3342 NS_DECL_ISUPPORTS
3343 NS_DECL_NSIOBSERVER
3346 NS_IMPL_ISUPPORTS(Debug_PrefObserver, nsIObserver)
3348 NS_IMETHODIMP
3349 Debug_PrefObserver::Observe(nsISupports* subject, const char* topic,
3350 const char16_t* data) {
3351 NS_ConvertUTF16toUTF8 prefName(data);
3353 bool value = Preferences::GetBool(prefName.get(), false);
3354 debug_SetCachedBoolPref(prefName.get(), value);
3355 return NS_OK;
3358 //////////////////////////////////////////////////////////////
3359 /* static */ void debug_RegisterPrefCallbacks() {
3360 static bool once = true;
3362 if (!once) {
3363 return;
3366 once = false;
3368 nsCOMPtr<nsIObserver> obs(new Debug_PrefObserver());
3369 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3370 // Initialize the pref values
3371 debug_PrefValues[i].value =
3372 Preferences::GetBool(debug_PrefValues[i].name, false);
3374 if (obs) {
3375 // Register callbacks for when these change
3376 nsCString name;
3377 name.AssignLiteral(debug_PrefValues[i].name,
3378 strlen(debug_PrefValues[i].name));
3379 Preferences::AddStrongObserver(obs, name);
3383 //////////////////////////////////////////////////////////////
3384 static int32_t _GetPrintCount() {
3385 static int32_t sCount = 0;
3387 return ++sCount;
3389 //////////////////////////////////////////////////////////////
3390 /* static */
3391 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut, nsIWidget* aWidget,
3392 WidgetGUIEvent* aGuiEvent,
3393 const char* aWidgetName, int32_t aWindowID) {
3394 if (aGuiEvent->mMessage == eMouseMove) {
3395 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3398 if (aGuiEvent->mMessage == eMouseEnterIntoWidget ||
3399 aGuiEvent->mMessage == eMouseExitFromWidget) {
3400 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3401 return;
3404 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3406 NS_LossyConvertUTF16toASCII tempString(
3407 debug_GuiEventToString(aGuiEvent).get());
3409 fprintf(aFileOut, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3410 _GetPrintCount(), tempString.get(), (void*)aWidget, aWidgetName,
3411 aWindowID, aGuiEvent->mRefPoint.x.value,
3412 aGuiEvent->mRefPoint.y.value);
3414 //////////////////////////////////////////////////////////////
3415 /* static */
3416 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut, nsIWidget* aWidget,
3417 const nsIntRegion& aRegion,
3418 const char* aWidgetName,
3419 int32_t aWindowID) {
3420 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3421 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3423 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3425 nsIntRect rect = aRegion.GetBounds();
3426 fprintf(aFileOut,
3427 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3428 "%3d,%-3d",
3429 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID, rect.X(),
3430 rect.Y(), rect.Width(), rect.Height());
3432 fprintf(aFileOut, "\n");
3434 //////////////////////////////////////////////////////////////
3435 /* static */
3436 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut, nsIWidget* aWidget,
3437 const LayoutDeviceIntRect* aRect,
3438 const char* aWidgetName,
3439 int32_t aWindowID) {
3440 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3442 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3443 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3445 fprintf(aFileOut, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3446 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID);
3448 if (aRect) {
3449 fprintf(aFileOut, " rect=%3d,%-3d %3d,%-3d", aRect->X(), aRect->Y(),
3450 aRect->Width(), aRect->Height());
3451 } else {
3452 fprintf(aFileOut, " rect=%-15s", "none");
3455 fprintf(aFileOut, "\n");
3457 //////////////////////////////////////////////////////////////
3459 #endif // DEBUG