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/RuntimeEnabledFeatures.h"
36 #include "platform/SharedBuffer.h"
37 #include "platform/TraceEvent.h"
38 #include "platform/graphics/BitmapImage.h"
39 #include "wtf/CurrentTime.h"
40 #include "wtf/StdLibExtras.h"
41 #include "wtf/Vector.h"
45 ImageResource::ImageResource(const ResourceRequest& resourceRequest)
46 : Resource(resourceRequest, Image)
47 , m_devicePixelRatioHeaderValue(1.0)
49 , m_loadingMultipartContent(false)
50 , m_hasDevicePixelRatioHeaderValue(false)
53 setCustomAcceptHeader();
56 ImageResource::ImageResource(WebCore::Image* image)
57 : Resource(ResourceRequest(""), Image)
62 setCustomAcceptHeader();
65 ImageResource::ImageResource(const ResourceRequest& resourceRequest, WebCore::Image* image)
66 : Resource(resourceRequest, Image)
71 setCustomAcceptHeader();
74 ImageResource::~ImageResource()
79 void ImageResource::load(ResourceFetcher* fetcher, const ResourceLoaderOptions& options)
81 if (!fetcher || fetcher->autoLoadImages())
82 Resource::load(fetcher, options);
87 void ImageResource::didAddClient(ResourceClient* c)
89 if (m_data && !m_image && !errorOccurred()) {
91 m_image->setData(m_data, true);
94 ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
95 if (m_image && !m_image->isNull())
96 static_cast<ImageResourceClient*>(c)->imageChanged(this);
98 Resource::didAddClient(c);
101 void ImageResource::didRemoveClient(ResourceClient* c)
104 ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
106 m_pendingContainerSizeRequests.remove(static_cast<ImageResourceClient*>(c));
108 m_svgImageCache->removeClientFromCache(static_cast<ImageResourceClient*>(c));
110 Resource::didRemoveClient(c);
113 void ImageResource::switchClientsToRevalidatedResource()
115 ASSERT(resourceToRevalidate());
116 ASSERT(resourceToRevalidate()->isImage());
117 // Pending container size requests need to be transferred to the revalidated resource.
118 if (!m_pendingContainerSizeRequests.isEmpty()) {
119 // A copy of pending size requests is needed as they are deleted during Resource::switchClientsToRevalidateResouce().
120 ContainerSizeRequests switchContainerSizeRequests;
121 for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
122 switchContainerSizeRequests.set(it->key, it->value);
123 Resource::switchClientsToRevalidatedResource();
124 ImageResource* revalidatedImageResource = toImageResource(resourceToRevalidate());
125 for (ContainerSizeRequests::iterator it = switchContainerSizeRequests.begin(); it != switchContainerSizeRequests.end(); ++it)
126 revalidatedImageResource->setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
130 Resource::switchClientsToRevalidatedResource();
133 bool ImageResource::isSafeToUnlock() const
135 // Note that |m_image| holds a reference to |m_data| in addition to the one held by the Resource parent class.
136 return !m_image || (m_image->hasOneRef() && m_data->refCount() == 2);
139 void ImageResource::destroyDecodedDataIfPossible()
141 if (!hasClients() && !isLoading() && (!m_image || (m_image->hasOneRef() && m_image->isBitmapImage()))) {
144 } else if (m_image && !errorOccurred()) {
145 m_image->destroyDecodedData(true);
149 void ImageResource::allClientsRemoved()
151 m_pendingContainerSizeRequests.clear();
152 if (m_image && !errorOccurred())
153 m_image->resetAnimation();
154 Resource::allClientsRemoved();
157 pair<WebCore::Image*, float> ImageResource::brokenImage(float deviceScaleFactor)
159 if (deviceScaleFactor >= 2) {
160 DEFINE_STATIC_REF(WebCore::Image, brokenImageHiRes, (WebCore::Image::loadPlatformResource("missingImage@2x")));
161 return std::make_pair(brokenImageHiRes, 2);
164 DEFINE_STATIC_REF(WebCore::Image, brokenImageLoRes, (WebCore::Image::loadPlatformResource("missingImage")));
165 return std::make_pair(brokenImageLoRes, 1);
168 bool ImageResource::willPaintBrokenImage() const
170 return errorOccurred();
173 WebCore::Image* ImageResource::image()
175 ASSERT(!isPurgeable());
177 if (errorOccurred()) {
178 // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
179 // deviceScaleFactor from here. It is critical that callers use ImageResource::brokenImage()
180 // when they need the real, deviceScaleFactor-appropriate broken image icon.
181 return brokenImage(1).first;
185 return m_image.get();
187 return WebCore::Image::nullImage();
190 WebCore::Image* ImageResource::imageForRenderer(const RenderObject* renderer)
192 ASSERT(!isPurgeable());
194 if (errorOccurred()) {
195 // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
196 // deviceScaleFactor from here. It is critical that callers use ImageResource::brokenImage()
197 // when they need the real, deviceScaleFactor-appropriate broken image icon.
198 return brokenImage(1).first;
202 return WebCore::Image::nullImage();
204 if (m_image->isSVGImage()) {
205 WebCore::Image* image = m_svgImageCache->imageForRenderer(renderer);
206 if (image != WebCore::Image::nullImage())
210 return m_image.get();
213 void ImageResource::setContainerSizeForRenderer(const ImageResourceClient* renderer, const IntSize& containerSize, float containerZoom)
215 if (containerSize.isEmpty())
218 ASSERT(containerZoom);
220 m_pendingContainerSizeRequests.set(renderer, SizeAndZoom(containerSize, containerZoom));
223 if (!m_image->isSVGImage()) {
224 m_image->setContainerSize(containerSize);
228 m_svgImageCache->setContainerSizeForRenderer(renderer, containerSize, containerZoom);
231 bool ImageResource::usesImageContainerSize() const
234 return m_image->usesContainerSize();
239 bool ImageResource::imageHasRelativeWidth() const
242 return m_image->hasRelativeWidth();
247 bool ImageResource::imageHasRelativeHeight() const
250 return m_image->hasRelativeHeight();
255 LayoutSize ImageResource::imageSizeForRenderer(const RenderObject* renderer, float multiplier, SizeType sizeType)
257 ASSERT(!isPurgeable());
262 LayoutSize imageSize;
264 if (m_image->isBitmapImage() && (renderer && renderer->shouldRespectImageOrientation() == RespectImageOrientation))
265 imageSize = toBitmapImage(m_image.get())->sizeRespectingOrientation();
266 else if (m_image->isSVGImage() && sizeType == NormalSize)
267 imageSize = m_svgImageCache->imageSizeForRenderer(renderer);
269 imageSize = m_image->size();
271 if (multiplier == 1.0f)
274 // Don't let images that have a width/height >= 1 shrink below 1 when zoomed.
275 float widthScale = m_image->hasRelativeWidth() ? 1.0f : multiplier;
276 float heightScale = m_image->hasRelativeHeight() ? 1.0f : multiplier;
277 LayoutSize minimumSize(imageSize.width() > 0 ? 1 : 0, imageSize.height() > 0 ? 1 : 0);
278 imageSize.scale(widthScale, heightScale);
279 imageSize.clampToMinimumSize(minimumSize);
280 ASSERT(multiplier != 1.0f || (imageSize.width().fraction() == 0.0f && imageSize.height().fraction() == 0.0f));
284 void ImageResource::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
287 m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
290 void ImageResource::notifyObservers(const IntRect* changeRect)
292 ResourceClientWalker<ImageResourceClient> w(m_clients);
293 while (ImageResourceClient* c = w.next())
294 c->imageChanged(this, changeRect);
297 void ImageResource::clear()
301 m_pendingContainerSizeRequests.clear();
305 void ImageResource::setCustomAcceptHeader()
307 DEFINE_STATIC_LOCAL(const AtomicString, acceptWebP, ("image/webp,*/*;q=0.8", AtomicString::ConstructFromLiteral));
308 setAccept(acceptWebP);
311 inline void ImageResource::createImage()
313 // Create the image if it doesn't yet exist.
317 if (m_response.mimeType() == "image/svg+xml") {
318 RefPtr<SVGImage> svgImage = SVGImage::create(this);
319 m_svgImageCache = SVGImageCache::create(svgImage.get());
320 m_image = svgImage.release();
322 m_image = BitmapImage::create(this);
326 // Send queued container size requests.
327 if (m_image->usesContainerSize()) {
328 for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
329 setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
331 m_pendingContainerSizeRequests.clear();
335 inline void ImageResource::clearImage()
337 // If our Image has an observer, it's always us so we need to clear the back pointer
338 // before dropping our reference.
340 m_image->setImageObserver(0);
344 void ImageResource::appendData(const char* data, int length)
346 Resource::appendData(data, length);
347 if (!m_loadingMultipartContent)
351 void ImageResource::updateImage(bool allDataReceived)
353 TRACE_EVENT0("webkit", "ImageResource::updateImage");
358 bool sizeAvailable = false;
360 // Have the image update its data from its internal buffer.
361 // It will not do anything now, but will delay decoding until
362 // queried for info (like size or specific image frames).
364 sizeAvailable = m_image->setData(m_data, allDataReceived);
366 // Go ahead and tell our observers to try to draw if we have either
367 // received all the data or the size is known. Each chunk from the
368 // network causes observers to repaint, which will force that chunk
370 if (sizeAvailable || allDataReceived) {
371 if (!m_image || m_image->isNull()) {
372 error(errorOccurred() ? status() : DecodeError);
373 if (memoryCache()->contains(this))
374 memoryCache()->remove(this);
378 // It would be nice to only redraw the decoded band of the image, but with the current design
379 // (decoding delayed until painting) that seems hard.
384 void ImageResource::finishOnePart()
386 if (m_loadingMultipartContent)
389 if (m_loadingMultipartContent)
391 Resource::finishOnePart();
394 void ImageResource::error(Resource::Status status)
397 Resource::error(status);
401 void ImageResource::responseReceived(const ResourceResponse& response)
403 if (m_loadingMultipartContent && m_data)
405 else if (response.isMultipart())
406 m_loadingMultipartContent = true;
407 if (RuntimeEnabledFeatures::clientHintsDprEnabled()) {
408 m_devicePixelRatioHeaderValue = response.httpHeaderField("DPR").toFloat(&m_hasDevicePixelRatioHeaderValue);
409 if (!m_hasDevicePixelRatioHeaderValue || m_devicePixelRatioHeaderValue <= 0.0) {
410 m_devicePixelRatioHeaderValue = 1.0;
411 m_hasDevicePixelRatioHeaderValue = false;
414 Resource::responseReceived(response);
417 void ImageResource::decodedSizeChanged(const WebCore::Image* image, int delta)
419 if (!image || image != m_image)
422 setDecodedSize(decodedSize() + delta);
425 void ImageResource::didDraw(const WebCore::Image* image)
427 if (!image || image != m_image)
429 Resource::didAccessDecodedData();
432 bool ImageResource::shouldPauseAnimation(const WebCore::Image* image)
434 if (!image || image != m_image)
437 ResourceClientWalker<ImageResourceClient> w(m_clients);
438 while (ImageResourceClient* c = w.next()) {
439 if (c->willRenderImage(this))
446 void ImageResource::animationAdvanced(const WebCore::Image* image)
448 if (!image || image != m_image)
453 void ImageResource::changedInRect(const WebCore::Image* image, const IntRect& rect)
455 if (!image || image != m_image)
457 notifyObservers(&rect);
460 bool ImageResource::currentFrameKnownToBeOpaque(const RenderObject* renderer)
462 WebCore::Image* image = imageForRenderer(renderer);
463 if (image->isBitmapImage())
464 image->nativeImageForCurrentFrame(); // force decode
465 return image->currentFrameKnownToBeOpaque();
468 bool ImageResource::isAccessAllowed(SecurityOrigin* securityOrigin)
470 if (!image()->currentFrameHasSingleSecurityOrigin())
472 if (passesAccessControlCheck(securityOrigin))
474 return !securityOrigin->taintsCanvas(response().url());
477 } // namespace WebCore