/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * (C) 1999 Antti Koivisto (koivisto@kde.org) * Copyright (C) 2004-2026 Apple Inc. All rights reserved. * Copyright (C) 2010-2015 Google 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 "HTMLImageElement.h" #include "CSSPropertyNames.h" #include "CSSSerializationContext.h" #include "CSSValueKeywords.h" #include "CachedImage.h" #include "Chrome.h" #include "ChromeClient.h" #include "CommonAtomStrings.h" #include "ContainerNodeInlines.h" #include "Editor.h" #include "ElementChildIteratorInlines.h" #include "ElementInlinesLight.h" #include "ElementRareData.h" #include "EventLoop.h" #include "EventNames.h" #include "HTMLAnchorElement.h" #include "HTMLAttachmentElement.h" #include "HTMLDocument.h" #include "HTMLFormElement.h" #include "HTMLImageDensityCorrectedSizing.h" #include "HTMLImageLoader.h" #include "HTMLMapElement.h" #include "HTMLParserIdioms.h" #include "HTMLPictureElement.h" #include "HTMLSourceElement.h" #include "HTMLSrcsetParser.h" #include "ImageAnimationTimeline.h" #include "ImageOrientation.h" #include "ImageRequestState.h" #include "ImageTypes.h" #include "JSRequestPriority.h" #include "LazyLoadElementObserver.h" #include "LazyLoading.h" #include "LocalFrameView.h" #include "Logging.h" #include "MIMETypeRegistry.h" #include "MediaQueryEvaluator.h" #include "MouseEvent.h" #include "NodeName.h" #include "NodeTraversal.h" #include "Page.h" #include "PlatformMouseEvent.h" #include "RenderBoxInlines.h" #include "RenderElementStyleInlines.h" #include "RenderImage.h" #include "RenderImageResource.h" #include "RenderView.h" #include "RequestPriority.h" #include "Settings.h" #include "ShadowRoot.h" #include "SizesAttributeParser.h" #include "StyleComputedStyle.h" #include "StyleImageOrientation.h" #include "StyleZoomPrimitivesInlines.h" #include #include "DocumentPage.h" #include "FrameDestructionObserverInlines.h" #include #if ENABLE(SERVICE_CONTROLS) #include "ImageControlsMac.h" #endif #if ENABLE(SPATIAL_IMAGE_CONTROLS) #include "SpatialImageControls.h" #endif #if ENABLE(IMAGE_ELEMENT_IMMERSIVE) #include "DocumentImmersive.h" #include "JSDOMPromiseDeferred.h" #endif namespace WebCore { WTF_MAKE_TZONE_ALLOCATED_IMPL(HTMLImageElement); using namespace HTMLNames; HTMLImageElement::HTMLImageElement(const QualifiedName& tagName, Document& document) : HTMLElement(tagName, document, { TypeFlag::HasCustomStyleResolveCallbacks, TypeFlag::HasDidMoveToNewDocument }) , ActiveDOMObject(document) , m_imageLoader(makeUniqueWithoutRefCountedCheck(*this)) , m_currentPixelDensity(1.0f) { ASSERT(hasTagName(imgTag)); } Ref HTMLImageElement::create(Document& document) { Ref image = adoptRef(*new HTMLImageElement(imgTag, document)); image->suspendIfNeeded(); return image; } Ref HTMLImageElement::create(const QualifiedName& tagName, Document& document) { Ref image = adoptRef(*new HTMLImageElement(tagName, document)); image->suspendIfNeeded(); return image; } HTMLImageElement::~HTMLImageElement() { disconnectFromIntersectionObservers(); Ref document = this->document(); document->removeDynamicMediaQueryDependentImage(*this); setForm(nullptr); if (RefPtr page = document->page()) page->removeIndividuallyPlayingAnimationElement(*this); } void HTMLImageElement::resetFormOwner() { setForm(HTMLFormElement::findClosestFormAncestor(*this)); } void HTMLImageElement::setFormInternal(RefPtr&& newForm) { if (RefPtr form = FormAssociatedElement::form()) form->unregisterImgElement(*this); FormAssociatedElement::setFormInternal(newForm.copyRef()); if (newForm) newForm->registerImgElement(*this); } void HTMLImageElement::formOwnerRemovedFromTree(const Node& formRoot) { Ref rootNode = traverseToRootNode(); // Do not rely on rootNode() because our IsInTreeScope can be outdated. if (rootNode.ptr() != &formRoot) setForm(nullptr); } Ref HTMLImageElement::createForLegacyFactoryFunction(Document& document, std::optional width, std::optional height) { auto image = adoptRef(*new HTMLImageElement(imgTag, document)); if (width) image->setUnsignedIntegralAttribute(widthAttr, width.value()); if (height) image->setUnsignedIntegralAttribute(heightAttr, height.value()); image->suspendIfNeeded(); return image; } bool HTMLImageElement::hasPresentationalHintsForAttribute(const QualifiedName& name) const { switch (name.nodeName()) { case AttributeNames::widthAttr: case AttributeNames::heightAttr: case AttributeNames::borderAttr: case AttributeNames::vspaceAttr: case AttributeNames::hspaceAttr: case AttributeNames::valignAttr: return true; default: break; } return HTMLElement::hasPresentationalHintsForAttribute(name); } void HTMLImageElement::collectPresentationalHintsForAttribute(const QualifiedName& name, const AtomString& value, MutableStyleProperties& style) { switch (name.nodeName()) { case AttributeNames::widthAttr: addHTMLMultiLengthToStyle(style, CSSPropertyID::Width, value); applyAspectRatioFromWidthAndHeightAttributesToStyle(value, attributeWithoutSynchronization(heightAttr), style); break; case AttributeNames::heightAttr: addHTMLMultiLengthToStyle(style, CSSPropertyID::Height, value); applyAspectRatioFromWidthAndHeightAttributesToStyle(attributeWithoutSynchronization(widthAttr), value, style); break; case AttributeNames::borderAttr: applyBorderAttributeToStyle(value, style); break; case AttributeNames::vspaceAttr: addHTMLLengthToStyle(style, CSSPropertyID::MarginTop, value); addHTMLLengthToStyle(style, CSSPropertyID::MarginBottom, value); break; case AttributeNames::hspaceAttr: addHTMLLengthToStyle(style, CSSPropertyID::MarginLeft, value); addHTMLLengthToStyle(style, CSSPropertyID::MarginRight, value); break; case AttributeNames::alignAttr: applyAlignmentAttributeToStyle(value, style); break; case AttributeNames::valignAttr: addPropertyToPresentationalHintStyle(style, CSSPropertyID::VerticalAlign, value); break; default: HTMLElement::collectPresentationalHintsForAttribute(name, value, style); break; } } void HTMLImageElement::collectExtraStyleForPresentationalHints(MutableStyleProperties& style) { RefPtr sourceElement = this->sourceElement(); if (!sourceElement) return; auto& widthAttrFromSource = sourceElement->attributeWithoutSynchronization(widthAttr); auto& heightAttrFromSource = sourceElement->attributeWithoutSynchronization(heightAttr); // If both width and height attributes of is undefined, the style's value should not // be overwritten. Otherwise, will overwrite it. I.e., if only has one attribute // defined, the other one and aspect-ratio shouldn't be set to auto. if (widthAttrFromSource.isNull() && heightAttrFromSource.isNull()) return; if (!widthAttrFromSource.isNull()) addHTMLLengthToStyle(style, CSSPropertyID::Width, widthAttrFromSource); else addPropertyToPresentationalHintStyle(style, CSSPropertyID::Width, CSSValueID::Auto); if (!heightAttrFromSource.isNull()) addHTMLLengthToStyle(style, CSSPropertyID::Height, heightAttrFromSource); else addPropertyToPresentationalHintStyle(style, CSSPropertyID::Height, CSSValueID::Auto); if (!widthAttrFromSource.isNull() && !heightAttrFromSource.isNull()) applyAspectRatioFromWidthAndHeightAttributesToStyle(widthAttrFromSource, heightAttrFromSource, style); else addPropertyToPresentationalHintStyle(style, CSSPropertyID::AspectRatio, CSSValueID::Auto); } String HTMLImageElement::imageSourceURL() const { return m_bestFitImageURL.isEmpty() ? attributeWithoutSynchronization(srcAttr) : m_bestFitImageURL; } const AtomString& HTMLImageElement::currentSrc() { if (m_currentSrc.isNull()) { if (!m_currentURL.isEmpty()) m_currentSrc = AtomString(m_currentURL.string()); } return m_currentSrc; } void HTMLImageElement::setBestFitURLAndDPRFromImageCandidate(const ImageCandidate& candidate) { m_bestFitImageURL = candidate.string.toAtomString(); auto sourceURL = imageSourceURL(); // Only complete the URL if it's non-empty to avoid resolving "" to the document base URL. m_currentURL = sourceURL.isEmpty() ? URL() : protect(document())->encodingParseURL(sourceURL); m_currentSrc = { }; if (candidate.density >= 0) m_currentPixelDensity = candidate.density; if (CheckedPtr renderImage = dynamicDowncast(renderer())) renderImage->setCurrentPixelDensity(m_currentPixelDensity); } static String extractMIMETypeFromTypeAttributeForLookup(const String& typeAttribute) { auto semicolonIndex = typeAttribute.find(';'); if (semicolonIndex == notFound) return typeAttribute.trim(isASCIIWhitespace); return StringView(typeAttribute).left(semicolonIndex).trim(isASCIIWhitespace).toStringWithoutCopying(); } bool HTMLImageElement::isSupportedImageSourceType(const String& typeAttribute) { auto type = extractMIMETypeFromTypeAttributeForLookup(typeAttribute); if (type.isEmpty()) return true; return MIMETypeRegistry::isSupportedImageVideoOrSVGMIMEType(type); } ImageCandidate HTMLImageElement::bestFitSourceFromPictureElement() { RefPtr picture = pictureElement(); if (!picture) return { }; ImageCandidate candidate; for (RefPtr child = picture->firstChild(); child && child != this; child = child->nextSibling()) { auto* source = dynamicDowncast(*child); if (!source) continue; auto& srcset = source->attributeWithoutSynchronization(srcsetAttr); if (srcset.isEmpty()) continue; auto& typeAttribute = source->attributeWithoutSynchronization(typeAttr); if (!typeAttribute.isNull()) { if (!isSupportedImageSourceType(typeAttribute)) continue; } Ref document = this->document(); MQ::MediaQueryEvaluator evaluator { document->printing() ? printAtom() : screenAtom(), document }; auto& queries = source->parsedMediaAttribute(document.get()); LOG(MediaQueries, "HTMLImageElement %p bestFitSourceFromPictureElement evaluating media queries", this); auto result = evaluator.evaluate(queries); if (!evaluator.collectDynamicDependencies(queries).isEmpty()) m_dynamicMediaQueryResults.append({ queries, result }); if (!result) continue; // Per the spec, if the source has no sizes attribute, use the img's sizes attribute. auto& sourceSizesAttr = source->attributeWithoutSynchronization(sizesAttr); auto sizesString = sourceSizesAttr.isNull() ? attributeWithoutSynchronization(sizesAttr).string() : sourceSizesAttr.string(); SizesAttributeParser sizesParser(sizesString, document.get()); m_dynamicMediaQueryResults.appendVector(sizesParser.dynamicMediaQueryResults()); auto sourceSize = sizesParser.effectiveSize(); if (sizesParser.isAuto() && LazyLoading::isInLazyState(*this)) { if (auto layoutWidth = autoSizesLayoutWidth()) sourceSize = std::optional(*layoutWidth); } candidate = bestFitSourceForImageAttributes(document->deviceScaleFactor(), nullAtom(), srcset, sourceSize, [&](auto& candidate) { return m_imageLoader->shouldIgnoreCandidateWhenLoadingFromArchive(candidate); }); if (!candidate.isEmpty()) { setSourceElement(source); break; } } return candidate; } void HTMLImageElement::setIsUserAgentShadowRootResource() { m_imageLoader->setElementIsUserAgentShadowRootResource(true); } void HTMLImageElement::evaluateDynamicMediaQueryDependencies() { Ref document = this->document(); MQ::MediaQueryEvaluator evaluator { document->printing() ? printAtom() : screenAtom(), document }; auto hasChanges = [&] { for (auto& results : m_dynamicMediaQueryResults) { if (results.result != evaluator.evaluate(results.mediaQueryList)) return true; } return false; }(); if (!hasChanges) return; selectImageSource(RelevantMutation::No); } void HTMLImageElement::selectImageSource(RelevantMutation relevantMutation) { m_dynamicMediaQueryResults = { }; Ref document = this->document(); document->removeDynamicMediaQueryDependentImage(*this); // If sizes=auto is active with loading=lazy but the layout width is not // yet available, defer source selection. didAttachRenderers() and // RenderImage::layout() will re-invoke this. if (allowsAutoSizes() && !autoSizesLayoutWidth() && usesSrcsetOrPicture()) return; // First look for the best fit source from our parent if we have one. ImageCandidate candidate = bestFitSourceFromPictureElement(); if (candidate.isEmpty()) { setSourceElement(nullptr); auto srcAttribute = attributeWithoutSynchronization(srcAttr); auto srcsetAttribute = attributeWithoutSynchronization(srcsetAttr); // This is extremely common case. We should not invoke SizesAttributeParser at all. if (srcsetAttribute.isNull()) { if (srcAttribute.isNull()) candidate = { }; else candidate = ImageCandidate(StringViewWithUnderlyingString(srcAttribute, srcAttribute), DescriptorParsingResult(), ImageCandidate::SrcOrigin); } else { // If we don't have a or didn't find a source, then we use our own attributes. SizesAttributeParser sizesParser(attributeWithoutSynchronization(sizesAttr).string(), document.get()); m_dynamicMediaQueryResults.appendVector(sizesParser.dynamicMediaQueryResults()); auto sourceSize = sizesParser.effectiveSize(); if (sizesParser.isAuto() && LazyLoading::isInLazyState(*this)) { if (auto layoutWidth = autoSizesLayoutWidth()) sourceSize = std::optional(*layoutWidth); } candidate = bestFitSourceForImageAttributes(document->deviceScaleFactor(), srcAttribute, srcsetAttribute, sourceSize, [&](auto& candidate) { return m_imageLoader->shouldIgnoreCandidateWhenLoadingFromArchive(candidate); }); } } setBestFitURLAndDPRFromImageCandidate(candidate); m_imageLoader->updateFromElementIgnoringPreviousError(relevantMutation); if (!m_dynamicMediaQueryResults.isEmpty()) document->addDynamicMediaQueryDependentImage(*this); } bool HTMLImageElement::hasAutoSizesAttributeValue(StringView attributeValue) { return attributeValue.startsWithIgnoringASCIICase("auto"_s) && (attributeValue.length() == 4 || attributeValue[4] == ','); } bool HTMLImageElement::hasAutoSizes() const { return hasAutoSizesAttributeValue(attributeWithoutSynchronization(sizesAttr)); } void HTMLImageElement::scheduleAutoSizesResolution() { ASSERT(hasAutoSizes()); // Defer source selection to avoid mutating the render tree during layout. protect(protect(document())->eventLoop())->queueTask(TaskSource::DOMManipulation, [weakThis = WeakPtr { *this }] { RefPtr protectedThis = weakThis.get(); if (!protectedThis) return; protectedThis->selectImageSource(RelevantMutation::No); }); } void HTMLImageElement::attributeChanged(const QualifiedName& name, const AtomString& oldValue, const AtomString& newValue, AttributeModificationReason attributeModificationReason) { HTMLElement::attributeChanged(name, oldValue, newValue, attributeModificationReason); switch (name.nodeName()) { case AttributeNames::altAttr: if (CheckedPtr renderImage = dynamicDowncast(renderer())) renderImage->updateAltText(); if (isInSelectOrDataListSubtree()) { if (RefPtr parent = parentElement()) parent->notifyDescendantsChanged(); } break; case AttributeNames::srcAttr: case AttributeNames::srcsetAttr: case AttributeNames::sizesAttr: if (oldValue != newValue) selectImageSource(RelevantMutation::Yes); else m_imageLoader->updateFromElementIgnoringPreviousErrorToSameValue(); break; case AttributeNames::usemapAttr: { Ref treeScope = this->treeScope(); if (isInTreeScope() && !m_parsedUsemap.isNull()) treeScope->removeImageElementByUsemap(m_parsedUsemap, *this); m_parsedUsemap = parseHTMLHashNameReference(newValue); if (isInTreeScope() && !m_parsedUsemap.isNull()) treeScope->addImageElementByUsemap(m_parsedUsemap, *this); break; } case AttributeNames::loadingAttr: if (!LazyLoading::hasLazyAttributeValue(newValue)) loadDeferredImage(); else if (!isConnected() && !m_imageLoader->image()) { // An eager-to-lazy transition before the element is connected may need to defer a // pending error queued for an empty/whitespace source. Re-run to re-evaluate deferral. m_imageLoader->updateFromElementIgnoringPreviousError(); } break; case AttributeNames::referrerpolicyAttr: { auto oldReferrerPolicy = parseReferrerPolicy(oldValue, ReferrerPolicySource::ReferrerPolicyAttribute).value_or(ReferrerPolicy::EmptyString); auto newReferrerPolicy = parseReferrerPolicy(newValue, ReferrerPolicySource::ReferrerPolicyAttribute).value_or(ReferrerPolicy::EmptyString); if (oldReferrerPolicy != newReferrerPolicy) m_imageLoader->updateFromElementIgnoringPreviousError(RelevantMutation::Yes); break; } case AttributeNames::crossoriginAttr: if (parseCORSSettingsAttribute(oldValue) != parseCORSSettingsAttribute(newValue)) m_imageLoader->updateFromElementIgnoringPreviousError(RelevantMutation::Yes); break; case AttributeNames::nameAttr: { bool willHaveName = !newValue.isEmpty(); if (RefPtr document = dynamicDowncast(this->document()); document && m_hadNameBeforeAttributeChanged != willHaveName && isConnected() && !isInShadowTree()) { const AtomString& id = getIdAttribute(); if (!id.isEmpty() && id != getNameAttribute()) { if (willHaveName) document->addDocumentNamedItem(id, *this); else document->removeDocumentNamedItem(id, *this); } } m_hadNameBeforeAttributeChanged = willHaveName; break; } #if ENABLE(SPATIAL_IMAGE_CONTROLS) case AttributeNames::controlsAttr: SpatialImageControls::updateSpatialImageControls(*this); break; #endif default: break; } #if ENABLE(SERVICE_CONTROLS) if (isImageMenuEnabled()) ImageControlsMac::updateImageControls(*this); #endif } void HTMLImageElement::loadDeferredImage() { if (hasAutoSizes()) selectImageSource(RelevantMutation::No); m_imageLoader->loadDeferredImage(); } std::optional HTMLImageElement::autoSizesLayoutWidth() const { CheckedPtr box = renderBox(); if (!box) return { }; return box->contentBoxWidth().toFloat(); } void HTMLImageElement::lazyLoadIntersectionCallbackInvoked(bool isIntersecting) { if (!isIntersecting) return; loadDeferredImage(); LazyLoadElementObserver::unobserve(*this, protect(document())); } const AtomString& HTMLImageElement::altText() const { // lets figure out the alt text.. magic stuff // http://www.w3.org/TR/1998/REC-html40-19980424/appendix/notes.html#altgen // also heavily discussed by Hixie on bugzilla const AtomString& alt = attributeWithoutSynchronization(altAttr); if (!alt.isNull()) return alt; // fall back to title attribute return attributeWithoutSynchronization(titleAttr); } RenderPtr HTMLImageElement::createElementRenderer(UniqueRef&& style, const RenderTreePosition&) { if (style->content().isData()) return RenderElement::createFor(*this, WTF::move(style)); return createRenderer(RenderObject::Type::Image, *this, WTF::move(style), nullptr, m_currentPixelDensity); } bool HTMLImageElement::isReplaced(const Style::ComputedStyle* style) const { return !style || !style->content().isData(); } bool HTMLImageElement::canStartSelection() const { if (shadowRoot()) return HTMLElement::canStartSelection(); return false; } bool HTMLImageElement::isInteractiveContent() const { return hasAttributeWithoutSynchronization(usemapAttr); } void HTMLImageElement::didAttachRenderers() { CheckedPtr renderImage = dynamicDowncast(renderer()); if (!renderImage) return; if (m_imageLoader->hasPendingBeforeLoadEvent()) return; #if ENABLE(SERVICE_CONTROLS) ImageControlsMac::updateImageControls(*this); #endif CheckedRef renderImageResource = renderImage->imageResource(); if (renderImageResource->cachedImage()) return; renderImageResource->setCachedImage(protect(m_imageLoader->image())); // If we have no image at all because we have no src attribute, set // image height and width for the alt text instead. if (!m_imageLoader->image() && !renderImageResource->cachedImage()) renderImage->setImageSizeForAltText(); // https://html.spec.whatwg.org/multipage/images.html#relevant-mutations // "If the element allows auto-sizes: the element starts [...] being rendered" if (allowsAutoSizes()) scheduleAutoSizesResolution(); } Node::NeedsPostConnectionSteps HTMLImageElement::insertionSteps(InsertionType insertionType, ContainerNode& parentOfInsertedTree) { FormAssociatedElement::elementInsertedIntoAncestor(*this, insertionType); if (!form()) resetFormOwner(); // Insert needs to complete first, before we start updating the loader. Loader dispatches events which could result // in callbacks back to this node. Node::NeedsPostConnectionSteps insertNotificationRequest = HTMLElement::insertionSteps(insertionType, parentOfInsertedTree); if (insertionType.treeScopeChanged && !m_parsedUsemap.isNull()) protect(treeScope())->addImageElementByUsemap(m_parsedUsemap, *this); if (auto* parentPicture = dynamicDowncast(parentOfInsertedTree); parentPicture && &parentOfInsertedTree == parentElement()) { // FIXME: When the hack in HTMLConstructionSite::createHTMLElementOrFindCustomElementInterface to eagerly call setPictureElement is removed, we can just assert !pictureElement(). ASSERT(!pictureElement() || pictureElement() == &parentOfInsertedTree); setPictureElement(parentPicture); selectImageSource(RelevantMutation::Yes); return insertNotificationRequest; } // If we have been inserted from a renderer-less document, // our loader may have not fetched the image, so do it now. if (insertionType.connectedToDocument && !m_imageLoader->image()) m_imageLoader->updateFromElement(); return insertNotificationRequest; } void HTMLImageElement::removingSteps(RemovalType removalType, ContainerNode& oldParentOfRemovedTree) { if (removalType.treeScopeChanged && !m_parsedUsemap.isNull()) protect(oldParentOfRemovedTree.treeScope())->removeImageElementByUsemap(m_parsedUsemap, *this); if (is(oldParentOfRemovedTree) && !parentElement()) { ASSERT(pictureElement() == &oldParentOfRemovedTree); setPictureElement(nullptr); selectImageSource(RelevantMutation::Yes); } HTMLElement::removingSteps(removalType, oldParentOfRemovedTree); FormAssociatedElement::elementRemovedFromAncestor(*this, removalType); #if ENABLE(IMAGE_ELEMENT_IMMERSIVE) if (removalType.disconnectedFromDocument) exitImmersiveIfNeeded(); #endif } void HTMLImageElement::movingSteps(MovingType movingType, ContainerNode& oldParent) { HTMLElement::movingSteps(movingType, oldParent); if (!m_parsedUsemap.isNull()) { if (movingType.didRemoveFromOldTreeScope) protect(oldParent.treeScope())->removeImageElementByUsemap(m_parsedUsemap, *this); if (movingType.didInsertIntoNewTreeScope) protect(treeScope())->addImageElementByUsemap(m_parsedUsemap, *this); } if (!movingType.isSubtreeRoot) return; if (RefPtr parentPicture = dynamicDowncast(parentElement())) { setPictureElement(parentPicture.get()); selectImageSource(RelevantMutation::Yes); } else if (RefPtr oldParentPicture = dynamicDowncast(oldParent)) { setPictureElement(nullptr); selectImageSource(RelevantMutation::Yes); } } HTMLPictureElement* HTMLImageElement::pictureElement() const { return m_pictureElement.get(); } void HTMLImageElement::setPictureElement(HTMLPictureElement* pictureElement) { m_pictureElement = pictureElement; } LayoutSize HTMLImageElement::densityCorrectedNaturalSize() const { // https://html.spec.whatwg.org/multipage/images.html#density-corrected-intrinsic-width-and-height RefPtr image = m_imageLoader->image(); if (!image || !image->hasImage()) return { }; auto naturalDimensions = image->naturalDimensions(ImageOrientation::Orientation::FromImage); return LayoutSize(HTMLImageDensityCorrectedSizing { m_currentPixelDensity }.resolve(naturalDimensions).size()); } unsigned HTMLImageElement::width() { if (inRenderedDocument()) protect(document())->updateLayoutIgnorePendingStylesheets({ LayoutOptions::TreatContentVisibilityHiddenAsVisible, LayoutOptions::TreatContentVisibilityAutoAsVisible }, this); if (!renderer()) { // check the attribute first for an explicit pixel value if (auto optionalWidth = parseHTMLNonNegativeInteger(attributeWithoutSynchronization(widthAttr))) return optionalWidth.value(); // otherwise fall back to what naturalWidth returns return densityCorrectedNaturalSize().width().toUnsigned(); } CheckedPtr box = renderBox(); if (!box) return 0; LayoutRect contentRect = box->contentBoxRect(); return Style::unapplyingZoom(contentRect.width(), *box).round(); } unsigned HTMLImageElement::height() { if (inRenderedDocument()) protect(document())->updateLayoutIgnorePendingStylesheets({ LayoutOptions::TreatContentVisibilityHiddenAsVisible, LayoutOptions::TreatContentVisibilityAutoAsVisible }, this); if (!renderer()) { // check the attribute first for an explicit pixel value if (auto optionalHeight = parseHTMLNonNegativeInteger(attributeWithoutSynchronization(heightAttr))) return optionalHeight.value(); // otherwise fall back to what naturalHeight returns return densityCorrectedNaturalSize().height().toUnsigned(); } CheckedPtr box = renderBox(); if (!box) return 0; LayoutRect contentRect = box->contentBoxRect(); return Style::unapplyingZoom(contentRect.height(), *box).round(); } unsigned HTMLImageElement::naturalWidth() const { return densityCorrectedNaturalSize().width().toUnsigned(); } unsigned HTMLImageElement::naturalHeight() const { return densityCorrectedNaturalSize().height().toUnsigned(); } bool HTMLImageElement::isURLAttribute(const Attribute& attribute) const { return attribute.name() == srcAttr || attribute.name() == lowsrcAttr || attribute.name() == longdescAttr || (attribute.name() == usemapAttr && attribute.value().string()[0] != '#') || HTMLElement::isURLAttribute(attribute); } bool HTMLImageElement::attributeContainsURL(const Attribute& attribute) const { return attribute.name() == srcsetAttr || HTMLElement::attributeContainsURL(attribute); } String HTMLImageElement::completeURLsInAttributeValue(const URL& base, const Attribute& attribute, ResolveURLs resolveURLs) const { if (attribute.name() == srcsetAttr) { if (resolveURLs == ResolveURLs::No) return attribute.value(); Vector imageCandidates = parseImageCandidatesFromSrcsetAttribute(StringView(attribute.value())); if (resolveURLs == ResolveURLs::NoExcludingURLsForPrivacy) { bool needsToResolveURLs = false; for (const auto& candidate : imageCandidates) { auto urlString = candidate.string.toString(); Ref document = this->document(); auto completeURL = base.isNull() ? document->encodingParseURL(urlString) : URL(base, urlString); if (document->shouldMaskURLForBindings(completeURL)) { needsToResolveURLs = true; break; } } if (!needsToResolveURLs) return attribute.value(); } StringBuilder result; for (const auto& candidate : imageCandidates) { if (&candidate != &imageCandidates[0]) result.append(", "_s); result.append(resolveURLStringIfNeeded(candidate.string.toString(), resolveURLs, base)); if (candidate.density != UninitializedDescriptor) result.append(' ', candidate.density, 'x'); if (candidate.resourceWidth != UninitializedDescriptor) result.append(' ', candidate.resourceWidth, 'w'); } return result.toString(); } return HTMLElement::completeURLsInAttributeValue(base, attribute, resolveURLs); } Attribute HTMLImageElement::replaceURLsInAttributeValue(const Attribute& attribute, const CSS::SerializationContext& serializationContext) const { if (attribute.name() != srcsetAttr) return attribute; if (serializationContext.replacementURLStrings.isEmpty()) return attribute; return Attribute { srcsetAttr, AtomString { replaceURLsInSrcsetAttribute(*this, StringView(attribute.value()), serializationContext) } }; } bool HTMLImageElement::matchesUsemap(const AtomString& name) const { return m_parsedUsemap == name; } RefPtr HTMLImageElement::associatedMapElement() const { return protect(treeScope())->getImageMap(m_parsedUsemap); } int HTMLImageElement::x() const { protect(document())->updateLayoutIgnorePendingStylesheets({ LayoutOptions::TreatContentVisibilityHiddenAsVisible, LayoutOptions::TreatContentVisibilityAutoAsVisible }, this); CheckedPtr renderer = this->renderer(); if (!renderer) return 0; // FIXME: This doesn't work correctly with transforms. return renderer->localToAbsolute().x(); } int HTMLImageElement::y() const { protect(document())->updateLayoutIgnorePendingStylesheets({ LayoutOptions::TreatContentVisibilityHiddenAsVisible, LayoutOptions::TreatContentVisibilityAutoAsVisible }, this); CheckedPtr renderer = this->renderer(); if (!renderer) return 0; // FIXME: This doesn't work correctly with transforms. return renderer->localToAbsolute().y(); } bool HTMLImageElement::complete() const { return m_imageLoader->imageComplete(); } String HTMLImageElement::decoding() const { switch (decodingMode()) { case DecodingMode::Auto: break; case DecodingMode::Synchronous: return "sync"_s; case DecodingMode::Asynchronous: return "async"_s; } return autoAtom(); } DecodingMode HTMLImageElement::decodingMode() const { const AtomString& decodingMode = attributeWithoutSynchronization(decodingAttr); if (equalLettersIgnoringASCIICase(decodingMode, "sync"_s)) return DecodingMode::Synchronous; if (equalLettersIgnoringASCIICase(decodingMode, "async"_s)) return DecodingMode::Asynchronous; return DecodingMode::Auto; } void HTMLImageElement::decode(Ref&& promise) { return m_imageLoader->decode(WTF::move(promise)); } void HTMLImageElement::addSubresourceAttributeURLs(OrderedHashSet& urls) const { HTMLElement::addSubresourceAttributeURLs(urls); Ref document = this->document(); addSubresourceURL(urls, document->encodingParseURL(imageSourceURL())); // FIXME: What about when the usemap attribute begins with "#"? addSubresourceURL(urls, document->encodingParseURL(attributeWithoutSynchronization(usemapAttr))); } void HTMLImageElement::addCandidateSubresourceURLs(OrderedHashSet& urls) const { auto src = attributeWithoutSynchronization(srcAttr); if (!src.isEmpty()) { URL url { resolveURLStringIfNeeded(src) }; if (!url.isNull()) urls.add(url); } getURLsFromSrcsetAttribute(*this, attributeWithoutSynchronization(srcsetAttr), urls); } void HTMLImageElement::didMoveToNewDocument(Document& oldDocument, Document& newDocument) { ActiveDOMObject::didMoveToNewDocument(newDocument); oldDocument.removeDynamicMediaQueryDependentImage(*this); m_imageLoader->elementDidMoveToNewDocument(oldDocument); selectImageSource(RelevantMutation::No); HTMLElement::didMoveToNewDocument(oldDocument, newDocument); if (RefPtr element = pictureElement()) element->sourcesChanged(); } bool HTMLImageElement::isServerMap() const { if (!hasAttributeWithoutSynchronization(ismapAttr)) return false; const AtomString& usemap = attributeWithoutSynchronization(usemapAttr); // If the usemap attribute starts with '#', it refers to a map element in the document. return !usemap.startsWith('#'); } String HTMLImageElement::crossOrigin() const { return parseCORSSettingsAttribute(attributeWithoutSynchronization(crossoriginAttr)); } bool HTMLImageElement::allowsOrientationOverride() const { if (auto* cachedImage = this->cachedImage()) return cachedImage->allowsOrientationOverride(); return true; } ImageOrientation HTMLImageElement::orientationForSourceImage() { if (!allowsOrientationOverride()) return ImageOrientation::Orientation::FromImage; if (CheckedPtr renderer = this->renderer()) return Style::toPlatform(renderer->style().imageOrientationOutOfLine()).orientation(); if (CheckedPtr computedStyle = this->computedStyle()) return Style::toPlatform(computedStyle->imageOrientationOutOfLine()).orientation(); return ImageOrientation::Orientation::FromImage; } ImageRequestState HTMLImageElement::currentRequestState() const { return m_imageLoader->currentRequestState(); } RefPtr HTMLImageElement::sourceImage() const { return image(); } Image* HTMLImageElement::image() const { if (RefPtr cachedImage = this->cachedImage()) return cachedImage->image(); return nullptr; } bool HTMLImageElement::allowsAnimation() const { RefPtr image = this->image(); if (!image) return false; switch (image->animationOverride()) { case ImageAnimationOverride::None: return document().page() && document().page()->imageAnimationEnabled(); case ImageAnimationOverride::Play: return true; case ImageAnimationOverride::Pause: return false; } RELEASE_ASSERT_NOT_REACHED(); } Ref HTMLImageElement::imageAnimationTimeline() const { if (m_imageAnimationTimeline) return *m_imageAnimationTimeline; RefPtr page = document().page(); return page ? page->imageAnimationTimeline() : ImageAnimationTimeline::normal(); } void HTMLImageElement::clearImageAnimationTimeline() { RefPtr timeline = std::exchange(m_imageAnimationTimeline, nullptr); if (!timeline) return; if (timeline->state() == ImageAnimationTimeline::State::Running) { if (RefPtr page = document().page()) page->removeIndividuallyPlayingAnimationElement(*this); } } void HTMLImageElement::setAnimationOverride(ImageAnimationOverride animationOverride) { if (RefPtr image = this->image()) { image->setAnimationOverride(animationOverride); // A new timeline for each change, so that a pause holds the image where it is when next drawn. switch (animationOverride) { case ImageAnimationOverride::None: m_imageAnimationTimeline = nullptr; break; case ImageAnimationOverride::Play: m_imageAnimationTimeline = ImageAnimationTimeline::createRunning(); break; case ImageAnimationOverride::Pause: m_imageAnimationTimeline = ImageAnimationTimeline::createPaused(); break; } if (CheckedPtr renderer = this->renderer()) renderer->repaint(); if (RefPtr page = document().page()) { if (animationOverride == ImageAnimationOverride::Play) page->addIndividuallyPlayingAnimationElement(*this); else page->removeIndividuallyPlayingAnimationElement(*this); } } } #if ENABLE(ATTACHMENT_ELEMENT) void HTMLImageElement::setAttachmentElement(Ref&& attachment) { AttachmentAssociatedElement::setAttachmentElement(WTF::move(attachment)); #if ENABLE(SERVICE_CONTROLS) bool shouldEnableImageMenu = true; #if ENABLE(MULTI_REPRESENTATION_HEIC) shouldEnableImageMenu = !isMultiRepresentationHEIC(); #endif setImageMenuEnabled(shouldEnableImageMenu); #endif // ENABLE(SERVICE_CONTROLS) } #endif // ENABLE(ATTACHMENT_ELEMENT) #if ENABLE(SERVICE_CONTROLS) bool HTMLImageElement::childShouldCreateRenderer(const Node& child) const { return hasShadowRootParent(child) && HTMLElement::childShouldCreateRenderer(child); } #endif #if ENABLE(CONTENT_CHANGE_OBSERVER) // FIXME: We should find a better place for the touch callout logic. See rdar://problem/48937767. bool HTMLImageElement::willRespondToMouseClickEventsWithEditability(Editability editability, IgnoreTouchCallout ignoreTouchCallout) const { #if ENABLE(WEBKIT_TOUCH_CALLOUT_CSS_PROPERTY) CheckedPtr renderer = this->renderer(); bool touchCalloutIsDefault = !renderer || renderer->style().touchCallout() == Style::WebkitTouchCallout::Default; #else bool touchCalloutIsDefault = true; #endif if (ignoreTouchCallout == IgnoreTouchCallout::No && touchCalloutIsDefault) return true; return HTMLElement::willRespondToMouseClickEventsWithEditability(editability); } bool HTMLImageElement::willRespondToMouseClickEventsWithEditability(Editability editability) const { return willRespondToMouseClickEventsWithEditability(editability, IgnoreTouchCallout::No); } #endif #if USE(SYSTEM_PREVIEW) bool HTMLImageElement::isSystemPreviewImage() const { if (!document().settings().systemPreviewEnabled()) return false; RefPtr parent = parentElement(); if (RefPtr anchorElement = dynamicDowncast(parent)) return anchorElement->isSystemPreviewLink(); if (RefPtr pictureElement = dynamicDowncast(parent)) return pictureElement->isSystemPreviewImage(); return false; } #endif #if ENABLE(MULTI_REPRESENTATION_HEIC) bool HTMLImageElement::isMultiRepresentationHEIC() const { if (!m_sourceElement) return false; auto& typeAttribute = m_sourceElement->attributeWithoutSynchronization(typeAttr); return typeAttribute == "image/x-apple-adaptive-glyph"_s; } #endif void HTMLImageElement::copyNonAttributePropertiesFromElement(const Element& source) { #if ENABLE(ATTACHMENT_ELEMENT) auto& sourceImage = downcast(source); copyAttachmentAssociatedPropertiesFromElement(sourceImage); #endif Element::copyNonAttributePropertiesFromElement(source); } CachedImage* HTMLImageElement::cachedImage() const { return m_imageLoader->image(); } void HTMLImageElement::setLoadManually(bool loadManually) { m_imageLoader->setLoadManually(loadManually); } bool HTMLImageElement::virtualHasPendingActivity() const { return m_imageLoader->hasPendingActivity(); } size_t HTMLImageElement::pendingDecodePromisesCountForTesting() const { return m_imageLoader->pendingDecodePromisesCountForTesting(); } bool HTMLImageElement::usesSrcsetOrPicture() const { return !attributeWithoutSynchronization(srcsetAttr).isNull() || !!pictureElement(); } AtomString HTMLImageElement::srcsetForBindings() const { return getAttributeForBindings(srcsetAttr); } bool HTMLImageElement::isDeferred() const { return m_imageLoader->isDeferred(); } // https://html.spec.whatwg.org/multipage/embedded-content.html#allows-auto-sizes bool HTMLImageElement::allowsAutoSizes() const { return hasAutoSizes() && LazyLoading::isInLazyState(*this); } String HTMLImageElement::referrerPolicyForBindings() const { return referrerPolicyToString(referrerPolicy()); } ReferrerPolicy HTMLImageElement::referrerPolicy() const { return parseReferrerPolicy(attributeWithoutSynchronization(referrerpolicyAttr), ReferrerPolicySource::ReferrerPolicyAttribute).value_or(ReferrerPolicy::EmptyString); } HTMLSourceElement* HTMLImageElement::sourceElement() const { return m_sourceElement.get(); } void HTMLImageElement::setSourceElement(HTMLSourceElement* sourceElement) { if (m_sourceElement == sourceElement) return; m_sourceElement = sourceElement; invalidateAttributeMapping(); } void HTMLImageElement::invalidateAttributeMapping() { invalidatePresentationalHintStyle(); } Ref HTMLImageElement::cloneElementWithoutAttributesAndChildren(Document& document, CustomElementRegistry*) const { auto clone = create(document); #if ENABLE(ATTACHMENT_ELEMENT) cloneAttachmentAssociatedElementWithoutAttributesAndChildren(clone, document); #endif return clone; } String HTMLImageElement::fetchPriorityForBindings() const { return convertEnumerationToString(fetchPriority()); } RequestPriority HTMLImageElement::fetchPriority() const { return parseEnumerationFromString(attributeWithoutSynchronization(fetchpriorityAttr)).value_or(RequestPriority::Auto); } bool HTMLImageElement::originClean(const SecurityOrigin& origin) const { UNUSED_PARAM(origin); RefPtr cachedImage = this->cachedImage(); if (!cachedImage) return true; RefPtr image = cachedImage->image(); if (!image) return true; if (image->renderingTaintsOrigin()) return false; if (image->sourceURL().protocolIsData()) return true; if (cachedImage->isCORSCrossOrigin()) return false; ASSERT(cachedImage->origin()); ASSERT(origin.toString() == cachedImage->origin()->toString()); return true; } IntersectionObserverData& HTMLImageElement::ensureIntersectionObserverData() { if (!m_intersectionObserverData) lazyInitialize(m_intersectionObserverData, makeUnique()); return *m_intersectionObserverData; } IntersectionObserverData* HTMLImageElement::intersectionObserverDataIfExists() const { return m_intersectionObserverData.get(); } #if ENABLE(IMAGE_ELEMENT_IMMERSIVE) void HTMLImageElement::suspend(ReasonForSuspension reason) { if (reason == ReasonForSuspension::BackForwardCache) exitImmersiveIfNeeded(); } void HTMLImageElement::stop() { exitImmersiveIfNeeded(); } void HTMLImageElement::exitImmersiveIfNeeded() { if (RefPtr documentImmersive = document().immersiveIfExists()) documentImmersive->exitRemovedImmersiveElementIfNeeded(this, [] { }); } bool HTMLImageElement::isImmersiveEnabled() const { return document().settings().imageElementImmersiveEnabled(); } void HTMLImageElement::prepareImmersivePresentation(CompletionHandler)>&& completion) { // `src` can change while the consent prompt is up. if (auto error = immersiveImageError()) return completion(WTF::move(*error)); completion({ }); } std::optional HTMLImageElement::immersiveImageError() const { RefPtr image = this->image(); if (!image || !image->isPanorama()) return Exception { ExceptionCode::InvalidStateError, "requestImmersive() requires a panoramic image."_s }; return std::nullopt; } void HTMLImageElement::requestImmersive(DOMPromiseDeferred&& promise) { if (auto error = immersiveImageError()) return promise.reject(WTF::move(*error)); protect(document().immersive())->requestImmersive(this, [promise = WTF::move(promise)](ExceptionOr result) mutable { if (result.hasException()) { promise.reject(result.releaseException()); return; } promise.resolve(); }); } #endif }