Web Inspector: Native Memory Instrumentation: fix instrumentation for already instrum...
[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::allClientsRemoved()
118 {
119     m_pendingContainerSizeRequests.clear();
120     if (m_image && !errorOccurred())
121         m_image->resetAnimation();
122 }
123
124 pair<Image*, float> CachedImage::brokenImage(float deviceScaleFactor) const
125 {
126     if (deviceScaleFactor >= 2) {
127         DEFINE_STATIC_LOCAL(Image*, brokenImageHiRes, (Image::loadPlatformResource("missingImage@2x").leakRef()));
128         return std::make_pair(brokenImageHiRes, 2);
129     }
130
131     DEFINE_STATIC_LOCAL(Image*, brokenImageLoRes, (Image::loadPlatformResource("missingImage").leakRef()));
132     return std::make_pair(brokenImageLoRes, 1);
133 }
134
135 bool CachedImage::willPaintBrokenImage() const
136 {
137     return errorOccurred() && m_shouldPaintBrokenImage;
138 }
139
140 #if ENABLE(SVG)
141 inline Image* CachedImage::lookupOrCreateImageForRenderer(const RenderObject* renderer)
142 {
143     if (!m_image)
144         return 0;
145     if (!m_image->isSVGImage())
146         return m_image.get();
147     Image* useImage = m_svgImageCache->lookupOrCreateBitmapImageForRenderer(renderer);
148     if (useImage == Image::nullImage())
149         return m_image.get();
150     return useImage;
151 }
152 #else
153 inline Image* CachedImage::lookupOrCreateImageForRenderer(const RenderObject*)
154 {
155     return m_image.get();
156 }
157 #endif
158
159 Image* CachedImage::image()
160 {
161     ASSERT(!isPurgeable());
162
163     if (errorOccurred() && m_shouldPaintBrokenImage) {
164         // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
165         // deviceScaleFactor from here. It is critical that callers use CachedImage::brokenImage() 
166         // when they need the real, deviceScaleFactor-appropriate broken image icon. 
167         return brokenImage(1).first;
168     }
169
170     if (m_image)
171         return m_image.get();
172
173     return Image::nullImage();
174 }
175
176 Image* CachedImage::imageForRenderer(const RenderObject* renderer)
177 {
178     ASSERT(!isPurgeable());
179
180     if (errorOccurred() && m_shouldPaintBrokenImage) {
181         // Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
182         // deviceScaleFactor from here. It is critical that callers use CachedImage::brokenImage() 
183         // when they need the real, deviceScaleFactor-appropriate broken image icon. 
184         return brokenImage(1).first;
185     }
186
187     if (m_image)
188         return lookupOrCreateImageForRenderer(renderer);
189
190     return Image::nullImage();
191 }
192
193 void CachedImage::setContainerSizeForRenderer(const CachedImageClient* renderer, const IntSize& containerSize, float containerZoom)
194 {
195     if (containerSize.isEmpty())
196         return;
197     ASSERT(renderer);
198     if (!m_image) {
199         m_pendingContainerSizeRequests.set(renderer, SizeAndZoom(containerSize, containerZoom));
200         return;
201     }
202 #if ENABLE(SVG)
203     if (!m_image->isSVGImage()) {
204         m_image->setContainerSize(containerSize);
205         return;
206     }
207
208     m_svgImageCache->setRequestedSizeAndScales(renderer, SVGImageCache::SizeAndScales(containerSize, containerZoom));
209 #else
210     UNUSED_PARAM(containerZoom);
211     m_image->setContainerSize(containerSize);
212 #endif
213 }
214
215 bool CachedImage::usesImageContainerSize() const
216 {
217     if (m_image)
218         return m_image->usesContainerSize();
219
220     return false;
221 }
222
223 bool CachedImage::imageHasRelativeWidth() const
224 {
225     if (m_image)
226         return m_image->hasRelativeWidth();
227
228     return false;
229 }
230
231 bool CachedImage::imageHasRelativeHeight() const
232 {
233     if (m_image)
234         return m_image->hasRelativeHeight();
235
236     return false;
237 }
238
239 LayoutSize CachedImage::imageSizeForRenderer(const RenderObject* renderer, float multiplier)
240 {
241     ASSERT(!isPurgeable());
242
243     if (!m_image)
244         return IntSize();
245
246     LayoutSize imageSize;
247
248     if (m_image->isBitmapImage() && (renderer && renderer->shouldRespectImageOrientation() == RespectImageOrientation))
249         imageSize = static_cast<BitmapImage*>(m_image.get())->sizeRespectingOrientation();
250     else
251         imageSize = m_image->size();
252
253 #if ENABLE(SVG)
254     if (m_image->isSVGImage()) {
255         SVGImageCache::SizeAndScales sizeAndScales = m_svgImageCache->requestedSizeAndScales(renderer);
256         if (!sizeAndScales.size.isEmpty()) {
257             float scale = sizeAndScales.scale;
258             if (!scale) {
259                 Page* page = renderer->document()->page();
260                 scale = page->deviceScaleFactor() * page->pageScaleFactor();
261             }
262
263             imageSize.setWidth(scale * sizeAndScales.size.width() / sizeAndScales.zoom);
264             imageSize.setHeight(scale * sizeAndScales.size.height() / sizeAndScales.zoom);
265         }
266     }
267 #endif
268
269     if (multiplier == 1.0f)
270         return imageSize;
271         
272     // Don't let images that have a width/height >= 1 shrink below 1 when zoomed.
273     float widthScale = m_image->hasRelativeWidth() ? 1.0f : multiplier;
274     float heightScale = m_image->hasRelativeHeight() ? 1.0f : multiplier;
275     LayoutSize minimumSize(imageSize.width() > 0 ? 1 : 0, imageSize.height() > 0 ? 1 : 0);
276     imageSize.scale(widthScale, heightScale);
277     imageSize.clampToMinimumSize(minimumSize);
278     ASSERT(multiplier != 1.0f || (imageSize.width().fraction() == 0.0f && imageSize.height().fraction() == 0.0f));
279     return imageSize;
280 }
281
282 void CachedImage::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
283 {
284     if (m_image)
285         m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
286 }
287
288 void CachedImage::notifyObservers(const IntRect* changeRect)
289 {
290     CachedResourceClientWalker<CachedImageClient> w(m_clients);
291     while (CachedImageClient* c = w.next())
292         c->imageChanged(this, changeRect);
293 }
294
295 void CachedImage::checkShouldPaintBrokenImage()
296 {
297     if (!m_loader || m_loader->reachedTerminalState())
298         return;
299
300     m_shouldPaintBrokenImage = m_loader->frameLoader()->client()->shouldPaintBrokenImage(m_resourceRequest.url());
301 }
302
303 void CachedImage::clear()
304 {
305     destroyDecodedData();
306 #if ENABLE(SVG)
307     m_svgImageCache.clear();
308 #endif
309     clearImage();
310     m_pendingContainerSizeRequests.clear();
311     setEncodedSize(0);
312 }
313
314 inline void CachedImage::createImage()
315 {
316     // Create the image if it doesn't yet exist.
317     if (m_image)
318         return;
319 #if USE(CG) && !USE(WEBKIT_IMAGE_DECODERS)
320     else if (m_response.mimeType() == "application/pdf")
321         m_image = PDFDocumentImage::create();
322 #endif
323 #if ENABLE(SVG)
324     else if (m_response.mimeType() == "image/svg+xml") {
325         RefPtr<SVGImage> svgImage = SVGImage::create(this);
326         m_svgImageCache = SVGImageCache::create(svgImage.get());
327         m_image = svgImage.release();
328     }
329 #endif
330     else
331         m_image = BitmapImage::create(this);
332
333     if (m_image) {
334         // Send queued container size requests.
335         if (m_image->usesContainerSize()) {
336             for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
337                 setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
338         }
339         m_pendingContainerSizeRequests.clear();
340     }
341 }
342
343 inline void CachedImage::clearImage()
344 {
345     // If our Image has an observer, it's always us so we need to clear the back pointer
346     // before dropping our reference.
347     if (m_image)
348         m_image->setImageObserver(0);
349     m_image.clear();
350 }
351
352 size_t CachedImage::maximumDecodedImageSize()
353 {
354     if (!m_loader || m_loader->reachedTerminalState())
355         return 0;
356     Settings* settings = m_loader->frameLoader()->frame()->settings();
357     return settings ? settings->maximumDecodedImageSize() : 0;
358 }
359
360 void CachedImage::data(PassRefPtr<ResourceBuffer> data, bool allDataReceived)
361 {
362     m_data = data;
363
364     if (m_data)
365         createImage();
366
367     bool sizeAvailable = false;
368
369     // Have the image update its data from its internal buffer.
370     // It will not do anything now, but will delay decoding until 
371     // queried for info (like size or specific image frames).
372     if (m_image)
373         sizeAvailable = m_image->setData(m_data ? m_data->sharedBuffer() : 0, allDataReceived);
374
375     // Go ahead and tell our observers to try to draw if we have either
376     // received all the data or the size is known.  Each chunk from the
377     // network causes observers to repaint, which will force that chunk
378     // to decode.
379     if (sizeAvailable || allDataReceived) {
380         size_t maxDecodedImageSize = maximumDecodedImageSize();
381         IntSize s = m_image ? m_image->size() : IntSize();
382         size_t estimatedDecodedImageSize = s.width() * s.height() * 4; // no overflow check
383         if (!m_image || m_image->isNull() || (maxDecodedImageSize > 0 && estimatedDecodedImageSize > maxDecodedImageSize)) {
384             error(errorOccurred() ? status() : DecodeError);
385             if (inCache())
386                 memoryCache()->remove(this);
387             return;
388         }
389         
390         // It would be nice to only redraw the decoded band of the image, but with the current design
391         // (decoding delayed until painting) that seems hard.
392         notifyObservers();
393
394         if (m_image)
395             setEncodedSize(m_image->data() ? m_image->data()->size() : 0);
396     }
397     
398     if (allDataReceived) {
399         setLoading(false);
400         checkNotify();
401     }
402 }
403
404 void CachedImage::error(CachedResource::Status status)
405 {
406     checkShouldPaintBrokenImage();
407     clear();
408     CachedResource::error(status);
409     notifyObservers();
410 }
411
412 void CachedImage::responseReceived(const ResourceResponse& response)
413 {
414     if (!m_response.isNull())
415         clear();
416     CachedResource::responseReceived(response);
417 }
418
419 void CachedImage::destroyDecodedData()
420 {
421     bool canDeleteImage = !m_image || (m_image->hasOneRef() && m_image->isBitmapImage());
422     if (isSafeToMakePurgeable() && canDeleteImage && !isLoading()) {
423         // Image refs the data buffer so we should not make it purgeable while the image is alive. 
424         // Invoking addClient() will reconstruct the image object.
425         m_image = 0;
426         setDecodedSize(0);
427         if (!MemoryCache::shouldMakeResourcePurgeableOnEviction())
428             makePurgeable(true);
429     } else if (m_image && !errorOccurred())
430         m_image->destroyDecodedData();
431 }
432
433 void CachedImage::decodedSizeChanged(const Image* image, int delta)
434 {
435     if (!image || image != m_image)
436         return;
437     
438     setDecodedSize(decodedSize() + delta);
439 }
440
441 void CachedImage::didDraw(const Image* image)
442 {
443     if (!image || image != m_image)
444         return;
445     
446     double timeStamp = FrameView::currentPaintTimeStamp();
447     if (!timeStamp) // If didDraw is called outside of a Frame paint.
448         timeStamp = currentTime();
449     
450     CachedResource::didAccessDecodedData(timeStamp);
451 }
452
453 bool CachedImage::shouldPauseAnimation(const Image* image)
454 {
455     if (!image || image != m_image)
456         return false;
457     
458     CachedResourceClientWalker<CachedImageClient> w(m_clients);
459     while (CachedImageClient* c = w.next()) {
460         if (c->willRenderImage(this))
461             return false;
462     }
463
464     return true;
465 }
466
467 void CachedImage::animationAdvanced(const Image* image)
468 {
469     if (!image || image != m_image)
470         return;
471     notifyObservers();
472 }
473
474 void CachedImage::changedInRect(const Image* image, const IntRect& rect)
475 {
476     if (!image || image != m_image)
477         return;
478 #if ENABLE(SVG)
479     // We have to update the cached ImageBuffers if the underlying content changed.
480     if (image->isSVGImage()) {
481         m_svgImageCache->imageContentChanged();
482         return;
483     }
484 #endif
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);
494     info.addMember(m_image, "m_image");
495 #if ENABLE(SVG)
496     info.addMember(m_svgImageCache);
497 #endif
498 }
499
500 bool CachedImage::currentFrameHasAlpha(const RenderObject* renderer)
501 {
502     Image* image = imageForRenderer(renderer);
503     if (image->isBitmapImage())
504         image->nativeImageForCurrentFrame(); // force decode
505     return image->currentFrameHasAlpha();
506 }
507
508 } // namespace WebCore