2 Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
3 Copyright (C) 2001 Dirk Mueller (mueller@kde.org)
4 Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
5 Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
6 Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
8 This library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Library General Public
10 License as published by the Free Software Foundation; either
11 version 2 of the License, or (at your option) any later version.
13 This library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Library General Public License for more details.
18 You should have received a copy of the GNU Library General Public License
19 along with this library; see the file COPYING.LIB. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA.
25 #include "core/fetch/ImageResource.h"
27 #include "RuntimeEnabledFeatures.h"
28 #include "core/fetch/ImageResourceClient.h"
29 #include "core/fetch/MemoryCache.h"
30 #include "core/fetch/ResourceClient.h"
31 #include "core/fetch/ResourceClientWalker.h"
32 #include "core/fetch/ResourceFetcher.h"
33 #include "core/frame/FrameView.h"
34 #include "core/rendering/RenderObject.h"
35 #include "core/svg/graphics/SVGImage.h"
36 #include "platform/SharedBuffer.h"
37 #include "platform/graphics/BitmapImage.h"
38 #include "wtf/CurrentTime.h"
39 #include "wtf/StdLibExtras.h"
40 #include "wtf/Vector.h"
44 ImageResource::ImageResource(const ResourceRequest& resourceRequest)
45 : Resource(resourceRequest, Image)
46 , m_devicePixelRatioHeaderValue(1.0)
48 , m_loadingMultipartContent(false)
49 , m_hasDevicePixelRatioHeaderValue(false)
52 setCustomAcceptHeader();
55 ImageResource::ImageResource(WebCore::Image* image)
56 : Resource(ResourceRequest(""), Image)
61 setCustomAcceptHeader();
64 ImageResource::ImageResource(const ResourceRequest& resourceRequest, WebCore::Image* image)
65 : Resource(resourceRequest, Image)
70 setCustomAcceptHeader();
73 ImageResource::~ImageResource()
78 void ImageResource::load(ResourceFetcher* fetcher, const ResourceLoaderOptions& options)
80 if (!fetcher || fetcher->autoLoadImages())
81 Resource::load(fetcher, options);
86 void ImageResource::didAddClient(ResourceClient* c)
88 if (m_data && !m_image && !errorOccurred()) {
90 m_image->setData(m_data, true);
93 ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
94 if (m_image && !m_image->isNull())
95 static_cast<ImageResourceClient*>(c)->imageChanged(this);
97 Resource::didAddClient(c);
100 void ImageResource::didRemoveClient(ResourceClient* c)
103 ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
105 m_pendingContainerSizeRequests.remove(static_cast<ImageResourceClient*>(c));
107 m_svgImageCache->removeClientFromCache(static_cast<ImageResourceClient*>(c));
109 Resource::didRemoveClient(c);
112 void ImageResource::switchClientsToRevalidatedResource()
114 ASSERT(resourceToRevalidate());
115 ASSERT(resourceToRevalidate()->isImage());
116 // Pending container size requests need to be transferred to the revalidated resource.
117 if (!m_pendingContainerSizeRequests.isEmpty()) {
118 // A copy of pending size requests is needed as they are deleted during Resource::switchClientsToRevalidateResouce().
119 ContainerSizeRequests switchContainerSizeRequests;
120 for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
121 switchContainerSizeRequests.set(it->key, it->value);
122 Resource::switchClientsToRevalidatedResource();
123 ImageResource* revalidatedImageResource = toImageResource(resourceToRevalidate());
124 for (ContainerSizeRequests::iterator it = switchContainerSizeRequests.begin(); it != switchContainerSizeRequests.end(); ++it)
125 revalidatedImageResource->setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
129 Resource::switchClientsToRevalidatedResource();
132 bool ImageResource::isSafeToUnlock() const
134 // Note that |m_image| holds a reference to |m_data| in addition to the one held by the Resource parent class.
135 return !m_image || (m_image->hasOneRef() && m_data->refCount() == 2);
138 void ImageResource::destroyDecodedDataIfPossible()
140 if (!hasClients() && !isLoading() && (!m_image || (m_image->hasOneRef() && m_image->isBitmapImage()))) {
143 } else if (m_image && !errorOccurred()) {
144 m_image->destroyDecodedData(true);
148 void ImageResource::allClientsRemoved()
150 m_pendingContainerSizeRequests.clear();
151 if (m_image && !errorOccurred())
152 m_image->resetAnimation();
153 Resource::allClientsRemoved();
156 pair<WebCore::Image*, float> ImageResource::brokenImage(float deviceScaleFactor)
158 if (deviceScaleFactor >= 2) {
159 DEFINE_STATIC_REF(WebCore::Image, brokenImageHiRes, (WebCore::Image::loadPlatformResource("missingImage@2x")));
160 return std::make_pair(brokenImageHiRes, 2);
163 DEFINE_STATIC_REF(WebCore::Image, brokenImageLoRes, (WebCore::Image::loadPlatformResource("missingImage")));
164 return std::make_pair(brokenImageLoRes, 1);
167 bool ImageResource::willPaintBrokenImage() const
169 return errorOccurred();
172 WebCore::Image* ImageResource::image()
174 ASSERT(!isPurgeable());
176 if (errorOccurred()) {
177 // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
178 // deviceScaleFactor from here. It is critical that callers use ImageResource::brokenImage()
179 // when they need the real, deviceScaleFactor-appropriate broken image icon.
180 return brokenImage(1).first;
184 return m_image.get();
186 return WebCore::Image::nullImage();
189 WebCore::Image* ImageResource::imageForRenderer(const RenderObject* renderer)
191 ASSERT(!isPurgeable());
193 if (errorOccurred()) {
194 // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
195 // deviceScaleFactor from here. It is critical that callers use ImageResource::brokenImage()
196 // when they need the real, deviceScaleFactor-appropriate broken image icon.
197 return brokenImage(1).first;
201 return WebCore::Image::nullImage();
203 if (m_image->isSVGImage()) {
204 WebCore::Image* image = m_svgImageCache->imageForRenderer(renderer);
205 if (image != WebCore::Image::nullImage())
209 return m_image.get();
212 void ImageResource::setContainerSizeForRenderer(const ImageResourceClient* renderer, const IntSize& containerSize, float containerZoom)
214 if (containerSize.isEmpty())
217 ASSERT(containerZoom);
219 m_pendingContainerSizeRequests.set(renderer, SizeAndZoom(containerSize, containerZoom));
222 if (!m_image->isSVGImage()) {
223 m_image->setContainerSize(containerSize);
227 m_svgImageCache->setContainerSizeForRenderer(renderer, containerSize, containerZoom);
230 bool ImageResource::usesImageContainerSize() const
233 return m_image->usesContainerSize();
238 bool ImageResource::imageHasRelativeWidth() const
241 return m_image->hasRelativeWidth();
246 bool ImageResource::imageHasRelativeHeight() const
249 return m_image->hasRelativeHeight();
254 LayoutSize ImageResource::imageSizeForRenderer(const RenderObject* renderer, float multiplier, SizeType sizeType)
256 ASSERT(!isPurgeable());
261 LayoutSize imageSize;
263 if (m_image->isBitmapImage() && (renderer && renderer->shouldRespectImageOrientation() == RespectImageOrientation))
264 imageSize = toBitmapImage(m_image.get())->sizeRespectingOrientation();
265 else if (m_image->isSVGImage() && sizeType == NormalSize)
266 imageSize = m_svgImageCache->imageSizeForRenderer(renderer);
268 imageSize = m_image->size();
270 if (multiplier == 1.0f)
273 // Don't let images that have a width/height >= 1 shrink below 1 when zoomed.
274 float widthScale = m_image->hasRelativeWidth() ? 1.0f : multiplier;
275 float heightScale = m_image->hasRelativeHeight() ? 1.0f : multiplier;
276 LayoutSize minimumSize(imageSize.width() > 0 ? 1 : 0, imageSize.height() > 0 ? 1 : 0);
277 imageSize.scale(widthScale, heightScale);
278 imageSize.clampToMinimumSize(minimumSize);
279 ASSERT(multiplier != 1.0f || (imageSize.width().fraction() == 0.0f && imageSize.height().fraction() == 0.0f));
283 void ImageResource::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
286 m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
289 void ImageResource::notifyObservers(const IntRect* changeRect)
291 ResourceClientWalker<ImageResourceClient> w(m_clients);
292 while (ImageResourceClient* c = w.next())
293 c->imageChanged(this, changeRect);
296 void ImageResource::clear()
300 m_pendingContainerSizeRequests.clear();
304 void ImageResource::setCustomAcceptHeader()
306 DEFINE_STATIC_LOCAL(const AtomicString, acceptWebP, ("image/webp,*/*;q=0.8", AtomicString::ConstructFromLiteral));
307 setAccept(acceptWebP);
310 inline void ImageResource::createImage()
312 // Create the image if it doesn't yet exist.
316 if (m_response.mimeType() == "image/svg+xml") {
317 RefPtr<SVGImage> svgImage = SVGImage::create(this);
318 m_svgImageCache = SVGImageCache::create(svgImage.get());
319 m_image = svgImage.release();
321 m_image = BitmapImage::create(this);
325 // Send queued container size requests.
326 if (m_image->usesContainerSize()) {
327 for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
328 setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
330 m_pendingContainerSizeRequests.clear();
334 inline void ImageResource::clearImage()
336 // If our Image has an observer, it's always us so we need to clear the back pointer
337 // before dropping our reference.
339 m_image->setImageObserver(0);
343 void ImageResource::appendData(const char* data, int length)
345 Resource::appendData(data, length);
346 if (!m_loadingMultipartContent)
350 void ImageResource::updateImage(bool allDataReceived)
352 TRACE_EVENT0("webkit", "ImageResource::updateImage");
357 bool sizeAvailable = false;
359 // Have the image update its data from its internal buffer.
360 // It will not do anything now, but will delay decoding until
361 // queried for info (like size or specific image frames).
363 sizeAvailable = m_image->setData(m_data, allDataReceived);
365 // Go ahead and tell our observers to try to draw if we have either
366 // received all the data or the size is known. Each chunk from the
367 // network causes observers to repaint, which will force that chunk
369 if (sizeAvailable || allDataReceived) {
370 if (!m_image || m_image->isNull()) {
371 error(errorOccurred() ? status() : DecodeError);
372 if (memoryCache()->contains(this))
373 memoryCache()->remove(this);
377 // It would be nice to only redraw the decoded band of the image, but with the current design
378 // (decoding delayed until painting) that seems hard.
383 void ImageResource::finishOnePart()
385 if (m_loadingMultipartContent)
388 if (m_loadingMultipartContent)
390 Resource::finishOnePart();
393 void ImageResource::error(Resource::Status status)
396 Resource::error(status);
400 void ImageResource::responseReceived(const ResourceResponse& response)
402 if (m_loadingMultipartContent && m_data)
404 else if (response.isMultipart())
405 m_loadingMultipartContent = true;
406 if (RuntimeEnabledFeatures::clientHintsDprEnabled()) {
407 m_devicePixelRatioHeaderValue = response.httpHeaderField("DPR").toFloat(&m_hasDevicePixelRatioHeaderValue);
408 if (!m_hasDevicePixelRatioHeaderValue || m_devicePixelRatioHeaderValue <= 0.0) {
409 m_devicePixelRatioHeaderValue = 1.0;
410 m_hasDevicePixelRatioHeaderValue = false;
413 Resource::responseReceived(response);
416 void ImageResource::decodedSizeChanged(const WebCore::Image* image, int delta)
418 if (!image || image != m_image)
421 setDecodedSize(decodedSize() + delta);
424 void ImageResource::didDraw(const WebCore::Image* image)
426 if (!image || image != m_image)
428 Resource::didAccessDecodedData();
431 bool ImageResource::shouldPauseAnimation(const WebCore::Image* image)
433 if (!image || image != m_image)
436 ResourceClientWalker<ImageResourceClient> w(m_clients);
437 while (ImageResourceClient* c = w.next()) {
438 if (c->willRenderImage(this))
445 void ImageResource::animationAdvanced(const WebCore::Image* image)
447 if (!image || image != m_image)
452 void ImageResource::changedInRect(const WebCore::Image* image, const IntRect& rect)
454 if (!image || image != m_image)
456 notifyObservers(&rect);
459 bool ImageResource::currentFrameKnownToBeOpaque(const RenderObject* renderer)
461 WebCore::Image* image = imageForRenderer(renderer);
462 if (image->isBitmapImage())
463 image->nativeImageForCurrentFrame(); // force decode
464 return image->currentFrameKnownToBeOpaque();
467 bool ImageResource::isAccessAllowed(SecurityOrigin* securityOrigin)
469 if (!image()->currentFrameHasSingleSecurityOrigin())
471 if (passesAccessControlCheck(securityOrigin))
473 return !securityOrigin->taintsCanvas(response().url());
476 } // namespace WebCore