Bug Summary

File:var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp
Warning:line 253, column 9
Value stored to 'subdocRootFrame' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name Unified_cpp_layout_generic4.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -ffp-contract=off -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fdebug-compilation-dir=/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/layout/generic -fcoverage-compilation-dir=/var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/layout/generic -resource-dir /usr/lib/llvm-18/lib/clang/18 -include /var/lib/jenkins/workspace/firefox-scan-build/config/gcc_hidden.h -include /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/mozilla-config.h -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/stl_wrappers -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/system_wrappers -U _FORTIFY_SOURCE -D _FORTIFY_SOURCE=2 -D DEBUG=1 -D MOZ_HAS_MOZGLUE -D MOZILLA_INTERNAL_API -D IMPL_LIBXUL -D STATIC_EXPORTABLE_JS_API -I /var/lib/jenkins/workspace/firefox-scan-build/layout/generic -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/layout/generic -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/ipc/ipdl/_ipdlheaders -I /var/lib/jenkins/workspace/firefox-scan-build/ipc/chromium/src -I /var/lib/jenkins/workspace/firefox-scan-build/layout/base -I /var/lib/jenkins/workspace/firefox-scan-build/layout/forms -I /var/lib/jenkins/workspace/firefox-scan-build/layout/painting -I /var/lib/jenkins/workspace/firefox-scan-build/layout/style -I /var/lib/jenkins/workspace/firefox-scan-build/layout/tables -I /var/lib/jenkins/workspace/firefox-scan-build/layout/xul -I /var/lib/jenkins/workspace/firefox-scan-build/docshell/base -I /var/lib/jenkins/workspace/firefox-scan-build/dom/base -I /var/lib/jenkins/workspace/firefox-scan-build/dom/html -I /var/lib/jenkins/workspace/firefox-scan-build/dom/xul -I /var/lib/jenkins/workspace/firefox-scan-build/gfx/cairo/cairo/src -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/nspr -I /var/lib/jenkins/workspace/firefox-scan-build/obj-x86_64-pc-linux-gnu/dist/include/nss -D MOZILLA_CLIENT -I /usr/include/gtk-3.0 -I /usr/include/pango-1.0 -I /usr/include/glib-2.0 -I /usr/lib/x86_64-linux-gnu/glib-2.0/include -I /usr/include/harfbuzz -I /usr/include/freetype2 -I /usr/include/libpng16 -I /usr/include/libmount -I /usr/include/blkid -I /usr/include/fribidi -I /usr/include/cairo -I /usr/include/pixman-1 -I /usr/include/gdk-pixbuf-2.0 -I /usr/include/x86_64-linux-gnu -I /usr/include/webp -I /usr/include/gio-unix-2.0 -I /usr/include/cloudproviders -I /usr/include/atk-1.0 -I /usr/include/at-spi2-atk/2.0 -I /usr/include/at-spi-2.0 -I /usr/include/dbus-1.0 -I /usr/lib/x86_64-linux-gnu/dbus-1.0/include -I /usr/include/gtk-3.0/unix-print -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/13/../../../../include/c++/13 -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/13/../../../../include/x86_64-linux-gnu/c++/13 -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/13/../../../../include/c++/13/backward -internal-isystem /usr/lib/llvm-18/lib/clang/18/include -internal-isystem /usr/local/include -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/13/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-error=tautological-type-limit-compare -Wno-invalid-offsetof -Wno-range-loop-analysis -Wno-deprecated-anon-enum-enum-conversion -Wno-deprecated-enum-enum-conversion -Wno-deprecated-this-capture -Wno-inline-new-delete -Wno-error=deprecated-declarations -Wno-error=array-bounds -Wno-error=free-nonheap-object -Wno-error=atomic-alignment -Wno-error=deprecated-builtins -Wno-psabi -Wno-error=builtin-macro-redefined -Wno-vla-cxx-extension -Wno-unknown-warning-option -fdeprecated-macro -ferror-limit 19 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fno-rtti -fgnuc-version=4.2.1 -fno-aligned-allocation -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2024-05-16-034744-15991-1 -x c++ Unified_cpp_layout_generic4.cpp
1/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3/* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7/*
8 * rendering object for replaced elements that contain a document, such
9 * as <frame>, <iframe>, and some <object>s
10 */
11
12#include "nsSubDocumentFrame.h"
13
14#include "mozilla/ComputedStyleInlines.h"
15#include "mozilla/Preferences.h"
16#include "mozilla/PresShell.h"
17#include "mozilla/StaticPrefs_layout.h"
18#include "mozilla/Unused.h"
19#include "mozilla/dom/Document.h"
20#include "mozilla/dom/HTMLFrameElement.h"
21#include "mozilla/dom/ImageDocument.h"
22#include "mozilla/dom/BrowserParent.h"
23
24#include "nsCOMPtr.h"
25#include "nsGenericHTMLElement.h"
26#include "nsGenericHTMLFrameElement.h"
27#include "nsAttrValueInlines.h"
28#include "nsIDocShell.h"
29#include "nsIDocumentViewer.h"
30#include "nsIContentInlines.h"
31#include "nsPresContext.h"
32#include "nsView.h"
33#include "nsViewManager.h"
34#include "nsGkAtoms.h"
35#include "nsStyleConsts.h"
36#include "nsStyleStruct.h"
37#include "nsStyleStructInlines.h"
38#include "nsFrameSetFrame.h"
39#include "nsNameSpaceManager.h"
40#include "nsDisplayList.h"
41#include "nsIScrollableFrame.h"
42#include "nsIObjectLoadingContent.h"
43#include "nsLayoutUtils.h"
44#include "nsContentUtils.h"
45#include "nsServiceManagerUtils.h"
46#include "nsQueryObject.h"
47#include "RetainedDisplayListBuilder.h"
48#include "nsObjectLoadingContent.h"
49
50#include "mozilla/layers/WebRenderUserData.h"
51#include "mozilla/layers/WebRenderScrollData.h"
52#include "mozilla/layers/RenderRootStateManager.h"
53#include "mozilla/layers/StackingContextHelper.h" // for StackingContextHelper
54#include "mozilla/ProfilerLabels.h"
55
56using namespace mozilla;
57using namespace mozilla::dom;
58using namespace mozilla::gfx;
59using namespace mozilla::layers;
60
61static Document* GetDocumentFromView(nsView* aView) {
62 MOZ_ASSERT(aView, "null view")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aView)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(aView))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("aView" " (" "null view" ")"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 62); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aView" ") (" "null view"
")"); do { *((volatile int*)__null) = 62; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
63
64 nsViewManager* vm = aView->GetViewManager();
65 PresShell* presShell = vm ? vm->GetPresShell() : nullptr;
66 return presShell ? presShell->GetDocument() : nullptr;
67}
68
69static void PropagateIsUnderHiddenEmbedderElement(nsFrameLoader* aFrameLoader,
70 bool aValue) {
71 if (!aFrameLoader) {
72 return;
73 }
74
75 if (BrowsingContext* bc = aFrameLoader->GetExtantBrowsingContext()) {
76 if (bc->IsUnderHiddenEmbedderElement() != aValue) {
77 Unused << bc->SetIsUnderHiddenEmbedderElement(aValue);
78 }
79 }
80}
81
82nsSubDocumentFrame::nsSubDocumentFrame(ComputedStyle* aStyle,
83 nsPresContext* aPresContext)
84 : nsAtomicContainerFrame(aStyle, aPresContext, kClassID),
85 mOuterView(nullptr),
86 mInnerView(nullptr),
87 mIsInline(false),
88 mPostedReflowCallback(false),
89 mDidCreateDoc(false),
90 mCallingShow(false),
91 mIsInObjectOrEmbed(false) {}
92
93#ifdef ACCESSIBILITY1
94a11y::AccType nsSubDocumentFrame::AccessibleType() {
95 return a11y::eOuterDocType;
96}
97#endif
98
99NS_QUERYFRAME_HEAD(nsSubDocumentFrame)void* nsSubDocumentFrame ::QueryFrame(FrameIID id) const { switch
(id) {
100 NS_QUERYFRAME_ENTRY(nsSubDocumentFrame)case nsSubDocumentFrame ::kFrameIID: { static_assert( std::is_same_v
<nsSubDocumentFrame, nsSubDocumentFrame ::Has_NS_DECL_QUERYFRAME_TARGET
>, "nsSubDocumentFrame" " must declare itself as a queryframe target"
); return const_cast<nsSubDocumentFrame*>(static_cast<
const nsSubDocumentFrame*>(this)); }
101NS_QUERYFRAME_TAIL_INHERITING(nsAtomicContainerFrame)default: break; } return nsAtomicContainerFrame ::QueryFrame(
id); }
102
103class AsyncFrameInit : public Runnable {
104 public:
105 explicit AsyncFrameInit(nsIFrame* aFrame)
106 : mozilla::Runnable("AsyncFrameInit"), mFrame(aFrame) {}
107 NS_IMETHODvirtual nsresult Run() override {
108 AUTO_PROFILER_LABEL("AsyncFrameInit::Run", OTHER)mozilla::AutoProfilerLabel raiiObject108( "AsyncFrameInit::Run"
, nullptr, JS::ProfilingCategoryPair::OTHER)
;
109 if (mFrame.IsAlive()) {
110 static_cast<nsSubDocumentFrame*>(mFrame.GetFrame())->ShowViewer();
111 }
112 return NS_OK;
113 }
114
115 private:
116 WeakFrame mFrame;
117};
118
119void nsSubDocumentFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
120 nsIFrame* aPrevInFlow) {
121 MOZ_ASSERT(aContent)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aContent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aContent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aContent", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 121); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aContent" ")"
); do { *((volatile int*)__null) = 121; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
122 // determine if we are a <frame> or <iframe>
123 mIsInline = !aContent->IsHTMLElement(nsGkAtoms::frame);
124
125 nsAtomicContainerFrame::Init(aContent, aParent, aPrevInFlow);
126
127 // CreateView() creates this frame's view, stored in mOuterView. It needs to
128 // be created first since it's the parent of the inner view, stored in
129 // mInnerView.
130 CreateView();
131 EnsureInnerView();
132
133 // Set the primary frame now so that nsDocumentViewer::FindContainerView
134 // called from within EndSwapDocShellsForViews below can find it if needed.
135 aContent->SetPrimaryFrame(this);
136
137 // If we have a detached subdoc's root view on our frame loader, re-insert it
138 // into the view tree. This happens when we've been reframed, and ensures the
139 // presentation persists across reframes.
140 if (RefPtr<nsFrameLoader> frameloader = FrameLoader()) {
141 bool hadFrame = false;
142 nsIFrame* detachedFrame = frameloader->GetDetachedSubdocFrame(&hadFrame);
143 frameloader->SetDetachedSubdocFrame(nullptr);
144 nsView* detachedView = detachedFrame ? detachedFrame->GetView() : nullptr;
145 if (detachedView) {
146 // Restore stashed presentation.
147 InsertViewsInReverseOrder(detachedView, mInnerView);
148 EndSwapDocShellsForViews(mInnerView->GetFirstChild());
149 } else if (hadFrame) {
150 // Presentation is for a different document, don't restore it.
151 frameloader->Hide();
152 }
153 }
154
155 // NOTE: The frame loader might not yet be initialized yet. If it's not, the
156 // call in ShowViewer() should pick things up.
157 UpdateEmbeddedBrowsingContextDependentData();
158 nsContentUtils::AddScriptRunner(new AsyncFrameInit(this));
159}
160
161void nsSubDocumentFrame::UpdateEmbeddedBrowsingContextDependentData() {
162 if (!mFrameLoader) {
163 return;
164 }
165 BrowsingContext* bc = mFrameLoader->GetExtantBrowsingContext();
166 if (!bc) {
167 return;
168 }
169 mIsInObjectOrEmbed = bc->IsEmbedderTypeObjectOrEmbed();
170 MaybeUpdateRemoteStyle();
171 MaybeUpdateEmbedderColorScheme();
172 PropagateIsUnderHiddenEmbedderElement(
173 PresShell()->IsUnderHiddenEmbedderElement() ||
174 !StyleVisibility()->IsVisible());
175}
176
177void nsSubDocumentFrame::PropagateIsUnderHiddenEmbedderElement(bool aValue) {
178 ::PropagateIsUnderHiddenEmbedderElement(mFrameLoader, aValue);
179}
180
181void nsSubDocumentFrame::ShowViewer() {
182 if (mCallingShow) {
183 return;
184 }
185
186 RefPtr<nsFrameLoader> frameloader = FrameLoader();
187 if (!frameloader || frameloader->IsDead()) {
188 return;
189 }
190
191 if (!frameloader->IsRemoteFrame() && !PresContext()->IsDynamic()) {
192 // We let the printing code take care of loading the document and
193 // initializing the shell; just create the inner view for it to use.
194 (void)EnsureInnerView();
195 } else {
196 AutoWeakFrame weakThis(this);
197 mCallingShow = true;
198 bool didCreateDoc = frameloader->Show(this);
199 if (!weakThis.IsAlive()) {
200 return;
201 }
202 mCallingShow = false;
203 mDidCreateDoc = didCreateDoc;
204 if (!HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
205 frameloader->UpdatePositionAndSize(this);
206 }
207 if (!weakThis.IsAlive()) {
208 return;
209 }
210 UpdateEmbeddedBrowsingContextDependentData();
211 InvalidateFrame();
212 }
213}
214
215nsIFrame* nsSubDocumentFrame::GetSubdocumentRootFrame() {
216 if (!mInnerView) return nullptr;
217 nsView* subdocView = mInnerView->GetFirstChild();
218 return subdocView ? subdocView->GetFrame() : nullptr;
219}
220
221mozilla::PresShell* nsSubDocumentFrame::GetSubdocumentPresShellForPainting(
222 uint32_t aFlags) {
223 if (!mInnerView) return nullptr;
224
225 nsView* subdocView = mInnerView->GetFirstChild();
226 if (!subdocView) return nullptr;
227
228 mozilla::PresShell* presShell = nullptr;
229
230 nsIFrame* subdocRootFrame = subdocView->GetFrame();
231 if (subdocRootFrame) {
232 presShell = subdocRootFrame->PresShell();
233 }
234
235 // If painting is suppressed in the presshell, we try to look for a better
236 // presshell to use.
237 if (!presShell || (presShell->IsPaintingSuppressed() &&
238 !(aFlags & IGNORE_PAINT_SUPPRESSION))) {
239 // During page transition mInnerView will sometimes have two children, the
240 // first being the new page that may not have any frame, and the second
241 // being the old page that will probably have a frame.
242 nsView* nextView = subdocView->GetNextSibling();
243 nsIFrame* frame = nullptr;
244 if (nextView) {
245 frame = nextView->GetFrame();
246 }
247 if (frame) {
248 mozilla::PresShell* presShellForNextView = frame->PresShell();
249 if (!presShell || (presShellForNextView &&
250 !presShellForNextView->IsPaintingSuppressed() &&
251 StaticPrefs::layout_show_previous_page())) {
252 subdocView = nextView;
253 subdocRootFrame = frame;
Value stored to 'subdocRootFrame' is never read
254 presShell = presShellForNextView;
255 }
256 }
257 if (!presShell) {
258 // If we don't have a frame we use this roundabout way to get the pres
259 // shell.
260 if (!mFrameLoader) return nullptr;
261 nsIDocShell* docShell = mFrameLoader->GetDocShell(IgnoreErrors());
262 if (!docShell) return nullptr;
263 presShell = docShell->GetPresShell();
264 }
265 }
266
267 return presShell;
268}
269
270nsRect nsSubDocumentFrame::GetDestRect() {
271 nsRect rect = GetContent()->IsHTMLElement(nsGkAtoms::frame)
272 ? GetRectRelativeToSelf()
273 : GetContentRectRelativeToSelf();
274
275 // Adjust subdocument size, according to 'object-fit' and the subdocument's
276 // intrinsic size and ratio.
277 return nsLayoutUtils::ComputeObjectDestRect(
278 rect, GetIntrinsicSize(), GetIntrinsicRatio(), StylePosition());
279}
280
281ScreenIntSize nsSubDocumentFrame::GetSubdocumentSize() {
282 if (HasAnyStateBits(NS_FRAME_FIRST_REFLOW)) {
283 if (RefPtr<nsFrameLoader> frameloader = FrameLoader()) {
284 nsIFrame* detachedFrame = frameloader->GetDetachedSubdocFrame();
285 if (nsView* view = detachedFrame ? detachedFrame->GetView() : nullptr) {
286 nsSize size = view->GetBounds().Size();
287 nsPresContext* presContext = detachedFrame->PresContext();
288 return ScreenIntSize(presContext->AppUnitsToDevPixels(size.width),
289 presContext->AppUnitsToDevPixels(size.height));
290 }
291 }
292 // Pick some default size for now. Using 10x10 because that's what the
293 // code used to do.
294 return ScreenIntSize(10, 10);
295 }
296
297 nsSize docSizeAppUnits = GetDestRect().Size();
298 nsPresContext* pc = PresContext();
299 return ScreenIntSize(pc->AppUnitsToDevPixels(docSizeAppUnits.width),
300 pc->AppUnitsToDevPixels(docSizeAppUnits.height));
301}
302
303static void WrapBackgroundColorInOwnLayer(nsDisplayListBuilder* aBuilder,
304 nsIFrame* aFrame,
305 nsDisplayList* aList) {
306 for (nsDisplayItem* item : aList->TakeItems()) {
307 if (item->GetType() == DisplayItemType::TYPE_BACKGROUND_COLOR) {
308 nsDisplayList tmpList(aBuilder);
309 tmpList.AppendToTop(item);
310 item = MakeDisplayItemWithIndex<nsDisplayOwnLayer>(
311 aBuilder, aFrame, /* aIndex = */ nsDisplayOwnLayer::OwnLayerForSubdoc,
312 &tmpList, aBuilder->CurrentActiveScrolledRoot(),
313 nsDisplayOwnLayerFlags::None, ScrollbarData{}, true, false);
314 }
315 aList->AppendToTop(item);
316 }
317}
318
319void nsSubDocumentFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
320 const nsDisplayListSet& aLists) {
321 if (!IsVisibleForPainting()) {
322 return;
323 }
324
325 const bool pointerEventsNone =
326 Style()->PointerEvents() == StylePointerEvents::None;
327 if (aBuilder->IsForEventDelivery() && pointerEventsNone) {
328 // If we are pointer-events:none then we don't need to HitTest background or
329 // anything else.
330 return;
331 }
332
333 nsFrameLoader* frameLoader = FrameLoader();
334 const bool isRemoteFrame = frameLoader && frameLoader->IsRemoteFrame();
335
336 nsDisplayListCollection decorations(aBuilder);
337 DisplayBorderBackgroundOutline(aBuilder, decorations);
338 if (isRemoteFrame) {
339 // Wrap background colors of <iframe>s with remote subdocuments in their
340 // own layer so we generate a ColorLayer. This is helpful for optimizing
341 // compositing; we can skip compositing the ColorLayer when the
342 // remote content is opaque.
343 WrapBackgroundColorInOwnLayer(aBuilder, this,
344 decorations.BorderBackground());
345 }
346 decorations.MoveTo(aLists);
347
348 if (HidesContent()) {
349 return;
350 }
351
352 // If we're passing pointer events to children then we have to descend into
353 // subdocuments no matter what, to determine which parts are transparent for
354 // hit-testing or event regions.
355 bool needToDescend = aBuilder->GetDescendIntoSubdocuments();
356 if (!mInnerView || !needToDescend) {
357 return;
358 }
359
360 if (isRemoteFrame) {
361 // We're the subdoc for <browser remote="true"> and it has
362 // painted content. Display its shadow layer tree.
363 DisplayListClipState::AutoSaveRestore clipState(aBuilder);
364 clipState.ClipContainingBlockDescendantsToContentBox(aBuilder, this);
365
366 aLists.Content()->AppendNewToTop<nsDisplayRemote>(aBuilder, this);
367 return;
368 }
369
370 RefPtr<mozilla::PresShell> presShell = GetSubdocumentPresShellForPainting(
371 aBuilder->IsIgnoringPaintSuppression() ? IGNORE_PAINT_SUPPRESSION : 0);
372
373 if (!presShell) {
374 return;
375 }
376
377 if (aBuilder->IsInFilter()) {
378 Document* outerDoc = PresShell()->GetDocument();
379 Document* innerDoc = presShell->GetDocument();
380 if (outerDoc && innerDoc) {
381 if (!outerDoc->NodePrincipal()->Equals(innerDoc->NodePrincipal())) {
382 outerDoc->SetUseCounter(eUseCounter_custom_FilteredCrossOriginIFrame);
383 }
384 }
385 }
386
387 nsIFrame* subdocRootFrame = presShell->GetRootFrame();
388
389 nsPresContext* presContext = presShell->GetPresContext();
390
391 int32_t parentAPD = PresContext()->AppUnitsPerDevPixel();
392 int32_t subdocAPD = presContext->AppUnitsPerDevPixel();
393
394 nsRect visible;
395 nsRect dirty;
396 bool ignoreViewportScrolling = false;
397 if (subdocRootFrame) {
398 // get the dirty rect relative to the root frame of the subdoc
399 visible = aBuilder->GetVisibleRect() + GetOffsetToCrossDoc(subdocRootFrame);
400 dirty = aBuilder->GetDirtyRect() + GetOffsetToCrossDoc(subdocRootFrame);
401 // and convert into the appunits of the subdoc
402 visible = visible.ScaleToOtherAppUnitsRoundOut(parentAPD, subdocAPD);
403 dirty = dirty.ScaleToOtherAppUnitsRoundOut(parentAPD, subdocAPD);
404
405 if (nsIScrollableFrame* rootScrollableFrame =
406 presShell->GetRootScrollFrameAsScrollable()) {
407 // Use a copy, so the rects don't get modified.
408 nsRect copyOfDirty = dirty;
409 nsRect copyOfVisible = visible;
410 // TODO(botond): Can we just axe this DecideScrollableLayer call?
411 rootScrollableFrame->DecideScrollableLayer(aBuilder, &copyOfVisible,
412 &copyOfDirty,
413 /* aSetBase = */ true);
414
415 ignoreViewportScrolling = presShell->IgnoringViewportScrolling();
416 }
417
418 aBuilder->EnterPresShell(subdocRootFrame, pointerEventsNone);
419 aBuilder->IncrementPresShellPaintCount(presShell);
420 } else {
421 visible = aBuilder->GetVisibleRect();
422 dirty = aBuilder->GetDirtyRect();
423 }
424
425 DisplayListClipState::AutoSaveRestore clipState(aBuilder);
426 clipState.ClipContainingBlockDescendantsToContentBox(aBuilder, this);
427
428 nsIScrollableFrame* sf = presShell->GetRootScrollFrameAsScrollable();
429 bool constructZoomItem = subdocRootFrame && parentAPD != subdocAPD;
430 bool needsOwnLayer = constructZoomItem ||
431 presContext->IsRootContentDocumentCrossProcess() ||
432 (sf && sf->IsScrollingActive());
433
434 nsDisplayList childItems(aBuilder);
435
436 {
437 DisplayListClipState::AutoSaveRestore nestedClipState(aBuilder);
438 if (needsOwnLayer) {
439 // Clear current clip. There's no point in propagating it down, since
440 // the layer we will construct will be clipped by the current clip.
441 // In fact for nsDisplayZoom propagating it down would be incorrect since
442 // nsDisplayZoom changes the meaning of appunits.
443 nestedClipState.Clear();
444 }
445
446 // Invoke AutoBuildingDisplayList to ensure that the correct dirty rect
447 // is used to compute the visible rect if AddCanvasBackgroundColorItem
448 // creates a display item.
449 nsIFrame* frame = subdocRootFrame ? subdocRootFrame : this;
450 nsDisplayListBuilder::AutoBuildingDisplayList building(aBuilder, frame,
451 visible, dirty);
452
453 if (subdocRootFrame) {
454 bool hasDocumentLevelListenersForApzAwareEvents =
455 gfxPlatform::AsyncPanZoomEnabled() &&
456 nsLayoutUtils::HasDocumentLevelListenersForApzAwareEvents(presShell);
457
458 aBuilder->SetAncestorHasApzAwareEventHandler(
459 hasDocumentLevelListenersForApzAwareEvents);
460 subdocRootFrame->BuildDisplayListForStackingContext(aBuilder,
461 &childItems);
462 if (!aBuilder->IsForEventDelivery()) {
463 // If we are going to use a displayzoom below then any items we put
464 // under it need to have underlying frames from the subdocument. So we
465 // need to calculate the bounds based on which frame will be the
466 // underlying frame for the canvas background color item.
467 nsRect bounds =
468 GetContentRectRelativeToSelf() + aBuilder->ToReferenceFrame(this);
469 bounds = bounds.ScaleToOtherAppUnitsRoundOut(parentAPD, subdocAPD);
470
471 // Add the canvas background color to the bottom of the list. This
472 // happens after we've built the list so that
473 // AddCanvasBackgroundColorItem can monkey with the contents if
474 // necessary.
475 presShell->AddCanvasBackgroundColorItem(aBuilder, &childItems, frame,
476 bounds, NS_RGBA(0, 0, 0, 0)((nscolor)(((0) << 24) | ((0) << 16) | ((0) <<
8) | (0)))
);
477 }
478 }
479 }
480
481 if (subdocRootFrame) {
482 aBuilder->LeavePresShell(subdocRootFrame, &childItems);
483 }
484
485 // Generate a resolution and/or zoom item if needed. If one or both of those
486 // is created, we don't need to create a separate nsDisplaySubDocument.
487
488 nsDisplayOwnLayerFlags flags =
489 nsDisplayOwnLayerFlags::GenerateSubdocInvalidations;
490 // If ignoreViewportScrolling is true then the top most layer we create here
491 // is going to become the scrollable layer for the root scroll frame, so we
492 // want to add nsDisplayOwnLayer::GENERATE_SCROLLABLE_LAYER to whatever layer
493 // becomes the topmost. We do this below.
494 if (constructZoomItem) {
495 nsDisplayOwnLayerFlags zoomFlags = flags;
496 if (ignoreViewportScrolling) {
497 zoomFlags |= nsDisplayOwnLayerFlags::GenerateScrollableLayer;
498 }
499 childItems.AppendNewToTop<nsDisplayZoom>(aBuilder, subdocRootFrame, this,
500 &childItems, subdocAPD, parentAPD,
501 zoomFlags);
502
503 needsOwnLayer = false;
504 }
505 // Wrap the zoom item in the resolution item if we have both because we want
506 // the resolution scale applied on top of the app units per dev pixel
507 // conversion.
508 if (ignoreViewportScrolling) {
509 flags |= nsDisplayOwnLayerFlags::GenerateScrollableLayer;
510 }
511
512 // We always want top level content documents to be in their own layer.
513 nsDisplaySubDocument* layerItem = MakeDisplayItem<nsDisplaySubDocument>(
514 aBuilder, subdocRootFrame ? subdocRootFrame : this, this, &childItems,
515 flags);
516 if (layerItem) {
517 childItems.AppendToTop(layerItem);
518 layerItem->SetShouldFlattenAway(!needsOwnLayer);
519 }
520
521 if (aBuilder->IsForFrameVisibility()) {
522 // We don't add the childItems to the return list as we're dealing with them
523 // here.
524 presShell->RebuildApproximateFrameVisibilityDisplayList(childItems);
525 childItems.DeleteAll(aBuilder);
526 } else {
527 aLists.Content()->AppendToTop(&childItems);
528 }
529}
530
531#ifdef DEBUG_FRAME_DUMP1
532void nsSubDocumentFrame::List(FILE* out, const char* aPrefix,
533 ListFlags aFlags) const {
534 nsCString str;
535 ListGeneric(str, aPrefix, aFlags);
536 fprintf_stderr(out, "%s\n", str.get());
537
538 if (aFlags.contains(ListFlag::TraverseSubdocumentFrames)) {
539 nsSubDocumentFrame* f = const_cast<nsSubDocumentFrame*>(this);
540 nsIFrame* subdocRootFrame = f->GetSubdocumentRootFrame();
541 if (subdocRootFrame) {
542 nsCString pfx(aPrefix);
543 pfx += " ";
544 subdocRootFrame->List(out, pfx.get(), aFlags);
545 }
546 }
547}
548
549nsresult nsSubDocumentFrame::GetFrameName(nsAString& aResult) const {
550 return MakeFrameName(u"FrameOuter"_ns, aResult);
551}
552#endif
553
554/* virtual */
555nscoord nsSubDocumentFrame::GetMinISize(gfxContext* aRenderingContext) {
556 return GetIntrinsicISize();
557}
558
559/* virtual */
560nscoord nsSubDocumentFrame::GetPrefISize(gfxContext* aRenderingContext) {
561 // If the subdocument is an SVG document, then in theory we want to return
562 // the same thing that SVGOuterSVGFrame::GetPrefISize does. That method
563 // has some special handling of percentage values to avoid unhelpful zero
564 // sizing in the presence of orthogonal writing modes. We don't bother
565 // with that for SVG documents in <embed> and <object>, since that special
566 // handling doesn't look up across document boundaries anyway.
567 return GetIntrinsicISize();
568}
569
570/* virtual */
571IntrinsicSize nsSubDocumentFrame::GetIntrinsicSize() {
572 const auto containAxes = GetContainSizeAxes();
573 if (containAxes.IsBoth()) {
574 // Intrinsic size of 'contain:size' replaced elements is determined by
575 // contain-intrinsic-size.
576 return FinishIntrinsicSize(containAxes, IntrinsicSize(0, 0));
577 }
578
579 if (nsCOMPtr<nsIObjectLoadingContent> iolc = do_QueryInterface(mContent)) {
580 const auto* olc = static_cast<nsObjectLoadingContent*>(iolc.get());
581 if (auto size = olc->GetSubdocumentIntrinsicSize()) {
582 // Use the intrinsic size from the child SVG document, if available.
583 return FinishIntrinsicSize(containAxes, *size);
584 }
585 }
586
587 if (!IsInline()) {
588 return {}; // <frame> elements have no useful intrinsic size.
589 }
590
591 if (mContent->IsXULElement()) {
592 return {}; // XUL <iframe> and <browser> have no useful intrinsic size
593 }
594
595 // We must be an HTML <iframe>. Return fallback size.
596 return FinishIntrinsicSize(containAxes,
597 IntrinsicSize(kFallbackIntrinsicSize));
598}
599
600/* virtual */
601AspectRatio nsSubDocumentFrame::GetIntrinsicRatio() const {
602 // FIXME(emilio): This should probably respect contain: size and return no
603 // ratio in the case subDocRoot is non-null. Otherwise we do it by virtue of
604 // using a zero-size below and reusing GetIntrinsicSize().
605 if (nsCOMPtr<nsIObjectLoadingContent> iolc = do_QueryInterface(mContent)) {
606 auto olc = static_cast<nsObjectLoadingContent*>(iolc.get());
607
608 auto ratio = olc->GetSubdocumentIntrinsicRatio();
609 if (ratio && *ratio) {
610 // Use the intrinsic aspect ratio from the child SVG document, if
611 // available.
612 return *ratio;
613 }
614 }
615
616 // NOTE(emilio): Even though we have an intrinsic size, we may not have an
617 // intrinsic ratio. For example `<iframe style="width: 100px">` should not
618 // shrink in the vertical axis to preserve the 300x150 ratio.
619 return nsAtomicContainerFrame::GetIntrinsicRatio();
620}
621
622/* virtual */
623LogicalSize nsSubDocumentFrame::ComputeAutoSize(
624 gfxContext* aRenderingContext, WritingMode aWM, const LogicalSize& aCBSize,
625 nscoord aAvailableISize, const LogicalSize& aMargin,
626 const LogicalSize& aBorderPadding, const StyleSizeOverrides& aSizeOverrides,
627 ComputeSizeFlags aFlags) {
628 if (!IsInline()) {
629 return nsIFrame::ComputeAutoSize(aRenderingContext, aWM, aCBSize,
630 aAvailableISize, aMargin, aBorderPadding,
631 aSizeOverrides, aFlags);
632 }
633
634 const WritingMode wm = GetWritingMode();
635 LogicalSize result(wm, GetIntrinsicISize(), GetIntrinsicBSize());
636 return result.ConvertTo(aWM, wm);
637}
638
639/* virtual */
640nsIFrame::SizeComputationResult nsSubDocumentFrame::ComputeSize(
641 gfxContext* aRenderingContext, WritingMode aWM, const LogicalSize& aCBSize,
642 nscoord aAvailableISize, const LogicalSize& aMargin,
643 const LogicalSize& aBorderPadding, const StyleSizeOverrides& aSizeOverrides,
644 ComputeSizeFlags aFlags) {
645 return {ComputeSizeWithIntrinsicDimensions(
646 aRenderingContext, aWM, GetIntrinsicSize(), GetAspectRatio(),
647 aCBSize, aMargin, aBorderPadding, aSizeOverrides, aFlags),
648 AspectRatioUsage::None};
649}
650
651void nsSubDocumentFrame::Reflow(nsPresContext* aPresContext,
652 ReflowOutput& aDesiredSize,
653 const ReflowInput& aReflowInput,
654 nsReflowStatus& aStatus) {
655 MarkInReflow();
656 DO_GLOBAL_REFLOW_COUNT("nsSubDocumentFrame")aPresContext->CountReflows(("nsSubDocumentFrame"), (nsIFrame
*)this);
;
657 MOZ_ASSERT(aStatus.IsEmpty(), "Caller should pass a fresh reflow status!")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aStatus.IsEmpty())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aStatus.IsEmpty()))), 0))) {
do { } while (false); MOZ_ReportAssertionFailure("aStatus.IsEmpty()"
" (" "Caller should pass a fresh reflow status!" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 657); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aStatus.IsEmpty()"
") (" "Caller should pass a fresh reflow status!" ")"); do {
*((volatile int*)__null) = 657; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
658 NS_FRAME_TRACE(do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("enter nsSubDocumentFrame::Reflow: maxSize=%d,%d"
, aReflowInput.AvailableWidth(), aReflowInput.AvailableHeight
()); } } while (0)
659 NS_FRAME_TRACE_CALLS,do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("enter nsSubDocumentFrame::Reflow: maxSize=%d,%d"
, aReflowInput.AvailableWidth(), aReflowInput.AvailableHeight
()); } } while (0)
660 ("enter nsSubDocumentFrame::Reflow: maxSize=%d,%d",do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("enter nsSubDocumentFrame::Reflow: maxSize=%d,%d"
, aReflowInput.AvailableWidth(), aReflowInput.AvailableHeight
()); } } while (0)
661 aReflowInput.AvailableWidth(), aReflowInput.AvailableHeight()))do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("enter nsSubDocumentFrame::Reflow: maxSize=%d,%d"
, aReflowInput.AvailableWidth(), aReflowInput.AvailableHeight
()); } } while (0)
;
662
663 NS_ASSERTION(aReflowInput.ComputedISize() != NS_UNCONSTRAINEDSIZE,do { if (!(aReflowInput.ComputedISize() != NS_UNCONSTRAINEDSIZE
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Shouldn't have unconstrained inline-size here "
"thanks to the rules of reflow", "aReflowInput.ComputedISize() != NS_UNCONSTRAINEDSIZE"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 665); MOZ_PretendNoReturn(); } } while (0)
664 "Shouldn't have unconstrained inline-size here "do { if (!(aReflowInput.ComputedISize() != NS_UNCONSTRAINEDSIZE
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Shouldn't have unconstrained inline-size here "
"thanks to the rules of reflow", "aReflowInput.ComputedISize() != NS_UNCONSTRAINEDSIZE"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 665); MOZ_PretendNoReturn(); } } while (0)
665 "thanks to the rules of reflow")do { if (!(aReflowInput.ComputedISize() != NS_UNCONSTRAINEDSIZE
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Shouldn't have unconstrained inline-size here "
"thanks to the rules of reflow", "aReflowInput.ComputedISize() != NS_UNCONSTRAINEDSIZE"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 665); MOZ_PretendNoReturn(); } } while (0)
;
666 NS_ASSERTION(aReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE,do { if (!(aReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Shouldn't have unconstrained block-size here "
"thanks to ComputeAutoSize", "aReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 668); MOZ_PretendNoReturn(); } } while (0)
667 "Shouldn't have unconstrained block-size here "do { if (!(aReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Shouldn't have unconstrained block-size here "
"thanks to ComputeAutoSize", "aReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 668); MOZ_PretendNoReturn(); } } while (0)
668 "thanks to ComputeAutoSize")do { if (!(aReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE
)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Shouldn't have unconstrained block-size here "
"thanks to ComputeAutoSize", "aReflowInput.ComputedBSize() != NS_UNCONSTRAINEDSIZE"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 668); MOZ_PretendNoReturn(); } } while (0)
;
669
670 NS_ASSERTION(mContent->GetPrimaryFrame() == this, "Shouldn't happen")do { if (!(mContent->GetPrimaryFrame() == this)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "Shouldn't happen", "mContent->GetPrimaryFrame() == this"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 670); MOZ_PretendNoReturn(); } } while (0)
;
671
672 // XUL <iframe> or <browser>, or HTML <iframe>, <object> or <embed>
673 const auto wm = aReflowInput.GetWritingMode();
674 aDesiredSize.SetSize(wm, aReflowInput.ComputedSizeWithBorderPadding(wm));
675
676 // "offset" is the offset of our content area from our frame's
677 // top-left corner.
678 nsPoint offset = nsPoint(aReflowInput.ComputedPhysicalBorderPadding().left,
679 aReflowInput.ComputedPhysicalBorderPadding().top);
680
681 if (mInnerView) {
682 const nsMargin& bp = aReflowInput.ComputedPhysicalBorderPadding();
683 nsSize innerSize(aDesiredSize.Width() - bp.LeftRight(),
684 aDesiredSize.Height() - bp.TopBottom());
685
686 // Size & position the view according to 'object-fit' & 'object-position'.
687 nsRect destRect = nsLayoutUtils::ComputeObjectDestRect(
688 nsRect(offset, innerSize), GetIntrinsicSize(), GetIntrinsicRatio(),
689 StylePosition());
690
691 nsViewManager* vm = mInnerView->GetViewManager();
692 vm->MoveViewTo(mInnerView, destRect.x, destRect.y);
693 vm->ResizeView(mInnerView, nsRect(nsPoint(0, 0), destRect.Size()));
694 }
695
696 aDesiredSize.SetOverflowAreasToDesiredBounds();
697
698 FinishAndStoreOverflow(&aDesiredSize);
699
700 if (!aPresContext->IsRootPaginatedDocument() && !mPostedReflowCallback) {
701 PresShell()->PostReflowCallback(this);
702 mPostedReflowCallback = true;
703 }
704
705 NS_FRAME_TRACE(do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("exit nsSubDocumentFrame::Reflow: size=%d,%d status=%s"
, aDesiredSize.Width(), aDesiredSize.Height(), ToString(aStatus
).c_str()); } } while (0)
706 NS_FRAME_TRACE_CALLS,do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("exit nsSubDocumentFrame::Reflow: size=%d,%d status=%s"
, aDesiredSize.Width(), aDesiredSize.Height(), ToString(aStatus
).c_str()); } } while (0)
707 ("exit nsSubDocumentFrame::Reflow: size=%d,%d status=%s",do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("exit nsSubDocumentFrame::Reflow: size=%d,%d status=%s"
, aDesiredSize.Width(), aDesiredSize.Height(), ToString(aStatus
).c_str()); } } while (0)
708 aDesiredSize.Width(), aDesiredSize.Height(), ToString(aStatus).c_str()))do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("exit nsSubDocumentFrame::Reflow: size=%d,%d status=%s"
, aDesiredSize.Width(), aDesiredSize.Height(), ToString(aStatus
).c_str()); } } while (0)
;
709}
710
711bool nsSubDocumentFrame::ReflowFinished() {
712 RefPtr<nsFrameLoader> frameloader = FrameLoader();
713 if (frameloader) {
714 AutoWeakFrame weakFrame(this);
715
716 frameloader->UpdatePositionAndSize(this);
717
718 if (weakFrame.IsAlive()) {
719 // Make sure that we can post a reflow callback in the future.
720 mPostedReflowCallback = false;
721 }
722 } else {
723 mPostedReflowCallback = false;
724 }
725 return false;
726}
727
728void nsSubDocumentFrame::ReflowCallbackCanceled() {
729 mPostedReflowCallback = false;
730}
731
732nsresult nsSubDocumentFrame::AttributeChanged(int32_t aNameSpaceID,
733 nsAtom* aAttribute,
734 int32_t aModType) {
735 if (aNameSpaceID != kNameSpaceID_None) {
736 return NS_OK;
737 }
738
739 // If the noResize attribute changes, dis/allow frame to be resized
740 if (aAttribute == nsGkAtoms::noresize) {
741 // Note that we're not doing content type checks, but that's ok -- if
742 // they'd fail we will just end up with a null framesetFrame.
743 if (mContent->GetParent()->IsHTMLElement(nsGkAtoms::frameset)) {
744 nsIFrame* parentFrame = GetParent();
745
746 if (parentFrame) {
747 // There is no interface for nsHTMLFramesetFrame so QI'ing to
748 // concrete class, yay!
749 nsHTMLFramesetFrame* framesetFrame = do_QueryFrame(parentFrame);
750 if (framesetFrame) {
751 framesetFrame->RecalculateBorderResize();
752 }
753 }
754 }
755 } else if (aAttribute == nsGkAtoms::marginwidth ||
756 aAttribute == nsGkAtoms::marginheight) {
757 // Notify the frameloader
758 if (RefPtr<nsFrameLoader> frameloader = FrameLoader()) {
759 frameloader->MarginsChanged();
760 }
761 }
762
763 return NS_OK;
764}
765
766void nsSubDocumentFrame::MaybeUpdateEmbedderColorScheme() {
767 nsFrameLoader* fl = mFrameLoader.get();
768 if (!fl) {
769 return;
770 }
771
772 BrowsingContext* bc = fl->GetExtantBrowsingContext();
773 if (!bc) {
774 return;
775 }
776
777 auto ToOverride = [](ColorScheme aScheme) -> PrefersColorSchemeOverride {
778 return aScheme == ColorScheme::Dark ? PrefersColorSchemeOverride::Dark
779 : PrefersColorSchemeOverride::Light;
780 };
781
782 EmbedderColorSchemes schemes{
783 ToOverride(LookAndFeel::ColorSchemeForFrame(this, ColorSchemeMode::Used)),
784 ToOverride(
785 LookAndFeel::ColorSchemeForFrame(this, ColorSchemeMode::Preferred))};
786 if (bc->GetEmbedderColorSchemes() == schemes) {
787 return;
788 }
789
790 Unused << bc->SetEmbedderColorSchemes(schemes);
791}
792
793void nsSubDocumentFrame::MaybeUpdateRemoteStyle(
794 ComputedStyle* aOldComputedStyle) {
795 if (!mIsInObjectOrEmbed) {
796 return;
797 }
798
799 if (aOldComputedStyle &&
800 aOldComputedStyle->StyleVisibility()->mImageRendering ==
801 Style()->StyleVisibility()->mImageRendering) {
802 return;
803 }
804
805 if (!mFrameLoader) {
806 return;
807 }
808
809 if (mFrameLoader->IsRemoteFrame()) {
810 mFrameLoader->UpdateRemoteStyle(
811 Style()->StyleVisibility()->mImageRendering);
812 return;
813 }
814
815 BrowsingContext* context = mFrameLoader->GetExtantBrowsingContext();
816 if (!context) {
817 return;
818 }
819
820 Document* document = context->GetDocument();
821 if (!document) {
822 return;
823 }
824
825 if (document->IsImageDocument()) {
826 document->AsImageDocument()->UpdateRemoteStyle(
827 Style()->StyleVisibility()->mImageRendering);
828 }
829}
830
831void nsSubDocumentFrame::DidSetComputedStyle(ComputedStyle* aOldComputedStyle) {
832 nsAtomicContainerFrame::DidSetComputedStyle(aOldComputedStyle);
833
834 MaybeUpdateEmbedderColorScheme();
835
836 MaybeUpdateRemoteStyle(aOldComputedStyle);
837
838 // If this presshell has invisible ancestors, we don't need to propagate the
839 // visibility style change to the subdocument since the subdocument should
840 // have already set the IsUnderHiddenEmbedderElement flag in
841 // nsSubDocumentFrame::Init.
842 if (PresShell()->IsUnderHiddenEmbedderElement()) {
843 return;
844 }
845
846 const bool isVisible = StyleVisibility()->IsVisible();
847 if (!aOldComputedStyle ||
848 isVisible != aOldComputedStyle->StyleVisibility()->IsVisible()) {
849 PropagateIsUnderHiddenEmbedderElement(!isVisible);
850 }
851}
852
853nsIFrame* NS_NewSubDocumentFrame(PresShell* aPresShell, ComputedStyle* aStyle) {
854 return new (aPresShell)
855 nsSubDocumentFrame(aStyle, aPresShell->GetPresContext());
856}
857
858NS_IMPL_FRAMEARENA_HELPERS(nsSubDocumentFrame)void* nsSubDocumentFrame ::operator new(size_t sz, mozilla::PresShell
* aShell) { return aShell->AllocateFrame(nsQueryFrame::nsSubDocumentFrame_id
, sz); }
859
860class nsHideViewer final : public Runnable {
861 public:
862 nsHideViewer(nsIContent* aFrameElement, nsFrameLoader* aFrameLoader,
863 PresShell* aPresShell, bool aHideViewerIfFrameless)
864 : mozilla::Runnable("nsHideViewer"),
865 mFrameElement(aFrameElement),
866 mFrameLoader(aFrameLoader),
867 mPresShell(aPresShell),
868 mHideViewerIfFrameless(aHideViewerIfFrameless) {
869 NS_ASSERTION(mFrameElement, "Must have a frame element")do { if (!(mFrameElement)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "Must have a frame element", "mFrameElement", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 869); MOZ_PretendNoReturn(); } } while (0)
;
870 NS_ASSERTION(mFrameLoader, "Must have a frame loader")do { if (!(mFrameLoader)) { NS_DebugBreak(NS_DEBUG_ASSERTION,
"Must have a frame loader", "mFrameLoader", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 870); MOZ_PretendNoReturn(); } } while (0)
;
871 NS_ASSERTION(mPresShell, "Must have a presshell")do { if (!(mPresShell)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Must have a presshell"
, "mPresShell", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 871); MOZ_PretendNoReturn(); } } while (0)
;
872 }
873
874 MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHODvirtual nsresult Run() override {
875 // Flush frames, to ensure any pending display:none changes are made.
876 // Note it can be unsafe to flush if we've destroyed the presentation
877 // for some other reason, like if we're shutting down.
878 //
879 // But avoid the flush if we know for sure we're away, like when we're out
880 // of the document already.
881 //
882 // FIXME(emilio): This could still be a perf footgun when removing lots of
883 // siblings where each of them cause the reframe of an ancestor which happen
884 // to contain a subdocument.
885 //
886 // We should find some way to avoid that!
887 if (!mPresShell->IsDestroying() && mFrameElement->IsInComposedDoc()) {
888 mPresShell->FlushPendingNotifications(FlushType::Frames);
889 }
890
891 // Either the frame has been constructed by now, or it never will be,
892 // either way we want to clear the stashed views.
893 mFrameLoader->SetDetachedSubdocFrame(nullptr);
894
895 nsSubDocumentFrame* frame = do_QueryFrame(mFrameElement->GetPrimaryFrame());
896 if (!frame || frame->FrameLoader() != mFrameLoader) {
897 PropagateIsUnderHiddenEmbedderElement(mFrameLoader, true);
898 if (mHideViewerIfFrameless) {
899 // The frame element has no nsIFrame for the same frame loader.
900 // Hide the nsFrameLoader, which destroys the presentation.
901 mFrameLoader->Hide();
902 }
903 }
904 return NS_OK;
905 }
906
907 private:
908 const nsCOMPtr<nsIContent> mFrameElement;
909 const RefPtr<nsFrameLoader> mFrameLoader;
910 const RefPtr<PresShell> mPresShell;
911 const bool mHideViewerIfFrameless;
912};
913
914static nsView* BeginSwapDocShellsForViews(nsView* aSibling);
915
916void nsSubDocumentFrame::Destroy(DestroyContext& aContext) {
917 if (mPostedReflowCallback) {
918 PresShell()->CancelReflowCallback(this);
919 mPostedReflowCallback = false;
920 }
921
922 // Detach the subdocument's views and stash them in the frame loader.
923 // We can then reattach them if we're being reframed (for example if
924 // the frame has been made position:fixed).
925 if (RefPtr<nsFrameLoader> frameloader = FrameLoader()) {
926 ClearDisplayItems();
927
928 nsView* detachedViews =
929 ::BeginSwapDocShellsForViews(mInnerView->GetFirstChild());
930
931 frameloader->SetDetachedSubdocFrame(
932 detachedViews ? detachedViews->GetFrame() : nullptr);
933
934 // We call nsFrameLoader::HideViewer() in a script runner so that we can
935 // safely determine whether the frame is being reframed or destroyed.
936 nsContentUtils::AddScriptRunner(new nsHideViewer(
937 mContent, frameloader, PresShell(), (mDidCreateDoc || mCallingShow)));
938 }
939
940 nsAtomicContainerFrame::Destroy(aContext);
941}
942
943nsFrameLoader* nsSubDocumentFrame::FrameLoader() const {
944 if (mFrameLoader) {
945 return mFrameLoader;
946 }
947
948 if (RefPtr<nsFrameLoaderOwner> loaderOwner = do_QueryObject(GetContent())) {
949 mFrameLoader = loaderOwner->GetFrameLoader();
950 }
951
952 return mFrameLoader;
953}
954
955auto nsSubDocumentFrame::GetRemotePaintData() const -> RemoteFramePaintData {
956 if (mRetainedRemoteFrame) {
957 return *mRetainedRemoteFrame;
958 }
959
960 RemoteFramePaintData data;
961 nsFrameLoader* fl = FrameLoader();
962 if (!fl) {
963 return data;
964 }
965
966 auto* rb = fl->GetRemoteBrowser();
967 if (!rb) {
968 return data;
969 }
970 data.mLayersId = rb->GetLayersId();
971 data.mTabId = rb->GetTabId();
972 return data;
973}
974
975void nsSubDocumentFrame::ResetFrameLoader(RetainPaintData aRetain) {
976 if (aRetain == RetainPaintData::Yes && mFrameLoader) {
977 mRetainedRemoteFrame = Some(GetRemotePaintData());
978 } else {
979 mRetainedRemoteFrame.reset();
980 }
981 mFrameLoader = nullptr;
982 ClearDisplayItems();
983 nsContentUtils::AddScriptRunner(new AsyncFrameInit(this));
984}
985
986void nsSubDocumentFrame::ClearRetainedPaintData() {
987 mRetainedRemoteFrame.reset();
988 ClearDisplayItems();
989 InvalidateFrameSubtree();
990}
991
992// XXX this should be called ObtainDocShell or something like that,
993// to indicate that it could have side effects
994nsIDocShell* nsSubDocumentFrame::GetDocShell() const {
995 // How can FrameLoader() return null???
996 if (NS_WARN_IF(!FrameLoader())NS_warn_if_impl(!FrameLoader(), "!FrameLoader()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 996)
) {
997 return nullptr;
998 }
999 return mFrameLoader->GetDocShell(IgnoreErrors());
1000}
1001
1002static void DestroyDisplayItemDataForFrames(nsIFrame* aFrame) {
1003 // Destroying a WebRenderUserDataTable can cause destruction of other objects
1004 // which can remove frame properties in their destructor. If we delete a frame
1005 // property it runs the destructor of the stored object in the middle of
1006 // updating the frame property table, so if the destruction of that object
1007 // causes another update to the frame property table it would leave the frame
1008 // property table in an inconsistent state. So we remove it from the table and
1009 // then destroy it. (bug 1530657)
1010 WebRenderUserDataTable* userDataTable =
1011 aFrame->TakeProperty(WebRenderUserDataProperty::Key());
1012 if (userDataTable) {
1013 for (const auto& data : userDataTable->Values()) {
1014 data->RemoveFromTable();
1015 }
1016 delete userDataTable;
1017 }
1018
1019 for (const auto& childList : aFrame->ChildLists()) {
1020 for (nsIFrame* child : childList.mList) {
1021 DestroyDisplayItemDataForFrames(child);
1022 }
1023 }
1024}
1025
1026static CallState BeginSwapDocShellsForDocument(Document& aDocument) {
1027 if (PresShell* presShell = aDocument.GetPresShell()) {
1028 // Disable painting while the views are detached, see bug 946929.
1029 presShell->SetNeverPainting(true);
1030
1031 if (nsIFrame* rootFrame = presShell->GetRootFrame()) {
1032 ::DestroyDisplayItemDataForFrames(rootFrame);
1033 }
1034 }
1035 aDocument.EnumerateSubDocuments(BeginSwapDocShellsForDocument);
1036 return CallState::Continue;
1037}
1038
1039static nsView* BeginSwapDocShellsForViews(nsView* aSibling) {
1040 // Collect the removed sibling views in reverse order in 'removedViews'.
1041 nsView* removedViews = nullptr;
1042 while (aSibling) {
1043 if (Document* doc = ::GetDocumentFromView(aSibling)) {
1044 ::BeginSwapDocShellsForDocument(*doc);
1045 }
1046 nsView* next = aSibling->GetNextSibling();
1047 aSibling->GetViewManager()->RemoveChild(aSibling);
1048 aSibling->SetNextSibling(removedViews);
1049 removedViews = aSibling;
1050 aSibling = next;
1051 }
1052 return removedViews;
1053}
1054
1055/* static */
1056void nsSubDocumentFrame::InsertViewsInReverseOrder(nsView* aSibling,
1057 nsView* aParent) {
1058 MOZ_ASSERT(aParent, "null view")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aParent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aParent))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aParent" " (" "null view"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 1058); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aParent" ") ("
"null view" ")"); do { *((volatile int*)__null) = 1058; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
;
1059 MOZ_ASSERT(!aParent->GetFirstChild(), "inserting into non-empty list")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!aParent->GetFirstChild())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!aParent->GetFirstChild()
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"!aParent->GetFirstChild()" " (" "inserting into non-empty list"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 1059); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!aParent->GetFirstChild()"
") (" "inserting into non-empty list" ")"); do { *((volatile
int*)__null) = 1059; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
1060
1061 nsViewManager* vm = aParent->GetViewManager();
1062 while (aSibling) {
1063 nsView* next = aSibling->GetNextSibling();
1064 aSibling->SetNextSibling(nullptr);
1065 // true means 'after' in document order which is 'before' in view order,
1066 // so this call prepends the child, thus reversing the siblings as we go.
1067 vm->InsertChild(aParent, aSibling, nullptr, true);
1068 aSibling = next;
1069 }
1070}
1071
1072nsresult nsSubDocumentFrame::BeginSwapDocShells(nsIFrame* aOther) {
1073 if (!aOther || !aOther->IsSubDocumentFrame()) {
1074 return NS_ERROR_NOT_IMPLEMENTED;
1075 }
1076
1077 nsSubDocumentFrame* other = static_cast<nsSubDocumentFrame*>(aOther);
1078 if (!mFrameLoader || !mDidCreateDoc || mCallingShow || !other->mFrameLoader ||
1079 !other->mDidCreateDoc) {
1080 return NS_ERROR_NOT_IMPLEMENTED;
1081 }
1082
1083 ClearDisplayItems();
1084 other->ClearDisplayItems();
1085
1086 if (mInnerView && other->mInnerView) {
1087 nsView* ourSubdocViews = mInnerView->GetFirstChild();
1088 nsView* ourRemovedViews = ::BeginSwapDocShellsForViews(ourSubdocViews);
1089 nsView* otherSubdocViews = other->mInnerView->GetFirstChild();
1090 nsView* otherRemovedViews = ::BeginSwapDocShellsForViews(otherSubdocViews);
1091
1092 InsertViewsInReverseOrder(ourRemovedViews, other->mInnerView);
1093 InsertViewsInReverseOrder(otherRemovedViews, mInnerView);
1094 }
1095 mFrameLoader.swap(other->mFrameLoader);
1096 return NS_OK;
1097}
1098
1099static CallState EndSwapDocShellsForDocument(Document& aDocument) {
1100 // Our docshell and view trees have been updated for the new hierarchy.
1101 // Now also update all nsDeviceContext::mWidget to that of the
1102 // container view in the new hierarchy.
1103 if (nsCOMPtr<nsIDocShell> ds = aDocument.GetDocShell()) {
1104 nsCOMPtr<nsIDocumentViewer> viewer;
1105 ds->GetDocViewer(getter_AddRefs(viewer));
1106 while (viewer) {
1107 RefPtr<nsPresContext> pc = viewer->GetPresContext();
1108 if (pc && pc->GetPresShell()) {
1109 pc->GetPresShell()->SetNeverPainting(ds->IsInvisible());
1110 }
1111 nsDeviceContext* dc = pc ? pc->DeviceContext() : nullptr;
1112 if (dc) {
1113 nsView* v = viewer->FindContainerView();
1114 dc->Init(v ? v->GetNearestWidget(nullptr) : nullptr);
1115 }
1116 viewer = viewer->GetPreviousViewer();
1117 }
1118 }
1119
1120 aDocument.EnumerateSubDocuments(EndSwapDocShellsForDocument);
1121 return CallState::Continue;
1122}
1123
1124/* static */
1125void nsSubDocumentFrame::EndSwapDocShellsForViews(nsView* aSibling) {
1126 for (; aSibling; aSibling = aSibling->GetNextSibling()) {
1127 if (Document* doc = ::GetDocumentFromView(aSibling)) {
1128 ::EndSwapDocShellsForDocument(*doc);
1129 }
1130 nsIFrame* frame = aSibling->GetFrame();
1131 if (frame) {
1132 nsIFrame* parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(frame);
1133 if (parent->HasAnyStateBits(NS_FRAME_IN_POPUP)) {
1134 nsIFrame::AddInPopupStateBitToDescendants(frame);
1135 } else {
1136 nsIFrame::RemoveInPopupStateBitFromDescendants(frame);
1137 }
1138 if (frame->HasInvalidFrameInSubtree()) {
1139 while (parent &&
1140 !parent->HasAnyStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT |
1141 NS_FRAME_IS_NONDISPLAY)) {
1142 parent->AddStateBits(NS_FRAME_DESCENDANT_NEEDS_PAINT);
1143 parent = nsLayoutUtils::GetCrossDocParentFrameInProcess(parent);
1144 }
1145 }
1146 }
1147 }
1148}
1149
1150void nsSubDocumentFrame::EndSwapDocShells(nsIFrame* aOther) {
1151 nsSubDocumentFrame* other = static_cast<nsSubDocumentFrame*>(aOther);
1152 AutoWeakFrame weakThis(this);
1153 AutoWeakFrame weakOther(aOther);
1154
1155 if (mInnerView) {
1156 EndSwapDocShellsForViews(mInnerView->GetFirstChild());
1157 }
1158 if (other->mInnerView) {
1159 EndSwapDocShellsForViews(other->mInnerView->GetFirstChild());
1160 }
1161
1162 // Now make sure we reflow both frames, in case their contents
1163 // determine their size.
1164 // And repaint them, for good measure, in case there's nothing
1165 // interesting that happens during reflow.
1166 if (weakThis.IsAlive()) {
1167 PresShell()->FrameNeedsReflow(this, IntrinsicDirty::FrameAndAncestors,
1168 NS_FRAME_IS_DIRTY);
1169 InvalidateFrameSubtree();
1170 PropagateIsUnderHiddenEmbedderElement(
1171 PresShell()->IsUnderHiddenEmbedderElement() ||
1172 !StyleVisibility()->IsVisible());
1173 }
1174 if (weakOther.IsAlive()) {
1175 other->PresShell()->FrameNeedsReflow(
1176 other, IntrinsicDirty::FrameAndAncestors, NS_FRAME_IS_DIRTY);
1177 other->InvalidateFrameSubtree();
1178 other->PropagateIsUnderHiddenEmbedderElement(
1179 other->PresShell()->IsUnderHiddenEmbedderElement() ||
1180 !other->StyleVisibility()->IsVisible());
1181 }
1182}
1183
1184void nsSubDocumentFrame::ClearDisplayItems() {
1185 if (auto* builder = nsLayoutUtils::GetRetainedDisplayListBuilder(this)) {
1186 DL_LOGD("nsSubDocumentFrame::ClearDisplayItems() %p", this)do { const ::mozilla::LogModule* moz_real_module = GetLoggerByProcess
(); if ((__builtin_expect(!!(mozilla::detail::log_test(moz_real_module
, LogLevel::Debug)), 0))) { mozilla::detail::log_print(moz_real_module
, LogLevel::Debug, "nsSubDocumentFrame::ClearDisplayItems() %p"
, this); } } while (0)
;
1187 builder->ClearRetainedData();
1188 }
1189}
1190
1191nsView* nsSubDocumentFrame::EnsureInnerView() {
1192 if (mInnerView) {
1193 return mInnerView;
1194 }
1195
1196 // create, init, set the parent of the view
1197 nsView* outerView = GetView();
1198 NS_ASSERTION(outerView, "Must have an outer view already")do { if (!(outerView)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Must have an outer view already"
, "outerView", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 1198); MOZ_PretendNoReturn(); } } while (0)
;
1199 nsRect viewBounds(0, 0, 0, 0); // size will be fixed during reflow
1200
1201 nsViewManager* viewMan = outerView->GetViewManager();
1202 nsView* innerView = viewMan->CreateView(viewBounds, outerView);
1203 if (!innerView) {
1204 NS_ERROR("Could not create inner view")do { NS_DebugBreak(NS_DEBUG_ASSERTION, "Could not create inner view"
, "Error", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 1204); MOZ_PretendNoReturn(); } while (0)
;
1205 return nullptr;
1206 }
1207 mInnerView = innerView;
1208 viewMan->InsertChild(outerView, innerView, nullptr, true);
1209
1210 return mInnerView;
1211}
1212
1213nsPoint nsSubDocumentFrame::GetExtraOffset() const {
1214 MOZ_ASSERT(mInnerView)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mInnerView)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mInnerView))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("mInnerView", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 1214); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mInnerView"
")"); do { *((volatile int*)__null) = 1214; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1215 return mInnerView->GetPosition();
1216}
1217
1218void nsSubDocumentFrame::SubdocumentIntrinsicSizeOrRatioChanged() {
1219 const nsStylePosition* pos = StylePosition();
1220 bool dependsOnIntrinsics =
1221 !pos->mWidth.ConvertsToLength() || !pos->mHeight.ConvertsToLength();
1222
1223 if (dependsOnIntrinsics || pos->mObjectFit != StyleObjectFit::Fill) {
1224 auto dirtyHint = dependsOnIntrinsics
1225 ? IntrinsicDirty::FrameAncestorsAndDescendants
1226 : IntrinsicDirty::None;
1227 PresShell()->FrameNeedsReflow(this, dirtyHint, NS_FRAME_IS_DIRTY);
1228 InvalidateFrame();
1229 }
1230}
1231
1232// Return true iff |aManager| is a "temporary layer manager". They're
1233// used for small software rendering tasks, like drawWindow. That's
1234// currently implemented by a BasicLayerManager without a backing
1235// widget, and hence in non-retained mode.
1236nsDisplayRemote::nsDisplayRemote(nsDisplayListBuilder* aBuilder,
1237 nsSubDocumentFrame* aFrame)
1238 : nsPaintedDisplayItem(aBuilder, aFrame),
1239 mEventRegionsOverride(EventRegionsOverride::NoOverride) {
1240 const bool frameIsPointerEventsNone =
1241 aFrame->Style()->PointerEvents() == StylePointerEvents::None;
1242 if (aBuilder->IsInsidePointerEventsNoneDoc() || frameIsPointerEventsNone) {
1243 mEventRegionsOverride |= EventRegionsOverride::ForceEmptyHitRegion;
1244 }
1245 if (nsLayoutUtils::HasDocumentLevelListenersForApzAwareEvents(
1246 aFrame->PresShell())) {
1247 mEventRegionsOverride |= EventRegionsOverride::ForceDispatchToContent;
1248 }
1249
1250 mPaintData = aFrame->GetRemotePaintData();
1251}
1252
1253namespace mozilla {
1254
1255void nsDisplayRemote::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
1256 nsPresContext* pc = mFrame->PresContext();
1257 nsFrameLoader* fl = GetFrameLoader();
1258 if (pc->GetPrintSettings() && fl->IsRemoteFrame()) {
1259 // See the comment below in CreateWebRenderCommands() as for why doing this.
1260 fl->UpdatePositionAndSize(static_cast<nsSubDocumentFrame*>(mFrame));
1261 }
1262
1263 DrawTarget* target = aCtx->GetDrawTarget();
1264 if (!target->IsRecording() || mPaintData.mTabId == 0) {
1265 NS_WARNING("Remote iframe not rendered")NS_DebugBreak(NS_DEBUG_WARNING, "Remote iframe not rendered",
nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsSubDocumentFrame.cpp"
, 1265)
;
1266 return;
1267 }
1268
1269 // Rendering the inner document will apply a scale to account for its app
1270 // units per dev pixel ratio. We want to apply the inverse scaling using our
1271 // app units per dev pixel ratio, so that no actual scaling will be applied if
1272 // they match. For in-process rendering, nsSubDocumentFrame creates an
1273 // nsDisplayZoom item if the app units per dev pixel ratio changes.
1274 //
1275 // Similarly, rendering the inner document will scale up by the cross process
1276 // paint scale again, so we also need to account for that.
1277 const int32_t appUnitsPerDevPixel = pc->AppUnitsPerDevPixel();
1278
1279 gfxContextMatrixAutoSaveRestore saveMatrix(aCtx);
1280 gfxFloat targetAuPerDev =
1281 gfxFloat(AppUnitsPerCSSPixel()) / aCtx->GetCrossProcessPaintScale();
1282
1283 gfxFloat scale = targetAuPerDev / appUnitsPerDevPixel;
1284 aCtx->Multiply(gfxMatrix::Scaling(scale, scale));
1285
1286 Rect destRect =
1287 NSRectToSnappedRect(GetContentRect(), targetAuPerDev, *target);
1288 target->DrawDependentSurface(mPaintData.mTabId, destRect);
1289}
1290
1291bool nsDisplayRemote::CreateWebRenderCommands(
1292 mozilla::wr::DisplayListBuilder& aBuilder,
1293 mozilla::wr::IpcResourceUpdateQueue& aResources,
1294 const StackingContextHelper& aSc,
1295 mozilla::layers::RenderRootStateManager* aManager,
1296 nsDisplayListBuilder* aDisplayListBuilder) {
1297 if (!mPaintData.mLayersId.IsValid()) {
1298 return true;
1299 }
1300
1301 nsPresContext* pc = mFrame->PresContext();
1302 nsFrameLoader* fl = GetFrameLoader();
1303
1304 auto* subDocFrame = static_cast<nsSubDocumentFrame*>(mFrame);
1305 nsRect destRect = subDocFrame->GetDestRect();
1306 if (RefPtr<RemoteBrowser> remoteBrowser = fl->GetRemoteBrowser()) {
1307 if (pc->GetPrintSettings()) {
1308 // HACK(emilio): Usually we update sizing/positioning from
1309 // ReflowFinished(). Print documents have no incremental reflow at all
1310 // though, so we can't rely on it firing after a frame becomes remote.
1311 // Thus, if we're painting a remote frame, update its sizing and position
1312 // now.
1313 //
1314 // UpdatePositionAndSize() can cause havoc for non-remote frames but
1315 // luckily we don't care about those, so this is fine.
1316 fl->UpdatePositionAndSize(subDocFrame);
1317 }
1318
1319 // Adjust mItemVisibleRect, which is relative to the reference frame, to be
1320 // relative to this frame.
1321 const nsRect buildingRect = GetBuildingRect() - ToReferenceFrame();
1322 Maybe<nsRect> visibleRect =
1323 buildingRect.EdgeInclusiveIntersection(destRect);
1324 if (visibleRect) {
1325 *visibleRect -= destRect.TopLeft();
1326 }
1327
1328 // Generate an effects update notifying the browser it is visible
1329 MatrixScales scale = aSc.GetInheritedScale();
1330
1331 ParentLayerToScreenScale2D transformToAncestorScale =
1332 ParentLayerToParentLayerScale(
1333 pc->GetPresShell() ? pc->GetPresShell()->GetCumulativeResolution()
1334 : 1.f) *
1335 nsLayoutUtils::GetTransformToAncestorScaleCrossProcessForFrameMetrics(
1336 mFrame);
1337
1338 aDisplayListBuilder->AddEffectUpdate(
1339 remoteBrowser, EffectsInfo::VisibleWithinRect(
1340 visibleRect, scale, transformToAncestorScale));
1341
1342 // Create a WebRenderRemoteData to notify the RemoteBrowser when it is no
1343 // longer visible
1344 RefPtr<WebRenderRemoteData> userData =
1345 aManager->CommandBuilder()
1346 .CreateOrRecycleWebRenderUserData<WebRenderRemoteData>(this,
1347 nullptr);
1348 userData->SetRemoteBrowser(remoteBrowser);
1349 }
1350
1351 nscoord auPerDevPixel = pc->AppUnitsPerDevPixel();
1352 nsPoint layerOffset =
1353 aDisplayListBuilder->ToReferenceFrame(mFrame) + destRect.TopLeft();
1354 mOffset = LayoutDevicePoint::FromAppUnits(layerOffset, auPerDevPixel);
1355
1356 destRect.MoveTo(0, 0);
1357 auto rect = LayoutDeviceRect::FromAppUnits(destRect, auPerDevPixel);
1358 rect += mOffset;
1359
1360 aBuilder.PushIFrame(rect, !BackfaceIsHidden(),
1361 mozilla::wr::AsPipelineId(mPaintData.mLayersId),
1362 /*ignoreMissingPipelines*/ true);
1363
1364 return true;
1365}
1366
1367bool nsDisplayRemote::UpdateScrollData(
1368 mozilla::layers::WebRenderScrollData* aData,
1369 mozilla::layers::WebRenderLayerScrollData* aLayerData) {
1370 if (!mPaintData.mLayersId.IsValid()) {
1371 return true;
1372 }
1373
1374 if (aLayerData) {
1375 aLayerData->SetReferentId(mPaintData.mLayersId);
1376
1377 auto size = static_cast<nsSubDocumentFrame*>(mFrame)->GetSubdocumentSize();
1378 Matrix4x4 m = Matrix4x4::Translation(mOffset.x, mOffset.y, 0.0);
1379 aLayerData->SetTransform(m);
1380 aLayerData->SetEventRegionsOverride(mEventRegionsOverride);
1381 aLayerData->SetRemoteDocumentSize(LayerIntSize(size.width, size.height));
1382 }
1383 return true;
1384}
1385
1386nsFrameLoader* nsDisplayRemote::GetFrameLoader() const {
1387 return static_cast<nsSubDocumentFrame*>(mFrame)->FrameLoader();
1388}
1389
1390} // namespace mozilla