1
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/. */
7
8 #include "nsBaseWidget.h"
9
10 #include <utility>
11
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/MouseEvents.h"
24 #include "mozilla/NativeKeyBindingsType.h"
25 #include "mozilla/Preferences.h"
26 #include "mozilla/PresShell.h"
27 #include "mozilla/Sprintf.h"
28 #include "mozilla/StaticPrefs_apz.h"
29 #include "mozilla/StaticPrefs_dom.h"
30 #include "mozilla/StaticPrefs_gfx.h"
31 #include "mozilla/StaticPrefs_layers.h"
32 #include "mozilla/StaticPrefs_layout.h"
33 #include "mozilla/TextEventDispatcher.h"
34 #include "mozilla/TextEventDispatcherListener.h"
35 #include "mozilla/UniquePtr.h"
36 #include "mozilla/Unused.h"
37 #include "mozilla/VsyncDispatcher.h"
38 #include "mozilla/dom/BrowserParent.h"
39 #include "mozilla/dom/ContentChild.h"
40 #include "mozilla/dom/Document.h"
41 #include "mozilla/dom/SimpleGestureEventBinding.h"
42 #include "mozilla/gfx/2D.h"
43 #include "mozilla/gfx/GPUProcessManager.h"
44 #include "mozilla/gfx/gfxVars.h"
45 #include "mozilla/layers/APZCCallbackHelper.h"
46 #include "mozilla/layers/TouchActionHelper.h"
47 #include "mozilla/layers/APZEventState.h"
48 #include "mozilla/layers/APZInputBridge.h"
49 #include "mozilla/layers/APZThreadUtils.h"
50 #include "mozilla/layers/ChromeProcessController.h"
51 #include "mozilla/layers/Compositor.h"
52 #include "mozilla/layers/CompositorBridgeChild.h"
53 #include "mozilla/layers/CompositorBridgeParent.h"
54 #include "mozilla/layers/CompositorOptions.h"
55 #include "mozilla/layers/IAPZCTreeManager.h"
56 #include "mozilla/layers/ImageBridgeChild.h"
57 #include "mozilla/layers/InputAPZContext.h"
58 #include "mozilla/layers/WebRenderLayerManager.h"
59 #include "mozilla/webrender/WebRenderTypes.h"
60 #include "nsAppDirectoryServiceDefs.h"
61 #include "nsCOMPtr.h"
62 #include "nsContentUtils.h"
63 #include "nsDeviceContext.h"
64 #include "nsGfxCIID.h"
65 #include "nsIAppWindow.h"
66 #include "nsIBaseWindow.h"
67 #include "nsIContent.h"
68 #include "nsIScreenManager.h"
69 #include "nsISimpleEnumerator.h"
70 #include "nsIWidgetListener.h"
71 #include "nsRefPtrHashtable.h"
72 #include "nsServiceManagerUtils.h"
73 #include "nsWidgetsCID.h"
74 #include "nsXULPopupManager.h"
75 #include "prdtoa.h"
76 #include "prenv.h"
77 #ifdef ACCESSIBILITY
78 # include "nsAccessibilityService.h"
79 #endif
80 #include "gfxConfig.h"
81 #include "gfxUtils.h" // for ToDeviceColor
82 #include "mozilla/layers/CompositorSession.h"
83 #include "VRManagerChild.h"
84 #include "gfxConfig.h"
85 #include "nsView.h"
86 #include "nsViewManager.h"
87
88 #ifdef DEBUG
89 # include "nsIObserver.h"
90
91 static void debug_RegisterPrefCallbacks();
92
93 #endif
94
95 #ifdef NOISY_WIDGET_LEAKS
96 static int32_t gNumWidgets;
97 #endif
98
99 #ifdef XP_MACOSX
100 # include "nsCocoaFeatures.h"
101 #endif
102
103 nsIRollupListener* nsBaseWidget::gRollupListener = nullptr;
104
105 using namespace mozilla::dom;
106 using namespace mozilla::layers;
107 using namespace mozilla::ipc;
108 using namespace mozilla::widget;
109 using namespace mozilla;
110
111 // Async pump timer during injected long touch taps
112 #define TOUCH_INJECT_PUMP_TIMER_MSEC 50
113 #define TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC 1500
114 int32_t nsIWidget::sPointerIdCounter = 0;
115
116 // Some statics from nsIWidget.h
117 /*static*/
118 uint64_t AutoObserverNotifier::sObserverId = 0;
119 /*static*/ nsTHashMap<uint64_t, nsCOMPtr<nsIObserver>>
120 AutoObserverNotifier::sSavedObservers;
121
122 // The maximum amount of time to let the EnableDragDrop runnable wait in the
123 // idle queue before timing out and moving it to the regular queue. Value is in
124 // milliseconds.
125 const uint32_t kAsyncDragDropTimeout = 1000;
126
NS_IMPL_ISUPPORTS(nsBaseWidget,nsIWidget,nsISupportsWeakReference)127 NS_IMPL_ISUPPORTS(nsBaseWidget, nsIWidget, nsISupportsWeakReference)
128
129 //-------------------------------------------------------------------------
130 //
131 // nsBaseWidget constructor
132 //
133 //-------------------------------------------------------------------------
134
135 nsBaseWidget::nsBaseWidget() : nsBaseWidget(eBorderStyle_none) {}
136
nsBaseWidget(nsBorderStyle aBorderStyle)137 nsBaseWidget::nsBaseWidget(nsBorderStyle aBorderStyle)
138 : mWidgetListener(nullptr),
139 mAttachedWidgetListener(nullptr),
140 mPreviouslyAttachedWidgetListener(nullptr),
141 mCompositorVsyncDispatcher(nullptr),
142 mBorderStyle(aBorderStyle),
143 mBounds(0, 0, 0, 0),
144 mOriginalBounds(nullptr),
145 mSizeMode(nsSizeMode_Normal),
146 mIsTiled(false),
147 mPopupLevel(ePopupLevelTop),
148 mPopupType(ePopupTypeAny),
149 mHasRemoteContent(false),
150 mFissionWindow(false),
151 mUpdateCursor(true),
152 mUseAttachedEvents(false),
153 mIMEHasFocus(false),
154 mIMEHasQuit(false),
155 mIsFullyOccluded(false),
156 mCurrentPanGestureBelongsToSwipe(false) {
157 #ifdef NOISY_WIDGET_LEAKS
158 gNumWidgets++;
159 printf("WIDGETS+ = %d\n", gNumWidgets);
160 #endif
161
162 #ifdef DEBUG
163 debug_RegisterPrefCallbacks();
164 #endif
165
166 mShutdownObserver = new WidgetShutdownObserver(this);
167 }
168
NS_IMPL_ISUPPORTS(WidgetShutdownObserver,nsIObserver)169 NS_IMPL_ISUPPORTS(WidgetShutdownObserver, nsIObserver)
170
171 WidgetShutdownObserver::WidgetShutdownObserver(nsBaseWidget* aWidget)
172 : mWidget(aWidget), mRegistered(false) {
173 Register();
174 }
175
~WidgetShutdownObserver()176 WidgetShutdownObserver::~WidgetShutdownObserver() {
177 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
178 // gets torn down. The observer service and nsBaseWidget have a ref on us
179 // so nsBaseWidget has to call Unregister and then clear its ref.
180 }
181
182 NS_IMETHODIMP
Observe(nsISupports * aSubject,const char * aTopic,const char16_t * aData)183 WidgetShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
184 const char16_t* aData) {
185 if (!mWidget) {
186 return NS_OK;
187 }
188 if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
189 RefPtr<nsBaseWidget> widget(mWidget);
190 widget->Shutdown();
191 } else if (!strcmp(aTopic, "quit-application")) {
192 RefPtr<nsBaseWidget> widget(mWidget);
193 widget->QuitIME();
194 }
195 return NS_OK;
196 }
197
Register()198 void WidgetShutdownObserver::Register() {
199 if (!mRegistered) {
200 mRegistered = true;
201 nsContentUtils::RegisterShutdownObserver(this);
202
203 #ifndef MOZ_WIDGET_ANDROID
204 // The primary purpose of observing quit-application is
205 // to avoid leaking a widget on Windows when nothing else
206 // breaks the circular reference between the widget and
207 // TSFTextStore. However, our Android IME code crashes if
208 // doing this on Android, so let's not do this on Android.
209 // Doing this on Gtk and Mac just in case.
210 nsCOMPtr<nsIObserverService> observerService =
211 mozilla::services::GetObserverService();
212 if (observerService) {
213 observerService->AddObserver(this, "quit-application", false);
214 }
215 #endif
216 }
217 }
218
Unregister()219 void WidgetShutdownObserver::Unregister() {
220 if (mRegistered) {
221 mWidget = nullptr;
222
223 #ifndef MOZ_WIDGET_ANDROID
224 nsCOMPtr<nsIObserverService> observerService =
225 mozilla::services::GetObserverService();
226 if (observerService) {
227 observerService->RemoveObserver(this, "quit-application");
228 }
229 #endif
230
231 nsContentUtils::UnregisterShutdownObserver(this);
232 mRegistered = false;
233 }
234 }
235
236 #define INTL_APP_LOCALES_CHANGED "intl:app-locales-changed"
237 #define L10N_PSEUDO_PREF "intl.l10n.pseudo"
238
239 static const char* kObservedPrefs[] = {L10N_PSEUDO_PREF, nullptr};
240
NS_IMPL_ISUPPORTS(LocalesChangedObserver,nsIObserver)241 NS_IMPL_ISUPPORTS(LocalesChangedObserver, nsIObserver)
242
243 LocalesChangedObserver::LocalesChangedObserver(nsBaseWidget* aWidget)
244 : mWidget(aWidget), mRegistered(false) {
245 Register();
246 }
247
~LocalesChangedObserver()248 LocalesChangedObserver::~LocalesChangedObserver() {
249 // No need to call Unregister(), we can't be destroyed until nsBaseWidget
250 // gets torn down. The observer service and nsBaseWidget have a ref on us
251 // so nsBaseWidget has to call Unregister and then clear its ref.
252 }
253
254 NS_IMETHODIMP
Observe(nsISupports * aSubject,const char * aTopic,const char16_t * aData)255 LocalesChangedObserver::Observe(nsISupports* aSubject, const char* aTopic,
256 const char16_t* aData) {
257 if (!mWidget) {
258 return NS_OK;
259 }
260 if (!strcmp(aTopic, INTL_APP_LOCALES_CHANGED)) {
261 RefPtr<nsBaseWidget> widget(mWidget);
262 widget->LocalesChanged();
263 } else {
264 MOZ_ASSERT(!strcmp("nsPref:changed", aTopic));
265 nsDependentString pref(aData);
266 if (pref.EqualsLiteral(L10N_PSEUDO_PREF)) {
267 RefPtr<nsBaseWidget> widget(mWidget);
268 widget->LocalesChanged();
269 }
270 }
271 return NS_OK;
272 }
273
Register()274 void LocalesChangedObserver::Register() {
275 if (mRegistered) {
276 return;
277 }
278
279 DebugOnly<nsresult> rv =
280 Preferences::AddStrongObservers(this, kObservedPrefs);
281 MOZ_ASSERT(NS_SUCCEEDED(rv), "Adding observers failed.");
282
283 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
284 if (obs) {
285 obs->AddObserver(this, INTL_APP_LOCALES_CHANGED, true);
286 }
287
288 // Locale might be update before registering
289 RefPtr<nsBaseWidget> widget(mWidget);
290 widget->LocalesChanged();
291
292 mRegistered = true;
293 }
294
Unregister()295 void LocalesChangedObserver::Unregister() {
296 if (!mRegistered) {
297 return;
298 }
299
300 nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
301 if (obs) {
302 obs->RemoveObserver(this, INTL_APP_LOCALES_CHANGED);
303 }
304 Preferences::RemoveObservers(this, kObservedPrefs);
305
306 mWidget = nullptr;
307 mRegistered = false;
308 }
309
Shutdown()310 void nsBaseWidget::Shutdown() {
311 NotifyLiveResizeStopped();
312 RevokeTransactionIdAllocator();
313 DestroyCompositor();
314 FreeLocalesChangedObserver();
315 FreeShutdownObserver();
316 }
317
QuitIME()318 void nsBaseWidget::QuitIME() {
319 IMEStateManager::WidgetOnQuit(this);
320 this->mIMEHasQuit = true;
321 }
322
DestroyCompositor()323 void nsBaseWidget::DestroyCompositor() {
324 // We release this before releasing the compositor, since it may hold the
325 // last reference to our ClientLayerManager. ClientLayerManager's dtor can
326 // trigger a paint, creating a new compositor, and we don't want to re-use
327 // the old vsync dispatcher.
328 if (mCompositorVsyncDispatcher) {
329 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
330
331 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
332 mCompositorVsyncDispatcher->Shutdown();
333 mCompositorVsyncDispatcher = nullptr;
334 }
335
336 // The compositor shutdown sequence looks like this:
337 // 1. CompositorSession calls CompositorBridgeChild::Destroy.
338 // 2. CompositorBridgeChild synchronously sends WillClose.
339 // 3. CompositorBridgeParent releases some resources (such as the layer
340 // manager, compositor, and widget).
341 // 4. CompositorBridgeChild::Destroy returns.
342 // 5. Asynchronously, CompositorBridgeParent::ActorDestroy will fire on the
343 // compositor thread when the I/O thread closes the IPC channel.
344 // 6. Step 5 will schedule DeferredDestroy on the compositor thread, which
345 // releases the reference CompositorBridgeParent holds to itself.
346 //
347 // When CompositorSession::Shutdown returns, we assume the compositor is gone
348 // or will be gone very soon.
349 if (mCompositorSession) {
350 ReleaseContentController();
351 mAPZC = nullptr;
352 SetCompositorWidgetDelegate(nullptr);
353 mCompositorBridgeChild = nullptr;
354 mCompositorSession->Shutdown();
355 mCompositorSession = nullptr;
356 }
357 }
358
359 // This prevents the layer manager from starting a new transaction during
360 // shutdown.
RevokeTransactionIdAllocator()361 void nsBaseWidget::RevokeTransactionIdAllocator() {
362 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
363 return;
364 }
365 mWindowRenderer->AsWebRender()->SetTransactionIdAllocator(nullptr);
366 }
367
ReleaseContentController()368 void nsBaseWidget::ReleaseContentController() {
369 if (mRootContentController) {
370 mRootContentController->Destroy();
371 mRootContentController = nullptr;
372 }
373 }
374
DestroyLayerManager()375 void nsBaseWidget::DestroyLayerManager() {
376 if (mWindowRenderer) {
377 mWindowRenderer->Destroy();
378 mWindowRenderer = nullptr;
379 }
380 DestroyCompositor();
381 }
382
OnRenderingDeviceReset()383 void nsBaseWidget::OnRenderingDeviceReset() { DestroyLayerManager(); }
384
FreeShutdownObserver()385 void nsBaseWidget::FreeShutdownObserver() {
386 if (mShutdownObserver) {
387 mShutdownObserver->Unregister();
388 }
389 mShutdownObserver = nullptr;
390 }
391
FreeLocalesChangedObserver()392 void nsBaseWidget::FreeLocalesChangedObserver() {
393 if (mLocalesChangedObserver) {
394 mLocalesChangedObserver->Unregister();
395 }
396 mLocalesChangedObserver = nullptr;
397 }
398
399 //-------------------------------------------------------------------------
400 //
401 // nsBaseWidget destructor
402 //
403 //-------------------------------------------------------------------------
404
~nsBaseWidget()405 nsBaseWidget::~nsBaseWidget() {
406 if (mSwipeTracker) {
407 mSwipeTracker->Destroy();
408 mSwipeTracker = nullptr;
409 }
410
411 IMEStateManager::WidgetDestroyed(this);
412
413 FreeLocalesChangedObserver();
414 FreeShutdownObserver();
415 RevokeTransactionIdAllocator();
416 DestroyLayerManager();
417
418 #ifdef NOISY_WIDGET_LEAKS
419 gNumWidgets--;
420 printf("WIDGETS- = %d\n", gNumWidgets);
421 #endif
422
423 delete mOriginalBounds;
424 }
425
426 //-------------------------------------------------------------------------
427 //
428 // Basic create.
429 //
430 //-------------------------------------------------------------------------
BaseCreate(nsIWidget * aParent,nsWidgetInitData * aInitData)431 void nsBaseWidget::BaseCreate(nsIWidget* aParent, nsWidgetInitData* aInitData) {
432 // keep a reference to the device context
433 if (nullptr != aInitData) {
434 mWindowType = aInitData->mWindowType;
435 mBorderStyle = aInitData->mBorderStyle;
436 mPopupLevel = aInitData->mPopupLevel;
437 mPopupType = aInitData->mPopupHint;
438 mHasRemoteContent = aInitData->mHasRemoteContent;
439 mFissionWindow = aInitData->mFissionWindow;
440 }
441
442 if (aParent) {
443 aParent->AddChild(this);
444 }
445 }
446
447 //-------------------------------------------------------------------------
448 //
449 // Accessor functions to get/set the client data
450 //
451 //-------------------------------------------------------------------------
452
GetWidgetListener() const453 nsIWidgetListener* nsBaseWidget::GetWidgetListener() const {
454 return mWidgetListener;
455 }
456
SetWidgetListener(nsIWidgetListener * aWidgetListener)457 void nsBaseWidget::SetWidgetListener(nsIWidgetListener* aWidgetListener) {
458 mWidgetListener = aWidgetListener;
459 }
460
CreateChild(const LayoutDeviceIntRect & aRect,nsWidgetInitData * aInitData,bool aForceUseIWidgetParent)461 already_AddRefed<nsIWidget> nsBaseWidget::CreateChild(
462 const LayoutDeviceIntRect& aRect, nsWidgetInitData* aInitData,
463 bool aForceUseIWidgetParent) {
464 nsIWidget* parent = this;
465 nsNativeWidget nativeParent = nullptr;
466
467 if (!aForceUseIWidgetParent) {
468 // Use only either parent or nativeParent, not both, to match
469 // existing code. Eventually Create() should be divested of its
470 // nativeWidget parameter.
471 nativeParent = parent ? parent->GetNativeData(NS_NATIVE_WIDGET) : nullptr;
472 parent = nativeParent ? nullptr : parent;
473 MOZ_ASSERT(!parent || !nativeParent, "messed up logic");
474 }
475
476 nsCOMPtr<nsIWidget> widget;
477 if (aInitData && aInitData->mWindowType == eWindowType_popup) {
478 widget = AllocateChildPopupWidget();
479 } else {
480 widget = nsIWidget::CreateChildWindow();
481 }
482
483 if (widget &&
484 NS_SUCCEEDED(widget->Create(parent, nativeParent, aRect, aInitData))) {
485 return widget.forget();
486 }
487
488 return nullptr;
489 }
490
491 // Attach a view to our widget which we'll send events to.
AttachViewToTopLevel(bool aUseAttachedEvents)492 void nsBaseWidget::AttachViewToTopLevel(bool aUseAttachedEvents) {
493 NS_ASSERTION((mWindowType == eWindowType_toplevel ||
494 mWindowType == eWindowType_dialog ||
495 mWindowType == eWindowType_invisible ||
496 mWindowType == eWindowType_child),
497 "Can't attach to window of that type");
498
499 mUseAttachedEvents = aUseAttachedEvents;
500 }
501
GetAttachedWidgetListener() const502 nsIWidgetListener* nsBaseWidget::GetAttachedWidgetListener() const {
503 return mAttachedWidgetListener;
504 }
505
GetPreviouslyAttachedWidgetListener()506 nsIWidgetListener* nsBaseWidget::GetPreviouslyAttachedWidgetListener() {
507 return mPreviouslyAttachedWidgetListener;
508 }
509
SetPreviouslyAttachedWidgetListener(nsIWidgetListener * aListener)510 void nsBaseWidget::SetPreviouslyAttachedWidgetListener(
511 nsIWidgetListener* aListener) {
512 mPreviouslyAttachedWidgetListener = aListener;
513 }
514
SetAttachedWidgetListener(nsIWidgetListener * aListener)515 void nsBaseWidget::SetAttachedWidgetListener(nsIWidgetListener* aListener) {
516 mAttachedWidgetListener = aListener;
517 }
518
519 //-------------------------------------------------------------------------
520 //
521 // Close this nsBaseWidget
522 //
523 //-------------------------------------------------------------------------
Destroy()524 void nsBaseWidget::Destroy() {
525 // Just in case our parent is the only ref to us
526 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
527 // disconnect from the parent
528 nsIWidget* parent = GetParent();
529 if (parent) {
530 parent->RemoveChild(this);
531 }
532 }
533
534 //-------------------------------------------------------------------------
535 //
536 // Get this nsBaseWidget parent
537 //
538 //-------------------------------------------------------------------------
GetParent(void)539 nsIWidget* nsBaseWidget::GetParent(void) { return nullptr; }
540
541 //-------------------------------------------------------------------------
542 //
543 // Get this nsBaseWidget top level widget
544 //
545 //-------------------------------------------------------------------------
GetTopLevelWidget()546 nsIWidget* nsBaseWidget::GetTopLevelWidget() {
547 nsIWidget *topLevelWidget = nullptr, *widget = this;
548 while (widget) {
549 topLevelWidget = widget;
550 widget = widget->GetParent();
551 }
552 return topLevelWidget;
553 }
554
555 //-------------------------------------------------------------------------
556 //
557 // Get this nsBaseWidget's top (non-sheet) parent (if it's a sheet)
558 //
559 //-------------------------------------------------------------------------
GetSheetWindowParent(void)560 nsIWidget* nsBaseWidget::GetSheetWindowParent(void) { return nullptr; }
561
GetDPI()562 float nsBaseWidget::GetDPI() { return 96.0f; }
563
GetDefaultScale()564 CSSToLayoutDeviceScale nsIWidget::GetDefaultScale() {
565 double devPixelsPerCSSPixel = StaticPrefs::layout_css_devPixelsPerPx();
566
567 if (devPixelsPerCSSPixel <= 0.0) {
568 devPixelsPerCSSPixel = GetDefaultScaleInternal();
569 }
570
571 return CSSToLayoutDeviceScale(devPixelsPerCSSPixel);
572 }
573
CustomCursorSize(const Cursor & aCursor)574 nsIntSize nsIWidget::CustomCursorSize(const Cursor& aCursor) {
575 MOZ_ASSERT(aCursor.IsCustom());
576 int32_t width = 0;
577 int32_t height = 0;
578 aCursor.mContainer->GetWidth(&width);
579 aCursor.mContainer->GetHeight(&height);
580 aCursor.mResolution.ApplyTo(width, height);
581 return {width, height};
582 }
583
584 //-------------------------------------------------------------------------
585 //
586 // Add a child to the list of children
587 //
588 //-------------------------------------------------------------------------
AddChild(nsIWidget * aChild)589 void nsBaseWidget::AddChild(nsIWidget* aChild) {
590 MOZ_ASSERT(!aChild->GetNextSibling() && !aChild->GetPrevSibling(),
591 "aChild not properly removed from its old child list");
592
593 if (!mFirstChild) {
594 mFirstChild = mLastChild = aChild;
595 } else {
596 // append to the list
597 MOZ_ASSERT(mLastChild);
598 MOZ_ASSERT(!mLastChild->GetNextSibling());
599 mLastChild->SetNextSibling(aChild);
600 aChild->SetPrevSibling(mLastChild);
601 mLastChild = aChild;
602 }
603 }
604
605 //-------------------------------------------------------------------------
606 //
607 // Remove a child from the list of children
608 //
609 //-------------------------------------------------------------------------
RemoveChild(nsIWidget * aChild)610 void nsBaseWidget::RemoveChild(nsIWidget* aChild) {
611 #ifdef DEBUG
612 # ifdef XP_MACOSX
613 // nsCocoaWindow doesn't implement GetParent, so in that case parent will be
614 // null and we'll just have to do without this assertion.
615 nsIWidget* parent = aChild->GetParent();
616 NS_ASSERTION(!parent || parent == this, "Not one of our kids!");
617 # else
618 MOZ_RELEASE_ASSERT(aChild->GetParent() == this, "Not one of our kids!");
619 # endif
620 #endif
621
622 if (mLastChild == aChild) {
623 mLastChild = mLastChild->GetPrevSibling();
624 }
625 if (mFirstChild == aChild) {
626 mFirstChild = mFirstChild->GetNextSibling();
627 }
628
629 // Now remove from the list. Make sure that we pass ownership of the tail
630 // of the list correctly before we have aChild let go of it.
631 nsIWidget* prev = aChild->GetPrevSibling();
632 nsIWidget* next = aChild->GetNextSibling();
633 if (prev) {
634 prev->SetNextSibling(next);
635 }
636 if (next) {
637 next->SetPrevSibling(prev);
638 }
639
640 aChild->SetNextSibling(nullptr);
641 aChild->SetPrevSibling(nullptr);
642 }
643
644 //-------------------------------------------------------------------------
645 //
646 // Sets widget's position within its parent's child list.
647 //
648 //-------------------------------------------------------------------------
SetZIndex(int32_t aZIndex)649 void nsBaseWidget::SetZIndex(int32_t aZIndex) {
650 // Hold a ref to ourselves just in case, since we're going to remove
651 // from our parent.
652 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
653
654 mZIndex = aZIndex;
655
656 // reorder this child in its parent's list.
657 auto* parent = static_cast<nsBaseWidget*>(GetParent());
658 if (parent) {
659 parent->RemoveChild(this);
660 // Scope sib outside the for loop so we can check it afterward
661 nsIWidget* sib = parent->GetFirstChild();
662 for (; sib; sib = sib->GetNextSibling()) {
663 int32_t childZIndex = GetZIndex();
664 if (aZIndex < childZIndex) {
665 // Insert ourselves before sib
666 nsIWidget* prev = sib->GetPrevSibling();
667 mNextSibling = sib;
668 mPrevSibling = prev;
669 sib->SetPrevSibling(this);
670 if (prev) {
671 prev->SetNextSibling(this);
672 } else {
673 NS_ASSERTION(sib == parent->mFirstChild, "Broken child list");
674 // We've taken ownership of sib, so it's safe to have parent let
675 // go of it
676 parent->mFirstChild = this;
677 }
678 PlaceBehind(eZPlacementBelow, sib, false);
679 break;
680 }
681 }
682 // were we added to the list?
683 if (!sib) {
684 parent->AddChild(this);
685 }
686 }
687 }
688
689 //-------------------------------------------------------------------------
690 //
691 // Maximize, minimize or restore the window. The BaseWidget implementation
692 // merely stores the state.
693 //
694 //-------------------------------------------------------------------------
SetSizeMode(nsSizeMode aMode)695 void nsBaseWidget::SetSizeMode(nsSizeMode aMode) {
696 MOZ_ASSERT(aMode == nsSizeMode_Normal || aMode == nsSizeMode_Minimized ||
697 aMode == nsSizeMode_Maximized || aMode == nsSizeMode_Fullscreen);
698 mSizeMode = aMode;
699 }
700
GetWorkspaceID(nsAString & workspaceID)701 void nsBaseWidget::GetWorkspaceID(nsAString& workspaceID) {
702 workspaceID.Truncate();
703 }
704
MoveToWorkspace(const nsAString & workspaceID)705 void nsBaseWidget::MoveToWorkspace(const nsAString& workspaceID) {
706 // Noop.
707 }
708
709 //-------------------------------------------------------------------------
710 //
711 // Get this component cursor
712 //
713 //-------------------------------------------------------------------------
714
SetCursor(const Cursor & aCursor)715 void nsBaseWidget::SetCursor(const Cursor& aCursor) { mCursor = aCursor; }
716
717 //-------------------------------------------------------------------------
718 //
719 // Window transparency methods
720 //
721 //-------------------------------------------------------------------------
722
SetTransparencyMode(nsTransparencyMode aMode)723 void nsBaseWidget::SetTransparencyMode(nsTransparencyMode aMode) {}
724
GetTransparencyMode()725 nsTransparencyMode nsBaseWidget::GetTransparencyMode() {
726 return eTransparencyOpaque;
727 }
728
729 /* virtual */
PerformFullscreenTransition(FullscreenTransitionStage aStage,uint16_t aDuration,nsISupports * aData,nsIRunnable * aCallback)730 void nsBaseWidget::PerformFullscreenTransition(FullscreenTransitionStage aStage,
731 uint16_t aDuration,
732 nsISupports* aData,
733 nsIRunnable* aCallback) {
734 MOZ_ASSERT_UNREACHABLE(
735 "Should never call PerformFullscreenTransition on nsBaseWidget");
736 }
737
738 //-------------------------------------------------------------------------
739 //
740 // Put the window into full-screen mode
741 //
742 //-------------------------------------------------------------------------
InfallibleMakeFullScreen(bool aFullScreen)743 void nsBaseWidget::InfallibleMakeFullScreen(bool aFullScreen) {
744 HideWindowChrome(aFullScreen);
745
746 if (aFullScreen) {
747 if (!mOriginalBounds) {
748 mOriginalBounds = new LayoutDeviceIntRect();
749 }
750 *mOriginalBounds = GetScreenBounds();
751
752 // Move to top-left corner of screen and size to the screen dimensions
753 nsCOMPtr<nsIScreen> screen = GetWidgetScreen();
754 if (screen) {
755 int32_t left, top, width, height;
756 if (NS_SUCCEEDED(
757 screen->GetRectDisplayPix(&left, &top, &width, &height))) {
758 Resize(left, top, width, height, true);
759 }
760 }
761 } else if (mOriginalBounds) {
762 if (BoundsUseDesktopPixels()) {
763 DesktopRect deskRect = *mOriginalBounds / GetDesktopToDeviceScale();
764 Resize(deskRect.X(), deskRect.Y(), deskRect.Width(), deskRect.Height(),
765 true);
766 } else {
767 Resize(mOriginalBounds->X(), mOriginalBounds->Y(),
768 mOriginalBounds->Width(), mOriginalBounds->Height(), true);
769 }
770 }
771 }
772
MakeFullScreen(bool aFullScreen)773 nsresult nsBaseWidget::MakeFullScreen(bool aFullScreen) {
774 InfallibleMakeFullScreen(aFullScreen);
775 return NS_OK;
776 }
777
AutoLayerManagerSetup(nsBaseWidget * aWidget,gfxContext * aTarget,BufferMode aDoubleBuffering)778 nsBaseWidget::AutoLayerManagerSetup::AutoLayerManagerSetup(
779 nsBaseWidget* aWidget, gfxContext* aTarget, BufferMode aDoubleBuffering)
780 : mWidget(aWidget) {
781 WindowRenderer* renderer = mWidget->GetWindowRenderer();
782 if (renderer->AsFallback()) {
783 mRenderer = renderer->AsFallback();
784 mRenderer->SetTarget(aTarget, aDoubleBuffering);
785 }
786 }
787
~AutoLayerManagerSetup()788 nsBaseWidget::AutoLayerManagerSetup::~AutoLayerManagerSetup() {
789 if (mRenderer) {
790 mRenderer->SetTarget(nullptr, mozilla::layers::BufferMode::BUFFER_NONE);
791 }
792 }
793
IsSmallPopup() const794 bool nsBaseWidget::IsSmallPopup() const {
795 return mWindowType == eWindowType_popup && mPopupType != ePopupTypePanel;
796 }
797
ComputeShouldAccelerate()798 bool nsBaseWidget::ComputeShouldAccelerate() {
799 return gfx::gfxConfig::IsEnabled(gfx::Feature::HW_COMPOSITING) &&
800 (WidgetTypeSupportsAcceleration() ||
801 StaticPrefs::gfx_webrender_unaccelerated_widget_force());
802 }
803
UseAPZ()804 bool nsBaseWidget::UseAPZ() {
805 return (gfxPlatform::AsyncPanZoomEnabled() &&
806 (WindowType() == eWindowType_toplevel ||
807 WindowType() == eWindowType_child ||
808 ((WindowType() == eWindowType_popup ||
809 WindowType() == eWindowType_dialog) &&
810 HasRemoteContent() && StaticPrefs::apz_popups_enabled())));
811 }
812
CreateCompositor()813 void nsBaseWidget::CreateCompositor() {
814 LayoutDeviceIntRect rect = GetBounds();
815 CreateCompositor(rect.Width(), rect.Height());
816 }
817
818 already_AddRefed<GeckoContentController>
CreateRootContentController()819 nsBaseWidget::CreateRootContentController() {
820 RefPtr<GeckoContentController> controller =
821 new ChromeProcessController(this, mAPZEventState, mAPZC);
822 return controller.forget();
823 }
824
ConfigureAPZCTreeManager()825 void nsBaseWidget::ConfigureAPZCTreeManager() {
826 MOZ_ASSERT(NS_IsMainThread());
827 MOZ_ASSERT(mAPZC);
828
829 mAPZC->SetDPI(GetDPI());
830
831 if (StaticPrefs::apz_keyboard_enabled_AtStartup()) {
832 KeyboardMap map = RootWindowGlobalKeyListener::CollectKeyboardShortcuts();
833 mAPZC->SetKeyboardMap(map);
834 }
835
836 ContentReceivedInputBlockCallback callback(
837 [treeManager = RefPtr{mAPZC.get()}](uint64_t aInputBlockId,
838 bool aPreventDefault) {
839 MOZ_ASSERT(NS_IsMainThread());
840 treeManager->ContentReceivedInputBlock(aInputBlockId, aPreventDefault);
841 });
842 mAPZEventState = new APZEventState(this, std::move(callback));
843
844 mRootContentController = CreateRootContentController();
845 if (mRootContentController) {
846 mCompositorSession->SetContentController(mRootContentController);
847 }
848
849 // When APZ is enabled, we can actually enable raw touch events because we
850 // have code that can deal with them properly. If APZ is not enabled, this
851 // function doesn't get called.
852 if (StaticPrefs::dom_w3c_touch_events_enabled()) {
853 RegisterTouchWindow();
854 }
855 }
856
ConfigureAPZControllerThread()857 void nsBaseWidget::ConfigureAPZControllerThread() {
858 // By default the controller thread is the main thread.
859 APZThreadUtils::SetControllerThread(NS_GetCurrentThread());
860 }
861
SetConfirmedTargetAPZC(uint64_t aInputBlockId,const nsTArray<ScrollableLayerGuid> & aTargets) const862 void nsBaseWidget::SetConfirmedTargetAPZC(
863 uint64_t aInputBlockId,
864 const nsTArray<ScrollableLayerGuid>& aTargets) const {
865 mAPZC->SetTargetAPZC(aInputBlockId, aTargets);
866 }
867
UpdateZoomConstraints(const uint32_t & aPresShellId,const ScrollableLayerGuid::ViewID & aViewId,const Maybe<ZoomConstraints> & aConstraints)868 void nsBaseWidget::UpdateZoomConstraints(
869 const uint32_t& aPresShellId, const ScrollableLayerGuid::ViewID& aViewId,
870 const Maybe<ZoomConstraints>& aConstraints) {
871 if (!mCompositorSession || !mAPZC) {
872 if (mInitialZoomConstraints) {
873 MOZ_ASSERT(mInitialZoomConstraints->mPresShellID == aPresShellId);
874 MOZ_ASSERT(mInitialZoomConstraints->mViewID == aViewId);
875 if (!aConstraints) {
876 mInitialZoomConstraints.reset();
877 }
878 }
879
880 if (aConstraints) {
881 // We have some constraints, but the compositor and APZC aren't created
882 // yet. Save these so we can use them later.
883 mInitialZoomConstraints = Some(
884 InitialZoomConstraints(aPresShellId, aViewId, aConstraints.ref()));
885 }
886 return;
887 }
888 LayersId layersId = mCompositorSession->RootLayerTreeId();
889 mAPZC->UpdateZoomConstraints(
890 ScrollableLayerGuid(layersId, aPresShellId, aViewId), aConstraints);
891 }
892
AsyncPanZoomEnabled() const893 bool nsBaseWidget::AsyncPanZoomEnabled() const { return !!mAPZC; }
894
ProcessUntransformedAPZEvent(WidgetInputEvent * aEvent,const APZEventResult & aApzResult)895 nsEventStatus nsBaseWidget::ProcessUntransformedAPZEvent(
896 WidgetInputEvent* aEvent, const APZEventResult& aApzResult) {
897 MOZ_ASSERT(NS_IsMainThread());
898 ScrollableLayerGuid targetGuid = aApzResult.mTargetGuid;
899 uint64_t inputBlockId = aApzResult.mInputBlockId;
900 InputAPZContext context(aApzResult.mTargetGuid, inputBlockId,
901 aApzResult.GetStatus());
902
903 // Make a copy of the original event for the APZCCallbackHelper helpers that
904 // we call later, because the event passed to DispatchEvent can get mutated in
905 // ways that we don't want (i.e. touch points can get stripped out).
906 nsEventStatus status;
907 UniquePtr<WidgetEvent> original(aEvent->Duplicate());
908 DispatchEvent(aEvent, status);
909
910 if (mAPZC && !InputAPZContext::WasRoutedToChildProcess() && inputBlockId) {
911 // EventStateManager did not route the event into the child process.
912 // It's safe to communicate to APZ that the event has been processed.
913 // Note that here aGuid.mLayersId might be different from
914 // mCompositorSession->RootLayerTreeId() because the event might have gotten
915 // hit-tested by APZ to be targeted at a child process, but a parent process
916 // event listener called preventDefault on it. In that case aGuid.mLayersId
917 // would still be the layers id for the child process, but the event would
918 // not have actually gotten routed to the child process. The main-thread
919 // hit-test result therefore needs to use the parent process layers id.
920 LayersId rootLayersId = mCompositorSession->RootLayerTreeId();
921
922 RefPtr<DisplayportSetListener> postLayerization;
923 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
924 nsTArray<TouchBehaviorFlags> allowedTouchBehaviors;
925 if (touchEvent->mMessage == eTouchStart) {
926 auto& originalEvent = *original->AsTouchEvent();
927 MOZ_ASSERT(NS_IsMainThread());
928 allowedTouchBehaviors = TouchActionHelper::GetAllowedTouchBehavior(
929 this, GetDocument(), originalEvent);
930 if (!allowedTouchBehaviors.IsEmpty()) {
931 mAPZC->SetAllowedTouchBehavior(inputBlockId, allowedTouchBehaviors);
932 }
933 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
934 this, GetDocument(), originalEvent, rootLayersId, inputBlockId);
935 }
936 mAPZEventState->ProcessTouchEvent(*touchEvent, targetGuid, inputBlockId,
937 aApzResult.GetStatus(), status,
938 std::move(allowedTouchBehaviors));
939 } else if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
940 MOZ_ASSERT(wheelEvent->mFlags.mHandledByAPZ);
941 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
942 this, GetDocument(), *original->AsWheelEvent(), rootLayersId,
943 inputBlockId);
944 if (wheelEvent->mCanTriggerSwipe) {
945 ReportSwipeStarted(inputBlockId, wheelEvent->TriggersSwipe());
946 }
947 mAPZEventState->ProcessWheelEvent(*wheelEvent, inputBlockId);
948 } else if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
949 MOZ_ASSERT(mouseEvent->mFlags.mHandledByAPZ);
950 postLayerization = APZCCallbackHelper::SendSetTargetAPZCNotification(
951 this, GetDocument(), *original->AsMouseEvent(), rootLayersId,
952 inputBlockId);
953 mAPZEventState->ProcessMouseEvent(*mouseEvent, inputBlockId);
954 }
955 if (postLayerization) {
956 postLayerization->Register();
957 }
958 }
959
960 return status;
961 }
962
963 template <class InputType, class EventType>
964 class DispatchEventOnMainThread : public Runnable {
965 public:
DispatchEventOnMainThread(const InputType & aInput,nsBaseWidget * aWidget,const APZEventResult & aAPZResult)966 DispatchEventOnMainThread(const InputType& aInput, nsBaseWidget* aWidget,
967 const APZEventResult& aAPZResult)
968 : mozilla::Runnable("DispatchEventOnMainThread"),
969 mInput(aInput),
970 mWidget(aWidget),
971 mAPZResult(aAPZResult) {}
972
Run()973 NS_IMETHOD Run() override {
974 EventType event = mInput.ToWidgetEvent(mWidget);
975 mWidget->ProcessUntransformedAPZEvent(&event, mAPZResult);
976 return NS_OK;
977 }
978
979 private:
980 InputType mInput;
981 nsBaseWidget* mWidget;
982 APZEventResult mAPZResult;
983 };
984
985 template <class InputType, class EventType>
986 class DispatchInputOnControllerThread : public Runnable {
987 public:
DispatchInputOnControllerThread(const EventType & aEvent,IAPZCTreeManager * aAPZC,nsBaseWidget * aWidget)988 DispatchInputOnControllerThread(const EventType& aEvent,
989 IAPZCTreeManager* aAPZC,
990 nsBaseWidget* aWidget)
991 : mozilla::Runnable("DispatchInputOnControllerThread"),
992 mMainMessageLoop(MessageLoop::current()),
993 mInput(aEvent),
994 mAPZC(aAPZC),
995 mWidget(aWidget) {}
996
Run()997 NS_IMETHOD Run() override {
998 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(mInput);
999 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1000 return NS_OK;
1001 }
1002 RefPtr<Runnable> r = new DispatchEventOnMainThread<InputType, EventType>(
1003 mInput, mWidget, result);
1004 mMainMessageLoop->PostTask(r.forget());
1005 return NS_OK;
1006 }
1007
1008 private:
1009 MessageLoop* mMainMessageLoop;
1010 InputType mInput;
1011 RefPtr<IAPZCTreeManager> mAPZC;
1012 nsBaseWidget* mWidget;
1013 };
1014
DispatchTouchInput(MultiTouchInput & aInput,uint16_t aInputSource)1015 void nsBaseWidget::DispatchTouchInput(MultiTouchInput& aInput,
1016 uint16_t aInputSource) {
1017 MOZ_ASSERT(NS_IsMainThread());
1018 MOZ_ASSERT(aInputSource ==
1019 mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_TOUCH ||
1020 aInputSource == mozilla::dom::MouseEvent_Binding::MOZ_SOURCE_PEN);
1021 if (mAPZC) {
1022 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1023
1024 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1025 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1026 return;
1027 }
1028
1029 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1030 ProcessUntransformedAPZEvent(&event, result);
1031 } else {
1032 WidgetTouchEvent event = aInput.ToWidgetEvent(this, aInputSource);
1033
1034 nsEventStatus status;
1035 DispatchEvent(&event, status);
1036 }
1037 }
1038
DispatchPanGestureInput(PanGestureInput & aInput)1039 void nsBaseWidget::DispatchPanGestureInput(PanGestureInput& aInput) {
1040 MOZ_ASSERT(NS_IsMainThread());
1041 if (mAPZC) {
1042 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1043
1044 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1045 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1046 return;
1047 }
1048
1049 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1050 ProcessUntransformedAPZEvent(&event, result);
1051 } else {
1052 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1053 nsEventStatus status;
1054 DispatchEvent(&event, status);
1055 }
1056 }
1057
DispatchPinchGestureInput(PinchGestureInput & aInput)1058 void nsBaseWidget::DispatchPinchGestureInput(PinchGestureInput& aInput) {
1059 MOZ_ASSERT(NS_IsMainThread());
1060 if (mAPZC) {
1061 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1062 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(aInput);
1063
1064 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1065 return;
1066 }
1067 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1068 ProcessUntransformedAPZEvent(&event, result);
1069 } else {
1070 WidgetWheelEvent event = aInput.ToWidgetEvent(this);
1071 nsEventStatus status;
1072 DispatchEvent(&event, status);
1073 }
1074 }
1075
DispatchInputEvent(WidgetInputEvent * aEvent)1076 nsIWidget::ContentAndAPZEventStatus nsBaseWidget::DispatchInputEvent(
1077 WidgetInputEvent* aEvent) {
1078 nsIWidget::ContentAndAPZEventStatus status;
1079 MOZ_ASSERT(NS_IsMainThread());
1080 if (mAPZC) {
1081 if (APZThreadUtils::IsControllerThread()) {
1082 APZEventResult result = mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1083 status.mApzStatus = result.GetStatus();
1084 if (result.GetStatus() == nsEventStatus_eConsumeNoDefault) {
1085 return status;
1086 }
1087 status.mContentStatus = ProcessUntransformedAPZEvent(aEvent, result);
1088 return status;
1089 }
1090 if (WidgetWheelEvent* wheelEvent = aEvent->AsWheelEvent()) {
1091 RefPtr<Runnable> r =
1092 new DispatchInputOnControllerThread<ScrollWheelInput,
1093 WidgetWheelEvent>(*wheelEvent,
1094 mAPZC, this);
1095 APZThreadUtils::RunOnControllerThread(std::move(r));
1096 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1097 return status;
1098 }
1099 if (WidgetMouseEvent* mouseEvent = aEvent->AsMouseEvent()) {
1100 RefPtr<Runnable> r =
1101 new DispatchInputOnControllerThread<MouseInput, WidgetMouseEvent>(
1102 *mouseEvent, mAPZC, this);
1103 APZThreadUtils::RunOnControllerThread(std::move(r));
1104 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1105 return status;
1106 }
1107 if (WidgetTouchEvent* touchEvent = aEvent->AsTouchEvent()) {
1108 RefPtr<Runnable> r =
1109 new DispatchInputOnControllerThread<MultiTouchInput,
1110 WidgetTouchEvent>(*touchEvent,
1111 mAPZC, this);
1112 APZThreadUtils::RunOnControllerThread(std::move(r));
1113 status.mContentStatus = nsEventStatus_eConsumeDoDefault;
1114 return status;
1115 }
1116 // Allow dispatching keyboard events on Gecko thread.
1117 MOZ_ASSERT(aEvent->AsKeyboardEvent());
1118 }
1119
1120 DispatchEvent(aEvent, status.mContentStatus);
1121 return status;
1122 }
1123
DispatchEventToAPZOnly(mozilla::WidgetInputEvent * aEvent)1124 void nsBaseWidget::DispatchEventToAPZOnly(mozilla::WidgetInputEvent* aEvent) {
1125 MOZ_ASSERT(NS_IsMainThread());
1126 if (mAPZC) {
1127 MOZ_ASSERT(APZThreadUtils::IsControllerThread());
1128 mAPZC->InputBridge()->ReceiveInputEvent(*aEvent);
1129 }
1130 }
1131
DispatchWindowEvent(WidgetGUIEvent & event)1132 bool nsBaseWidget::DispatchWindowEvent(WidgetGUIEvent& event) {
1133 nsEventStatus status;
1134 DispatchEvent(&event, status);
1135 return ConvertStatus(status);
1136 }
1137
GetDocument() const1138 Document* nsBaseWidget::GetDocument() const {
1139 if (mWidgetListener) {
1140 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1141 return presShell->GetDocument();
1142 }
1143 }
1144 return nullptr;
1145 }
1146
CreateCompositorVsyncDispatcher()1147 void nsBaseWidget::CreateCompositorVsyncDispatcher() {
1148 // Parent directly listens to the vsync source whereas
1149 // child process communicate via IPC
1150 // Should be called AFTER gfxPlatform is initialized
1151 if (XRE_IsParentProcess()) {
1152 if (!mCompositorVsyncDispatcherLock) {
1153 mCompositorVsyncDispatcherLock =
1154 MakeUnique<Mutex>("mCompositorVsyncDispatcherLock");
1155 }
1156 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1157 if (!mCompositorVsyncDispatcher) {
1158 mCompositorVsyncDispatcher = new CompositorVsyncDispatcher();
1159 }
1160 }
1161 }
1162
1163 already_AddRefed<CompositorVsyncDispatcher>
GetCompositorVsyncDispatcher()1164 nsBaseWidget::GetCompositorVsyncDispatcher() {
1165 MOZ_ASSERT(mCompositorVsyncDispatcherLock.get());
1166
1167 MutexAutoLock lock(*mCompositorVsyncDispatcherLock.get());
1168 RefPtr<CompositorVsyncDispatcher> dispatcher = mCompositorVsyncDispatcher;
1169 return dispatcher.forget();
1170 }
1171
CreateCompositorSession(int aWidth,int aHeight,CompositorOptions * aOptionsOut)1172 already_AddRefed<WebRenderLayerManager> nsBaseWidget::CreateCompositorSession(
1173 int aWidth, int aHeight, CompositorOptions* aOptionsOut) {
1174 MOZ_ASSERT(aOptionsOut);
1175
1176 do {
1177 CreateCompositorVsyncDispatcher();
1178
1179 gfx::GPUProcessManager* gpu = gfx::GPUProcessManager::Get();
1180 // Make sure GPU process is ready for use.
1181 // If it failed to connect to GPU process, GPU process usage is disabled in
1182 // EnsureGPUReady(). It could update gfxVars and gfxConfigs.
1183 gpu->EnsureGPUReady();
1184
1185 // If widget type does not supports acceleration, we may be allowed to use
1186 // software WebRender instead. If not, then we use ClientLayerManager even
1187 // when gfxVars::UseWebRender() is true. WebRender could coexist only with
1188 // BasicCompositor.
1189 bool supportsAcceleration = WidgetTypeSupportsAcceleration();
1190 bool enableWR;
1191 bool enableSWWR;
1192 if (supportsAcceleration ||
1193 StaticPrefs::gfx_webrender_unaccelerated_widget_force()) {
1194 enableWR = gfx::gfxVars::UseWebRender();
1195 enableSWWR = gfx::gfxVars::UseSoftwareWebRender();
1196 } else {
1197 enableWR = enableSWWR = gfx::gfxVars::UseWebRender();
1198 }
1199 MOZ_RELEASE_ASSERT(enableWR);
1200 bool enableAPZ = UseAPZ();
1201 CompositorOptions options(enableAPZ, enableSWWR);
1202
1203 #ifdef XP_WIN
1204 if (supportsAcceleration) {
1205 options.SetAllowSoftwareWebRenderD3D11(
1206 gfx::gfxVars::AllowSoftwareWebRenderD3D11());
1207 }
1208 #elif defined(MOZ_WIDGET_ANDROID)
1209 MOZ_ASSERT(supportsAcceleration);
1210 options.SetAllowSoftwareWebRenderOGL(
1211 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1212 #elif defined(MOZ_WIDGET_GTK)
1213 if (supportsAcceleration) {
1214 options.SetAllowSoftwareWebRenderOGL(
1215 StaticPrefs::gfx_webrender_software_opengl_AtStartup());
1216 }
1217 #endif
1218
1219 options.SetUseWebGPU(StaticPrefs::dom_webgpu_enabled());
1220
1221 #ifdef MOZ_WIDGET_ANDROID
1222 // Unconditionally set the compositor as initially paused, as we have not
1223 // yet had a chance to send the compositor surface to the GPU process. We
1224 // will do so shortly once we have returned to nsWindow::CreateLayerManager,
1225 // where we will also resume the compositor if required.
1226 options.SetInitiallyPaused(true);
1227 #else
1228 options.SetInitiallyPaused(CompositorInitiallyPaused());
1229 #endif
1230
1231 RefPtr<WebRenderLayerManager> lm = new WebRenderLayerManager(this);
1232
1233 bool retry = false;
1234 mCompositorSession = gpu->CreateTopLevelCompositor(
1235 this, lm, GetDefaultScale(), options, UseExternalCompositingSurface(),
1236 gfx::IntSize(aWidth, aHeight), &retry);
1237
1238 if (mCompositorSession) {
1239 TextureFactoryIdentifier textureFactoryIdentifier;
1240 nsCString error;
1241 lm->Initialize(mCompositorSession->GetCompositorBridgeChild(),
1242 wr::AsPipelineId(mCompositorSession->RootLayerTreeId()),
1243 &textureFactoryIdentifier, error);
1244 if (textureFactoryIdentifier.mParentBackend != LayersBackend::LAYERS_WR) {
1245 retry = true;
1246 DestroyCompositor();
1247 // gfxVars::UseDoubleBufferingWithCompositor() is also disabled.
1248 gfx::GPUProcessManager::Get()->DisableWebRender(
1249 wr::WebRenderError::INITIALIZE, error);
1250 }
1251 }
1252
1253 // We need to retry in a loop because the act of failing to create the
1254 // compositor can change our state (e.g. disable WebRender).
1255 if (mCompositorSession || !retry) {
1256 *aOptionsOut = options;
1257 return lm.forget();
1258 }
1259 } while (true);
1260 }
1261
CreateCompositor(int aWidth,int aHeight)1262 void nsBaseWidget::CreateCompositor(int aWidth, int aHeight) {
1263 // This makes sure that gfxPlatforms gets initialized if it hasn't by now.
1264 gfxPlatform::GetPlatform();
1265
1266 MOZ_ASSERT(gfxPlatform::UsesOffMainThreadCompositing(),
1267 "This function assumes OMTC");
1268
1269 MOZ_ASSERT(!mCompositorSession && !mCompositorBridgeChild,
1270 "Should have properly cleaned up the previous PCompositor pair "
1271 "beforehand");
1272
1273 if (mCompositorBridgeChild) {
1274 mCompositorBridgeChild->Destroy();
1275 }
1276
1277 // Recreating this is tricky, as we may still have an old and we need
1278 // to make sure it's properly destroyed by calling DestroyCompositor!
1279
1280 // If we've already received a shutdown notification, don't try
1281 // create a new compositor.
1282 if (!mShutdownObserver) {
1283 return;
1284 }
1285
1286 // The controller thread must be configured before the compositor
1287 // session is created, so that the input bridge runs on the right
1288 // thread.
1289 ConfigureAPZControllerThread();
1290
1291 CompositorOptions options;
1292 RefPtr<WebRenderLayerManager> lm =
1293 CreateCompositorSession(aWidth, aHeight, &options);
1294 if (!lm) {
1295 return;
1296 }
1297
1298 MOZ_ASSERT(mCompositorSession);
1299 mCompositorBridgeChild = mCompositorSession->GetCompositorBridgeChild();
1300 SetCompositorWidgetDelegate(
1301 mCompositorSession->GetCompositorWidgetDelegate());
1302
1303 if (options.UseAPZ()) {
1304 mAPZC = mCompositorSession->GetAPZCTreeManager();
1305 ConfigureAPZCTreeManager();
1306 } else {
1307 mAPZC = nullptr;
1308 }
1309
1310 if (mInitialZoomConstraints) {
1311 UpdateZoomConstraints(mInitialZoomConstraints->mPresShellID,
1312 mInitialZoomConstraints->mViewID,
1313 Some(mInitialZoomConstraints->mConstraints));
1314 mInitialZoomConstraints.reset();
1315 }
1316
1317 TextureFactoryIdentifier textureFactoryIdentifier =
1318 lm->GetTextureFactoryIdentifier();
1319 MOZ_ASSERT(textureFactoryIdentifier.mParentBackend ==
1320 LayersBackend::LAYERS_WR);
1321 ImageBridgeChild::IdentifyCompositorTextureHost(textureFactoryIdentifier);
1322 gfx::VRManagerChild::IdentifyTextureHost(textureFactoryIdentifier);
1323
1324 WindowUsesOMTC();
1325
1326 mWindowRenderer = std::move(lm);
1327
1328 // Only track compositors for top-level windows, since other window types
1329 // may use the basic compositor. Except on the OS X - see bug 1306383
1330 #if defined(XP_MACOSX)
1331 bool getCompositorFromThisWindow = true;
1332 #else
1333 bool getCompositorFromThisWindow = (mWindowType == eWindowType_toplevel);
1334 #endif
1335
1336 if (getCompositorFromThisWindow) {
1337 gfxPlatform::GetPlatform()->NotifyCompositorCreated(
1338 mWindowRenderer->GetCompositorBackendType());
1339 }
1340 }
1341
NotifyCompositorSessionLost(CompositorSession * aSession)1342 void nsBaseWidget::NotifyCompositorSessionLost(CompositorSession* aSession) {
1343 MOZ_ASSERT(aSession == mCompositorSession);
1344 DestroyLayerManager();
1345 }
1346
ShouldUseOffMainThreadCompositing()1347 bool nsBaseWidget::ShouldUseOffMainThreadCompositing() {
1348 return gfxPlatform::UsesOffMainThreadCompositing();
1349 }
1350
GetWindowRenderer()1351 WindowRenderer* nsBaseWidget::GetWindowRenderer() {
1352 if (!mWindowRenderer) {
1353 if (!mShutdownObserver) {
1354 // We are shutting down, do not try to re-create a LayerManager
1355 return nullptr;
1356 }
1357 // Try to use an async compositor first, if possible
1358 if (ShouldUseOffMainThreadCompositing()) {
1359 CreateCompositor();
1360 }
1361
1362 if (!mWindowRenderer) {
1363 mWindowRenderer = CreateFallbackRenderer();
1364 }
1365 }
1366 return mWindowRenderer;
1367 }
1368
CreateFallbackRenderer()1369 WindowRenderer* nsBaseWidget::CreateFallbackRenderer() {
1370 return new FallbackRenderer;
1371 }
1372
GetRemoteRenderer()1373 CompositorBridgeChild* nsBaseWidget::GetRemoteRenderer() {
1374 return mCompositorBridgeChild;
1375 }
1376
ClearCachedWebrenderResources()1377 void nsBaseWidget::ClearCachedWebrenderResources() {
1378 if (!mWindowRenderer || !mWindowRenderer->AsWebRender()) {
1379 return;
1380 }
1381 mWindowRenderer->AsWebRender()->ClearCachedResources();
1382 }
1383
StartRemoteDrawing()1384 already_AddRefed<gfx::DrawTarget> nsBaseWidget::StartRemoteDrawing() {
1385 return nullptr;
1386 }
1387
GetGLFrameBufferFormat()1388 uint32_t nsBaseWidget::GetGLFrameBufferFormat() { return LOCAL_GL_RGBA; }
1389
1390 //-------------------------------------------------------------------------
1391 //
1392 // Destroy the window
1393 //
1394 //-------------------------------------------------------------------------
OnDestroy()1395 void nsBaseWidget::OnDestroy() {
1396 if (mTextEventDispatcher) {
1397 mTextEventDispatcher->OnDestroyWidget();
1398 // Don't release it until this widget actually released because after this
1399 // is called, TextEventDispatcher() may create it again.
1400 }
1401
1402 // If this widget is being destroyed, let the APZ code know to drop references
1403 // to this widget. Callers of this function all should be holding a deathgrip
1404 // on this widget already.
1405 ReleaseContentController();
1406 }
1407
MoveClient(const DesktopPoint & aOffset)1408 void nsBaseWidget::MoveClient(const DesktopPoint& aOffset) {
1409 LayoutDeviceIntPoint clientOffset(GetClientOffset());
1410
1411 // GetClientOffset returns device pixels; scale back to desktop pixels
1412 // if that's what this widget uses for the Move/Resize APIs
1413 if (BoundsUseDesktopPixels()) {
1414 DesktopPoint desktopOffset = clientOffset / GetDesktopToDeviceScale();
1415 Move(aOffset.x - desktopOffset.x, aOffset.y - desktopOffset.y);
1416 } else {
1417 LayoutDevicePoint layoutOffset = aOffset * GetDesktopToDeviceScale();
1418 Move(layoutOffset.x - clientOffset.x, layoutOffset.y - clientOffset.y);
1419 }
1420 }
1421
ResizeClient(const DesktopSize & aSize,bool aRepaint)1422 void nsBaseWidget::ResizeClient(const DesktopSize& aSize, bool aRepaint) {
1423 NS_ASSERTION((aSize.width >= 0), "Negative width passed to ResizeClient");
1424 NS_ASSERTION((aSize.height >= 0), "Negative height passed to ResizeClient");
1425
1426 LayoutDeviceIntRect clientBounds = GetClientBounds();
1427
1428 // GetClientBounds and mBounds are device pixels; scale back to desktop pixels
1429 // if that's what this widget uses for the Move/Resize APIs
1430 if (BoundsUseDesktopPixels()) {
1431 DesktopSize desktopDelta =
1432 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1433 clientBounds.Size()) /
1434 GetDesktopToDeviceScale();
1435 Resize(aSize.width + desktopDelta.width, aSize.height + desktopDelta.height,
1436 aRepaint);
1437 } else {
1438 LayoutDeviceSize layoutSize = aSize * GetDesktopToDeviceScale();
1439 Resize(mBounds.Width() + (layoutSize.width - clientBounds.Width()),
1440 mBounds.Height() + (layoutSize.height - clientBounds.Height()),
1441 aRepaint);
1442 }
1443 }
1444
ResizeClient(const DesktopRect & aRect,bool aRepaint)1445 void nsBaseWidget::ResizeClient(const DesktopRect& aRect, bool aRepaint) {
1446 NS_ASSERTION((aRect.Width() >= 0), "Negative width passed to ResizeClient");
1447 NS_ASSERTION((aRect.Height() >= 0), "Negative height passed to ResizeClient");
1448
1449 LayoutDeviceIntRect clientBounds = GetClientBounds();
1450 LayoutDeviceIntPoint clientOffset = GetClientOffset();
1451 DesktopToLayoutDeviceScale scale = GetDesktopToDeviceScale();
1452
1453 if (BoundsUseDesktopPixels()) {
1454 DesktopPoint desktopOffset = clientOffset / scale;
1455 DesktopSize desktopDelta =
1456 (LayoutDeviceIntSize(mBounds.Width(), mBounds.Height()) -
1457 clientBounds.Size()) /
1458 scale;
1459 Resize(aRect.X() - desktopOffset.x, aRect.Y() - desktopOffset.y,
1460 aRect.Width() + desktopDelta.width,
1461 aRect.Height() + desktopDelta.height, aRepaint);
1462 } else {
1463 LayoutDeviceRect layoutRect = aRect * scale;
1464 Resize(layoutRect.X() - clientOffset.x, layoutRect.Y() - clientOffset.y,
1465 layoutRect.Width() + mBounds.Width() - clientBounds.Width(),
1466 layoutRect.Height() + mBounds.Height() - clientBounds.Height(),
1467 aRepaint);
1468 }
1469 }
1470
1471 //-------------------------------------------------------------------------
1472 //
1473 // Bounds
1474 //
1475 //-------------------------------------------------------------------------
1476
1477 /**
1478 * If the implementation of nsWindow supports borders this method MUST be
1479 * overridden
1480 *
1481 **/
GetClientBounds()1482 LayoutDeviceIntRect nsBaseWidget::GetClientBounds() { return GetBounds(); }
1483
1484 /**
1485 * If the implementation of nsWindow supports borders this method MUST be
1486 * overridden
1487 *
1488 **/
GetBounds()1489 LayoutDeviceIntRect nsBaseWidget::GetBounds() { return mBounds; }
1490
1491 /**
1492 * If the implementation of nsWindow uses a local coordinate system within the
1493 *window, this method must be overridden
1494 *
1495 **/
GetScreenBounds()1496 LayoutDeviceIntRect nsBaseWidget::GetScreenBounds() { return GetBounds(); }
1497
GetRestoredBounds(LayoutDeviceIntRect & aRect)1498 nsresult nsBaseWidget::GetRestoredBounds(LayoutDeviceIntRect& aRect) {
1499 if (SizeMode() != nsSizeMode_Normal) {
1500 return NS_ERROR_FAILURE;
1501 }
1502 aRect = GetScreenBounds();
1503 return NS_OK;
1504 }
1505
GetClientOffset()1506 LayoutDeviceIntPoint nsBaseWidget::GetClientOffset() {
1507 return LayoutDeviceIntPoint(0, 0);
1508 }
1509
SetNonClientMargins(LayoutDeviceIntMargin & margins)1510 nsresult nsBaseWidget::SetNonClientMargins(LayoutDeviceIntMargin& margins) {
1511 return NS_ERROR_NOT_IMPLEMENTED;
1512 }
1513
SetResizeMargin(LayoutDeviceIntCoord aResizeMargin)1514 void nsBaseWidget::SetResizeMargin(LayoutDeviceIntCoord aResizeMargin) {}
1515
GetMaxTouchPoints() const1516 uint32_t nsBaseWidget::GetMaxTouchPoints() const { return 0; }
1517
HasPendingInputEvent()1518 bool nsBaseWidget::HasPendingInputEvent() { return false; }
1519
ShowsResizeIndicator(LayoutDeviceIntRect * aResizerRect)1520 bool nsBaseWidget::ShowsResizeIndicator(LayoutDeviceIntRect* aResizerRect) {
1521 return false;
1522 }
1523
1524 /**
1525 * Modifies aFile to point at an icon file with the given name and suffix. The
1526 * suffix may correspond to a file extension with leading '.' if appropriate.
1527 * Returns true if the icon file exists and can be read.
1528 */
ResolveIconNameHelper(nsIFile * aFile,const nsAString & aIconName,const nsAString & aIconSuffix)1529 static bool ResolveIconNameHelper(nsIFile* aFile, const nsAString& aIconName,
1530 const nsAString& aIconSuffix) {
1531 aFile->Append(u"icons"_ns);
1532 aFile->Append(u"default"_ns);
1533 aFile->Append(aIconName + aIconSuffix);
1534
1535 bool readable;
1536 return NS_SUCCEEDED(aFile->IsReadable(&readable)) && readable;
1537 }
1538
1539 /**
1540 * Resolve the given icon name into a local file object. This method is
1541 * intended to be called by subclasses of nsBaseWidget. aIconSuffix is a
1542 * platform specific icon file suffix (e.g., ".ico" under Win32).
1543 *
1544 * If no file is found matching the given parameters, then null is returned.
1545 */
ResolveIconName(const nsAString & aIconName,const nsAString & aIconSuffix,nsIFile ** aResult)1546 void nsBaseWidget::ResolveIconName(const nsAString& aIconName,
1547 const nsAString& aIconSuffix,
1548 nsIFile** aResult) {
1549 *aResult = nullptr;
1550
1551 nsCOMPtr<nsIProperties> dirSvc =
1552 do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
1553 if (!dirSvc) return;
1554
1555 // first check auxilary chrome directories
1556
1557 nsCOMPtr<nsISimpleEnumerator> dirs;
1558 dirSvc->Get(NS_APP_CHROME_DIR_LIST, NS_GET_IID(nsISimpleEnumerator),
1559 getter_AddRefs(dirs));
1560 if (dirs) {
1561 bool hasMore;
1562 while (NS_SUCCEEDED(dirs->HasMoreElements(&hasMore)) && hasMore) {
1563 nsCOMPtr<nsISupports> element;
1564 dirs->GetNext(getter_AddRefs(element));
1565 if (!element) continue;
1566 nsCOMPtr<nsIFile> file = do_QueryInterface(element);
1567 if (!file) continue;
1568 if (ResolveIconNameHelper(file, aIconName, aIconSuffix)) {
1569 NS_ADDREF(*aResult = file);
1570 return;
1571 }
1572 }
1573 }
1574
1575 // then check the main app chrome directory
1576
1577 nsCOMPtr<nsIFile> file;
1578 dirSvc->Get(NS_APP_CHROME_DIR, NS_GET_IID(nsIFile), getter_AddRefs(file));
1579 if (file && ResolveIconNameHelper(file, aIconName, aIconSuffix))
1580 NS_ADDREF(*aResult = file);
1581 }
1582
SetSizeConstraints(const SizeConstraints & aConstraints)1583 void nsBaseWidget::SetSizeConstraints(const SizeConstraints& aConstraints) {
1584 mSizeConstraints = aConstraints;
1585
1586 // Popups are constrained during layout, and we don't want to synchronously
1587 // paint from reflow, so bail out... This is not great, but it's no worse than
1588 // what we used to do.
1589 //
1590 // The right fix here is probably making constraint changes go through the
1591 // view manager and such.
1592 if (mWindowType == eWindowType_popup) {
1593 return;
1594 }
1595
1596 // If the current size doesn't meet the new constraints, trigger a
1597 // resize to apply it. Note that, we don't want to invoke Resize if
1598 // the new constraints don't affect the current size, because Resize
1599 // implementation on some platforms may touch other geometry even if
1600 // the size don't need to change.
1601 LayoutDeviceIntSize curSize = mBounds.Size();
1602 LayoutDeviceIntSize clampedSize =
1603 Max(aConstraints.mMinSize, Min(aConstraints.mMaxSize, curSize));
1604 if (clampedSize != curSize) {
1605 gfx::Size size;
1606 if (BoundsUseDesktopPixels()) {
1607 DesktopSize desktopSize = clampedSize / GetDesktopToDeviceScale();
1608 size = desktopSize.ToUnknownSize();
1609 } else {
1610 size = gfx::Size(clampedSize.ToUnknownSize());
1611 }
1612 Resize(size.width, size.height, true);
1613 }
1614 }
1615
GetSizeConstraints()1616 const widget::SizeConstraints nsBaseWidget::GetSizeConstraints() {
1617 return mSizeConstraints;
1618 }
1619
1620 // static
GetActiveRollupListener()1621 nsIRollupListener* nsBaseWidget::GetActiveRollupListener() {
1622 // If set, then this is likely an <html:select> dropdown.
1623 if (gRollupListener) return gRollupListener;
1624
1625 return nsXULPopupManager::GetInstance();
1626 }
1627
NotifyWindowDestroyed()1628 void nsBaseWidget::NotifyWindowDestroyed() {
1629 if (!mWidgetListener) return;
1630
1631 nsCOMPtr<nsIAppWindow> window = mWidgetListener->GetAppWindow();
1632 nsCOMPtr<nsIBaseWindow> appWindow(do_QueryInterface(window));
1633 if (appWindow) {
1634 appWindow->Destroy();
1635 }
1636 }
1637
NotifyWindowMoved(int32_t aX,int32_t aY)1638 void nsBaseWidget::NotifyWindowMoved(int32_t aX, int32_t aY) {
1639 if (mWidgetListener) {
1640 mWidgetListener->WindowMoved(this, aX, aY);
1641 }
1642
1643 if (mIMEHasFocus && IMENotificationRequestsRef().WantPositionChanged()) {
1644 NotifyIME(IMENotification(IMEMessage::NOTIFY_IME_OF_POSITION_CHANGE));
1645 }
1646 }
1647
NotifySizeMoveDone()1648 void nsBaseWidget::NotifySizeMoveDone() {
1649 if (!mWidgetListener) {
1650 return;
1651 }
1652 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1653 presShell->WindowSizeMoveDone();
1654 }
1655 }
1656
NotifyThemeChanged(ThemeChangeKind aKind)1657 void nsBaseWidget::NotifyThemeChanged(ThemeChangeKind aKind) {
1658 LookAndFeel::NotifyChangedAllWindows(aKind);
1659 }
1660
NotifyUIStateChanged(UIStateChangeType aShowFocusRings)1661 void nsBaseWidget::NotifyUIStateChanged(UIStateChangeType aShowFocusRings) {
1662 if (Document* doc = GetDocument()) {
1663 if (nsPIDOMWindowOuter* win = doc->GetWindow()) {
1664 win->SetKeyboardIndicators(aShowFocusRings);
1665 }
1666 }
1667 }
1668
NotifyIME(const IMENotification & aIMENotification)1669 nsresult nsBaseWidget::NotifyIME(const IMENotification& aIMENotification) {
1670 if (mIMEHasQuit) {
1671 return NS_OK;
1672 }
1673 switch (aIMENotification.mMessage) {
1674 case REQUEST_TO_COMMIT_COMPOSITION:
1675 case REQUEST_TO_CANCEL_COMPOSITION:
1676 // We should send request to IME only when there is a TextEventDispatcher
1677 // instance (this means that this widget has dispatched at least one
1678 // composition event or keyboard event) and the it has composition.
1679 // Otherwise, there is nothing to do.
1680 // Note that if current input transaction is for native input events,
1681 // TextEventDispatcher::NotifyIME() will call
1682 // TextEventDispatcherListener::NotifyIME().
1683 if (mTextEventDispatcher && mTextEventDispatcher->IsComposing()) {
1684 return mTextEventDispatcher->NotifyIME(aIMENotification);
1685 }
1686 return NS_OK;
1687 default: {
1688 if (aIMENotification.mMessage == NOTIFY_IME_OF_FOCUS) {
1689 mIMEHasFocus = true;
1690 }
1691 EnsureTextEventDispatcher();
1692 // TextEventDispatcher::NotifyIME() will always call
1693 // TextEventDispatcherListener::NotifyIME(). I.e., even if current
1694 // input transaction is for synthesized events for automated tests,
1695 // notifications will be sent to native IME.
1696 nsresult rv = mTextEventDispatcher->NotifyIME(aIMENotification);
1697 if (aIMENotification.mMessage == NOTIFY_IME_OF_BLUR) {
1698 mIMEHasFocus = false;
1699 }
1700 return rv;
1701 }
1702 }
1703 }
1704
EnsureTextEventDispatcher()1705 void nsBaseWidget::EnsureTextEventDispatcher() {
1706 if (mTextEventDispatcher) {
1707 return;
1708 }
1709 mTextEventDispatcher = new TextEventDispatcher(this);
1710 }
1711
GetNativeIMEContext()1712 nsIWidget::NativeIMEContext nsBaseWidget::GetNativeIMEContext() {
1713 if (mTextEventDispatcher && mTextEventDispatcher->GetPseudoIMEContext()) {
1714 // If we already have a TextEventDispatcher and it's working with
1715 // a TextInputProcessor, we need to return pseudo IME context since
1716 // TextCompositionArray::IndexOf(nsIWidget*) should return a composition
1717 // on the pseudo IME context in such case.
1718 NativeIMEContext pseudoIMEContext;
1719 pseudoIMEContext.InitWithRawNativeIMEContext(
1720 mTextEventDispatcher->GetPseudoIMEContext());
1721 return pseudoIMEContext;
1722 }
1723 return NativeIMEContext(this);
1724 }
1725
GetTextEventDispatcher()1726 nsIWidget::TextEventDispatcher* nsBaseWidget::GetTextEventDispatcher() {
1727 EnsureTextEventDispatcher();
1728 return mTextEventDispatcher;
1729 }
1730
GetPseudoIMEContext()1731 void* nsBaseWidget::GetPseudoIMEContext() {
1732 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
1733 if (!dispatcher) {
1734 return nullptr;
1735 }
1736 return dispatcher->GetPseudoIMEContext();
1737 }
1738
1739 TextEventDispatcherListener*
GetNativeTextEventDispatcherListener()1740 nsBaseWidget::GetNativeTextEventDispatcherListener() {
1741 // TODO: If all platforms supported use of TextEventDispatcher for handling
1742 // native IME and keyboard events, this method should be removed since
1743 // in such case, this is overridden by all the subclasses.
1744 return nullptr;
1745 }
1746
ZoomToRect(const uint32_t & aPresShellId,const ScrollableLayerGuid::ViewID & aViewId,const CSSRect & aRect,const uint32_t & aFlags)1747 void nsBaseWidget::ZoomToRect(const uint32_t& aPresShellId,
1748 const ScrollableLayerGuid::ViewID& aViewId,
1749 const CSSRect& aRect, const uint32_t& aFlags) {
1750 if (!mCompositorSession || !mAPZC) {
1751 return;
1752 }
1753 LayersId layerId = mCompositorSession->RootLayerTreeId();
1754 mAPZC->ZoomToRect(ScrollableLayerGuid(layerId, aPresShellId, aViewId),
1755 ZoomTarget{aRect}, aFlags);
1756 }
1757
1758 #ifdef ACCESSIBILITY
1759
GetRootAccessible()1760 a11y::LocalAccessible* nsBaseWidget::GetRootAccessible() {
1761 NS_ENSURE_TRUE(mWidgetListener, nullptr);
1762
1763 PresShell* presShell = mWidgetListener->GetPresShell();
1764 NS_ENSURE_TRUE(presShell, nullptr);
1765
1766 // If container is null then the presshell is not active. This often happens
1767 // when a preshell is being held onto for fastback.
1768 nsPresContext* presContext = presShell->GetPresContext();
1769 NS_ENSURE_TRUE(presContext->GetContainerWeak(), nullptr);
1770
1771 // LocalAccessible creation might be not safe so use IsSafeToRunScript to
1772 // make sure it's not created at unsafe times.
1773 nsAccessibilityService* accService = GetOrCreateAccService();
1774 if (accService) {
1775 return accService->GetRootDocumentAccessible(
1776 presShell, nsContentUtils::IsSafeToRunScript());
1777 }
1778
1779 return nullptr;
1780 }
1781
1782 #endif // ACCESSIBILITY
1783
StartAsyncScrollbarDrag(const AsyncDragMetrics & aDragMetrics)1784 void nsBaseWidget::StartAsyncScrollbarDrag(
1785 const AsyncDragMetrics& aDragMetrics) {
1786 if (!AsyncPanZoomEnabled()) {
1787 return;
1788 }
1789
1790 MOZ_ASSERT(XRE_IsParentProcess() && mCompositorSession);
1791
1792 LayersId layersId = mCompositorSession->RootLayerTreeId();
1793 ScrollableLayerGuid guid(layersId, aDragMetrics.mPresShellId,
1794 aDragMetrics.mViewId);
1795
1796 mAPZC->StartScrollbarDrag(guid, aDragMetrics);
1797 }
1798
StartAsyncAutoscroll(const ScreenPoint & aAnchorLocation,const ScrollableLayerGuid & aGuid)1799 bool nsBaseWidget::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
1800 const ScrollableLayerGuid& aGuid) {
1801 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1802
1803 return mAPZC->StartAutoscroll(aGuid, aAnchorLocation);
1804 }
1805
StopAsyncAutoscroll(const ScrollableLayerGuid & aGuid)1806 void nsBaseWidget::StopAsyncAutoscroll(const ScrollableLayerGuid& aGuid) {
1807 MOZ_ASSERT(XRE_IsParentProcess() && AsyncPanZoomEnabled());
1808
1809 mAPZC->StopAutoscroll(aGuid);
1810 }
1811
GetRootLayerTreeId()1812 LayersId nsBaseWidget::GetRootLayerTreeId() {
1813 return mCompositorSession ? mCompositorSession->RootLayerTreeId()
1814 : LayersId{0};
1815 }
1816
GetWidgetScreen()1817 already_AddRefed<nsIScreen> nsBaseWidget::GetWidgetScreen() {
1818 nsCOMPtr<nsIScreenManager> screenManager;
1819 screenManager = do_GetService("@mozilla.org/gfx/screenmanager;1");
1820 if (!screenManager) {
1821 return nullptr;
1822 }
1823
1824 LayoutDeviceIntRect bounds = GetScreenBounds();
1825 DesktopIntRect deskBounds = RoundedToInt(bounds / GetDesktopToDeviceScale());
1826 nsCOMPtr<nsIScreen> screen;
1827 screenManager->ScreenForRect(deskBounds.X(), deskBounds.Y(),
1828 deskBounds.Width(), deskBounds.Height(),
1829 getter_AddRefs(screen));
1830 return screen.forget();
1831 }
1832
1833 mozilla::DesktopToLayoutDeviceScale
GetDesktopToDeviceScaleByScreen()1834 nsBaseWidget::GetDesktopToDeviceScaleByScreen() {
1835 return (nsView::GetViewFor(this)->GetViewManager()->GetDeviceContext())
1836 ->GetDesktopToDeviceScale();
1837 }
1838
SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint,bool aLongTap,nsIObserver * aObserver)1839 nsresult nsIWidget::SynthesizeNativeTouchTap(LayoutDeviceIntPoint aPoint,
1840 bool aLongTap,
1841 nsIObserver* aObserver) {
1842 AutoObserverNotifier notifier(aObserver, "touchtap");
1843
1844 if (sPointerIdCounter > TOUCH_INJECT_MAX_POINTS) {
1845 sPointerIdCounter = 0;
1846 }
1847 int pointerId = sPointerIdCounter;
1848 sPointerIdCounter++;
1849 nsresult rv = SynthesizeNativeTouchPoint(pointerId, TOUCH_CONTACT, aPoint,
1850 1.0, 90, nullptr);
1851 if (NS_FAILED(rv)) {
1852 return rv;
1853 }
1854
1855 if (!aLongTap) {
1856 return SynthesizeNativeTouchPoint(pointerId, TOUCH_REMOVE, aPoint, 0, 0,
1857 nullptr);
1858 }
1859
1860 // initiate a long tap
1861 int elapse = Preferences::GetInt("ui.click_hold_context_menus.delay",
1862 TOUCH_INJECT_LONG_TAP_DEFAULT_MSEC);
1863 if (!mLongTapTimer) {
1864 mLongTapTimer = NS_NewTimer();
1865 if (!mLongTapTimer) {
1866 SynthesizeNativeTouchPoint(pointerId, TOUCH_CANCEL, aPoint, 0, 0,
1867 nullptr);
1868 return NS_ERROR_UNEXPECTED;
1869 }
1870 // Windows requires recuring events, so we set this to a smaller window
1871 // than the pref value.
1872 int timeout = elapse;
1873 if (timeout > TOUCH_INJECT_PUMP_TIMER_MSEC) {
1874 timeout = TOUCH_INJECT_PUMP_TIMER_MSEC;
1875 }
1876 mLongTapTimer->InitWithNamedFuncCallback(
1877 OnLongTapTimerCallback, this, timeout, nsITimer::TYPE_REPEATING_SLACK,
1878 "nsIWidget::SynthesizeNativeTouchTap");
1879 }
1880
1881 // If we already have a long tap pending, cancel it. We only allow one long
1882 // tap to be active at a time.
1883 if (mLongTapTouchPoint) {
1884 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1885 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1886 }
1887
1888 mLongTapTouchPoint = MakeUnique<LongTapInfo>(
1889 pointerId, aPoint, TimeDuration::FromMilliseconds(elapse), aObserver);
1890 notifier.SkipNotification(); // we'll do it in the long-tap callback
1891 return NS_OK;
1892 }
1893
1894 // static
OnLongTapTimerCallback(nsITimer * aTimer,void * aClosure)1895 void nsIWidget::OnLongTapTimerCallback(nsITimer* aTimer, void* aClosure) {
1896 auto* self = static_cast<nsIWidget*>(aClosure);
1897
1898 if ((self->mLongTapTouchPoint->mStamp + self->mLongTapTouchPoint->mDuration) >
1899 TimeStamp::Now()) {
1900 #ifdef XP_WIN
1901 // Windows needs us to keep pumping feedback to the digitizer, so update
1902 // the pointer id with the same position.
1903 self->SynthesizeNativeTouchPoint(
1904 self->mLongTapTouchPoint->mPointerId, TOUCH_CONTACT,
1905 self->mLongTapTouchPoint->mPosition, 1.0, 90, nullptr);
1906 #endif
1907 return;
1908 }
1909
1910 AutoObserverNotifier notifier(self->mLongTapTouchPoint->mObserver,
1911 "touchtap");
1912
1913 // finished, remove the touch point
1914 self->mLongTapTimer->Cancel();
1915 self->mLongTapTimer = nullptr;
1916 self->SynthesizeNativeTouchPoint(
1917 self->mLongTapTouchPoint->mPointerId, TOUCH_REMOVE,
1918 self->mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1919 self->mLongTapTouchPoint = nullptr;
1920 }
1921
ClearNativeTouchSequence(nsIObserver * aObserver)1922 nsresult nsIWidget::ClearNativeTouchSequence(nsIObserver* aObserver) {
1923 AutoObserverNotifier notifier(aObserver, "cleartouch");
1924
1925 if (!mLongTapTimer) {
1926 return NS_OK;
1927 }
1928 mLongTapTimer->Cancel();
1929 mLongTapTimer = nullptr;
1930 SynthesizeNativeTouchPoint(mLongTapTouchPoint->mPointerId, TOUCH_CANCEL,
1931 mLongTapTouchPoint->mPosition, 0, 0, nullptr);
1932 mLongTapTouchPoint = nullptr;
1933 return NS_OK;
1934 }
1935
UpdateSynthesizedTouchState(MultiTouchInput * aState,uint32_t aTime,mozilla::TimeStamp aTimeStamp,uint32_t aPointerId,TouchPointerState aPointerState,LayoutDeviceIntPoint aPoint,double aPointerPressure,uint32_t aPointerOrientation)1936 MultiTouchInput nsBaseWidget::UpdateSynthesizedTouchState(
1937 MultiTouchInput* aState, uint32_t aTime, mozilla::TimeStamp aTimeStamp,
1938 uint32_t aPointerId, TouchPointerState aPointerState,
1939 LayoutDeviceIntPoint aPoint, double aPointerPressure,
1940 uint32_t aPointerOrientation) {
1941 ScreenIntPoint pointerScreenPoint = ViewAs<ScreenPixel>(
1942 aPoint, PixelCastJustification::LayoutDeviceIsScreenForBounds);
1943
1944 // We can't dispatch *aState directly because (a) dispatching
1945 // it might inadvertently modify it and (b) in the case of touchend or
1946 // touchcancel events aState will hold the touches that are
1947 // still down whereas the input dispatched needs to hold the removed
1948 // touch(es). We use |inputToDispatch| for this purpose.
1949 MultiTouchInput inputToDispatch;
1950 inputToDispatch.mInputType = MULTITOUCH_INPUT;
1951 inputToDispatch.mTime = aTime;
1952 inputToDispatch.mTimeStamp = aTimeStamp;
1953
1954 int32_t index = aState->IndexOfTouch((int32_t)aPointerId);
1955 if (aPointerState == TOUCH_CONTACT) {
1956 if (index >= 0) {
1957 // found an existing touch point, update it
1958 SingleTouchData& point = aState->mTouches[index];
1959 point.mScreenPoint = pointerScreenPoint;
1960 point.mRotationAngle = (float)aPointerOrientation;
1961 point.mForce = (float)aPointerPressure;
1962 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_MOVE;
1963 } else {
1964 // new touch point, add it
1965 aState->mTouches.AppendElement(SingleTouchData(
1966 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
1967 (float)aPointerOrientation, (float)aPointerPressure));
1968 inputToDispatch.mType = MultiTouchInput::MULTITOUCH_START;
1969 }
1970 inputToDispatch.mTouches = aState->mTouches;
1971 } else {
1972 MOZ_ASSERT(aPointerState == TOUCH_REMOVE || aPointerState == TOUCH_CANCEL);
1973 // a touch point is being lifted, so remove it from the stored list
1974 if (index >= 0) {
1975 aState->mTouches.RemoveElementAt(index);
1976 }
1977 inputToDispatch.mType =
1978 (aPointerState == TOUCH_REMOVE ? MultiTouchInput::MULTITOUCH_END
1979 : MultiTouchInput::MULTITOUCH_CANCEL);
1980 inputToDispatch.mTouches.AppendElement(SingleTouchData(
1981 (int32_t)aPointerId, pointerScreenPoint, ScreenSize(0, 0),
1982 (float)aPointerOrientation, (float)aPointerPressure));
1983 }
1984
1985 return inputToDispatch;
1986 }
1987
NotifyLiveResizeStarted()1988 void nsBaseWidget::NotifyLiveResizeStarted() {
1989 // If we have mLiveResizeListeners already non-empty, we should notify those
1990 // listeners that the resize stopped before starting anew. In theory this
1991 // should never happen because we shouldn't get nested live resize actions.
1992 NotifyLiveResizeStopped();
1993 MOZ_ASSERT(mLiveResizeListeners.IsEmpty());
1994
1995 // If we can get the active remote tab for the current widget, suppress
1996 // the displayport on it during the live resize.
1997 if (!mWidgetListener) {
1998 return;
1999 }
2000 nsCOMPtr<nsIAppWindow> appWindow = mWidgetListener->GetAppWindow();
2001 if (!appWindow) {
2002 return;
2003 }
2004 mLiveResizeListeners = appWindow->GetLiveResizeListeners();
2005 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2006 mLiveResizeListeners[i]->LiveResizeStarted();
2007 }
2008 }
2009
NotifyLiveResizeStopped()2010 void nsBaseWidget::NotifyLiveResizeStopped() {
2011 if (!mLiveResizeListeners.IsEmpty()) {
2012 for (uint32_t i = 0; i < mLiveResizeListeners.Length(); i++) {
2013 mLiveResizeListeners[i]->LiveResizeStopped();
2014 }
2015 mLiveResizeListeners.Clear();
2016 }
2017 }
2018
AsyncEnableDragDrop(bool aEnable)2019 nsresult nsBaseWidget::AsyncEnableDragDrop(bool aEnable) {
2020 RefPtr<nsBaseWidget> kungFuDeathGrip = this;
2021 return NS_DispatchToCurrentThreadQueue(
2022 NS_NewRunnableFunction(
2023 "AsyncEnableDragDropFn",
2024 [this, aEnable, kungFuDeathGrip]() { EnableDragDrop(aEnable); }),
2025 kAsyncDragDropTimeout, EventQueuePriority::Idle);
2026 }
2027
SwipeFinished()2028 void nsBaseWidget::SwipeFinished() { mSwipeTracker = nullptr; }
2029
ReportSwipeStarted(uint64_t aInputBlockId,bool aStartSwipe)2030 void nsBaseWidget::ReportSwipeStarted(uint64_t aInputBlockId,
2031 bool aStartSwipe) {
2032 if (mSwipeEventQueue && mSwipeEventQueue->inputBlockId == aInputBlockId) {
2033 if (aStartSwipe) {
2034 PanGestureInput& startEvent = mSwipeEventQueue->queuedEvents[0];
2035 TrackScrollEventAsSwipe(startEvent, mSwipeEventQueue->allowedDirections);
2036 for (size_t i = 1; i < mSwipeEventQueue->queuedEvents.Length(); i++) {
2037 mSwipeTracker->ProcessEvent(mSwipeEventQueue->queuedEvents[i]);
2038 }
2039 }
2040 mSwipeEventQueue = nullptr;
2041 }
2042 }
2043
TrackScrollEventAsSwipe(const mozilla::PanGestureInput & aSwipeStartEvent,uint32_t aAllowedDirections)2044 void nsBaseWidget::TrackScrollEventAsSwipe(
2045 const mozilla::PanGestureInput& aSwipeStartEvent,
2046 uint32_t aAllowedDirections) {
2047 // If a swipe is currently being tracked kill it -- it's been interrupted
2048 // by another gesture event.
2049 if (mSwipeTracker) {
2050 mSwipeTracker->CancelSwipe(aSwipeStartEvent.mTimeStamp);
2051 mSwipeTracker->Destroy();
2052 mSwipeTracker = nullptr;
2053 }
2054
2055 uint32_t direction =
2056 (aSwipeStartEvent.mPanDisplacement.x > 0.0)
2057 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2058 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT;
2059
2060 mSwipeTracker =
2061 new SwipeTracker(*this, aSwipeStartEvent, aAllowedDirections, direction);
2062
2063 if (!mAPZC) {
2064 mCurrentPanGestureBelongsToSwipe = true;
2065 }
2066 }
2067
SendMayStartSwipe(const mozilla::PanGestureInput & aSwipeStartEvent)2068 nsBaseWidget::SwipeInfo nsBaseWidget::SendMayStartSwipe(
2069 const mozilla::PanGestureInput& aSwipeStartEvent) {
2070 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
2071
2072 uint32_t direction =
2073 (aSwipeStartEvent.mPanDisplacement.x > 0.0)
2074 ? (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_RIGHT
2075 : (uint32_t)dom::SimpleGestureEvent_Binding::DIRECTION_LEFT;
2076
2077 // We're ready to start the animation. Tell Gecko about it, and at the same
2078 // time ask it if it really wants to start an animation for this event.
2079 // This event also reports back the directions that we can swipe in.
2080 LayoutDeviceIntPoint position = RoundedToInt(aSwipeStartEvent.mPanStartPoint *
2081 ScreenToLayoutDeviceScale(1));
2082 WidgetSimpleGestureEvent geckoEvent = SwipeTracker::CreateSwipeGestureEvent(
2083 eSwipeGestureMayStart, this, position, aSwipeStartEvent.mTimeStamp);
2084 geckoEvent.mDirection = direction;
2085 geckoEvent.mDelta = 0.0;
2086 geckoEvent.mAllowedDirections = 0;
2087 bool shouldStartSwipe =
2088 DispatchWindowEvent(geckoEvent); // event cancelled == swipe should start
2089
2090 SwipeInfo result = {shouldStartSwipe, geckoEvent.mAllowedDirections};
2091 return result;
2092 }
2093
MayStartSwipeForAPZ(const PanGestureInput & aPanInput,const APZEventResult & aApzResult,CanTriggerSwipe aCanTriggerSwipe)2094 WidgetWheelEvent nsBaseWidget::MayStartSwipeForAPZ(
2095 const PanGestureInput& aPanInput, const APZEventResult& aApzResult,
2096 CanTriggerSwipe aCanTriggerSwipe) {
2097 WidgetWheelEvent event = aPanInput.ToWidgetEvent(this);
2098 if (aCanTriggerSwipe == CanTriggerSwipe::Yes &&
2099 aPanInput.mOverscrollBehaviorAllowsSwipe) {
2100 SwipeInfo swipeInfo = SendMayStartSwipe(aPanInput);
2101 event.mCanTriggerSwipe = swipeInfo.wantsSwipe;
2102 if (swipeInfo.wantsSwipe) {
2103 if (aApzResult.GetStatus() == nsEventStatus_eIgnore) {
2104 // APZ has determined and that scrolling horizontally in the
2105 // requested direction is impossible, so it didn't do any
2106 // scrolling for the event.
2107 // We know now that MayStartSwipe wants a swipe, so we can start
2108 // the swipe now.
2109 TrackScrollEventAsSwipe(aPanInput, swipeInfo.allowedDirections);
2110 } else {
2111 // We don't know whether this event can start a swipe, so we need
2112 // to queue up events and wait for a call to ReportSwipeStarted.
2113 // APZ might already have started scrolling in response to the
2114 // event if it knew that it's the right thing to do. In that case
2115 // we'll still get a call to ReportSwipeStarted, and we will
2116 // discard the queued events at that point.
2117 mSwipeEventQueue = MakeUnique<SwipeEventQueue>(
2118 swipeInfo.allowedDirections, aApzResult.mInputBlockId);
2119 }
2120 }
2121 }
2122
2123 if (mSwipeEventQueue &&
2124 mSwipeEventQueue->inputBlockId == aApzResult.mInputBlockId) {
2125 mSwipeEventQueue->queuedEvents.AppendElement(aPanInput);
2126 }
2127
2128 return event;
2129 }
2130
MayStartSwipeForNonAPZ(const PanGestureInput & aPanInput,CanTriggerSwipe aCanTriggerSwipe)2131 bool nsBaseWidget::MayStartSwipeForNonAPZ(const PanGestureInput& aPanInput,
2132 CanTriggerSwipe aCanTriggerSwipe) {
2133 if (aPanInput.mType == PanGestureInput::PANGESTURE_MAYSTART ||
2134 aPanInput.mType == PanGestureInput::PANGESTURE_START) {
2135 mCurrentPanGestureBelongsToSwipe = false;
2136 }
2137 if (mCurrentPanGestureBelongsToSwipe) {
2138 // Ignore this event. It's a momentum event from a scroll gesture
2139 // that was processed as a swipe, and the swipe animation has
2140 // already finished (so mSwipeTracker is already null).
2141 MOZ_ASSERT(aPanInput.IsMomentum(),
2142 "If the fingers are still on the touchpad, we should still have "
2143 "a SwipeTracker, "
2144 "and it should have consumed this event.");
2145 return true;
2146 }
2147
2148 if (aCanTriggerSwipe == CanTriggerSwipe::No) {
2149 return false;
2150 }
2151
2152 SwipeInfo swipeInfo = SendMayStartSwipe(aPanInput);
2153
2154 // We're in the non-APZ case here, but we still want to know whether
2155 // the event was routed to a child process, so we use InputAPZContext
2156 // to get that piece of information.
2157 ScrollableLayerGuid guid;
2158 InputAPZContext context(guid, 0, nsEventStatus_eIgnore);
2159
2160 WidgetWheelEvent event = aPanInput.ToWidgetEvent(this);
2161 event.mCanTriggerSwipe = swipeInfo.wantsSwipe;
2162 nsEventStatus status;
2163 DispatchEvent(&event, status);
2164 if (swipeInfo.wantsSwipe) {
2165 if (context.WasRoutedToChildProcess()) {
2166 // We don't know whether this event can start a swipe, so we need
2167 // to queue up events and wait for a call to ReportSwipeStarted.
2168 mSwipeEventQueue =
2169 MakeUnique<SwipeEventQueue>(swipeInfo.allowedDirections, 0);
2170 } else if (event.TriggersSwipe()) {
2171 TrackScrollEventAsSwipe(aPanInput, swipeInfo.allowedDirections);
2172 }
2173 }
2174
2175 if (mSwipeEventQueue && mSwipeEventQueue->inputBlockId == 0) {
2176 mSwipeEventQueue->queuedEvents.AppendElement(aPanInput);
2177 }
2178
2179 return true;
2180 }
2181
IMENotificationRequestsRef()2182 const IMENotificationRequests& nsIWidget::IMENotificationRequestsRef() {
2183 TextEventDispatcher* dispatcher = GetTextEventDispatcher();
2184 return dispatcher->IMENotificationRequestsRef();
2185 }
2186
PostHandleKeyEvent(mozilla::WidgetKeyboardEvent * aEvent)2187 void nsIWidget::PostHandleKeyEvent(mozilla::WidgetKeyboardEvent* aEvent) {}
2188
GetEditCommands(NativeKeyBindingsType aType,const WidgetKeyboardEvent & aEvent,nsTArray<CommandInt> & aCommands)2189 bool nsIWidget::GetEditCommands(NativeKeyBindingsType aType,
2190 const WidgetKeyboardEvent& aEvent,
2191 nsTArray<CommandInt>& aCommands) {
2192 MOZ_ASSERT(aEvent.IsTrusted());
2193 MOZ_ASSERT(aCommands.IsEmpty());
2194 return true;
2195 }
2196
CreateBidiKeyboard()2197 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboard() {
2198 if (XRE_IsContentProcess()) {
2199 return CreateBidiKeyboardContentProcess();
2200 }
2201 return CreateBidiKeyboardInner();
2202 }
2203
2204 #ifdef ANDROID
CreateBidiKeyboardInner()2205 already_AddRefed<nsIBidiKeyboard> nsIWidget::CreateBidiKeyboardInner() {
2206 // no bidi keyboard implementation
2207 return nullptr;
2208 }
2209 #endif
2210
2211 namespace mozilla::widget {
2212
ToChar(InputContext::Origin aOrigin)2213 const char* ToChar(InputContext::Origin aOrigin) {
2214 switch (aOrigin) {
2215 case InputContext::ORIGIN_MAIN:
2216 return "ORIGIN_MAIN";
2217 case InputContext::ORIGIN_CONTENT:
2218 return "ORIGIN_CONTENT";
2219 default:
2220 return "Unexpected value";
2221 }
2222 }
2223
ToChar(IMEMessage aIMEMessage)2224 const char* ToChar(IMEMessage aIMEMessage) {
2225 switch (aIMEMessage) {
2226 case NOTIFY_IME_OF_NOTHING:
2227 return "NOTIFY_IME_OF_NOTHING";
2228 case NOTIFY_IME_OF_FOCUS:
2229 return "NOTIFY_IME_OF_FOCUS";
2230 case NOTIFY_IME_OF_BLUR:
2231 return "NOTIFY_IME_OF_BLUR";
2232 case NOTIFY_IME_OF_SELECTION_CHANGE:
2233 return "NOTIFY_IME_OF_SELECTION_CHANGE";
2234 case NOTIFY_IME_OF_TEXT_CHANGE:
2235 return "NOTIFY_IME_OF_TEXT_CHANGE";
2236 case NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED:
2237 return "NOTIFY_IME_OF_COMPOSITION_EVENT_HANDLED";
2238 case NOTIFY_IME_OF_POSITION_CHANGE:
2239 return "NOTIFY_IME_OF_POSITION_CHANGE";
2240 case NOTIFY_IME_OF_MOUSE_BUTTON_EVENT:
2241 return "NOTIFY_IME_OF_MOUSE_BUTTON_EVENT";
2242 case REQUEST_TO_COMMIT_COMPOSITION:
2243 return "REQUEST_TO_COMMIT_COMPOSITION";
2244 case REQUEST_TO_CANCEL_COMPOSITION:
2245 return "REQUEST_TO_CANCEL_COMPOSITION";
2246 default:
2247 return "Unexpected value";
2248 }
2249 }
2250
Init(nsIWidget * aWidget)2251 void NativeIMEContext::Init(nsIWidget* aWidget) {
2252 if (!aWidget) {
2253 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2254 mOriginProcessID = static_cast<uint64_t>(-1);
2255 return;
2256 }
2257 if (!XRE_IsContentProcess()) {
2258 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(
2259 aWidget->GetNativeData(NS_RAW_NATIVE_IME_CONTEXT));
2260 mOriginProcessID = 0;
2261 return;
2262 }
2263 // If this is created in a child process, aWidget is an instance of
2264 // PuppetWidget which doesn't support NS_RAW_NATIVE_IME_CONTEXT.
2265 // Instead of that PuppetWidget::GetNativeIMEContext() returns cached
2266 // native IME context of the parent process.
2267 *this = aWidget->GetNativeIMEContext();
2268 }
2269
InitWithRawNativeIMEContext(void * aRawNativeIMEContext)2270 void NativeIMEContext::InitWithRawNativeIMEContext(void* aRawNativeIMEContext) {
2271 if (NS_WARN_IF(!aRawNativeIMEContext)) {
2272 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(nullptr);
2273 mOriginProcessID = static_cast<uint64_t>(-1);
2274 return;
2275 }
2276 mRawNativeIMEContext = reinterpret_cast<uintptr_t>(aRawNativeIMEContext);
2277 mOriginProcessID =
2278 XRE_IsContentProcess() ? ContentChild::GetSingleton()->GetID() : 0;
2279 }
2280
MergeWith(const IMENotification::TextChangeDataBase & aOther)2281 void IMENotification::TextChangeDataBase::MergeWith(
2282 const IMENotification::TextChangeDataBase& aOther) {
2283 MOZ_ASSERT(aOther.IsValid(), "Merging data must store valid data");
2284 MOZ_ASSERT(aOther.mStartOffset <= aOther.mRemovedEndOffset,
2285 "end of removed text must be same or larger than start");
2286 MOZ_ASSERT(aOther.mStartOffset <= aOther.mAddedEndOffset,
2287 "end of added text must be same or larger than start");
2288
2289 if (!IsValid()) {
2290 *this = aOther;
2291 return;
2292 }
2293
2294 // |mStartOffset| and |mRemovedEndOffset| represent all replaced or removed
2295 // text ranges. I.e., mStartOffset should be the smallest offset of all
2296 // modified text ranges in old text. |mRemovedEndOffset| should be the
2297 // largest end offset in old text of all modified text ranges.
2298 // |mAddedEndOffset| represents the end offset of all inserted text ranges.
2299 // I.e., only this is an offset in new text.
2300 // In other words, between mStartOffset and |mRemovedEndOffset| of the
2301 // premodified text was already removed. And some text whose length is
2302 // |mAddedEndOffset - mStartOffset| is inserted to |mStartOffset|. I.e.,
2303 // this allows IME to mark dirty the modified text range with |mStartOffset|
2304 // and |mRemovedEndOffset| if IME stores all text of the focused editor and
2305 // to compute new text length with |mAddedEndOffset| and |mRemovedEndOffset|.
2306 // Additionally, IME can retrieve only the text between |mStartOffset| and
2307 // |mAddedEndOffset| for updating stored text.
2308
2309 // For comparing new and old |mStartOffset|/|mRemovedEndOffset| values, they
2310 // should be adjusted to be in same text. The |newData.mStartOffset| and
2311 // |newData.mRemovedEndOffset| should be computed as in old text because
2312 // |mStartOffset| and |mRemovedEndOffset| represent the modified text range
2313 // in the old text but even if some text before the values of the newData
2314 // has already been modified, the values don't include the changes.
2315
2316 // For comparing new and old |mAddedEndOffset| values, they should be
2317 // adjusted to be in same text. The |oldData.mAddedEndOffset| should be
2318 // computed as in the new text because |mAddedEndOffset| indicates the end
2319 // offset of inserted text in the new text but |oldData.mAddedEndOffset|
2320 // doesn't include any changes of the text before |newData.mAddedEndOffset|.
2321
2322 const TextChangeDataBase& newData = aOther;
2323 const TextChangeDataBase oldData = *this;
2324
2325 // mCausedOnlyByComposition should be true only when all changes are caused
2326 // by composition.
2327 mCausedOnlyByComposition =
2328 newData.mCausedOnlyByComposition && oldData.mCausedOnlyByComposition;
2329
2330 // mIncludingChangesWithoutComposition should be true if at least one of
2331 // merged changes occurred without composition.
2332 mIncludingChangesWithoutComposition =
2333 newData.mIncludingChangesWithoutComposition ||
2334 oldData.mIncludingChangesWithoutComposition;
2335
2336 // mIncludingChangesDuringComposition should be true when at least one of
2337 // the merged non-composition changes occurred during the latest composition.
2338 if (!newData.mCausedOnlyByComposition &&
2339 !newData.mIncludingChangesDuringComposition) {
2340 MOZ_ASSERT(newData.mIncludingChangesWithoutComposition);
2341 MOZ_ASSERT(mIncludingChangesWithoutComposition);
2342 // If new change is neither caused by composition nor occurred during
2343 // composition, set mIncludingChangesDuringComposition to false because
2344 // IME doesn't want outdated text changes as text change during current
2345 // composition.
2346 mIncludingChangesDuringComposition = false;
2347 } else {
2348 // Otherwise, set mIncludingChangesDuringComposition to true if either
2349 // oldData or newData includes changes during composition.
2350 mIncludingChangesDuringComposition =
2351 newData.mIncludingChangesDuringComposition ||
2352 oldData.mIncludingChangesDuringComposition;
2353 }
2354
2355 if (newData.mStartOffset >= oldData.mAddedEndOffset) {
2356 // Case 1:
2357 // If new start is after old end offset of added text, it means that text
2358 // after the modified range is modified. Like:
2359 // added range of old change: +----------+
2360 // removed range of new change: +----------+
2361 // So, the old start offset is always the smaller offset.
2362 mStartOffset = oldData.mStartOffset;
2363 // The new end offset of removed text is moved by the old change and we
2364 // need to cancel the move of the old change for comparing the offsets in
2365 // same text because it doesn't make sensce to compare offsets in different
2366 // text.
2367 uint32_t newRemovedEndOffsetInOldText =
2368 newData.mRemovedEndOffset - oldData.Difference();
2369 mRemovedEndOffset =
2370 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2371 // The new end offset of added text is always the larger offset.
2372 mAddedEndOffset = newData.mAddedEndOffset;
2373 return;
2374 }
2375
2376 if (newData.mStartOffset >= oldData.mStartOffset) {
2377 // If new start is in the modified range, it means that new data changes
2378 // a part or all of the range.
2379 mStartOffset = oldData.mStartOffset;
2380 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2381 // Case 2:
2382 // If new end of removed text is greater than old end of added text, it
2383 // means that all or a part of modified range modified again and text
2384 // after the modified range is also modified. Like:
2385 // added range of old change: +----------+
2386 // removed range of new change: +----------+
2387 // So, the new removed end offset is moved by the old change and we need
2388 // to cancel the move of the old change for comparing the offsets in the
2389 // same text because it doesn't make sense to compare the offsets in
2390 // different text.
2391 uint32_t newRemovedEndOffsetInOldText =
2392 newData.mRemovedEndOffset - oldData.Difference();
2393 mRemovedEndOffset =
2394 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2395 // The old end of added text is replaced by new change. So, it should be
2396 // same as the new start. On the other hand, the new added end offset is
2397 // always same or larger. Therefore, the merged end offset of added
2398 // text should be the new end offset of added text.
2399 mAddedEndOffset = newData.mAddedEndOffset;
2400 return;
2401 }
2402
2403 // Case 3:
2404 // If new end of removed text is less than old end of added text, it means
2405 // that only a part of the modified range is modified again. Like:
2406 // added range of old change: +------------+
2407 // removed range of new change: +-----+
2408 // So, the new end offset of removed text should be same as the old end
2409 // offset of removed text. Therefore, the merged end offset of removed
2410 // text should be the old text change's |mRemovedEndOffset|.
2411 mRemovedEndOffset = oldData.mRemovedEndOffset;
2412 // The old end of added text is moved by new change. So, we need to cancel
2413 // the move of the new change for comparing the offsets in same text.
2414 uint32_t oldAddedEndOffsetInNewText =
2415 oldData.mAddedEndOffset + newData.Difference();
2416 mAddedEndOffset =
2417 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2418 return;
2419 }
2420
2421 if (newData.mRemovedEndOffset >= oldData.mStartOffset) {
2422 // If new end of removed text is greater than old start (and new start is
2423 // less than old start), it means that a part of modified range is modified
2424 // again and some new text before the modified range is also modified.
2425 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2426 "new start offset should be less than old one here");
2427 mStartOffset = newData.mStartOffset;
2428 if (newData.mRemovedEndOffset >= oldData.mAddedEndOffset) {
2429 // Case 4:
2430 // If new end of removed text is greater than old end of added text, it
2431 // means that all modified text and text after the modified range is
2432 // modified. Like:
2433 // added range of old change: +----------+
2434 // removed range of new change: +------------------+
2435 // So, the new end of removed text is moved by the old change. Therefore,
2436 // we need to cancel the move of the old change for comparing the offsets
2437 // in same text because it doesn't make sense to compare the offsets in
2438 // different text.
2439 uint32_t newRemovedEndOffsetInOldText =
2440 newData.mRemovedEndOffset - oldData.Difference();
2441 mRemovedEndOffset =
2442 std::max(newRemovedEndOffsetInOldText, oldData.mRemovedEndOffset);
2443 // The old end of added text is replaced by new change. So, the old end
2444 // offset of added text is same as new text change's start offset. Then,
2445 // new change's end offset of added text is always same or larger than
2446 // it. Therefore, merged end offset of added text is always the new end
2447 // offset of added text.
2448 mAddedEndOffset = newData.mAddedEndOffset;
2449 return;
2450 }
2451
2452 // Case 5:
2453 // If new end of removed text is less than old end of added text, it
2454 // means that only a part of the modified range is modified again. Like:
2455 // added range of old change: +----------+
2456 // removed range of new change: +----------+
2457 // So, the new end of removed text should be same as old end of removed
2458 // text for preventing end of removed text to be modified. Therefore,
2459 // merged end offset of removed text is always the old end offset of removed
2460 // text.
2461 mRemovedEndOffset = oldData.mRemovedEndOffset;
2462 // The old end of added text is moved by this change. So, we need to
2463 // cancel the move of the new change for comparing the offsets in same text
2464 // because it doesn't make sense to compare the offsets in different text.
2465 uint32_t oldAddedEndOffsetInNewText =
2466 oldData.mAddedEndOffset + newData.Difference();
2467 mAddedEndOffset =
2468 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2469 return;
2470 }
2471
2472 // Case 6:
2473 // Otherwise, i.e., both new end of added text and new start are less than
2474 // old start, text before the modified range is modified. Like:
2475 // added range of old change: +----------+
2476 // removed range of new change: +----------+
2477 MOZ_ASSERT(newData.mStartOffset < oldData.mStartOffset,
2478 "new start offset should be less than old one here");
2479 mStartOffset = newData.mStartOffset;
2480 MOZ_ASSERT(newData.mRemovedEndOffset < oldData.mRemovedEndOffset,
2481 "new removed end offset should be less than old one here");
2482 mRemovedEndOffset = oldData.mRemovedEndOffset;
2483 // The end of added text should be adjusted with the new difference.
2484 uint32_t oldAddedEndOffsetInNewText =
2485 oldData.mAddedEndOffset + newData.Difference();
2486 mAddedEndOffset =
2487 std::max(newData.mAddedEndOffset, oldAddedEndOffsetInNewText);
2488 }
2489
2490 #ifdef DEBUG
2491
2492 // Let's test the code of merging multiple text change data in debug build
2493 // and crash if one of them fails because this feature is very complex but
2494 // cannot be tested with mochitest.
Test()2495 void IMENotification::TextChangeDataBase::Test() {
2496 static bool gTestTextChangeEvent = true;
2497 if (!gTestTextChangeEvent) {
2498 return;
2499 }
2500 gTestTextChangeEvent = false;
2501
2502 /****************************************************************************
2503 * Case 1
2504 ****************************************************************************/
2505
2506 // Appending text
2507 MergeWith(TextChangeData(10, 10, 20, false, false));
2508 MergeWith(TextChangeData(20, 20, 35, false, false));
2509 MOZ_ASSERT(mStartOffset == 10,
2510 "Test 1-1-1: mStartOffset should be the first offset");
2511 MOZ_ASSERT(
2512 mRemovedEndOffset == 10, // 20 - (20 - 10)
2513 "Test 1-1-2: mRemovedEndOffset should be the first end of removed text");
2514 MOZ_ASSERT(
2515 mAddedEndOffset == 35,
2516 "Test 1-1-3: mAddedEndOffset should be the last end of added text");
2517 Clear();
2518
2519 // Removing text (longer line -> shorter line)
2520 MergeWith(TextChangeData(10, 20, 10, false, false));
2521 MergeWith(TextChangeData(10, 30, 10, false, false));
2522 MOZ_ASSERT(mStartOffset == 10,
2523 "Test 1-2-1: mStartOffset should be the first offset");
2524 MOZ_ASSERT(mRemovedEndOffset == 40, // 30 + (10 - 20)
2525 "Test 1-2-2: mRemovedEndOffset should be the the last end of "
2526 "removed text "
2527 "with already removed length");
2528 MOZ_ASSERT(
2529 mAddedEndOffset == 10,
2530 "Test 1-2-3: mAddedEndOffset should be the last end of added text");
2531 Clear();
2532
2533 // Removing text (shorter line -> longer line)
2534 MergeWith(TextChangeData(10, 20, 10, false, false));
2535 MergeWith(TextChangeData(10, 15, 10, false, false));
2536 MOZ_ASSERT(mStartOffset == 10,
2537 "Test 1-3-1: mStartOffset should be the first offset");
2538 MOZ_ASSERT(mRemovedEndOffset == 25, // 15 + (10 - 20)
2539 "Test 1-3-2: mRemovedEndOffset should be the the last end of "
2540 "removed text "
2541 "with already removed length");
2542 MOZ_ASSERT(
2543 mAddedEndOffset == 10,
2544 "Test 1-3-3: mAddedEndOffset should be the last end of added text");
2545 Clear();
2546
2547 // Appending text at different point (not sure if actually occurs)
2548 MergeWith(TextChangeData(10, 10, 20, false, false));
2549 MergeWith(TextChangeData(55, 55, 60, false, false));
2550 MOZ_ASSERT(mStartOffset == 10,
2551 "Test 1-4-1: mStartOffset should be the smallest offset");
2552 MOZ_ASSERT(
2553 mRemovedEndOffset == 45, // 55 - (10 - 20)
2554 "Test 1-4-2: mRemovedEndOffset should be the the largest end of removed "
2555 "text without already added length");
2556 MOZ_ASSERT(
2557 mAddedEndOffset == 60,
2558 "Test 1-4-3: mAddedEndOffset should be the last end of added text");
2559 Clear();
2560
2561 // Removing text at different point (not sure if actually occurs)
2562 MergeWith(TextChangeData(10, 20, 10, false, false));
2563 MergeWith(TextChangeData(55, 68, 55, false, false));
2564 MOZ_ASSERT(mStartOffset == 10,
2565 "Test 1-5-1: mStartOffset should be the smallest offset");
2566 MOZ_ASSERT(
2567 mRemovedEndOffset == 78, // 68 - (10 - 20)
2568 "Test 1-5-2: mRemovedEndOffset should be the the largest end of removed "
2569 "text with already removed length");
2570 MOZ_ASSERT(
2571 mAddedEndOffset == 55,
2572 "Test 1-5-3: mAddedEndOffset should be the largest end of added text");
2573 Clear();
2574
2575 // Replacing text and append text (becomes longer)
2576 MergeWith(TextChangeData(30, 35, 32, false, false));
2577 MergeWith(TextChangeData(32, 32, 40, false, false));
2578 MOZ_ASSERT(mStartOffset == 30,
2579 "Test 1-6-1: mStartOffset should be the smallest offset");
2580 MOZ_ASSERT(
2581 mRemovedEndOffset == 35, // 32 - (32 - 35)
2582 "Test 1-6-2: mRemovedEndOffset should be the the first end of removed "
2583 "text");
2584 MOZ_ASSERT(
2585 mAddedEndOffset == 40,
2586 "Test 1-6-3: mAddedEndOffset should be the last end of added text");
2587 Clear();
2588
2589 // Replacing text and append text (becomes shorter)
2590 MergeWith(TextChangeData(30, 35, 32, false, false));
2591 MergeWith(TextChangeData(32, 32, 33, false, false));
2592 MOZ_ASSERT(mStartOffset == 30,
2593 "Test 1-7-1: mStartOffset should be the smallest offset");
2594 MOZ_ASSERT(
2595 mRemovedEndOffset == 35, // 32 - (32 - 35)
2596 "Test 1-7-2: mRemovedEndOffset should be the the first end of removed "
2597 "text");
2598 MOZ_ASSERT(
2599 mAddedEndOffset == 33,
2600 "Test 1-7-3: mAddedEndOffset should be the last end of added text");
2601 Clear();
2602
2603 // Removing text and replacing text after first range (not sure if actually
2604 // occurs)
2605 MergeWith(TextChangeData(30, 35, 30, false, false));
2606 MergeWith(TextChangeData(32, 34, 48, false, false));
2607 MOZ_ASSERT(mStartOffset == 30,
2608 "Test 1-8-1: mStartOffset should be the smallest offset");
2609 MOZ_ASSERT(mRemovedEndOffset == 39, // 34 - (30 - 35)
2610 "Test 1-8-2: mRemovedEndOffset should be the the first end of "
2611 "removed text "
2612 "without already removed text");
2613 MOZ_ASSERT(
2614 mAddedEndOffset == 48,
2615 "Test 1-8-3: mAddedEndOffset should be the last end of added text");
2616 Clear();
2617
2618 // Removing text and replacing text after first range (not sure if actually
2619 // occurs)
2620 MergeWith(TextChangeData(30, 35, 30, false, false));
2621 MergeWith(TextChangeData(32, 38, 36, false, false));
2622 MOZ_ASSERT(mStartOffset == 30,
2623 "Test 1-9-1: mStartOffset should be the smallest offset");
2624 MOZ_ASSERT(mRemovedEndOffset == 43, // 38 - (30 - 35)
2625 "Test 1-9-2: mRemovedEndOffset should be the the first end of "
2626 "removed text "
2627 "without already removed text");
2628 MOZ_ASSERT(
2629 mAddedEndOffset == 36,
2630 "Test 1-9-3: mAddedEndOffset should be the last end of added text");
2631 Clear();
2632
2633 /****************************************************************************
2634 * Case 2
2635 ****************************************************************************/
2636
2637 // Replacing text in around end of added text (becomes shorter) (not sure
2638 // if actually occurs)
2639 MergeWith(TextChangeData(50, 50, 55, false, false));
2640 MergeWith(TextChangeData(53, 60, 54, false, false));
2641 MOZ_ASSERT(mStartOffset == 50,
2642 "Test 2-1-1: mStartOffset should be the smallest offset");
2643 MOZ_ASSERT(mRemovedEndOffset == 55, // 60 - (55 - 50)
2644 "Test 2-1-2: mRemovedEndOffset should be the the last end of "
2645 "removed text "
2646 "without already added text length");
2647 MOZ_ASSERT(
2648 mAddedEndOffset == 54,
2649 "Test 2-1-3: mAddedEndOffset should be the last end of added text");
2650 Clear();
2651
2652 // Replacing text around end of added text (becomes longer) (not sure
2653 // if actually occurs)
2654 MergeWith(TextChangeData(50, 50, 55, false, false));
2655 MergeWith(TextChangeData(54, 62, 68, false, false));
2656 MOZ_ASSERT(mStartOffset == 50,
2657 "Test 2-2-1: mStartOffset should be the smallest offset");
2658 MOZ_ASSERT(mRemovedEndOffset == 57, // 62 - (55 - 50)
2659 "Test 2-2-2: mRemovedEndOffset should be the the last end of "
2660 "removed text "
2661 "without already added text length");
2662 MOZ_ASSERT(
2663 mAddedEndOffset == 68,
2664 "Test 2-2-3: mAddedEndOffset should be the last end of added text");
2665 Clear();
2666
2667 // Replacing text around end of replaced text (became shorter) (not sure if
2668 // actually occurs)
2669 MergeWith(TextChangeData(36, 48, 45, false, false));
2670 MergeWith(TextChangeData(43, 50, 49, false, false));
2671 MOZ_ASSERT(mStartOffset == 36,
2672 "Test 2-3-1: mStartOffset should be the smallest offset");
2673 MOZ_ASSERT(mRemovedEndOffset == 53, // 50 - (45 - 48)
2674 "Test 2-3-2: mRemovedEndOffset should be the the last end of "
2675 "removed text "
2676 "without already removed text length");
2677 MOZ_ASSERT(
2678 mAddedEndOffset == 49,
2679 "Test 2-3-3: mAddedEndOffset should be the last end of added text");
2680 Clear();
2681
2682 // Replacing text around end of replaced text (became longer) (not sure if
2683 // actually occurs)
2684 MergeWith(TextChangeData(36, 52, 53, false, false));
2685 MergeWith(TextChangeData(43, 68, 61, false, false));
2686 MOZ_ASSERT(mStartOffset == 36,
2687 "Test 2-4-1: mStartOffset should be the smallest offset");
2688 MOZ_ASSERT(mRemovedEndOffset == 67, // 68 - (53 - 52)
2689 "Test 2-4-2: mRemovedEndOffset should be the the last end of "
2690 "removed text "
2691 "without already added text length");
2692 MOZ_ASSERT(
2693 mAddedEndOffset == 61,
2694 "Test 2-4-3: mAddedEndOffset should be the last end of added text");
2695 Clear();
2696
2697 /****************************************************************************
2698 * Case 3
2699 ****************************************************************************/
2700
2701 // Appending text in already added text (not sure if actually occurs)
2702 MergeWith(TextChangeData(10, 10, 20, false, false));
2703 MergeWith(TextChangeData(15, 15, 30, false, false));
2704 MOZ_ASSERT(mStartOffset == 10,
2705 "Test 3-1-1: mStartOffset should be the smallest offset");
2706 MOZ_ASSERT(mRemovedEndOffset == 10,
2707 "Test 3-1-2: mRemovedEndOffset should be the the first end of "
2708 "removed text");
2709 MOZ_ASSERT(
2710 mAddedEndOffset == 35, // 20 + (30 - 15)
2711 "Test 3-1-3: mAddedEndOffset should be the first end of added text with "
2712 "added text length by the new change");
2713 Clear();
2714
2715 // Replacing text in added text (not sure if actually occurs)
2716 MergeWith(TextChangeData(50, 50, 55, false, false));
2717 MergeWith(TextChangeData(52, 53, 56, false, false));
2718 MOZ_ASSERT(mStartOffset == 50,
2719 "Test 3-2-1: mStartOffset should be the smallest offset");
2720 MOZ_ASSERT(mRemovedEndOffset == 50,
2721 "Test 3-2-2: mRemovedEndOffset should be the the first end of "
2722 "removed text");
2723 MOZ_ASSERT(
2724 mAddedEndOffset == 58, // 55 + (56 - 53)
2725 "Test 3-2-3: mAddedEndOffset should be the first end of added text with "
2726 "added text length by the new change");
2727 Clear();
2728
2729 // Replacing text in replaced text (became shorter) (not sure if actually
2730 // occurs)
2731 MergeWith(TextChangeData(36, 48, 45, false, false));
2732 MergeWith(TextChangeData(37, 38, 50, false, false));
2733 MOZ_ASSERT(mStartOffset == 36,
2734 "Test 3-3-1: mStartOffset should be the smallest offset");
2735 MOZ_ASSERT(mRemovedEndOffset == 48,
2736 "Test 3-3-2: mRemovedEndOffset should be the the first end of "
2737 "removed text");
2738 MOZ_ASSERT(
2739 mAddedEndOffset == 57, // 45 + (50 - 38)
2740 "Test 3-3-3: mAddedEndOffset should be the first end of added text with "
2741 "added text length by the new change");
2742 Clear();
2743
2744 // Replacing text in replaced text (became longer) (not sure if actually
2745 // occurs)
2746 MergeWith(TextChangeData(32, 48, 53, false, false));
2747 MergeWith(TextChangeData(43, 50, 52, false, false));
2748 MOZ_ASSERT(mStartOffset == 32,
2749 "Test 3-4-1: mStartOffset should be the smallest offset");
2750 MOZ_ASSERT(mRemovedEndOffset == 48,
2751 "Test 3-4-2: mRemovedEndOffset should be the the last end of "
2752 "removed text "
2753 "without already added text length");
2754 MOZ_ASSERT(
2755 mAddedEndOffset == 55, // 53 + (52 - 50)
2756 "Test 3-4-3: mAddedEndOffset should be the first end of added text with "
2757 "added text length by the new change");
2758 Clear();
2759
2760 // Replacing text in replaced text (became shorter) (not sure if actually
2761 // occurs)
2762 MergeWith(TextChangeData(36, 48, 50, false, false));
2763 MergeWith(TextChangeData(37, 49, 47, false, false));
2764 MOZ_ASSERT(mStartOffset == 36,
2765 "Test 3-5-1: mStartOffset should be the smallest offset");
2766 MOZ_ASSERT(
2767 mRemovedEndOffset == 48,
2768 "Test 3-5-2: mRemovedEndOffset should be the the first end of removed "
2769 "text");
2770 MOZ_ASSERT(mAddedEndOffset == 48, // 50 + (47 - 49)
2771 "Test 3-5-3: mAddedEndOffset should be the first end of added "
2772 "text without "
2773 "removed text length by the new change");
2774 Clear();
2775
2776 // Replacing text in replaced text (became longer) (not sure if actually
2777 // occurs)
2778 MergeWith(TextChangeData(32, 48, 53, false, false));
2779 MergeWith(TextChangeData(43, 50, 47, false, false));
2780 MOZ_ASSERT(mStartOffset == 32,
2781 "Test 3-6-1: mStartOffset should be the smallest offset");
2782 MOZ_ASSERT(mRemovedEndOffset == 48,
2783 "Test 3-6-2: mRemovedEndOffset should be the the last end of "
2784 "removed text "
2785 "without already added text length");
2786 MOZ_ASSERT(mAddedEndOffset == 50, // 53 + (47 - 50)
2787 "Test 3-6-3: mAddedEndOffset should be the first end of added "
2788 "text without "
2789 "removed text length by the new change");
2790 Clear();
2791
2792 /****************************************************************************
2793 * Case 4
2794 ****************************************************************************/
2795
2796 // Replacing text all of already append text (not sure if actually occurs)
2797 MergeWith(TextChangeData(50, 50, 55, false, false));
2798 MergeWith(TextChangeData(44, 66, 68, false, false));
2799 MOZ_ASSERT(mStartOffset == 44,
2800 "Test 4-1-1: mStartOffset should be the smallest offset");
2801 MOZ_ASSERT(mRemovedEndOffset == 61, // 66 - (55 - 50)
2802 "Test 4-1-2: mRemovedEndOffset should be the the last end of "
2803 "removed text "
2804 "without already added text length");
2805 MOZ_ASSERT(
2806 mAddedEndOffset == 68,
2807 "Test 4-1-3: mAddedEndOffset should be the last end of added text");
2808 Clear();
2809
2810 // Replacing text around a point in which text was removed (not sure if
2811 // actually occurs)
2812 MergeWith(TextChangeData(50, 62, 50, false, false));
2813 MergeWith(TextChangeData(44, 66, 68, false, false));
2814 MOZ_ASSERT(mStartOffset == 44,
2815 "Test 4-2-1: mStartOffset should be the smallest offset");
2816 MOZ_ASSERT(mRemovedEndOffset == 78, // 66 - (50 - 62)
2817 "Test 4-2-2: mRemovedEndOffset should be the the last end of "
2818 "removed text "
2819 "without already removed text length");
2820 MOZ_ASSERT(
2821 mAddedEndOffset == 68,
2822 "Test 4-2-3: mAddedEndOffset should be the last end of added text");
2823 Clear();
2824
2825 // Replacing text all replaced text (became shorter) (not sure if actually
2826 // occurs)
2827 MergeWith(TextChangeData(50, 62, 60, false, false));
2828 MergeWith(TextChangeData(49, 128, 130, false, false));
2829 MOZ_ASSERT(mStartOffset == 49,
2830 "Test 4-3-1: mStartOffset should be the smallest offset");
2831 MOZ_ASSERT(mRemovedEndOffset == 130, // 128 - (60 - 62)
2832 "Test 4-3-2: mRemovedEndOffset should be the the last end of "
2833 "removed text "
2834 "without already removed text length");
2835 MOZ_ASSERT(
2836 mAddedEndOffset == 130,
2837 "Test 4-3-3: mAddedEndOffset should be the last end of added text");
2838 Clear();
2839
2840 // Replacing text all replaced text (became longer) (not sure if actually
2841 // occurs)
2842 MergeWith(TextChangeData(50, 61, 73, false, false));
2843 MergeWith(TextChangeData(44, 100, 50, false, false));
2844 MOZ_ASSERT(mStartOffset == 44,
2845 "Test 4-4-1: mStartOffset should be the smallest offset");
2846 MOZ_ASSERT(mRemovedEndOffset == 88, // 100 - (73 - 61)
2847 "Test 4-4-2: mRemovedEndOffset should be the the last end of "
2848 "removed text "
2849 "with already added text length");
2850 MOZ_ASSERT(
2851 mAddedEndOffset == 50,
2852 "Test 4-4-3: mAddedEndOffset should be the last end of added text");
2853 Clear();
2854
2855 /****************************************************************************
2856 * Case 5
2857 ****************************************************************************/
2858
2859 // Replacing text around start of added text (not sure if actually occurs)
2860 MergeWith(TextChangeData(50, 50, 55, false, false));
2861 MergeWith(TextChangeData(48, 52, 49, false, false));
2862 MOZ_ASSERT(mStartOffset == 48,
2863 "Test 5-1-1: mStartOffset should be the smallest offset");
2864 MOZ_ASSERT(
2865 mRemovedEndOffset == 50,
2866 "Test 5-1-2: mRemovedEndOffset should be the the first end of removed "
2867 "text");
2868 MOZ_ASSERT(
2869 mAddedEndOffset == 52, // 55 + (52 - 49)
2870 "Test 5-1-3: mAddedEndOffset should be the first end of added text with "
2871 "added text length by the new change");
2872 Clear();
2873
2874 // Replacing text around start of replaced text (became shorter) (not sure if
2875 // actually occurs)
2876 MergeWith(TextChangeData(50, 60, 58, false, false));
2877 MergeWith(TextChangeData(43, 50, 48, false, false));
2878 MOZ_ASSERT(mStartOffset == 43,
2879 "Test 5-2-1: mStartOffset should be the smallest offset");
2880 MOZ_ASSERT(
2881 mRemovedEndOffset == 60,
2882 "Test 5-2-2: mRemovedEndOffset should be the the first end of removed "
2883 "text");
2884 MOZ_ASSERT(mAddedEndOffset == 56, // 58 + (48 - 50)
2885 "Test 5-2-3: mAddedEndOffset should be the first end of added "
2886 "text without "
2887 "removed text length by the new change");
2888 Clear();
2889
2890 // Replacing text around start of replaced text (became longer) (not sure if
2891 // actually occurs)
2892 MergeWith(TextChangeData(50, 60, 68, false, false));
2893 MergeWith(TextChangeData(43, 55, 53, false, false));
2894 MOZ_ASSERT(mStartOffset == 43,
2895 "Test 5-3-1: mStartOffset should be the smallest offset");
2896 MOZ_ASSERT(
2897 mRemovedEndOffset == 60,
2898 "Test 5-3-2: mRemovedEndOffset should be the the first end of removed "
2899 "text");
2900 MOZ_ASSERT(mAddedEndOffset == 66, // 68 + (53 - 55)
2901 "Test 5-3-3: mAddedEndOffset should be the first end of added "
2902 "text without "
2903 "removed text length by the new change");
2904 Clear();
2905
2906 // Replacing text around start of replaced text (became shorter) (not sure if
2907 // actually occurs)
2908 MergeWith(TextChangeData(50, 60, 58, false, false));
2909 MergeWith(TextChangeData(43, 50, 128, false, false));
2910 MOZ_ASSERT(mStartOffset == 43,
2911 "Test 5-4-1: mStartOffset should be the smallest offset");
2912 MOZ_ASSERT(
2913 mRemovedEndOffset == 60,
2914 "Test 5-4-2: mRemovedEndOffset should be the the first end of removed "
2915 "text");
2916 MOZ_ASSERT(
2917 mAddedEndOffset == 136, // 58 + (128 - 50)
2918 "Test 5-4-3: mAddedEndOffset should be the first end of added text with "
2919 "added text length by the new change");
2920 Clear();
2921
2922 // Replacing text around start of replaced text (became longer) (not sure if
2923 // actually occurs)
2924 MergeWith(TextChangeData(50, 60, 68, false, false));
2925 MergeWith(TextChangeData(43, 55, 65, false, false));
2926 MOZ_ASSERT(mStartOffset == 43,
2927 "Test 5-5-1: mStartOffset should be the smallest offset");
2928 MOZ_ASSERT(
2929 mRemovedEndOffset == 60,
2930 "Test 5-5-2: mRemovedEndOffset should be the the first end of removed "
2931 "text");
2932 MOZ_ASSERT(
2933 mAddedEndOffset == 78, // 68 + (65 - 55)
2934 "Test 5-5-3: mAddedEndOffset should be the first end of added text with "
2935 "added text length by the new change");
2936 Clear();
2937
2938 /****************************************************************************
2939 * Case 6
2940 ****************************************************************************/
2941
2942 // Appending text before already added text (not sure if actually occurs)
2943 MergeWith(TextChangeData(30, 30, 45, false, false));
2944 MergeWith(TextChangeData(10, 10, 20, false, false));
2945 MOZ_ASSERT(mStartOffset == 10,
2946 "Test 6-1-1: mStartOffset should be the smallest offset");
2947 MOZ_ASSERT(
2948 mRemovedEndOffset == 30,
2949 "Test 6-1-2: mRemovedEndOffset should be the the largest end of removed "
2950 "text");
2951 MOZ_ASSERT(
2952 mAddedEndOffset == 55, // 45 + (20 - 10)
2953 "Test 6-1-3: mAddedEndOffset should be the first end of added text with "
2954 "added text length by the new change");
2955 Clear();
2956
2957 // Removing text before already removed text (not sure if actually occurs)
2958 MergeWith(TextChangeData(30, 35, 30, false, false));
2959 MergeWith(TextChangeData(10, 25, 10, false, false));
2960 MOZ_ASSERT(mStartOffset == 10,
2961 "Test 6-2-1: mStartOffset should be the smallest offset");
2962 MOZ_ASSERT(
2963 mRemovedEndOffset == 35,
2964 "Test 6-2-2: mRemovedEndOffset should be the the largest end of removed "
2965 "text");
2966 MOZ_ASSERT(
2967 mAddedEndOffset == 15, // 30 - (25 - 10)
2968 "Test 6-2-3: mAddedEndOffset should be the first end of added text with "
2969 "removed text length by the new change");
2970 Clear();
2971
2972 // Replacing text before already replaced text (not sure if actually occurs)
2973 MergeWith(TextChangeData(50, 65, 70, false, false));
2974 MergeWith(TextChangeData(13, 24, 15, false, false));
2975 MOZ_ASSERT(mStartOffset == 13,
2976 "Test 6-3-1: mStartOffset should be the smallest offset");
2977 MOZ_ASSERT(
2978 mRemovedEndOffset == 65,
2979 "Test 6-3-2: mRemovedEndOffset should be the the largest end of removed "
2980 "text");
2981 MOZ_ASSERT(mAddedEndOffset == 61, // 70 + (15 - 24)
2982 "Test 6-3-3: mAddedEndOffset should be the first end of added "
2983 "text without "
2984 "removed text length by the new change");
2985 Clear();
2986
2987 // Replacing text before already replaced text (not sure if actually occurs)
2988 MergeWith(TextChangeData(50, 65, 70, false, false));
2989 MergeWith(TextChangeData(13, 24, 36, false, false));
2990 MOZ_ASSERT(mStartOffset == 13,
2991 "Test 6-4-1: mStartOffset should be the smallest offset");
2992 MOZ_ASSERT(
2993 mRemovedEndOffset == 65,
2994 "Test 6-4-2: mRemovedEndOffset should be the the largest end of removed "
2995 "text");
2996 MOZ_ASSERT(mAddedEndOffset == 82, // 70 + (36 - 24)
2997 "Test 6-4-3: mAddedEndOffset should be the first end of added "
2998 "text without "
2999 "removed text length by the new change");
3000 Clear();
3001 }
3002
3003 #endif // #ifdef DEBUG
3004
3005 } // namespace mozilla::widget
3006
3007 #ifdef DEBUG
3008 //////////////////////////////////////////////////////////////
3009 //
3010 // Convert a GUI event message code to a string.
3011 // Makes it a lot easier to debug events.
3012 //
3013 // See gtk/nsWidget.cpp and windows/nsWindow.cpp
3014 // for a DebugPrintEvent() function that uses
3015 // this.
3016 //
3017 //////////////////////////////////////////////////////////////
3018 /* static */
debug_GuiEventToString(WidgetGUIEvent * aGuiEvent)3019 nsAutoString nsBaseWidget::debug_GuiEventToString(WidgetGUIEvent* aGuiEvent) {
3020 NS_ASSERTION(nullptr != aGuiEvent, "cmon, null gui event.");
3021
3022 nsAutoString eventName(u"UNKNOWN"_ns);
3023
3024 # define _ASSIGN_eventName(_value, _name) \
3025 case _value: \
3026 eventName.AssignLiteral(_name); \
3027 break
3028
3029 switch (aGuiEvent->mMessage) {
3030 _ASSIGN_eventName(eBlur, "eBlur");
3031 _ASSIGN_eventName(eDrop, "eDrop");
3032 _ASSIGN_eventName(eDragEnter, "eDragEnter");
3033 _ASSIGN_eventName(eDragExit, "eDragExit");
3034 _ASSIGN_eventName(eDragOver, "eDragOver");
3035 _ASSIGN_eventName(eEditorInput, "eEditorInput");
3036 _ASSIGN_eventName(eFocus, "eFocus");
3037 _ASSIGN_eventName(eFocusIn, "eFocusIn");
3038 _ASSIGN_eventName(eFocusOut, "eFocusOut");
3039 _ASSIGN_eventName(eFormSelect, "eFormSelect");
3040 _ASSIGN_eventName(eFormChange, "eFormChange");
3041 _ASSIGN_eventName(eFormReset, "eFormReset");
3042 _ASSIGN_eventName(eFormSubmit, "eFormSubmit");
3043 _ASSIGN_eventName(eImageAbort, "eImageAbort");
3044 _ASSIGN_eventName(eLoadError, "eLoadError");
3045 _ASSIGN_eventName(eKeyDown, "eKeyDown");
3046 _ASSIGN_eventName(eKeyPress, "eKeyPress");
3047 _ASSIGN_eventName(eKeyUp, "eKeyUp");
3048 _ASSIGN_eventName(eMouseEnterIntoWidget, "eMouseEnterIntoWidget");
3049 _ASSIGN_eventName(eMouseExitFromWidget, "eMouseExitFromWidget");
3050 _ASSIGN_eventName(eMouseDown, "eMouseDown");
3051 _ASSIGN_eventName(eMouseUp, "eMouseUp");
3052 _ASSIGN_eventName(eMouseClick, "eMouseClick");
3053 _ASSIGN_eventName(eMouseAuxClick, "eMouseAuxClick");
3054 _ASSIGN_eventName(eMouseDoubleClick, "eMouseDoubleClick");
3055 _ASSIGN_eventName(eMouseMove, "eMouseMove");
3056 _ASSIGN_eventName(eLoad, "eLoad");
3057 _ASSIGN_eventName(ePopState, "ePopState");
3058 _ASSIGN_eventName(eBeforeScriptExecute, "eBeforeScriptExecute");
3059 _ASSIGN_eventName(eAfterScriptExecute, "eAfterScriptExecute");
3060 _ASSIGN_eventName(eUnload, "eUnload");
3061 _ASSIGN_eventName(eHashChange, "eHashChange");
3062 _ASSIGN_eventName(eReadyStateChange, "eReadyStateChange");
3063 _ASSIGN_eventName(eXULBroadcast, "eXULBroadcast");
3064 _ASSIGN_eventName(eXULCommandUpdate, "eXULCommandUpdate");
3065
3066 # undef _ASSIGN_eventName
3067
3068 default: {
3069 eventName.AssignLiteral("UNKNOWN: ");
3070 eventName.AppendInt(aGuiEvent->mMessage);
3071 } break;
3072 }
3073
3074 return nsAutoString(eventName);
3075 }
3076 //////////////////////////////////////////////////////////////
3077 //
3078 // Code to deal with paint and event debug prefs.
3079 //
3080 //////////////////////////////////////////////////////////////
3081 struct PrefPair {
3082 const char* name;
3083 bool value;
3084 };
3085
3086 static PrefPair debug_PrefValues[] = {
3087 {"nglayout.debug.crossing_event_dumping", false},
3088 {"nglayout.debug.event_dumping", false},
3089 {"nglayout.debug.invalidate_dumping", false},
3090 {"nglayout.debug.motion_event_dumping", false},
3091 {"nglayout.debug.paint_dumping", false}};
3092
3093 //////////////////////////////////////////////////////////////
debug_GetCachedBoolPref(const char * aPrefName)3094 bool nsBaseWidget::debug_GetCachedBoolPref(const char* aPrefName) {
3095 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3096
3097 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3098 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3099 return debug_PrefValues[i].value;
3100 }
3101 }
3102
3103 return false;
3104 }
3105 //////////////////////////////////////////////////////////////
debug_SetCachedBoolPref(const char * aPrefName,bool aValue)3106 static void debug_SetCachedBoolPref(const char* aPrefName, bool aValue) {
3107 NS_ASSERTION(nullptr != aPrefName, "cmon, pref name is null.");
3108
3109 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3110 if (strcmp(debug_PrefValues[i].name, aPrefName) == 0) {
3111 debug_PrefValues[i].value = aValue;
3112
3113 return;
3114 }
3115 }
3116
3117 NS_ASSERTION(false, "cmon, this code is not reached dude.");
3118 }
3119
3120 //////////////////////////////////////////////////////////////
3121 class Debug_PrefObserver final : public nsIObserver {
3122 ~Debug_PrefObserver() = default;
3123
3124 public:
3125 NS_DECL_ISUPPORTS
3126 NS_DECL_NSIOBSERVER
3127 };
3128
NS_IMPL_ISUPPORTS(Debug_PrefObserver,nsIObserver)3129 NS_IMPL_ISUPPORTS(Debug_PrefObserver, nsIObserver)
3130
3131 NS_IMETHODIMP
3132 Debug_PrefObserver::Observe(nsISupports* subject, const char* topic,
3133 const char16_t* data) {
3134 NS_ConvertUTF16toUTF8 prefName(data);
3135
3136 bool value = Preferences::GetBool(prefName.get(), false);
3137 debug_SetCachedBoolPref(prefName.get(), value);
3138 return NS_OK;
3139 }
3140
3141 //////////////////////////////////////////////////////////////
debug_RegisterPrefCallbacks()3142 /* static */ void debug_RegisterPrefCallbacks() {
3143 static bool once = true;
3144
3145 if (!once) {
3146 return;
3147 }
3148
3149 once = false;
3150
3151 nsCOMPtr<nsIObserver> obs(new Debug_PrefObserver());
3152 for (uint32_t i = 0; i < ArrayLength(debug_PrefValues); i++) {
3153 // Initialize the pref values
3154 debug_PrefValues[i].value =
3155 Preferences::GetBool(debug_PrefValues[i].name, false);
3156
3157 if (obs) {
3158 // Register callbacks for when these change
3159 nsCString name;
3160 name.AssignLiteral(debug_PrefValues[i].name,
3161 strlen(debug_PrefValues[i].name));
3162 Preferences::AddStrongObserver(obs, name);
3163 }
3164 }
3165 }
3166 //////////////////////////////////////////////////////////////
_GetPrintCount()3167 static int32_t _GetPrintCount() {
3168 static int32_t sCount = 0;
3169
3170 return ++sCount;
3171 }
3172 //////////////////////////////////////////////////////////////
3173 /* static */
debug_DumpEvent(FILE * aFileOut,nsIWidget * aWidget,WidgetGUIEvent * aGuiEvent,const char * aWidgetName,int32_t aWindowID)3174 void nsBaseWidget::debug_DumpEvent(FILE* aFileOut, nsIWidget* aWidget,
3175 WidgetGUIEvent* aGuiEvent,
3176 const char* aWidgetName, int32_t aWindowID) {
3177 if (aGuiEvent->mMessage == eMouseMove) {
3178 if (!debug_GetCachedBoolPref("nglayout.debug.motion_event_dumping")) return;
3179 }
3180
3181 if (aGuiEvent->mMessage == eMouseEnterIntoWidget ||
3182 aGuiEvent->mMessage == eMouseExitFromWidget) {
3183 if (!debug_GetCachedBoolPref("nglayout.debug.crossing_event_dumping"))
3184 return;
3185 }
3186
3187 if (!debug_GetCachedBoolPref("nglayout.debug.event_dumping")) return;
3188
3189 NS_LossyConvertUTF16toASCII tempString(
3190 debug_GuiEventToString(aGuiEvent).get());
3191
3192 fprintf(aFileOut, "%4d %-26s widget=%-8p name=%-12s id=0x%-6x refpt=%d,%d\n",
3193 _GetPrintCount(), tempString.get(), (void*)aWidget, aWidgetName,
3194 aWindowID, aGuiEvent->mRefPoint.x, aGuiEvent->mRefPoint.y);
3195 }
3196 //////////////////////////////////////////////////////////////
3197 /* static */
debug_DumpPaintEvent(FILE * aFileOut,nsIWidget * aWidget,const nsIntRegion & aRegion,const char * aWidgetName,int32_t aWindowID)3198 void nsBaseWidget::debug_DumpPaintEvent(FILE* aFileOut, nsIWidget* aWidget,
3199 const nsIntRegion& aRegion,
3200 const char* aWidgetName,
3201 int32_t aWindowID) {
3202 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3203 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3204
3205 if (!debug_GetCachedBoolPref("nglayout.debug.paint_dumping")) return;
3206
3207 nsIntRect rect = aRegion.GetBounds();
3208 fprintf(aFileOut,
3209 "%4d PAINT widget=%p name=%-12s id=0x%-6x bounds-rect=%3d,%-3d "
3210 "%3d,%-3d",
3211 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID, rect.X(),
3212 rect.Y(), rect.Width(), rect.Height());
3213
3214 fprintf(aFileOut, "\n");
3215 }
3216 //////////////////////////////////////////////////////////////
3217 /* static */
debug_DumpInvalidate(FILE * aFileOut,nsIWidget * aWidget,const LayoutDeviceIntRect * aRect,const char * aWidgetName,int32_t aWindowID)3218 void nsBaseWidget::debug_DumpInvalidate(FILE* aFileOut, nsIWidget* aWidget,
3219 const LayoutDeviceIntRect* aRect,
3220 const char* aWidgetName,
3221 int32_t aWindowID) {
3222 if (!debug_GetCachedBoolPref("nglayout.debug.invalidate_dumping")) return;
3223
3224 NS_ASSERTION(nullptr != aFileOut, "cmon, null output FILE");
3225 NS_ASSERTION(nullptr != aWidget, "cmon, the widget is null");
3226
3227 fprintf(aFileOut, "%4d Invalidate widget=%p name=%-12s id=0x%-6x",
3228 _GetPrintCount(), (void*)aWidget, aWidgetName, aWindowID);
3229
3230 if (aRect) {
3231 fprintf(aFileOut, " rect=%3d,%-3d %3d,%-3d", aRect->X(), aRect->Y(),
3232 aRect->Width(), aRect->Height());
3233 } else {
3234 fprintf(aFileOut, " rect=%-15s", "none");
3235 }
3236
3237 fprintf(aFileOut, "\n");
3238 }
3239 //////////////////////////////////////////////////////////////
3240
3241 #endif // DEBUG
3242