Bug Summary

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