Bug 1687945 [wpt PR 27273] - [resources] Fix conftest.py for pytest>6, a=testonly
[gecko.git] / view / nsView.cpp
blobc3f7154861a40cf620257b6e299a4e6950e03294
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "nsView.h"
8 #include "mozilla/Attributes.h"
9 #include "mozilla/BasicEvents.h"
10 #include "mozilla/DebugOnly.h"
11 #include "mozilla/IntegerPrintfMacros.h"
12 #include "mozilla/Likely.h"
13 #include "mozilla/Poison.h"
14 #include "mozilla/PresShell.h"
15 #include "mozilla/StaticPrefs_layout.h"
16 #include "mozilla/dom/Document.h"
17 #include "mozilla/dom/BrowserParent.h"
18 #include "nsIWidget.h"
19 #include "nsViewManager.h"
20 #include "nsIFrame.h"
21 #include "nsPresArena.h"
22 #include "nsXULPopupManager.h"
23 #include "nsIScreen.h"
24 #include "nsIWidgetListener.h"
25 #include "nsContentUtils.h" // for nsAutoScriptBlocker
26 #include "nsDocShell.h"
27 #include "mozilla/TimelineConsumers.h"
28 #include "mozilla/CompositeTimelineMarker.h"
29 #include "mozilla/StartupTimeline.h"
31 using namespace mozilla;
33 nsView::nsView(nsViewManager* aViewManager, nsViewVisibility aVisibility)
34 : mViewManager(aViewManager),
35 mParent(nullptr),
36 mNextSibling(nullptr),
37 mFirstChild(nullptr),
38 mFrame(nullptr),
39 mDirtyRegion(nullptr),
40 mZIndex(0),
41 mVis(aVisibility),
42 mPosX(0),
43 mPosY(0),
44 mVFlags(0),
45 mWidgetIsTopLevel(false),
46 mForcedRepaint(false),
47 mNeedsWindowPropertiesSync(false) {
48 MOZ_COUNT_CTOR(nsView);
50 // Views should be transparent by default. Not being transparent is
51 // a promise that the view will paint all its pixels opaquely. Views
52 // should make this promise explicitly by calling
53 // SetViewContentTransparency.
56 void nsView::DropMouseGrabbing() {
57 if (mViewManager->GetPresShell()) {
58 PresShell::ClearMouseCaptureOnView(this);
62 nsView::~nsView() {
63 MOZ_COUNT_DTOR(nsView);
65 while (GetFirstChild()) {
66 nsView* child = GetFirstChild();
67 if (child->GetViewManager() == mViewManager) {
68 child->Destroy();
69 } else {
70 // just unhook it. Someone else will want to destroy this.
71 RemoveChild(child);
75 if (mViewManager) {
76 DropMouseGrabbing();
78 nsView* rootView = mViewManager->GetRootView();
80 if (rootView) {
81 // Root views can have parents!
82 if (mParent) {
83 mViewManager->RemoveChild(this);
86 if (rootView == this) {
87 // Inform the view manager that the root view has gone away...
88 mViewManager->SetRootView(nullptr);
90 } else if (mParent) {
91 mParent->RemoveChild(this);
94 mViewManager = nullptr;
95 } else if (mParent) {
96 mParent->RemoveChild(this);
99 if (mPreviousWindow) {
100 mPreviousWindow->SetPreviouslyAttachedWidgetListener(nullptr);
103 // Destroy and release the widget
104 DestroyWidget();
106 MOZ_RELEASE_ASSERT(!mFrame);
108 delete mDirtyRegion;
111 class DestroyWidgetRunnable : public Runnable {
112 public:
113 NS_DECL_NSIRUNNABLE
115 explicit DestroyWidgetRunnable(nsIWidget* aWidget)
116 : mozilla::Runnable("DestroyWidgetRunnable"), mWidget(aWidget) {}
118 private:
119 nsCOMPtr<nsIWidget> mWidget;
122 NS_IMETHODIMP DestroyWidgetRunnable::Run() {
123 mWidget->Destroy();
124 mWidget = nullptr;
125 return NS_OK;
128 void nsView::DestroyWidget() {
129 if (mWindow) {
130 // If we are not attached to a base window, we're going to tear down our
131 // widget here. However, if we're attached to somebody elses widget, we
132 // want to leave the widget alone: don't reset the client data or call
133 // Destroy. Just clear our event view ptr and free our reference to it.
134 if (mWidgetIsTopLevel) {
135 mWindow->SetAttachedWidgetListener(nullptr);
136 } else {
137 mWindow->SetWidgetListener(nullptr);
139 nsCOMPtr<nsIRunnable> widgetDestroyer =
140 new DestroyWidgetRunnable(mWindow);
142 // Don't leak if we happen to arrive here after the main thread
143 // has disappeared.
144 nsCOMPtr<nsIThread> mainThread = do_GetMainThread();
145 if (mainThread) {
146 mainThread->Dispatch(widgetDestroyer.forget(), NS_DISPATCH_NORMAL);
150 mWindow = nullptr;
154 nsView* nsView::GetViewFor(nsIWidget* aWidget) {
155 MOZ_ASSERT(nullptr != aWidget, "null widget ptr");
157 nsIWidgetListener* listener = aWidget->GetWidgetListener();
158 if (listener) {
159 nsView* view = listener->GetView();
160 if (view) return view;
163 listener = aWidget->GetAttachedWidgetListener();
164 return listener ? listener->GetView() : nullptr;
167 void nsView::Destroy() {
168 this->~nsView();
169 mozWritePoison(this, sizeof(*this));
170 nsView::operator delete(this);
173 void nsView::SetPosition(nscoord aX, nscoord aY) {
174 mDimBounds.MoveBy(aX - mPosX, aY - mPosY);
175 mPosX = aX;
176 mPosY = aY;
178 NS_ASSERTION(GetParent() || (aX == 0 && aY == 0),
179 "Don't try to move the root widget to something non-zero");
181 ResetWidgetBounds(true, false);
184 void nsView::ResetWidgetBounds(bool aRecurse, bool aForceSync) {
185 if (mWindow) {
186 if (!aForceSync) {
187 // Don't change widget geometry synchronously, since that can
188 // cause synchronous painting.
189 mViewManager->PostPendingUpdate();
190 } else {
191 DoResetWidgetBounds(false, true);
193 return;
196 if (aRecurse) {
197 // reposition any widgets under this view
198 for (nsView* v = GetFirstChild(); v; v = v->GetNextSibling()) {
199 v->ResetWidgetBounds(true, aForceSync);
204 bool nsView::IsEffectivelyVisible() {
205 for (nsView* v = this; v; v = v->mParent) {
206 if (v->GetVisibility() == nsViewVisibility_kHide) return false;
208 return true;
211 LayoutDeviceIntRect nsView::CalcWidgetBounds(nsWindowType aType) {
212 int32_t p2a = mViewManager->AppUnitsPerDevPixel();
214 nsRect viewBounds(mDimBounds);
216 nsView* parent = GetParent();
217 nsIWidget* parentWidget = nullptr;
218 if (parent) {
219 nsPoint offset;
220 parentWidget = parent->GetNearestWidget(&offset, p2a);
221 // make viewBounds be relative to the parent widget, in appunits
222 viewBounds += offset;
224 if (parentWidget && aType == eWindowType_popup && IsEffectivelyVisible()) {
225 // put offset into screen coordinates. (based on client area origin)
226 LayoutDeviceIntPoint screenPoint = parentWidget->WidgetToScreenOffset();
227 viewBounds += nsPoint(NSIntPixelsToAppUnits(screenPoint.x, p2a),
228 NSIntPixelsToAppUnits(screenPoint.y, p2a));
232 // Compute widget bounds in device pixels
233 LayoutDeviceIntRect newBounds =
234 LayoutDeviceIntRect::FromUnknownRect(viewBounds.ToNearestPixels(p2a));
236 #if defined(XP_MACOSX) || defined(MOZ_WIDGET_GTK)
237 // cocoa and GTK round widget coordinates to the nearest global "display
238 // pixel" integer value. So we avoid fractional display pixel values by
239 // rounding to the nearest value that won't yield a fractional display pixel.
240 nsIWidget* widget = parentWidget ? parentWidget : mWindow.get();
241 uint32_t round;
242 if (aType == eWindowType_popup && widget &&
243 ((round = widget->RoundsWidgetCoordinatesTo()) > 1)) {
244 LayoutDeviceIntSize pixelRoundedSize = newBounds.Size();
245 // round the top left and bottom right to the nearest round pixel
246 newBounds.x =
247 NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.x, p2a) / round) *
248 round;
249 newBounds.y =
250 NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.y, p2a) / round) *
251 round;
252 newBounds.width =
253 NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.XMost(), p2a) /
254 round) *
255 round -
256 newBounds.x;
257 newBounds.height =
258 NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.YMost(), p2a) /
259 round) *
260 round -
261 newBounds.y;
262 // but if that makes the widget larger then our frame may not paint the
263 // extra pixels, so reduce the size to the nearest round value
264 if (newBounds.width > pixelRoundedSize.width) {
265 newBounds.width -= round;
267 if (newBounds.height > pixelRoundedSize.height) {
268 newBounds.height -= round;
271 #endif
273 // Compute where the top-left of our widget ended up relative to the parent
274 // widget, in appunits.
275 nsPoint roundedOffset(NSIntPixelsToAppUnits(newBounds.X(), p2a),
276 NSIntPixelsToAppUnits(newBounds.Y(), p2a));
278 // mViewToWidgetOffset is added to coordinates relative to the view origin
279 // to get coordinates relative to the widget.
280 // The view origin, relative to the parent widget, is at
281 // (mPosX,mPosY) - mDimBounds.TopLeft() + viewBounds.TopLeft().
282 // Our widget, relative to the parent widget, is roundedOffset.
283 mViewToWidgetOffset = nsPoint(mPosX, mPosY) - mDimBounds.TopLeft() +
284 viewBounds.TopLeft() - roundedOffset;
286 return newBounds;
289 void nsView::DoResetWidgetBounds(bool aMoveOnly, bool aInvalidateChangedSize) {
290 // The geometry of a root view's widget is controlled externally,
291 // NOT by sizing or positioning the view
292 if (mViewManager->GetRootView() == this) {
293 return;
296 MOZ_ASSERT(mWindow, "Why was this called??");
298 // Hold this ref to make sure it stays alive.
299 nsCOMPtr<nsIWidget> widget = mWindow;
301 // Stash a copy of these and use them so we can handle this being deleted (say
302 // from sync painting/flushing from Show/Move/Resize on the widget).
303 LayoutDeviceIntRect newBounds;
305 nsWindowType type = widget->WindowType();
307 LayoutDeviceIntRect curBounds = widget->GetClientBounds();
308 bool invisiblePopup = type == eWindowType_popup &&
309 ((curBounds.IsEmpty() && mDimBounds.IsEmpty()) ||
310 mVis == nsViewVisibility_kHide);
312 if (invisiblePopup) {
313 // We're going to hit the early exit below, avoid calling CalcWidgetBounds.
314 } else {
315 newBounds = CalcWidgetBounds(type);
316 invisiblePopup = newBounds.IsEmpty();
319 bool curVisibility = widget->IsVisible();
320 bool newVisibility = !invisiblePopup && IsEffectivelyVisible();
321 if (curVisibility && !newVisibility) {
322 widget->Show(false);
325 if (invisiblePopup) {
326 // Don't manipulate empty or hidden popup widgets. For example there's no
327 // point moving hidden comboboxes around, or doing X server roundtrips
328 // to compute their true screen position. This could mean that
329 // WidgetToScreen operations on these widgets don't return up-to-date
330 // values, but popup positions aren't reliable anyway because of correction
331 // to be on or off-screen.
332 return;
335 bool changedPos = curBounds.TopLeft() != newBounds.TopLeft();
336 bool changedSize = curBounds.Size() != newBounds.Size();
338 // Child views are never attached to top level widgets, this is safe.
340 // Coordinates are converted to desktop pixels for window Move/Resize APIs,
341 // because of the potential for device-pixel coordinate spaces for mixed
342 // hidpi/lodpi screens to overlap each other and result in bad placement
343 // (bug 814434).
345 DesktopToLayoutDeviceScale scale = widget->GetDesktopToDeviceScaleByScreen();
347 DesktopRect deskRect = newBounds / scale;
348 if (changedPos) {
349 if (changedSize && !aMoveOnly) {
350 widget->ResizeClient(deskRect, aInvalidateChangedSize);
351 } else {
352 widget->MoveClient(deskRect.TopLeft());
354 } else {
355 if (changedSize && !aMoveOnly) {
356 widget->ResizeClient(deskRect.Size(), aInvalidateChangedSize);
357 } // else do nothing!
360 if (!curVisibility && newVisibility) {
361 widget->Show(true);
365 void nsView::SetDimensions(const nsRect& aRect, bool aPaint,
366 bool aResizeWidget) {
367 nsRect dims = aRect;
368 dims.MoveBy(mPosX, mPosY);
370 // Don't use nsRect's operator== here, since it returns true when
371 // both rects are empty even if they have different widths and we
372 // have cases where that sort of thing matters to us.
373 if (mDimBounds.TopLeft() == dims.TopLeft() &&
374 mDimBounds.Size() == dims.Size()) {
375 return;
378 mDimBounds = dims;
380 if (aResizeWidget) {
381 ResetWidgetBounds(false, false);
385 void nsView::NotifyEffectiveVisibilityChanged(bool aEffectivelyVisible) {
386 if (!aEffectivelyVisible) {
387 DropMouseGrabbing();
390 SetForcedRepaint(true);
392 if (nullptr != mWindow) {
393 ResetWidgetBounds(false, false);
396 for (nsView* child = mFirstChild; child; child = child->mNextSibling) {
397 if (child->mVis == nsViewVisibility_kHide) {
398 // It was effectively hidden and still is
399 continue;
401 // Our child is visible if we are
402 child->NotifyEffectiveVisibilityChanged(aEffectivelyVisible);
406 void nsView::SetVisibility(nsViewVisibility aVisibility) {
407 mVis = aVisibility;
408 NotifyEffectiveVisibilityChanged(IsEffectivelyVisible());
411 void nsView::SetFloating(bool aFloatingView) {
412 if (aFloatingView)
413 mVFlags |= NS_VIEW_FLAG_FLOATING;
414 else
415 mVFlags &= ~NS_VIEW_FLAG_FLOATING;
418 void nsView::InvalidateHierarchy() {
419 if (mViewManager->GetRootView() == this) mViewManager->InvalidateHierarchy();
421 for (nsView* child = mFirstChild; child; child = child->GetNextSibling())
422 child->InvalidateHierarchy();
425 void nsView::InsertChild(nsView* aChild, nsView* aSibling) {
426 MOZ_ASSERT(nullptr != aChild, "null ptr");
428 if (nullptr != aChild) {
429 if (nullptr != aSibling) {
430 #ifdef DEBUG
431 NS_ASSERTION(aSibling->GetParent() == this,
432 "tried to insert view with invalid sibling");
433 #endif
434 // insert after sibling
435 aChild->SetNextSibling(aSibling->GetNextSibling());
436 aSibling->SetNextSibling(aChild);
437 } else {
438 aChild->SetNextSibling(mFirstChild);
439 mFirstChild = aChild;
441 aChild->SetParent(this);
443 // If we just inserted a root view, then update the RootViewManager
444 // on all view managers in the new subtree.
446 nsViewManager* vm = aChild->GetViewManager();
447 if (vm->GetRootView() == aChild) {
448 aChild->InvalidateHierarchy();
453 void nsView::RemoveChild(nsView* child) {
454 MOZ_ASSERT(nullptr != child, "null ptr");
456 if (nullptr != child) {
457 nsView* prevKid = nullptr;
458 nsView* kid = mFirstChild;
459 DebugOnly<bool> found = false;
460 while (nullptr != kid) {
461 if (kid == child) {
462 if (nullptr != prevKid) {
463 prevKid->SetNextSibling(kid->GetNextSibling());
464 } else {
465 mFirstChild = kid->GetNextSibling();
467 child->SetParent(nullptr);
468 found = true;
469 break;
471 prevKid = kid;
472 kid = kid->GetNextSibling();
474 NS_ASSERTION(found, "tried to remove non child");
476 // If we just removed a root view, then update the RootViewManager
477 // on all view managers in the removed subtree.
479 nsViewManager* vm = child->GetViewManager();
480 if (vm->GetRootView() == child) {
481 child->InvalidateHierarchy();
486 // Native widgets ultimately just can't deal with the awesome power of
487 // CSS2 z-index. However, we set the z-index on the widget anyway
488 // because in many simple common cases the widgets do end up in the
489 // right order. We set each widget's z-index to the z-index of the
490 // nearest ancestor that has non-auto z-index.
491 static void UpdateNativeWidgetZIndexes(nsView* aView, int32_t aZIndex) {
492 if (aView->HasWidget()) {
493 nsIWidget* widget = aView->GetWidget();
494 if (widget->GetZIndex() != aZIndex) {
495 widget->SetZIndex(aZIndex);
497 } else {
498 for (nsView* v = aView->GetFirstChild(); v; v = v->GetNextSibling()) {
499 if (v->GetZIndexIsAuto()) {
500 UpdateNativeWidgetZIndexes(v, aZIndex);
506 static int32_t FindNonAutoZIndex(nsView* aView) {
507 while (aView) {
508 if (!aView->GetZIndexIsAuto()) {
509 return aView->GetZIndex();
511 aView = aView->GetParent();
513 return 0;
516 struct DefaultWidgetInitData : public nsWidgetInitData {
517 DefaultWidgetInitData() : nsWidgetInitData() {
518 mWindowType = eWindowType_child;
519 clipChildren = true;
520 clipSiblings = true;
524 nsresult nsView::CreateWidget(nsWidgetInitData* aWidgetInitData,
525 bool aEnableDragDrop, bool aResetVisibility) {
526 AssertNoWindow();
527 MOZ_ASSERT(
528 !aWidgetInitData || aWidgetInitData->mWindowType != eWindowType_popup,
529 "Use CreateWidgetForPopup");
531 DefaultWidgetInitData defaultInitData;
532 bool initDataPassedIn = !!aWidgetInitData;
533 aWidgetInitData = aWidgetInitData ? aWidgetInitData : &defaultInitData;
534 defaultInitData.mListenForResizes =
535 (!initDataPassedIn && GetParent() &&
536 GetParent()->GetViewManager() != mViewManager);
538 LayoutDeviceIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
540 nsIWidget* parentWidget =
541 GetParent() ? GetParent()->GetNearestWidget(nullptr) : nullptr;
542 if (!parentWidget) {
543 NS_ERROR("nsView::CreateWidget without suitable parent widget??");
544 return NS_ERROR_FAILURE;
547 // XXX: using aForceUseIWidgetParent=true to preserve previous
548 // semantics. It's not clear that it's actually needed.
549 mWindow = parentWidget->CreateChild(trect, aWidgetInitData, true);
550 if (!mWindow) {
551 return NS_ERROR_FAILURE;
554 InitializeWindow(aEnableDragDrop, aResetVisibility);
556 return NS_OK;
559 nsresult nsView::CreateWidgetForParent(nsIWidget* aParentWidget,
560 nsWidgetInitData* aWidgetInitData,
561 bool aEnableDragDrop,
562 bool aResetVisibility) {
563 AssertNoWindow();
564 MOZ_ASSERT(
565 !aWidgetInitData || aWidgetInitData->mWindowType != eWindowType_popup,
566 "Use CreateWidgetForPopup");
567 MOZ_ASSERT(aParentWidget, "Parent widget required");
569 DefaultWidgetInitData defaultInitData;
570 aWidgetInitData = aWidgetInitData ? aWidgetInitData : &defaultInitData;
572 LayoutDeviceIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
574 mWindow = aParentWidget->CreateChild(trect, aWidgetInitData);
575 if (!mWindow) {
576 return NS_ERROR_FAILURE;
579 InitializeWindow(aEnableDragDrop, aResetVisibility);
581 return NS_OK;
584 nsresult nsView::CreateWidgetForPopup(nsWidgetInitData* aWidgetInitData,
585 nsIWidget* aParentWidget,
586 bool aEnableDragDrop,
587 bool aResetVisibility) {
588 AssertNoWindow();
589 MOZ_ASSERT(aWidgetInitData, "Widget init data required");
590 MOZ_ASSERT(aWidgetInitData->mWindowType == eWindowType_popup,
591 "Use one of the other CreateWidget methods");
593 LayoutDeviceIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
595 // XXX/cjones: having these two separate creation cases seems ... um
596 // ... unnecessary, but it's the way the old code did it. Please
597 // unify them by first finding a suitable parent nsIWidget, then
598 // getting rid of aForceUseIWidgetParent.
599 if (aParentWidget) {
600 // XXX: using aForceUseIWidgetParent=true to preserve previous
601 // semantics. It's not clear that it's actually needed.
602 mWindow = aParentWidget->CreateChild(trect, aWidgetInitData, true);
603 } else {
604 nsIWidget* nearestParent =
605 GetParent() ? GetParent()->GetNearestWidget(nullptr) : nullptr;
606 if (!nearestParent) {
607 // Without a parent, we can't make a popup. This can happen
608 // when printing
609 return NS_ERROR_FAILURE;
612 mWindow = nearestParent->CreateChild(trect, aWidgetInitData);
614 if (!mWindow) {
615 return NS_ERROR_FAILURE;
618 InitializeWindow(aEnableDragDrop, aResetVisibility);
620 return NS_OK;
623 void nsView::InitializeWindow(bool aEnableDragDrop, bool aResetVisibility) {
624 MOZ_ASSERT(mWindow, "Must have a window to initialize");
626 mWindow->SetWidgetListener(this);
628 if (aEnableDragDrop) {
629 mWindow->EnableDragDrop(true);
632 // propagate the z-index to the widget.
633 UpdateNativeWidgetZIndexes(this, FindNonAutoZIndex(this));
635 // make sure visibility state is accurate
637 if (aResetVisibility) {
638 SetVisibility(GetVisibility());
642 void nsView::SetNeedsWindowPropertiesSync() {
643 mNeedsWindowPropertiesSync = true;
644 if (mViewManager) {
645 mViewManager->PostPendingUpdate();
649 // Attach to a top level widget and start receiving mirrored events.
650 nsresult nsView::AttachToTopLevelWidget(nsIWidget* aWidget) {
651 MOZ_ASSERT(nullptr != aWidget, "null widget ptr");
653 /// XXXjimm This is a temporary workaround to an issue w/document
654 // viewer (bug 513162).
655 nsIWidgetListener* listener = aWidget->GetAttachedWidgetListener();
656 if (listener) {
657 nsView* oldView = listener->GetView();
658 if (oldView) {
659 oldView->DetachFromTopLevelWidget();
663 // Note, the previous device context will be released. Detaching
664 // will not restore the old one.
665 aWidget->AttachViewToTopLevel(!nsIWidget::UsePuppetWidgets());
667 mWindow = aWidget;
669 mWindow->SetAttachedWidgetListener(this);
670 if (mWindow->WindowType() != eWindowType_invisible) {
671 nsresult rv = mWindow->AsyncEnableDragDrop(true);
672 NS_ENSURE_SUCCESS(rv, rv);
674 mWidgetIsTopLevel = true;
676 // Refresh the view bounds
677 CalcWidgetBounds(mWindow->WindowType());
679 return NS_OK;
682 // Detach this view from an attached widget.
683 nsresult nsView::DetachFromTopLevelWidget() {
684 MOZ_ASSERT(mWidgetIsTopLevel, "Not attached currently!");
685 MOZ_ASSERT(mWindow, "null mWindow for DetachFromTopLevelWidget!");
687 mWindow->SetAttachedWidgetListener(nullptr);
688 nsIWidgetListener* listener = mWindow->GetPreviouslyAttachedWidgetListener();
690 if (listener && listener->GetView()) {
691 // Ensure the listener doesn't think it's being used anymore
692 listener->GetView()->SetPreviousWidget(nullptr);
695 // If the new view's frame is paint suppressed then the window
696 // will want to use us instead until that's done
697 mWindow->SetPreviouslyAttachedWidgetListener(this);
699 mPreviousWindow = mWindow;
700 mWindow = nullptr;
702 mWidgetIsTopLevel = false;
704 return NS_OK;
707 void nsView::SetZIndex(bool aAuto, int32_t aZIndex) {
708 bool oldIsAuto = GetZIndexIsAuto();
709 mVFlags = (mVFlags & ~NS_VIEW_FLAG_AUTO_ZINDEX) |
710 (aAuto ? NS_VIEW_FLAG_AUTO_ZINDEX : 0);
711 mZIndex = aZIndex;
713 if (HasWidget() || !oldIsAuto || !aAuto) {
714 UpdateNativeWidgetZIndexes(this, FindNonAutoZIndex(this));
718 void nsView::AssertNoWindow() {
719 // XXX: it would be nice to make this a strong assert
720 if (MOZ_UNLIKELY(mWindow)) {
721 NS_ERROR("We already have a window for this view? BAD");
722 mWindow->SetWidgetListener(nullptr);
723 mWindow->Destroy();
724 mWindow = nullptr;
729 // internal window creation functions
731 void nsView::AttachWidgetEventHandler(nsIWidget* aWidget) {
732 #ifdef DEBUG
733 NS_ASSERTION(!aWidget->GetWidgetListener(), "Already have a widget listener");
734 #endif
736 aWidget->SetWidgetListener(this);
739 void nsView::DetachWidgetEventHandler(nsIWidget* aWidget) {
740 NS_ASSERTION(!aWidget->GetWidgetListener() ||
741 aWidget->GetWidgetListener()->GetView() == this,
742 "Wrong view");
743 aWidget->SetWidgetListener(nullptr);
746 #ifdef DEBUG
747 void nsView::List(FILE* out, int32_t aIndent) const {
748 int32_t i;
749 for (i = aIndent; --i >= 0;) fputs(" ", out);
750 fprintf(out, "%p ", (void*)this);
751 if (nullptr != mWindow) {
752 nscoord p2a = mViewManager->AppUnitsPerDevPixel();
753 LayoutDeviceIntRect rect = mWindow->GetClientBounds();
754 nsRect windowBounds = LayoutDeviceIntRect::ToAppUnits(rect, p2a);
755 rect = mWindow->GetBounds();
756 nsRect nonclientBounds = LayoutDeviceIntRect::ToAppUnits(rect, p2a);
757 nsrefcnt widgetRefCnt = mWindow.get()->AddRef() - 1;
758 mWindow.get()->Release();
759 int32_t Z = mWindow->GetZIndex();
760 fprintf(out, "(widget=%p[%" PRIuPTR "] z=%d pos={%d,%d,%d,%d}) ",
761 (void*)mWindow, widgetRefCnt, Z, nonclientBounds.X(),
762 nonclientBounds.Y(), windowBounds.Width(), windowBounds.Height());
764 nsRect brect = GetBounds();
765 fprintf(out, "{%d,%d,%d,%d} @ %d,%d", brect.X(), brect.Y(), brect.Width(),
766 brect.Height(), mPosX, mPosY);
767 fprintf(out, " flags=%x z=%d vis=%d frame=%p <\n", mVFlags, mZIndex, mVis,
768 static_cast<void*>(mFrame));
769 for (nsView* kid = mFirstChild; kid; kid = kid->GetNextSibling()) {
770 NS_ASSERTION(kid->GetParent() == this, "incorrect parent");
771 kid->List(out, aIndent + 1);
773 for (i = aIndent; --i >= 0;) fputs(" ", out);
774 fputs(">\n", out);
776 #endif // DEBUG
778 nsPoint nsView::GetOffsetTo(const nsView* aOther) const {
779 return GetOffsetTo(aOther, GetViewManager()->AppUnitsPerDevPixel());
782 nsPoint nsView::GetOffsetTo(const nsView* aOther, const int32_t aAPD) const {
783 MOZ_ASSERT(GetParent() || !aOther || aOther->GetParent() || this == aOther,
784 "caller of (outer) GetOffsetTo must not pass unrelated views");
785 // We accumulate the final result in offset
786 nsPoint offset(0, 0);
787 // The offset currently accumulated at the current APD
788 nsPoint docOffset(0, 0);
789 const nsView* v = this;
790 nsViewManager* currVM = v->GetViewManager();
791 int32_t currAPD = currVM->AppUnitsPerDevPixel();
792 const nsView* root = nullptr;
793 for (; v != aOther && v; root = v, v = v->GetParent()) {
794 nsViewManager* newVM = v->GetViewManager();
795 if (newVM != currVM) {
796 int32_t newAPD = newVM->AppUnitsPerDevPixel();
797 if (newAPD != currAPD) {
798 offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
799 docOffset.x = docOffset.y = 0;
800 currAPD = newAPD;
802 currVM = newVM;
804 docOffset += v->GetPosition();
806 offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
808 if (v != aOther) {
809 // Looks like aOther wasn't an ancestor of |this|. So now we have
810 // the root-VM-relative position of |this| in |offset|. Get the
811 // root-VM-relative position of aOther and subtract it.
812 nsPoint negOffset = aOther->GetOffsetTo(root, aAPD);
813 offset -= negOffset;
816 return offset;
819 nsPoint nsView::GetOffsetToWidget(nsIWidget* aWidget) const {
820 nsPoint pt;
821 // Get the view for widget
822 nsView* widgetView = GetViewFor(aWidget);
823 if (!widgetView) {
824 return pt;
827 // Get the offset to the widget view in the widget view's APD
828 // We get the offset in the widget view's APD first and then convert to our
829 // APD afterwards so that we can include the widget view's ViewToWidgetOffset
830 // in the sum in its native APD, and then convert the whole thing to our APD
831 // so that we don't have to convert the APD of the relatively small
832 // ViewToWidgetOffset by itself with a potentially large relative rounding
833 // error.
834 pt = -widgetView->GetOffsetTo(this);
835 // Add in the offset to the widget.
836 pt += widgetView->ViewToWidgetOffset();
838 // Convert to our appunits.
839 int32_t widgetAPD = widgetView->GetViewManager()->AppUnitsPerDevPixel();
840 int32_t ourAPD = GetViewManager()->AppUnitsPerDevPixel();
841 pt = pt.ScaleToOtherAppUnits(widgetAPD, ourAPD);
842 return pt;
845 nsIWidget* nsView::GetNearestWidget(nsPoint* aOffset) const {
846 return GetNearestWidget(aOffset, GetViewManager()->AppUnitsPerDevPixel());
849 nsIWidget* nsView::GetNearestWidget(nsPoint* aOffset,
850 const int32_t aAPD) const {
851 // aOffset is based on the view's position, which ignores any chrome on
852 // attached parent widgets.
854 // We accumulate the final result in pt
855 nsPoint pt(0, 0);
856 // The offset currently accumulated at the current APD
857 nsPoint docPt(0, 0);
858 const nsView* v = this;
859 nsViewManager* currVM = v->GetViewManager();
860 int32_t currAPD = currVM->AppUnitsPerDevPixel();
861 for (; v && !v->HasWidget(); v = v->GetParent()) {
862 nsViewManager* newVM = v->GetViewManager();
863 if (newVM != currVM) {
864 int32_t newAPD = newVM->AppUnitsPerDevPixel();
865 if (newAPD != currAPD) {
866 pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
867 docPt.x = docPt.y = 0;
868 currAPD = newAPD;
870 currVM = newVM;
872 docPt += v->GetPosition();
874 if (!v) {
875 if (aOffset) {
876 pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
877 *aOffset = pt;
879 return nullptr;
882 // pt is now the offset from v's origin to this view's origin.
883 // We add the ViewToWidgetOffset to get the offset to the widget.
884 if (aOffset) {
885 docPt += v->ViewToWidgetOffset();
886 pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
887 *aOffset = pt;
889 return v->GetWidget();
892 bool nsView::IsRoot() const {
893 NS_ASSERTION(mViewManager != nullptr,
894 " View manager is null in nsView::IsRoot()");
895 return mViewManager->GetRootView() == this;
898 nsRect nsView::GetBoundsInParentUnits() const {
899 nsView* parent = GetParent();
900 nsViewManager* VM = GetViewManager();
901 if (this != VM->GetRootView() || !parent) {
902 return mDimBounds;
904 int32_t ourAPD = VM->AppUnitsPerDevPixel();
905 int32_t parentAPD = parent->GetViewManager()->AppUnitsPerDevPixel();
906 return mDimBounds.ScaleToOtherAppUnitsRoundOut(ourAPD, parentAPD);
909 nsPoint nsView::ConvertFromParentCoords(nsPoint aPt) const {
910 const nsView* parent = GetParent();
911 if (parent) {
912 aPt = aPt.ScaleToOtherAppUnits(
913 parent->GetViewManager()->AppUnitsPerDevPixel(),
914 GetViewManager()->AppUnitsPerDevPixel());
916 aPt -= GetPosition();
917 return aPt;
920 static bool IsPopupWidget(nsIWidget* aWidget) {
921 return (aWidget->WindowType() == eWindowType_popup);
924 PresShell* nsView::GetPresShell() { return GetViewManager()->GetPresShell(); }
926 bool nsView::WindowMoved(nsIWidget* aWidget, int32_t x, int32_t y) {
927 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
928 if (pm && IsPopupWidget(aWidget)) {
929 pm->PopupMoved(mFrame, nsIntPoint(x, y));
930 return true;
933 return false;
936 bool nsView::WindowResized(nsIWidget* aWidget, int32_t aWidth,
937 int32_t aHeight) {
938 // The root view may not be set if this is the resize associated with
939 // window creation
940 SetForcedRepaint(true);
941 if (this == mViewManager->GetRootView()) {
942 RefPtr<nsDeviceContext> devContext = mViewManager->GetDeviceContext();
943 // ensure DPI is up-to-date, in case of window being opened and sized
944 // on a non-default-dpi display (bug 829963)
945 devContext->CheckDPIChange();
946 int32_t p2a = devContext->AppUnitsPerDevPixel();
947 mViewManager->SetWindowDimensions(NSIntPixelsToAppUnits(aWidth, p2a),
948 NSIntPixelsToAppUnits(aHeight, p2a));
950 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
951 if (pm) {
952 PresShell* presShell = mViewManager->GetPresShell();
953 if (presShell && presShell->GetDocument()) {
954 pm->AdjustPopupsOnWindowChange(presShell);
958 return true;
960 if (IsPopupWidget(aWidget)) {
961 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
962 if (pm) {
963 pm->PopupResized(mFrame, LayoutDeviceIntSize(aWidth, aHeight));
964 return true;
968 return false;
971 #if defined(MOZ_WIDGET_ANDROID)
972 void nsView::DynamicToolbarMaxHeightChanged(ScreenIntCoord aHeight) {
973 MOZ_ASSERT(XRE_IsParentProcess(),
974 "Should be only called for the browser parent process");
975 MOZ_ASSERT(this == mViewManager->GetRootView(),
976 "Should be called for the root view");
978 PresShell* presShell = mViewManager->GetPresShell();
979 if (!presShell) {
980 return;
983 dom::Document* document = presShell->GetDocument();
984 if (!document) {
985 return;
988 nsPIDOMWindowOuter* window = document->GetWindow();
989 if (!window) {
990 return;
993 nsContentUtils::CallOnAllRemoteChildren(
994 window, [&aHeight](dom::BrowserParent* aBrowserParent) -> CallState {
995 aBrowserParent->DynamicToolbarMaxHeightChanged(aHeight);
996 return CallState::Continue;
1000 void nsView::DynamicToolbarOffsetChanged(ScreenIntCoord aOffset) {
1001 MOZ_ASSERT(XRE_IsParentProcess(),
1002 "Should be only called for the browser parent process");
1003 MOZ_ASSERT(this == mViewManager->GetRootView(),
1004 "Should be called for the root view");
1006 PresShell* presShell = mViewManager->GetPresShell();
1007 if (!presShell) {
1008 return;
1011 dom::Document* document = presShell->GetDocument();
1012 if (!document) {
1013 return;
1016 nsPIDOMWindowOuter* window = document->GetWindow();
1017 if (!window) {
1018 return;
1021 nsContentUtils::CallOnAllRemoteChildren(
1022 window, [&aOffset](dom::BrowserParent* aBrowserParent) -> CallState {
1023 // Skip background tabs.
1024 if (!aBrowserParent->GetDocShellIsActive()) {
1025 return CallState::Continue;
1028 aBrowserParent->DynamicToolbarOffsetChanged(aOffset);
1029 return CallState::Stop;
1032 #endif
1034 bool nsView::RequestWindowClose(nsIWidget* aWidget) {
1035 if (mFrame && IsPopupWidget(aWidget) && mFrame->IsMenuPopupFrame()) {
1036 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
1037 if (pm) {
1038 pm->HidePopup(mFrame->GetContent(), false, true, false, false);
1039 return true;
1043 return false;
1046 void nsView::WillPaintWindow(nsIWidget* aWidget) {
1047 RefPtr<nsViewManager> vm = mViewManager;
1048 vm->WillPaintWindow(aWidget);
1051 bool nsView::PaintWindow(nsIWidget* aWidget, LayoutDeviceIntRegion aRegion) {
1052 NS_ASSERTION(this == nsView::GetViewFor(aWidget), "wrong view for widget?");
1054 RefPtr<nsViewManager> vm = mViewManager;
1055 bool result = vm->PaintWindow(aWidget, aRegion);
1056 return result;
1059 void nsView::DidPaintWindow() {
1060 RefPtr<nsViewManager> vm = mViewManager;
1061 vm->DidPaintWindow();
1064 void nsView::DidCompositeWindow(mozilla::layers::TransactionId aTransactionId,
1065 const TimeStamp& aCompositeStart,
1066 const TimeStamp& aCompositeEnd) {
1067 PresShell* presShell = mViewManager->GetPresShell();
1068 if (!presShell) {
1069 return;
1072 nsAutoScriptBlocker scriptBlocker;
1074 nsPresContext* context = presShell->GetPresContext();
1075 nsRootPresContext* rootContext = context->GetRootPresContext();
1076 if (rootContext) {
1077 rootContext->NotifyDidPaintForSubtree(aTransactionId, aCompositeEnd);
1080 mozilla::StartupTimeline::RecordOnce(mozilla::StartupTimeline::FIRST_PAINT2,
1081 aCompositeEnd);
1083 // If the two timestamps are identical, this was likely a fake composite
1084 // event which wouldn't be terribly useful to display.
1085 if (aCompositeStart == aCompositeEnd) {
1086 return;
1089 nsIDocShell* docShell = context->GetDocShell();
1090 RefPtr<TimelineConsumers> timelines = TimelineConsumers::Get();
1092 if (timelines && timelines->HasConsumer(docShell)) {
1093 timelines->AddMarkerForDocShell(
1094 docShell, MakeUnique<CompositeTimelineMarker>(
1095 aCompositeStart, MarkerTracingType::START));
1096 timelines->AddMarkerForDocShell(
1097 docShell, MakeUnique<CompositeTimelineMarker>(aCompositeEnd,
1098 MarkerTracingType::END));
1102 void nsView::RequestRepaint() {
1103 PresShell* presShell = mViewManager->GetPresShell();
1104 if (presShell) {
1105 presShell->ScheduleViewManagerFlush();
1109 bool nsView::ShouldNotBeVisible() {
1110 if (mFrame && mFrame->IsMenuPopupFrame()) {
1111 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
1112 return !pm || !pm->IsPopupOpen(mFrame->GetContent());
1115 return false;
1118 nsEventStatus nsView::HandleEvent(WidgetGUIEvent* aEvent,
1119 bool aUseAttachedEvents) {
1120 MOZ_ASSERT(nullptr != aEvent->mWidget, "null widget ptr");
1122 nsEventStatus result = nsEventStatus_eIgnore;
1123 nsView* view;
1124 if (aUseAttachedEvents) {
1125 nsIWidgetListener* listener = aEvent->mWidget->GetAttachedWidgetListener();
1126 view = listener ? listener->GetView() : nullptr;
1127 } else {
1128 view = GetViewFor(aEvent->mWidget);
1131 if (view) {
1132 RefPtr<nsViewManager> vm = view->GetViewManager();
1133 vm->DispatchEvent(aEvent, view, &result);
1136 return result;
1139 void nsView::SafeAreaInsetsChanged(const ScreenIntMargin& aSafeAreaInsets) {
1140 if (!IsRoot()) {
1141 return;
1144 PresShell* presShell = mViewManager->GetPresShell();
1145 if (!presShell) {
1146 return;
1149 ScreenIntMargin windowSafeAreaInsets;
1150 LayoutDeviceIntRect windowRect = mWindow->GetScreenBounds();
1151 nsCOMPtr<nsIScreen> screen = mWindow->GetWidgetScreen();
1152 if (screen) {
1153 windowSafeAreaInsets = nsContentUtils::GetWindowSafeAreaInsets(
1154 screen, aSafeAreaInsets, windowRect);
1157 presShell->GetPresContext()->SetSafeAreaInsets(windowSafeAreaInsets);
1159 // https://github.com/w3c/csswg-drafts/issues/4670
1160 // Actually we don't set this value on sub document. This behaviour is
1161 // same as Blink.
1163 dom::Document* document = presShell->GetDocument();
1164 if (!document) {
1165 return;
1168 nsPIDOMWindowOuter* window = document->GetWindow();
1169 if (!window) {
1170 return;
1173 nsContentUtils::CallOnAllRemoteChildren(
1174 window,
1175 [windowSafeAreaInsets](dom::BrowserParent* aBrowserParent) -> CallState {
1176 Unused << aBrowserParent->SendSafeAreaInsetsChanged(
1177 windowSafeAreaInsets);
1178 return CallState::Continue;
1182 bool nsView::IsPrimaryFramePaintSuppressed() {
1183 return StaticPrefs::layout_show_previous_page() && mFrame &&
1184 mFrame->PresShell()->IsPaintingSuppressed();