Bug Summary

File:Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore/rendering/svg/RenderSVGImage.cpp
Warning:line 290, column 26
Local variable 'cachedImage' is uncounted and unsafe

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple arm64-apple-ios26.2.0-simulator -O3 -Wundef-prefix=TARGET_OS_ -Werror=undef-prefix -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -Werror=implicit-function-declaration -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name UnifiedSource426.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=osx -analyzer-checker=security.insecureAPI.decodeValueOfObjCType -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 -mframe-pointer=non-leaf -ffp-contract=on -fno-rounding-math -target-sdk-version=26.2 -fdepfile-entry=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/SDKSettings.json -fcompatibility-qualified-id-block-type-checking -fvisibility-inlines-hidden-static-local-var -fno-modulemap-allow-subdirectory-search -fdefine-target-os-macros -enable-tlsdesc -target-cpu apple-m1 -target-feature +v8.4a -target-feature +aes -target-feature +altnzcv -target-feature +ccdp -target-feature +ccpp -target-feature +complxnum -target-feature +crc -target-feature +dotprod -target-feature +flagm -target-feature +fp-armv8 -target-feature +fp16fml -target-feature +fptoint -target-feature +fullfp16 -target-feature +jsconv -target-feature +lse -target-feature +neon -target-feature +pauth -target-feature +perfmon -target-feature +predres -target-feature +ras -target-feature +rcpc -target-feature +rdm -target-feature +sb -target-feature +sha2 -target-feature +sha3 -target-feature +specrestrict -target-feature +ssbs -target-abi darwinpcs -dwarf-ext-refs -fmodule-format=obj -debug-info-kind=standalone -dwarf-version=5 -debugger-tuning=lldb -fdebug-compilation-dir=/Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore -target-linker-version 1230.1 -fcoverage-compilation-dir=/Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore -resource-dir /Users/buildbot/Library/Developer/Toolchains/swift-webkit.xctoolchain/usr/lib/clang/21 -dependency-file /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/scan-build-output/StaticAnalyzer/WebCore/WebCore/normal/arm64/UnifiedSource426.d -skip-unused-modulemap-deps -MT dependencies -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk -iquote /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/WebCore-generated-files.hmap -iquote /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/WebCore-project-headers.hmap -isystem /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore/PAL/ThirdParty/dav1d/include -isystem /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/SDKAdditions/usr/include -iframework /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/SDKAdditions/System/Library/Frameworks -iframework /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitLibraries/SDKs/iphonesimulator26.0-additions.sdk/System/Library/PrivateFrameworks -iframework /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/System/Library/Frameworks -include-pch /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/PrecompiledHeaders/SharedPrecompiledHeaders/11721353671419897710/WebCorePrefix.h.gch -D _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE -D NDEBUG -D BUILDING_WEBKIT -D GL_SILENCE_DEPRECATION=1 -D GLES_SILENCE_DEPRECATION=1 -D __clang_analyzer__ -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/WebCore-own-target-headers.hmap -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/WebCore-all-target-headers.hmap -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/include -I PAL -I ForwardingHeaders -I /usr/include/libxslt -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/include/libxml2 -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/DerivedSources/WebCore -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/usr/local/include -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/usr/local/include/WebKitAdditions -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/local/include/WebKitAdditions -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/usr/local/include -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitLibraries/SDKs/iphonesimulator26.0-additions.sdk/usr/local/include -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/local/include -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/usr/local/include/webrtc -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/local/include/webrtc -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/usr/local/include/webm -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/local/include/webm -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/PAL.build/PAL.build/DerivedSources -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/PAL.build/Release-iphonesimulator/PAL.build/DerivedSources -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/Source/WebCore -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/DerivedSources-normal/arm64 -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/DerivedSources/arm64 -I /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/WebCore.build/Release-iphonesimulator/WebCore.build/DerivedSources -F/Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator -F/Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator -I/usr/local/include -stdlib=libc++ -internal-isystem /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/include/c++/v1 -internal-isystem /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/local/include -internal-isystem /Users/buildbot/Library/Developer/Toolchains/swift-webkit.xctoolchain/usr/lib/clang/21/include -internal-externc-isystem /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/usr/include -internal-iframework /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/System/Library/Frameworks -internal-iframework /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/System/Library/SubFrameworks -internal-iframework /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator26.2.sdk/Library/Frameworks -Wno-trigraphs -Werror -Wno-missing-field-initializers -Wmissing-prototypes -Wunreachable-code -Wnon-virtual-dtor -Wno-overloaded-virtual -Wno-exit-time-destructors -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wno-float-conversion -Wnon-literal-null-conversion -Wobjc-literal-conversion -Wsign-compare -Wno-shorten-64-to-32 -Wnewline-eof -Wno-c++11-extensions -Wno-implicit-fallthrough -Wdeprecated-declarations -Winvalid-offsetof -Wno-sign-conversion -Winfinite-recursion -Wmove -Wcomma -Wblock-capture-autoreleasing -Wstrict-prototypes -Wrange-loop-analysis -Wno-semicolon-before-method-body -Wall -Wc99-designator -Wconditional-uninitialized -Wextra -Wdeprecated-enum-enum-conversion -Wdeprecated-enum-float-conversion -Wenum-float-conversion -Wfinal-dtor-non-final-class -Wformat=2 -Wmisleading-indentation -Wpointer-to-int-cast -Wreorder-init-list -Wundef -Wunused-but-set-variable -Wvla -Werror=unguarded-availability -Wno-elaborated-enum-base -Wcast-qual -Wchar-subscripts -Wextra-tokens -Winit-self -Wmissing-noreturn -Wpacked -Wpointer-arith -Wredundant-decls -Wwrite-strings -Wexit-time-destructors -Wglobal-constructors -Wtautological-compare -Wimplicit-fallthrough -Wvla -Wno-unknown-warning-option -Wliteral-conversion -Wthread-safety -Wno-profile-instr-out-of-date -Wno-profile-instr-unprofiled -Wno-backend-plugin -Wunsafe-buffer-usage -std=c++2b -fdeprecated-macro -ferror-limit 19 -fmacro-backtrace-limit=0 -fvisibility=hidden -fvisibility-inlines-hidden -stack-protector 1 -fblocks -fencode-extended-block-signature -fno-rtti -fregister-global-dtors-with-atexit -fgnuc-version=4.2.1 -fno-cxx-modules -fno-implicit-modules -fskip-odr-check-in-gmf -fpascal-strings -fmax-type-align=16 -fdiagnostics-show-note-include-stack -vectorize-loops -vectorize-slp -fsafe-buffer-usage-suggestions -analyzer-output=html -analyzer-config report-in-main-source-file=true -analyzer-config nullability:NoDiagnoseCallsToSystemHeaders=true -analyzer-checker optin.osx.cocoa.localizability.NonLocalizedStringChecker -analyzer-checker security.insecureAPI.UncheckedReturn -analyzer-checker security.insecureAPI.getpw -analyzer-checker security.insecureAPI.gets -analyzer-checker security.insecureAPI.mkstemp -analyzer-checker security.insecureAPI.mktemp -analyzer-disable-checker security.insecureAPI.rand -analyzer-disable-checker security.insecureAPI.strcpy -analyzer-checker security.insecureAPI.vfork -analyzer-disable-checker alpha,apiModeling,core,cplusplus,deadcode,debug,fuchsia,nullability,optin,osx,security,unix,webkit -analyzer-checker alpha.webkit.ForwardDeclChecker,alpha.webkit.MemoryUnsafeCastChecker,alpha.webkit.NoDeleteChecker,alpha.webkit.NoUncheckedPtrMemberChecker,alpha.webkit.NoUnretainedMemberChecker,alpha.webkit.RetainPtrCtorAdoptChecker,alpha.webkit.UncheckedCallArgsChecker,alpha.webkit.UncheckedLocalVarsChecker,alpha.webkit.UncountedCallArgsChecker,alpha.webkit.UncountedLocalVarsChecker,alpha.webkit.UnretainedCallArgsChecker,alpha.webkit.UnretainedLambdaCapturesChecker,alpha.webkit.UnretainedLocalVarsChecker,webkit.NoUncountedMemberChecker,webkit.RefCntblBaseVirtualDtor,webkit.UncountedLambdaCapturesChecker -analyzer-config max-nodes=10000000 -analyzer-config verbose-report-filename=true -fdwarf2-cfi-asm -o /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/scan-build-output/StaticAnalyzer/WebCore/WebCore/normal/arm64/UnifiedSource426.plist -x c++ /Volumes/Data/worker/Apple-iOS-26-Safer-CPP-Checks-EWS/build/WebKitBuild/Release-iphonesimulator/DerivedSources/WebCore/unified-sources/UnifiedSource426.cpp
1/*
2 * Copyright (C) 2006 Alexander Kellett <lypanov@kde.org>
3 * Copyright (C) 2006 Apple Inc. All rights reserved.
4 * Copyright (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>
5 * Copyright (C) 2007, 2008, 2009 Rob Buis <buis@kde.org>
6 * Copyright (C) 2009 Google, Inc.
7 * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
8 * Copyright (C) 2010 Patrick Gansterer <paroga@paroga.com>
9 * Copyright (c) 2020, 2021, 2022 Igalia S.L.
10 *
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
15 *
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
20 *
21 * You should have received a copy of the GNU Library General Public License
22 * along with this library; see the file COPYING.LIB. If not, write to
23 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 * Boston, MA 02110-1301, USA.
25 */
26
27#include "config.h"
28#include "RenderSVGImage.h"
29
30#include "AXObjectCache.h"
31#include "BitmapImage.h"
32#include "GeometryUtilities.h"
33#include "GraphicsContext.h"
34#include "HitTestResult.h"
35#include "ImageBuffer.h"
36#include "ImageQualityController.h"
37#include "LayoutRepainter.h"
38#include "PointerEventsHitRules.h"
39#include "RenderElementStyleInlines.h"
40#include "RenderImageResource.h"
41#include "RenderLayer.h"
42#include "RenderObjectInlines.h"
43#include "RenderSVGModelObjectInlines.h"
44#include "SVGElementTypeHelpers.h"
45#include "SVGImageElement.h"
46#include "SVGVisitedRendererTracking.h"
47#include "Settings.h"
48#include <wtf/StackStats.h>
49#include <wtf/TZoneMallocInlines.h>
50
51namespace WebCore {
52
53WTF_MAKE_TZONE_ALLOCATED_IMPL(RenderSVGImage)::bmalloc::api::HeapRef RenderSVGImage::s_heapRef; const TZoneSpecification
RenderSVGImage::s_heapSpec = { &RenderSVGImage::s_heapRef
, TZoneSpecification::encodeSize<RenderSVGImage>(), TZoneSpecification
::encodeAlignment<RenderSVGImage>(), TZoneSpecification
::encodeCategory<RenderSVGImage>(), ::bmalloc::api::compactAllocationMode
<RenderSVGImage>(), TZoneSpecification::encodeDescriptor
<RenderSVGImage>(), }; void* RenderSVGImage::operatorNewSlow
(size_t size) { if constexpr (::bmalloc::api::compactAllocationMode
<RenderSVGImage>() == CompactAllocationMode::Compact) return
::bmalloc::api::tzoneAllocateCompactSlow(size, s_heapSpec); return
::bmalloc::api::tzoneAllocateNonCompactSlow(size, s_heapSpec
); } using __makeBtzoneMallocedInlineMacroSemicolonifier __attribute__
((unused)) = int
;
54
55RenderSVGImage::RenderSVGImage(SVGImageElement& element, RenderStyle&& style)
56 : RenderSVGModelObject(Type::SVGImage, element, WTF::move(style))
57 , m_imageResource(makeUniqueRef<RenderImageResource>())
58{
59 ASSERT(isRenderSVGImage())((void)0);
60 imageResource().initialize(*this);
61}
62
63RenderSVGImage::~RenderSVGImage() = default;
64
65void RenderSVGImage::willBeDestroyed()
66{
67 imageResource().willBeDestroyed();
68 RenderSVGModelObject::willBeDestroyed();
69}
70
71SVGImageElement& RenderSVGImage::imageElement() const
72{
73 return downcast<SVGImageElement>(RenderSVGModelObject::element());
74}
75
76FloatRect RenderSVGImage::calculateObjectBoundingBox() const
77{
78 LayoutSize intrinsicSize;
79 if (CachedImage* cachedImage = imageResource().cachedImage())
80 intrinsicSize = cachedImage->imageSizeForRenderer(nullptr, style().usedZoom());
81
82 Ref imageElement = this->imageElement();
83 SVGLengthContext lengthContext(imageElement.ptr());
84
85 CheckedRef style = this->style();
86 auto& width = style->width();
87 auto& height = style->height();
88 auto usedZoom = style->usedZoomForLength();
89
90 float concreteWidth;
91 if (!width.isAuto())
92 concreteWidth = lengthContext.valueForLength(width, usedZoom, SVGLengthMode::Width);
93 else if (!height.isAuto() && !intrinsicSize.isEmpty())
94 concreteWidth = lengthContext.valueForLength(height, usedZoom, SVGLengthMode::Height) * intrinsicSize.width() / intrinsicSize.height();
95 else
96 concreteWidth = intrinsicSize.width();
97
98 float concreteHeight;
99 if (!height.isAuto())
100 concreteHeight = lengthContext.valueForLength(height, usedZoom, SVGLengthMode::Height);
101 else if (!width.isAuto() && !intrinsicSize.isEmpty())
102 concreteHeight = lengthContext.valueForLength(width, usedZoom, SVGLengthMode::Width) * intrinsicSize.height() / intrinsicSize.width();
103 else
104 concreteHeight = intrinsicSize.height();
105
106 return { imageElement->x().value(lengthContext), imageElement->y().value(lengthContext), concreteWidth, concreteHeight };
107}
108
109void RenderSVGImage::layout()
110{
111 StackStats::LayoutCheckPoint layoutCheckPoint;
112
113 LayoutRepainter repainter(*this);
114
115 updateImageViewport();
116 setCurrentSVGLayoutRect(enclosingLayoutRect(m_objectBoundingBox));
117 m_cachedVisualOverflowRect = std::nullopt;
118
119 updateLayerTransform();
120
121 repainter.repaintAfterLayout();
122 clearNeedsLayout();
123}
124
125void RenderSVGImage::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
126{
127 OptionSet<PaintPhase> relevantPaintPhases { PaintPhase::Foreground, PaintPhase::ClippingMask, PaintPhase::Mask, PaintPhase::Outline, PaintPhase::SelfOutline };
128 if (!shouldPaintSVGRenderer(paintInfo, relevantPaintPhases) || !imageResource().cachedImage())
129 return;
130
131 if (paintInfo.phase == PaintPhase::ClippingMask) {
132 paintSVGClippingMask(paintInfo, objectBoundingBox());
133 return;
134 }
135
136 auto adjustedPaintOffset = paintOffset + currentSVGLayoutLocation();
137 if (paintInfo.phase == PaintPhase::Mask) {
138 paintSVGMask(paintInfo, adjustedPaintOffset);
139 return;
140 }
141
142 auto visualOverflowRect = visualOverflowRectEquivalent();
143 visualOverflowRect.moveBy(adjustedPaintOffset);
144 if (!visualOverflowRect.intersects(paintInfo.rect))
145 return;
146
147 GraphicsContextStateSaver stateSaver(paintInfo.context());
148
149 if (paintInfo.phase == PaintPhase::Outline || paintInfo.phase == PaintPhase::SelfOutline) {
150 paintInfo.context().resetClip();
151 paintSVGOutline(paintInfo, adjustedPaintOffset);
152 return;
153 }
154
155 ASSERT(paintInfo.phase == PaintPhase::Foreground)((void)0);
156
157 auto coordinateSystemOriginTranslation = adjustedPaintOffset - flooredLayoutPoint(objectBoundingBox().location());
158 paintInfo.context().translate(coordinateSystemOriginTranslation.width(), coordinateSystemOriginTranslation.height());
159
160 if (style().bufferedRendering() == BufferedRendering::Static && bufferForeground(paintInfo, flooredLayoutPoint(objectBoundingBox().location())))
161 return;
162
163 paintForeground(paintInfo, flooredLayoutPoint(objectBoundingBox().location()));
164}
165
166ImageDrawResult RenderSVGImage::paintIntoRect(PaintInfo& paintInfo, const FloatRect& rect, const FloatRect& sourceRect)
167{
168 if (!imageResource().cachedImage() || rect.width() <= 0 || rect.height() <= 0)
169 return ImageDrawResult::DidNothing;
170
171 RefPtr<Image> image = imageResource().image();
172 if (!image || image->isNull())
173 return ImageDrawResult::DidNothing;
174
175 ImagePaintingOptions options {
176 CompositeOperator::SourceOver,
177 DecodingMode::Synchronous,
178 imageOrientation(),
179 ImageQualityController::chooseInterpolationQualityForSVG(paintInfo.context(), *this, *image),
180 settings().imageSubsamplingEnabled() ? AllowImageSubsampling::Yes : AllowImageSubsampling::No,
181 settings().showDebugBorders() ? ShowDebugBackground::Yes : ShowDebugBackground::No
182 };
183
184 auto drawResult = paintInfo.context().drawImage(*image, rect, sourceRect, options);
185 if (drawResult == ImageDrawResult::DidRequestDecoding)
186 imageResource().cachedImage()->addClientWaitingForAsyncDecoding(cachedImageClient());
187
188 return drawResult;
189}
190
191void RenderSVGImage::paintForeground(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
192{
193 GraphicsContext& context = paintInfo.context();
194 if (context.invalidatingImagesWithAsyncDecodes()) {
195 if (cachedImage() && cachedImage()->isClientWaitingForAsyncDecoding(cachedImageClient()))
196 cachedImage()->removeAllClientsWaitingForAsyncDecoding();
197 return;
198 }
199
200 if (!imageResource().cachedImage()) {
201 page().addRelevantUnpaintedObject(*this, visualOverflowRectEquivalent());
202 return;
203 }
204
205 RefPtr<Image> image = imageResource().image();
206 if (!image || image->isNull()) {
207 page().addRelevantUnpaintedObject(*this, visualOverflowRectEquivalent());
208 return;
209 }
210
211 FloatRect contentBoxRect = borderBoxRectEquivalent();
212 FloatRect replacedContentRect(0, 0, image->width(), image->height());
213 protect(imageElement())->preserveAspectRatio().transformRect(contentBoxRect, replacedContentRect);
214
215 contentBoxRect.moveBy(paintOffset);
216
217 ImageDrawResult result = paintIntoRect(paintInfo, contentBoxRect, replacedContentRect);
218
219 if (cachedImage() && !context.paintingDisabled()) {
220 // For now, count images as unpainted if they are still progressively loading. We may want
221 // to refine this in the future to account for the portion of the image that has painted.
222 replacedContentRect.moveBy(paintOffset);
223 auto visibleRect = intersection(replacedContentRect, contentBoxRect);
224 if (cachedImage()->isLoading() || result == ImageDrawResult::DidRequestDecoding)
225 page().addRelevantUnpaintedObject(*this, enclosingLayoutRect(visibleRect));
226 else
227 page().addRelevantRepaintedObject(*this, enclosingLayoutRect(visibleRect));
228
229 auto localVisibleRect = visibleRect;
230 localVisibleRect.moveBy(-paintOffset);
231 protect(document())->didPaintImage(protect(imageElement()).get(), cachedImage(), localVisibleRect);
232 }
233}
234
235bool RenderSVGImage::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
236{
237 if (hitTestAction != HitTestForeground)
238 return false;
239
240 auto adjustedLocation = accumulatedOffset + currentSVGLayoutLocation();
241
242 auto visualOverflowRect = visualOverflowRectEquivalent();
243 visualOverflowRect.moveBy(adjustedLocation);
244 if (!locationInContainer.intersects(visualOverflowRect))
245 return false;
246
247 static NeverDestroyed<SVGVisitedRendererTracking::VisitedSet> s_visitedSet;
248
249 SVGVisitedRendererTracking recursionTracking(s_visitedSet);
250 if (recursionTracking.isVisiting(*this))
251 return false;
252
253 SVGVisitedRendererTracking::Scope recursionScope(recursionTracking, *this);
254
255 auto localPoint = locationInContainer.point();
256 auto boundingBoxTopLeftCorner = flooredLayoutPoint(objectBoundingBox().minXMinYCorner());
257 auto coordinateSystemOriginTranslation = boundingBoxTopLeftCorner - adjustedLocation;
258 localPoint.move(coordinateSystemOriginTranslation);
259
260 if (!pointInSVGClippingArea(localPoint))
261 return false;
262
263 PointerEventsHitRules hitRules(PointerEventsHitRules::HitTestingTargetType::SVGImage, request, style().pointerEvents());
264 if (request.isVisibleForStyle(style()) || !hitRules.requireVisible) {
265 if (hitRules.canHitFill) {
266 if (m_objectBoundingBox.contains(localPoint)) {
267 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
268 if (result.addNodeToListBasedTestResult(protect(nodeForHitTest()).get(), request, locationInContainer, visualOverflowRect) == HitTestProgress::Stop)
269 return true;
270 }
271 }
272 }
273
274 return false;
275}
276
277bool RenderSVGImage::updateImageViewport()
278{
279 auto oldBoundaries = m_objectBoundingBox;
280 m_objectBoundingBox = calculateObjectBoundingBox();
281
282 bool updatedViewport = false;
283 Ref imageElement = this->imageElement();
284 URL imageSourceURL = document().completeURL(imageElement->imageSourceURL());
285
286 // Images with preserveAspectRatio=none should force non-uniform scaling. This can be achieved
287 // by setting the image's container size to its intrinsic size.
288 // See: http://www.w3.org/TR/SVG/single-page.html, 7.8 The ‘preserveAspectRatio’ attribute.
289 if (imageElement->preserveAspectRatio().align() == SVGPreserveAspectRatioValue::SVG_PRESERVEASPECTRATIO_NONE) {
290 if (CachedImage* cachedImage = imageResource().cachedImage()) {
Local variable 'cachedImage' is uncounted and unsafe
291 LayoutSize intrinsicSize = cachedImage->imageSizeForRenderer(nullptr, style().usedZoom());
292 if (intrinsicSize != imageResource().imageSize(style().usedZoom())) {
293 imageResource().setContainerContext(roundedIntSize(intrinsicSize), imageSourceURL);
294 updatedViewport = true;
295 }
296 }
297 }
298
299 if (oldBoundaries != m_objectBoundingBox) {
300 if (!updatedViewport)
301 imageResource().setContainerContext(enclosingIntRect(m_objectBoundingBox).size(), imageSourceURL);
302 updatedViewport = true;
303 }
304
305 return updatedViewport;
306}
307
308void RenderSVGImage::repaintOrMarkForLayout(const IntRect* rect)
309{
310 // Update the SVGImageCache sizeAndScales entry in case image loading finished after layout.
311 // (https://bugs.webkit.org/show_bug.cgi?id=99489)
312 m_objectBoundingBox = FloatRect();
313 if (updateImageViewport())
314 setNeedsLayout();
315
316 m_bufferedForeground = nullptr;
317
318 FloatRect repaintRect = borderBoxRectEquivalent();
319 if (rect) {
320 // The image changed rect is in source image coordinates (pre-zooming),
321 // so map from the bounds of the image to the contentsBox.
322 repaintRect.intersect(enclosingIntRect(mapRect(*rect, FloatRect(FloatPoint(), imageResource().imageSize(1.0f)), repaintRect)));
323 }
324
325 repaintRectangle(enclosingLayoutRect(repaintRect));
326
327 // Tell any potential compositing layers that the image needs updating.
328 if (hasLayer())
329 layer()->contentChanged(ContentChangeType::Image);
330}
331
332void RenderSVGImage::notifyFinished(CachedResource& newImage, const NetworkLoadMetrics& metrics, LoadWillContinueInAnotherProcess loadWillContinueInAnotherProcess)
333{
334 if (renderTreeBeingDestroyed())
335 return;
336
337 invalidateBackgroundObscurationStatus();
338
339 if (&newImage == cachedImage()) {
340 // tell any potential compositing layers
341 // that the image is done and they can reference it directly.
342 if (hasLayer())
343 layer()->contentChanged(ContentChangeType::Image);
344 }
345
346 RenderSVGModelObject::notifyFinished(newImage, metrics, loadWillContinueInAnotherProcess);
347}
348
349void RenderSVGImage::imageChanged(WrappedImagePtr newImage, const IntRect* rect)
350{
351 if (renderTreeBeingDestroyed() || !parent())
352 return;
353
354 repaintClientsOfReferencedSVGResources();
355
356 if (hasVisibleBoxDecorations() || hasMask() || hasShapeOutside())
357 RenderSVGModelObject::imageChanged(newImage, rect);
358
359 if (newImage != imageResource().imagePtr() || !newImage)
360 return;
361
362 repaintOrMarkForLayout(rect);
363
364 if (CheckedPtr cache = document().existingAXObjectCache())
365 cache->deferRecomputeIsIgnoredIfNeeded(protect(imageElement()).ptr());
366
367 if (auto* image = imageResource().cachedImage(); image && image->currentFrameIsComplete(this)) {
368 if (auto styleable = Styleable::fromRenderer(*this))
369 protect(document())->didLoadImage(protect(styleable->element).get(), image);
370 }
371}
372
373bool RenderSVGImage::bufferForeground(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
374{
375 auto& destinationContext = paintInfo.context();
376
377 auto repaintBoundingBox = borderBoxRectEquivalent();
378 repaintBoundingBox.moveBy(paintOffset);
379
380 // Invalidate an existing buffer if the scale is not correct.
381 const auto& absoluteTransform = destinationContext.getCTM(GraphicsContext::DefinitelyIncludeDeviceScale);
382
383 auto absoluteTargetRect = enclosingIntRect(absoluteTransform.mapRect(repaintBoundingBox));
384 if (m_bufferedForeground) {
385 if (absoluteTargetRect.size() != m_bufferedForeground->backendSize())
386 m_bufferedForeground = nullptr;
387 else {
388 const auto& absoluteTransformBuffer = m_bufferedForeground->context().getCTM(GraphicsContext::DefinitelyIncludeDeviceScale);
389 if (absoluteTransformBuffer != absoluteTransform)
390 m_bufferedForeground = nullptr;
391 }
392 }
393
394 // Create a new buffer and paint the foreground into it.
395 if (!m_bufferedForeground) {
396 m_bufferedForeground = destinationContext.createAlignedImageBuffer(expandedIntSize(repaintBoundingBox.size()));
397 if (!m_bufferedForeground)
398 return false;
399 }
400
401 auto& bufferedContext = m_bufferedForeground->context();
402 bufferedContext.clearRect(absoluteTargetRect);
403
404 PaintInfo bufferedInfo(paintInfo);
405 bufferedInfo.setContext(bufferedContext);
406 paintForeground(bufferedInfo, paintOffset);
407
408 destinationContext.concatCTM(absoluteTransform.inverse().value_or(AffineTransform()));
409 RefPtr bufferedForeground = m_bufferedForeground.copyRef();
410 destinationContext.drawImageBuffer(*bufferedForeground, absoluteTargetRect);
411 destinationContext.concatCTM(absoluteTransform);
412
413 return true;
414}
415
416bool RenderSVGImage::needsHasSVGTransformFlags() const
417{
418 return protect(imageElement())->hasTransformRelatedAttributes();
419}
420
421void RenderSVGImage::applyTransform(TransformationMatrix& transform, const RenderStyle& style, const FloatRect& boundingBox, OptionSet<Style::TransformResolverOption> options) const
422{
423 applySVGTransform(transform, protect(imageElement()), style, boundingBox, std::nullopt, std::nullopt, options);
424}
425
426} // namespace WebCore