Bug 1732409 let fake:true getUserMedia() parameter override loopback prefs r=jib
[gecko.git] / view / nsView.cpp
bloba86ef0494ccd18ee681c5b3114da943a6b48f839
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 mZIndex(0),
40 mVis(aVisibility),
41 mPosX(0),
42 mPosY(0),
43 mVFlags(0),
44 mWidgetIsTopLevel(false),
45 mForcedRepaint(false),
46 mNeedsWindowPropertiesSync(false) {
47 MOZ_COUNT_CTOR(nsView);
49 // Views should be transparent by default. Not being transparent is
50 // a promise that the view will paint all its pixels opaquely. Views
51 // should make this promise explicitly by calling
52 // SetViewContentTransparency.
55 void nsView::DropMouseGrabbing() {
56 if (mViewManager->GetPresShell()) {
57 PresShell::ClearMouseCaptureOnView(this);
61 nsView::~nsView() {
62 MOZ_COUNT_DTOR(nsView);
64 while (GetFirstChild()) {
65 nsView* child = GetFirstChild();
66 if (child->GetViewManager() == mViewManager) {
67 child->Destroy();
68 } else {
69 // just unhook it. Someone else will want to destroy this.
70 RemoveChild(child);
74 if (mViewManager) {
75 DropMouseGrabbing();
77 nsView* rootView = mViewManager->GetRootView();
79 if (rootView) {
80 // Root views can have parents!
81 if (mParent) {
82 mViewManager->RemoveChild(this);
85 if (rootView == this) {
86 // Inform the view manager that the root view has gone away...
87 mViewManager->SetRootView(nullptr);
89 } else if (mParent) {
90 mParent->RemoveChild(this);
93 mViewManager = nullptr;
94 } else if (mParent) {
95 mParent->RemoveChild(this);
98 if (mPreviousWindow) {
99 mPreviousWindow->SetPreviouslyAttachedWidgetListener(nullptr);
102 // Destroy and release the widget
103 DestroyWidget();
105 MOZ_RELEASE_ASSERT(!mFrame);
108 class DestroyWidgetRunnable : public Runnable {
109 public:
110 NS_DECL_NSIRUNNABLE
112 explicit DestroyWidgetRunnable(nsIWidget* aWidget)
113 : mozilla::Runnable("DestroyWidgetRunnable"), mWidget(aWidget) {}
115 private:
116 nsCOMPtr<nsIWidget> mWidget;
119 NS_IMETHODIMP DestroyWidgetRunnable::Run() {
120 mWidget->Destroy();
121 mWidget = nullptr;
122 return NS_OK;
125 void nsView::DestroyWidget() {
126 if (mWindow) {
127 // If we are not attached to a base window, we're going to tear down our
128 // widget here. However, if we're attached to somebody elses widget, we
129 // want to leave the widget alone: don't reset the client data or call
130 // Destroy. Just clear our event view ptr and free our reference to it.
131 if (mWidgetIsTopLevel) {
132 mWindow->SetAttachedWidgetListener(nullptr);
133 } else {
134 mWindow->SetWidgetListener(nullptr);
136 nsCOMPtr<nsIRunnable> widgetDestroyer =
137 new DestroyWidgetRunnable(mWindow);
139 // Don't leak if we happen to arrive here after the main thread
140 // has disappeared.
141 nsCOMPtr<nsIThread> mainThread = do_GetMainThread();
142 if (mainThread) {
143 mainThread->Dispatch(widgetDestroyer.forget(), NS_DISPATCH_NORMAL);
147 mWindow = nullptr;
151 nsView* nsView::GetViewFor(const nsIWidget* aWidget) {
152 MOZ_ASSERT(aWidget, "null widget ptr");
154 nsIWidgetListener* listener = aWidget->GetWidgetListener();
155 if (listener) {
156 if (nsView* view = listener->GetView()) {
157 return view;
161 listener = aWidget->GetAttachedWidgetListener();
162 return listener ? listener->GetView() : nullptr;
165 void nsView::Destroy() {
166 this->~nsView();
167 mozWritePoison(this, sizeof(*this));
168 nsView::operator delete(this);
171 void nsView::SetPosition(nscoord aX, nscoord aY) {
172 mDimBounds.MoveBy(aX - mPosX, aY - mPosY);
173 mPosX = aX;
174 mPosY = aY;
176 NS_ASSERTION(GetParent() || (aX == 0 && aY == 0),
177 "Don't try to move the root widget to something non-zero");
179 ResetWidgetBounds(true, false);
182 void nsView::ResetWidgetBounds(bool aRecurse, bool aForceSync) {
183 if (mWindow) {
184 if (!aForceSync) {
185 // Don't change widget geometry synchronously, since that can
186 // cause synchronous painting.
187 mViewManager->PostPendingUpdate();
188 } else {
189 DoResetWidgetBounds(false, true);
191 return;
194 if (aRecurse) {
195 // reposition any widgets under this view
196 for (nsView* v = GetFirstChild(); v; v = v->GetNextSibling()) {
197 v->ResetWidgetBounds(true, aForceSync);
202 bool nsView::IsEffectivelyVisible() {
203 for (nsView* v = this; v; v = v->mParent) {
204 if (v->GetVisibility() == nsViewVisibility_kHide) return false;
206 return true;
209 LayoutDeviceIntRect nsView::CalcWidgetBounds(nsWindowType aType) {
210 int32_t p2a = mViewManager->AppUnitsPerDevPixel();
212 nsRect viewBounds(mDimBounds);
214 nsView* parent = GetParent();
215 nsIWidget* parentWidget = nullptr;
216 if (parent) {
217 nsPoint offset;
218 parentWidget = parent->GetNearestWidget(&offset, p2a);
219 // make viewBounds be relative to the parent widget, in appunits
220 viewBounds += offset;
222 if (parentWidget && aType == eWindowType_popup && IsEffectivelyVisible()) {
223 // put offset into screen coordinates. (based on client area origin)
224 LayoutDeviceIntPoint screenPoint = parentWidget->WidgetToScreenOffset();
225 viewBounds += nsPoint(NSIntPixelsToAppUnits(screenPoint.x, p2a),
226 NSIntPixelsToAppUnits(screenPoint.y, p2a));
230 // Compute widget bounds in device pixels
231 LayoutDeviceIntRect newBounds =
232 LayoutDeviceIntRect::FromUnknownRect(viewBounds.ToNearestPixels(p2a));
234 #if defined(XP_MACOSX) || defined(MOZ_WIDGET_GTK)
235 // cocoa and GTK round widget coordinates to the nearest global "display
236 // pixel" integer value. So we avoid fractional display pixel values by
237 // rounding to the nearest value that won't yield a fractional display pixel.
238 nsIWidget* widget = parentWidget ? parentWidget : mWindow.get();
239 uint32_t round;
240 if (aType == eWindowType_popup && widget &&
241 ((round = widget->RoundsWidgetCoordinatesTo()) > 1)) {
242 LayoutDeviceIntSize pixelRoundedSize = newBounds.Size();
243 // round the top left and bottom right to the nearest round pixel
244 newBounds.x =
245 NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.x, p2a) / round) *
246 round;
247 newBounds.y =
248 NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.y, p2a) / round) *
249 round;
250 newBounds.width =
251 NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.XMost(), p2a) /
252 round) *
253 round -
254 newBounds.x;
255 newBounds.height =
256 NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.YMost(), p2a) /
257 round) *
258 round -
259 newBounds.y;
260 // but if that makes the widget larger then our frame may not paint the
261 // extra pixels, so reduce the size to the nearest round value
262 if (newBounds.width > pixelRoundedSize.width) {
263 newBounds.width -= round;
265 if (newBounds.height > pixelRoundedSize.height) {
266 newBounds.height -= round;
269 #endif
271 // Compute where the top-left of our widget ended up relative to the parent
272 // widget, in appunits.
273 nsPoint roundedOffset(NSIntPixelsToAppUnits(newBounds.X(), p2a),
274 NSIntPixelsToAppUnits(newBounds.Y(), p2a));
276 // mViewToWidgetOffset is added to coordinates relative to the view origin
277 // to get coordinates relative to the widget.
278 // The view origin, relative to the parent widget, is at
279 // (mPosX,mPosY) - mDimBounds.TopLeft() + viewBounds.TopLeft().
280 // Our widget, relative to the parent widget, is roundedOffset.
281 mViewToWidgetOffset = nsPoint(mPosX, mPosY) - mDimBounds.TopLeft() +
282 viewBounds.TopLeft() - roundedOffset;
284 return newBounds;
287 void nsView::DoResetWidgetBounds(bool aMoveOnly, bool aInvalidateChangedSize) {
288 // The geometry of a root view's widget is controlled externally,
289 // NOT by sizing or positioning the view
290 if (mViewManager->GetRootView() == this) {
291 return;
294 MOZ_ASSERT(mWindow, "Why was this called??");
296 // Hold this ref to make sure it stays alive.
297 nsCOMPtr<nsIWidget> widget = mWindow;
299 // Stash a copy of these and use them so we can handle this being deleted (say
300 // from sync painting/flushing from Show/Move/Resize on the widget).
301 LayoutDeviceIntRect newBounds;
303 nsWindowType type = widget->WindowType();
305 LayoutDeviceIntRect curBounds = widget->GetClientBounds();
306 bool invisiblePopup = type == eWindowType_popup &&
307 ((curBounds.IsEmpty() && mDimBounds.IsEmpty()) ||
308 mVis == nsViewVisibility_kHide);
310 if (invisiblePopup) {
311 // We're going to hit the early exit below, avoid calling CalcWidgetBounds.
312 } else {
313 newBounds = CalcWidgetBounds(type);
314 invisiblePopup = newBounds.IsEmpty();
317 bool curVisibility = widget->IsVisible();
318 bool newVisibility = !invisiblePopup && IsEffectivelyVisible();
319 if (curVisibility && !newVisibility) {
320 widget->Show(false);
323 if (invisiblePopup) {
324 // Don't manipulate empty or hidden popup widgets. For example there's no
325 // point moving hidden comboboxes around, or doing X server roundtrips
326 // to compute their true screen position. This could mean that
327 // WidgetToScreen operations on these widgets don't return up-to-date
328 // values, but popup positions aren't reliable anyway because of correction
329 // to be on or off-screen.
330 return;
333 // Apply the widget size constraints to newBounds.
334 widget->ConstrainSize(&newBounds.width, &newBounds.height);
336 bool changedPos = curBounds.TopLeft() != newBounds.TopLeft();
337 bool changedSize = curBounds.Size() != newBounds.Size();
339 // Child views are never attached to top level widgets, this is safe.
341 // Coordinates are converted to desktop pixels for window Move/Resize APIs,
342 // because of the potential for device-pixel coordinate spaces for mixed
343 // hidpi/lodpi screens to overlap each other and result in bad placement
344 // (bug 814434).
346 DesktopToLayoutDeviceScale scale = widget->GetDesktopToDeviceScaleByScreen();
348 DesktopRect deskRect = newBounds / scale;
349 if (changedPos) {
350 if (changedSize && !aMoveOnly) {
351 widget->ResizeClient(deskRect, aInvalidateChangedSize);
352 } else {
353 widget->MoveClient(deskRect.TopLeft());
355 } else {
356 if (changedSize && !aMoveOnly) {
357 widget->ResizeClient(deskRect.Size(), aInvalidateChangedSize);
358 } // else do nothing!
361 if (!curVisibility && newVisibility) {
362 widget->Show(true);
366 void nsView::SetDimensions(const nsRect& aRect, bool aPaint,
367 bool aResizeWidget) {
368 nsRect dims = aRect;
369 dims.MoveBy(mPosX, mPosY);
371 // Don't use nsRect's operator== here, since it returns true when
372 // both rects are empty even if they have different widths and we
373 // have cases where that sort of thing matters to us.
374 if (mDimBounds.TopLeft() == dims.TopLeft() &&
375 mDimBounds.Size() == dims.Size()) {
376 return;
379 mDimBounds = dims;
381 if (aResizeWidget) {
382 ResetWidgetBounds(false, false);
386 void nsView::NotifyEffectiveVisibilityChanged(bool aEffectivelyVisible) {
387 if (!aEffectivelyVisible) {
388 DropMouseGrabbing();
391 SetForcedRepaint(true);
393 if (nullptr != mWindow) {
394 ResetWidgetBounds(false, false);
397 for (nsView* child = mFirstChild; child; child = child->mNextSibling) {
398 if (child->mVis == nsViewVisibility_kHide) {
399 // It was effectively hidden and still is
400 continue;
402 // Our child is visible if we are
403 child->NotifyEffectiveVisibilityChanged(aEffectivelyVisible);
407 void nsView::SetVisibility(nsViewVisibility aVisibility) {
408 mVis = aVisibility;
409 NotifyEffectiveVisibilityChanged(IsEffectivelyVisible());
412 void nsView::SetFloating(bool aFloatingView) {
413 if (aFloatingView)
414 mVFlags |= NS_VIEW_FLAG_FLOATING;
415 else
416 mVFlags &= ~NS_VIEW_FLAG_FLOATING;
419 void nsView::InvalidateHierarchy() {
420 if (mViewManager->GetRootView() == this) mViewManager->InvalidateHierarchy();
422 for (nsView* child = mFirstChild; child; child = child->GetNextSibling())
423 child->InvalidateHierarchy();
426 void nsView::InsertChild(nsView* aChild, nsView* aSibling) {
427 MOZ_ASSERT(nullptr != aChild, "null ptr");
429 if (nullptr != aChild) {
430 if (nullptr != aSibling) {
431 #ifdef DEBUG
432 NS_ASSERTION(aSibling->GetParent() == this,
433 "tried to insert view with invalid sibling");
434 #endif
435 // insert after sibling
436 aChild->SetNextSibling(aSibling->GetNextSibling());
437 aSibling->SetNextSibling(aChild);
438 } else {
439 aChild->SetNextSibling(mFirstChild);
440 mFirstChild = aChild;
442 aChild->SetParent(this);
444 // If we just inserted a root view, then update the RootViewManager
445 // on all view managers in the new subtree.
447 nsViewManager* vm = aChild->GetViewManager();
448 if (vm->GetRootView() == aChild) {
449 aChild->InvalidateHierarchy();
454 void nsView::RemoveChild(nsView* child) {
455 MOZ_ASSERT(nullptr != child, "null ptr");
457 if (nullptr != child) {
458 nsView* prevKid = nullptr;
459 nsView* kid = mFirstChild;
460 DebugOnly<bool> found = false;
461 while (nullptr != kid) {
462 if (kid == child) {
463 if (nullptr != prevKid) {
464 prevKid->SetNextSibling(kid->GetNextSibling());
465 } else {
466 mFirstChild = kid->GetNextSibling();
468 child->SetParent(nullptr);
469 found = true;
470 break;
472 prevKid = kid;
473 kid = kid->GetNextSibling();
475 NS_ASSERTION(found, "tried to remove non child");
477 // If we just removed a root view, then update the RootViewManager
478 // on all view managers in the removed subtree.
480 nsViewManager* vm = child->GetViewManager();
481 if (vm->GetRootView() == child) {
482 child->InvalidateHierarchy();
487 // Native widgets ultimately just can't deal with the awesome power of
488 // CSS2 z-index. However, we set the z-index on the widget anyway
489 // because in many simple common cases the widgets do end up in the
490 // right order. We set each widget's z-index to the z-index of the
491 // nearest ancestor that has non-auto z-index.
492 static void UpdateNativeWidgetZIndexes(nsView* aView, int32_t aZIndex) {
493 if (aView->HasWidget()) {
494 nsIWidget* widget = aView->GetWidget();
495 if (widget->GetZIndex() != aZIndex) {
496 widget->SetZIndex(aZIndex);
498 } else {
499 for (nsView* v = aView->GetFirstChild(); v; v = v->GetNextSibling()) {
500 if (v->GetZIndexIsAuto()) {
501 UpdateNativeWidgetZIndexes(v, aZIndex);
507 static int32_t FindNonAutoZIndex(nsView* aView) {
508 while (aView) {
509 if (!aView->GetZIndexIsAuto()) {
510 return aView->GetZIndex();
512 aView = aView->GetParent();
514 return 0;
517 struct DefaultWidgetInitData : public nsWidgetInitData {
518 DefaultWidgetInitData() : nsWidgetInitData() {
519 mWindowType = eWindowType_child;
520 clipChildren = true;
521 clipSiblings = true;
525 nsresult nsView::CreateWidget(nsWidgetInitData* aWidgetInitData,
526 bool aEnableDragDrop, bool aResetVisibility) {
527 AssertNoWindow();
528 MOZ_ASSERT(
529 !aWidgetInitData || aWidgetInitData->mWindowType != eWindowType_popup,
530 "Use CreateWidgetForPopup");
532 DefaultWidgetInitData defaultInitData;
533 aWidgetInitData = aWidgetInitData ? aWidgetInitData : &defaultInitData;
534 LayoutDeviceIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
536 nsIWidget* parentWidget =
537 GetParent() ? GetParent()->GetNearestWidget(nullptr) : nullptr;
538 if (!parentWidget) {
539 NS_ERROR("nsView::CreateWidget without suitable parent widget??");
540 return NS_ERROR_FAILURE;
543 // XXX: using aForceUseIWidgetParent=true to preserve previous
544 // semantics. It's not clear that it's actually needed.
545 mWindow = parentWidget->CreateChild(trect, aWidgetInitData, true);
546 if (!mWindow) {
547 return NS_ERROR_FAILURE;
550 InitializeWindow(aEnableDragDrop, aResetVisibility);
552 return NS_OK;
555 nsresult nsView::CreateWidgetForParent(nsIWidget* aParentWidget,
556 nsWidgetInitData* aWidgetInitData,
557 bool aEnableDragDrop,
558 bool aResetVisibility) {
559 AssertNoWindow();
560 MOZ_ASSERT(
561 !aWidgetInitData || aWidgetInitData->mWindowType != eWindowType_popup,
562 "Use CreateWidgetForPopup");
563 MOZ_ASSERT(aParentWidget, "Parent widget required");
565 DefaultWidgetInitData defaultInitData;
566 aWidgetInitData = aWidgetInitData ? aWidgetInitData : &defaultInitData;
568 LayoutDeviceIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
570 mWindow = aParentWidget->CreateChild(trect, aWidgetInitData);
571 if (!mWindow) {
572 return NS_ERROR_FAILURE;
575 InitializeWindow(aEnableDragDrop, aResetVisibility);
577 return NS_OK;
580 nsresult nsView::CreateWidgetForPopup(nsWidgetInitData* aWidgetInitData,
581 nsIWidget* aParentWidget,
582 bool aEnableDragDrop,
583 bool aResetVisibility) {
584 AssertNoWindow();
585 MOZ_ASSERT(aWidgetInitData, "Widget init data required");
586 MOZ_ASSERT(aWidgetInitData->mWindowType == eWindowType_popup,
587 "Use one of the other CreateWidget methods");
589 LayoutDeviceIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
591 // XXX/cjones: having these two separate creation cases seems ... um
592 // ... unnecessary, but it's the way the old code did it. Please
593 // unify them by first finding a suitable parent nsIWidget, then
594 // getting rid of aForceUseIWidgetParent.
595 if (aParentWidget) {
596 // XXX: using aForceUseIWidgetParent=true to preserve previous
597 // semantics. It's not clear that it's actually needed.
598 mWindow = aParentWidget->CreateChild(trect, aWidgetInitData, true);
599 } else {
600 nsIWidget* nearestParent =
601 GetParent() ? GetParent()->GetNearestWidget(nullptr) : nullptr;
602 if (!nearestParent) {
603 // Without a parent, we can't make a popup. This can happen
604 // when printing
605 return NS_ERROR_FAILURE;
608 mWindow = nearestParent->CreateChild(trect, aWidgetInitData);
610 if (!mWindow) {
611 return NS_ERROR_FAILURE;
614 InitializeWindow(aEnableDragDrop, aResetVisibility);
616 return NS_OK;
619 void nsView::InitializeWindow(bool aEnableDragDrop, bool aResetVisibility) {
620 MOZ_ASSERT(mWindow, "Must have a window to initialize");
622 mWindow->SetWidgetListener(this);
624 if (aEnableDragDrop) {
625 mWindow->EnableDragDrop(true);
628 // propagate the z-index to the widget.
629 UpdateNativeWidgetZIndexes(this, FindNonAutoZIndex(this));
631 // make sure visibility state is accurate
633 if (aResetVisibility) {
634 SetVisibility(GetVisibility());
638 void nsView::SetNeedsWindowPropertiesSync() {
639 mNeedsWindowPropertiesSync = true;
640 if (mViewManager) {
641 mViewManager->PostPendingUpdate();
645 // Attach to a top level widget and start receiving mirrored events.
646 nsresult nsView::AttachToTopLevelWidget(nsIWidget* aWidget) {
647 MOZ_ASSERT(nullptr != aWidget, "null widget ptr");
649 /// XXXjimm This is a temporary workaround to an issue w/document
650 // viewer (bug 513162).
651 nsIWidgetListener* listener = aWidget->GetAttachedWidgetListener();
652 if (listener) {
653 nsView* oldView = listener->GetView();
654 if (oldView) {
655 oldView->DetachFromTopLevelWidget();
659 // Note, the previous device context will be released. Detaching
660 // will not restore the old one.
661 aWidget->AttachViewToTopLevel(!nsIWidget::UsePuppetWidgets());
663 mWindow = aWidget;
665 mWindow->SetAttachedWidgetListener(this);
666 if (mWindow->WindowType() != eWindowType_invisible) {
667 nsresult rv = mWindow->AsyncEnableDragDrop(true);
668 NS_ENSURE_SUCCESS(rv, rv);
670 mWidgetIsTopLevel = true;
672 // Refresh the view bounds
673 CalcWidgetBounds(mWindow->WindowType());
675 return NS_OK;
678 // Detach this view from an attached widget.
679 nsresult nsView::DetachFromTopLevelWidget() {
680 MOZ_ASSERT(mWidgetIsTopLevel, "Not attached currently!");
681 MOZ_ASSERT(mWindow, "null mWindow for DetachFromTopLevelWidget!");
683 mWindow->SetAttachedWidgetListener(nullptr);
684 nsIWidgetListener* listener = mWindow->GetPreviouslyAttachedWidgetListener();
686 if (listener && listener->GetView()) {
687 // Ensure the listener doesn't think it's being used anymore
688 listener->GetView()->SetPreviousWidget(nullptr);
691 // If the new view's frame is paint suppressed then the window
692 // will want to use us instead until that's done
693 mWindow->SetPreviouslyAttachedWidgetListener(this);
695 mPreviousWindow = mWindow;
696 mWindow = nullptr;
698 mWidgetIsTopLevel = false;
700 return NS_OK;
703 void nsView::SetZIndex(bool aAuto, int32_t aZIndex) {
704 bool oldIsAuto = GetZIndexIsAuto();
705 mVFlags = (mVFlags & ~NS_VIEW_FLAG_AUTO_ZINDEX) |
706 (aAuto ? NS_VIEW_FLAG_AUTO_ZINDEX : 0);
707 mZIndex = aZIndex;
709 if (HasWidget() || !oldIsAuto || !aAuto) {
710 UpdateNativeWidgetZIndexes(this, FindNonAutoZIndex(this));
714 void nsView::AssertNoWindow() {
715 // XXX: it would be nice to make this a strong assert
716 if (MOZ_UNLIKELY(mWindow)) {
717 NS_ERROR("We already have a window for this view? BAD");
718 mWindow->SetWidgetListener(nullptr);
719 mWindow->Destroy();
720 mWindow = nullptr;
725 // internal window creation functions
727 void nsView::AttachWidgetEventHandler(nsIWidget* aWidget) {
728 #ifdef DEBUG
729 NS_ASSERTION(!aWidget->GetWidgetListener(), "Already have a widget listener");
730 #endif
732 aWidget->SetWidgetListener(this);
735 void nsView::DetachWidgetEventHandler(nsIWidget* aWidget) {
736 NS_ASSERTION(!aWidget->GetWidgetListener() ||
737 aWidget->GetWidgetListener()->GetView() == this,
738 "Wrong view");
739 aWidget->SetWidgetListener(nullptr);
742 #ifdef DEBUG
743 void nsView::List(FILE* out, int32_t aIndent) const {
744 int32_t i;
745 for (i = aIndent; --i >= 0;) fputs(" ", out);
746 fprintf(out, "%p ", (void*)this);
747 if (nullptr != mWindow) {
748 nscoord p2a = mViewManager->AppUnitsPerDevPixel();
749 LayoutDeviceIntRect rect = mWindow->GetClientBounds();
750 nsRect windowBounds = LayoutDeviceIntRect::ToAppUnits(rect, p2a);
751 rect = mWindow->GetBounds();
752 nsRect nonclientBounds = LayoutDeviceIntRect::ToAppUnits(rect, p2a);
753 nsrefcnt widgetRefCnt = mWindow.get()->AddRef() - 1;
754 mWindow.get()->Release();
755 int32_t Z = mWindow->GetZIndex();
756 fprintf(out, "(widget=%p[%" PRIuPTR "] z=%d pos={%d,%d,%d,%d}) ",
757 (void*)mWindow, widgetRefCnt, Z, nonclientBounds.X(),
758 nonclientBounds.Y(), windowBounds.Width(), windowBounds.Height());
760 nsRect brect = GetBounds();
761 fprintf(out, "{%d,%d,%d,%d} @ %d,%d", brect.X(), brect.Y(), brect.Width(),
762 brect.Height(), mPosX, mPosY);
763 fprintf(out, " flags=%x z=%d vis=%d frame=%p <\n", mVFlags, mZIndex, mVis,
764 static_cast<void*>(mFrame));
765 for (nsView* kid = mFirstChild; kid; kid = kid->GetNextSibling()) {
766 NS_ASSERTION(kid->GetParent() == this, "incorrect parent");
767 kid->List(out, aIndent + 1);
769 for (i = aIndent; --i >= 0;) fputs(" ", out);
770 fputs(">\n", out);
772 #endif // DEBUG
774 nsPoint nsView::GetOffsetTo(const nsView* aOther) const {
775 return GetOffsetTo(aOther, GetViewManager()->AppUnitsPerDevPixel());
778 nsPoint nsView::GetOffsetTo(const nsView* aOther, const int32_t aAPD) const {
779 MOZ_ASSERT(GetParent() || !aOther || aOther->GetParent() || this == aOther,
780 "caller of (outer) GetOffsetTo must not pass unrelated views");
781 // We accumulate the final result in offset
782 nsPoint offset(0, 0);
783 // The offset currently accumulated at the current APD
784 nsPoint docOffset(0, 0);
785 const nsView* v = this;
786 nsViewManager* currVM = v->GetViewManager();
787 int32_t currAPD = currVM->AppUnitsPerDevPixel();
788 const nsView* root = nullptr;
789 for (; v != aOther && v; root = v, v = v->GetParent()) {
790 nsViewManager* newVM = v->GetViewManager();
791 if (newVM != currVM) {
792 int32_t newAPD = newVM->AppUnitsPerDevPixel();
793 if (newAPD != currAPD) {
794 offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
795 docOffset.x = docOffset.y = 0;
796 currAPD = newAPD;
798 currVM = newVM;
800 docOffset += v->GetPosition();
802 offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
804 if (v != aOther) {
805 // Looks like aOther wasn't an ancestor of |this|. So now we have
806 // the root-VM-relative position of |this| in |offset|. Get the
807 // root-VM-relative position of aOther and subtract it.
808 nsPoint negOffset = aOther->GetOffsetTo(root, aAPD);
809 offset -= negOffset;
812 return offset;
815 nsPoint nsView::GetOffsetToWidget(nsIWidget* aWidget) const {
816 nsPoint pt;
817 // Get the view for widget
818 nsView* widgetView = GetViewFor(aWidget);
819 if (!widgetView) {
820 return pt;
823 // Get the offset to the widget view in the widget view's APD
824 // We get the offset in the widget view's APD first and then convert to our
825 // APD afterwards so that we can include the widget view's ViewToWidgetOffset
826 // in the sum in its native APD, and then convert the whole thing to our APD
827 // so that we don't have to convert the APD of the relatively small
828 // ViewToWidgetOffset by itself with a potentially large relative rounding
829 // error.
830 pt = -widgetView->GetOffsetTo(this);
831 // Add in the offset to the widget.
832 pt += widgetView->ViewToWidgetOffset();
834 // Convert to our appunits.
835 int32_t widgetAPD = widgetView->GetViewManager()->AppUnitsPerDevPixel();
836 int32_t ourAPD = GetViewManager()->AppUnitsPerDevPixel();
837 pt = pt.ScaleToOtherAppUnits(widgetAPD, ourAPD);
838 return pt;
841 nsIWidget* nsView::GetNearestWidget(nsPoint* aOffset) const {
842 return GetNearestWidget(aOffset, GetViewManager()->AppUnitsPerDevPixel());
845 nsIWidget* nsView::GetNearestWidget(nsPoint* aOffset,
846 const int32_t aAPD) const {
847 // aOffset is based on the view's position, which ignores any chrome on
848 // attached parent widgets.
850 // We accumulate the final result in pt
851 nsPoint pt(0, 0);
852 // The offset currently accumulated at the current APD
853 nsPoint docPt(0, 0);
854 const nsView* v = this;
855 nsViewManager* currVM = v->GetViewManager();
856 int32_t currAPD = currVM->AppUnitsPerDevPixel();
857 for (; v && !v->HasWidget(); v = v->GetParent()) {
858 nsViewManager* newVM = v->GetViewManager();
859 if (newVM != currVM) {
860 int32_t newAPD = newVM->AppUnitsPerDevPixel();
861 if (newAPD != currAPD) {
862 pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
863 docPt.x = docPt.y = 0;
864 currAPD = newAPD;
866 currVM = newVM;
868 docPt += v->GetPosition();
870 if (!v) {
871 if (aOffset) {
872 pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
873 *aOffset = pt;
875 return nullptr;
878 // pt is now the offset from v's origin to this view's origin.
879 // We add the ViewToWidgetOffset to get the offset to the widget.
880 if (aOffset) {
881 docPt += v->ViewToWidgetOffset();
882 pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
883 *aOffset = pt;
885 return v->GetWidget();
888 bool nsView::IsRoot() const {
889 NS_ASSERTION(mViewManager != nullptr,
890 " View manager is null in nsView::IsRoot()");
891 return mViewManager->GetRootView() == this;
894 nsRect nsView::GetBoundsInParentUnits() const {
895 nsView* parent = GetParent();
896 nsViewManager* VM = GetViewManager();
897 if (this != VM->GetRootView() || !parent) {
898 return mDimBounds;
900 int32_t ourAPD = VM->AppUnitsPerDevPixel();
901 int32_t parentAPD = parent->GetViewManager()->AppUnitsPerDevPixel();
902 return mDimBounds.ScaleToOtherAppUnitsRoundOut(ourAPD, parentAPD);
905 nsPoint nsView::ConvertFromParentCoords(nsPoint aPt) const {
906 const nsView* parent = GetParent();
907 if (parent) {
908 aPt = aPt.ScaleToOtherAppUnits(
909 parent->GetViewManager()->AppUnitsPerDevPixel(),
910 GetViewManager()->AppUnitsPerDevPixel());
912 aPt -= GetPosition();
913 return aPt;
916 static bool IsPopupWidget(nsIWidget* aWidget) {
917 return (aWidget->WindowType() == eWindowType_popup);
920 PresShell* nsView::GetPresShell() { return GetViewManager()->GetPresShell(); }
922 bool nsView::WindowMoved(nsIWidget* aWidget, int32_t x, int32_t y) {
923 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
924 if (pm && IsPopupWidget(aWidget)) {
925 pm->PopupMoved(mFrame, nsIntPoint(x, y));
926 return true;
929 return false;
932 bool nsView::WindowResized(nsIWidget* aWidget, int32_t aWidth,
933 int32_t aHeight) {
934 // The root view may not be set if this is the resize associated with
935 // window creation
936 SetForcedRepaint(true);
937 if (this == mViewManager->GetRootView()) {
938 RefPtr<nsDeviceContext> devContext = mViewManager->GetDeviceContext();
939 // ensure DPI is up-to-date, in case of window being opened and sized
940 // on a non-default-dpi display (bug 829963)
941 devContext->CheckDPIChange();
942 int32_t p2a = devContext->AppUnitsPerDevPixel();
943 mViewManager->SetWindowDimensions(NSIntPixelsToAppUnits(aWidth, p2a),
944 NSIntPixelsToAppUnits(aHeight, p2a));
946 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
947 if (pm) {
948 PresShell* presShell = mViewManager->GetPresShell();
949 if (presShell && presShell->GetDocument()) {
950 pm->AdjustPopupsOnWindowChange(presShell);
954 return true;
956 if (IsPopupWidget(aWidget)) {
957 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
958 if (pm) {
959 pm->PopupResized(mFrame, LayoutDeviceIntSize(aWidth, aHeight));
960 return true;
964 return false;
967 #if defined(MOZ_WIDGET_ANDROID)
968 void nsView::DynamicToolbarMaxHeightChanged(ScreenIntCoord aHeight) {
969 MOZ_ASSERT(XRE_IsParentProcess(),
970 "Should be only called for the browser parent process");
971 MOZ_ASSERT(this == mViewManager->GetRootView(),
972 "Should be called for the root view");
974 PresShell* presShell = mViewManager->GetPresShell();
975 if (!presShell) {
976 return;
979 dom::Document* document = presShell->GetDocument();
980 if (!document) {
981 return;
984 nsPIDOMWindowOuter* window = document->GetWindow();
985 if (!window) {
986 return;
989 nsContentUtils::CallOnAllRemoteChildren(
990 window, [&aHeight](dom::BrowserParent* aBrowserParent) -> CallState {
991 aBrowserParent->DynamicToolbarMaxHeightChanged(aHeight);
992 return CallState::Continue;
996 void nsView::DynamicToolbarOffsetChanged(ScreenIntCoord aOffset) {
997 MOZ_ASSERT(XRE_IsParentProcess(),
998 "Should be only called for the browser parent process");
999 MOZ_ASSERT(this == mViewManager->GetRootView(),
1000 "Should be called for the root view");
1002 PresShell* presShell = mViewManager->GetPresShell();
1003 if (!presShell) {
1004 return;
1007 dom::Document* document = presShell->GetDocument();
1008 if (!document) {
1009 return;
1012 nsPIDOMWindowOuter* window = document->GetWindow();
1013 if (!window) {
1014 return;
1017 nsContentUtils::CallOnAllRemoteChildren(
1018 window, [&aOffset](dom::BrowserParent* aBrowserParent) -> CallState {
1019 // Skip background tabs.
1020 if (!aBrowserParent->GetDocShellIsActive()) {
1021 return CallState::Continue;
1024 aBrowserParent->DynamicToolbarOffsetChanged(aOffset);
1025 return CallState::Stop;
1028 #endif
1030 bool nsView::RequestWindowClose(nsIWidget* aWidget) {
1031 if (mFrame && IsPopupWidget(aWidget) && mFrame->IsMenuPopupFrame()) {
1032 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
1033 if (pm) {
1034 pm->HidePopup(mFrame->GetContent(), false, true, false, false);
1035 return true;
1039 return false;
1042 void nsView::WillPaintWindow(nsIWidget* aWidget) {
1043 RefPtr<nsViewManager> vm = mViewManager;
1044 vm->WillPaintWindow(aWidget);
1047 bool nsView::PaintWindow(nsIWidget* aWidget, LayoutDeviceIntRegion aRegion) {
1048 NS_ASSERTION(this == nsView::GetViewFor(aWidget), "wrong view for widget?");
1050 RefPtr<nsViewManager> vm = mViewManager;
1051 bool result = vm->PaintWindow(aWidget, aRegion);
1052 return result;
1055 void nsView::DidPaintWindow() {
1056 RefPtr<nsViewManager> vm = mViewManager;
1057 vm->DidPaintWindow();
1060 void nsView::DidCompositeWindow(mozilla::layers::TransactionId aTransactionId,
1061 const TimeStamp& aCompositeStart,
1062 const TimeStamp& aCompositeEnd) {
1063 PresShell* presShell = mViewManager->GetPresShell();
1064 if (!presShell) {
1065 return;
1068 nsAutoScriptBlocker scriptBlocker;
1070 nsPresContext* context = presShell->GetPresContext();
1071 nsRootPresContext* rootContext = context->GetRootPresContext();
1072 if (rootContext) {
1073 rootContext->NotifyDidPaintForSubtree(aTransactionId, aCompositeEnd);
1076 mozilla::StartupTimeline::RecordOnce(mozilla::StartupTimeline::FIRST_PAINT2,
1077 aCompositeEnd);
1079 // If the two timestamps are identical, this was likely a fake composite
1080 // event which wouldn't be terribly useful to display.
1081 if (aCompositeStart == aCompositeEnd) {
1082 return;
1085 nsIDocShell* docShell = context->GetDocShell();
1086 RefPtr<TimelineConsumers> timelines = TimelineConsumers::Get();
1088 if (timelines && timelines->HasConsumer(docShell)) {
1089 timelines->AddMarkerForDocShell(
1090 docShell, MakeUnique<CompositeTimelineMarker>(
1091 aCompositeStart, MarkerTracingType::START));
1092 timelines->AddMarkerForDocShell(
1093 docShell, MakeUnique<CompositeTimelineMarker>(aCompositeEnd,
1094 MarkerTracingType::END));
1098 void nsView::RequestRepaint() {
1099 PresShell* presShell = mViewManager->GetPresShell();
1100 if (presShell) {
1101 presShell->ScheduleViewManagerFlush();
1105 bool nsView::ShouldNotBeVisible() {
1106 if (mFrame && mFrame->IsMenuPopupFrame()) {
1107 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
1108 return !pm || !pm->IsPopupOpen(mFrame->GetContent());
1111 return false;
1114 nsEventStatus nsView::HandleEvent(WidgetGUIEvent* aEvent,
1115 bool aUseAttachedEvents) {
1116 MOZ_ASSERT(nullptr != aEvent->mWidget, "null widget ptr");
1118 nsEventStatus result = nsEventStatus_eIgnore;
1119 nsView* view;
1120 if (aUseAttachedEvents) {
1121 nsIWidgetListener* listener = aEvent->mWidget->GetAttachedWidgetListener();
1122 view = listener ? listener->GetView() : nullptr;
1123 } else {
1124 view = GetViewFor(aEvent->mWidget);
1127 if (view) {
1128 RefPtr<nsViewManager> vm = view->GetViewManager();
1129 vm->DispatchEvent(aEvent, view, &result);
1132 return result;
1135 void nsView::SafeAreaInsetsChanged(const ScreenIntMargin& aSafeAreaInsets) {
1136 if (!IsRoot()) {
1137 return;
1140 PresShell* presShell = mViewManager->GetPresShell();
1141 if (!presShell) {
1142 return;
1145 ScreenIntMargin windowSafeAreaInsets;
1146 LayoutDeviceIntRect windowRect = mWindow->GetScreenBounds();
1147 nsCOMPtr<nsIScreen> screen = mWindow->GetWidgetScreen();
1148 if (screen) {
1149 windowSafeAreaInsets = nsContentUtils::GetWindowSafeAreaInsets(
1150 screen, aSafeAreaInsets, windowRect);
1153 presShell->GetPresContext()->SetSafeAreaInsets(windowSafeAreaInsets);
1155 // https://github.com/w3c/csswg-drafts/issues/4670
1156 // Actually we don't set this value on sub document. This behaviour is
1157 // same as Blink.
1159 dom::Document* document = presShell->GetDocument();
1160 if (!document) {
1161 return;
1164 nsPIDOMWindowOuter* window = document->GetWindow();
1165 if (!window) {
1166 return;
1169 nsContentUtils::CallOnAllRemoteChildren(
1170 window,
1171 [windowSafeAreaInsets](dom::BrowserParent* aBrowserParent) -> CallState {
1172 Unused << aBrowserParent->SendSafeAreaInsetsChanged(
1173 windowSafeAreaInsets);
1174 return CallState::Continue;
1178 bool nsView::IsPrimaryFramePaintSuppressed() {
1179 return StaticPrefs::layout_show_previous_page() && mFrame &&
1180 mFrame->PresShell()->IsPaintingSuppressed();