Bug 1728955: part 5) Add missing `// static` comment to `nsClipboard::CreateNativeDat...
[gecko.git] / view / nsView.cpp
blob38bf0097576d5aa6a6350533f6cf80af316b1b25
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 // Apply the widget size constraints to newBounds.
336 widget->ConstrainSize(&newBounds.width, &newBounds.height);
338 bool changedPos = curBounds.TopLeft() != newBounds.TopLeft();
339 bool changedSize = curBounds.Size() != newBounds.Size();
341 // Child views are never attached to top level widgets, this is safe.
343 // Coordinates are converted to desktop pixels for window Move/Resize APIs,
344 // because of the potential for device-pixel coordinate spaces for mixed
345 // hidpi/lodpi screens to overlap each other and result in bad placement
346 // (bug 814434).
348 DesktopToLayoutDeviceScale scale = widget->GetDesktopToDeviceScaleByScreen();
350 DesktopRect deskRect = newBounds / scale;
351 if (changedPos) {
352 if (changedSize && !aMoveOnly) {
353 widget->ResizeClient(deskRect, aInvalidateChangedSize);
354 } else {
355 widget->MoveClient(deskRect.TopLeft());
357 } else {
358 if (changedSize && !aMoveOnly) {
359 widget->ResizeClient(deskRect.Size(), aInvalidateChangedSize);
360 } // else do nothing!
363 if (!curVisibility && newVisibility) {
364 widget->Show(true);
368 void nsView::SetDimensions(const nsRect& aRect, bool aPaint,
369 bool aResizeWidget) {
370 nsRect dims = aRect;
371 dims.MoveBy(mPosX, mPosY);
373 // Don't use nsRect's operator== here, since it returns true when
374 // both rects are empty even if they have different widths and we
375 // have cases where that sort of thing matters to us.
376 if (mDimBounds.TopLeft() == dims.TopLeft() &&
377 mDimBounds.Size() == dims.Size()) {
378 return;
381 mDimBounds = dims;
383 if (aResizeWidget) {
384 ResetWidgetBounds(false, false);
388 void nsView::NotifyEffectiveVisibilityChanged(bool aEffectivelyVisible) {
389 if (!aEffectivelyVisible) {
390 DropMouseGrabbing();
393 SetForcedRepaint(true);
395 if (nullptr != mWindow) {
396 ResetWidgetBounds(false, false);
399 for (nsView* child = mFirstChild; child; child = child->mNextSibling) {
400 if (child->mVis == nsViewVisibility_kHide) {
401 // It was effectively hidden and still is
402 continue;
404 // Our child is visible if we are
405 child->NotifyEffectiveVisibilityChanged(aEffectivelyVisible);
409 void nsView::SetVisibility(nsViewVisibility aVisibility) {
410 mVis = aVisibility;
411 NotifyEffectiveVisibilityChanged(IsEffectivelyVisible());
414 void nsView::SetFloating(bool aFloatingView) {
415 if (aFloatingView)
416 mVFlags |= NS_VIEW_FLAG_FLOATING;
417 else
418 mVFlags &= ~NS_VIEW_FLAG_FLOATING;
421 void nsView::InvalidateHierarchy() {
422 if (mViewManager->GetRootView() == this) mViewManager->InvalidateHierarchy();
424 for (nsView* child = mFirstChild; child; child = child->GetNextSibling())
425 child->InvalidateHierarchy();
428 void nsView::InsertChild(nsView* aChild, nsView* aSibling) {
429 MOZ_ASSERT(nullptr != aChild, "null ptr");
431 if (nullptr != aChild) {
432 if (nullptr != aSibling) {
433 #ifdef DEBUG
434 NS_ASSERTION(aSibling->GetParent() == this,
435 "tried to insert view with invalid sibling");
436 #endif
437 // insert after sibling
438 aChild->SetNextSibling(aSibling->GetNextSibling());
439 aSibling->SetNextSibling(aChild);
440 } else {
441 aChild->SetNextSibling(mFirstChild);
442 mFirstChild = aChild;
444 aChild->SetParent(this);
446 // If we just inserted a root view, then update the RootViewManager
447 // on all view managers in the new subtree.
449 nsViewManager* vm = aChild->GetViewManager();
450 if (vm->GetRootView() == aChild) {
451 aChild->InvalidateHierarchy();
456 void nsView::RemoveChild(nsView* child) {
457 MOZ_ASSERT(nullptr != child, "null ptr");
459 if (nullptr != child) {
460 nsView* prevKid = nullptr;
461 nsView* kid = mFirstChild;
462 DebugOnly<bool> found = false;
463 while (nullptr != kid) {
464 if (kid == child) {
465 if (nullptr != prevKid) {
466 prevKid->SetNextSibling(kid->GetNextSibling());
467 } else {
468 mFirstChild = kid->GetNextSibling();
470 child->SetParent(nullptr);
471 found = true;
472 break;
474 prevKid = kid;
475 kid = kid->GetNextSibling();
477 NS_ASSERTION(found, "tried to remove non child");
479 // If we just removed a root view, then update the RootViewManager
480 // on all view managers in the removed subtree.
482 nsViewManager* vm = child->GetViewManager();
483 if (vm->GetRootView() == child) {
484 child->InvalidateHierarchy();
489 // Native widgets ultimately just can't deal with the awesome power of
490 // CSS2 z-index. However, we set the z-index on the widget anyway
491 // because in many simple common cases the widgets do end up in the
492 // right order. We set each widget's z-index to the z-index of the
493 // nearest ancestor that has non-auto z-index.
494 static void UpdateNativeWidgetZIndexes(nsView* aView, int32_t aZIndex) {
495 if (aView->HasWidget()) {
496 nsIWidget* widget = aView->GetWidget();
497 if (widget->GetZIndex() != aZIndex) {
498 widget->SetZIndex(aZIndex);
500 } else {
501 for (nsView* v = aView->GetFirstChild(); v; v = v->GetNextSibling()) {
502 if (v->GetZIndexIsAuto()) {
503 UpdateNativeWidgetZIndexes(v, aZIndex);
509 static int32_t FindNonAutoZIndex(nsView* aView) {
510 while (aView) {
511 if (!aView->GetZIndexIsAuto()) {
512 return aView->GetZIndex();
514 aView = aView->GetParent();
516 return 0;
519 struct DefaultWidgetInitData : public nsWidgetInitData {
520 DefaultWidgetInitData() : nsWidgetInitData() {
521 mWindowType = eWindowType_child;
522 clipChildren = true;
523 clipSiblings = true;
527 nsresult nsView::CreateWidget(nsWidgetInitData* aWidgetInitData,
528 bool aEnableDragDrop, bool aResetVisibility) {
529 AssertNoWindow();
530 MOZ_ASSERT(
531 !aWidgetInitData || aWidgetInitData->mWindowType != eWindowType_popup,
532 "Use CreateWidgetForPopup");
534 DefaultWidgetInitData defaultInitData;
535 bool initDataPassedIn = !!aWidgetInitData;
536 aWidgetInitData = aWidgetInitData ? aWidgetInitData : &defaultInitData;
537 defaultInitData.mListenForResizes =
538 (!initDataPassedIn && GetParent() &&
539 GetParent()->GetViewManager() != mViewManager);
541 LayoutDeviceIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
543 nsIWidget* parentWidget =
544 GetParent() ? GetParent()->GetNearestWidget(nullptr) : nullptr;
545 if (!parentWidget) {
546 NS_ERROR("nsView::CreateWidget without suitable parent widget??");
547 return NS_ERROR_FAILURE;
550 // XXX: using aForceUseIWidgetParent=true to preserve previous
551 // semantics. It's not clear that it's actually needed.
552 mWindow = parentWidget->CreateChild(trect, aWidgetInitData, true);
553 if (!mWindow) {
554 return NS_ERROR_FAILURE;
557 InitializeWindow(aEnableDragDrop, aResetVisibility);
559 return NS_OK;
562 nsresult nsView::CreateWidgetForParent(nsIWidget* aParentWidget,
563 nsWidgetInitData* aWidgetInitData,
564 bool aEnableDragDrop,
565 bool aResetVisibility) {
566 AssertNoWindow();
567 MOZ_ASSERT(
568 !aWidgetInitData || aWidgetInitData->mWindowType != eWindowType_popup,
569 "Use CreateWidgetForPopup");
570 MOZ_ASSERT(aParentWidget, "Parent widget required");
572 DefaultWidgetInitData defaultInitData;
573 aWidgetInitData = aWidgetInitData ? aWidgetInitData : &defaultInitData;
575 LayoutDeviceIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
577 mWindow = aParentWidget->CreateChild(trect, aWidgetInitData);
578 if (!mWindow) {
579 return NS_ERROR_FAILURE;
582 InitializeWindow(aEnableDragDrop, aResetVisibility);
584 return NS_OK;
587 nsresult nsView::CreateWidgetForPopup(nsWidgetInitData* aWidgetInitData,
588 nsIWidget* aParentWidget,
589 bool aEnableDragDrop,
590 bool aResetVisibility) {
591 AssertNoWindow();
592 MOZ_ASSERT(aWidgetInitData, "Widget init data required");
593 MOZ_ASSERT(aWidgetInitData->mWindowType == eWindowType_popup,
594 "Use one of the other CreateWidget methods");
596 LayoutDeviceIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
598 // XXX/cjones: having these two separate creation cases seems ... um
599 // ... unnecessary, but it's the way the old code did it. Please
600 // unify them by first finding a suitable parent nsIWidget, then
601 // getting rid of aForceUseIWidgetParent.
602 if (aParentWidget) {
603 // XXX: using aForceUseIWidgetParent=true to preserve previous
604 // semantics. It's not clear that it's actually needed.
605 mWindow = aParentWidget->CreateChild(trect, aWidgetInitData, true);
606 } else {
607 nsIWidget* nearestParent =
608 GetParent() ? GetParent()->GetNearestWidget(nullptr) : nullptr;
609 if (!nearestParent) {
610 // Without a parent, we can't make a popup. This can happen
611 // when printing
612 return NS_ERROR_FAILURE;
615 mWindow = nearestParent->CreateChild(trect, aWidgetInitData);
617 if (!mWindow) {
618 return NS_ERROR_FAILURE;
621 InitializeWindow(aEnableDragDrop, aResetVisibility);
623 return NS_OK;
626 void nsView::InitializeWindow(bool aEnableDragDrop, bool aResetVisibility) {
627 MOZ_ASSERT(mWindow, "Must have a window to initialize");
629 mWindow->SetWidgetListener(this);
631 if (aEnableDragDrop) {
632 mWindow->EnableDragDrop(true);
635 // propagate the z-index to the widget.
636 UpdateNativeWidgetZIndexes(this, FindNonAutoZIndex(this));
638 // make sure visibility state is accurate
640 if (aResetVisibility) {
641 SetVisibility(GetVisibility());
645 void nsView::SetNeedsWindowPropertiesSync() {
646 mNeedsWindowPropertiesSync = true;
647 if (mViewManager) {
648 mViewManager->PostPendingUpdate();
652 // Attach to a top level widget and start receiving mirrored events.
653 nsresult nsView::AttachToTopLevelWidget(nsIWidget* aWidget) {
654 MOZ_ASSERT(nullptr != aWidget, "null widget ptr");
656 /// XXXjimm This is a temporary workaround to an issue w/document
657 // viewer (bug 513162).
658 nsIWidgetListener* listener = aWidget->GetAttachedWidgetListener();
659 if (listener) {
660 nsView* oldView = listener->GetView();
661 if (oldView) {
662 oldView->DetachFromTopLevelWidget();
666 // Note, the previous device context will be released. Detaching
667 // will not restore the old one.
668 aWidget->AttachViewToTopLevel(!nsIWidget::UsePuppetWidgets());
670 mWindow = aWidget;
672 mWindow->SetAttachedWidgetListener(this);
673 if (mWindow->WindowType() != eWindowType_invisible) {
674 nsresult rv = mWindow->AsyncEnableDragDrop(true);
675 NS_ENSURE_SUCCESS(rv, rv);
677 mWidgetIsTopLevel = true;
679 // Refresh the view bounds
680 CalcWidgetBounds(mWindow->WindowType());
682 return NS_OK;
685 // Detach this view from an attached widget.
686 nsresult nsView::DetachFromTopLevelWidget() {
687 MOZ_ASSERT(mWidgetIsTopLevel, "Not attached currently!");
688 MOZ_ASSERT(mWindow, "null mWindow for DetachFromTopLevelWidget!");
690 mWindow->SetAttachedWidgetListener(nullptr);
691 nsIWidgetListener* listener = mWindow->GetPreviouslyAttachedWidgetListener();
693 if (listener && listener->GetView()) {
694 // Ensure the listener doesn't think it's being used anymore
695 listener->GetView()->SetPreviousWidget(nullptr);
698 // If the new view's frame is paint suppressed then the window
699 // will want to use us instead until that's done
700 mWindow->SetPreviouslyAttachedWidgetListener(this);
702 mPreviousWindow = mWindow;
703 mWindow = nullptr;
705 mWidgetIsTopLevel = false;
707 return NS_OK;
710 void nsView::SetZIndex(bool aAuto, int32_t aZIndex) {
711 bool oldIsAuto = GetZIndexIsAuto();
712 mVFlags = (mVFlags & ~NS_VIEW_FLAG_AUTO_ZINDEX) |
713 (aAuto ? NS_VIEW_FLAG_AUTO_ZINDEX : 0);
714 mZIndex = aZIndex;
716 if (HasWidget() || !oldIsAuto || !aAuto) {
717 UpdateNativeWidgetZIndexes(this, FindNonAutoZIndex(this));
721 void nsView::AssertNoWindow() {
722 // XXX: it would be nice to make this a strong assert
723 if (MOZ_UNLIKELY(mWindow)) {
724 NS_ERROR("We already have a window for this view? BAD");
725 mWindow->SetWidgetListener(nullptr);
726 mWindow->Destroy();
727 mWindow = nullptr;
732 // internal window creation functions
734 void nsView::AttachWidgetEventHandler(nsIWidget* aWidget) {
735 #ifdef DEBUG
736 NS_ASSERTION(!aWidget->GetWidgetListener(), "Already have a widget listener");
737 #endif
739 aWidget->SetWidgetListener(this);
742 void nsView::DetachWidgetEventHandler(nsIWidget* aWidget) {
743 NS_ASSERTION(!aWidget->GetWidgetListener() ||
744 aWidget->GetWidgetListener()->GetView() == this,
745 "Wrong view");
746 aWidget->SetWidgetListener(nullptr);
749 #ifdef DEBUG
750 void nsView::List(FILE* out, int32_t aIndent) const {
751 int32_t i;
752 for (i = aIndent; --i >= 0;) fputs(" ", out);
753 fprintf(out, "%p ", (void*)this);
754 if (nullptr != mWindow) {
755 nscoord p2a = mViewManager->AppUnitsPerDevPixel();
756 LayoutDeviceIntRect rect = mWindow->GetClientBounds();
757 nsRect windowBounds = LayoutDeviceIntRect::ToAppUnits(rect, p2a);
758 rect = mWindow->GetBounds();
759 nsRect nonclientBounds = LayoutDeviceIntRect::ToAppUnits(rect, p2a);
760 nsrefcnt widgetRefCnt = mWindow.get()->AddRef() - 1;
761 mWindow.get()->Release();
762 int32_t Z = mWindow->GetZIndex();
763 fprintf(out, "(widget=%p[%" PRIuPTR "] z=%d pos={%d,%d,%d,%d}) ",
764 (void*)mWindow, widgetRefCnt, Z, nonclientBounds.X(),
765 nonclientBounds.Y(), windowBounds.Width(), windowBounds.Height());
767 nsRect brect = GetBounds();
768 fprintf(out, "{%d,%d,%d,%d} @ %d,%d", brect.X(), brect.Y(), brect.Width(),
769 brect.Height(), mPosX, mPosY);
770 fprintf(out, " flags=%x z=%d vis=%d frame=%p <\n", mVFlags, mZIndex, mVis,
771 static_cast<void*>(mFrame));
772 for (nsView* kid = mFirstChild; kid; kid = kid->GetNextSibling()) {
773 NS_ASSERTION(kid->GetParent() == this, "incorrect parent");
774 kid->List(out, aIndent + 1);
776 for (i = aIndent; --i >= 0;) fputs(" ", out);
777 fputs(">\n", out);
779 #endif // DEBUG
781 nsPoint nsView::GetOffsetTo(const nsView* aOther) const {
782 return GetOffsetTo(aOther, GetViewManager()->AppUnitsPerDevPixel());
785 nsPoint nsView::GetOffsetTo(const nsView* aOther, const int32_t aAPD) const {
786 MOZ_ASSERT(GetParent() || !aOther || aOther->GetParent() || this == aOther,
787 "caller of (outer) GetOffsetTo must not pass unrelated views");
788 // We accumulate the final result in offset
789 nsPoint offset(0, 0);
790 // The offset currently accumulated at the current APD
791 nsPoint docOffset(0, 0);
792 const nsView* v = this;
793 nsViewManager* currVM = v->GetViewManager();
794 int32_t currAPD = currVM->AppUnitsPerDevPixel();
795 const nsView* root = nullptr;
796 for (; v != aOther && v; root = v, v = v->GetParent()) {
797 nsViewManager* newVM = v->GetViewManager();
798 if (newVM != currVM) {
799 int32_t newAPD = newVM->AppUnitsPerDevPixel();
800 if (newAPD != currAPD) {
801 offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
802 docOffset.x = docOffset.y = 0;
803 currAPD = newAPD;
805 currVM = newVM;
807 docOffset += v->GetPosition();
809 offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
811 if (v != aOther) {
812 // Looks like aOther wasn't an ancestor of |this|. So now we have
813 // the root-VM-relative position of |this| in |offset|. Get the
814 // root-VM-relative position of aOther and subtract it.
815 nsPoint negOffset = aOther->GetOffsetTo(root, aAPD);
816 offset -= negOffset;
819 return offset;
822 nsPoint nsView::GetOffsetToWidget(nsIWidget* aWidget) const {
823 nsPoint pt;
824 // Get the view for widget
825 nsView* widgetView = GetViewFor(aWidget);
826 if (!widgetView) {
827 return pt;
830 // Get the offset to the widget view in the widget view's APD
831 // We get the offset in the widget view's APD first and then convert to our
832 // APD afterwards so that we can include the widget view's ViewToWidgetOffset
833 // in the sum in its native APD, and then convert the whole thing to our APD
834 // so that we don't have to convert the APD of the relatively small
835 // ViewToWidgetOffset by itself with a potentially large relative rounding
836 // error.
837 pt = -widgetView->GetOffsetTo(this);
838 // Add in the offset to the widget.
839 pt += widgetView->ViewToWidgetOffset();
841 // Convert to our appunits.
842 int32_t widgetAPD = widgetView->GetViewManager()->AppUnitsPerDevPixel();
843 int32_t ourAPD = GetViewManager()->AppUnitsPerDevPixel();
844 pt = pt.ScaleToOtherAppUnits(widgetAPD, ourAPD);
845 return pt;
848 nsIWidget* nsView::GetNearestWidget(nsPoint* aOffset) const {
849 return GetNearestWidget(aOffset, GetViewManager()->AppUnitsPerDevPixel());
852 nsIWidget* nsView::GetNearestWidget(nsPoint* aOffset,
853 const int32_t aAPD) const {
854 // aOffset is based on the view's position, which ignores any chrome on
855 // attached parent widgets.
857 // We accumulate the final result in pt
858 nsPoint pt(0, 0);
859 // The offset currently accumulated at the current APD
860 nsPoint docPt(0, 0);
861 const nsView* v = this;
862 nsViewManager* currVM = v->GetViewManager();
863 int32_t currAPD = currVM->AppUnitsPerDevPixel();
864 for (; v && !v->HasWidget(); v = v->GetParent()) {
865 nsViewManager* newVM = v->GetViewManager();
866 if (newVM != currVM) {
867 int32_t newAPD = newVM->AppUnitsPerDevPixel();
868 if (newAPD != currAPD) {
869 pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
870 docPt.x = docPt.y = 0;
871 currAPD = newAPD;
873 currVM = newVM;
875 docPt += v->GetPosition();
877 if (!v) {
878 if (aOffset) {
879 pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
880 *aOffset = pt;
882 return nullptr;
885 // pt is now the offset from v's origin to this view's origin.
886 // We add the ViewToWidgetOffset to get the offset to the widget.
887 if (aOffset) {
888 docPt += v->ViewToWidgetOffset();
889 pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
890 *aOffset = pt;
892 return v->GetWidget();
895 bool nsView::IsRoot() const {
896 NS_ASSERTION(mViewManager != nullptr,
897 " View manager is null in nsView::IsRoot()");
898 return mViewManager->GetRootView() == this;
901 nsRect nsView::GetBoundsInParentUnits() const {
902 nsView* parent = GetParent();
903 nsViewManager* VM = GetViewManager();
904 if (this != VM->GetRootView() || !parent) {
905 return mDimBounds;
907 int32_t ourAPD = VM->AppUnitsPerDevPixel();
908 int32_t parentAPD = parent->GetViewManager()->AppUnitsPerDevPixel();
909 return mDimBounds.ScaleToOtherAppUnitsRoundOut(ourAPD, parentAPD);
912 nsPoint nsView::ConvertFromParentCoords(nsPoint aPt) const {
913 const nsView* parent = GetParent();
914 if (parent) {
915 aPt = aPt.ScaleToOtherAppUnits(
916 parent->GetViewManager()->AppUnitsPerDevPixel(),
917 GetViewManager()->AppUnitsPerDevPixel());
919 aPt -= GetPosition();
920 return aPt;
923 static bool IsPopupWidget(nsIWidget* aWidget) {
924 return (aWidget->WindowType() == eWindowType_popup);
927 PresShell* nsView::GetPresShell() { return GetViewManager()->GetPresShell(); }
929 bool nsView::WindowMoved(nsIWidget* aWidget, int32_t x, int32_t y) {
930 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
931 if (pm && IsPopupWidget(aWidget)) {
932 pm->PopupMoved(mFrame, nsIntPoint(x, y));
933 return true;
936 return false;
939 bool nsView::WindowResized(nsIWidget* aWidget, int32_t aWidth,
940 int32_t aHeight) {
941 // The root view may not be set if this is the resize associated with
942 // window creation
943 SetForcedRepaint(true);
944 if (this == mViewManager->GetRootView()) {
945 RefPtr<nsDeviceContext> devContext = mViewManager->GetDeviceContext();
946 // ensure DPI is up-to-date, in case of window being opened and sized
947 // on a non-default-dpi display (bug 829963)
948 devContext->CheckDPIChange();
949 int32_t p2a = devContext->AppUnitsPerDevPixel();
950 mViewManager->SetWindowDimensions(NSIntPixelsToAppUnits(aWidth, p2a),
951 NSIntPixelsToAppUnits(aHeight, p2a));
953 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
954 if (pm) {
955 PresShell* presShell = mViewManager->GetPresShell();
956 if (presShell && presShell->GetDocument()) {
957 pm->AdjustPopupsOnWindowChange(presShell);
961 return true;
963 if (IsPopupWidget(aWidget)) {
964 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
965 if (pm) {
966 pm->PopupResized(mFrame, LayoutDeviceIntSize(aWidth, aHeight));
967 return true;
971 return false;
974 #if defined(MOZ_WIDGET_ANDROID)
975 void nsView::DynamicToolbarMaxHeightChanged(ScreenIntCoord aHeight) {
976 MOZ_ASSERT(XRE_IsParentProcess(),
977 "Should be only called for the browser parent process");
978 MOZ_ASSERT(this == mViewManager->GetRootView(),
979 "Should be called for the root view");
981 PresShell* presShell = mViewManager->GetPresShell();
982 if (!presShell) {
983 return;
986 dom::Document* document = presShell->GetDocument();
987 if (!document) {
988 return;
991 nsPIDOMWindowOuter* window = document->GetWindow();
992 if (!window) {
993 return;
996 nsContentUtils::CallOnAllRemoteChildren(
997 window, [&aHeight](dom::BrowserParent* aBrowserParent) -> CallState {
998 aBrowserParent->DynamicToolbarMaxHeightChanged(aHeight);
999 return CallState::Continue;
1003 void nsView::DynamicToolbarOffsetChanged(ScreenIntCoord aOffset) {
1004 MOZ_ASSERT(XRE_IsParentProcess(),
1005 "Should be only called for the browser parent process");
1006 MOZ_ASSERT(this == mViewManager->GetRootView(),
1007 "Should be called for the root view");
1009 PresShell* presShell = mViewManager->GetPresShell();
1010 if (!presShell) {
1011 return;
1014 dom::Document* document = presShell->GetDocument();
1015 if (!document) {
1016 return;
1019 nsPIDOMWindowOuter* window = document->GetWindow();
1020 if (!window) {
1021 return;
1024 nsContentUtils::CallOnAllRemoteChildren(
1025 window, [&aOffset](dom::BrowserParent* aBrowserParent) -> CallState {
1026 // Skip background tabs.
1027 if (!aBrowserParent->GetDocShellIsActive()) {
1028 return CallState::Continue;
1031 aBrowserParent->DynamicToolbarOffsetChanged(aOffset);
1032 return CallState::Stop;
1035 #endif
1037 bool nsView::RequestWindowClose(nsIWidget* aWidget) {
1038 if (mFrame && IsPopupWidget(aWidget) && mFrame->IsMenuPopupFrame()) {
1039 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
1040 if (pm) {
1041 pm->HidePopup(mFrame->GetContent(), false, true, false, false);
1042 return true;
1046 return false;
1049 void nsView::WillPaintWindow(nsIWidget* aWidget) {
1050 RefPtr<nsViewManager> vm = mViewManager;
1051 vm->WillPaintWindow(aWidget);
1054 bool nsView::PaintWindow(nsIWidget* aWidget, LayoutDeviceIntRegion aRegion) {
1055 NS_ASSERTION(this == nsView::GetViewFor(aWidget), "wrong view for widget?");
1057 RefPtr<nsViewManager> vm = mViewManager;
1058 bool result = vm->PaintWindow(aWidget, aRegion);
1059 return result;
1062 void nsView::DidPaintWindow() {
1063 RefPtr<nsViewManager> vm = mViewManager;
1064 vm->DidPaintWindow();
1067 void nsView::DidCompositeWindow(mozilla::layers::TransactionId aTransactionId,
1068 const TimeStamp& aCompositeStart,
1069 const TimeStamp& aCompositeEnd) {
1070 PresShell* presShell = mViewManager->GetPresShell();
1071 if (!presShell) {
1072 return;
1075 nsAutoScriptBlocker scriptBlocker;
1077 nsPresContext* context = presShell->GetPresContext();
1078 nsRootPresContext* rootContext = context->GetRootPresContext();
1079 if (rootContext) {
1080 rootContext->NotifyDidPaintForSubtree(aTransactionId, aCompositeEnd);
1083 mozilla::StartupTimeline::RecordOnce(mozilla::StartupTimeline::FIRST_PAINT2,
1084 aCompositeEnd);
1086 // If the two timestamps are identical, this was likely a fake composite
1087 // event which wouldn't be terribly useful to display.
1088 if (aCompositeStart == aCompositeEnd) {
1089 return;
1092 nsIDocShell* docShell = context->GetDocShell();
1093 RefPtr<TimelineConsumers> timelines = TimelineConsumers::Get();
1095 if (timelines && timelines->HasConsumer(docShell)) {
1096 timelines->AddMarkerForDocShell(
1097 docShell, MakeUnique<CompositeTimelineMarker>(
1098 aCompositeStart, MarkerTracingType::START));
1099 timelines->AddMarkerForDocShell(
1100 docShell, MakeUnique<CompositeTimelineMarker>(aCompositeEnd,
1101 MarkerTracingType::END));
1105 void nsView::RequestRepaint() {
1106 PresShell* presShell = mViewManager->GetPresShell();
1107 if (presShell) {
1108 presShell->ScheduleViewManagerFlush();
1112 bool nsView::ShouldNotBeVisible() {
1113 if (mFrame && mFrame->IsMenuPopupFrame()) {
1114 nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
1115 return !pm || !pm->IsPopupOpen(mFrame->GetContent());
1118 return false;
1121 nsEventStatus nsView::HandleEvent(WidgetGUIEvent* aEvent,
1122 bool aUseAttachedEvents) {
1123 MOZ_ASSERT(nullptr != aEvent->mWidget, "null widget ptr");
1125 nsEventStatus result = nsEventStatus_eIgnore;
1126 nsView* view;
1127 if (aUseAttachedEvents) {
1128 nsIWidgetListener* listener = aEvent->mWidget->GetAttachedWidgetListener();
1129 view = listener ? listener->GetView() : nullptr;
1130 } else {
1131 view = GetViewFor(aEvent->mWidget);
1134 if (view) {
1135 RefPtr<nsViewManager> vm = view->GetViewManager();
1136 vm->DispatchEvent(aEvent, view, &result);
1139 return result;
1142 void nsView::SafeAreaInsetsChanged(const ScreenIntMargin& aSafeAreaInsets) {
1143 if (!IsRoot()) {
1144 return;
1147 PresShell* presShell = mViewManager->GetPresShell();
1148 if (!presShell) {
1149 return;
1152 ScreenIntMargin windowSafeAreaInsets;
1153 LayoutDeviceIntRect windowRect = mWindow->GetScreenBounds();
1154 nsCOMPtr<nsIScreen> screen = mWindow->GetWidgetScreen();
1155 if (screen) {
1156 windowSafeAreaInsets = nsContentUtils::GetWindowSafeAreaInsets(
1157 screen, aSafeAreaInsets, windowRect);
1160 presShell->GetPresContext()->SetSafeAreaInsets(windowSafeAreaInsets);
1162 // https://github.com/w3c/csswg-drafts/issues/4670
1163 // Actually we don't set this value on sub document. This behaviour is
1164 // same as Blink.
1166 dom::Document* document = presShell->GetDocument();
1167 if (!document) {
1168 return;
1171 nsPIDOMWindowOuter* window = document->GetWindow();
1172 if (!window) {
1173 return;
1176 nsContentUtils::CallOnAllRemoteChildren(
1177 window,
1178 [windowSafeAreaInsets](dom::BrowserParent* aBrowserParent) -> CallState {
1179 Unused << aBrowserParent->SendSafeAreaInsetsChanged(
1180 windowSafeAreaInsets);
1181 return CallState::Continue;
1185 bool nsView::IsPrimaryFramePaintSuppressed() {
1186 return StaticPrefs::layout_show_previous_page() && mFrame &&
1187 mFrame->PresShell()->IsPaintingSuppressed();