Replace SVG bitmap cache with directly-rendered SVG
[WebKit-https.git] / Source / WebCore / loader / cache / CachedImage.cpp
1 /*
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.
7
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.
12
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.
17
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.
22 */
23
24 #include "config.h"
25 #include "CachedImage.h"
26
27 #include "BitmapImage.h"
28 #include "CachedImageClient.h"
29 #include "CachedResourceClient.h"
30 #include "CachedResourceClientWalker.h"
31 #include "CachedResourceLoader.h"
32 #include "FrameLoaderClient.h"
33 #include "FrameLoaderTypes.h"
34 #include "FrameView.h"
35 #include "MemoryCache.h"
36 #include "Page.h"
37 #include "RenderObject.h"
38 #include "ResourceBuffer.h"
39 #include "Settings.h"
40 #include "SubresourceLoader.h"
41 #include <wtf/CurrentTime.h>
42 #include <wtf/MemoryInstrumentationHashMap.h>
43 #include <wtf/MemoryObjectInfo.h>
44 #include <wtf/StdLibExtras.h>
45 #include <wtf/Vector.h>
46
47 #if USE(CG)
48 #include "PDFDocumentImage.h"
49 #endif
50
51 #if ENABLE(SVG)
52 #include "SVGImage.h"
53 #endif
54
55 using std::max;
56
57 namespace WebCore {
58
59 CachedImage::CachedImage(const ResourceRequest& resourceRequest)
60     : CachedResource(resourceRequest, ImageResource)
61     , m_image(0)
62     , m_shouldPaintBrokenImage(true)
63 {
64     setStatus(Unknown);
65 }
66
67 CachedImage::CachedImage(Image* image)
68     : CachedResource(ResourceRequest(), ImageResource)
69     , m_image(image)
70     , m_shouldPaintBrokenImage(true)
71 {
72     setStatus(Cached);
73     setLoading(false);
74 }
75
76 CachedImage::~CachedImage()
77 {
78     clearImage();
79 }
80
81 void CachedImage::load(CachedResourceLoader* cachedResourceLoader, const ResourceLoaderOptions& options)
82 {
83     if (!cachedResourceLoader || cachedResourceLoader->autoLoadImages())
84         CachedResource::load(cachedResourceLoader, options);
85     else
86         setLoading(false);
87 }
88
89 void CachedImage::didAddClient(CachedResourceClient* c)
90 {
91     if (m_data && !m_image && !errorOccurred()) {
92         createImage();
93         m_image->setData(m_data->sharedBuffer(), true);
94     }
95     
96     ASSERT(c->resourceClientType() == CachedImageClient::expectedType());
97     if (m_image && !m_image->isNull())
98         static_cast<CachedImageClient*>(c)->imageChanged(this);
99
100     CachedResource::didAddClient(c);
101 }
102
103 void CachedImage::didRemoveClient(CachedResourceClient* c)
104 {
105     ASSERT(c);
106     ASSERT(c->resourceClientType() == CachedImageClient::expectedType());
107
108     m_pendingContainerSizeRequests.remove(static_cast<CachedImageClient*>(c));
109 #if ENABLE(SVG)
110     if (m_svgImageCache)
111         m_svgImageCache->removeClientFromCache(static_cast<CachedImageClient*>(c));
112 #endif
113
114     CachedResource::didRemoveClient(c);
115 }
116
117 void CachedImage::switchClientsToRevalidatedResource()
118 {
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 CachedResource::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         CachedResource::switchClientsToRevalidatedResource();
128         CachedImage* revalidatedCachedImage = static_cast<CachedImage*>(resourceToRevalidate());
129         for (ContainerSizeRequests::iterator it = switchContainerSizeRequests.begin(); it != switchContainerSizeRequests.end(); ++it)
130             revalidatedCachedImage->setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
131         return;
132     }
133
134     CachedResource::switchClientsToRevalidatedResource();
135 }
136
137 void CachedImage::allClientsRemoved()
138 {
139     m_pendingContainerSizeRequests.clear();
140     if (m_image && !errorOccurred())
141         m_image->resetAnimation();
142 }
143
144 pair<Image*, float> CachedImage::brokenImage(float deviceScaleFactor) const
145 {
146     if (deviceScaleFactor >= 2) {
147         DEFINE_STATIC_LOCAL(Image*, brokenImageHiRes, (Image::loadPlatformResource("missingImage@2x").leakRef()));
148         return std::make_pair(brokenImageHiRes, 2);
149     }
150
151     DEFINE_STATIC_LOCAL(Image*, brokenImageLoRes, (Image::loadPlatformResource("missingImage").leakRef()));
152     return std::make_pair(brokenImageLoRes, 1);
153 }
154
155 bool CachedImage::willPaintBrokenImage() const
156 {
157     return errorOccurred() && m_shouldPaintBrokenImage;
158 }
159
160 #if ENABLE(SVG)
161 inline Image* CachedImage::lookupOrCreateImageForRenderer(const RenderObject* renderer)
162 {
163     if (!m_image)
164         return 0;
165     if (!m_image->isSVGImage())
166         return m_image.get();
167     Image* useImage = m_svgImageCache->imageForRenderer(renderer);
168     if (useImage == Image::nullImage())
169         return m_image.get();
170     return useImage;
171 }
172 #else
173 inline Image* CachedImage::lookupOrCreateImageForRenderer(const RenderObject*)
174 {
175     return m_image.get();
176 }
177 #endif
178
179 Image* CachedImage::image()
180 {
181     ASSERT(!isPurgeable());
182
183     if (errorOccurred() && m_shouldPaintBrokenImage) {
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 CachedImage::brokenImage() 
186         // when they need the real, deviceScaleFactor-appropriate broken image icon. 
187         return brokenImage(1).first;
188     }
189
190     if (m_image)
191         return m_image.get();
192
193     return Image::nullImage();
194 }
195
196 Image* CachedImage::imageForRenderer(const RenderObject* renderer)
197 {
198     ASSERT(!isPurgeable());
199
200     if (errorOccurred() && m_shouldPaintBrokenImage) {
201         // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
202         // deviceScaleFactor from here. It is critical that callers use CachedImage::brokenImage() 
203         // when they need the real, deviceScaleFactor-appropriate broken image icon. 
204         return brokenImage(1).first;
205     }
206
207     if (m_image)
208         return lookupOrCreateImageForRenderer(renderer);
209
210     return Image::nullImage();
211 }
212
213 void CachedImage::setContainerSizeForRenderer(const CachedImageClient* renderer, const IntSize& containerSize, float containerZoom)
214 {
215     if (containerSize.isEmpty())
216         return;
217     ASSERT(renderer);
218     ASSERT(containerZoom);
219     if (!m_image) {
220         m_pendingContainerSizeRequests.set(renderer, SizeAndZoom(containerSize, containerZoom));
221         return;
222     }
223 #if ENABLE(SVG)
224     if (!m_image->isSVGImage()) {
225         m_image->setContainerSize(containerSize);
226         return;
227     }
228
229     m_svgImageCache->setContainerSizeForRenderer(renderer, containerSize, containerZoom);
230 #else
231     UNUSED_PARAM(containerZoom);
232     m_image->setContainerSize(containerSize);
233 #endif
234 }
235
236 bool CachedImage::usesImageContainerSize() const
237 {
238     if (m_image)
239         return m_image->usesContainerSize();
240
241     return false;
242 }
243
244 bool CachedImage::imageHasRelativeWidth() const
245 {
246     if (m_image)
247         return m_image->hasRelativeWidth();
248
249     return false;
250 }
251
252 bool CachedImage::imageHasRelativeHeight() const
253 {
254     if (m_image)
255         return m_image->hasRelativeHeight();
256
257     return false;
258 }
259
260 LayoutSize CachedImage::imageSizeForRenderer(const RenderObject* renderer, float multiplier)
261 {
262     ASSERT(!isPurgeable());
263
264     if (!m_image)
265         return IntSize();
266
267     LayoutSize imageSize;
268
269     if (m_image->isBitmapImage() && (renderer && renderer->shouldRespectImageOrientation() == RespectImageOrientation))
270         imageSize = static_cast<BitmapImage*>(m_image.get())->sizeRespectingOrientation();
271 #if ENABLE(SVG)
272     else if (m_image->isSVGImage()) {
273         imageSize = m_svgImageCache->imageSizeForRenderer(renderer);
274     }
275 #endif
276     else
277         imageSize = m_image->size();
278
279     if (multiplier == 1.0f)
280         return imageSize;
281         
282     // Don't let images that have a width/height >= 1 shrink below 1 when zoomed.
283     float widthScale = m_image->hasRelativeWidth() ? 1.0f : multiplier;
284     float heightScale = m_image->hasRelativeHeight() ? 1.0f : multiplier;
285     LayoutSize minimumSize(imageSize.width() > 0 ? 1 : 0, imageSize.height() > 0 ? 1 : 0);
286     imageSize.scale(widthScale, heightScale);
287     imageSize.clampToMinimumSize(minimumSize);
288     ASSERT(multiplier != 1.0f || (imageSize.width().fraction() == 0.0f && imageSize.height().fraction() == 0.0f));
289     return imageSize;
290 }
291
292 void CachedImage::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
293 {
294     if (m_image)
295         m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
296 }
297
298 void CachedImage::notifyObservers(const IntRect* changeRect)
299 {
300     CachedResourceClientWalker<CachedImageClient> w(m_clients);
301     while (CachedImageClient* c = w.next())
302         c->imageChanged(this, changeRect);
303 }
304
305 void CachedImage::checkShouldPaintBrokenImage()
306 {
307     if (!m_loader || m_loader->reachedTerminalState())
308         return;
309
310     m_shouldPaintBrokenImage = m_loader->frameLoader()->client()->shouldPaintBrokenImage(m_resourceRequest.url());
311 }
312
313 void CachedImage::clear()
314 {
315     destroyDecodedData();
316     clearImage();
317     m_pendingContainerSizeRequests.clear();
318     setEncodedSize(0);
319 }
320
321 inline void CachedImage::createImage()
322 {
323     // Create the image if it doesn't yet exist.
324     if (m_image)
325         return;
326 #if USE(CG) && !USE(WEBKIT_IMAGE_DECODERS)
327     else if (m_response.mimeType() == "application/pdf")
328         m_image = PDFDocumentImage::create();
329 #endif
330 #if ENABLE(SVG)
331     else if (m_response.mimeType() == "image/svg+xml") {
332         RefPtr<SVGImage> svgImage = SVGImage::create(this);
333         m_svgImageCache = SVGImageCache::create(svgImage.get());
334         m_image = svgImage.release();
335     }
336 #endif
337     else
338         m_image = BitmapImage::create(this);
339
340     if (m_image) {
341         // Send queued container size requests.
342         if (m_image->usesContainerSize()) {
343             for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
344                 setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
345         }
346         m_pendingContainerSizeRequests.clear();
347     }
348 }
349
350 inline void CachedImage::clearImage()
351 {
352     // If our Image has an observer, it's always us so we need to clear the back pointer
353     // before dropping our reference.
354     if (m_image)
355         m_image->setImageObserver(0);
356     m_image.clear();
357 }
358
359 size_t CachedImage::maximumDecodedImageSize()
360 {
361     if (!m_loader || m_loader->reachedTerminalState())
362         return 0;
363     Settings* settings = m_loader->frameLoader()->frame()->settings();
364     return settings ? settings->maximumDecodedImageSize() : 0;
365 }
366
367 void CachedImage::data(PassRefPtr<ResourceBuffer> data, bool allDataReceived)
368 {
369     m_data = data;
370
371     if (m_data)
372         createImage();
373
374     bool sizeAvailable = false;
375
376     // Have the image update its data from its internal buffer.
377     // It will not do anything now, but will delay decoding until 
378     // queried for info (like size or specific image frames).
379     if (m_image)
380         sizeAvailable = m_image->setData(m_data ? m_data->sharedBuffer() : 0, allDataReceived);
381
382     // Go ahead and tell our observers to try to draw if we have either
383     // received all the data or the size is known.  Each chunk from the
384     // network causes observers to repaint, which will force that chunk
385     // to decode.
386     if (sizeAvailable || allDataReceived) {
387         size_t maxDecodedImageSize = maximumDecodedImageSize();
388         IntSize s = m_image ? m_image->size() : IntSize();
389         size_t estimatedDecodedImageSize = s.width() * s.height() * 4; // no overflow check
390         if (!m_image || m_image->isNull() || (maxDecodedImageSize > 0 && estimatedDecodedImageSize > maxDecodedImageSize)) {
391             error(errorOccurred() ? status() : DecodeError);
392             if (inCache())
393                 memoryCache()->remove(this);
394             return;
395         }
396         
397         // It would be nice to only redraw the decoded band of the image, but with the current design
398         // (decoding delayed until painting) that seems hard.
399         notifyObservers();
400
401         if (m_image)
402             setEncodedSize(m_image->data() ? m_image->data()->size() : 0);
403     }
404     
405     if (allDataReceived) {
406         setLoading(false);
407         checkNotify();
408     }
409 }
410
411 void CachedImage::error(CachedResource::Status status)
412 {
413     checkShouldPaintBrokenImage();
414     clear();
415     CachedResource::error(status);
416     notifyObservers();
417 }
418
419 void CachedImage::responseReceived(const ResourceResponse& response)
420 {
421     if (!m_response.isNull())
422         clear();
423     CachedResource::responseReceived(response);
424 }
425
426 void CachedImage::destroyDecodedData()
427 {
428     bool canDeleteImage = !m_image || (m_image->hasOneRef() && m_image->isBitmapImage());
429     if (isSafeToMakePurgeable() && canDeleteImage && !isLoading()) {
430         // Image refs the data buffer so we should not make it purgeable while the image is alive. 
431         // Invoking addClient() will reconstruct the image object.
432         m_image = 0;
433         setDecodedSize(0);
434         if (!MemoryCache::shouldMakeResourcePurgeableOnEviction())
435             makePurgeable(true);
436     } else if (m_image && !errorOccurred())
437         m_image->destroyDecodedData();
438 }
439
440 void CachedImage::decodedSizeChanged(const Image* image, int delta)
441 {
442     if (!image || image != m_image)
443         return;
444     
445     setDecodedSize(decodedSize() + delta);
446 }
447
448 void CachedImage::didDraw(const Image* image)
449 {
450     if (!image || image != m_image)
451         return;
452     
453     double timeStamp = FrameView::currentPaintTimeStamp();
454     if (!timeStamp) // If didDraw is called outside of a Frame paint.
455         timeStamp = currentTime();
456     
457     CachedResource::didAccessDecodedData(timeStamp);
458 }
459
460 bool CachedImage::shouldPauseAnimation(const Image* image)
461 {
462     if (!image || image != m_image)
463         return false;
464     
465     CachedResourceClientWalker<CachedImageClient> w(m_clients);
466     while (CachedImageClient* c = w.next()) {
467         if (c->willRenderImage(this))
468             return false;
469     }
470
471     return true;
472 }
473
474 void CachedImage::animationAdvanced(const Image* image)
475 {
476     if (!image || image != m_image)
477         return;
478     notifyObservers();
479 }
480
481 void CachedImage::changedInRect(const Image* image, const IntRect& rect)
482 {
483     if (!image || image != m_image)
484         return;
485     notifyObservers(&rect);
486 }
487
488 void CachedImage::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
489 {
490     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CachedResourceImage);
491     memoryObjectInfo->setClassName("CachedImage");
492     CachedResource::reportMemoryUsage(memoryObjectInfo);
493     info.addMember(m_pendingContainerSizeRequests, "pendingContainerSizeRequests");
494     info.addMember(m_image, "m_image");
495 #if ENABLE(SVG)
496     info.addMember(m_svgImageCache, "svgImageCache");
497 #endif
498 }
499
500 bool CachedImage::currentFrameKnownToBeOpaque(const RenderObject* renderer)
501 {
502     Image* image = imageForRenderer(renderer);
503     if (image->isBitmapImage())
504         image->nativeImageForCurrentFrame(); // force decode
505     return image->currentFrameKnownToBeOpaque();
506 }
507
508 } // namespace WebCore