1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
|
/*
Copyright (C) 1998 Lars Knoll (knoll@mpi-hd.mpg.de)
Copyright (C) 2001 Dirk Mueller (mueller@kde.org)
Copyright (C) 2002 Waldo Bastian (bastian@kde.org)
Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "CachedImage.h"
#include "BitmapImage.h"
#include "CachedImageClient.h"
#include "CachedResourceClient.h"
#include "CachedResourceClientWalker.h"
#include "CachedResourceLoader.h"
#include "FrameLoader.h"
#include "FrameLoaderTypes.h"
#include "LocalFrame.h"
#include "LocalFrameLoaderClient.h"
#include "LocalFrameView.h"
#include "MIMETypeRegistry.h"
#include "MemoryCache.h"
#include "RenderElement.h"
#include "SVGElementTypeHelpers.h"
#include "SVGImage.h"
#include "SecurityOrigin.h"
#include "Settings.h"
#include "SharedBuffer.h"
#include "SubresourceLoader.h"
#include <wtf/NeverDestroyed.h>
#include <wtf/StdLibExtras.h>
#if PLATFORM(IOS_FAMILY)
#include "SystemMemory.h"
#endif
#if USE(CG)
#include "PDFDocumentImage.h"
#endif
namespace WebCore {
CachedImage::CachedImage(CachedResourceRequest&& request, PAL::SessionID sessionID, const CookieJar* cookieJar)
: CachedResource(WTFMove(request), Type::ImageResource, sessionID, cookieJar)
, m_updateImageDataCount(0)
, m_isManuallyCached(false)
, m_shouldPaintBrokenImage(true)
, m_forceUpdateImageDataEnabledForTesting(false)
{
setStatus(Unknown);
}
CachedImage::CachedImage(Image* image, PAL::SessionID sessionID, const CookieJar* cookieJar)
: CachedResource(URL(), Type::ImageResource, sessionID, cookieJar)
, m_image(image)
, m_updateImageDataCount(0)
, m_isManuallyCached(false)
, m_shouldPaintBrokenImage(true)
, m_forceUpdateImageDataEnabledForTesting(false)
{
}
CachedImage::CachedImage(const URL& url, Image* image, PAL::SessionID sessionID, const CookieJar* cookieJar, const String& domainForCachePartition)
: CachedResource(url, Type::ImageResource, sessionID, cookieJar)
, m_image(image)
, m_updateImageDataCount(0)
, m_isManuallyCached(true)
, m_shouldPaintBrokenImage(true)
, m_forceUpdateImageDataEnabledForTesting(false)
{
m_resourceRequest.setDomainForCachePartition(domainForCachePartition);
// Use the incoming URL in the response field. This ensures that code using the response directly,
// such as origin checks for security, actually see something.
mutableResponse().setURL(url);
}
CachedImage::~CachedImage()
{
clearImage();
}
void CachedImage::load(CachedResourceLoader& loader)
{
m_skippingRevalidationDocument = loader.document();
#if ENABLE(LAYER_BASED_SVG_ENGINE)
m_layerBasedSVGEngineEnabled = loader.document() ? loader.document()->settings().layerBasedSVGEngineEnabled() : false;
#endif
if (loader.shouldPerformImageLoad(url()))
CachedResource::load(loader);
else
setLoading(false);
}
void CachedImage::setBodyDataFrom(const CachedResource& resource)
{
ASSERT(resource.type() == type());
const CachedImage& image = static_cast<const CachedImage&>(resource);
CachedResource::setBodyDataFrom(resource);
m_image = image.m_image;
m_imageObserver = image.m_imageObserver;
if (m_imageObserver)
m_imageObserver->cachedImages().add(*this);
if (m_image && is<SVGImage>(*m_image))
m_svgImageCache = makeUnique<SVGImageCache>(&downcast<SVGImage>(*m_image));
}
void CachedImage::didAddClient(CachedResourceClient& client)
{
if (m_data && !m_image && !errorOccurred()) {
createImage();
m_image->setData(m_data.copyRef(), true);
}
ASSERT(client.resourceClientType() == CachedImageClient::expectedType());
if (m_image && !m_image->isNull())
downcast<CachedImageClient>(client).imageChanged(this);
if (m_image)
m_image->startAnimationAsynchronously();
CachedResource::didAddClient(client);
}
void CachedImage::didRemoveClient(CachedResourceClient& client)
{
ASSERT(client.resourceClientType() == CachedImageClient::expectedType());
m_pendingContainerContextRequests.remove(&downcast<CachedImageClient>(client));
m_clientsWaitingForAsyncDecoding.remove(downcast<CachedImageClient>(client));
if (m_svgImageCache)
m_svgImageCache->removeClientFromCache(&downcast<CachedImageClient>(client));
CachedResource::didRemoveClient(client);
downcast<CachedImageClient>(client).didRemoveCachedImageClient(*this);
}
bool CachedImage::isClientWaitingForAsyncDecoding(const CachedImageClient& client) const
{
return m_clientsWaitingForAsyncDecoding.contains(const_cast<CachedImageClient&>(client));
}
void CachedImage::addClientWaitingForAsyncDecoding(CachedImageClient& client)
{
ASSERT(client.resourceClientType() == CachedImageClient::expectedType());
if (m_clientsWaitingForAsyncDecoding.contains(client))
return;
if (!m_clients.contains(client)) {
// If the <html> element does not have its own background specified, painting the root box
// renderer uses the style of the <body> element, see RenderView::rendererForRootBackground().
// In this case, the client we are asked to add is the root box renderer. Since we can't add
// a client to m_clientsWaitingForAsyncDecoding unless it is one of the m_clients, we are going
// to cancel the repaint optimization we do in CachedImage::imageFrameAvailable() by adding
// all the m_clients to m_clientsWaitingForAsyncDecoding.
CachedResourceClientWalker<CachedImageClient> walker(*this);
while (auto* client = walker.next())
m_clientsWaitingForAsyncDecoding.add(*client);
} else
m_clientsWaitingForAsyncDecoding.add(client);
}
void CachedImage::removeAllClientsWaitingForAsyncDecoding()
{
if (m_clientsWaitingForAsyncDecoding.isEmptyIgnoringNullReferences() || !hasImage() || !is<BitmapImage>(image()))
return;
downcast<BitmapImage>(image())->stopAsyncDecodingQueue();
for (auto& client : m_clientsWaitingForAsyncDecoding)
client.imageChanged(this);
m_clientsWaitingForAsyncDecoding.clear();
}
void CachedImage::switchClientsToRevalidatedResource()
{
ASSERT(is<CachedImage>(resourceToRevalidate()));
// Pending container size requests need to be transferred to the revalidated resource.
if (!m_pendingContainerContextRequests.isEmpty()) {
// A copy of pending size requests is needed as they are deleted during CachedResource::switchClientsToRevalidateResouce().
ContainerContextRequests switchContainerContextRequests;
for (auto& request : m_pendingContainerContextRequests)
switchContainerContextRequests.set(request.key, request.value);
CachedResource::switchClientsToRevalidatedResource();
CachedImage& revalidatedCachedImage = downcast<CachedImage>(*resourceToRevalidate());
for (auto& request : switchContainerContextRequests)
revalidatedCachedImage.setContainerContextForClient(*request.key, request.value.containerSize, request.value.containerZoom, request.value.imageURL);
return;
}
CachedResource::switchClientsToRevalidatedResource();
}
void CachedImage::allClientsRemoved()
{
m_pendingContainerContextRequests.clear();
m_clientsWaitingForAsyncDecoding.clear();
if (m_image && !errorOccurred())
m_image->resetAnimation();
}
std::pair<Image*, float> CachedImage::brokenImage(float deviceScaleFactor) const
{
if (deviceScaleFactor >= 3) {
static NeverDestroyed<Image*> brokenImageVeryHiRes(&Image::loadPlatformResource("missingImage@3x").leakRef());
return std::make_pair(brokenImageVeryHiRes, 3);
}
if (deviceScaleFactor >= 2) {
static NeverDestroyed<Image*> brokenImageHiRes(&Image::loadPlatformResource("missingImage@2x").leakRef());
return std::make_pair(brokenImageHiRes, 2);
}
static NeverDestroyed<Image*> brokenImageLoRes(&Image::loadPlatformResource("missingImage").leakRef());
return std::make_pair(brokenImageLoRes, 1);
}
bool CachedImage::willPaintBrokenImage() const
{
return errorOccurred() && m_shouldPaintBrokenImage;
}
Image* CachedImage::image() const
{
if (errorOccurred() && m_shouldPaintBrokenImage) {
// Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
// deviceScaleFactor from here. It is critical that callers use CachedImage::brokenImage()
// when they need the real, deviceScaleFactor-appropriate broken image icon.
return brokenImage(1).first;
}
if (m_image)
return m_image.get();
return &Image::nullImage();
}
Image* CachedImage::imageForRenderer(const RenderObject* renderer)
{
if (errorOccurred() && m_shouldPaintBrokenImage) {
// Returning the 1x broken image is non-ideal, but we cannot reliably access the appropriate
// deviceScaleFactor from here. It is critical that callers use CachedImage::brokenImage()
// when they need the real, deviceScaleFactor-appropriate broken image icon.
return brokenImage(1).first;
}
if (!m_image)
return &Image::nullImage();
if (m_image->drawsSVGImage()) {
Image* image = m_svgImageCache->imageForRenderer(renderer);
if (image != &Image::nullImage())
return image;
}
return m_image.get();
}
bool CachedImage::hasSVGImage() const
{
return image() && image()->isSVGImage();
}
void CachedImage::setContainerContextForClient(const CachedImageClient& client, const LayoutSize& containerSize, float containerZoom, const URL& imageURL)
{
if (containerSize.isEmpty())
return;
ASSERT(containerZoom);
if (!m_image) {
m_pendingContainerContextRequests.set(&client, ContainerContext { containerSize, containerZoom, imageURL });
return;
}
if (!m_image->drawsSVGImage()) {
m_image->setContainerSize(containerSize);
return;
}
m_svgImageCache->setContainerContextForClient(client, containerSize, containerZoom, imageURL);
}
FloatSize CachedImage::imageSizeForRenderer(const RenderElement* renderer, SizeType sizeType) const
{
if (!m_image)
return { };
if (m_image->drawsSVGImage() && sizeType == UsedSize)
return m_svgImageCache->imageSizeForRenderer(renderer);
return m_image->size(renderer ? renderer->imageOrientation() : ImageOrientation(ImageOrientation::Orientation::FromImage));
}
LayoutSize CachedImage::unclampedImageSizeForRenderer(const RenderElement* renderer, float multiplier, SizeType sizeType) const
{
LayoutSize imageSize = LayoutSize(imageSizeForRenderer(renderer, sizeType));
if (imageSize.isEmpty() || multiplier == 1.0f)
return imageSize;
float widthScale = m_image->hasRelativeWidth() ? 1.0f : multiplier;
float heightScale = m_image->hasRelativeHeight() ? 1.0f : multiplier;
imageSize.scale(widthScale, heightScale);
return imageSize;
}
LayoutSize CachedImage::imageSizeForRenderer(const RenderElement* renderer, float multiplier, SizeType sizeType) const
{
auto imageSize = unclampedImageSizeForRenderer(renderer, multiplier, sizeType);
if (imageSize.isEmpty() || multiplier == 1.0f)
return imageSize;
// Don't let images that have a width/height >= 1 shrink below 1 when zoomed.
LayoutSize minimumSize(imageSize.width() > 0 ? 1 : 0, imageSize.height() > 0 ? 1 : 0);
imageSize.clampToMinimumSize(minimumSize);
ASSERT(multiplier != 1.0f || (imageSize.width().fraction() == 0.0f && imageSize.height().fraction() == 0.0f));
return imageSize;
}
void CachedImage::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
{
if (m_image)
m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
}
void CachedImage::notifyObservers(const IntRect* changeRect)
{
CachedResourceClientWalker<CachedImageClient> walker(*this);
while (CachedImageClient* c = walker.next())
c->imageChanged(this, changeRect);
}
void CachedImage::checkShouldPaintBrokenImage()
{
if (!m_loader || m_loader->reachedTerminalState())
return;
m_shouldPaintBrokenImage = m_loader->frameLoader()->client().shouldPaintBrokenImage(url());
}
bool CachedImage::isPDFResource() const
{
return Image::isPDFResource(response().mimeType(), url());
}
bool CachedImage::isPostScriptResource() const
{
return Image::isPostScriptResource(response().mimeType(), url());
}
void CachedImage::clear()
{
destroyDecodedData();
clearImage();
m_pendingContainerContextRequests.clear();
m_clientsWaitingForAsyncDecoding.clear();
setEncodedSize(0);
}
inline void CachedImage::createImage()
{
// Create the image if it doesn't yet exist.
if (m_image)
return;
m_imageObserver = CachedImageObserver::create(*this);
m_image = Image::create(*m_imageObserver);
if (m_image) {
if (is<SVGImage>(*m_image))
m_svgImageCache = makeUnique<SVGImageCache>(&downcast<SVGImage>(*m_image));
// Send queued container size requests.
if (m_image->usesContainerSize()) {
for (auto& request : m_pendingContainerContextRequests)
setContainerContextForClient(*request.key, request.value.containerSize, request.value.containerZoom, request.value.imageURL);
}
m_pendingContainerContextRequests.clear();
m_clientsWaitingForAsyncDecoding.clear();
}
}
CachedImage::CachedImageObserver::CachedImageObserver(CachedImage& image)
{
m_cachedImages.add(image);
}
void CachedImage::CachedImageObserver::encodedDataStatusChanged(const Image& image, EncodedDataStatus status)
{
for (auto& cachedImage : m_cachedImages)
cachedImage.encodedDataStatusChanged(image, status);
}
void CachedImage::CachedImageObserver::decodedSizeChanged(const Image& image, long long delta)
{
for (auto& cachedImage : m_cachedImages)
cachedImage.decodedSizeChanged(image, delta);
}
void CachedImage::CachedImageObserver::didDraw(const Image& image)
{
for (auto& cachedImage : m_cachedImages)
cachedImage.didDraw(image);
}
bool CachedImage::CachedImageObserver::canDestroyDecodedData(const Image& image)
{
for (auto& cachedImage : m_cachedImages) {
if (&image != cachedImage.image())
continue;
if (!cachedImage.canDestroyDecodedData(image))
return false;
}
return true;
}
void CachedImage::CachedImageObserver::imageFrameAvailable(const Image& image, ImageAnimatingState animatingState, const IntRect* changeRect, DecodingStatus decodingStatus)
{
for (auto& cachedImage : m_cachedImages)
cachedImage.imageFrameAvailable(image, animatingState, changeRect, decodingStatus);
}
void CachedImage::CachedImageObserver::changedInRect(const Image& image, const IntRect* rect)
{
for (auto& cachedImage : m_cachedImages)
cachedImage.changedInRect(image, rect);
}
void CachedImage::CachedImageObserver::scheduleRenderingUpdate(const Image& image)
{
for (auto& cachedImage : m_cachedImages)
cachedImage.scheduleRenderingUpdate(image);
}
bool CachedImage::CachedImageObserver::allowsAnimation(const Image& image) const
{
for (auto& cachedImage : m_cachedImages) {
if (cachedImage.allowsAnimation(image))
return true;
}
return false;
}
inline void CachedImage::clearImage()
{
if (!m_image)
return;
if (m_imageObserver) {
m_imageObserver->cachedImages().remove(*this);
if (m_imageObserver->cachedImages().isEmptyIgnoringNullReferences()) {
ASSERT(m_imageObserver->hasOneRef());
m_image->setImageObserver(nullptr);
}
m_imageObserver = nullptr;
}
m_image = nullptr;
m_lastUpdateImageDataTime = { };
m_updateImageDataCount = 0;
}
void CachedImage::updateBufferInternal(const FragmentedSharedBuffer& data)
{
CachedResourceHandle protectedThis { *this };
m_data = const_cast<FragmentedSharedBuffer*>(&data);
setEncodedSize(m_data->size());
createImage();
// Don't update the image with the new buffer very often. Changing the decoder
// internal data and repainting the observers sometimes are very expensive operations.
if (!m_forceUpdateImageDataEnabledForTesting && shouldDeferUpdateImageData())
return;
EncodedDataStatus encodedDataStatus = EncodedDataStatus::Unknown;
if (isPostScriptResource()) {
#if PLATFORM(MAC) && !USE(WEBKIT_IMAGE_DECODERS)
// Delay updating the image with the PostScript data till all the data
// is received so it can be converted to PDF data.
return;
#else
// Set the encodedDataStatus to Error so loading this image will be canceled.
encodedDataStatus = EncodedDataStatus::Error;
#endif
} else {
// Have the image update its data from its internal buffer. Decoding the image data
// will be delayed until info (like size or specific image frames) are queried which
// usually happens when the observers are repainted.
encodedDataStatus = updateImageData(false);
}
if (encodedDataStatus > EncodedDataStatus::Error && encodedDataStatus < EncodedDataStatus::SizeAvailable)
return;
if (encodedDataStatus == EncodedDataStatus::Error || m_image->isNull()) {
// Image decoding failed. Either we need more image data or the image data is malformed.
error(errorOccurred() ? status() : DecodeError);
if (inCache())
MemoryCache::singleton().remove(*this);
if (m_loader && encodedDataStatus == EncodedDataStatus::Error)
m_loader->cancel();
return;
}
// Tell our observers to try to draw.
notifyObservers();
}
bool CachedImage::shouldDeferUpdateImageData() const
{
static const double updateImageDataBackoffIntervals[] = { 0, 1, 3, 6, 15 };
unsigned interval = m_updateImageDataCount;
// The first time through, the chunk time will be 0 and the image will get an update.
return (MonotonicTime::now() - m_lastUpdateImageDataTime).seconds() < updateImageDataBackoffIntervals[interval];
}
RefPtr<SharedBuffer> CachedImage::convertedDataIfNeeded(const FragmentedSharedBuffer* data) const
{
if (!data)
return nullptr;
return data->makeContiguous();
}
void CachedImage::didUpdateImageData()
{
m_lastUpdateImageDataTime = MonotonicTime::now();
unsigned previous = m_updateImageDataCount;
if (previous != maxUpdateImageDataCount)
m_updateImageDataCount += 1;
}
EncodedDataStatus CachedImage::updateImageData(bool allDataReceived)
{
if (!m_image || !m_data)
return EncodedDataStatus::Error;
EncodedDataStatus result = m_image->setData(m_data.copyRef(), allDataReceived);
didUpdateImageData();
return result;
}
void CachedImage::updateBuffer(const FragmentedSharedBuffer& buffer)
{
ASSERT(dataBufferingPolicy() == DataBufferingPolicy::BufferData);
updateBufferInternal(buffer);
}
void CachedImage::updateData(const SharedBuffer& data)
{
ASSERT(dataBufferingPolicy() == DataBufferingPolicy::DoNotBufferData);
updateBufferInternal(data);
}
void CachedImage::finishLoading(const FragmentedSharedBuffer* data, const NetworkLoadMetrics& metrics)
{
m_data = convertedDataIfNeeded(data);
if (m_data) {
setEncodedSize(m_data->size());
createImage();
}
EncodedDataStatus encodedDataStatus = updateImageData(true);
if (encodedDataStatus == EncodedDataStatus::Error || m_image->isNull()) {
// Image decoding failed; the image data is malformed.
error(errorOccurred() ? status() : DecodeError);
if (inCache())
MemoryCache::singleton().remove(*this);
return;
}
setLoading(false);
notifyObservers();
CachedResource::finishLoading(data, metrics);
}
void CachedImage::didReplaceSharedBufferContents()
{
if (m_image) {
// Let the Image know that the FragmentedSharedBuffer has been rejigged, so it can let go of any references to the heap-allocated resource buffer.
// FIXME(rdar://problem/24275617): It would be better if we could somehow tell the Image's decoder to swap in the new contents without destroying anything.
m_image->destroyDecodedData(true);
}
CachedResource::didReplaceSharedBufferContents();
}
void CachedImage::error(CachedResource::Status status)
{
checkShouldPaintBrokenImage();
clear();
CachedResource::error(status);
notifyObservers();
}
void CachedImage::responseReceived(const ResourceResponse& newResponse)
{
if (!response().isNull())
clear();
CachedResource::responseReceived(newResponse);
}
void CachedImage::destroyDecodedData()
{
bool canDeleteImage = !m_image || (m_image->hasOneRef() && m_image->isBitmapImage());
if (canDeleteImage && !isLoading() && !hasClients()) {
m_image = nullptr;
setDecodedSize(0);
} else if (m_image && !errorOccurred())
m_image->destroyDecodedData();
}
void CachedImage::encodedDataStatusChanged(const Image& image, EncodedDataStatus)
{
if (&image != m_image)
return;
notifyObservers();
}
void CachedImage::decodedSizeChanged(const Image& image, long long delta)
{
if (&image != m_image)
return;
ASSERT(delta >= 0 || decodedSize() + delta >= 0);
setDecodedSize(static_cast<unsigned>(decodedSize() + delta));
}
void CachedImage::didDraw(const Image& image)
{
if (&image != m_image)
return;
MonotonicTime timeStamp = LocalFrameView::currentPaintTimeStamp();
if (!timeStamp) // If didDraw is called outside of a Frame paint.
timeStamp = MonotonicTime::now();
CachedResource::didAccessDecodedData(timeStamp);
}
bool CachedImage::canDestroyDecodedData(const Image& image)
{
if (&image != m_image)
return false;
CachedResourceClientWalker<CachedImageClient> walker(*this);
while (CachedImageClient* client = walker.next()) {
if (!client->canDestroyDecodedData())
return false;
}
return true;
}
void CachedImage::imageFrameAvailable(const Image& image, ImageAnimatingState animatingState, const IntRect* changeRect, DecodingStatus decodingStatus)
{
if (&image != m_image)
return;
CachedResourceClientWalker<CachedImageClient> walker(*this);
VisibleInViewportState visibleState = VisibleInViewportState::No;
while (CachedImageClient* client = walker.next()) {
// All the clients of animated images have to be notified. The new frame has to be drawn in all of them.
if (animatingState == ImageAnimatingState::No && !m_clientsWaitingForAsyncDecoding.contains(*client))
continue;
if (client->imageFrameAvailable(*this, animatingState, changeRect) == VisibleInViewportState::Yes)
visibleState = VisibleInViewportState::Yes;
}
if (visibleState == VisibleInViewportState::No && animatingState == ImageAnimatingState::Yes)
m_image->stopAnimation();
if (decodingStatus != DecodingStatus::Partial)
m_clientsWaitingForAsyncDecoding.clear();
}
void CachedImage::changedInRect(const Image& image, const IntRect* rect)
{
if (&image != m_image)
return;
notifyObservers(rect);
}
void CachedImage::scheduleRenderingUpdate(const Image& image)
{
if (&image != m_image)
return;
CachedResourceClientWalker<CachedImageClient> walker(*this);
while (auto* client = walker.next())
client->scheduleRenderingUpdateForImage(*this);
}
bool CachedImage::allowsAnimation(const Image& image) const
{
if (&image != m_image)
return false;
CachedResourceClientWalker<CachedImageClient> walker(*this);
while (auto* client = walker.next()) {
if (!client->allowsAnimation())
return false;
}
return true;
}
bool CachedImage::currentFrameKnownToBeOpaque(const RenderElement* renderer)
{
Image* image = imageForRenderer(renderer);
return image->currentFrameKnownToBeOpaque();
}
bool CachedImage::isOriginClean(SecurityOrigin* origin)
{
ASSERT_UNUSED(origin, origin);
ASSERT(this->origin());
ASSERT(origin->toString() == this->origin()->toString());
return !loadFailedOrCanceled() && isCORSSameOrigin();
}
CachedResource::RevalidationDecision CachedImage::makeRevalidationDecision(CachePolicy cachePolicy) const
{
if (UNLIKELY(isManuallyCached())) {
// Do not revalidate manually cached images. This mechanism is used as a
// way to efficiently share an image from the client to content and
// the URL for that image may not represent a resource that can be
// retrieved by standard means. If the manual caching SPI is used, it is
// incumbent on the client to only use valid resources.
return RevalidationDecision::No;
}
return CachedResource::makeRevalidationDecision(cachePolicy);
}
bool CachedImage::canSkipRevalidation(const CachedResourceLoader& loader, const CachedResourceRequest& request) const
{
if (options().mode != request.options().mode || options().credentials != request.options().credentials || resourceRequest().allowCookies() != request.resourceRequest().allowCookies())
return false;
// Skip revalidation as per https://html.spec.whatwg.org/#ignore-higher-layer-caching which defines a per-document image list.
// This rule is loosely implemented by other browsers, we could relax it and should update it once memory cache is properly specified.
return m_skippingRevalidationDocument && loader.document() == m_skippingRevalidationDocument;
}
bool CachedImage::isVisibleInViewport(const Document& document) const
{
CachedResourceClientWalker<CachedImageClient> walker(*this);
while (auto* client = walker.next()) {
if (client->imageVisibleInViewport(document) == VisibleInViewportState::Yes)
return true;
}
return false;
}
} // namespace WebCore
|