Bug Summary

File:var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp
Warning:line 171, column 5
Value stored to 'result' 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_generic2.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-20/lib/clang/20 -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 _GLIBCXX_ASSERTIONS -D DEBUG=1 -D MOZ_HAS_MOZGLUE -D MOZILLA_INTERNAL_API -D IMPL_LIBXUL -D MOZ_SUPPORT_LEAKCHECKING -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/sysprof-6 -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/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/x86_64-linux-gnu/c++/14 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../include/c++/14/backward -internal-isystem /usr/lib/llvm-20/lib/clang/20/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/14/../../../../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 -fstrict-flex-arrays=1 -stack-protector 2 -fstack-clash-protection -ftrivial-auto-var-init=pattern -fno-rtti -fgnuc-version=4.2.1 -fskip-odr-check-in-gmf -fno-sized-deallocation -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-2025-01-14-004844-944539-1 -x c++ Unified_cpp_layout_generic2.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/* rendering object for replaced elements with image data */
8
9#include "nsImageFrame.h"
10
11#include "TextDrawTarget.h"
12#include "gfx2DGlue.h"
13#include "gfxContext.h"
14#include "gfxUtils.h"
15#include "mozilla/dom/NameSpaceConstants.h"
16#include "mozilla/intl/BidiEmbeddingLevel.h"
17#include "mozilla/ComputedStyle.h"
18#include "mozilla/DebugOnly.h"
19#include "mozilla/Encoding.h"
20#include "mozilla/HTMLEditor.h"
21#include "mozilla/dom/FetchPriority.h"
22#include "mozilla/dom/ImageTracker.h"
23#include "mozilla/gfx/2D.h"
24#include "mozilla/gfx/Helpers.h"
25#include "mozilla/gfx/PathHelpers.h"
26#include "mozilla/dom/GeneratedImageContent.h"
27#include "mozilla/dom/HTMLAreaElement.h"
28#include "mozilla/dom/HTMLImageElement.h"
29#include "mozilla/dom/ReferrerInfo.h"
30#include "mozilla/dom/ResponsiveImageSelector.h"
31#include "mozilla/dom/LargestContentfulPaint.h"
32#include "mozilla/image/WebRenderImageProvider.h"
33#include "mozilla/layers/RenderRootStateManager.h"
34#include "mozilla/layers/WebRenderLayerManager.h"
35#include "mozilla/MouseEvents.h"
36#include "mozilla/PresShell.h"
37#include "mozilla/PresShellInlines.h"
38#include "mozilla/StaticPrefs_browser.h"
39#include "mozilla/StaticPrefs_image.h"
40#include "mozilla/StaticPrefs_layout.h"
41#include "mozilla/SVGImageContext.h"
42#include "mozilla/Unused.h"
43
44#include "nsCOMPtr.h"
45#include "nsFontMetrics.h"
46#include "nsIFrameInlines.h"
47#include "nsIImageLoadingContent.h"
48#include "nsImageLoadingContent.h"
49#include "nsImageRenderer.h"
50#include "nsObjectLoadingContent.h"
51#include "nsString.h"
52#include "nsPrintfCString.h"
53#include "nsPresContext.h"
54#include "nsGkAtoms.h"
55#include "mozilla/dom/Document.h"
56#include "nsContentUtils.h"
57#include "nsCSSAnonBoxes.h"
58#include "nsStyleConsts.h"
59#include "nsStyleUtil.h"
60#include "nsTransform2D.h"
61#include "nsImageMap.h"
62#include "nsILoadGroup.h"
63#include "nsNetUtil.h"
64#include "nsNetCID.h"
65#include "nsCSSRendering.h"
66#include "nsNameSpaceManager.h"
67#include <algorithm>
68#ifdef ACCESSIBILITY1
69# include "nsAccessibilityService.h"
70#endif
71#include "nsLayoutUtils.h"
72#include "nsDisplayList.h"
73#include "nsIContent.h"
74#include "mozilla/dom/Selection.h"
75#include "nsIURIMutator.h"
76
77#include "imgIContainer.h"
78#include "imgLoader.h"
79#include "imgRequestProxy.h"
80
81#include "nsCSSFrameConstructor.h"
82#include "nsRange.h"
83
84#include "nsError.h"
85#include "nsBidiUtils.h"
86#include "nsBidiPresUtils.h"
87
88#include "gfxRect.h"
89#include "ImageRegion.h"
90#include "ImageContainer.h"
91#include "mozilla/ServoStyleSet.h"
92#include "nsBlockFrame.h"
93#include "nsStyleStructInlines.h"
94
95#include "mozilla/Preferences.h"
96
97#include "mozilla/dom/Link.h"
98#include "mozilla/dom/HTMLAnchorElement.h"
99#include "mozilla/dom/BrowserChild.h"
100
101using namespace mozilla;
102using namespace mozilla::dom;
103using namespace mozilla::gfx;
104using namespace mozilla::image;
105using namespace mozilla::layers;
106
107using mozilla::layout::TextDrawTarget;
108
109class nsDisplayGradient final : public nsPaintedDisplayItem {
110 public:
111 nsDisplayGradient(nsDisplayListBuilder* aBuilder, nsImageFrame* aFrame)
112 : nsPaintedDisplayItem(aBuilder, aFrame) {
113 MOZ_COUNT_CTOR(nsDisplayGradient)do { static_assert(std::is_class_v<nsDisplayGradient>, "Token '"
"nsDisplayGradient" "' is not a class type."); static_assert
(!std::is_base_of<nsISupports, nsDisplayGradient>::value
, "nsISupports classes don't need to call MOZ_COUNT_CTOR or "
"MOZ_COUNT_DTOR");; NS_LogCtor((void*)this, "nsDisplayGradient"
, sizeof(*this)); } while (0)
;
114 }
115
116 MOZ_COUNTED_DTOR_FINAL(nsDisplayGradient)~nsDisplayGradient() final { do { static_assert(std::is_class_v
<nsDisplayGradient>, "Token '" "nsDisplayGradient" "' is not a class type."
); static_assert(!std::is_base_of<nsISupports, nsDisplayGradient
>::value, "nsISupports classes don't need to call MOZ_COUNT_CTOR or "
"MOZ_COUNT_DTOR");; NS_LogDtor((void*)this, "nsDisplayGradient"
, sizeof(*this)); } while (0); }
117
118 nsRect GetBounds(bool* aSnap) const {
119 *aSnap = true;
120 return Frame()->GetContentRectRelativeToSelf() + ToReferenceFrame();
121 }
122
123 nsRect GetBounds(nsDisplayListBuilder*, bool* aSnap) const final {
124 return GetBounds(aSnap);
125 }
126
127 void Paint(nsDisplayListBuilder*, gfxContext* aCtx) final;
128
129 bool CreateWebRenderCommands(mozilla::wr::DisplayListBuilder&,
130 mozilla::wr::IpcResourceUpdateQueue&,
131 const StackingContextHelper&,
132 mozilla::layers::RenderRootStateManager*,
133 nsDisplayListBuilder*) final;
134
135 NS_DISPLAY_DECL_NAME("Gradient", TYPE_GRADIENT)const char* Name() const override { return "Gradient"; } constexpr
static DisplayItemType ItemType() { return DisplayItemType::
TYPE_GRADIENT; } private: void* operator new(size_t aSize, nsDisplayListBuilder
* aBuilder) { return aBuilder->Allocate(aSize, DisplayItemType
::TYPE_GRADIENT); } template <typename T, typename F, typename
... Args> friend T* mozilla::MakeDisplayItemWithIndex( nsDisplayListBuilder
* aBuilder, F* aFrame, const uint16_t aIndex, Args&&...
aArgs); public:
136};
137
138void nsDisplayGradient::Paint(nsDisplayListBuilder* aBuilder,
139 gfxContext* aCtx) {
140 auto* frame = static_cast<nsImageFrame*>(Frame());
141 nsImageRenderer imageRenderer(frame, frame->GetImageFromStyle(),
142 aBuilder->GetImageRendererFlags());
143 nsSize size = frame->GetSize();
144 imageRenderer.SetPreferredSize({}, size);
145
146 ImgDrawResult result;
147 if (!imageRenderer.PrepareImage()) {
148 result = imageRenderer.PrepareResult();
149 } else {
150 nsRect dest(ToReferenceFrame(), size);
151 result = imageRenderer.DrawLayer(
152 frame->PresContext(), *aCtx, dest, dest, dest.TopLeft(),
153 GetPaintRect(aBuilder, aCtx), dest.Size(), /* aOpacity = */ 1.0f);
154 }
155 Unused << result;
156}
157
158bool nsDisplayGradient::CreateWebRenderCommands(
159 wr::DisplayListBuilder& aBuilder, wr::IpcResourceUpdateQueue& aResources,
160 const StackingContextHelper& aSc,
161 mozilla::layers::RenderRootStateManager* aManager,
162 nsDisplayListBuilder* aDisplayListBuilder) {
163 auto* frame = static_cast<nsImageFrame*>(Frame());
164 nsImageRenderer imageRenderer(frame, frame->GetImageFromStyle(),
165 aDisplayListBuilder->GetImageRendererFlags());
166 nsSize size = frame->GetSize();
167 imageRenderer.SetPreferredSize({}, size);
168
169 ImgDrawResult result;
170 if (!imageRenderer.PrepareImage()) {
171 result = imageRenderer.PrepareResult();
Value stored to 'result' is never read
172 } else {
173 nsRect dest(ToReferenceFrame(), size);
174 result = imageRenderer.BuildWebRenderDisplayItemsForLayer(
175 frame->PresContext(), aBuilder, aResources, aSc, aManager, this, dest,
176 dest, dest.TopLeft(), dest, dest.Size(),
177 /* aOpacity = */ 1.0f);
178 if (result == ImgDrawResult::NOT_SUPPORTED) {
179 return false;
180 }
181 }
182 return true;
183}
184
185// sizes (pixels) for image icon, padding and border frame
186#define ICON_SIZE(16) (16)
187#define ICON_PADDING(3) (3)
188#define ALT_BORDER_WIDTH(1) (1)
189
190// Default alignment value (so we can tell an unset value from a set value)
191#define ALIGN_UNSETuint8_t(-1) uint8_t(-1)
192
193class BrokenImageIcon final : public imgINotificationObserver {
194 // private class that wraps the data and logic needed for
195 // broken image and loading image icons
196 public:
197 explicit BrokenImageIcon(const nsImageFrame& aFrame);
198 static void Shutdown();
199
200 NS_DECL_ISUPPORTSpublic: virtual nsresult QueryInterface(const nsIID& aIID
, void** aInstancePtr) override; virtual MozExternalRefCountType
AddRef(void) override; virtual MozExternalRefCountType Release
(void) override; using HasThreadSafeRefCnt = std::false_type;
protected: nsAutoRefCnt mRefCnt; nsAutoOwningThread _mOwningThread
; public:
201 NS_DECL_IMGINOTIFICATIONOBSERVERvirtual void Notify(imgIRequest *aProxy, int32_t aType, const
nsIntRect * aRect) override;
202
203 static imgRequestProxy* GetImage(nsImageFrame* aFrame) {
204 return Get(*aFrame).mImage.get();
205 }
206
207 static void AddObserver(nsImageFrame* aFrame) {
208 auto& instance = Get(*aFrame);
209 MOZ_ASSERT(!instance.mObservers.Contains(aFrame),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!instance.mObservers.Contains(aFrame))>::isValid,
"invalid assertion condition"); if ((__builtin_expect(!!(!(!
!(!instance.mObservers.Contains(aFrame)))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!instance.mObservers.Contains(aFrame)"
" (" "Observer shouldn't aleady be in array" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 210); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!instance.mObservers.Contains(aFrame)"
") (" "Observer shouldn't aleady be in array" ")"); do { *((
volatile int*)__null) = 210; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
210 "Observer shouldn't aleady be in array")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!instance.mObservers.Contains(aFrame))>::isValid,
"invalid assertion condition"); if ((__builtin_expect(!!(!(!
!(!instance.mObservers.Contains(aFrame)))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("!instance.mObservers.Contains(aFrame)"
" (" "Observer shouldn't aleady be in array" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 210); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!instance.mObservers.Contains(aFrame)"
") (" "Observer shouldn't aleady be in array" ")"); do { *((
volatile int*)__null) = 210; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
211 instance.mObservers.AppendElement(aFrame);
212 }
213
214 static void RemoveObserver(nsImageFrame* aFrame) {
215 auto& instance = Get(*aFrame);
216 DebugOnly<bool> didRemove = instance.mObservers.RemoveElement(aFrame);
217 MOZ_ASSERT(didRemove, "Observer not in array")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(didRemove)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(didRemove))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("didRemove" " (" "Observer not in array"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 217); AnnotateMozCrashReason("MOZ_ASSERT" "(" "didRemove" ") ("
"Observer not in array" ")"); do { *((volatile int*)__null) =
217; __attribute__((nomerge)) ::abort(); } while (false); } }
while (false)
;
218 }
219
220 private:
221 static BrokenImageIcon& Get(const nsImageFrame& aFrame) {
222 if (!gSingleton) {
223 gSingleton = new BrokenImageIcon(aFrame);
224 }
225 return *gSingleton;
226 }
227
228 ~BrokenImageIcon() = default;
229
230 nsTObserverArray<nsImageFrame*> mObservers;
231 RefPtr<imgRequestProxy> mImage;
232
233 static StaticRefPtr<BrokenImageIcon> gSingleton;
234};
235
236StaticRefPtr<BrokenImageIcon> BrokenImageIcon::gSingleton;
237
238NS_IMPL_ISUPPORTS(BrokenImageIcon, imgINotificationObserver)MozExternalRefCountType BrokenImageIcon::AddRef(void) { static_assert
(!std::is_destructible_v<BrokenImageIcon>, "Reference-counted class "
"BrokenImageIcon" " should not have a public destructor. " "Make this class's destructor non-public"
); do { static_assert( mozilla::detail::AssertionConditionType
<decltype(int32_t(mRefCnt) >= 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(int32_t(mRefCnt) >= 0))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("int32_t(mRefCnt) >= 0"
" (" "illegal refcnt" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 238); AnnotateMozCrashReason("MOZ_ASSERT" "(" "int32_t(mRefCnt) >= 0"
") (" "illegal refcnt" ")"); do { *((volatile int*)__null) =
238; __attribute__((nomerge)) ::abort(); } while (false); } }
while (false); do { static_assert( mozilla::detail::AssertionConditionType
<decltype("BrokenImageIcon" != nullptr)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!("BrokenImageIcon" != nullptr
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"\"BrokenImageIcon\" != nullptr" " (" "Must specify a name" ")"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 238); AnnotateMozCrashReason("MOZ_ASSERT" "(" "\"BrokenImageIcon\" != nullptr"
") (" "Must specify a name" ")"); do { *((volatile int*)__null
) = 238; __attribute__((nomerge)) ::abort(); } while (false);
} } while (false); if (!mRefCnt.isThreadSafe) _mOwningThread
.AssertOwnership("BrokenImageIcon" " not thread-safe"); nsrefcnt
count = ++mRefCnt; NS_LogAddRef((this), (count), ("BrokenImageIcon"
), (uint32_t)(sizeof(*this))); return count; } MozExternalRefCountType
BrokenImageIcon::Release(void) { do { static_assert( mozilla
::detail::AssertionConditionType<decltype(int32_t(mRefCnt)
> 0)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(int32_t(mRefCnt) > 0))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("int32_t(mRefCnt) > 0" " (" "dup release"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 238); AnnotateMozCrashReason("MOZ_ASSERT" "(" "int32_t(mRefCnt) > 0"
") (" "dup release" ")"); do { *((volatile int*)__null) = 238
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false); do { static_assert( mozilla::detail::AssertionConditionType
<decltype("BrokenImageIcon" != nullptr)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!("BrokenImageIcon" != nullptr
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"\"BrokenImageIcon\" != nullptr" " (" "Must specify a name" ")"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 238); AnnotateMozCrashReason("MOZ_ASSERT" "(" "\"BrokenImageIcon\" != nullptr"
") (" "Must specify a name" ")"); do { *((volatile int*)__null
) = 238; __attribute__((nomerge)) ::abort(); } while (false);
} } while (false); if (!mRefCnt.isThreadSafe) _mOwningThread
.AssertOwnership("BrokenImageIcon" " not thread-safe"); const
char* const nametmp = "BrokenImageIcon"; nsrefcnt count = --
mRefCnt; NS_LogRelease((this), (count), (nametmp)); if (count
== 0) { mRefCnt = 1; delete (this); return 0; } return count
; } nsresult BrokenImageIcon::QueryInterface(const nsIID&
aIID, void** aInstancePtr) { do { if (!(aInstancePtr)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "QueryInterface requires a non-NULL destination!"
, "aInstancePtr", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 238); MOZ_PretendNoReturn(); } } while (0); nsresult rv = NS_ERROR_FAILURE
; static_assert(1 > 0, "Need more arguments to NS_INTERFACE_TABLE"
); static const QITableEntry table[] = { {&mozilla::detail
::kImplementedIID<BrokenImageIcon, imgINotificationObserver
>, int32_t( reinterpret_cast<char*>(static_cast<imgINotificationObserver
*>((BrokenImageIcon*)0x1000)) - reinterpret_cast<char*>
((BrokenImageIcon*)0x1000))}, {&mozilla::detail::kImplementedIID
<BrokenImageIcon, nsISupports>, int32_t(reinterpret_cast
<char*>(static_cast<nsISupports*>( static_cast<
imgINotificationObserver*>((BrokenImageIcon*)0x1000))) - reinterpret_cast
<char*>((BrokenImageIcon*)0x1000))}, { nullptr, 0 } } ;
static_assert(std::size(table) > 1, "need at least 1 interface"
); rv = NS_TableDrivenQI(static_cast<void*>(this), aIID
, aInstancePtr, table); return rv; }
239
240BrokenImageIcon::BrokenImageIcon(const nsImageFrame& aFrame) {
241 constexpr auto brokenSrc = u"resource://gre-resources/broken-image.png"_ns;
242 nsCOMPtr<nsIURI> realURI;
243 NS_NewURI(getter_AddRefs(realURI), brokenSrc);
244
245 MOZ_ASSERT(realURI, "how?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(realURI)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(realURI))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("realURI" " (" "how?" ")"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 245); AnnotateMozCrashReason("MOZ_ASSERT" "(" "realURI" ") ("
"how?" ")"); do { *((volatile int*)__null) = 245; __attribute__
((nomerge)) ::abort(); } while (false); } } while (false)
;
246 if (NS_WARN_IF(!realURI)NS_warn_if_impl(!realURI, "!realURI", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 246)
) {
247 return;
248 }
249
250 nsPresContext* pc = aFrame.PresContext();
251 Document* doc = pc->Document();
252 RefPtr<imgLoader> il = nsContentUtils::GetImgLoaderForDocument(doc);
253
254 nsCOMPtr<nsILoadGroup> loadGroup = doc->GetDocumentLoadGroup();
255
256 // For icon loads, we don't need to merge with the loadgroup flags
257 const nsLoadFlags loadFlags = nsIRequest::LOAD_NORMAL;
258 const nsContentPolicyType contentPolicyType =
259 nsIContentPolicy::TYPE_INTERNAL_IMAGE;
260
261 nsresult rv =
262 il->LoadImage(realURI, /* icon URI */
263 nullptr, /* initial document URI; this is only
264 relevant for cookies, so does not
265 apply to icons. */
266 nullptr, /* referrer (not relevant for icons) */
267 nullptr, /* principal (not relevant for icons) */
268 0, loadGroup, this, nullptr, /* No context */
269 nullptr, /* Not associated with any particular document */
270 loadFlags, nullptr, contentPolicyType, u""_ns,
271 false, /* aUseUrgentStartForChannel */
272 false, /* aLinkPreload */
273 0, FetchPriority::Auto, getter_AddRefs(mImage));
274 Unused << NS_WARN_IF(NS_FAILED(rv))NS_warn_if_impl(((bool)(__builtin_expect(!!(NS_FAILED_impl(rv
)), 0))), "NS_FAILED(rv)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 274)
;
275}
276
277void BrokenImageIcon::Shutdown() {
278 if (!gSingleton) {
279 return;
280 }
281 if (gSingleton->mImage) {
282 gSingleton->mImage->CancelAndForgetObserver(NS_ERROR_FAILURE);
283 gSingleton->mImage = nullptr;
284 }
285 gSingleton = nullptr;
286}
287
288void BrokenImageIcon::Notify(imgIRequest* aRequest, int32_t aType,
289 const nsIntRect* aData) {
290 MOZ_ASSERT(aRequest)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aRequest)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aRequest))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aRequest", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 290); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aRequest" ")"
); do { *((volatile int*)__null) = 290; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
291
292 if (aType != imgINotificationObserver::LOAD_COMPLETE &&
293 aType != imgINotificationObserver::FRAME_UPDATE) {
294 return;
295 }
296
297 if (aType == imgINotificationObserver::LOAD_COMPLETE) {
298 nsCOMPtr<imgIContainer> image;
299 aRequest->GetImage(getter_AddRefs(image));
300 if (!image) {
301 return;
302 }
303
304 // Retrieve the image's intrinsic size.
305 int32_t width = 0;
306 int32_t height = 0;
307 image->GetWidth(&width);
308 image->GetHeight(&height);
309
310 // Request a decode at that size.
311 image->RequestDecodeForSize(IntSize(width, height),
312 imgIContainer::DECODE_FLAGS_DEFAULT |
313 imgIContainer::FLAG_HIGH_QUALITY_SCALING);
314 }
315
316 for (nsImageFrame* frame : mObservers.ForwardRange()) {
317 frame->InvalidateFrame();
318 }
319}
320
321// test if the width and height are fixed, looking at the style data
322// This is used by nsImageFrame::ImageFrameTypeFor and should not be used for
323// layout decisions.
324static bool HaveSpecifiedSize(const nsStylePosition* aStylePosition) {
325 // check the width and height values in the reflow input's style struct
326 // - if width and height are specified as either coord or percentage, then
327 // the size of the image frame is constrained
328 return aStylePosition->GetWidth().IsLengthPercentage() &&
329 aStylePosition->GetHeight().IsLengthPercentage();
330}
331
332template <typename SizeOrMaxSize>
333static bool DependsOnIntrinsicSize(const SizeOrMaxSize& aMinOrMaxSize) {
334 auto length = nsIFrame::ToExtremumLength(aMinOrMaxSize);
335 if (!length) {
336 return false;
337 }
338 switch (*length) {
339 case nsIFrame::ExtremumLength::MinContent:
340 case nsIFrame::ExtremumLength::MaxContent:
341 case nsIFrame::ExtremumLength::FitContent:
342 case nsIFrame::ExtremumLength::FitContentFunction:
343 return true;
344 case nsIFrame::ExtremumLength::MozAvailable:
345 case nsIFrame::ExtremumLength::Stretch:
346 return false;
347 }
348 MOZ_ASSERT_UNREACHABLE("Unknown sizing keyword?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Unknown sizing keyword?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 348); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Unknown sizing keyword?" ")"); do
{ *((volatile int*)__null) = 348; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
349 return false;
350}
351
352// Decide whether we can optimize away reflows that result from the
353// image's intrinsic size changing.
354static bool SizeDependsOnIntrinsicSize(const ReflowInput& aReflowInput) {
355 const auto& position = *aReflowInput.mStylePosition;
356 WritingMode wm = aReflowInput.GetWritingMode();
357 // Don't try to make this optimization when an image has percentages
358 // in its 'width' or 'height'. The percentages might be treated like
359 // auto (especially for intrinsic width calculations and for heights).
360 //
361 // min-width: min-content and such can also affect our intrinsic size.
362 // but note that those keywords on the block axis behave like auto, so we
363 // don't need to check them.
364 //
365 // Flex item's min-[width|height]:auto resolution depends on intrinsic size.
366 return !position.GetHeight().ConvertsToLength() ||
367 !position.GetWidth().ConvertsToLength() ||
368 DependsOnIntrinsicSize(position.MinISize(wm)) ||
369 DependsOnIntrinsicSize(position.MaxISize(wm)) ||
370 aReflowInput.mFrame->IsFlexItem();
371}
372
373nsIFrame* NS_NewImageFrame(PresShell* aPresShell, ComputedStyle* aStyle) {
374 return new (aPresShell) nsImageFrame(aStyle, aPresShell->GetPresContext(),
375 nsImageFrame::Kind::ImageLoadingContent);
376}
377
378nsIFrame* NS_NewXULImageFrame(PresShell* aPresShell, ComputedStyle* aStyle) {
379 return new (aPresShell) nsImageFrame(aStyle, aPresShell->GetPresContext(),
380 nsImageFrame::Kind::XULImage);
381}
382
383nsIFrame* NS_NewImageFrameForContentProperty(PresShell* aPresShell,
384 ComputedStyle* aStyle) {
385 return new (aPresShell) nsImageFrame(aStyle, aPresShell->GetPresContext(),
386 nsImageFrame::Kind::ContentProperty);
387}
388
389nsIFrame* NS_NewImageFrameForGeneratedContentIndex(PresShell* aPresShell,
390 ComputedStyle* aStyle) {
391 return new (aPresShell)
392 nsImageFrame(aStyle, aPresShell->GetPresContext(),
393 nsImageFrame::Kind::ContentPropertyAtIndex);
394}
395
396nsIFrame* NS_NewImageFrameForListStyleImage(PresShell* aPresShell,
397 ComputedStyle* aStyle) {
398 return new (aPresShell) nsImageFrame(aStyle, aPresShell->GetPresContext(),
399 nsImageFrame::Kind::ListStyleImage);
400}
401
402bool nsImageFrame::ShouldShowBrokenImageIcon() const {
403 // NOTE(emilio, https://github.com/w3c/csswg-drafts/issues/2832): WebKit and
404 // Blink behave differently here for content: url(..), for now adapt to
405 // Blink's behavior.
406 if (mKind != Kind::ImageLoadingContent) {
407 return false;
408 }
409
410 if (!StaticPrefs::browser_display_show_image_placeholders()) {
411 return false;
412 }
413
414 // <img alt=""> is special, and it shouldn't draw the broken image icon,
415 // unlike the no-alt attribute or non-empty-alt-attribute case.
416 if (auto* image = HTMLImageElement::FromNode(mContent)) {
417 const nsAttrValue* alt = image->GetParsedAttr(nsGkAtoms::alt);
418 if (alt && alt->IsEmptyString()) {
419 return false;
420 }
421 }
422
423 // check for broken images. valid null images (eg. img src="") are
424 // not considered broken because they have no image requests
425 if (nsCOMPtr<imgIRequest> currentRequest = GetCurrentRequest()) {
426 uint32_t imageStatus;
427 return NS_SUCCEEDED(currentRequest->GetImageStatus(&imageStatus))((bool)(__builtin_expect(!!(!NS_FAILED_impl(currentRequest->
GetImageStatus(&imageStatus))), 1)))
&&
428 (imageStatus & imgIRequest::STATUS_ERROR);
429 }
430
431 nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mContent);
432 MOZ_ASSERT(imageLoader)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(imageLoader)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(imageLoader))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("imageLoader", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 432); AnnotateMozCrashReason("MOZ_ASSERT" "(" "imageLoader"
")"); do { *((volatile int*)__null) = 432; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
433 // Show the broken image icon only if we've tried to perform a load at all
434 // (that is, if we have a current uri).
435 nsCOMPtr<nsIURI> currentURI = imageLoader->GetCurrentURI();
436 return !!currentURI;
437}
438
439nsImageFrame* nsImageFrame::CreateContinuingFrame(
440 mozilla::PresShell* aPresShell, ComputedStyle* aStyle) const {
441 return new (aPresShell)
442 nsImageFrame(aStyle, aPresShell->GetPresContext(), mKind);
443}
444
445NS_IMPL_FRAMEARENA_HELPERS(nsImageFrame)void* nsImageFrame ::operator new(size_t sz, mozilla::PresShell
* aShell) { return aShell->AllocateFrame(nsQueryFrame::nsImageFrame_id
, sz); }
446
447nsImageFrame::nsImageFrame(ComputedStyle* aStyle, nsPresContext* aPresContext,
448 ClassID aID, Kind aKind)
449 : nsAtomicContainerFrame(aStyle, aPresContext, aID),
450 mIntrinsicSize(0, 0),
451 mKind(aKind) {
452 EnableVisibilityTracking();
453}
454
455nsImageFrame::~nsImageFrame() = default;
456
457NS_QUERYFRAME_HEAD(nsImageFrame)void* nsImageFrame ::QueryFrame(FrameIID id) const { switch (
id) {
458 NS_QUERYFRAME_ENTRY(nsImageFrame)case nsImageFrame ::kFrameIID: { static_assert( std::is_same_v
<nsImageFrame, nsImageFrame ::Has_NS_DECL_QUERYFRAME_TARGET
>, "nsImageFrame" " must declare itself as a queryframe target"
); return const_cast<nsImageFrame*>(static_cast<const
nsImageFrame*>(this)); }
459NS_QUERYFRAME_TAIL_INHERITING(nsAtomicContainerFrame)default: break; } return nsAtomicContainerFrame ::QueryFrame(
id); }
460
461#ifdef ACCESSIBILITY1
462a11y::AccType nsImageFrame::AccessibleType() {
463 if (mKind == Kind::ListStyleImage) {
464 // This is an HTMLListBulletAccessible.
465 return a11y::eNoType;
466 }
467
468 // Don't use GetImageMap() to avoid reentrancy into accessibility.
469 if (HasImageMap()) {
470 return a11y::eHTMLImageMapType;
471 }
472
473 return a11y::eImageType;
474}
475#endif
476
477void nsImageFrame::DisconnectMap() {
478 if (!mImageMap) {
479 return;
480 }
481
482 mImageMap->Destroy();
483 mImageMap = nullptr;
484
485#ifdef ACCESSIBILITY1
486 if (nsAccessibilityService* accService = GetAccService()) {
487 accService->RecreateAccessible(PresShell(), mContent);
488 }
489#endif
490}
491
492void nsImageFrame::Destroy(DestroyContext& aContext) {
493 MaybeSendIntrinsicSizeAndRatioToEmbedder(Nothing(), Nothing());
494
495 if (mReflowCallbackPosted) {
496 PresShell()->CancelReflowCallback(this);
497 mReflowCallbackPosted = false;
498 }
499
500 // Tell our image map, if there is one, to clean up
501 // This causes the nsImageMap to unregister itself as
502 // a DOM listener.
503 DisconnectMap();
504
505 MOZ_ASSERT(mListener)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mListener)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mListener))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mListener", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 505); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mListener" ")"
); do { *((volatile int*)__null) = 505; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
506
507 if (mKind == Kind::ImageLoadingContent) {
508 MOZ_ASSERT(!mOwnedRequest)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mOwnedRequest)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!mOwnedRequest))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("!mOwnedRequest"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 508); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!mOwnedRequest"
")"); do { *((volatile int*)__null) = 508; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
509 MOZ_ASSERT(!mOwnedRequestRegistered)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mOwnedRequestRegistered)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!mOwnedRequestRegistered))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("!mOwnedRequestRegistered"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 509); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!mOwnedRequestRegistered"
")"); do { *((volatile int*)__null) = 509; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
510 nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mContent);
511 MOZ_ASSERT(imageLoader)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(imageLoader)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(imageLoader))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("imageLoader", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 511); AnnotateMozCrashReason("MOZ_ASSERT" "(" "imageLoader"
")"); do { *((volatile int*)__null) = 511; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
512
513 // Notify our image loading content that we are going away so it can
514 // deregister with our refresh driver.
515 imageLoader->FrameDestroyed(this);
516 imageLoader->RemoveNativeObserver(mListener);
517 } else {
518 DeinitOwnedRequest();
519 }
520
521 // set the frame to null so we don't send messages to a dead object.
522 mListener->SetFrame(nullptr);
523 mListener = nullptr;
524
525 // If we were displaying an icon, take ourselves off the list
526 if (mDisplayingIcon) {
527 BrokenImageIcon::RemoveObserver(this);
528 }
529
530 nsAtomicContainerFrame::Destroy(aContext);
531}
532
533void nsImageFrame::DeinitOwnedRequest() {
534 MOZ_ASSERT(mKind != Kind::ImageLoadingContent)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mKind != Kind::ImageLoadingContent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mKind != Kind::ImageLoadingContent
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"mKind != Kind::ImageLoadingContent", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 534); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mKind != Kind::ImageLoadingContent"
")"); do { *((volatile int*)__null) = 534; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
535 if (!mOwnedRequest) {
536 return;
537 }
538 PresContext()->Document()->ImageTracker()->Remove(mOwnedRequest);
539 nsLayoutUtils::DeregisterImageRequest(PresContext(), mOwnedRequest,
540 &mOwnedRequestRegistered);
541 mOwnedRequest->CancelAndForgetObserver(NS_BINDING_ABORTED);
542 mOwnedRequest = nullptr;
543}
544
545void nsImageFrame::DidSetComputedStyle(ComputedStyle* aOldStyle) {
546 nsAtomicContainerFrame::DidSetComputedStyle(aOldStyle);
547
548 // A ::marker's default size is calculated from the font's em-size.
549 if (IsForMarkerPseudo()) {
550 mIntrinsicSize = IntrinsicSize(0, 0);
551 UpdateIntrinsicSize();
552 }
553
554 // Normal "owned" images reframe when `content` or `list-style-image` change,
555 // but XUL images don't (and we don't really need to). So deal with the
556 // dynamic list-style-image change in that case.
557 //
558 // TODO(emilio): We might want to do the same for regular list-style-image or
559 // even simple content: url() changes.
560 if (mKind == Kind::XULImage && aOldStyle) {
561 if (!mContent->AsElement()->HasNonEmptyAttr(nsGkAtoms::src) &&
562 aOldStyle->StyleList()->mListStyleImage !=
563 StyleList()->mListStyleImage) {
564 UpdateXULImage();
565 }
566 // If we have no image our intrinsic size might be themed. We need to
567 // update the size even if the effective appearance hasn't changed to
568 // deal correctly with theme changes.
569 if (!mOwnedRequest) {
570 UpdateIntrinsicSize();
571 }
572 }
573
574 // We need to update our orientation either if we had no ComputedStyle before
575 // because this is the first time it's been set, or if the image-orientation
576 // property changed from its previous value.
577 bool shouldUpdateOrientation = false;
578 nsCOMPtr<imgIRequest> currentRequest = GetCurrentRequest();
579 const auto newOrientation =
580 StyleVisibility()->UsedImageOrientation(currentRequest);
581 if (mImage) {
582 if (aOldStyle) {
583 auto oldOrientation =
584 aOldStyle->StyleVisibility()->UsedImageOrientation(currentRequest);
585 shouldUpdateOrientation = oldOrientation != newOrientation;
586 } else {
587 shouldUpdateOrientation = true;
588 }
589 }
590
591 if (shouldUpdateOrientation) {
592 nsCOMPtr<imgIContainer> image(mImage->Unwrap());
593 mImage = nsLayoutUtils::OrientImage(image, newOrientation);
594
595 UpdateIntrinsicSize();
596 UpdateIntrinsicRatio();
597 } else if (!aOldStyle || aOldStyle->StylePosition()->mAspectRatio !=
598 StylePosition()->mAspectRatio) {
599 UpdateIntrinsicRatio();
600 }
601}
602
603static bool SizeIsAvailable(imgIRequest* aRequest) {
604 if (!aRequest) {
605 return false;
606 }
607
608 uint32_t imageStatus = 0;
609 nsresult rv = aRequest->GetImageStatus(&imageStatus);
610 return NS_SUCCEEDED(rv)((bool)(__builtin_expect(!!(!NS_FAILED_impl(rv)), 1))) && (imageStatus & imgIRequest::STATUS_SIZE_AVAILABLE);
611}
612
613const StyleImage* nsImageFrame::GetImageFromStyle() const {
614 switch (mKind) {
615 case Kind::ImageLoadingContent:
616 break;
617 case Kind::ListStyleImage:
618 MOZ_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetParent()->GetContent()->IsGeneratedContentContainerForMarker
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(GetParent()->GetContent()->IsGeneratedContentContainerForMarker
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("GetParent()->GetContent()->IsGeneratedContentContainerForMarker()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 619); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetParent()->GetContent()->IsGeneratedContentContainerForMarker()"
")"); do { *((volatile int*)__null) = 619; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
619 GetParent()->GetContent()->IsGeneratedContentContainerForMarker())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(GetParent()->GetContent()->IsGeneratedContentContainerForMarker
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(GetParent()->GetContent()->IsGeneratedContentContainerForMarker
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("GetParent()->GetContent()->IsGeneratedContentContainerForMarker()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 619); AnnotateMozCrashReason("MOZ_ASSERT" "(" "GetParent()->GetContent()->IsGeneratedContentContainerForMarker()"
")"); do { *((volatile int*)__null) = 619; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
620 MOZ_ASSERT(mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 620); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage)"
")"); do { *((volatile int*)__null) = 620; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
621 return &StyleList()->mListStyleImage;
622 case Kind::XULImage:
623 MOZ_ASSERT(!mContent->AsElement()->HasNonEmptyAttr(nsGkAtoms::src))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mContent->AsElement()->HasNonEmptyAttr(nsGkAtoms
::src))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(!mContent->AsElement()->HasNonEmptyAttr(nsGkAtoms
::src)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("!mContent->AsElement()->HasNonEmptyAttr(nsGkAtoms::src)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 623); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!mContent->AsElement()->HasNonEmptyAttr(nsGkAtoms::src)"
")"); do { *((volatile int*)__null) = 623; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
624 return &StyleList()->mListStyleImage;
625 case Kind::ContentProperty:
626 case Kind::ContentPropertyAtIndex: {
627 uint32_t contentIndex = 0;
628 const nsStyleContent* styleContent = StyleContent();
629 if (mKind == Kind::ContentPropertyAtIndex) {
630 MOZ_RELEASE_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 631); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage)"
")"); do { *((volatile int*)__null) = 631; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
631 mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage
))>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 631); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "mContent->IsHTMLElement(nsGkAtoms::mozgeneratedcontentimage)"
")"); do { *((volatile int*)__null) = 631; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
632 contentIndex =
633 static_cast<GeneratedImageContent*>(mContent.get())->Index();
634
635 // TODO(emilio): Consider inheriting the `content` property instead of
636 // doing this parent traversal?
637 nsIFrame* parent = GetParent();
638 MOZ_DIAGNOSTIC_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(parent->GetContent()->IsGeneratedContentContainerForMarker
() || parent->GetContent()->IsGeneratedContentContainerForAfter
() || parent->GetContent()->IsGeneratedContentContainerForBefore
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(parent->GetContent()->IsGeneratedContentContainerForMarker
() || parent->GetContent()->IsGeneratedContentContainerForAfter
() || parent->GetContent()->IsGeneratedContentContainerForBefore
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("parent->GetContent()->IsGeneratedContentContainerForMarker() || parent->GetContent()->IsGeneratedContentContainerForAfter() || parent->GetContent()->IsGeneratedContentContainerForBefore()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 641); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "parent->GetContent()->IsGeneratedContentContainerForMarker() || parent->GetContent()->IsGeneratedContentContainerForAfter() || parent->GetContent()->IsGeneratedContentContainerForBefore()"
")"); do { *((volatile int*)__null) = 641; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
639 parent->GetContent()->IsGeneratedContentContainerForMarker() ||do { static_assert( mozilla::detail::AssertionConditionType<
decltype(parent->GetContent()->IsGeneratedContentContainerForMarker
() || parent->GetContent()->IsGeneratedContentContainerForAfter
() || parent->GetContent()->IsGeneratedContentContainerForBefore
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(parent->GetContent()->IsGeneratedContentContainerForMarker
() || parent->GetContent()->IsGeneratedContentContainerForAfter
() || parent->GetContent()->IsGeneratedContentContainerForBefore
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("parent->GetContent()->IsGeneratedContentContainerForMarker() || parent->GetContent()->IsGeneratedContentContainerForAfter() || parent->GetContent()->IsGeneratedContentContainerForBefore()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 641); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "parent->GetContent()->IsGeneratedContentContainerForMarker() || parent->GetContent()->IsGeneratedContentContainerForAfter() || parent->GetContent()->IsGeneratedContentContainerForBefore()"
")"); do { *((volatile int*)__null) = 641; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
640 parent->GetContent()->IsGeneratedContentContainerForAfter() ||do { static_assert( mozilla::detail::AssertionConditionType<
decltype(parent->GetContent()->IsGeneratedContentContainerForMarker
() || parent->GetContent()->IsGeneratedContentContainerForAfter
() || parent->GetContent()->IsGeneratedContentContainerForBefore
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(parent->GetContent()->IsGeneratedContentContainerForMarker
() || parent->GetContent()->IsGeneratedContentContainerForAfter
() || parent->GetContent()->IsGeneratedContentContainerForBefore
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("parent->GetContent()->IsGeneratedContentContainerForMarker() || parent->GetContent()->IsGeneratedContentContainerForAfter() || parent->GetContent()->IsGeneratedContentContainerForBefore()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 641); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "parent->GetContent()->IsGeneratedContentContainerForMarker() || parent->GetContent()->IsGeneratedContentContainerForAfter() || parent->GetContent()->IsGeneratedContentContainerForBefore()"
")"); do { *((volatile int*)__null) = 641; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
641 parent->GetContent()->IsGeneratedContentContainerForBefore())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(parent->GetContent()->IsGeneratedContentContainerForMarker
() || parent->GetContent()->IsGeneratedContentContainerForAfter
() || parent->GetContent()->IsGeneratedContentContainerForBefore
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(parent->GetContent()->IsGeneratedContentContainerForMarker
() || parent->GetContent()->IsGeneratedContentContainerForAfter
() || parent->GetContent()->IsGeneratedContentContainerForBefore
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("parent->GetContent()->IsGeneratedContentContainerForMarker() || parent->GetContent()->IsGeneratedContentContainerForAfter() || parent->GetContent()->IsGeneratedContentContainerForBefore()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 641); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "parent->GetContent()->IsGeneratedContentContainerForMarker() || parent->GetContent()->IsGeneratedContentContainerForAfter() || parent->GetContent()->IsGeneratedContentContainerForBefore()"
")"); do { *((volatile int*)__null) = 641; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
642 nsIFrame* nonAnonymousParent = parent;
643 while (nonAnonymousParent->Style()->IsAnonBox()) {
644 nonAnonymousParent = nonAnonymousParent->GetParent();
645 }
646 MOZ_DIAGNOSTIC_ASSERT(parent->GetContent() ==do { static_assert( mozilla::detail::AssertionConditionType<
decltype(parent->GetContent() == nonAnonymousParent->GetContent
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(parent->GetContent() == nonAnonymousParent->GetContent
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("parent->GetContent() == nonAnonymousParent->GetContent()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 647); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "parent->GetContent() == nonAnonymousParent->GetContent()"
")"); do { *((volatile int*)__null) = 647; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
647 nonAnonymousParent->GetContent())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(parent->GetContent() == nonAnonymousParent->GetContent
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(parent->GetContent() == nonAnonymousParent->GetContent
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("parent->GetContent() == nonAnonymousParent->GetContent()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 647); AnnotateMozCrashReason("MOZ_DIAGNOSTIC_ASSERT" "(" "parent->GetContent() == nonAnonymousParent->GetContent()"
")"); do { *((volatile int*)__null) = 647; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
648 styleContent = nonAnonymousParent->StyleContent();
649 }
650 auto items = styleContent->NonAltContentItems();
651 MOZ_RELEASE_ASSERT(contentIndex < items.Length())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(contentIndex < items.Length())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(contentIndex < items.Length
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("contentIndex < items.Length()", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 651); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "contentIndex < items.Length()"
")"); do { *((volatile int*)__null) = 651; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
652 const auto& contentItem = items[contentIndex];
653 MOZ_RELEASE_ASSERT(contentItem.IsImage())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(contentItem.IsImage())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(contentItem.IsImage()))), 0)
)) { do { } while (false); MOZ_ReportAssertionFailure("contentItem.IsImage()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 653); AnnotateMozCrashReason("MOZ_RELEASE_ASSERT" "(" "contentItem.IsImage()"
")"); do { *((volatile int*)__null) = 653; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
654 return &contentItem.AsImage();
655 }
656 }
657 MOZ_ASSERT_UNREACHABLE("Don't call me")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Don't call me" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 657); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Don't call me" ")"); do { *((volatile
int*)__null) = 657; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
658 return nullptr;
659}
660
661void nsImageFrame::UpdateXULImage() {
662 MOZ_ASSERT(mKind == Kind::XULImage)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mKind == Kind::XULImage)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mKind == Kind::XULImage))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("mKind == Kind::XULImage"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 662); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mKind == Kind::XULImage"
")"); do { *((volatile int*)__null) = 662; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
663 DeinitOwnedRequest();
664
665 nsAutoString src;
666 nsPresContext* pc = PresContext();
667 if (mContent->AsElement()->GetAttr(nsGkAtoms::src, src) && !src.IsEmpty()) {
668 nsContentPolicyType contentPolicyType;
669 nsCOMPtr<nsIPrincipal> triggeringPrincipal;
670 uint64_t requestContextID = 0;
671 nsContentUtils::GetContentPolicyTypeForUIImageLoading(
672 mContent, getter_AddRefs(triggeringPrincipal), contentPolicyType,
673 &requestContextID);
674 nsCOMPtr<nsIURI> uri;
675 nsContentUtils::NewURIWithDocumentCharset(
676 getter_AddRefs(uri), src, pc->Document(), mContent->GetBaseURI());
677 if (uri) {
678 auto referrerInfo = MakeRefPtr<ReferrerInfo>(*mContent->AsElement());
679 nsContentUtils::LoadImage(
680 uri, mContent, pc->Document(), triggeringPrincipal, requestContextID,
681 referrerInfo, mListener, nsIRequest::LOAD_NORMAL, u""_ns,
682 getter_AddRefs(mOwnedRequest), contentPolicyType);
683 SetupOwnedRequest();
684 }
685 } else {
686 const auto* image = GetImageFromStyle();
687 if (image->IsImageRequestType()) {
688 if (imgRequestProxy* proxy = image->GetImageRequest()) {
689 proxy->Clone(mListener, pc->Document(), getter_AddRefs(mOwnedRequest));
690 SetupOwnedRequest();
691 }
692 }
693 }
694
695 if (!mOwnedRequest) {
696 UpdateImage(nullptr, nullptr);
697 }
698}
699
700void nsImageFrame::Init(nsIContent* aContent, nsContainerFrame* aParent,
701 nsIFrame* aPrevInFlow) {
702 MOZ_ASSERT_IF(aPrevInFlow,do { if (aPrevInFlow) { do { static_assert( mozilla::detail::
AssertionConditionType<decltype(aPrevInFlow->Type() == Type
() && static_cast<nsImageFrame*>(aPrevInFlow)->
mKind == mKind)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(aPrevInFlow->Type() == Type
() && static_cast<nsImageFrame*>(aPrevInFlow)->
mKind == mKind))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aPrevInFlow->Type() == Type() && static_cast<nsImageFrame*>(aPrevInFlow)->mKind == mKind"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 704); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPrevInFlow->Type() == Type() && static_cast<nsImageFrame*>(aPrevInFlow)->mKind == mKind"
")"); do { *((volatile int*)__null) = 704; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
703 aPrevInFlow->Type() == Type() &&do { if (aPrevInFlow) { do { static_assert( mozilla::detail::
AssertionConditionType<decltype(aPrevInFlow->Type() == Type
() && static_cast<nsImageFrame*>(aPrevInFlow)->
mKind == mKind)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(aPrevInFlow->Type() == Type
() && static_cast<nsImageFrame*>(aPrevInFlow)->
mKind == mKind))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aPrevInFlow->Type() == Type() && static_cast<nsImageFrame*>(aPrevInFlow)->mKind == mKind"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 704); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPrevInFlow->Type() == Type() && static_cast<nsImageFrame*>(aPrevInFlow)->mKind == mKind"
")"); do { *((volatile int*)__null) = 704; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
704 static_cast<nsImageFrame*>(aPrevInFlow)->mKind == mKind)do { if (aPrevInFlow) { do { static_assert( mozilla::detail::
AssertionConditionType<decltype(aPrevInFlow->Type() == Type
() && static_cast<nsImageFrame*>(aPrevInFlow)->
mKind == mKind)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(aPrevInFlow->Type() == Type
() && static_cast<nsImageFrame*>(aPrevInFlow)->
mKind == mKind))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("aPrevInFlow->Type() == Type() && static_cast<nsImageFrame*>(aPrevInFlow)->mKind == mKind"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 704); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aPrevInFlow->Type() == Type() && static_cast<nsImageFrame*>(aPrevInFlow)->mKind == mKind"
")"); do { *((volatile int*)__null) = 704; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
705
706 nsAtomicContainerFrame::Init(aContent, aParent, aPrevInFlow);
707
708 mListener = new nsImageListener(this);
709
710 GetImageMap(); // Ensure to init the image map asap. This is important to
711 // make <area> elements focusable.
712
713 if (StaticPrefs::layout_image_eager_broken_image_icon()) {
714 Unused << BrokenImageIcon::GetImage(this);
715 }
716
717 nsPresContext* pc = PresContext();
718 if (mKind == Kind::ImageLoadingContent) {
719 nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(aContent);
720 MOZ_ASSERT(imageLoader)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(imageLoader)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(imageLoader))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("imageLoader", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 720); AnnotateMozCrashReason("MOZ_ASSERT" "(" "imageLoader"
")"); do { *((volatile int*)__null) = 720; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
721 imageLoader->AddNativeObserver(mListener);
722 // We have a PresContext now, so we need to notify the image content node
723 // that it can register images.
724 imageLoader->FrameCreated(this);
725 AssertSyncDecodingHintIsInSync();
726 if (nsIDocShell* docShell = pc->GetDocShell()) {
727 RefPtr<BrowsingContext> bc = docShell->GetBrowsingContext();
728 mIsInObjectOrEmbed = bc->IsEmbedderTypeObjectOrEmbed() &&
729 pc->Document()->IsImageDocument();
730 }
731 } else if (mKind == Kind::XULImage) {
732 UpdateXULImage();
733 } else {
734 const StyleImage* image = GetImageFromStyle();
735 if (image->IsImageRequestType()) {
736 if (imgRequestProxy* proxy = image->GetImageRequest()) {
737 proxy->Clone(mListener, pc->Document(), getter_AddRefs(mOwnedRequest));
738 SetupOwnedRequest();
739 }
740 }
741 }
742
743 // Give image loads associated with an image frame a small priority boost.
744 if (nsCOMPtr<imgIRequest> currentRequest = GetCurrentRequest()) {
745 uint32_t categoryToBoostPriority = imgIRequest::CATEGORY_FRAME_INIT;
746
747 // Increase load priority further if intrinsic size might be important for
748 // layout.
749 if (!HaveSpecifiedSize(StylePosition())) {
750 categoryToBoostPriority |= imgIRequest::CATEGORY_SIZE_QUERY;
751 }
752
753 currentRequest->BoostPriority(categoryToBoostPriority);
754 }
755
756 MaybeSendIntrinsicSizeAndRatioToEmbedder();
757}
758
759void nsImageFrame::SetupOwnedRequest() {
760 MOZ_ASSERT(mKind != Kind::ImageLoadingContent)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mKind != Kind::ImageLoadingContent)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(mKind != Kind::ImageLoadingContent
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"mKind != Kind::ImageLoadingContent", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 760); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mKind != Kind::ImageLoadingContent"
")"); do { *((volatile int*)__null) = 760; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
761 if (!mOwnedRequest) {
762 return;
763 }
764
765 // We're not using AssociateRequestToFrame for the content property, so we
766 // need to add it to the image tracker manually.
767 PresContext()->Document()->ImageTracker()->Add(mOwnedRequest);
768
769 uint32_t status = 0;
770 nsresult rv = mOwnedRequest->GetImageStatus(&status);
771 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
772 return;
773 }
774
775 if (status & imgIRequest::STATUS_SIZE_AVAILABLE) {
776 nsCOMPtr<imgIContainer> image;
777 mOwnedRequest->GetImage(getter_AddRefs(image));
778 OnSizeAvailable(mOwnedRequest, image);
779 }
780
781 if (status & imgIRequest::STATUS_FRAME_COMPLETE) {
782 mFirstFrameComplete = true;
783 }
784
785 if (status & imgIRequest::STATUS_IS_ANIMATED) {
786 nsLayoutUtils::RegisterImageRequest(PresContext(), mOwnedRequest,
787 &mOwnedRequestRegistered);
788 }
789}
790
791static void ScaleIntrinsicSizeForDensity(IntrinsicSize& aSize,
792 const ImageResolution& aResolution) {
793 if (aSize.width) {
794 aResolution.ApplyXTo(aSize.width.ref());
795 }
796 if (aSize.height) {
797 aResolution.ApplyYTo(aSize.height.ref());
798 }
799}
800
801static void ScaleIntrinsicSizeForDensity(imgIContainer* aImage,
802 nsIContent& aContent,
803 IntrinsicSize& aSize) {
804 ImageResolution resolution = aImage->GetResolution();
805 if (auto* image = HTMLImageElement::FromNode(aContent)) {
806 if (auto* selector = image->GetResponsiveImageSelector()) {
807 resolution.ScaleBy(selector->GetSelectedImageDensity());
808 }
809 }
810 ScaleIntrinsicSizeForDensity(aSize, resolution);
811}
812
813static nscoord ListImageDefaultLength(const nsImageFrame& aFrame) {
814 // https://drafts.csswg.org/css-lists-3/#image-markers
815 // The spec says we should use 1em x 1em, but that seems too large.
816 // See disussion in https://github.com/w3c/csswg-drafts/issues/4207
817 auto* pc = aFrame.PresContext();
818 RefPtr<nsFontMetrics> fm =
819 nsLayoutUtils::GetFontMetricsForComputedStyle(aFrame.Style(), pc);
820 RefPtr<gfxFont> font = fm->GetThebesFontGroup()->GetFirstValidFont();
821 auto emAU =
822 font->GetMetrics(fm->Orientation()).emHeight * pc->AppUnitsPerDevPixel();
823 return std::max(NSToCoordRound(0.4f * emAU),
824 nsPresContext::CSSPixelsToAppUnits(1));
825}
826
827IntrinsicSize nsImageFrame::ComputeIntrinsicSize(
828 bool aIgnoreContainment) const {
829 const auto containAxes =
830 aIgnoreContainment ? ContainSizeAxes(false, false) : GetContainSizeAxes();
831 if (containAxes.IsBoth()) {
832 return FinishIntrinsicSize(containAxes, IntrinsicSize(0, 0));
833 }
834
835 nsSize size;
836 if (mImage && NS_SUCCEEDED(mImage->GetIntrinsicSize(&size))((bool)(__builtin_expect(!!(!NS_FAILED_impl(mImage->GetIntrinsicSize
(&size))), 1)))
) {
837 IntrinsicSize intrinsicSize;
838 intrinsicSize.width = size.width == -1 ? Nothing() : Some(size.width);
839 intrinsicSize.height = size.height == -1 ? Nothing() : Some(size.height);
840 if (mKind == nsImageFrame::Kind::ListStyleImage) {
841 if (intrinsicSize.width.isNothing() || intrinsicSize.height.isNothing()) {
842 nscoord defaultLength = ListImageDefaultLength(*this);
843 if (intrinsicSize.width.isNothing()) {
844 intrinsicSize.width = Some(defaultLength);
845 }
846 if (intrinsicSize.height.isNothing()) {
847 intrinsicSize.height = Some(defaultLength);
848 }
849 }
850 }
851 if (mKind == nsImageFrame::Kind::ImageLoadingContent ||
852 (mKind == nsImageFrame::Kind::XULImage &&
853 GetContent()->AsElement()->HasNonEmptyAttr(nsGkAtoms::src))) {
854 ScaleIntrinsicSizeForDensity(mImage, *GetContent(), intrinsicSize);
855 } else {
856 ScaleIntrinsicSizeForDensity(
857 intrinsicSize, GetImageFromStyle()->GetResolution(*Style()));
858 }
859 return FinishIntrinsicSize(containAxes, intrinsicSize);
860 }
861
862 if (mKind == nsImageFrame::Kind::ListStyleImage) {
863 // Note: images are handled above, this handles gradients etc.
864 const nscoord defaultLength = ListImageDefaultLength(*this);
865 return FinishIntrinsicSize(containAxes,
866 IntrinsicSize(defaultLength, defaultLength));
867 }
868
869 if (mKind == nsImageFrame::Kind::XULImage && IsThemed()) {
870 nsPresContext* pc = PresContext();
871 // FIXME: const_cast here is a bit evil but IsThemed and so does the same.
872 const auto widgetSize = pc->Theme()->GetMinimumWidgetSize(
873 pc, const_cast<nsImageFrame*>(this),
874 StyleDisplay()->EffectiveAppearance());
875 const IntrinsicSize intrinsicSize(
876 LayoutDeviceIntSize::ToAppUnits(widgetSize, pc->AppUnitsPerDevPixel()));
877 return FinishIntrinsicSize(containAxes, intrinsicSize);
878 }
879
880 if (ShouldShowBrokenImageIcon()) {
881 nscoord edgeLengthToUse = nsPresContext::CSSPixelsToAppUnits(
882 ICON_SIZE(16) + (2 * (ICON_PADDING(3) + ALT_BORDER_WIDTH(1))));
883 return FinishIntrinsicSize(containAxes,
884 IntrinsicSize(edgeLengthToUse, edgeLengthToUse));
885 }
886
887 if (ShouldUseMappedAspectRatio() &&
888 StylePosition()->mAspectRatio.HasRatio()) {
889 return IntrinsicSize();
890 }
891
892 // XXX: No FinishIntrinsicSize?
893 return IntrinsicSize(0, 0);
894}
895
896// For compat reasons, see bug 1602047, we don't use the intrinsic ratio from
897// width="" and height="" for images with no src attribute (no request).
898//
899// But we shouldn't get fooled by <img loading=lazy>. We do want to apply the
900// ratio then...
901bool nsImageFrame::ShouldUseMappedAspectRatio() const {
902 if (mKind != Kind::ImageLoadingContent) {
903 return true;
904 }
905 nsCOMPtr<imgIRequest> currentRequest = GetCurrentRequest();
906 if (currentRequest) {
907 return true;
908 }
909 // TODO(emilio): Investigate the compat situation of the above check, maybe we
910 // can just check for empty src attribute or something...
911 auto* image = HTMLImageElement::FromNode(mContent);
912 return image && image->IsAwaitingLoadOrLazyLoading();
913}
914
915bool nsImageFrame::UpdateIntrinsicSize() {
916 IntrinsicSize oldIntrinsicSize = mIntrinsicSize;
917 mIntrinsicSize = ComputeIntrinsicSize();
918 return mIntrinsicSize != oldIntrinsicSize;
919}
920
921AspectRatio nsImageFrame::ComputeIntrinsicRatioForImage(
922 imgIContainer* aImage, bool aIgnoreContainment) const {
923 if (!aIgnoreContainment && GetContainSizeAxes().IsAny()) {
924 return AspectRatio();
925 }
926
927 if (aImage) {
928 if (AspectRatio fromImage = aImage->GetIntrinsicRatio()) {
929 return fromImage;
930 }
931 }
932 if (ShouldUseMappedAspectRatio()) {
933 const StyleAspectRatio& ratio = StylePosition()->mAspectRatio;
934 if (ratio.auto_ && ratio.HasRatio()) {
935 // Return the mapped intrinsic aspect ratio stored in
936 // nsStylePosition::mAspectRatio.
937 return ratio.ratio.AsRatio().ToLayoutRatio(UseBoxSizing::Yes);
938 }
939 }
940 if (ShouldShowBrokenImageIcon()) {
941 return AspectRatio(1.0f);
942 }
943 return AspectRatio();
944}
945
946bool nsImageFrame::UpdateIntrinsicRatio() {
947 AspectRatio oldIntrinsicRatio = mIntrinsicRatio;
948 mIntrinsicRatio = ComputeIntrinsicRatioForImage(mImage);
949 return mIntrinsicRatio != oldIntrinsicRatio;
950}
951
952bool nsImageFrame::GetSourceToDestTransform(nsTransform2D& aTransform) {
953 nsRect destRect = GetDestRect(GetContentRectRelativeToSelf());
954 // Set the translation components, based on destRect
955 // XXXbz does this introduce rounding errors because of the cast to
956 // float? Should we just manually add that stuff in every time
957 // instead?
958 aTransform.SetToTranslate(float(destRect.x), float(destRect.y));
959
960 // NOTE(emilio): This intrinsicSize is not the same as the layout intrinsic
961 // size (mIntrinsicSize), which can be scaled due to ResponsiveImageSelector,
962 // see ScaleIntrinsicSizeForDensity.
963 nsSize intrinsicSize;
964 if (!mImage || !NS_SUCCEEDED(mImage->GetIntrinsicSize(&intrinsicSize))((bool)(__builtin_expect(!!(!NS_FAILED_impl(mImage->GetIntrinsicSize
(&intrinsicSize))), 1)))
||
965 intrinsicSize.IsEmpty()) {
966 return false;
967 }
968
969 aTransform.SetScale(float(destRect.width) / float(intrinsicSize.width),
970 float(destRect.height) / float(intrinsicSize.height));
971 return true;
972}
973
974// This function checks whether the given request is the current request for our
975// mContent.
976bool nsImageFrame::IsPendingLoad(imgIRequest* aRequest) const {
977 // Default to pending load in case of errors
978 if (mKind != Kind::ImageLoadingContent) {
979 MOZ_ASSERT(aRequest == mOwnedRequest)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aRequest == mOwnedRequest)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(aRequest == mOwnedRequest)))
, 0))) { do { } while (false); MOZ_ReportAssertionFailure("aRequest == mOwnedRequest"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 979); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aRequest == mOwnedRequest"
")"); do { *((volatile int*)__null) = 979; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
980 return false;
981 }
982
983 nsCOMPtr<nsIImageLoadingContent> imageLoader(do_QueryInterface(mContent));
984 MOZ_ASSERT(imageLoader)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(imageLoader)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(imageLoader))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("imageLoader", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 984); AnnotateMozCrashReason("MOZ_ASSERT" "(" "imageLoader"
")"); do { *((volatile int*)__null) = 984; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
985
986 int32_t requestType = nsIImageLoadingContent::UNKNOWN_REQUEST;
987 imageLoader->GetRequestType(aRequest, &requestType);
988
989 return requestType != nsIImageLoadingContent::CURRENT_REQUEST;
990}
991
992nsRect nsImageFrame::SourceRectToDest(const nsIntRect& aRect) {
993 // When scaling the image, row N of the source image may (depending on
994 // the scaling function) be used to draw any row in the destination image
995 // between floor(F * (N-1)) and ceil(F * (N+1)), where F is the
996 // floating-point scaling factor. The same holds true for columns.
997 // So, we start by computing that bound without the floor and ceiling.
998
999 nsRect r(nsPresContext::CSSPixelsToAppUnits(aRect.x - 1),
1000 nsPresContext::CSSPixelsToAppUnits(aRect.y - 1),
1001 nsPresContext::CSSPixelsToAppUnits(aRect.width + 2),
1002 nsPresContext::CSSPixelsToAppUnits(aRect.height + 2));
1003
1004 nsTransform2D sourceToDest;
1005 if (!GetSourceToDestTransform(sourceToDest)) {
1006 // Failed to generate transform matrix. Return our whole content area,
1007 // to be on the safe side (since this method is used for generating
1008 // invalidation rects).
1009 return GetContentRectRelativeToSelf();
1010 }
1011
1012 sourceToDest.TransformCoord(&r.x, &r.y, &r.width, &r.height);
1013
1014 // Now, round the edges out to the pixel boundary.
1015 nscoord scale = nsPresContext::CSSPixelsToAppUnits(1);
1016 nscoord right = r.x + r.width;
1017 nscoord bottom = r.y + r.height;
1018
1019 r.x -= (scale + (r.x % scale)) % scale;
1020 r.y -= (scale + (r.y % scale)) % scale;
1021 r.width = right + ((scale - (right % scale)) % scale) - r.x;
1022 r.height = bottom + ((scale - (bottom % scale)) % scale) - r.y;
1023
1024 return r;
1025}
1026
1027static bool ImageOk(ElementState aState) {
1028 return !aState.HasState(ElementState::BROKEN);
1029}
1030
1031static bool HasAltText(const Element& aElement) {
1032 // We always return some alternate text for <input>, see
1033 // nsCSSFrameConstructor::GetAlternateTextFor.
1034 if (aElement.IsHTMLElement(nsGkAtoms::input)) {
1035 return true;
1036 }
1037
1038 MOZ_ASSERT(aElement.IsHTMLElement(nsGkAtoms::img))do { static_assert( mozilla::detail::AssertionConditionType<
decltype(aElement.IsHTMLElement(nsGkAtoms::img))>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(aElement.IsHTMLElement(nsGkAtoms::img)))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("aElement.IsHTMLElement(nsGkAtoms::img)"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1038); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aElement.IsHTMLElement(nsGkAtoms::img)"
")"); do { *((volatile int*)__null) = 1038; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1039 return aElement.HasNonEmptyAttr(nsGkAtoms::alt);
1040}
1041
1042bool nsImageFrame::ShouldCreateImageFrameForContentProperty(
1043 const Element& aElement, const ComputedStyle& aStyle) {
1044 if (aElement.IsRootOfNativeAnonymousSubtree()) {
1045 return false;
1046 }
1047 Span<const StyleContentItem> items =
1048 aStyle.StyleContent()->NonAltContentItems();
1049 return items.Length() == 1 && items[0].IsImage();
1050}
1051
1052// Check if we want to use an image frame or just let the frame constructor make
1053// us into an inline, and if so, which kind of image frame should we create.
1054/* static */
1055auto nsImageFrame::ImageFrameTypeFor(const Element& aElement,
1056 const ComputedStyle& aStyle)
1057 -> ImageFrameType {
1058 if (ShouldCreateImageFrameForContentProperty(aElement, aStyle)) {
1059 // Prefer the content property, for compat reasons, see bug 1484928.
1060 return ImageFrameType::ForContentProperty;
1061 }
1062
1063 if (ImageOk(aElement.State())) {
1064 // Image is fine or loading; do the image frame thing
1065 return ImageFrameType::ForElementRequest;
1066 }
1067
1068 if (aStyle.StyleUIReset()->mMozForceBrokenImageIcon) {
1069 return ImageFrameType::ForElementRequest;
1070 }
1071
1072 if (!HasAltText(aElement)) {
1073 return ImageFrameType::ForElementRequest;
1074 }
1075
1076 // FIXME(emilio, bug 1788767): We definitely don't reframe when
1077 // HaveSpecifiedSize changes...
1078 if (aElement.OwnerDoc()->GetCompatibilityMode() == eCompatibility_NavQuirks &&
1079 HaveSpecifiedSize(aStyle.StylePosition())) {
1080 return ImageFrameType::ForElementRequest;
1081 }
1082
1083 return ImageFrameType::None;
1084}
1085
1086void nsImageFrame::Notify(imgIRequest* aRequest, int32_t aType,
1087 const nsIntRect* aRect) {
1088 if (aType == imgINotificationObserver::SIZE_AVAILABLE) {
1089 nsCOMPtr<imgIContainer> image;
1090 aRequest->GetImage(getter_AddRefs(image));
1091 return OnSizeAvailable(aRequest, image);
1092 }
1093
1094 if (aType == imgINotificationObserver::FRAME_UPDATE) {
1095 return OnFrameUpdate(aRequest, aRect);
1096 }
1097
1098 if (aType == imgINotificationObserver::FRAME_COMPLETE) {
1099 mFirstFrameComplete = true;
1100 }
1101
1102 if (aType == imgINotificationObserver::IS_ANIMATED &&
1103 mKind != Kind::ImageLoadingContent) {
1104 nsLayoutUtils::RegisterImageRequest(PresContext(), mOwnedRequest,
1105 &mOwnedRequestRegistered);
1106 }
1107
1108 if (aType == imgINotificationObserver::LOAD_COMPLETE) {
1109 LargestContentfulPaint::MaybeProcessImageForElementTiming(
1110 static_cast<imgRequestProxy*>(aRequest), GetContent()->AsElement());
1111 return OnLoadComplete(aRequest);
1112 }
1113}
1114
1115void nsImageFrame::OnSizeAvailable(imgIRequest* aRequest,
1116 imgIContainer* aImage) {
1117 if (!aImage) {
1118 return;
1119 }
1120
1121 /* Get requested animation policy from the pres context:
1122 * normal = 0
1123 * one frame = 1
1124 * one loop = 2
1125 */
1126 aImage->SetAnimationMode(PresContext()->ImageAnimationMode());
1127
1128 if (IsPendingLoad(aRequest)) {
1129 // We don't care
1130 return;
1131 }
1132
1133 UpdateImage(aRequest, aImage);
1134}
1135
1136void nsImageFrame::UpdateImage(imgIRequest* aRequest, imgIContainer* aImage) {
1137 if (SizeIsAvailable(aRequest)) {
1138 StyleImageOrientation orientation =
1139 StyleVisibility()->UsedImageOrientation(aRequest);
1140 // This is valid and for the current request, so update our stored image
1141 // container, orienting according to our style.
1142 mImage = nsLayoutUtils::OrientImage(aImage, orientation);
1143 MOZ_ASSERT(mImage)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mImage)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(mImage))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("mImage", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1143); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mImage" ")"
); do { *((volatile int*)__null) = 1143; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1144 } else {
1145 // We no longer have a valid image, so release our stored image container.
1146 mImage = mPrevImage = nullptr;
1147 if (mKind == Kind::ListStyleImage) {
1148 auto* genContent = static_cast<GeneratedImageContent*>(GetContent());
1149 genContent->NotifyLoadFailed();
1150 // No need to continue below since the above state change will destroy
1151 // this frame.
1152 return;
1153 }
1154 }
1155
1156 UpdateIntrinsicSizeAndRatio();
1157
1158 if (!GotInitialReflow()) {
1159 return;
1160 }
1161
1162 // We're going to need to repaint now either way.
1163 InvalidateFrame();
1164}
1165
1166void nsImageFrame::OnFrameUpdate(imgIRequest* aRequest,
1167 const nsIntRect* aRect) {
1168 if (NS_WARN_IF(!aRect)NS_warn_if_impl(!aRect, "!aRect", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1168)
) {
1169 return;
1170 }
1171
1172 if (!GotInitialReflow()) {
1173 // Don't bother to do anything; we have a reflow coming up!
1174 return;
1175 }
1176
1177 if (mFirstFrameComplete && !StyleVisibility()->IsVisible()) {
1178 return;
1179 }
1180
1181 if (IsPendingLoad(aRequest)) {
1182 // We don't care
1183 return;
1184 }
1185
1186 nsIntRect layerInvalidRect =
1187 mImage ? mImage->GetImageSpaceInvalidationRect(*aRect) : *aRect;
1188
1189 if (layerInvalidRect.IsEqualInterior(GetMaxSizedIntRect())) {
1190 // Invalidate our entire area.
1191 InvalidateSelf(nullptr, nullptr);
1192 return;
1193 }
1194
1195 nsRect frameInvalidRect = SourceRectToDest(layerInvalidRect);
1196 InvalidateSelf(&layerInvalidRect, &frameInvalidRect);
1197}
1198
1199void nsImageFrame::InvalidateSelf(const nsIntRect* aLayerInvalidRect,
1200 const nsRect* aFrameInvalidRect) {
1201 // Check if WebRender has interacted with this frame. If it has
1202 // we need to let it know that things have changed.
1203 const auto type = DisplayItemType::TYPE_IMAGE;
1204 const auto providerId = mImage ? mImage->GetProviderId() : 0;
1205 if (WebRenderUserData::ProcessInvalidateForImage(this, type, providerId)) {
1206 return;
1207 }
1208
1209 InvalidateLayer(type, aLayerInvalidRect, aFrameInvalidRect);
1210
1211 if (!mFirstFrameComplete) {
1212 InvalidateLayer(DisplayItemType::TYPE_ALT_FEEDBACK, aLayerInvalidRect,
1213 aFrameInvalidRect);
1214 }
1215}
1216
1217void nsImageFrame::MaybeSendIntrinsicSizeAndRatioToEmbedder() {
1218 MaybeSendIntrinsicSizeAndRatioToEmbedder(Some(GetIntrinsicSize()),
1219 Some(GetAspectRatio()));
1220}
1221
1222void nsImageFrame::MaybeSendIntrinsicSizeAndRatioToEmbedder(
1223 Maybe<IntrinsicSize> aIntrinsicSize, Maybe<AspectRatio> aIntrinsicRatio) {
1224 if (!mIsInObjectOrEmbed || !mImage) {
1225 return;
1226 }
1227
1228 nsCOMPtr<nsIDocShell> docShell = PresContext()->GetDocShell();
1229 if (!docShell) {
1230 return;
1231 }
1232
1233 BrowsingContext* bc = docShell->GetBrowsingContext();
1234 if (!bc) {
1235 return;
1236 }
1237 MOZ_ASSERT(bc->IsContentSubframe())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(bc->IsContentSubframe())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(bc->IsContentSubframe()))
), 0))) { do { } while (false); MOZ_ReportAssertionFailure("bc->IsContentSubframe()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1237); AnnotateMozCrashReason("MOZ_ASSERT" "(" "bc->IsContentSubframe()"
")"); do { *((volatile int*)__null) = 1237; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1238
1239 if (bc->GetParent()->IsInProcess()) {
1240 if (Element* embedder = bc->GetEmbedderElement()) {
1241 if (nsCOMPtr<nsIObjectLoadingContent> olc = do_QueryInterface(embedder)) {
1242 static_cast<nsObjectLoadingContent*>(olc.get())
1243 ->SubdocumentIntrinsicSizeOrRatioChanged(aIntrinsicSize,
1244 aIntrinsicRatio);
1245 } else {
1246 MOZ_ASSERT_UNREACHABLE("Got out of sync?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(false)>::isValid, "invalid assertion condition");
if ((__builtin_expect(!!(!(!!(false))), 0))) { do { } while (
false); MOZ_ReportAssertionFailure("false" " (" "MOZ_ASSERT_UNREACHABLE: "
"Got out of sync?" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1246); AnnotateMozCrashReason("MOZ_ASSERT" "(" "false" ") ("
"MOZ_ASSERT_UNREACHABLE: " "Got out of sync?" ")"); do { *((
volatile int*)__null) = 1246; __attribute__((nomerge)) ::abort
(); } while (false); } } while (false)
;
1247 }
1248 return;
1249 }
1250 }
1251
1252 if (BrowserChild* browserChild = BrowserChild::GetFrom(docShell)) {
1253 Unused << browserChild->SendIntrinsicSizeOrRatioChanged(aIntrinsicSize,
1254 aIntrinsicRatio);
1255 }
1256}
1257
1258void nsImageFrame::OnLoadComplete(imgIRequest* aRequest) {
1259 NotifyNewCurrentRequest(aRequest);
1260}
1261
1262void nsImageFrame::ElementStateChanged(ElementState aStates) {
1263 if (!(aStates & ElementState::BROKEN)) {
1264 return;
1265 }
1266 if (mKind != Kind::ImageLoadingContent) {
1267 return;
1268 }
1269 if (!ImageOk(mContent->AsElement()->State())) {
1270 UpdateImage(nullptr, nullptr);
1271 }
1272}
1273
1274void nsImageFrame::ResponsiveContentDensityChanged() {
1275 UpdateIntrinsicSizeAndRatio();
1276}
1277
1278void nsImageFrame::UpdateIntrinsicSizeAndRatio() {
1279 bool intrinsicSizeOrRatioChanged = [&] {
1280 // NOTE(emilio): We intentionally want to call both functions and avoid
1281 // short-circuiting.
1282 bool intrinsicSizeChanged = UpdateIntrinsicSize();
1283 bool intrinsicRatioChanged = UpdateIntrinsicRatio();
1284 return intrinsicSizeChanged || intrinsicRatioChanged;
1285 }();
1286
1287 if (!intrinsicSizeOrRatioChanged) {
1288 return;
1289 }
1290
1291 // Our aspect-ratio property value changed, and an embedding <object> or
1292 // <embed> might care about that.
1293 MaybeSendIntrinsicSizeAndRatioToEmbedder();
1294
1295 if (!GotInitialReflow()) {
1296 return;
1297 }
1298
1299 // Now we need to reflow if we have an unconstrained size and have
1300 // already gotten the initial reflow.
1301 if (!HasAnyStateBits(IMAGE_SIZECONSTRAINED)) {
1302 PresShell()->FrameNeedsReflow(
1303 this, IntrinsicDirty::FrameAncestorsAndDescendants, NS_FRAME_IS_DIRTY);
1304 } else if (PresShell()->IsActive()) {
1305 // We've already gotten the initial reflow, and our size hasn't changed,
1306 // so we're ready to request a decode.
1307 MaybeDecodeForPredictedSize();
1308 }
1309}
1310
1311void nsImageFrame::NotifyNewCurrentRequest(imgIRequest* aRequest) {
1312 nsCOMPtr<imgIContainer> image;
1313 aRequest->GetImage(getter_AddRefs(image));
1314#ifdef DEBUG1
1315 uint32_t imgStatus;
1316 aRequest->GetImageStatus(&imgStatus);
1317 NS_ASSERTION(image || (imgStatus & imgIRequest::STATUS_ERROR),do { if (!(image || (imgStatus & imgIRequest::STATUS_ERROR
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Successful load with no container?"
, "image || (imgStatus & imgIRequest::STATUS_ERROR)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1318); MOZ_PretendNoReturn(); } } while (0)
1318 "Successful load with no container?")do { if (!(image || (imgStatus & imgIRequest::STATUS_ERROR
))) { NS_DebugBreak(NS_DEBUG_ASSERTION, "Successful load with no container?"
, "image || (imgStatus & imgIRequest::STATUS_ERROR)", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1318); MOZ_PretendNoReturn(); } } while (0)
;
1319#endif
1320 UpdateImage(aRequest, image);
1321}
1322
1323void nsImageFrame::MaybeDecodeForPredictedSize() {
1324 // Check that we're ready to decode.
1325 if (!mImage) {
1326 return; // Nothing to do yet.
1327 }
1328
1329 if (mComputedSize.IsEmpty()) {
1330 return; // We won't draw anything, so no point in decoding.
1331 }
1332
1333 if (GetVisibility() != Visibility::ApproximatelyVisible) {
1334 return; // We're not visible, so don't decode.
1335 }
1336
1337 // OK, we're ready to decode. Compute the scale to the screen...
1338 mozilla::PresShell* presShell = PresShell();
1339 MatrixScales scale =
1340 ScaleFactor<UnknownUnits, UnknownUnits>(
1341 presShell->GetCumulativeResolution()) *
1342 nsLayoutUtils::GetTransformToAncestorScaleExcludingAnimated(this);
1343 auto resolutionToScreen = ViewAs<LayoutDeviceToScreenScale2D>(scale);
1344
1345 // If we are in a remote browser, then apply scaling from ancestor browsers
1346 if (BrowserChild* browserChild = BrowserChild::GetFrom(presShell)) {
1347 resolutionToScreen =
1348 resolutionToScreen * ViewAs<ScreenToScreenScale2D>(
1349 browserChild->GetEffectsInfo().mRasterScale);
1350 }
1351
1352 // ...and this frame's content box...
1353 const nsPoint offset =
1354 GetOffsetToCrossDoc(nsLayoutUtils::GetReferenceFrame(this));
1355 const nsRect frameContentBox = GetContentRectRelativeToSelf() + offset;
1356
1357 // ...and our predicted dest rect...
1358 const int32_t factor = PresContext()->AppUnitsPerDevPixel();
1359 const LayoutDeviceRect destRect =
1360 LayoutDeviceRect::FromAppUnits(GetDestRect(frameContentBox), factor);
1361
1362 // ...and use them to compute our predicted size in screen pixels.
1363 const ScreenSize predictedScreenSize = destRect.Size() * resolutionToScreen;
1364 const ScreenIntSize predictedScreenIntSize =
1365 RoundedToInt(predictedScreenSize);
1366 if (predictedScreenIntSize.IsEmpty()) {
1367 return;
1368 }
1369
1370 // Determine the optimal image size to use.
1371 uint32_t flags = imgIContainer::FLAG_HIGH_QUALITY_SCALING |
1372 imgIContainer::FLAG_ASYNC_NOTIFY;
1373 SamplingFilter samplingFilter =
1374 nsLayoutUtils::GetSamplingFilterForFrame(this);
1375 gfxSize gfxPredictedScreenSize =
1376 gfxSize(predictedScreenIntSize.width, predictedScreenIntSize.height);
1377 nsIntSize predictedImageSize = mImage->OptimalImageSizeForDest(
1378 gfxPredictedScreenSize, imgIContainer::FRAME_CURRENT, samplingFilter,
1379 flags);
1380
1381 // Request a decode.
1382 mImage->RequestDecodeForSize(predictedImageSize, flags);
1383}
1384
1385nsRect nsImageFrame::GetDestRect(const nsRect& aFrameContentBox,
1386 nsPoint* aAnchorPoint) {
1387 // Note: To get the "dest rect", we have to provide the "constraint rect"
1388 // (which is the content-box, with the effects of fragmentation undone).
1389 nsRect constraintRect(aFrameContentBox.TopLeft(), mComputedSize);
1390 constraintRect.y -= GetContinuationOffset();
1391
1392 auto intrinsicSize = mIntrinsicSize;
1393 auto intrinsicRatio = mIntrinsicRatio;
1394 if (GetContainSizeAxes().IsAny()) {
1395 // Ignore containment for object-fit computations.
1396 const bool ignoreContainment = true;
1397 intrinsicSize = ComputeIntrinsicSize(ignoreContainment);
1398 intrinsicRatio = ComputeIntrinsicRatioForImage(mImage, ignoreContainment);
1399 }
1400 return nsLayoutUtils::ComputeObjectDestRect(constraintRect, intrinsicSize,
1401 intrinsicRatio, StylePosition(),
1402 aAnchorPoint);
1403}
1404
1405bool nsImageFrame::IsForMarkerPseudo() const {
1406 if (mKind == Kind::ImageLoadingContent) {
1407 return false;
1408 }
1409 auto* subtreeRoot = GetContent()->GetClosestNativeAnonymousSubtreeRoot();
1410 return subtreeRoot && subtreeRoot->IsGeneratedContentContainerForMarker();
1411}
1412
1413void nsImageFrame::EnsureIntrinsicSizeAndRatio() {
1414 const auto containAxes = GetContainSizeAxes();
1415 if (containAxes.IsBoth()) {
1416 // If we have 'contain:size', then we have no intrinsic aspect ratio,
1417 // and the intrinsic size is determined by contain-intrinsic-size,
1418 // regardless of what our underlying image may think.
1419 mIntrinsicSize = FinishIntrinsicSize(containAxes, IntrinsicSize(0, 0));
1420 mIntrinsicRatio = AspectRatio();
1421 return;
1422 }
1423
1424 // If mIntrinsicSize.width and height are 0, then we need to update from the
1425 // image container. Note that we handle ::marker intrinsic size/ratio in
1426 // DidSetComputedStyle.
1427 if (mIntrinsicSize != IntrinsicSize(0, 0) && !IsForMarkerPseudo()) {
1428 return;
1429 }
1430
1431 bool intrinsicSizeOrRatioChanged = UpdateIntrinsicSize();
1432 intrinsicSizeOrRatioChanged =
1433 UpdateIntrinsicRatio() || intrinsicSizeOrRatioChanged;
1434
1435 if (intrinsicSizeOrRatioChanged) {
1436 // Our aspect-ratio property value changed, and an embedding <object> or
1437 // <embed> might care about that.
1438 MaybeSendIntrinsicSizeAndRatioToEmbedder();
1439 }
1440}
1441
1442nsIFrame::SizeComputationResult nsImageFrame::ComputeSize(
1443 gfxContext* aRenderingContext, WritingMode aWM, const LogicalSize& aCBSize,
1444 nscoord aAvailableISize, const LogicalSize& aMargin,
1445 const LogicalSize& aBorderPadding, const StyleSizeOverrides& aSizeOverrides,
1446 ComputeSizeFlags aFlags) {
1447 EnsureIntrinsicSizeAndRatio();
1448 return {ComputeSizeWithIntrinsicDimensions(
1449 aRenderingContext, aWM, mIntrinsicSize, GetAspectRatio(), aCBSize,
1450 aMargin, aBorderPadding, aSizeOverrides, aFlags),
1451 AspectRatioUsage::None};
1452}
1453
1454Element* nsImageFrame::GetMapElement() const {
1455 return IsForImageLoadingContent()
1456 ? nsImageLoadingContent::FindImageMap(mContent->AsElement())
1457 : nullptr;
1458}
1459
1460// get the offset into the content area of the image where aImg starts if it is
1461// a continuation.
1462nscoord nsImageFrame::GetContinuationOffset() const {
1463 nscoord offset = 0;
1464 for (nsIFrame* f = GetPrevInFlow(); f; f = f->GetPrevInFlow()) {
1465 offset += f->GetContentRect().height;
1466 }
1467 NS_ASSERTION(offset >= 0, "bogus GetContentRect")do { if (!(offset >= 0)) { NS_DebugBreak(NS_DEBUG_ASSERTION
, "bogus GetContentRect", "offset >= 0", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1467); MOZ_PretendNoReturn(); } } while (0)
;
1468 return offset;
1469}
1470
1471nscoord nsImageFrame::IntrinsicISize(const IntrinsicSizeInput& aInput,
1472 IntrinsicISizeType aType) {
1473 EnsureIntrinsicSizeAndRatio();
1474 return mIntrinsicSize.ISize(GetWritingMode()).valueOr(0);
1475}
1476
1477void nsImageFrame::ReflowChildren(nsPresContext* aPresContext,
1478 const ReflowInput& aReflowInput,
1479 const LogicalSize& aImageSize) {
1480 for (nsIFrame* child : mFrames) {
1481 ReflowOutput childDesiredSize(aReflowInput);
1482 WritingMode wm = GetWritingMode();
1483 // Shouldn't be hard to support if we want, but why bother.
1484 MOZ_ASSERT(do { static_assert( mozilla::detail::AssertionConditionType<
decltype(wm == child->GetWritingMode())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(wm == child->GetWritingMode
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("wm == child->GetWritingMode()" " (" "We don't expect mismatched writing-modes in content we control"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1486); AnnotateMozCrashReason("MOZ_ASSERT" "(" "wm == child->GetWritingMode()"
") (" "We don't expect mismatched writing-modes in content we control"
")"); do { *((volatile int*)__null) = 1486; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1485 wm == child->GetWritingMode(),do { static_assert( mozilla::detail::AssertionConditionType<
decltype(wm == child->GetWritingMode())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(wm == child->GetWritingMode
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("wm == child->GetWritingMode()" " (" "We don't expect mismatched writing-modes in content we control"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1486); AnnotateMozCrashReason("MOZ_ASSERT" "(" "wm == child->GetWritingMode()"
") (" "We don't expect mismatched writing-modes in content we control"
")"); do { *((volatile int*)__null) = 1486; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
1486 "We don't expect mismatched writing-modes in content we control")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(wm == child->GetWritingMode())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(wm == child->GetWritingMode
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("wm == child->GetWritingMode()" " (" "We don't expect mismatched writing-modes in content we control"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1486); AnnotateMozCrashReason("MOZ_ASSERT" "(" "wm == child->GetWritingMode()"
") (" "We don't expect mismatched writing-modes in content we control"
")"); do { *((volatile int*)__null) = 1486; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1487 nsReflowStatus childStatus;
1488
1489 LogicalPoint childOffset(wm);
1490 ReflowInput childReflowInput(aPresContext, aReflowInput, child, aImageSize);
1491 const nsSize containerSize = aImageSize.GetPhysicalSize(wm);
1492 ReflowChild(child, aPresContext, childDesiredSize, childReflowInput, wm,
1493 childOffset, containerSize, ReflowChildFlags::Default,
1494 childStatus);
1495
1496 FinishReflowChild(child, aPresContext, childDesiredSize, &childReflowInput,
1497 wm, childOffset, containerSize,
1498 ReflowChildFlags::Default);
1499 }
1500}
1501
1502void nsImageFrame::Reflow(nsPresContext* aPresContext, ReflowOutput& aMetrics,
1503 const ReflowInput& aReflowInput,
1504 nsReflowStatus& aStatus) {
1505 MarkInReflow();
1506 DO_GLOBAL_REFLOW_COUNT("nsImageFrame")aPresContext->CountReflows(("nsImageFrame"), (nsIFrame*)this
);
;
1507 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/nsImageFrame.cpp"
, 1507); AnnotateMozCrashReason("MOZ_ASSERT" "(" "aStatus.IsEmpty()"
") (" "Caller should pass a fresh reflow status!" ")"); do {
*((volatile int*)__null) = 1507; __attribute__((nomerge)) ::
abort(); } while (false); } } while (false)
;
1508 NS_FRAME_TRACE(do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("enter nsImageFrame::Reflow: availSize=%d,%d"
, aReflowInput.AvailableWidth(), aReflowInput.AvailableHeight
()); } } while (0)
1509 NS_FRAME_TRACE_CALLS,do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("enter nsImageFrame::Reflow: availSize=%d,%d"
, aReflowInput.AvailableWidth(), aReflowInput.AvailableHeight
()); } } while (0)
1510 ("enter nsImageFrame::Reflow: availSize=%d,%d",do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("enter nsImageFrame::Reflow: availSize=%d,%d"
, aReflowInput.AvailableWidth(), aReflowInput.AvailableHeight
()); } } while (0)
1511 aReflowInput.AvailableWidth(), aReflowInput.AvailableHeight()))do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("enter nsImageFrame::Reflow: availSize=%d,%d"
, aReflowInput.AvailableWidth(), aReflowInput.AvailableHeight
()); } } while (0)
;
1512
1513 MOZ_ASSERT(HasAnyStateBits(NS_FRAME_IN_REFLOW), "frame is not in reflow")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(HasAnyStateBits(NS_FRAME_IN_REFLOW))>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(HasAnyStateBits(NS_FRAME_IN_REFLOW
)))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("HasAnyStateBits(NS_FRAME_IN_REFLOW)" " (" "frame is not in reflow"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1513); AnnotateMozCrashReason("MOZ_ASSERT" "(" "HasAnyStateBits(NS_FRAME_IN_REFLOW)"
") (" "frame is not in reflow" ")"); do { *((volatile int*)__null
) = 1513; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false)
;
1514
1515 // see if we have a frozen size (i.e. a fixed width and height)
1516 if (!SizeDependsOnIntrinsicSize(aReflowInput)) {
1517 AddStateBits(IMAGE_SIZECONSTRAINED);
1518 } else {
1519 RemoveStateBits(IMAGE_SIZECONSTRAINED);
1520 }
1521
1522 mComputedSize = aReflowInput.ComputedPhysicalSize();
1523
1524 const auto wm = GetWritingMode();
1525 aMetrics.SetSize(wm, aReflowInput.ComputedSizeWithBorderPadding(wm));
1526
1527 if (GetPrevInFlow()) {
1528 aMetrics.Width() = GetPrevInFlow()->GetSize().width;
1529 nscoord y = GetContinuationOffset();
1530 aMetrics.Height() -= y + aReflowInput.ComputedPhysicalBorderPadding().top;
1531 aMetrics.Height() = std::max(0, aMetrics.Height());
1532 }
1533
1534 // we have to split images if we are:
1535 // in Paginated mode, we need to have a constrained height, and have a height
1536 // larger than our available height
1537 uint32_t loadStatus = imgIRequest::STATUS_NONE;
1538 if (nsCOMPtr<imgIRequest> currentRequest = GetCurrentRequest()) {
1539 currentRequest->GetImageStatus(&loadStatus);
1540 }
1541
1542 if (aPresContext->IsPaginated() &&
1543 ((loadStatus & imgIRequest::STATUS_SIZE_AVAILABLE) ||
1544 HasAnyStateBits(IMAGE_SIZECONSTRAINED)) &&
1545 NS_UNCONSTRAINEDSIZE != aReflowInput.AvailableHeight() &&
1546 aMetrics.Height() > aReflowInput.AvailableHeight()) {
1547 // our desired height was greater than 0, so to avoid infinite
1548 // splitting, use 1 pixel as the min
1549 aMetrics.Height() = std::max(nsPresContext::CSSPixelsToAppUnits(1),
1550 aReflowInput.AvailableHeight());
1551 aStatus.SetIncomplete();
1552 }
1553
1554 aMetrics.SetOverflowAreasToDesiredBounds();
1555 bool imageOK = mKind != Kind::ImageLoadingContent ||
1556 ImageOk(mContent->AsElement()->State());
1557
1558 // Determine if the size is available
1559 bool haveSize = false;
1560 if (loadStatus & imgIRequest::STATUS_SIZE_AVAILABLE) {
1561 haveSize = true;
1562 }
1563
1564 if (!imageOK || !haveSize) {
1565 nsRect altFeedbackSize(
1566 0, 0,
1567 nsPresContext::CSSPixelsToAppUnits(
1568 ICON_SIZE(16) + 2 * (ICON_PADDING(3) + ALT_BORDER_WIDTH(1))),
1569 nsPresContext::CSSPixelsToAppUnits(
1570 ICON_SIZE(16) + 2 * (ICON_PADDING(3) + ALT_BORDER_WIDTH(1))));
1571 // We include the altFeedbackSize in our ink overflow, but not in our
1572 // scrollable overflow, since it doesn't really need to be scrolled to
1573 // outside the image.
1574 nsRect& inkOverflow = aMetrics.InkOverflow();
1575 inkOverflow.UnionRect(inkOverflow, altFeedbackSize);
1576 } else if (PresShell()->IsActive()) {
1577 // We've just reflowed and we should have an accurate size, so we're ready
1578 // to request a decode.
1579 MaybeDecodeForPredictedSize();
1580 }
1581 FinishAndStoreOverflow(&aMetrics, aReflowInput.mStyleDisplay);
1582
1583 // Reflow the child frames. Our children can't affect our size in any way.
1584 ReflowChildren(aPresContext, aReflowInput, aMetrics.Size(GetWritingMode()));
1585
1586 if (HasAnyStateBits(NS_FRAME_FIRST_REFLOW) && !mReflowCallbackPosted) {
1587 mReflowCallbackPosted = true;
1588 PresShell()->PostReflowCallback(this);
1589 }
1590
1591 NS_FRAME_TRACE(NS_FRAME_TRACE_CALLS, ("exit nsImageFrame::Reflow: size=%d,%d",do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("exit nsImageFrame::Reflow: size=%d,%d"
, aMetrics.Width(), aMetrics.Height()); } } while (0)
1592 aMetrics.Width(), aMetrics.Height()))do { if ((int(((mozilla::LogModule*)(nsIFrame::sFrameLogModule
))->Level()) & (0x1))) { TraceMsg ("exit nsImageFrame::Reflow: size=%d,%d"
, aMetrics.Width(), aMetrics.Height()); } } while (0)
;
1593}
1594
1595bool nsImageFrame::ReflowFinished() {
1596 mReflowCallbackPosted = false;
1597
1598 // XXX(seth): We don't need this. The purpose of updating visibility
1599 // synchronously is to ensure that animated images start animating
1600 // immediately. In the short term, however,
1601 // nsImageLoadingContent::OnUnlockedDraw() is enough to ensure that
1602 // animations start as soon as the image is painted for the first time, and in
1603 // the long term we want to update visibility information from the display
1604 // list whenever we paint, so we don't actually need to do this. However, to
1605 // avoid behavior changes during the transition from the old image visibility
1606 // code, we'll leave it in for now.
1607 UpdateVisibilitySynchronously();
1608
1609 return false;
1610}
1611
1612void nsImageFrame::ReflowCallbackCanceled() { mReflowCallbackPosted = false; }
1613
1614// Computes the width of the specified string. aMaxWidth specifies the maximum
1615// width available. Once this limit is reached no more characters are measured.
1616// The number of characters that fit within the maximum width are returned in
1617// aMaxFit. NOTE: it is assumed that the fontmetrics have already been selected
1618// into the rendering context before this is called (for performance). MMP
1619nscoord nsImageFrame::MeasureString(const char16_t* aString, int32_t aLength,
1620 nscoord aMaxWidth, uint32_t& aMaxFit,
1621 gfxContext& aContext,
1622 nsFontMetrics& aFontMetrics) {
1623 nscoord totalWidth = 0;
1624 aFontMetrics.SetTextRunRTL(false);
1625 nscoord spaceWidth = aFontMetrics.SpaceWidth();
1626
1627 aMaxFit = 0;
1628 while (aLength > 0) {
1629 // Find the next place we can line break
1630 uint32_t len = aLength;
1631 bool trailingSpace = false;
1632 for (int32_t i = 0; i < aLength; i++) {
1633 if (dom::IsSpaceCharacter(aString[i]) && (i > 0)) {
1634 len = i; // don't include the space when measuring
1635 trailingSpace = true;
1636 break;
1637 }
1638 }
1639
1640 // Measure this chunk of text, and see if it fits
1641 nscoord width = nsLayoutUtils::AppUnitWidthOfStringBidi(
1642 aString, len, this, aFontMetrics, aContext);
1643 bool fits = (totalWidth + width) <= aMaxWidth;
1644
1645 // If it fits on the line, or it's the first word we've processed then
1646 // include it
1647 if (fits || (0 == totalWidth)) {
1648 // New piece fits
1649 totalWidth += width;
1650
1651 // If there's a trailing space then see if it fits as well
1652 if (trailingSpace) {
1653 if ((totalWidth + spaceWidth) <= aMaxWidth) {
1654 totalWidth += spaceWidth;
1655 } else {
1656 // Space won't fit. Leave it at the end but don't include it in
1657 // the width
1658 fits = false;
1659 }
1660
1661 len++;
1662 }
1663
1664 aMaxFit += len;
1665 aString += len;
1666 aLength -= len;
1667 }
1668
1669 if (!fits) {
1670 break;
1671 }
1672 }
1673 return totalWidth;
1674}
1675
1676// Formats the alt-text to fit within the specified rectangle. Breaks lines
1677// between words if a word would extend past the edge of the rectangle
1678void nsImageFrame::DisplayAltText(nsPresContext* aPresContext,
1679 gfxContext& aRenderingContext,
1680 const nsString& aAltText,
1681 const nsRect& aRect) {
1682 // Set font and color
1683 aRenderingContext.SetColor(
1684 sRGBColor::FromABGR(StyleText()->mColor.ToColor()));
1685 RefPtr<nsFontMetrics> fm =
1686 nsLayoutUtils::GetInflatedFontMetricsForFrame(this);
1687
1688 // Format the text to display within the formatting rect
1689
1690 nscoord maxAscent = fm->MaxAscent();
1691 nscoord maxDescent = fm->MaxDescent();
1692 nscoord lineHeight = fm->MaxHeight(); // line-relative, so an x-coordinate
1693 // length if writing mode is vertical
1694
1695 WritingMode wm = GetWritingMode();
1696 bool isVertical = wm.IsVertical();
1697
1698 fm->SetVertical(isVertical);
1699 fm->SetTextOrientation(StyleVisibility()->mTextOrientation);
1700
1701 // XXX It would be nice if there was a way to have the font metrics tell
1702 // use where to break the text given a maximum width. At a minimum we need
1703 // to be able to get the break character...
1704 const char16_t* str = aAltText.get();
1705 int32_t strLen = aAltText.Length();
1706 nsPoint pt = wm.IsVerticalRL() ? aRect.TopRight() - nsPoint(lineHeight, 0)
1707 : aRect.TopLeft();
1708 nscoord iSize = isVertical ? aRect.height : aRect.width;
1709
1710 if (!aPresContext->BidiEnabled() && HasRTLChars(aAltText)) {
1711 aPresContext->SetBidiEnabled();
1712 }
1713
1714 // Always show the first line, even if we have to clip it below
1715 bool firstLine = true;
1716 while (strLen > 0) {
1717 if (!firstLine) {
1718 // If we've run out of space, break out of the loop
1719 if ((!isVertical && (pt.y + maxDescent) >= aRect.YMost()) ||
1720 (wm.IsVerticalRL() && (pt.x + maxDescent < aRect.x)) ||
1721 (wm.IsVerticalLR() && (pt.x + maxDescent >= aRect.XMost()))) {
1722 break;
1723 }
1724 }
1725
1726 // Determine how much of the text to display on this line
1727 uint32_t maxFit; // number of characters that fit
1728 nscoord strWidth =
1729 MeasureString(str, strLen, iSize, maxFit, aRenderingContext, *fm);
1730
1731 // Display the text
1732 nsresult rv = NS_ERROR_FAILURE;
1733
1734 if (aPresContext->BidiEnabled()) {
1735 mozilla::intl::BidiEmbeddingLevel level;
1736 nscoord x, y;
1737
1738 if (isVertical) {
1739 x = pt.x + maxDescent;
1740 if (wm.IsBidiLTR()) {
1741 y = aRect.y;
1742 level = mozilla::intl::BidiEmbeddingLevel::LTR();
1743 } else {
1744 y = aRect.YMost() - strWidth;
1745 level = mozilla::intl::BidiEmbeddingLevel::RTL();
1746 }
1747 } else {
1748 y = pt.y + maxAscent;
1749 if (wm.IsBidiLTR()) {
1750 x = aRect.x;
1751 level = mozilla::intl::BidiEmbeddingLevel::LTR();
1752 } else {
1753 x = aRect.XMost() - strWidth;
1754 level = mozilla::intl::BidiEmbeddingLevel::RTL();
1755 }
1756 }
1757
1758 rv = nsBidiPresUtils::RenderText(
1759 str, maxFit, level, aPresContext, aRenderingContext,
1760 aRenderingContext.GetDrawTarget(), *fm, x, y);
1761 }
1762 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
1763 nsLayoutUtils::DrawUniDirString(str, maxFit,
1764 isVertical
1765 ? nsPoint(pt.x + maxDescent, pt.y)
1766 : nsPoint(pt.x, pt.y + maxAscent),
1767 *fm, aRenderingContext);
1768 }
1769
1770 // Move to the next line
1771 str += maxFit;
1772 strLen -= maxFit;
1773 if (wm.IsVerticalRL()) {
1774 pt.x -= lineHeight;
1775 } else if (wm.IsVerticalLR()) {
1776 pt.x += lineHeight;
1777 } else {
1778 pt.y += lineHeight;
1779 }
1780
1781 firstLine = false;
1782 }
1783}
1784
1785struct nsRecessedBorder : public nsStyleBorder {
1786 explicit nsRecessedBorder(nscoord aBorderWidth) {
1787 for (const auto side : AllPhysicalSides()) {
1788 BorderColorFor(side) = StyleColor::Black();
1789 mBorder.Side(side) = aBorderWidth;
1790 // Note: use SetBorderStyle here because we want to affect
1791 // mComputedBorder
1792 SetBorderStyle(side, StyleBorderStyle::Inset);
1793 }
1794 }
1795};
1796
1797class nsDisplayAltFeedback final : public nsPaintedDisplayItem {
1798 public:
1799 nsDisplayAltFeedback(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
1800 : nsPaintedDisplayItem(aBuilder, aFrame) {}
1801
1802 nsRect GetBounds(nsDisplayListBuilder* aBuilder, bool* aSnap) const final {
1803 *aSnap = false;
1804 return mFrame->InkOverflowRectRelativeToSelf() + ToReferenceFrame();
1805 }
1806
1807 void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) final {
1808 // Always sync decode, because these icons are UI, and since they're not
1809 // discardable we'll pay the price of sync decoding at most once.
1810 uint32_t flags = imgIContainer::FLAG_SYNC_DECODE;
1811
1812 nsImageFrame* f = static_cast<nsImageFrame*>(mFrame);
1813 Unused << f->DisplayAltFeedback(*aCtx, GetPaintRect(aBuilder, aCtx),
1814 ToReferenceFrame(), flags);
1815 }
1816
1817 bool CreateWebRenderCommands(
1818 mozilla::wr::DisplayListBuilder& aBuilder,
1819 mozilla::wr::IpcResourceUpdateQueue& aResources,
1820 const StackingContextHelper& aSc,
1821 mozilla::layers::RenderRootStateManager* aManager,
1822 nsDisplayListBuilder* aDisplayListBuilder) final {
1823 // Always sync decode, because these icons are UI, and since they're not
1824 // discardable we'll pay the price of sync decoding at most once.
1825 uint32_t flags =
1826 imgIContainer::FLAG_SYNC_DECODE | imgIContainer::FLAG_ASYNC_NOTIFY;
1827 nsImageFrame* f = static_cast<nsImageFrame*>(mFrame);
1828 ImgDrawResult result = f->DisplayAltFeedbackWithoutLayer(
1829 this, aBuilder, aResources, aSc, aManager, aDisplayListBuilder,
1830 ToReferenceFrame(), flags);
1831
1832 return result == ImgDrawResult::SUCCESS;
1833 }
1834
1835 NS_DISPLAY_DECL_NAME("AltFeedback", TYPE_ALT_FEEDBACK)const char* Name() const override { return "AltFeedback"; } constexpr
static DisplayItemType ItemType() { return DisplayItemType::
TYPE_ALT_FEEDBACK; } private: void* operator new(size_t aSize
, nsDisplayListBuilder* aBuilder) { return aBuilder->Allocate
(aSize, DisplayItemType::TYPE_ALT_FEEDBACK); } template <typename
T, typename F, typename... Args> friend T* mozilla::MakeDisplayItemWithIndex
( nsDisplayListBuilder* aBuilder, F* aFrame, const uint16_t aIndex
, Args&&... aArgs); public:
1836};
1837
1838ImgDrawResult nsImageFrame::DisplayAltFeedback(gfxContext& aRenderingContext,
1839 const nsRect& aDirtyRect,
1840 nsPoint aPt, uint32_t aFlags) {
1841 // Whether we draw the broken or loading icon.
1842 bool isLoading = mKind != Kind::ImageLoadingContent ||
1843 ImageOk(mContent->AsElement()->State());
1844
1845 // Calculate the content area.
1846 nsRect inner = GetContentRectRelativeToSelf() + aPt;
1847
1848 // Display a recessed one pixel border
1849 nscoord borderEdgeWidth =
1850 nsPresContext::CSSPixelsToAppUnits(ALT_BORDER_WIDTH(1));
1851
1852 // if inner area is empty, then make it big enough for at least the icon
1853 if (inner.IsEmpty()) {
1854 inner.SizeTo(2 * (nsPresContext::CSSPixelsToAppUnits(
1855 ICON_SIZE(16) + ICON_PADDING(3) + ALT_BORDER_WIDTH(1))),
1856 2 * (nsPresContext::CSSPixelsToAppUnits(
1857 ICON_SIZE(16) + ICON_PADDING(3) + ALT_BORDER_WIDTH(1))));
1858 }
1859
1860 // Make sure we have enough room to actually render the border within
1861 // our frame bounds
1862 if ((inner.width < 2 * borderEdgeWidth) ||
1863 (inner.height < 2 * borderEdgeWidth)) {
1864 return ImgDrawResult::SUCCESS;
1865 }
1866
1867 // Paint the border
1868 if (!isLoading) {
1869 nsRecessedBorder recessedBorder(borderEdgeWidth);
1870
1871 // Assert that we're not drawing a border-image here; if we were, we
1872 // couldn't ignore the ImgDrawResult that PaintBorderWithStyleBorder
1873 // returns.
1874 MOZ_ASSERT(recessedBorder.mBorderImageSource.IsNone())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(recessedBorder.mBorderImageSource.IsNone())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(recessedBorder.mBorderImageSource.IsNone()))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("recessedBorder.mBorderImageSource.IsNone()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1874); AnnotateMozCrashReason("MOZ_ASSERT" "(" "recessedBorder.mBorderImageSource.IsNone()"
")"); do { *((volatile int*)__null) = 1874; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
1875
1876 Unused << nsCSSRendering::PaintBorderWithStyleBorder(
1877 PresContext(), aRenderingContext, this, inner, inner, recessedBorder,
1878 mComputedStyle, PaintBorderFlags::SyncDecodeImages);
1879 }
1880
1881 // Adjust the inner rect to account for the one pixel recessed border,
1882 // and a six pixel padding on each edge
1883 inner.Deflate(
1884 nsPresContext::CSSPixelsToAppUnits(ICON_PADDING(3) + ALT_BORDER_WIDTH(1)),
1885 nsPresContext::CSSPixelsToAppUnits(ICON_PADDING(3) + ALT_BORDER_WIDTH(1)));
1886 if (inner.IsEmpty()) {
1887 return ImgDrawResult::SUCCESS;
1888 }
1889
1890 DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
1891
1892 // Clip so we don't render outside the inner rect
1893 aRenderingContext.Save();
1894 aRenderingContext.Clip(NSRectToSnappedRect(
1895 inner, PresContext()->AppUnitsPerDevPixel(), *drawTarget));
1896
1897 ImgDrawResult result = ImgDrawResult::SUCCESS;
1898
1899 // Check if we should display image placeholders
1900 if (ShouldShowBrokenImageIcon()) {
1901 result = ImgDrawResult::NOT_READY;
1902 nscoord size = nsPresContext::CSSPixelsToAppUnits(ICON_SIZE(16));
1903 imgIRequest* request = BrokenImageIcon::GetImage(this);
1904
1905 // If we weren't previously displaying an icon, register ourselves
1906 // as an observer for load and animation updates and flag that we're
1907 // doing so now.
1908 if (request && !mDisplayingIcon) {
1909 BrokenImageIcon::AddObserver(this);
1910 mDisplayingIcon = true;
1911 }
1912
1913 WritingMode wm = GetWritingMode();
1914 bool flushRight = wm.IsPhysicalRTL();
1915
1916 // If the icon in question is loaded, draw it.
1917 uint32_t imageStatus = 0;
1918 if (request) {
1919 request->GetImageStatus(&imageStatus);
1920 }
1921 if (imageStatus & imgIRequest::STATUS_LOAD_COMPLETE &&
1922 !(imageStatus & imgIRequest::STATUS_ERROR)) {
1923 nsCOMPtr<imgIContainer> imgCon;
1924 request->GetImage(getter_AddRefs(imgCon));
1925 MOZ_ASSERT(imgCon, "Load complete, but no image container?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(imgCon)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(imgCon))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("imgCon" " (" "Load complete, but no image container?"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 1925); AnnotateMozCrashReason("MOZ_ASSERT" "(" "imgCon" ") ("
"Load complete, but no image container?" ")"); do { *((volatile
int*)__null) = 1925; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
1926 nsRect dest(flushRight ? inner.XMost() - size : inner.x, inner.y, size,
1927 size);
1928 result = nsLayoutUtils::DrawSingleImage(
1929 aRenderingContext, PresContext(), imgCon,
1930 nsLayoutUtils::GetSamplingFilterForFrame(this), dest, aDirtyRect,
1931 SVGImageContext(), aFlags);
1932 }
1933
1934 // If we could not draw the icon, just draw some graffiti in the mean time.
1935 if (result == ImgDrawResult::NOT_READY) {
1936 ColorPattern color(ToDeviceColor(sRGBColor(1.f, 0.f, 0.f, 1.f)));
1937
1938 nscoord iconXPos = flushRight ? inner.XMost() - size : inner.x;
1939
1940 // stroked rect:
1941 nsRect rect(iconXPos, inner.y, size, size);
1942 Rect devPxRect = ToRect(nsLayoutUtils::RectToGfxRect(
1943 rect, PresContext()->AppUnitsPerDevPixel()));
1944 drawTarget->StrokeRect(devPxRect, color);
1945
1946 // filled circle in bottom right quadrant of stroked rect:
1947 nscoord twoPX = nsPresContext::CSSPixelsToAppUnits(2);
1948 rect = nsRect(iconXPos + size / 2, inner.y + size / 2, size / 2 - twoPX,
1949 size / 2 - twoPX);
1950 devPxRect = ToRect(nsLayoutUtils::RectToGfxRect(
1951 rect, PresContext()->AppUnitsPerDevPixel()));
1952 RefPtr<PathBuilder> builder = drawTarget->CreatePathBuilder();
1953 AppendEllipseToPath(builder, devPxRect.Center(), devPxRect.Size());
1954 RefPtr<Path> ellipse = builder->Finish();
1955 drawTarget->Fill(ellipse, color);
1956 }
1957
1958 // Reduce the inner rect by the width of the icon, and leave an
1959 // additional ICON_PADDING pixels for padding
1960 int32_t paddedIconSize =
1961 nsPresContext::CSSPixelsToAppUnits(ICON_SIZE(16) + ICON_PADDING(3));
1962 if (wm.IsVertical()) {
1963 inner.y += paddedIconSize;
1964 inner.height -= paddedIconSize;
1965 } else {
1966 if (!flushRight) {
1967 inner.x += paddedIconSize;
1968 }
1969 inner.width -= paddedIconSize;
1970 }
1971 }
1972
1973 // If there's still room, display the alt-text
1974 if (!inner.IsEmpty()) {
1975 nsAutoString altText;
1976 nsCSSFrameConstructor::GetAlternateTextFor(*mContent->AsElement(), altText);
1977 DisplayAltText(PresContext(), aRenderingContext, altText, inner);
1978 }
1979
1980 aRenderingContext.Restore();
1981
1982 return result;
1983}
1984
1985ImgDrawResult nsImageFrame::DisplayAltFeedbackWithoutLayer(
1986 nsDisplayItem* aItem, mozilla::wr::DisplayListBuilder& aBuilder,
1987 mozilla::wr::IpcResourceUpdateQueue& aResources,
1988 const StackingContextHelper& aSc,
1989 mozilla::layers::RenderRootStateManager* aManager,
1990 nsDisplayListBuilder* aDisplayListBuilder, nsPoint aPt, uint32_t aFlags) {
1991 // Whether we draw the broken or loading icon.
1992 bool isLoading = mKind != Kind::ImageLoadingContent ||
1993 ImageOk(mContent->AsElement()->State());
1994
1995 // Calculate the content area.
1996 nsRect inner = GetContentRectRelativeToSelf() + aPt;
1997
1998 // Display a recessed one pixel border
1999 nscoord borderEdgeWidth =
2000 nsPresContext::CSSPixelsToAppUnits(ALT_BORDER_WIDTH(1));
2001
2002 // if inner area is empty, then make it big enough for at least the icon
2003 if (inner.IsEmpty()) {
2004 inner.SizeTo(2 * (nsPresContext::CSSPixelsToAppUnits(
2005 ICON_SIZE(16) + ICON_PADDING(3) + ALT_BORDER_WIDTH(1))),
2006 2 * (nsPresContext::CSSPixelsToAppUnits(
2007 ICON_SIZE(16) + ICON_PADDING(3) + ALT_BORDER_WIDTH(1))));
2008 }
2009
2010 // Make sure we have enough room to actually render the border within
2011 // our frame bounds
2012 if ((inner.width < 2 * borderEdgeWidth) ||
2013 (inner.height < 2 * borderEdgeWidth)) {
2014 return ImgDrawResult::SUCCESS;
2015 }
2016
2017 // If the TextDrawTarget requires fallback we need to rollback everything we
2018 // may have added to the display list, but we don't find that out until the
2019 // end.
2020 bool textDrawResult = true;
2021 class AutoSaveRestore {
2022 public:
2023 explicit AutoSaveRestore(mozilla::wr::DisplayListBuilder& aBuilder,
2024 bool& aTextDrawResult)
2025 : mBuilder(aBuilder), mTextDrawResult(aTextDrawResult) {
2026 mBuilder.Save();
2027 }
2028 ~AutoSaveRestore() {
2029 // If we have to use fallback for the text restore the builder and remove
2030 // anything else we added to the display list, we need to use fallback.
2031 if (mTextDrawResult) {
2032 mBuilder.ClearSave();
2033 } else {
2034 mBuilder.Restore();
2035 }
2036 }
2037
2038 private:
2039 mozilla::wr::DisplayListBuilder& mBuilder;
2040 bool& mTextDrawResult;
2041 };
2042
2043 AutoSaveRestore autoSaveRestore(aBuilder, textDrawResult);
2044
2045 // Paint the border
2046 if (!isLoading) {
2047 nsRecessedBorder recessedBorder(borderEdgeWidth);
2048 // Assert that we're not drawing a border-image here; if we were, we
2049 // couldn't ignore the ImgDrawResult that PaintBorderWithStyleBorder
2050 // returns.
2051 MOZ_ASSERT(recessedBorder.mBorderImageSource.IsNone())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(recessedBorder.mBorderImageSource.IsNone())>::isValid
, "invalid assertion condition"); if ((__builtin_expect(!!(!(
!!(recessedBorder.mBorderImageSource.IsNone()))), 0))) { do {
} while (false); MOZ_ReportAssertionFailure("recessedBorder.mBorderImageSource.IsNone()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2051); AnnotateMozCrashReason("MOZ_ASSERT" "(" "recessedBorder.mBorderImageSource.IsNone()"
")"); do { *((volatile int*)__null) = 2051; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2052
2053 nsRect rect = nsRect(aPt, GetSize());
2054 Unused << nsCSSRendering::CreateWebRenderCommandsForBorderWithStyleBorder(
2055 aItem, this, rect, aBuilder, aResources, aSc, aManager,
2056 aDisplayListBuilder, recessedBorder);
2057 }
2058
2059 // Adjust the inner rect to account for the one pixel recessed border,
2060 // and a six pixel padding on each edge
2061 inner.Deflate(
2062 nsPresContext::CSSPixelsToAppUnits(ICON_PADDING(3) + ALT_BORDER_WIDTH(1)),
2063 nsPresContext::CSSPixelsToAppUnits(ICON_PADDING(3) + ALT_BORDER_WIDTH(1)));
2064 if (inner.IsEmpty()) {
2065 return ImgDrawResult::SUCCESS;
2066 }
2067
2068 // Clip to this rect so we don't render outside the inner rect
2069 const auto bounds = LayoutDeviceRect::FromAppUnits(
2070 inner, PresContext()->AppUnitsPerDevPixel());
2071 auto wrBounds = wr::ToLayoutRect(bounds);
2072
2073 // Check if we should display image placeholders
2074 if (ShouldShowBrokenImageIcon()) {
2075 ImgDrawResult result = ImgDrawResult::NOT_READY;
2076 nscoord size = nsPresContext::CSSPixelsToAppUnits(ICON_SIZE(16));
2077 imgIRequest* request = BrokenImageIcon::GetImage(this);
2078
2079 // If we weren't previously displaying an icon, register ourselves
2080 // as an observer for load and animation updates and flag that we're
2081 // doing so now.
2082 if (request && !mDisplayingIcon) {
2083 BrokenImageIcon::AddObserver(this);
2084 mDisplayingIcon = true;
2085 }
2086
2087 WritingMode wm = GetWritingMode();
2088 const bool flushRight = wm.IsPhysicalRTL();
2089
2090 // If the icon in question is loaded, draw it.
2091 uint32_t imageStatus = 0;
2092 if (request) {
2093 request->GetImageStatus(&imageStatus);
2094 }
2095 if (imageStatus & imgIRequest::STATUS_LOAD_COMPLETE &&
2096 !(imageStatus & imgIRequest::STATUS_ERROR)) {
2097 nsCOMPtr<imgIContainer> imgCon;
2098 request->GetImage(getter_AddRefs(imgCon));
2099 MOZ_ASSERT(imgCon, "Load complete, but no image container?")do { static_assert( mozilla::detail::AssertionConditionType<
decltype(imgCon)>::isValid, "invalid assertion condition")
; if ((__builtin_expect(!!(!(!!(imgCon))), 0))) { do { } while
(false); MOZ_ReportAssertionFailure("imgCon" " (" "Load complete, but no image container?"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2099); AnnotateMozCrashReason("MOZ_ASSERT" "(" "imgCon" ") ("
"Load complete, but no image container?" ")"); do { *((volatile
int*)__null) = 2099; __attribute__((nomerge)) ::abort(); } while
(false); } } while (false)
;
2100
2101 nsRect dest(flushRight ? inner.XMost() - size : inner.x, inner.y, size,
2102 size);
2103
2104 const int32_t factor = PresContext()->AppUnitsPerDevPixel();
2105 const auto destRect = LayoutDeviceRect::FromAppUnits(dest, factor);
2106
2107 SVGImageContext svgContext;
2108 Maybe<ImageIntRegion> region;
2109 IntSize decodeSize =
2110 nsLayoutUtils::ComputeImageContainerDrawingParameters(
2111 imgCon, this, destRect, destRect, aSc, aFlags, svgContext,
2112 region);
2113 RefPtr<image::WebRenderImageProvider> provider;
2114 result = imgCon->GetImageProvider(aManager->LayerManager(), decodeSize,
2115 svgContext, region, aFlags,
2116 getter_AddRefs(provider));
2117 if (provider) {
2118 bool wrResult = aManager->CommandBuilder().PushImageProvider(
2119 aItem, provider, result, aBuilder, aResources, destRect, bounds);
2120 result &= wrResult ? ImgDrawResult::SUCCESS : ImgDrawResult::NOT_READY;
2121 } else {
2122 // We don't use &= here because we want the result to be NOT_READY so
2123 // the next block executes.
2124 result = ImgDrawResult::NOT_READY;
2125 }
2126 }
2127
2128 // If we could not draw the icon, just draw some graffiti in the mean time.
2129 if (result == ImgDrawResult::NOT_READY) {
2130 auto color = wr::ColorF{1.0f, 0.0f, 0.0f, 1.0f};
2131 bool isBackfaceVisible = !aItem->BackfaceIsHidden();
2132
2133 nscoord iconXPos = flushRight ? inner.XMost() - size : inner.x;
2134
2135 // stroked rect:
2136 nsRect rect(iconXPos, inner.y, size, size);
2137 auto devPxRect = LayoutDeviceRect::FromAppUnits(
2138 rect, PresContext()->AppUnitsPerDevPixel());
2139 auto dest = wr::ToLayoutRect(devPxRect);
2140
2141 auto borderWidths = wr::ToBorderWidths(1.0, 1.0, 1.0, 1.0);
2142 wr::BorderSide side = {color, wr::BorderStyle::Solid};
2143 wr::BorderSide sides[4] = {side, side, side, side};
2144 Range<const wr::BorderSide> sidesRange(sides, 4);
2145 aBuilder.PushBorder(dest, wrBounds, isBackfaceVisible, borderWidths,
2146 sidesRange, wr::EmptyBorderRadius());
2147
2148 // filled circle in bottom right quadrant of stroked rect:
2149 nscoord twoPX = nsPresContext::CSSPixelsToAppUnits(2);
2150 rect = nsRect(iconXPos + size / 2, inner.y + size / 2, size / 2 - twoPX,
2151 size / 2 - twoPX);
2152 devPxRect = LayoutDeviceRect::FromAppUnits(
2153 rect, PresContext()->AppUnitsPerDevPixel());
2154 dest = wr::ToLayoutRect(devPxRect);
2155
2156 aBuilder.PushRoundedRect(dest, wrBounds, isBackfaceVisible, color);
2157 }
2158
2159 // Reduce the inner rect by the width of the icon, and leave an
2160 // additional ICON_PADDING pixels for padding
2161 int32_t paddedIconSize =
2162 nsPresContext::CSSPixelsToAppUnits(ICON_SIZE(16) + ICON_PADDING(3));
2163 if (wm.IsVertical()) {
2164 inner.y += paddedIconSize;
2165 inner.height -= paddedIconSize;
2166 } else {
2167 if (!flushRight) {
2168 inner.x += paddedIconSize;
2169 }
2170 inner.width -= paddedIconSize;
2171 }
2172 }
2173
2174 // Draw text
2175 if (!inner.IsEmpty()) {
2176 RefPtr<TextDrawTarget> textDrawer =
2177 new TextDrawTarget(aBuilder, aResources, aSc, aManager, aItem, inner,
2178 /* aCallerDoesSaveRestore = */ true);
2179 MOZ_ASSERT(textDrawer->IsValid())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(textDrawer->IsValid())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(textDrawer->IsValid()))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("textDrawer->IsValid()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2179); AnnotateMozCrashReason("MOZ_ASSERT" "(" "textDrawer->IsValid()"
")"); do { *((volatile int*)__null) = 2179; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2180 if (textDrawer->IsValid()) {
2181 gfxContext captureCtx(textDrawer);
2182
2183 nsAutoString altText;
2184 nsCSSFrameConstructor::GetAlternateTextFor(*mContent->AsElement(),
2185 altText);
2186 DisplayAltText(PresContext(), captureCtx, altText, inner);
2187
2188 textDrawer->TerminateShadows();
2189 textDrawResult = !textDrawer->CheckHasUnsupportedFeatures();
2190 }
2191 }
2192
2193 // Purposely ignore local DrawResult because we handled it not being success
2194 // already.
2195 return textDrawResult ? ImgDrawResult::SUCCESS : ImgDrawResult::NOT_READY;
2196}
2197
2198// We want to sync-decode in this case, as otherwise we either need to flash
2199// white while waiting to decode the new image, or paint the old image with a
2200// different aspect-ratio, which would be bad as it'd be stretched.
2201//
2202// See bug 1589955.
2203static bool OldImageHasDifferentRatio(const nsImageFrame& aFrame,
2204 imgIContainer& aImage,
2205 imgIContainer* aPrevImage) {
2206 if (!aPrevImage || aPrevImage == &aImage) {
2207 return false;
2208 }
2209
2210 // If we don't depend on our intrinsic image size / ratio, we're good.
2211 //
2212 // FIXME(emilio): There's the case of the old image being painted
2213 // intrinsically, and src and styles changing at the same time... Maybe we
2214 // should keep track of the old GetPaintRect()'s ratio and the image's ratio,
2215 // instead of checking this bit?
2216 if (aFrame.HasAnyStateBits(IMAGE_SIZECONSTRAINED)) {
2217 return false;
2218 }
2219
2220 auto currentRatio = aFrame.GetIntrinsicRatio();
2221 auto oldRatio = aFrame.ComputeIntrinsicRatioForImage(aPrevImage);
2222 return oldRatio != currentRatio;
2223}
2224
2225#ifdef DEBUG1
2226void nsImageFrame::AssertSyncDecodingHintIsInSync() const {
2227 if (!IsForImageLoadingContent()) {
2228 return;
2229 }
2230 nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mContent);
2231 MOZ_ASSERT(imageLoader)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(imageLoader)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(imageLoader))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("imageLoader", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2231); AnnotateMozCrashReason("MOZ_ASSERT" "(" "imageLoader"
")"); do { *((volatile int*)__null) = 2231; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2232
2233 // The opposite is not true, we might have some other heuristics which force
2234 // sync-decoding of images.
2235 MOZ_ASSERT_IF(imageLoader->GetSyncDecodingHint(), mForceSyncDecoding)do { if (imageLoader->GetSyncDecodingHint()) { do { static_assert
( mozilla::detail::AssertionConditionType<decltype(mForceSyncDecoding
)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(mForceSyncDecoding))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("mForceSyncDecoding", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2235); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mForceSyncDecoding"
")"); do { *((volatile int*)__null) = 2235; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
2236}
2237#endif
2238
2239void nsDisplayImage::Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) {
2240 auto* frame = Frame();
2241 frame->AssertSyncDecodingHintIsInSync();
2242
2243 auto* image = frame->mImage.get();
2244 auto* prevImage = frame->mPrevImage.get();
2245 if (!image) {
2246 return;
2247 }
2248
2249 const bool oldImageIsDifferent =
2250 OldImageHasDifferentRatio(*frame, *image, prevImage);
2251
2252 uint32_t flags = aBuilder->GetImageDecodeFlags();
2253 if (aBuilder->ShouldSyncDecodeImages() || oldImageIsDifferent ||
2254 frame->mForceSyncDecoding) {
2255 flags |= imgIContainer::FLAG_SYNC_DECODE;
2256 }
2257
2258 ImgDrawResult result = frame->PaintImage(
2259 *aCtx, ToReferenceFrame(), GetPaintRect(aBuilder, aCtx), image, flags);
2260
2261 if (result == ImgDrawResult::NOT_READY ||
2262 result == ImgDrawResult::INCOMPLETE ||
2263 result == ImgDrawResult::TEMPORARY_ERROR) {
2264 // If the current image failed to paint because it's still loading or
2265 // decoding, try painting the previous image.
2266 if (prevImage) {
2267 result =
2268 frame->PaintImage(*aCtx, ToReferenceFrame(),
2269 GetPaintRect(aBuilder, aCtx), prevImage, flags);
2270 }
2271 }
2272}
2273
2274nsRect nsDisplayImage::GetDestRect() const {
2275 bool snap = true;
2276 const nsRect frameContentBox = GetBounds(&snap);
2277 nsImageFrame* imageFrame = static_cast<nsImageFrame*>(mFrame);
2278 return imageFrame->GetDestRect(frameContentBox);
2279}
2280
2281nsRegion nsDisplayImage::GetOpaqueRegion(nsDisplayListBuilder* aBuilder,
2282 bool* aSnap) const {
2283 *aSnap = false;
2284 auto* image = Frame()->mImage.get();
2285 if (image && image->WillDrawOpaqueNow()) {
2286 const nsRect frameContentBox = GetBounds(aSnap);
2287 return GetDestRect().Intersect(frameContentBox);
2288 }
2289 return nsRegion();
2290}
2291
2292bool nsDisplayImage::CreateWebRenderCommands(
2293 mozilla::wr::DisplayListBuilder& aBuilder,
2294 mozilla::wr::IpcResourceUpdateQueue& aResources,
2295 const StackingContextHelper& aSc, RenderRootStateManager* aManager,
2296 nsDisplayListBuilder* aDisplayListBuilder) {
2297 MOZ_ASSERT(mFrame->IsImageFrame() || mFrame->IsImageControlFrame())do { static_assert( mozilla::detail::AssertionConditionType<
decltype(mFrame->IsImageFrame() || mFrame->IsImageControlFrame
())>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(mFrame->IsImageFrame() || mFrame->IsImageControlFrame
()))), 0))) { do { } while (false); MOZ_ReportAssertionFailure
("mFrame->IsImageFrame() || mFrame->IsImageControlFrame()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2297); AnnotateMozCrashReason("MOZ_ASSERT" "(" "mFrame->IsImageFrame() || mFrame->IsImageControlFrame()"
")"); do { *((volatile int*)__null) = 2297; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2298 auto* frame = Frame();
2299 auto* image = frame->mImage.get();
2300 if (!image) {
2301 // TODO: View transitions.
2302 return true;
2303 }
2304
2305 if (frame->HasImageMap()) {
2306 // Image layer doesn't support draw focus ring for image map.
2307 return false;
2308 }
2309
2310 auto* prevImage = frame->mPrevImage.get();
2311
2312 frame->AssertSyncDecodingHintIsInSync();
2313 const bool oldImageIsDifferent =
2314 OldImageHasDifferentRatio(*frame, *image, prevImage);
2315
2316 uint32_t flags = aDisplayListBuilder->GetImageDecodeFlags();
2317 if (aDisplayListBuilder->ShouldSyncDecodeImages() || oldImageIsDifferent ||
2318 frame->mForceSyncDecoding) {
2319 flags |= imgIContainer::FLAG_SYNC_DECODE;
2320 }
2321 if (StaticPrefs::image_svg_blob_image() &&
2322 image->GetType() == imgIContainer::TYPE_VECTOR) {
2323 flags |= imgIContainer::FLAG_RECORD_BLOB;
2324 }
2325
2326 const nsRect destAppUnits = GetDestRect();
2327 const int32_t factor = mFrame->PresContext()->AppUnitsPerDevPixel();
2328 const auto destRect = LayoutDeviceRect::FromAppUnits(destAppUnits, factor);
2329
2330 SVGImageContext svgContext;
2331 Maybe<ImageIntRegion> region;
2332 IntSize decodeSize = nsLayoutUtils::ComputeImageContainerDrawingParameters(
2333 image, mFrame, destRect, destRect, aSc, flags, svgContext, region);
2334
2335 RefPtr<image::WebRenderImageProvider> provider;
2336 ImgDrawResult drawResult =
2337 image->GetImageProvider(aManager->LayerManager(), decodeSize, svgContext,
2338 region, flags, getter_AddRefs(provider));
2339
2340 if (nsCOMPtr<imgIRequest> currentRequest = frame->GetCurrentRequest()) {
2341 LCPHelpers::FinalizeLCPEntryForImage(
2342 frame->GetContent()->AsElement(),
2343 static_cast<imgRequestProxy*>(currentRequest.get()),
2344 destAppUnits - ToReferenceFrame());
2345 }
2346
2347 // While we got a container, it may not contain a fully decoded surface. If
2348 // that is the case, and we have an image we were previously displaying which
2349 // has a fully decoded surface, then we should prefer the previous image.
2350 bool updatePrevImage = false;
2351 switch (drawResult) {
2352 case ImgDrawResult::NOT_READY:
2353 case ImgDrawResult::INCOMPLETE:
2354 case ImgDrawResult::TEMPORARY_ERROR:
2355 if (prevImage && prevImage != image) {
2356 // The current image and the previous image might be switching between
2357 // rasterized surfaces and blob recordings, so we need to update the
2358 // flags appropriately.
2359 uint32_t prevFlags = flags;
2360 if (StaticPrefs::image_svg_blob_image() &&
2361 prevImage->GetType() == imgIContainer::TYPE_VECTOR) {
2362 prevFlags |= imgIContainer::FLAG_RECORD_BLOB;
2363 } else {
2364 prevFlags &= ~imgIContainer::FLAG_RECORD_BLOB;
2365 }
2366
2367 RefPtr<image::WebRenderImageProvider> prevProvider;
2368 ImgDrawResult prevDrawResult = prevImage->GetImageProvider(
2369 aManager->LayerManager(), decodeSize, svgContext, region, prevFlags,
2370 getter_AddRefs(prevProvider));
2371 if (prevProvider && (prevDrawResult == ImgDrawResult::SUCCESS ||
2372 prevDrawResult == ImgDrawResult::WRONG_SIZE)) {
2373 // We use WRONG_SIZE here to ensure that when the frame next tries to
2374 // invalidate due to a frame update from the current image, we don't
2375 // consider the result from the previous image to be a valid result to
2376 // avoid redrawing.
2377 drawResult = ImgDrawResult::WRONG_SIZE;
2378 provider = std::move(prevProvider);
2379 flags = prevFlags;
2380 break;
2381 }
2382
2383 // Previous image was unusable; we can forget about it.
2384 updatePrevImage = true;
2385 }
2386 break;
2387 case ImgDrawResult::NOT_SUPPORTED:
2388 return false;
2389 default:
2390 updatePrevImage = prevImage != image;
2391 break;
2392 }
2393
2394 // The previous image was not used, and is different from the current image.
2395 // We should forget about it. We need to update the frame as well because the
2396 // display item may get recreated.
2397 if (updatePrevImage) {
2398 frame->mPrevImage = frame->mImage;
2399 }
2400
2401 // If the image provider is null, we don't want to fallback. Any other
2402 // failure will be due to resource constraints and fallback is unlikely to
2403 // help us. Hence we can ignore the return value from PushImage.
2404 aManager->CommandBuilder().PushImageProvider(
2405 this, provider, drawResult, aBuilder, aResources, destRect, destRect);
2406 return true;
2407}
2408
2409ImgDrawResult nsImageFrame::PaintImage(gfxContext& aRenderingContext,
2410 nsPoint aPt, const nsRect& aDirtyRect,
2411 imgIContainer* aImage, uint32_t aFlags) {
2412 DrawTarget* drawTarget = aRenderingContext.GetDrawTarget();
2413
2414 // Render the image into our content area (the area inside
2415 // the borders and padding)
2416 NS_ASSERTION(GetContentRectRelativeToSelf().width == mComputedSize.width,do { if (!(GetContentRectRelativeToSelf().width == mComputedSize
.width)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "bad width", "GetContentRectRelativeToSelf().width == mComputedSize.width"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2417); MOZ_PretendNoReturn(); } } while (0)
2417 "bad width")do { if (!(GetContentRectRelativeToSelf().width == mComputedSize
.width)) { NS_DebugBreak(NS_DEBUG_ASSERTION, "bad width", "GetContentRectRelativeToSelf().width == mComputedSize.width"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2417); MOZ_PretendNoReturn(); } } while (0)
;
2418
2419 nsPoint anchorPoint;
2420 nsRect dest = GetDestRect(GetContentRectRelativeToSelf() + aPt, &anchorPoint);
2421
2422 SVGImageContext svgContext;
2423 SVGImageContext::MaybeStoreContextPaint(svgContext, this, aImage);
2424
2425 ImgDrawResult result = nsLayoutUtils::DrawSingleImage(
2426 aRenderingContext, PresContext(), aImage,
2427 nsLayoutUtils::GetSamplingFilterForFrame(this), dest, aDirtyRect,
2428 svgContext, aFlags, &anchorPoint);
2429
2430 if (nsImageMap* map = GetImageMap()) {
2431 gfxPoint devPixelOffset = nsLayoutUtils::PointToGfxPoint(
2432 dest.TopLeft(), PresContext()->AppUnitsPerDevPixel());
2433 AutoRestoreTransform autoRestoreTransform(drawTarget);
2434 drawTarget->SetTransform(
2435 drawTarget->GetTransform().PreTranslate(ToPoint(devPixelOffset)));
2436
2437 // solid white stroke:
2438 ColorPattern white(ToDeviceColor(sRGBColor::OpaqueWhite()));
2439 map->Draw(this, *drawTarget, white);
2440
2441 // then dashed black stroke over the top:
2442 ColorPattern black(ToDeviceColor(sRGBColor::OpaqueBlack()));
2443 StrokeOptions strokeOptions;
2444 nsLayoutUtils::InitDashPattern(strokeOptions, StyleBorderStyle::Dotted);
2445 map->Draw(this, *drawTarget, black, strokeOptions);
2446 }
2447
2448 if (result == ImgDrawResult::SUCCESS) {
2449 mPrevImage = aImage;
2450 } else if (result == ImgDrawResult::BAD_IMAGE) {
2451 mPrevImage = nullptr;
2452 }
2453
2454 return result;
2455}
2456
2457already_AddRefed<imgIRequest> nsImageFrame::GetCurrentRequest() const {
2458 if (mKind != Kind::ImageLoadingContent) {
2459 return do_AddRef(mOwnedRequest);
2460 }
2461
2462 MOZ_ASSERT(!mOwnedRequest)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(!mOwnedRequest)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(!mOwnedRequest))), 0))) { do
{ } while (false); MOZ_ReportAssertionFailure("!mOwnedRequest"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2462); AnnotateMozCrashReason("MOZ_ASSERT" "(" "!mOwnedRequest"
")"); do { *((volatile int*)__null) = 2462; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2463
2464 nsCOMPtr<imgIRequest> request;
2465 nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mContent);
2466 MOZ_ASSERT(imageLoader)do { static_assert( mozilla::detail::AssertionConditionType<
decltype(imageLoader)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(imageLoader))), 0))) { do { }
while (false); MOZ_ReportAssertionFailure("imageLoader", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2466); AnnotateMozCrashReason("MOZ_ASSERT" "(" "imageLoader"
")"); do { *((volatile int*)__null) = 2466; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false)
;
2467 imageLoader->GetRequest(nsIImageLoadingContent::CURRENT_REQUEST,
2468 getter_AddRefs(request));
2469 return request.forget();
2470}
2471
2472void nsImageFrame::BuildDisplayList(nsDisplayListBuilder* aBuilder,
2473 const nsDisplayListSet& aLists) {
2474 if (!IsVisibleForPainting()) {
2475 return;
2476 }
2477
2478 DisplayBorderBackgroundOutline(aBuilder, aLists);
2479
2480 if (HidesContent()) {
2481 DisplaySelectionOverlay(aBuilder, aLists.Content(),
2482 nsISelectionDisplay::DISPLAY_IMAGES);
2483 return;
2484 }
2485
2486 uint32_t clipFlags =
2487 nsStyleUtil::ObjectPropsMightCauseOverflow(StylePosition())
2488 ? 0
2489 : DisplayListClipState::ASSUME_DRAWING_RESTRICTED_TO_CONTENT_RECT;
2490
2491 DisplayListClipState::AutoClipContainingBlockDescendantsToContentBox clip(
2492 aBuilder, this, clipFlags);
2493
2494 if (!mComputedSize.IsEmpty()) {
2495 const bool imageOK = mKind != Kind::ImageLoadingContent ||
2496 ImageOk(mContent->AsElement()->State());
2497
2498 nsCOMPtr<imgIRequest> currentRequest = GetCurrentRequest();
2499
2500 const bool isImageFromStyle =
2501 mKind != Kind::ImageLoadingContent && mKind != Kind::XULImage;
2502 const bool drawAltFeedback = [&] {
2503 if (!imageOK) {
2504 return true;
2505 }
2506 // If we're a gradient, we don't need to draw alt feedback.
2507 if (isImageFromStyle && !GetImageFromStyle()->IsImageRequestType()) {
2508 return false;
2509 }
2510 // XXX(seth): The SizeIsAvailable check here should not be necessary - the
2511 // intention is that a non-null mImage means we have a size, but there is
2512 // currently some code that violates this invariant.
2513 return !mImage || !SizeIsAvailable(currentRequest);
2514 }();
2515
2516 if (drawAltFeedback) {
2517 // No image yet, or image load failed. Draw the alt-text and an icon
2518 // indicating the status
2519 aLists.Content()->AppendNewToTop<nsDisplayAltFeedback>(aBuilder, this);
2520
2521 // This image is visible (we are being asked to paint it) but it's not
2522 // decoded yet. And we are not going to ask the image to draw, so this
2523 // may be the only chance to tell it that it should decode.
2524 if (currentRequest) {
2525 uint32_t status = 0;
2526 currentRequest->GetImageStatus(&status);
2527 if (!(status & imgIRequest::STATUS_DECODE_COMPLETE)) {
2528 MaybeDecodeForPredictedSize();
2529 }
2530 // Increase loading priority if the image is ready to be displayed.
2531 if (!(status & imgIRequest::STATUS_LOAD_COMPLETE)) {
2532 currentRequest->BoostPriority(imgIRequest::CATEGORY_DISPLAY);
2533 }
2534 }
2535 } else {
2536 if (mImage) {
2537 aLists.Content()->AppendNewToTop<nsDisplayImage>(aBuilder, this);
2538 } else if (isImageFromStyle) {
2539 aLists.Content()->AppendNewToTop<nsDisplayGradient>(aBuilder, this);
2540 }
2541
2542 // If we were previously displaying an icon, we're not anymore
2543 if (mDisplayingIcon) {
2544 BrokenImageIcon::RemoveObserver(this);
2545 mDisplayingIcon = false;
2546 }
2547 }
2548 }
2549
2550 if (ShouldDisplaySelection()) {
2551 DisplaySelectionOverlay(aBuilder, aLists.Content(),
2552 nsISelectionDisplay::DISPLAY_IMAGES);
2553 }
2554
2555 BuildDisplayListForNonBlockChildren(aBuilder, aLists);
2556}
2557
2558bool nsImageFrame::ShouldDisplaySelection() {
2559 int16_t displaySelection = PresShell()->GetSelectionFlags();
2560 if (!(displaySelection & nsISelectionDisplay::DISPLAY_IMAGES)) {
2561 // no need to check the blue border, we cannot be drawn selected.
2562 return false;
2563 }
2564
2565 if (displaySelection != nsISelectionDisplay::DISPLAY_ALL) {
2566 return true;
2567 }
2568
2569 // If the image is currently resize target of the editor, don't draw the
2570 // selection overlay.
2571 HTMLEditor* htmlEditor = nsContentUtils::GetHTMLEditor(PresContext());
2572 if (!htmlEditor) {
2573 return true;
2574 }
2575
2576 return htmlEditor->GetResizerTarget() != mContent;
2577}
2578
2579nsImageMap* nsImageFrame::GetImageMap() {
2580 if (!mImageMap) {
2581 if (nsIContent* map = GetMapElement()) {
2582 mImageMap = new nsImageMap();
2583 mImageMap->Init(this, map);
2584 }
2585 }
2586
2587 return mImageMap;
2588}
2589
2590bool nsImageFrame::IsServerImageMap() {
2591 return mContent->AsElement()->HasAttr(nsGkAtoms::ismap);
2592}
2593
2594CSSIntPoint nsImageFrame::TranslateEventCoords(const nsPoint& aPoint) {
2595 const nsRect contentRect = GetContentRectRelativeToSelf();
2596 // Subtract out border and padding here so that the coordinates are
2597 // now relative to the content area of this frame.
2598 return CSSPixel::FromAppUnitsRounded(aPoint - contentRect.TopLeft());
2599}
2600
2601bool nsImageFrame::GetAnchorHREFTargetAndNode(nsIURI** aHref, nsString& aTarget,
2602 nsIContent** aNode) {
2603 aTarget.Truncate();
2604 *aHref = nullptr;
2605 *aNode = nullptr;
2606
2607 // Walk up the content tree, looking for an nsIDOMAnchorElement
2608 for (nsIContent* content = mContent->GetParent(); content;
2609 content = content->GetParent()) {
2610 nsCOMPtr<dom::Link> link = do_QueryInterface(content);
2611 if (!link) {
2612 continue;
2613 }
2614 if (nsCOMPtr<nsIURI> href = link->GetURI()) {
2615 href.forget(aHref);
2616 }
2617
2618 if (auto* anchor = HTMLAnchorElement::FromNode(content)) {
2619 anchor->GetLinkTarget(aTarget);
2620 }
2621 NS_ADDREF(*aNode = content)(*aNode = content)->AddRef();
2622 return *aHref != nullptr;
2623 }
2624 return false;
2625}
2626
2627bool nsImageFrame::IsLeafDynamic() const {
2628 if (mKind != Kind::ImageLoadingContent) {
2629 // Image frames created for "content: url()" could have an author-controlled
2630 // shadow root, we want to be a regular leaf for those.
2631 return true;
2632 }
2633 // For elements that create image frames, calling attachShadow() will throw,
2634 // so the only ShadowRoot we could ever have is a UA widget.
2635 const auto* shadow = mContent->AsElement()->GetShadowRoot();
2636 MOZ_ASSERT_IF(shadow, shadow->IsUAWidget())do { if (shadow) { do { static_assert( mozilla::detail::AssertionConditionType
<decltype(shadow->IsUAWidget())>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(shadow->IsUAWidget()))), 0
))) { do { } while (false); MOZ_ReportAssertionFailure("shadow->IsUAWidget()"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2636); AnnotateMozCrashReason("MOZ_ASSERT" "(" "shadow->IsUAWidget()"
")"); do { *((volatile int*)__null) = 2636; __attribute__((nomerge
)) ::abort(); } while (false); } } while (false); } } while (
false)
;
2637 return !shadow;
2638}
2639
2640nsresult nsImageFrame::GetContentForEvent(const WidgetEvent* aEvent,
2641 nsIContent** aContent) {
2642 NS_ENSURE_ARG_POINTER(aContent)do { if ((__builtin_expect(!!(!(aContent)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aContent" ") failed", nullptr
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2642); return NS_ERROR_INVALID_POINTER; } } while (false)
;
2643
2644 nsIFrame* f = nsLayoutUtils::GetNonGeneratedAncestor(this);
2645 if (f != this) {
2646 return f->GetContentForEvent(aEvent, aContent);
2647 }
2648
2649 // XXX We need to make this special check for area element's capturing the
2650 // mouse due to bug 135040. Remove it once that's fixed.
2651 nsIContent* capturingContent = aEvent->HasMouseEventMessage()
2652 ? PresShell::GetCapturingContent()
2653 : nullptr;
2654 if (capturingContent && capturingContent->GetPrimaryFrame() == this) {
2655 *aContent = capturingContent;
2656 NS_IF_ADDREF(*aContent)ns_if_addref(*aContent);
2657 return NS_OK;
2658 }
2659
2660 if (nsImageMap* map = GetImageMap()) {
2661 const CSSIntPoint p = TranslateEventCoords(
2662 nsLayoutUtils::GetEventCoordinatesRelativeTo(aEvent, RelativeTo{this}));
2663 nsCOMPtr<nsIContent> area = map->GetArea(p);
2664 if (area) {
2665 area.forget(aContent);
2666 return NS_OK;
2667 }
2668 }
2669
2670 *aContent = GetContent();
2671 NS_IF_ADDREF(*aContent)ns_if_addref(*aContent);
2672 return NS_OK;
2673}
2674
2675// XXX what should clicks on transparent pixels do?
2676nsresult nsImageFrame::HandleEvent(nsPresContext* aPresContext,
2677 WidgetGUIEvent* aEvent,
2678 nsEventStatus* aEventStatus) {
2679 NS_ENSURE_ARG_POINTER(aEventStatus)do { if ((__builtin_expect(!!(!(aEventStatus)), 0))) { NS_DebugBreak
(NS_DEBUG_WARNING, "NS_ENSURE_TRUE(" "aEventStatus" ") failed"
, nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2679); return NS_ERROR_INVALID_POINTER; } } while (false)
;
2680
2681 if ((aEvent->mMessage == ePointerClick &&
2682 aEvent->AsMouseEvent()->mButton == MouseButton::ePrimary) ||
2683 aEvent->mMessage == eMouseMove) {
2684 nsImageMap* map = GetImageMap();
2685 bool isServerMap = IsServerImageMap();
2686 if (map || isServerMap) {
2687 CSSIntPoint p =
2688 TranslateEventCoords(nsLayoutUtils::GetEventCoordinatesRelativeTo(
2689 aEvent, RelativeTo{this}));
2690
2691 // Even though client-side image map triggering happens
2692 // through content, we need to make sure we're not inside
2693 // (in case we deal with a case of both client-side and
2694 // sever-side on the same image - it happens!)
2695 const bool inside = map && map->GetArea(p);
2696
2697 if (!inside && isServerMap) {
2698 // Server side image maps use the href in a containing anchor
2699 // element to provide the basis for the destination url.
2700 nsCOMPtr<nsIURI> uri;
2701 nsAutoString target;
2702 nsCOMPtr<nsIContent> anchorNode;
2703 if (GetAnchorHREFTargetAndNode(getter_AddRefs(uri), target,
2704 getter_AddRefs(anchorNode))) {
2705 // XXX if the mouse is over/clicked in the border/padding area
2706 // we should probably just pretend nothing happened. Nav4
2707 // keeps the x,y coordinates positive as we do; IE doesn't
2708 // bother. Both of them send the click through even when the
2709 // mouse is over the border.
2710 if (p.x < 0) {
2711 p.x = 0;
2712 }
2713 if (p.y < 0) {
2714 p.y = 0;
2715 }
2716
2717 nsAutoCString spec;
2718 nsresult rv = uri->GetSpec(spec);
2719 NS_ENSURE_SUCCESS(rv, rv)do { nsresult __rv = rv; if (((bool)(__builtin_expect(!!(NS_FAILED_impl
(__rv)), 0)))) { const char* name = mozilla::GetStaticErrorName
(__rv); mozilla::SmprintfPointer msg = mozilla::Smprintf( "NS_ENSURE_SUCCESS(%s, %s) failed with "
"result 0x%" "X" "%s%s%s", "rv", "rv", static_cast<uint32_t
>(__rv), name ? " (" : "", name ? name : "", name ? ")" : ""
); NS_DebugBreak(NS_DEBUG_WARNING, msg.get(), nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2719); return rv; } } while (false)
;
2720
2721 spec += nsPrintfCString("?%d,%d", p.x.value, p.y.value);
2722 rv = NS_MutateURI(uri).SetSpec(spec).Finalize(uri);
2723 NS_ENSURE_SUCCESS(rv, rv)do { nsresult __rv = rv; if (((bool)(__builtin_expect(!!(NS_FAILED_impl
(__rv)), 0)))) { const char* name = mozilla::GetStaticErrorName
(__rv); mozilla::SmprintfPointer msg = mozilla::Smprintf( "NS_ENSURE_SUCCESS(%s, %s) failed with "
"result 0x%" "X" "%s%s%s", "rv", "rv", static_cast<uint32_t
>(__rv), name ? " (" : "", name ? name : "", name ? ")" : ""
); NS_DebugBreak(NS_DEBUG_WARNING, msg.get(), nullptr, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2723); return rv; } } while (false)
;
2724
2725 bool clicked = false;
2726 if (aEvent->mMessage == ePointerClick &&
2727 !aEvent->DefaultPrevented()) {
2728 *aEventStatus = nsEventStatus_eConsumeDoDefault;
2729 clicked = true;
2730 }
2731 nsContentUtils::TriggerLink(anchorNode, uri, target, clicked);
2732 }
2733 }
2734 }
2735 }
2736
2737 return nsAtomicContainerFrame::HandleEvent(aPresContext, aEvent,
2738 aEventStatus);
2739}
2740
2741nsIFrame::Cursor nsImageFrame::GetCursor(const nsPoint& aPoint) {
2742 nsImageMap* map = GetImageMap();
2743 if (!map) {
2744 return nsIFrame::GetCursor(aPoint);
2745 }
2746 const CSSIntPoint p = TranslateEventCoords(aPoint);
2747 HTMLAreaElement* area = map->GetArea(p);
2748 if (!area) {
2749 return nsIFrame::GetCursor(aPoint);
2750 }
2751
2752 // Use the cursor from the style of the *area* element.
2753 RefPtr<ComputedStyle> areaStyle =
2754 PresShell()->StyleSet()->ResolveStyleLazily(*area);
2755
2756 // This is one of the cases, like the <xul:tree> pseudo-style stuff, where we
2757 // get styles out of the blue and expect to trigger image loads for those.
2758 areaStyle->StartImageLoads(*PresContext()->Document());
2759
2760 StyleCursorKind kind = areaStyle->StyleUI()->Cursor().keyword;
2761 if (kind == StyleCursorKind::Auto) {
2762 kind = StyleCursorKind::Default;
2763 }
2764 return Cursor{kind, AllowCustomCursorImage::Yes, std::move(areaStyle)};
2765}
2766
2767nsresult nsImageFrame::AttributeChanged(int32_t aNameSpaceID,
2768 nsAtom* aAttribute, int32_t aModType) {
2769 nsresult rv = nsAtomicContainerFrame::AttributeChanged(aNameSpaceID,
2770 aAttribute, aModType);
2771 if (NS_FAILED(rv)((bool)(__builtin_expect(!!(NS_FAILED_impl(rv)), 0)))) {
2772 return rv;
2773 }
2774 if (nsGkAtoms::alt == aAttribute) {
2775 PresShell()->FrameNeedsReflow(
2776 this, IntrinsicDirty::FrameAncestorsAndDescendants, NS_FRAME_IS_DIRTY);
2777 }
2778 if (mKind == Kind::XULImage && aAttribute == nsGkAtoms::src &&
2779 aNameSpaceID == kNameSpaceID_None) {
2780 UpdateXULImage();
2781 }
2782 return NS_OK;
2783}
2784
2785void nsImageFrame::OnVisibilityChange(
2786 Visibility aNewVisibility, const Maybe<OnNonvisible>& aNonvisibleAction) {
2787 if (mKind == Kind::ImageLoadingContent) {
2788 nsCOMPtr<nsIImageLoadingContent> imageLoader = do_QueryInterface(mContent);
2789 imageLoader->OnVisibilityChange(aNewVisibility, aNonvisibleAction);
2790 }
2791
2792 if (aNewVisibility == Visibility::ApproximatelyVisible &&
2793 PresShell()->IsActive()) {
2794 MaybeDecodeForPredictedSize();
2795 }
2796
2797 nsAtomicContainerFrame::OnVisibilityChange(aNewVisibility, aNonvisibleAction);
2798}
2799
2800#ifdef DEBUG_FRAME_DUMP1
2801nsresult nsImageFrame::GetFrameName(nsAString& aResult) const {
2802 return MakeFrameName(u"ImageFrame"_ns, aResult);
2803}
2804
2805void nsImageFrame::List(FILE* out, const char* aPrefix,
2806 ListFlags aFlags) const {
2807 nsCString str;
2808 ListGeneric(str, aPrefix, aFlags);
2809
2810 // output the img src url
2811 if (nsCOMPtr<imgIRequest> currentRequest = GetCurrentRequest()) {
2812 nsCOMPtr<nsIURI> uri = currentRequest->GetURI();
2813 nsAutoCString uristr;
2814 uri->GetAsciiSpec(uristr);
2815 str += nsPrintfCString(" [src=%s]", uristr.get());
2816 }
2817 fprintf_stderr(out, "%s\n", str.get());
2818}
2819#endif
2820
2821LogicalSides nsImageFrame::GetLogicalSkipSides() const {
2822 LogicalSides skip(mWritingMode);
2823 if (MOZ_UNLIKELY(StyleBorder()->mBoxDecorationBreak ==(__builtin_expect(!!(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Clone), 0))
2824 StyleBoxDecorationBreak::Clone)(__builtin_expect(!!(StyleBorder()->mBoxDecorationBreak ==
StyleBoxDecorationBreak::Clone), 0))
) {
2825 return skip;
2826 }
2827 if (GetPrevInFlow()) {
2828 skip += LogicalSide::BStart;
2829 }
2830 if (GetNextInFlow()) {
2831 skip += LogicalSide::BEnd;
2832 }
2833 return skip;
2834}
2835NS_IMPL_ISUPPORTS(nsImageListener, imgINotificationObserver)MozExternalRefCountType nsImageListener::AddRef(void) { static_assert
(!std::is_destructible_v<nsImageListener>, "Reference-counted class "
"nsImageListener" " should not have a public destructor. " "Make this class's destructor non-public"
); do { static_assert( mozilla::detail::AssertionConditionType
<decltype(int32_t(mRefCnt) >= 0)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!(int32_t(mRefCnt) >= 0))),
0))) { do { } while (false); MOZ_ReportAssertionFailure("int32_t(mRefCnt) >= 0"
" (" "illegal refcnt" ")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2835); AnnotateMozCrashReason("MOZ_ASSERT" "(" "int32_t(mRefCnt) >= 0"
") (" "illegal refcnt" ")"); do { *((volatile int*)__null) =
2835; __attribute__((nomerge)) ::abort(); } while (false); }
} while (false); do { static_assert( mozilla::detail::AssertionConditionType
<decltype("nsImageListener" != nullptr)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!("nsImageListener" != nullptr
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"\"nsImageListener\" != nullptr" " (" "Must specify a name" ")"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2835); AnnotateMozCrashReason("MOZ_ASSERT" "(" "\"nsImageListener\" != nullptr"
") (" "Must specify a name" ")"); do { *((volatile int*)__null
) = 2835; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false); if (!mRefCnt.isThreadSafe) _mOwningThread
.AssertOwnership("nsImageListener" " not thread-safe"); nsrefcnt
count = ++mRefCnt; NS_LogAddRef((this), (count), ("nsImageListener"
), (uint32_t)(sizeof(*this))); return count; } MozExternalRefCountType
nsImageListener::Release(void) { do { static_assert( mozilla
::detail::AssertionConditionType<decltype(int32_t(mRefCnt)
> 0)>::isValid, "invalid assertion condition"); if ((__builtin_expect
(!!(!(!!(int32_t(mRefCnt) > 0))), 0))) { do { } while (false
); MOZ_ReportAssertionFailure("int32_t(mRefCnt) > 0" " (" "dup release"
")", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2835); AnnotateMozCrashReason("MOZ_ASSERT" "(" "int32_t(mRefCnt) > 0"
") (" "dup release" ")"); do { *((volatile int*)__null) = 2835
; __attribute__((nomerge)) ::abort(); } while (false); } } while
(false); do { static_assert( mozilla::detail::AssertionConditionType
<decltype("nsImageListener" != nullptr)>::isValid, "invalid assertion condition"
); if ((__builtin_expect(!!(!(!!("nsImageListener" != nullptr
))), 0))) { do { } while (false); MOZ_ReportAssertionFailure(
"\"nsImageListener\" != nullptr" " (" "Must specify a name" ")"
, "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2835); AnnotateMozCrashReason("MOZ_ASSERT" "(" "\"nsImageListener\" != nullptr"
") (" "Must specify a name" ")"); do { *((volatile int*)__null
) = 2835; __attribute__((nomerge)) ::abort(); } while (false)
; } } while (false); if (!mRefCnt.isThreadSafe) _mOwningThread
.AssertOwnership("nsImageListener" " not thread-safe"); const
char* const nametmp = "nsImageListener"; nsrefcnt count = --
mRefCnt; NS_LogRelease((this), (count), (nametmp)); if (count
== 0) { mRefCnt = 1; delete (this); return 0; } return count
; } nsresult nsImageListener::QueryInterface(const nsIID&
aIID, void** aInstancePtr) { do { if (!(aInstancePtr)) { NS_DebugBreak
(NS_DEBUG_ASSERTION, "QueryInterface requires a non-NULL destination!"
, "aInstancePtr", "/var/lib/jenkins/workspace/firefox-scan-build/layout/generic/nsImageFrame.cpp"
, 2835); MOZ_PretendNoReturn(); } } while (0); nsresult rv = NS_ERROR_FAILURE
; static_assert(1 > 0, "Need more arguments to NS_INTERFACE_TABLE"
); static const QITableEntry table[] = { {&mozilla::detail
::kImplementedIID<nsImageListener, imgINotificationObserver
>, int32_t( reinterpret_cast<char*>(static_cast<imgINotificationObserver
*>((nsImageListener*)0x1000)) - reinterpret_cast<char*>
((nsImageListener*)0x1000))}, {&mozilla::detail::kImplementedIID
<nsImageListener, nsISupports>, int32_t(reinterpret_cast
<char*>(static_cast<nsISupports*>( static_cast<
imgINotificationObserver*>((nsImageListener*)0x1000))) - reinterpret_cast
<char*>((nsImageListener*)0x1000))}, { nullptr, 0 } } ;
static_assert(std::size(table) > 1, "need at least 1 interface"
); rv = NS_TableDrivenQI(static_cast<void*>(this), aIID
, aInstancePtr, table); return rv; }
2836
2837nsImageListener::nsImageListener(nsImageFrame* aFrame) : mFrame(aFrame) {}
2838
2839nsImageListener::~nsImageListener() = default;
2840
2841void nsImageListener::Notify(imgIRequest* aRequest, int32_t aType,
2842 const nsIntRect* aData) {
2843 if (!mFrame) {
2844 return;
2845 }
2846
2847 return mFrame->Notify(aRequest, aType, aData);
2848}
2849
2850static bool IsInAutoWidthTableCellForQuirk(nsIFrame* aFrame) {
2851 if (eCompatibility_NavQuirks != aFrame->PresContext()->CompatibilityMode()) {
2852 return false;
2853 }
2854 // Check if the parent of the closest nsBlockFrame has auto width.
2855 nsBlockFrame* ancestor = nsLayoutUtils::FindNearestBlockAncestor(aFrame);
2856 if (ancestor->Style()->GetPseudoType() == PseudoStyleType::cellContent) {
2857 // Assume direct parent is a table cell frame.
2858 nsIFrame* grandAncestor = static_cast<nsIFrame*>(ancestor->GetParent());
2859 return grandAncestor && grandAncestor->StylePosition()->GetWidth().IsAuto();
2860 }
2861 return false;
2862}
2863
2864void nsImageFrame::AddInlineMinISize(const IntrinsicSizeInput& aInput,
2865 InlineMinISizeData* aData) {
2866 // Note: we are one of the children that mPercentageBasisForChildren was
2867 // prepared for (i.e. our parent frame prepares the percentage basis for us,
2868 // not for our own children). Hence it's fine that we're resolving our
2869 // percentages sizes against this basis in IntrinsicForContainer().
2870 nscoord isize = nsLayoutUtils::IntrinsicForContainer(
2871 aInput.mContext, this, IntrinsicISizeType::MinISize,
2872 aInput.mPercentageBasisForChildren);
2873 bool canBreak = !IsInAutoWidthTableCellForQuirk(this);
2874 aData->DefaultAddInlineMinISize(this, isize, canBreak);
2875}
2876
2877void nsImageFrame::ReleaseGlobals() { BrokenImageIcon::Shutdown(); }