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()
69 void ImageResource::load(ResourceFetcher* fetcher, const ResourceLoaderOptions& options)
71 if (!fetcher || fetcher->autoLoadImages())
72 Resource::load(fetcher, options);
77 void ImageResource::didAddClient(ResourceClient* c)
79 if (m_data && !m_image && !errorOccurred()) {
81 m_image->setData(m_data, true);
84 ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
85 if (m_image && !m_image->isNull())
86 static_cast<ImageResourceClient*>(c)->imageChanged(this);
88 Resource::didAddClient(c);
91 void ImageResource::didRemoveClient(ResourceClient* c)
94 ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
96 m_pendingContainerSizeRequests.remove(static_cast<ImageResourceClient*>(c));
98 m_svgImageCache->removeClientFromCache(static_cast<ImageResourceClient*>(c));
100 Resource::didRemoveClient(c);
103 void ImageResource::switchClientsToRevalidatedResource()
105 ASSERT(resourceToRevalidate());
106 ASSERT(resourceToRevalidate()->isImage());
107 // Pending container size requests need to be transferred to the revalidated resource.
108 if (!m_pendingContainerSizeRequests.isEmpty()) {
109 // A copy of pending size requests is needed as they are deleted during Resource::switchClientsToRevalidateResouce().
110 ContainerSizeRequests switchContainerSizeRequests;
111 for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
112 switchContainerSizeRequests.set(it->key, it->value);
113 Resource::switchClientsToRevalidatedResource();
114 ImageResource* revalidatedImageResource = toImageResource(resourceToRevalidate());
115 for (ContainerSizeRequests::iterator it = switchContainerSizeRequests.begin(); it != switchContainerSizeRequests.end(); ++it)
116 revalidatedImageResource->setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
120 Resource::switchClientsToRevalidatedResource();
123 bool ImageResource::isSafeToUnlock() const
125 return !m_image || (m_image->hasOneRef() && m_image->isBitmapImage());
128 void ImageResource::destroyDecodedDataIfPossible()
130 if (isSafeToUnlock() && !hasClients() && !isLoading()) {
133 } else if (m_image && !errorOccurred()) {
134 m_image->destroyDecodedData(true);
138 void ImageResource::allClientsRemoved()
140 m_pendingContainerSizeRequests.clear();
141 if (m_image && !errorOccurred())
142 m_image->resetAnimation();
143 Resource::allClientsRemoved();
146 pair<WebCore::Image*, float> ImageResource::brokenImage(float deviceScaleFactor)
148 if (deviceScaleFactor >= 2) {
149 DEFINE_STATIC_REF(WebCore::Image, brokenImageHiRes, (WebCore::Image::loadPlatformResource("missingImage@2x")));
150 return std::make_pair(brokenImageHiRes, 2);
153 DEFINE_STATIC_REF(WebCore::Image, brokenImageLoRes, (WebCore::Image::loadPlatformResource("missingImage")));
154 return std::make_pair(brokenImageLoRes, 1);
157 bool ImageResource::willPaintBrokenImage() const
159 return errorOccurred();
162 WebCore::Image* ImageResource::image()
164 ASSERT(!isPurgeable());
166 if (errorOccurred()) {
167 // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
168 // deviceScaleFactor from here. It is critical that callers use ImageResource::brokenImage()
169 // when they need the real, deviceScaleFactor-appropriate broken image icon.
170 return brokenImage(1).first;
174 return m_image.get();
176 return WebCore::Image::nullImage();
179 WebCore::Image* ImageResource::imageForRenderer(const RenderObject* renderer)
181 ASSERT(!isPurgeable());
183 if (errorOccurred()) {
184 // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
185 // deviceScaleFactor from here. It is critical that callers use ImageResource::brokenImage()
186 // when they need the real, deviceScaleFactor-appropriate broken image icon.
187 return brokenImage(1).first;
191 return WebCore::Image::nullImage();
193 if (m_image->isSVGImage()) {
194 WebCore::Image* image = m_svgImageCache->imageForRenderer(renderer);
195 if (image != WebCore::Image::nullImage())
199 return m_image.get();
202 void ImageResource::setContainerSizeForRenderer(const ImageResourceClient* renderer, const IntSize& containerSize, float containerZoom)
204 if (containerSize.isEmpty())
207 ASSERT(containerZoom);
209 m_pendingContainerSizeRequests.set(renderer, SizeAndZoom(containerSize, containerZoom));
212 if (!m_image->isSVGImage()) {
213 m_image->setContainerSize(containerSize);
217 m_svgImageCache->setContainerSizeForRenderer(renderer, containerSize, containerZoom);
220 bool ImageResource::usesImageContainerSize() const
223 return m_image->usesContainerSize();
228 bool ImageResource::imageHasRelativeWidth() const
231 return m_image->hasRelativeWidth();
236 bool ImageResource::imageHasRelativeHeight() const
239 return m_image->hasRelativeHeight();
244 LayoutSize ImageResource::imageSizeForRenderer(const RenderObject* renderer, float multiplier, SizeType sizeType)
246 ASSERT(!isPurgeable());
251 LayoutSize imageSize;
253 if (m_image->isBitmapImage() && (renderer && renderer->shouldRespectImageOrientation() == RespectImageOrientation))
254 imageSize = toBitmapImage(m_image.get())->sizeRespectingOrientation();
255 else if (m_image->isSVGImage() && sizeType == NormalSize)
256 imageSize = m_svgImageCache->imageSizeForRenderer(renderer);
258 imageSize = m_image->size();
260 if (multiplier == 1.0f)
263 // Don't let images that have a width/height >= 1 shrink below 1 when zoomed.
264 float widthScale = m_image->hasRelativeWidth() ? 1.0f : multiplier;
265 float heightScale = m_image->hasRelativeHeight() ? 1.0f : multiplier;
266 LayoutSize minimumSize(imageSize.width() > 0 ? 1 : 0, imageSize.height() > 0 ? 1 : 0);
267 imageSize.scale(widthScale, heightScale);
268 imageSize.clampToMinimumSize(minimumSize);
269 ASSERT(multiplier != 1.0f || (imageSize.width().fraction() == 0.0f && imageSize.height().fraction() == 0.0f));
273 void ImageResource::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
276 m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
279 void ImageResource::notifyObservers(const IntRect* changeRect)
281 ResourceClientWalker<ImageResourceClient> w(m_clients);
282 while (ImageResourceClient* c = w.next())
283 c->imageChanged(this, changeRect);
286 void ImageResource::clear()
290 m_pendingContainerSizeRequests.clear();
294 void ImageResource::setCustomAcceptHeader()
296 DEFINE_STATIC_LOCAL(const AtomicString, acceptWebP, ("image/webp,*/*;q=0.8", AtomicString::ConstructFromLiteral));
297 setAccept(acceptWebP);
300 inline void ImageResource::createImage()
302 // Create the image if it doesn't yet exist.
306 if (m_response.mimeType() == "image/svg+xml") {
307 RefPtr<SVGImage> svgImage = SVGImage::create(this);
308 m_svgImageCache = SVGImageCache::create(svgImage.get());
309 m_image = svgImage.release();
311 m_image = BitmapImage::create(this);
315 // Send queued container size requests.
316 if (m_image->usesContainerSize()) {
317 for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
318 setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
320 m_pendingContainerSizeRequests.clear();
324 inline void ImageResource::clearImage()
326 // If our Image has an observer, it's always us so we need to clear the back pointer
327 // before dropping our reference.
329 m_image->setImageObserver(0);
333 void ImageResource::appendData(const char* data, int length)
335 Resource::appendData(data, length);
336 if (!m_loadingMultipartContent)
340 void ImageResource::updateImage(bool allDataReceived)
342 TRACE_EVENT0("webkit", "ImageResource::updateImage");
347 bool sizeAvailable = false;
349 // Have the image update its data from its internal buffer.
350 // It will not do anything now, but will delay decoding until
351 // queried for info (like size or specific image frames).
353 sizeAvailable = m_image->setData(m_data, allDataReceived);
355 // Go ahead and tell our observers to try to draw if we have either
356 // received all the data or the size is known. Each chunk from the
357 // network causes observers to repaint, which will force that chunk
359 if (sizeAvailable || allDataReceived) {
360 if (!m_image || m_image->isNull()) {
361 error(errorOccurred() ? status() : DecodeError);
363 memoryCache()->remove(this);
367 // It would be nice to only redraw the decoded band of the image, but with the current design
368 // (decoding delayed until painting) that seems hard.
373 void ImageResource::finishOnePart()
375 if (m_loadingMultipartContent)
378 if (m_loadingMultipartContent)
380 Resource::finishOnePart();
383 void ImageResource::error(Resource::Status status)
386 Resource::error(status);
390 void ImageResource::responseReceived(const ResourceResponse& response)
392 if (m_loadingMultipartContent && m_data)
394 else if (response.isMultipart())
395 m_loadingMultipartContent = true;
396 if (RuntimeEnabledFeatures::clientHintsDprEnabled()) {
397 m_devicePixelRatioHeaderValue = response.httpHeaderField("DPR").toFloat(&m_hasDevicePixelRatioHeaderValue);
398 if (!m_hasDevicePixelRatioHeaderValue || m_devicePixelRatioHeaderValue <= 0.0) {
399 m_devicePixelRatioHeaderValue = 1.0;
400 m_hasDevicePixelRatioHeaderValue = false;
403 Resource::responseReceived(response);
406 void ImageResource::decodedSizeChanged(const WebCore::Image* image, int delta)
408 if (!image || image != m_image)
411 setDecodedSize(decodedSize() + delta);
414 void ImageResource::didDraw(const WebCore::Image* image)
416 if (!image || image != m_image)
419 double timeStamp = FrameView::currentFrameTimeStamp();
420 if (!timeStamp) // If didDraw is called outside of a Frame paint.
421 timeStamp = currentTime();
423 Resource::didAccessDecodedData(timeStamp);
426 bool ImageResource::shouldPauseAnimation(const WebCore::Image* image)
428 if (!image || image != m_image)
431 ResourceClientWalker<ImageResourceClient> w(m_clients);
432 while (ImageResourceClient* c = w.next()) {
433 if (c->willRenderImage(this))
440 void ImageResource::animationAdvanced(const WebCore::Image* image)
442 if (!image || image != m_image)
447 void ImageResource::changedInRect(const WebCore::Image* image, const IntRect& rect)
449 if (!image || image != m_image)
451 notifyObservers(&rect);
454 bool ImageResource::currentFrameKnownToBeOpaque(const RenderObject* renderer)
456 WebCore::Image* image = imageForRenderer(renderer);
457 if (image->isBitmapImage())
458 image->nativeImageForCurrentFrame(); // force decode
459 return image->currentFrameKnownToBeOpaque();
462 bool ImageResource::isAccessAllowed(SecurityOrigin* securityOrigin)
464 if (!image()->currentFrameHasSingleSecurityOrigin())
466 if (passesAccessControlCheck(securityOrigin))
468 return !securityOrigin->taintsCanvas(response().url());
471 } // namespace WebCore