Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / fetch / ImageResource.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 "core/fetch/ImageResource.h"
26
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"
41
42 namespace WebCore {
43
44 ImageResource::ImageResource(const ResourceRequest& resourceRequest)
45     : Resource(resourceRequest, Image)
46     , m_devicePixelRatioHeaderValue(1.0)
47     , m_image(0)
48     , m_loadingMultipartContent(false)
49     , m_hasDevicePixelRatioHeaderValue(false)
50 {
51     setStatus(Unknown);
52     setCustomAcceptHeader();
53 }
54
55 ImageResource::ImageResource(WebCore::Image* image)
56     : Resource(ResourceRequest(""), Image)
57     , m_image(image)
58 {
59     setStatus(Cached);
60     setLoading(false);
61     setCustomAcceptHeader();
62 }
63
64 ImageResource::~ImageResource()
65 {
66     clearImage();
67 }
68
69 void ImageResource::load(ResourceFetcher* fetcher, const ResourceLoaderOptions& options)
70 {
71     if (!fetcher || fetcher->autoLoadImages())
72         Resource::load(fetcher, options);
73     else
74         setLoading(false);
75 }
76
77 void ImageResource::didAddClient(ResourceClient* c)
78 {
79     if (m_data && !m_image && !errorOccurred()) {
80         createImage();
81         m_image->setData(m_data, true);
82     }
83
84     ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
85     if (m_image && !m_image->isNull())
86         static_cast<ImageResourceClient*>(c)->imageChanged(this);
87
88     Resource::didAddClient(c);
89 }
90
91 void ImageResource::didRemoveClient(ResourceClient* c)
92 {
93     ASSERT(c);
94     ASSERT(c->resourceClientType() == ImageResourceClient::expectedType());
95
96     m_pendingContainerSizeRequests.remove(static_cast<ImageResourceClient*>(c));
97     if (m_svgImageCache)
98         m_svgImageCache->removeClientFromCache(static_cast<ImageResourceClient*>(c));
99
100     Resource::didRemoveClient(c);
101 }
102
103 void ImageResource::switchClientsToRevalidatedResource()
104 {
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);
117         return;
118     }
119
120     Resource::switchClientsToRevalidatedResource();
121 }
122
123 bool ImageResource::isSafeToUnlock() const
124 {
125     return !m_image || (m_image->hasOneRef() && m_image->isBitmapImage());
126 }
127
128 void ImageResource::destroyDecodedDataIfPossible()
129 {
130     if (isSafeToUnlock() && !hasClients() && !isLoading()) {
131         m_image = 0;
132         setDecodedSize(0);
133     } else if (m_image && !errorOccurred()) {
134         m_image->destroyDecodedData(true);
135     }
136 }
137
138 void ImageResource::allClientsRemoved()
139 {
140     m_pendingContainerSizeRequests.clear();
141     if (m_image && !errorOccurred())
142         m_image->resetAnimation();
143     Resource::allClientsRemoved();
144 }
145
146 pair<WebCore::Image*, float> ImageResource::brokenImage(float deviceScaleFactor)
147 {
148     if (deviceScaleFactor >= 2) {
149         DEFINE_STATIC_REF(WebCore::Image, brokenImageHiRes, (WebCore::Image::loadPlatformResource("missingImage@2x")));
150         return std::make_pair(brokenImageHiRes, 2);
151     }
152
153     DEFINE_STATIC_REF(WebCore::Image, brokenImageLoRes, (WebCore::Image::loadPlatformResource("missingImage")));
154     return std::make_pair(brokenImageLoRes, 1);
155 }
156
157 bool ImageResource::willPaintBrokenImage() const
158 {
159     return errorOccurred();
160 }
161
162 WebCore::Image* ImageResource::image()
163 {
164     ASSERT(!isPurgeable());
165
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;
171     }
172
173     if (m_image)
174         return m_image.get();
175
176     return WebCore::Image::nullImage();
177 }
178
179 WebCore::Image* ImageResource::imageForRenderer(const RenderObject* renderer)
180 {
181     ASSERT(!isPurgeable());
182
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;
188     }
189
190     if (!m_image)
191         return WebCore::Image::nullImage();
192
193     if (m_image->isSVGImage()) {
194         WebCore::Image* image = m_svgImageCache->imageForRenderer(renderer);
195         if (image != WebCore::Image::nullImage())
196             return image;
197     }
198
199     return m_image.get();
200 }
201
202 void ImageResource::setContainerSizeForRenderer(const ImageResourceClient* renderer, const IntSize& containerSize, float containerZoom)
203 {
204     if (containerSize.isEmpty())
205         return;
206     ASSERT(renderer);
207     ASSERT(containerZoom);
208     if (!m_image) {
209         m_pendingContainerSizeRequests.set(renderer, SizeAndZoom(containerSize, containerZoom));
210         return;
211     }
212     if (!m_image->isSVGImage()) {
213         m_image->setContainerSize(containerSize);
214         return;
215     }
216
217     m_svgImageCache->setContainerSizeForRenderer(renderer, containerSize, containerZoom);
218 }
219
220 bool ImageResource::usesImageContainerSize() const
221 {
222     if (m_image)
223         return m_image->usesContainerSize();
224
225     return false;
226 }
227
228 bool ImageResource::imageHasRelativeWidth() const
229 {
230     if (m_image)
231         return m_image->hasRelativeWidth();
232
233     return false;
234 }
235
236 bool ImageResource::imageHasRelativeHeight() const
237 {
238     if (m_image)
239         return m_image->hasRelativeHeight();
240
241     return false;
242 }
243
244 LayoutSize ImageResource::imageSizeForRenderer(const RenderObject* renderer, float multiplier, SizeType sizeType)
245 {
246     ASSERT(!isPurgeable());
247
248     if (!m_image)
249         return IntSize();
250
251     LayoutSize imageSize;
252
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);
257     else
258         imageSize = m_image->size();
259
260     if (multiplier == 1.0f)
261         return imageSize;
262
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));
270     return imageSize;
271 }
272
273 void ImageResource::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
274 {
275     if (m_image)
276         m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
277 }
278
279 void ImageResource::notifyObservers(const IntRect* changeRect)
280 {
281     ResourceClientWalker<ImageResourceClient> w(m_clients);
282     while (ImageResourceClient* c = w.next())
283         c->imageChanged(this, changeRect);
284 }
285
286 void ImageResource::clear()
287 {
288     prune();
289     clearImage();
290     m_pendingContainerSizeRequests.clear();
291     setEncodedSize(0);
292 }
293
294 void ImageResource::setCustomAcceptHeader()
295 {
296     DEFINE_STATIC_LOCAL(const AtomicString, acceptWebP, ("image/webp,*/*;q=0.8", AtomicString::ConstructFromLiteral));
297     setAccept(acceptWebP);
298 }
299
300 inline void ImageResource::createImage()
301 {
302     // Create the image if it doesn't yet exist.
303     if (m_image)
304         return;
305
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();
310     } else {
311         m_image = BitmapImage::create(this);
312     }
313
314     if (m_image) {
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);
319         }
320         m_pendingContainerSizeRequests.clear();
321     }
322 }
323
324 inline void ImageResource::clearImage()
325 {
326     // If our Image has an observer, it's always us so we need to clear the back pointer
327     // before dropping our reference.
328     if (m_image)
329         m_image->setImageObserver(0);
330     m_image.clear();
331 }
332
333 void ImageResource::appendData(const char* data, int length)
334 {
335     Resource::appendData(data, length);
336     if (!m_loadingMultipartContent)
337         updateImage(false);
338 }
339
340 void ImageResource::updateImage(bool allDataReceived)
341 {
342     TRACE_EVENT0("webkit", "ImageResource::updateImage");
343
344     if (m_data)
345         createImage();
346
347     bool sizeAvailable = false;
348
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).
352     if (m_image)
353         sizeAvailable = m_image->setData(m_data, allDataReceived);
354
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
358     // to decode.
359     if (sizeAvailable || allDataReceived) {
360         if (!m_image || m_image->isNull()) {
361             error(errorOccurred() ? status() : DecodeError);
362             if (inCache())
363                 memoryCache()->remove(this);
364             return;
365         }
366
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.
369         notifyObservers();
370     }
371 }
372
373 void ImageResource::finishOnePart()
374 {
375     if (m_loadingMultipartContent)
376         clear();
377     updateImage(true);
378     if (m_loadingMultipartContent)
379         m_data.clear();
380     Resource::finishOnePart();
381 }
382
383 void ImageResource::error(Resource::Status status)
384 {
385     clear();
386     Resource::error(status);
387     notifyObservers();
388 }
389
390 void ImageResource::responseReceived(const ResourceResponse& response)
391 {
392     if (m_loadingMultipartContent && m_data)
393         finishOnePart();
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;
401         }
402     }
403     Resource::responseReceived(response);
404 }
405
406 void ImageResource::decodedSizeChanged(const WebCore::Image* image, int delta)
407 {
408     if (!image || image != m_image)
409         return;
410
411     setDecodedSize(decodedSize() + delta);
412 }
413
414 void ImageResource::didDraw(const WebCore::Image* image)
415 {
416     if (!image || image != m_image)
417         return;
418
419     double timeStamp = FrameView::currentFrameTimeStamp();
420     if (!timeStamp) // If didDraw is called outside of a Frame paint.
421         timeStamp = currentTime();
422
423     Resource::didAccessDecodedData(timeStamp);
424 }
425
426 bool ImageResource::shouldPauseAnimation(const WebCore::Image* image)
427 {
428     if (!image || image != m_image)
429         return false;
430
431     ResourceClientWalker<ImageResourceClient> w(m_clients);
432     while (ImageResourceClient* c = w.next()) {
433         if (c->willRenderImage(this))
434             return false;
435     }
436
437     return true;
438 }
439
440 void ImageResource::animationAdvanced(const WebCore::Image* image)
441 {
442     if (!image || image != m_image)
443         return;
444     notifyObservers();
445 }
446
447 void ImageResource::changedInRect(const WebCore::Image* image, const IntRect& rect)
448 {
449     if (!image || image != m_image)
450         return;
451     notifyObservers(&rect);
452 }
453
454 bool ImageResource::currentFrameKnownToBeOpaque(const RenderObject* renderer)
455 {
456     WebCore::Image* image = imageForRenderer(renderer);
457     if (image->isBitmapImage())
458         image->nativeImageForCurrentFrame(); // force decode
459     return image->currentFrameKnownToBeOpaque();
460 }
461
462 bool ImageResource::isAccessAllowed(SecurityOrigin* securityOrigin)
463 {
464     if (!image()->currentFrameHasSingleSecurityOrigin())
465         return false;
466     if (passesAccessControlCheck(securityOrigin))
467         return true;
468     return !securityOrigin->taintsCanvas(response().url());
469 }
470
471 } // namespace WebCore