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 "core/fetch/ImageResourceClient.h"
28 #include "core/fetch/MemoryCache.h"
29 #include "core/fetch/ResourceClient.h"
30 #include "core/fetch/ResourceClientWalker.h"
31 #include "core/fetch/ResourceFetcher.h"
32 #include "core/frame/FrameView.h"
33 #include "core/rendering/RenderObject.h"
34 #include "core/svg/graphics/SVGImage.h"
35 #include "platform/Logging.h"
36 #include "platform/RuntimeEnabledFeatures.h"
37 #include "platform/SharedBuffer.h"
38 #include "platform/TraceEvent.h"
39 #include "platform/graphics/BitmapImage.h"
40 #include "wtf/CurrentTime.h"
41 #include "wtf/StdLibExtras.h"
45 ImageResource::ImageResource(const ResourceRequest& resourceRequest)
46 : Resource(resourceRequest, Image)
47 , m_devicePixelRatioHeaderValue(1.0)
49 , m_loadingMultipartContent(false)
50 , m_hasDevicePixelRatioHeaderValue(false)
52 WTF_LOG(Timers, "new ImageResource(ResourceRequest) %p", this);
54 setCustomAcceptHeader();
57 ImageResource::ImageResource(blink::Image* image)
58 : Resource(ResourceRequest(""), Image)
61 WTF_LOG(Timers, "new ImageResource(Image) %p", this);
64 setCustomAcceptHeader();
67 ImageResource::ImageResource(const ResourceRequest& resourceRequest, blink::Image* image)
68 : Resource(resourceRequest, Image)
71 WTF_LOG(Timers, "new ImageResource(ResourceRequest, Image) %p", this);
74 setCustomAcceptHeader();
77 ImageResource::~ImageResource()
79 WTF_LOG(Timers, "~ImageResource %p", this);
83 void ImageResource::load(ResourceFetcher* fetcher, const ResourceLoaderOptions& options)
85 if (!fetcher || fetcher->autoLoadImages())
86 Resource::load(fetcher, options);
91 void ImageResource::didAddClient(ResourceClient* c)
93 if (m_data && !m_image && !errorOccurred()) {
95 m_image->setData(m_data, true);
98 ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
99 if (m_image && !m_image->isNull())
100 static_cast<ImageResourceClient*>(c)->imageChanged(this);
102 Resource::didAddClient(c);
105 void ImageResource::didRemoveClient(ResourceClient* c)
108 ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
110 m_pendingContainerSizeRequests.remove(static_cast<ImageResourceClient*>(c));
112 m_svgImageCache->removeClientFromCache(static_cast<ImageResourceClient*>(c));
114 Resource::didRemoveClient(c);
117 void ImageResource::switchClientsToRevalidatedResource()
119 ASSERT(resourceToRevalidate());
120 ASSERT(resourceToRevalidate()->isImage());
121 // Pending container size requests need to be transferred to the revalidated resource.
122 if (!m_pendingContainerSizeRequests.isEmpty()) {
123 // A copy of pending size requests is needed as they are deleted during Resource::switchClientsToRevalidateResouce().
124 ContainerSizeRequests switchContainerSizeRequests;
125 for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
126 switchContainerSizeRequests.set(it->key, it->value);
127 Resource::switchClientsToRevalidatedResource();
128 ImageResource* revalidatedImageResource = toImageResource(resourceToRevalidate());
129 for (ContainerSizeRequests::iterator it = switchContainerSizeRequests.begin(); it != switchContainerSizeRequests.end(); ++it)
130 revalidatedImageResource->setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
134 Resource::switchClientsToRevalidatedResource();
137 bool ImageResource::isSafeToUnlock() const
139 // Note that |m_image| holds a reference to |m_data| in addition to the one held by the Resource parent class.
140 return !m_image || (m_image->hasOneRef() && m_data->refCount() == 2);
143 void ImageResource::destroyDecodedDataIfPossible()
145 if (!hasClients() && !isLoading() && (!m_image || (m_image->hasOneRef() && m_image->isBitmapImage()))) {
148 } else if (m_image && !errorOccurred()) {
149 m_image->destroyDecodedData(true);
153 void ImageResource::allClientsRemoved()
155 m_pendingContainerSizeRequests.clear();
156 if (m_image && !errorOccurred())
157 m_image->resetAnimation();
158 Resource::allClientsRemoved();
161 pair<blink::Image*, float> ImageResource::brokenImage(float deviceScaleFactor)
163 if (deviceScaleFactor >= 2) {
164 DEFINE_STATIC_REF(blink::Image, brokenImageHiRes, (blink::Image::loadPlatformResource("missingImage@2x")));
165 return std::make_pair(brokenImageHiRes, 2);
168 DEFINE_STATIC_REF(blink::Image, brokenImageLoRes, (blink::Image::loadPlatformResource("missingImage")));
169 return std::make_pair(brokenImageLoRes, 1);
172 bool ImageResource::willPaintBrokenImage() const
174 return errorOccurred();
177 blink::Image* ImageResource::image()
179 ASSERT(!isPurgeable());
181 if (errorOccurred()) {
182 // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
183 // deviceScaleFactor from here. It is critical that callers use ImageResource::brokenImage()
184 // when they need the real, deviceScaleFactor-appropriate broken image icon.
185 return brokenImage(1).first;
189 return m_image.get();
191 return blink::Image::nullImage();
194 blink::Image* ImageResource::imageForRenderer(const RenderObject* renderer)
196 ASSERT(!isPurgeable());
198 if (errorOccurred()) {
199 // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
200 // deviceScaleFactor from here. It is critical that callers use ImageResource::brokenImage()
201 // when they need the real, deviceScaleFactor-appropriate broken image icon.
202 return brokenImage(1).first;
206 return blink::Image::nullImage();
208 if (m_image->isSVGImage()) {
209 blink::Image* image = m_svgImageCache->imageForRenderer(renderer);
210 if (image != blink::Image::nullImage())
214 return m_image.get();
217 void ImageResource::setContainerSizeForRenderer(const ImageResourceClient* renderer, const IntSize& containerSize, float containerZoom)
219 if (containerSize.isEmpty())
222 ASSERT(containerZoom);
224 m_pendingContainerSizeRequests.set(renderer, SizeAndZoom(containerSize, containerZoom));
227 if (!m_image->isSVGImage()) {
228 m_image->setContainerSize(containerSize);
232 m_svgImageCache->setContainerSizeForRenderer(renderer, containerSize, containerZoom);
235 bool ImageResource::usesImageContainerSize() const
238 return m_image->usesContainerSize();
243 bool ImageResource::imageHasRelativeWidth() const
246 return m_image->hasRelativeWidth();
251 bool ImageResource::imageHasRelativeHeight() const
254 return m_image->hasRelativeHeight();
259 LayoutSize ImageResource::imageSizeForRenderer(const RenderObject* renderer, float multiplier, SizeType sizeType)
261 ASSERT(!isPurgeable());
266 LayoutSize imageSize;
268 if (m_image->isBitmapImage() && (renderer && renderer->shouldRespectImageOrientation() == RespectImageOrientation))
269 imageSize = toBitmapImage(m_image.get())->sizeRespectingOrientation();
270 else if (m_image->isSVGImage() && sizeType == NormalSize)
271 imageSize = m_svgImageCache->imageSizeForRenderer(renderer);
273 imageSize = m_image->size();
275 if (multiplier == 1.0f)
278 // Don't let images that have a width/height >= 1 shrink below 1 when zoomed.
279 float widthScale = m_image->hasRelativeWidth() ? 1.0f : multiplier;
280 float heightScale = m_image->hasRelativeHeight() ? 1.0f : multiplier;
281 LayoutSize minimumSize(imageSize.width() > 0 ? 1 : 0, imageSize.height() > 0 ? 1 : 0);
282 imageSize.scale(widthScale, heightScale);
283 imageSize.clampToMinimumSize(minimumSize);
284 ASSERT(multiplier != 1.0f || (imageSize.width().fraction() == 0.0f && imageSize.height().fraction() == 0.0f));
288 void ImageResource::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
291 m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
294 void ImageResource::notifyObservers(const IntRect* changeRect)
296 ResourceClientWalker<ImageResourceClient> w(m_clients);
297 while (ImageResourceClient* c = w.next())
298 c->imageChanged(this, changeRect);
301 void ImageResource::clear()
305 m_pendingContainerSizeRequests.clear();
309 void ImageResource::setCustomAcceptHeader()
311 DEFINE_STATIC_LOCAL(const AtomicString, acceptWebP, ("image/webp,*/*;q=0.8", AtomicString::ConstructFromLiteral));
312 setAccept(acceptWebP);
315 inline void ImageResource::createImage()
317 // Create the image if it doesn't yet exist.
321 if (m_response.mimeType() == "image/svg+xml") {
322 RefPtr<SVGImage> svgImage = SVGImage::create(this);
323 m_svgImageCache = SVGImageCache::create(svgImage.get());
324 m_image = svgImage.release();
326 m_image = BitmapImage::create(this);
330 // Send queued container size requests.
331 if (m_image->usesContainerSize()) {
332 for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
333 setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
335 m_pendingContainerSizeRequests.clear();
339 inline void ImageResource::clearImage()
341 // If our Image has an observer, it's always us so we need to clear the back pointer
342 // before dropping our reference.
344 m_image->setImageObserver(0);
348 void ImageResource::appendData(const char* data, int length)
350 Resource::appendData(data, length);
351 if (!m_loadingMultipartContent)
355 void ImageResource::updateImage(bool allDataReceived)
357 TRACE_EVENT0("blink", "ImageResource::updateImage");
362 bool sizeAvailable = false;
364 // Have the image update its data from its internal buffer.
365 // It will not do anything now, but will delay decoding until
366 // queried for info (like size or specific image frames).
368 sizeAvailable = m_image->setData(m_data, allDataReceived);
370 // Go ahead and tell our observers to try to draw if we have either
371 // received all the data or the size is known. Each chunk from the
372 // network causes observers to repaint, which will force that chunk
374 if (sizeAvailable || allDataReceived) {
375 if (!m_image || m_image->isNull()) {
376 error(errorOccurred() ? status() : DecodeError);
377 if (memoryCache()->contains(this))
378 memoryCache()->remove(this);
382 // It would be nice to only redraw the decoded band of the image, but with the current design
383 // (decoding delayed until painting) that seems hard.
388 void ImageResource::updateBitmapImages(HashSet<ImageResource*>& images, bool redecodeImages)
390 for (HashSet<ImageResource*>::iterator it = images.begin(); it != images.end(); ++it) {
391 ImageResource* imageResource = *it;
392 if (!imageResource->hasImage() || imageResource->image()->isNull())
394 BitmapImage* image = toBitmapImage(imageResource->image());
396 image->resetDecoder();
397 imageResource->updateImage(image->isAllDataReceived());
401 void ImageResource::finishOnePart()
403 if (m_loadingMultipartContent)
406 if (m_loadingMultipartContent)
408 Resource::finishOnePart();
411 void ImageResource::error(Resource::Status status)
414 Resource::error(status);
418 void ImageResource::responseReceived(const ResourceResponse& response)
420 if (m_loadingMultipartContent && m_data)
422 else if (response.isMultipart())
423 m_loadingMultipartContent = true;
424 if (RuntimeEnabledFeatures::clientHintsDprEnabled()) {
425 m_devicePixelRatioHeaderValue = response.httpHeaderField("DPR").toFloat(&m_hasDevicePixelRatioHeaderValue);
426 if (!m_hasDevicePixelRatioHeaderValue || m_devicePixelRatioHeaderValue <= 0.0) {
427 m_devicePixelRatioHeaderValue = 1.0;
428 m_hasDevicePixelRatioHeaderValue = false;
431 Resource::responseReceived(response);
434 void ImageResource::decodedSizeChanged(const blink::Image* image, int delta)
436 if (!image || image != m_image)
439 setDecodedSize(decodedSize() + delta);
442 void ImageResource::didDraw(const blink::Image* image)
444 if (!image || image != m_image)
446 // decodedSize() == 0 indicates that the image is decoded into DiscardableMemory,
447 // not in MemoryCache. So we don't need to call Resource::didAccessDecodedData()
448 // to update MemoryCache.
449 if (decodedSize() != 0)
450 Resource::didAccessDecodedData();
453 bool ImageResource::shouldPauseAnimation(const blink::Image* image)
455 if (!image || image != m_image)
458 ResourceClientWalker<ImageResourceClient> w(m_clients);
459 while (ImageResourceClient* c = w.next()) {
460 if (c->willRenderImage(this))
467 void ImageResource::animationAdvanced(const blink::Image* image)
469 if (!image || image != m_image)
474 void ImageResource::changedInRect(const blink::Image* image, const IntRect& rect)
476 if (!image || image != m_image)
478 notifyObservers(&rect);
481 bool ImageResource::currentFrameKnownToBeOpaque(const RenderObject* renderer)
483 blink::Image* image = imageForRenderer(renderer);
484 if (image->isBitmapImage())
485 image->nativeImageForCurrentFrame(); // force decode
486 return image->currentFrameKnownToBeOpaque();
489 bool ImageResource::isAccessAllowed(SecurityOrigin* securityOrigin)
491 if (!image()->currentFrameHasSingleSecurityOrigin())
493 if (passesAccessControlCheck(securityOrigin))
495 return !securityOrigin->taintsCanvas(response().url());