mirror of
https://github.com/servo/servo
synced 2026-05-12 01:46:28 +02:00
This patch adds support for rendering static inline SVG documents in the
DOM tree by serializing the SVGElement's subtree and leveraging the
existing resvg based SVG stack for rendering. Serialiing the subtree is
necessary as resvg's tree representation (roxmltree) is immutable, so we
can't construct the tree incrementally.
Few other design choices here:
1. The `SVGSVGElement` is now treated as a replaced element and the
layout code is responsible for plumbing the serialized SVG source
(encoded as a base64 data: url) into the image cache, much like how
background images are handled.
2. The serialization is done on the script thread after an initial
layout pass. This is necessary because the serialization code asserts
that it is invoked from script thread i.e we can't call it from layout
workers.
3. The serialized SVG data: url is cached to avoid recomputing it on
subsequent layouts. The cache is invalidated when the SVGSVGElement's
subtree is mutated.
The original SVGSVGElement code was behind the `dom_svg_enabled` pref.
This patch also removes the preference and make SVG support using resvg
available unconditionally.
Below is the analysis of the new test failures:
These tests use inline SVG but used to pass by accident.
They now fail because they contain SVG with no intrinsic
sizing which is not handled by resvg in a way that would
allows us to distinguish it from the sized case. The same
limitation applies to non-inline SVG.
- /css/CSS2/positioning/absolute-replaced-width-003a.xht
- /css/CSS2/positioning/absolute-replaced-width-003b.xht
- /css/CSS2/positioning/absolute-replaced-width-003c.xht
These tests employ CSS styles in the HTML that
target the elements in inline SVG, which is not currently
supported.
-
/css/compositing/mix-blend-mode/mix-blend-mode-plus-lighter-svg-basic.html
- /css/compositing/mix-blend-mode/mix-blend-mode-plus-lighter-svg.html
This is a tentative test that uses the unsupported 'border-shape' CSS
property. The ref uses SVG, so it used to pass accidentally. The ref
still doesn't render correctly since it also relies on styling SVG
elements using CSS classes in the HTML (instead of inline in SVG).
- /css/css-borders/tentative/border-shape/border-shape-stroke.html
These tests use the attribute 'clip-path=circle(...)' in the
test, but this doesn't seem to work in resvg.
- /css/css-masking/clip-path/clip-path-borderBox-1b.html
- /css/css-masking/clip-path/clip-path-contentBox-1b.html
- /css/css-masking/clip-path/clip-path-contentBox-1c.html
- /css/css-masking/clip-path/clip-path-fillBox-1b.html
- /css/css-masking/clip-path/clip-path-marginBox-1a.html
- /css/css-masking/clip-path/clip-path-paddingBox-1b.html
- /css/css-masking/clip-path/clip-path-strokeBox-1b.html
- /css/css-masking/clip-path/clip-path-strokeBox-1c.html
- /css/css-masking/clip-path/clip-path-viewBox-1a.html
- /css/css-masking/clip-path/clip-path-viewBox-1b.html
- /css/css-masking/clip-path/clip-path-viewBox-1d.html
- /css/css-masking/clip-path/svg-clip-path-circle-offset.html
- /css/css-masking/clip-path/svg-clip-path-ellipse-offset.html
Additionally, the below two tests use a `foreignObject` SVG element
which
embeds a html div fragment. This is also not supported by resvg.
- /css/css-masking/clip-path/clip-path-viewBox-1d.html
- /css/css-masking/clip-path/clip-path-fillBox-1b.html
The following test fails because of apparent pixel differences
between a circle rendered purely using CSS clip-path vs a circle
rendered in SVG using resvg.
- /css/css-masking/clip-path/clip-path-contentBox-1c.html
These tests style the inline SVG elements using CSS in the HTML or
separate stylesheet. This is not supported by this implementation.
- /css-transforms/document-styles/svg-document-styles-{001..004}.html
- /css-transforms/document-styles/svg-document-styles-012.html
- /css-transforms/external-styles/svg-external-styles-{001..004}.html
- /css-transforms/external-styles/svg-external-styles-014.html
These tests seem like they should pass, but they fail because of what
seems like an anti-aliasing issue in the rendering engine. The
transformed element has a thin outline which is causing pixel difference
with the ref:
- /css/css-transforms/group/svg-transform-group-008.html
- /css/css-transforms/group/svg-transform-group-009.html
- /css/css-transforms/group/svg-transform-nested-009.html
- /css/css-transforms/group/svg-transform-nested-013.html
- /css/css-transforms/group/svg-transform-nested-014.html
- /css/css-transforms/group/svg-transform-nested-018.html
- /css/css-transforms/group/svg-transform-nested-019.html
- /css/css-transforms/group/svg-transform-nested-008.html
The below tests fail because resvg is calculating the wrong size for the
'rect' inside the SVG. The dimensions of the SVG are established via the
CSS in the HTML, so it seems resvg is using incorrect coordinates for
the children of the svg when explict width/height are not specified in
the root svg element.
- /css/css-transforms/group/svg-transform-group-011.html
- /css/css-transforms/group/svg-transform-nested-021.html
- /css/css-transforms/group/svg-transform-nested-029.html
All these tests use an SVG that doesn't have width nor height attributes
and this causes resvg to use incorrect coordinates for the SVG's
children. In addition, the following tests use the CSS syntax for
transforms inside the SVG (using style attribute) which is not supported
by resvg (it only supports the SVG 1.1 transform syntax).
- /css/css-transforms/inline-styles/svg-inline-styles-{001..004}.html
- /css/css-transforms/inline-styles/svg-inline-styles-012.html
In the case of these four tests, the `style` attribute specifies an
invalid transform, but resvg doesn't fallback to the transform specified
via the `transform` attribute on the same element.
- /css/css-transforms/inline-styles/svg-inline-styles-005.html
- /css/css-transforms/inline-styles/svg-inline-styles-006.html
- /css/css-transforms/inline-styles/svg-inline-styles-010.html
- /css/css-transforms/inline-styles/svg-inline-styles-013.html
The following test fails because of the lack of width/height in SVG as
described above but it also exposes gaps in our CSS tranform
implementation.
- /css/css-transforms/preserve3d-and-filter-with-perspective.html
These tests failure because resvg doesn't handle the SVG without
explicit width and height, but specified via CSS in the HTML. In
addition, there are pixel differences between the ref due to
antialiasing issues.
- /css/css-transforms/matrix/svg-matrix-{005...008}.html
- /css/css-transforms/matrix/svg-matrix-010.html
- /css/css-transforms/matrix/svg-matrix-012.html
- /css/css-transforms/matrix/svg-matrix-{015..069}.html
- /css/css-transforms/rotate/svg-rotate-angle-45-001.html
- /css/css-transforms/rotate/svg-rotate-angle-45-011.html
- /css/css-transforms/rotate/svg-rotate-angle-45-022.html
- /css/css-transforms/scale/svg-scale-006.html
- /css/css-transforms/scale/svg-scale-007.html
These tests seem to be failing due to some sort of antialiasing issue,
where a transformed SVG element has a thin border that causes pixel
differences compared to the solid colored reference.
- /css/css-transforms/skewX/svg-skewx-001.html
- /css/css-transforms/skewX/svg-skewx-006.html
- /css/css-transforms/skewX/svg-skewx-011.html
- /css/css-transforms/skewX/svg-skewx-016.html
- /css/css-transforms/skewX/svg-skewx-021.html
- /css/css-transforms/skewX/svg-skewxy-001.html
- /css/css-transforms/skewY/svg-skewy-001.html
- /css/css-transforms/skewY/svg-skewy-006.html
- /css/css-transforms/skewY/svg-skewy-011.html
- /css/css-transforms/skewY/svg-skewy-016.html
- /css/css-transforms/skewY/svg-skewy-021.html
These tests specify several SVG attributes such as transform,
vector-effect etc via CSS in the HTML (rather than inline in SVG). The
current implementation doesn't support this.
- /css/css-transforms/transform-box/stroke-box-mutation-001.html
- /css/css-transforms/transform-box/stroke-box-mutation-002.html
- /css/css-transforms/transform-box/stroke-box-mutation-003.html
- /css/css-transforms/transform-box/stroke-box-mutation-004.html
- /css/css-transforms/transform-box/svgbox-stroke-box-002.html
- /css/css-transforms/transform-box/svgbox-stroke-box-003.html
- /css/css-transforms/transform-box/svgbox-stroke-box-004.html
- /css/css-transforms/transform-box/svgbox-stroke-box-005.html
These tests depend on 'transform-origin' specified on an element inside
an SVG, but this transform is influenced by the 'tranform-box' set via
CSS in the HTML itself (not the SVG). The current implementation doesn't
support styling the SVG using document styles, so these tests just fail.
- /css/css-transforms/transform-origin/svg-origin-relative-length-*.html
These tests check the fallback behaviour when invalid syntax is
encountered in the 'transform-origin' value. resvg doesn't correctly
fallback to 0,0 causing the tests to fail.
-
/css/css-transforms/transform-origin/svg-origin-relative-length-invalid-001.html
-
/css/css-transforms/transform-origin/svg-origin-relative-length-invalid-002.html
-
/css/css-transforms/transform-origin/svg-origin-relative-length-invalid-003.html
-
/css/css-transforms/transform-origin/svg-origin-relative-length-invalid-004.html
These tests use unimplemented Canvas APIs like 'beginLayer' and
the 'CanvasFilter' constructor and hence fail at runtime.
-
/html/canvas/element/filters/2d.filter.canvasFilterObject.gaussianBlur.tentative.html
-
/html/canvas/element/filters/2d.filter.layers.gaussianBlur.tentative.html
-
/html/canvas/element/layers/2d.layer.anisotropic-blur.isotropic.tentative.html
-
/html/canvas/element/layers/2d.layer.anisotropic-blur.mostly-x.tentative.html
-
/html/canvas/element/layers/2d.layer.anisotropic-blur.mostly-y.tentative.html
-
/html/canvas/element/layers/2d.layer.anisotropic-blur.x-only.tentative.html
-
/html/canvas/element/layers/2d.layer.anisotropic-blur.y-only.tentative.html
-
/html/canvas/element/layers/2d.layer.css-filters.blur-and-shadow.tentative.html
- /html/canvas/element/layers/2d.layer.css-filters.blur.tentative.html
- /html/canvas/element/layers/2d.layer.css-filters.shadow.tentative.html
- /html/canvas/element/layers/2d.layer.ctm.layer-filter.tentative.html
-
/html/canvas/offscreen/filters/2d.filter.canvasFilterObject.dropShadow.tentative.html
-
/html/canvas/offscreen/filters/2d.filter.canvasFilterObject.gaussianBlur.tentative.html
-
/html/canvas/offscreen/filters/2d.filter.layers.dropShadow.tentative.html
-
/html/canvas/offscreen/filters/2d.filter.layers.gaussianBlur.tentative.html
-
/html/canvas/offscreen/layers/2d.layer.anisotropic-blur.isotropic.tentative.html
-
/html/canvas/offscreen/layers/2d.layer.anisotropic-blur.mostly-x.tentative.html
-
/html/canvas/offscreen/layers/2d.layer.anisotropic-blur.mostly-y.tentative.html
-
/html/canvas/offscreen/layers/2d.layer.anisotropic-blur.x-only.tentative.html
-
/html/canvas/offscreen/layers/2d.layer.anisotropic-blur.y-only.tentative.html
-
/html/canvas/offscreen/layers/2d.layer.css-filters.blur-and-shadow.tentative.html
- /html/canvas/offscreen/layers/2d.layer.css-filters.blur.tentative.html
-
/html/canvas/offscreen/layers/2d.layer.css-filters.shadow.tentative.html
- /html/canvas/offscreen/layers/2d.layer.ctm.layer-filter.tentative.html
These tests fail because resvg doesn't seem to honour the 'translate'
CSS property specified on an SVG element using an inline 'style'
attribute.
- /css/css-transforms/translate/svg-translate-with-units.html
-
/css/css-transforms/translate/translate-and-transform-attribute-in-svg.html
-
/css/css-transforms/translate/translate-and-transform-css-property-in-svg.html
- /css/css-transforms/translate/translate-in-svg.html
These tests seem to fail due to the filter effect implementation in
resvg either not being complete or spec compliant.
- /css/filter-effects/feconvolve-divisor.html
- /css/filter-effects/feconvolve-region-001.html
- /css/filter-effects/feconvolve-region-002.html
- /css/filter-effects/filter-subregion-01.html
- /css/filter-effects/svg-feimage-002.html
- /css/filter-effects/svg-feimage-003.html
- /css/filter-effects/svg-feimage-004.html
- /css/filter-effects/svg-feoffset-001.html
The test /css/filter-effects/svg-feimage-004.html should ideally PASS
but currently fails because we don't propagate height/width set using
CSS in HTML element to the root SVG, so resvg uses the wrong dimensions
when rendering the children of the SVG.
These failures are due to deficienies in our current implementation
i.e we don't support styling SVG elements using CSS in HTML.
-
/css/css-transforms/gradientTransform/svg-gradientTransform-combination-001.html
- /css/selectors/sharing-in-svg-use.html
The below test fails as our current implementation relies on resvg to
tell us the intrinsic ratio of the SVG, but this doesn't always work
correctly.
- /css/css-sizing/svg-intrinsic-size-005.html
This failure is due to lack of proper fallback to no-op transform in
resvg when the `rotate()` syntax is specified with an invalid list e.g
`rotate(90,)`.
- /css/css-transforms/rotate/svg-rotate-3args-invalid-002.html
This test only passes in CI and based on the raw log output, it seems
that no text inside the SVG is rendered in the CI. This could be an font
stack related issue.
- /css/css-display/display-contents-svg-elements.html
This test asserts that the CSP blocks loads triggered using `use`
elements in SVG. It used to TIMEOUT as without inline SVG support, no
CSP violation event was triggered. It fails now since the event is now
triggered for the load of the SVG itself (our current implementation
loads inline SVGs as serialized base64 data: urls). This doesn't match
the blocked URL in the use element though.
- /content-security-policy/img-src/svg-use-blocked.tentative.html
Signed-off-by: Mukilan Thiyagarajan <mukilan@igalia.com>
Signed-off-by: Mukilan Thiyagarajan <mukilan@igalia.com>
329 lines
13 KiB
Rust
329 lines
13 KiB
Rust
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
|
||
|
||
use std::sync::Arc;
|
||
|
||
use embedder_traits::UntrustedNodeAddress;
|
||
use euclid::Size2D;
|
||
use fnv::FnvHashMap;
|
||
use fonts::FontContext;
|
||
use fxhash::FxHashMap;
|
||
use layout_api::{
|
||
IFrameSizes, ImageAnimationState, PendingImage, PendingImageState, PendingRasterizationImage,
|
||
};
|
||
use net_traits::image_cache::{
|
||
Image as CachedImage, ImageCache, ImageCacheResult, ImageOrMetadataAvailable, PendingImageId,
|
||
UsePlaceholder,
|
||
};
|
||
use parking_lot::{Mutex, RwLock};
|
||
use pixels::RasterImage;
|
||
use servo_url::{ImmutableOrigin, ServoUrl};
|
||
use style::context::SharedStyleContext;
|
||
use style::dom::{OpaqueNode, TNode};
|
||
use style::values::computed::image::{Gradient, Image};
|
||
use webrender_api::units::{DeviceIntSize, DeviceSize};
|
||
|
||
pub(crate) type CachedImageOrError = Result<CachedImage, ResolveImageError>;
|
||
|
||
pub(crate) struct LayoutContext<'a> {
|
||
pub use_rayon: bool,
|
||
|
||
/// Bits shared by the layout and style system.
|
||
pub style_context: SharedStyleContext<'a>,
|
||
|
||
/// A FontContext to be used during layout.
|
||
pub font_context: Arc<FontContext>,
|
||
|
||
/// A collection of `<iframe>` sizes to send back to script.
|
||
pub iframe_sizes: Mutex<IFrameSizes>,
|
||
|
||
/// An [`ImageResolver`] used for resolving images during box and fragment
|
||
/// tree construction. Later passed to display list construction.
|
||
pub image_resolver: Arc<ImageResolver>,
|
||
}
|
||
|
||
pub enum ResolvedImage<'a> {
|
||
Gradient(&'a Gradient),
|
||
// The size is tracked explicitly as image-set images can specify their
|
||
// natural resolution which affects the final size for raster images.
|
||
Image {
|
||
image: CachedImage,
|
||
size: DeviceSize,
|
||
},
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug)]
|
||
pub enum ResolveImageError {
|
||
LoadError,
|
||
ImagePending,
|
||
OnlyMetadata,
|
||
InvalidUrl,
|
||
MissingNode,
|
||
ImageMissingFromImageSet,
|
||
NotImplementedYet,
|
||
None,
|
||
}
|
||
|
||
pub(crate) enum LayoutImageCacheResult {
|
||
Pending,
|
||
DataAvailable(ImageOrMetadataAvailable),
|
||
LoadError,
|
||
}
|
||
|
||
pub(crate) struct ImageResolver {
|
||
/// The origin of the `Document` that this [`ImageResolver`] resolves images for.
|
||
pub origin: ImmutableOrigin,
|
||
|
||
/// Reference to the script thread image cache.
|
||
pub image_cache: Arc<dyn ImageCache>,
|
||
|
||
/// A list of in-progress image loads to be shared with the script thread.
|
||
pub pending_images: Mutex<Vec<PendingImage>>,
|
||
|
||
/// A list of fully loaded vector images that need to be rasterized to a specific
|
||
/// size determined by layout. This will be shared with the script thread.
|
||
pub pending_rasterization_images: Mutex<Vec<PendingRasterizationImage>>,
|
||
|
||
/// A list of `SVGSVGElement`s encountered during layout that are not
|
||
/// serialized yet. This is needed to support inline SVGs as they are treated
|
||
/// as replaced elements and the layout is responsible for triggering the
|
||
/// network load for the corresponding serialzed data: urls (similar to
|
||
/// background images).
|
||
pub pending_svg_elements_for_serialization: Mutex<Vec<UntrustedNodeAddress>>,
|
||
|
||
/// A shared reference to script's map of DOM nodes with animated images. This is used
|
||
/// to manage image animations in script and inform the script about newly animating
|
||
/// nodes.
|
||
pub node_to_animating_image_map: Arc<RwLock<FxHashMap<OpaqueNode, ImageAnimationState>>>,
|
||
|
||
// A cache that maps image resources used in CSS (e.g as the `url()` value
|
||
// for `background-image` or `content` property) to the final resolved image data.
|
||
pub resolved_images_cache:
|
||
Arc<RwLock<FnvHashMap<(ServoUrl, UsePlaceholder), CachedImageOrError>>>,
|
||
|
||
/// The current animation timeline value used to properly initialize animating images.
|
||
pub animation_timeline_value: f64,
|
||
}
|
||
|
||
impl Drop for ImageResolver {
|
||
fn drop(&mut self) {
|
||
if !std::thread::panicking() {
|
||
assert!(self.pending_images.lock().is_empty());
|
||
assert!(self.pending_rasterization_images.lock().is_empty());
|
||
assert!(
|
||
self.pending_svg_elements_for_serialization
|
||
.lock()
|
||
.is_empty()
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
impl ImageResolver {
|
||
pub(crate) fn get_or_request_image_or_meta(
|
||
&self,
|
||
node: OpaqueNode,
|
||
url: ServoUrl,
|
||
use_placeholder: UsePlaceholder,
|
||
) -> LayoutImageCacheResult {
|
||
// Check for available image or start tracking.
|
||
let cache_result = self.image_cache.get_cached_image_status(
|
||
url.clone(),
|
||
self.origin.clone(),
|
||
None,
|
||
use_placeholder,
|
||
);
|
||
|
||
match cache_result {
|
||
ImageCacheResult::Available(img_or_meta) => {
|
||
LayoutImageCacheResult::DataAvailable(img_or_meta)
|
||
},
|
||
// Image has been requested, is still pending. Return no image for this paint loop.
|
||
// When the image loads it will trigger a reflow and/or repaint.
|
||
ImageCacheResult::Pending(id) => {
|
||
let image = PendingImage {
|
||
state: PendingImageState::PendingResponse,
|
||
node: node.into(),
|
||
id,
|
||
origin: self.origin.clone(),
|
||
};
|
||
self.pending_images.lock().push(image);
|
||
LayoutImageCacheResult::Pending
|
||
},
|
||
// Not yet requested - request image or metadata from the cache
|
||
ImageCacheResult::ReadyForRequest(id) => {
|
||
let image = PendingImage {
|
||
state: PendingImageState::Unrequested(url),
|
||
node: node.into(),
|
||
id,
|
||
origin: self.origin.clone(),
|
||
};
|
||
self.pending_images.lock().push(image);
|
||
LayoutImageCacheResult::Pending
|
||
},
|
||
// Image failed to load, so just return the same error.
|
||
ImageCacheResult::LoadError => LayoutImageCacheResult::LoadError,
|
||
}
|
||
}
|
||
|
||
pub(crate) fn handle_animated_image(&self, node: OpaqueNode, image: Arc<RasterImage>) {
|
||
let mut map = self.node_to_animating_image_map.write();
|
||
if !image.should_animate() {
|
||
map.remove(&node);
|
||
return;
|
||
}
|
||
let new_image_animation_state =
|
||
|| ImageAnimationState::new(image.clone(), self.animation_timeline_value);
|
||
|
||
let entry = map.entry(node).or_insert_with(new_image_animation_state);
|
||
|
||
// If the entry exists, but it is for a different image id, replace it as the image
|
||
// has changed during this layout.
|
||
if entry.image.id != image.id {
|
||
*entry = new_image_animation_state();
|
||
}
|
||
}
|
||
|
||
pub(crate) fn get_cached_image_for_url(
|
||
&self,
|
||
node: OpaqueNode,
|
||
url: ServoUrl,
|
||
use_placeholder: UsePlaceholder,
|
||
) -> Result<CachedImage, ResolveImageError> {
|
||
if let Some(cached_image) = self
|
||
.resolved_images_cache
|
||
.read()
|
||
.get(&(url.clone(), use_placeholder))
|
||
{
|
||
return cached_image.clone();
|
||
}
|
||
|
||
let result = self.get_or_request_image_or_meta(node, url.clone(), use_placeholder);
|
||
match result {
|
||
LayoutImageCacheResult::DataAvailable(img_or_meta) => match img_or_meta {
|
||
ImageOrMetadataAvailable::ImageAvailable { image, .. } => {
|
||
if let Some(image) = image.as_raster_image() {
|
||
self.handle_animated_image(node, image.clone());
|
||
}
|
||
|
||
let mut resolved_images_cache = self.resolved_images_cache.write();
|
||
resolved_images_cache.insert((url, use_placeholder), Ok(image.clone()));
|
||
Ok(image)
|
||
},
|
||
ImageOrMetadataAvailable::MetadataAvailable(..) => {
|
||
Result::Err(ResolveImageError::OnlyMetadata)
|
||
},
|
||
},
|
||
LayoutImageCacheResult::Pending => Result::Err(ResolveImageError::ImagePending),
|
||
LayoutImageCacheResult::LoadError => {
|
||
let error = Err(ResolveImageError::LoadError);
|
||
self.resolved_images_cache
|
||
.write()
|
||
.insert((url, use_placeholder), error.clone());
|
||
error
|
||
},
|
||
}
|
||
}
|
||
|
||
pub(crate) fn rasterize_vector_image(
|
||
&self,
|
||
image_id: PendingImageId,
|
||
size: DeviceIntSize,
|
||
node: OpaqueNode,
|
||
) -> Option<RasterImage> {
|
||
let result = self.image_cache.rasterize_vector_image(image_id, size);
|
||
if result.is_none() {
|
||
self.pending_rasterization_images
|
||
.lock()
|
||
.push(PendingRasterizationImage {
|
||
id: image_id,
|
||
node: node.into(),
|
||
size,
|
||
});
|
||
}
|
||
result
|
||
}
|
||
|
||
pub(crate) fn queue_svg_element_for_serialization(
|
||
&self,
|
||
element: script::layout_dom::ServoLayoutNode<'_>,
|
||
) {
|
||
self.pending_svg_elements_for_serialization
|
||
.lock()
|
||
.push(element.opaque().into())
|
||
}
|
||
|
||
pub(crate) fn resolve_image<'a>(
|
||
&self,
|
||
node: Option<OpaqueNode>,
|
||
image: &'a Image,
|
||
) -> Result<ResolvedImage<'a>, ResolveImageError> {
|
||
match image {
|
||
// TODO: Add support for PaintWorklet and CrossFade rendering.
|
||
Image::None => Result::Err(ResolveImageError::None),
|
||
Image::CrossFade(_) => Result::Err(ResolveImageError::NotImplementedYet),
|
||
Image::PaintWorklet(_) => Result::Err(ResolveImageError::NotImplementedYet),
|
||
Image::Gradient(gradient) => Ok(ResolvedImage::Gradient(gradient)),
|
||
Image::Url(image_url) => {
|
||
// FIXME: images won’t always have in intrinsic width or
|
||
// height when support for SVG is added, or a WebRender
|
||
// `ImageKey`, for that matter.
|
||
//
|
||
// FIXME: It feels like this should take into account the pseudo
|
||
// element and not just the node.
|
||
let image_url = image_url.url().ok_or(ResolveImageError::InvalidUrl)?;
|
||
let node = node.ok_or(ResolveImageError::MissingNode)?;
|
||
let image = self.get_cached_image_for_url(
|
||
node,
|
||
image_url.clone().into(),
|
||
UsePlaceholder::No,
|
||
)?;
|
||
let metadata = image.metadata();
|
||
let size = Size2D::new(metadata.width, metadata.height).to_f32();
|
||
Ok(ResolvedImage::Image { image, size })
|
||
},
|
||
Image::ImageSet(image_set) => {
|
||
image_set
|
||
.items
|
||
.get(image_set.selected_index)
|
||
.ok_or(ResolveImageError::ImageMissingFromImageSet)
|
||
.and_then(|image| {
|
||
self.resolve_image(node, &image.image)
|
||
.map(|info| match info {
|
||
ResolvedImage::Image {
|
||
image: cached_image,
|
||
..
|
||
} => {
|
||
// From <https://drafts.csswg.org/css-images-4/#image-set-notation>:
|
||
// > A <resolution> (optional). This is used to help the UA decide
|
||
// > which <image-set-option> to choose. If the image reference is
|
||
// > for a raster image, it also specifies the image’s natural
|
||
// > resolution, overriding any other source of data that might
|
||
// > supply a natural resolution.
|
||
let image_metadata = cached_image.metadata();
|
||
let size = if cached_image.as_raster_image().is_some() {
|
||
let scale_factor = image.resolution.dppx();
|
||
Size2D::new(
|
||
image_metadata.width as f32 / scale_factor,
|
||
image_metadata.height as f32 / scale_factor,
|
||
)
|
||
} else {
|
||
Size2D::new(image_metadata.width, image_metadata.height)
|
||
.to_f32()
|
||
};
|
||
|
||
ResolvedImage::Image {
|
||
image: cached_image,
|
||
size,
|
||
}
|
||
},
|
||
_ => info,
|
||
})
|
||
})
|
||
},
|
||
Image::LightDark(..) => unreachable!("light-dark() should be disabled"),
|
||
}
|
||
}
|
||
}
|