layout/
replaced.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use app_units::{Au, MAX_AU};
6use base::id::{BrowsingContextId, PipelineId};
7use data_url::DataUrl;
8use embedder_traits::ViewportDetails;
9use euclid::{Scale, Size2D};
10use layout_api::IFrameSize;
11use layout_api::wrapper_traits::ThreadSafeLayoutNode;
12use malloc_size_of_derive::MallocSizeOf;
13use net_traits::image_cache::{Image, ImageOrMetadataAvailable, UsePlaceholder, VectorImage};
14use script::layout_dom::ServoThreadSafeLayoutNode;
15use servo_arc::Arc as ServoArc;
16use style::Zero;
17use style::computed_values::object_fit::T as ObjectFit;
18use style::logical_geometry::{Direction, WritingMode};
19use style::properties::ComputedValues;
20use style::servo::url::ComputedUrl;
21use style::values::CSSFloat;
22use style::values::computed::image::Image as ComputedImage;
23use url::Url;
24use webrender_api::ImageKey;
25
26use crate::cell::ArcRefCell;
27use crate::context::{LayoutContext, LayoutImageCacheResult};
28use crate::dom::NodeExt;
29use crate::fragment_tree::{
30    BaseFragmentInfo, CollapsedBlockMargins, Fragment, IFrameFragment, ImageFragment,
31};
32use crate::geom::{LogicalVec2, PhysicalPoint, PhysicalRect, PhysicalSize};
33use crate::layout_box_base::{CacheableLayoutResult, LayoutBoxBase};
34use crate::sizing::{
35    ComputeInlineContentSizes, InlineContentSizesResult, LazySize, SizeConstraint,
36};
37use crate::style_ext::{AspectRatio, Clamp, ComputedValuesExt, LayoutStyle};
38use crate::{ConstraintSpace, ContainingBlock};
39
40#[derive(Debug, MallocSizeOf)]
41pub(crate) struct ReplacedContents {
42    pub kind: ReplacedContentKind,
43    natural_size: NaturalSizes,
44    base_fragment_info: BaseFragmentInfo,
45}
46
47/// The natural dimensions of a replaced element, including a height, width, and
48/// aspect ratio.
49///
50/// * Raster images always have an natural width and height, with 1 image pixel = 1px.
51///   The natural ratio should be based on dividing those.
52///   See <https://github.com/w3c/csswg-drafts/issues/4572> for the case where either is zero.
53///   PNG specifically disallows this but I (SimonSapin) am not sure about other formats.
54///
55/// * Form controls have both natural width and height **but no natural ratio**.
56///   See <https://github.com/w3c/csswg-drafts/issues/1044> and
57///   <https://drafts.csswg.org/css-images/#natural-dimensions> “In general, […]”
58///
59/// * For SVG, see <https://svgwg.org/svg2-draft/coords.html#SizingSVGInCSS>
60///   and again <https://github.com/w3c/csswg-drafts/issues/4572>.
61///
62/// * IFrames do not have natural width and height or natural ratio according
63///   to <https://drafts.csswg.org/css-images/#intrinsic-dimensions>.
64#[derive(Debug, MallocSizeOf)]
65pub(crate) struct NaturalSizes {
66    pub width: Option<Au>,
67    pub height: Option<Au>,
68    pub ratio: Option<CSSFloat>,
69}
70
71impl NaturalSizes {
72    pub(crate) fn from_width_and_height(width: f32, height: f32) -> Self {
73        // https://drafts.csswg.org/css-images/#natural-aspect-ratio:
74        // "If an object has a degenerate natural aspect ratio (at least one part being
75        // zero or infinity), it is treated as having no natural aspect ratio.""
76        let ratio = if width.is_normal() && height.is_normal() {
77            Some(width / height)
78        } else {
79            None
80        };
81
82        Self {
83            width: Some(Au::from_f32_px(width)),
84            height: Some(Au::from_f32_px(height)),
85            ratio,
86        }
87    }
88
89    pub(crate) fn from_natural_size_in_dots(natural_size_in_dots: PhysicalSize<f64>) -> Self {
90        // FIXME: should 'image-resolution' (when implemented) be used *instead* of
91        // `script::dom::htmlimageelement::ImageRequest::current_pixel_density`?
92        // https://drafts.csswg.org/css-images-4/#the-image-resolution
93        let dppx = 1.0;
94        let width = natural_size_in_dots.width as f32 / dppx;
95        let height = natural_size_in_dots.height as f32 / dppx;
96        Self::from_width_and_height(width, height)
97    }
98
99    pub(crate) fn empty() -> Self {
100        Self {
101            width: None,
102            height: None,
103            ratio: None,
104        }
105    }
106}
107
108#[derive(Debug, MallocSizeOf)]
109pub(crate) struct CanvasInfo {
110    pub source: Option<ImageKey>,
111}
112
113#[derive(Debug, MallocSizeOf)]
114pub(crate) struct IFrameInfo {
115    pub pipeline_id: PipelineId,
116    pub browsing_context_id: BrowsingContextId,
117}
118
119#[derive(Debug, MallocSizeOf)]
120pub(crate) struct VideoInfo {
121    pub image_key: webrender_api::ImageKey,
122}
123
124#[derive(Debug, MallocSizeOf)]
125pub(crate) enum ReplacedContentKind {
126    Image(Option<Image>),
127    IFrame(IFrameInfo),
128    Canvas(CanvasInfo),
129    Video(Option<VideoInfo>),
130    SVGElement(Option<VectorImage>),
131}
132
133impl ReplacedContents {
134    pub fn for_element(
135        node: ServoThreadSafeLayoutNode<'_>,
136        context: &LayoutContext,
137    ) -> Option<Self> {
138        if let Some(ref data_attribute_string) = node.as_typeless_object_with_data_attribute() {
139            if let Some(url) = try_to_parse_image_data_url(data_attribute_string) {
140                return Self::from_image_url(
141                    node,
142                    context,
143                    &ComputedUrl::Valid(ServoArc::new(url)),
144                );
145            }
146        }
147
148        let (kind, natural_size) = {
149            if let Some((image, natural_size_in_dots)) = node.as_image() {
150                (
151                    ReplacedContentKind::Image(image),
152                    NaturalSizes::from_natural_size_in_dots(natural_size_in_dots),
153                )
154            } else if let Some((canvas_info, natural_size_in_dots)) = node.as_canvas() {
155                (
156                    ReplacedContentKind::Canvas(canvas_info),
157                    NaturalSizes::from_natural_size_in_dots(natural_size_in_dots),
158                )
159            } else if let Some((pipeline_id, browsing_context_id)) = node.as_iframe() {
160                (
161                    ReplacedContentKind::IFrame(IFrameInfo {
162                        pipeline_id,
163                        browsing_context_id,
164                    }),
165                    NaturalSizes::empty(),
166                )
167            } else if let Some((image_key, natural_size_in_dots)) = node.as_video() {
168                (
169                    ReplacedContentKind::Video(image_key.map(|key| VideoInfo { image_key: key })),
170                    natural_size_in_dots
171                        .map_or_else(NaturalSizes::empty, NaturalSizes::from_natural_size_in_dots),
172                )
173            } else if let Some(svg_data) = node.as_svg() {
174                let svg_source = match svg_data.source {
175                    None => {
176                        // The SVGSVGElement is not yet serialized, so we add it to a list
177                        // and hand it over to script to peform the serialization.
178                        context
179                            .image_resolver
180                            .queue_svg_element_for_serialization(node);
181                        return None;
182                    },
183                    Some(Err(_)) => {
184                        // Don't attempt to serialize if previous attempt had errored.
185                        return None;
186                    },
187                    Some(Ok(svg_source)) => svg_source,
188                };
189
190                let result = context
191                    .image_resolver
192                    .get_cached_image_for_url(node.opaque(), svg_source, UsePlaceholder::No)
193                    .ok();
194
195                let vector_image = result.map(|result| match result {
196                    Image::Vector(vector_image) => vector_image,
197                    _ => unreachable!("SVG element can't contain a raster image."),
198                });
199                let natural_size = NaturalSizes {
200                    width: svg_data.width.map(Au::from_px),
201                    height: svg_data.height.map(Au::from_px),
202                    ratio: svg_data.ratio,
203                };
204                (ReplacedContentKind::SVGElement(vector_image), natural_size)
205            } else {
206                return None;
207            }
208        };
209
210        if let ReplacedContentKind::Image(Some(Image::Raster(ref image))) = kind {
211            context
212                .image_resolver
213                .handle_animated_image(node.opaque(), image.clone());
214        }
215
216        Some(Self {
217            kind,
218            natural_size,
219            base_fragment_info: node.into(),
220        })
221    }
222
223    pub fn from_image_url(
224        node: ServoThreadSafeLayoutNode<'_>,
225        context: &LayoutContext,
226        image_url: &ComputedUrl,
227    ) -> Option<Self> {
228        if let ComputedUrl::Valid(image_url) = image_url {
229            let (image, width, height) = match context.image_resolver.get_or_request_image_or_meta(
230                node.opaque(),
231                image_url.clone().into(),
232                UsePlaceholder::No,
233            ) {
234                LayoutImageCacheResult::DataAvailable(img_or_meta) => match img_or_meta {
235                    ImageOrMetadataAvailable::ImageAvailable { image, .. } => {
236                        let metadata = image.metadata();
237                        (
238                            Some(image.clone()),
239                            metadata.width as f32,
240                            metadata.height as f32,
241                        )
242                    },
243                    ImageOrMetadataAvailable::MetadataAvailable(metadata, _id) => {
244                        (None, metadata.width as f32, metadata.height as f32)
245                    },
246                },
247                LayoutImageCacheResult::Pending | LayoutImageCacheResult::LoadError => return None,
248            };
249
250            return Some(Self {
251                kind: ReplacedContentKind::Image(image),
252                natural_size: NaturalSizes::from_width_and_height(width, height),
253                base_fragment_info: node.into(),
254            });
255        }
256        None
257    }
258
259    pub fn from_image(
260        element: ServoThreadSafeLayoutNode<'_>,
261        context: &LayoutContext,
262        image: &ComputedImage,
263    ) -> Option<Self> {
264        match image {
265            ComputedImage::Url(image_url) => Self::from_image_url(element, context, image_url),
266            _ => None, // TODO
267        }
268    }
269
270    #[inline]
271    fn content_size(
272        &self,
273        axis: Direction,
274        preferred_aspect_ratio: Option<AspectRatio>,
275        get_size_in_opposite_axis: &dyn Fn() -> SizeConstraint,
276        get_fallback_size: &dyn Fn() -> Au,
277    ) -> Au {
278        let Some(ratio) = preferred_aspect_ratio else {
279            return get_fallback_size();
280        };
281        let transfer = |size| ratio.compute_dependent_size(axis, size);
282        match get_size_in_opposite_axis() {
283            SizeConstraint::Definite(size) => transfer(size),
284            SizeConstraint::MinMax(min_size, max_size) => get_fallback_size()
285                .clamp_between_extremums(transfer(min_size), max_size.map(transfer)),
286        }
287    }
288
289    pub fn make_fragments(
290        &self,
291        layout_context: &LayoutContext,
292        style: &ServoArc<ComputedValues>,
293        size: PhysicalSize<Au>,
294    ) -> Vec<Fragment> {
295        let natural_size = PhysicalSize::new(
296            self.natural_size.width.unwrap_or(size.width),
297            self.natural_size.height.unwrap_or(size.height),
298        );
299
300        let object_fit_size = self.natural_size.ratio.map_or(size, |width_over_height| {
301            let preserve_aspect_ratio_with_comparison =
302                |size: PhysicalSize<Au>, comparison: fn(&Au, &Au) -> bool| {
303                    let candidate_width = size.height.scale_by(width_over_height);
304                    if comparison(&candidate_width, &size.width) {
305                        return PhysicalSize::new(candidate_width, size.height);
306                    }
307
308                    let candidate_height = size.width.scale_by(1. / width_over_height);
309                    debug_assert!(comparison(&candidate_height, &size.height));
310                    PhysicalSize::new(size.width, candidate_height)
311                };
312
313            match style.clone_object_fit() {
314                ObjectFit::Fill => size,
315                ObjectFit::Contain => preserve_aspect_ratio_with_comparison(size, PartialOrd::le),
316                ObjectFit::Cover => preserve_aspect_ratio_with_comparison(size, PartialOrd::ge),
317                ObjectFit::None => natural_size,
318                ObjectFit::ScaleDown => {
319                    preserve_aspect_ratio_with_comparison(size.min(natural_size), PartialOrd::le)
320                },
321            }
322        });
323
324        let object_position = style.clone_object_position();
325        let horizontal_position = object_position
326            .horizontal
327            .to_used_value(size.width - object_fit_size.width);
328        let vertical_position = object_position
329            .vertical
330            .to_used_value(size.height - object_fit_size.height);
331
332        let rect = PhysicalRect::new(
333            PhysicalPoint::new(horizontal_position, vertical_position),
334            object_fit_size,
335        );
336        let clip = PhysicalRect::new(PhysicalPoint::origin(), size);
337
338        match &self.kind {
339            ReplacedContentKind::Image(image) => image
340                .as_ref()
341                .and_then(|image| match image {
342                    Image::Raster(raster_image) => raster_image.id,
343                    Image::Vector(vector_image) => {
344                        let scale = layout_context.style_context.device_pixel_ratio();
345                        let width = object_fit_size.width.scale_by(scale.0).to_px();
346                        let height = object_fit_size.height.scale_by(scale.0).to_px();
347                        let size = Size2D::new(width, height);
348                        let tag = self.base_fragment_info.tag?;
349                        layout_context
350                            .image_resolver
351                            .rasterize_vector_image(vector_image.id, size, tag.node)
352                            .and_then(|i| i.id)
353                    },
354                })
355                .map(|image_key| {
356                    Fragment::Image(ArcRefCell::new(ImageFragment {
357                        base: self.base_fragment_info.into(),
358                        style: style.clone(),
359                        rect,
360                        clip,
361                        image_key: Some(image_key),
362                    }))
363                })
364                .into_iter()
365                .collect(),
366            ReplacedContentKind::Video(video) => {
367                vec![Fragment::Image(ArcRefCell::new(ImageFragment {
368                    base: self.base_fragment_info.into(),
369                    style: style.clone(),
370                    rect,
371                    clip,
372                    image_key: video.as_ref().map(|video| video.image_key),
373                }))]
374            },
375            ReplacedContentKind::IFrame(iframe) => {
376                let size = Size2D::new(rect.size.width.to_f32_px(), rect.size.height.to_f32_px());
377                let hidpi_scale_factor = layout_context.style_context.device_pixel_ratio();
378
379                layout_context.iframe_sizes.lock().insert(
380                    iframe.browsing_context_id,
381                    IFrameSize {
382                        browsing_context_id: iframe.browsing_context_id,
383                        pipeline_id: iframe.pipeline_id,
384                        viewport_details: ViewportDetails {
385                            size,
386                            hidpi_scale_factor: Scale::new(hidpi_scale_factor.0),
387                        },
388                    },
389                );
390                vec![Fragment::IFrame(ArcRefCell::new(IFrameFragment {
391                    base: self.base_fragment_info.into(),
392                    style: style.clone(),
393                    pipeline_id: iframe.pipeline_id,
394                    rect,
395                }))]
396            },
397            ReplacedContentKind::Canvas(canvas_info) => {
398                if self.natural_size.width == Some(Au::zero()) ||
399                    self.natural_size.height == Some(Au::zero())
400                {
401                    return vec![];
402                }
403
404                let Some(image_key) = canvas_info.source else {
405                    return vec![];
406                };
407
408                vec![Fragment::Image(ArcRefCell::new(ImageFragment {
409                    base: self.base_fragment_info.into(),
410                    style: style.clone(),
411                    rect,
412                    clip,
413                    image_key: Some(image_key),
414                }))]
415            },
416            ReplacedContentKind::SVGElement(vector_image) => {
417                let Some(vector_image) = vector_image else {
418                    return vec![];
419                };
420                let scale = layout_context.style_context.device_pixel_ratio();
421                // TODO: This is incorrect if the SVG has a viewBox.
422                let size = PhysicalSize::new(
423                    vector_image
424                        .metadata
425                        .width
426                        .try_into()
427                        .map_or(MAX_AU, Au::from_px),
428                    vector_image
429                        .metadata
430                        .height
431                        .try_into()
432                        .map_or(MAX_AU, Au::from_px),
433                );
434                let rect = PhysicalRect::from_size(size);
435                let raster_size = Size2D::new(
436                    size.width.scale_by(scale.0).to_px(),
437                    size.height.scale_by(scale.0).to_px(),
438                );
439                let tag = self.base_fragment_info.tag.unwrap();
440                layout_context
441                    .image_resolver
442                    .rasterize_vector_image(vector_image.id, raster_size, tag.node)
443                    .and_then(|image| image.id)
444                    .map(|image_key| {
445                        Fragment::Image(ArcRefCell::new(ImageFragment {
446                            base: self.base_fragment_info.into(),
447                            style: style.clone(),
448                            rect,
449                            clip,
450                            image_key: Some(image_key),
451                        }))
452                    })
453                    .into_iter()
454                    .collect()
455            },
456        }
457    }
458
459    pub(crate) fn preferred_aspect_ratio(
460        &self,
461        style: &ComputedValues,
462        padding_border_sums: &LogicalVec2<Au>,
463    ) -> Option<AspectRatio> {
464        style.preferred_aspect_ratio(self.natural_size.ratio, padding_border_sums)
465    }
466
467    /// The inline size that would result from combining the natural size
468    /// and the default object size, but disregarding the specified size.
469    /// <https://drafts.csswg.org/css-images-3/#natural-dimensions>
470    /// <https://drafts.csswg.org/css-images-3/#default-object-size>
471    /// <https://drafts.csswg.org/css-images-3/#specified-size>
472    pub(crate) fn fallback_inline_size(&self, writing_mode: WritingMode) -> Au {
473        if writing_mode.is_horizontal() {
474            self.natural_size.width.unwrap_or_else(|| Au::from_px(300))
475        } else {
476            self.natural_size.height.unwrap_or_else(|| Au::from_px(150))
477        }
478    }
479
480    /// The block size that would result from combining the natural size
481    /// and the default object size, but disregarding the specified size.
482    /// <https://drafts.csswg.org/css-images-3/#natural-dimensions>
483    /// <https://drafts.csswg.org/css-images-3/#default-object-size>
484    /// <https://drafts.csswg.org/css-images-3/#specified-size>
485    pub(crate) fn fallback_block_size(&self, writing_mode: WritingMode) -> Au {
486        if writing_mode.is_horizontal() {
487            self.natural_size.height.unwrap_or_else(|| Au::from_px(150))
488        } else {
489            self.natural_size.width.unwrap_or_else(|| Au::from_px(300))
490        }
491    }
492
493    #[inline]
494    pub(crate) fn layout_style<'a>(&self, base: &'a LayoutBoxBase) -> LayoutStyle<'a> {
495        LayoutStyle::Default(&base.style)
496    }
497
498    pub(crate) fn layout(
499        &self,
500        layout_context: &LayoutContext,
501        containing_block_for_children: &ContainingBlock,
502        preferred_aspect_ratio: Option<AspectRatio>,
503        base: &LayoutBoxBase,
504        lazy_block_size: &LazySize,
505    ) -> CacheableLayoutResult {
506        let writing_mode = base.style.writing_mode;
507        let inline_size = containing_block_for_children.size.inline;
508        let content_block_size = self.content_size(
509            Direction::Block,
510            preferred_aspect_ratio,
511            &|| SizeConstraint::Definite(inline_size),
512            &|| self.fallback_block_size(writing_mode),
513        );
514        let size = LogicalVec2 {
515            inline: inline_size,
516            block: lazy_block_size.resolve(|| content_block_size),
517        }
518        .to_physical_size(writing_mode);
519        CacheableLayoutResult {
520            baselines: Default::default(),
521            collapsible_margins_in_children: CollapsedBlockMargins::zero(),
522            content_block_size,
523            content_inline_size_for_table: None,
524            // The result doesn't depend on `containing_block_for_children.size.block`,
525            // but it depends on `lazy_block_size`, which is probably tied to that.
526            depends_on_block_constraints: true,
527            fragments: self.make_fragments(layout_context, &base.style, size),
528            specific_layout_info: None,
529        }
530    }
531}
532
533impl ComputeInlineContentSizes for ReplacedContents {
534    fn compute_inline_content_sizes(
535        &self,
536        _: &LayoutContext,
537        constraint_space: &ConstraintSpace,
538    ) -> InlineContentSizesResult {
539        let inline_content_size = self.content_size(
540            Direction::Inline,
541            constraint_space.preferred_aspect_ratio,
542            &|| constraint_space.block_size,
543            &|| self.fallback_inline_size(constraint_space.writing_mode),
544        );
545        InlineContentSizesResult {
546            sizes: inline_content_size.into(),
547            depends_on_block_constraints: constraint_space.preferred_aspect_ratio.is_some(),
548        }
549    }
550}
551
552fn try_to_parse_image_data_url(string: &str) -> Option<Url> {
553    if !string.starts_with("data:") {
554        return None;
555    }
556    let data_url = DataUrl::process(string).ok()?;
557    let mime_type = data_url.mime_type();
558    if mime_type.type_ != "image" {
559        return None;
560    }
561
562    // TODO: Find a better way to test for supported image formats. Currently this type of check is
563    // repeated several places in Servo, but should be centralized somehow.
564    if !matches!(
565        mime_type.subtype.as_str(),
566        "png" | "jpeg" | "gif" | "webp" | "bmp" | "ico"
567    ) {
568        return None;
569    }
570
571    Url::parse(string).ok()
572}