Skip to main content

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 std::sync::Arc;
6
7use app_units::{Au, MAX_AU};
8use data_url::DataUrl;
9use embedder_traits::ViewportDetails;
10use euclid::{Scale, Size2D};
11use layout_api::{IFrameSize, LayoutElement, LayoutImageDestination, LayoutNode, SVGElementData};
12use malloc_size_of_derive::MallocSizeOf;
13use net_traits::image_cache::{Image, ImageOrMetadataAvailable, VectorImage};
14use net_traits::request::InternalRequest;
15use script::layout_dom::ServoLayoutNode;
16use servo_arc::Arc as ServoArc;
17use servo_base::id::{BrowsingContextId, PipelineId};
18use servo_url::ServoUrl;
19use style::Zero;
20use style::attr::AttrValue;
21use style::computed_values::object_fit::T as ObjectFit;
22use style::context::TreeCountingCaches;
23use style::dom::DummyElementContext;
24use style::logical_geometry::{Direction, WritingMode};
25use style::properties::{ComputedValues, StyleBuilder};
26use style::rule_cache::RuleCacheConditions;
27use style::rule_tree::RuleCascadeFlags;
28use style::stylesheets::container_rule::ContainerSizeQuery;
29use style::url::ComputedUrl;
30use style::values::CSSFloat;
31use style::values::computed::image::Image as ComputedImage;
32use style::values::computed::{Content, Context, ToComputedValue};
33use style::values::generics::counters::{GenericContentItem, GenericContentItems};
34use url::Url;
35use web_atoms::local_name;
36use webrender_api::ImageKey;
37
38use crate::context::{LayoutContext, LayoutImageCacheResult};
39use crate::dom::NodeExt;
40use crate::fragment_tree::{
41    BaseFragment, BaseFragmentInfo, CollapsedBlockMargins, Fragment, IFrameFragment, ImageFragment,
42};
43use crate::geom::{LogicalVec2, PhysicalPoint, PhysicalRect, PhysicalSize};
44use crate::layout_box_base::{IndependentFormattingContextLayoutResult, LayoutBoxBase};
45use crate::sizing::{
46    ComputeInlineContentSizes, InlineContentSizesResult, LazySize, SizeConstraint,
47};
48use crate::style_ext::{AspectRatio, Clamp, ComputedValuesExt, LayoutStyle};
49use crate::{ConstraintSpace, ContainingBlock};
50
51#[derive(Debug, MallocSizeOf)]
52pub(crate) struct ReplacedContents {
53    pub kind: ReplacedContentKind,
54    /// Whether or not this [`ReplacedContents`] is due to content replacement, i.e.
55    /// `content: <image>` in style.
56    pub is_content_replacement: bool,
57    natural_size: NaturalSizes,
58    base_fragment_info: BaseFragmentInfo,
59}
60
61/// The natural dimensions of a replaced element, including a height, width, and
62/// aspect ratio.
63///
64/// * Raster images always have an natural width and height, with 1 image pixel = 1px.
65///   The natural ratio should be based on dividing those.
66///   See <https://github.com/w3c/csswg-drafts/issues/4572> for the case where either is zero.
67///   PNG specifically disallows this but I (SimonSapin) am not sure about other formats.
68///
69/// * Form controls have both natural width and height **but no natural ratio**.
70///   See <https://github.com/w3c/csswg-drafts/issues/1044> and
71///   <https://drafts.csswg.org/css-images/#natural-dimensions> “In general, […]”
72///
73/// * For SVG, see <https://svgwg.org/svg2-draft/coords.html#SizingSVGInCSS>
74///   and again <https://github.com/w3c/csswg-drafts/issues/4572>.
75///
76/// * IFrames do not have natural width and height or natural ratio according
77///   to <https://drafts.csswg.org/css-images/#intrinsic-dimensions>.
78#[derive(Debug, MallocSizeOf)]
79pub(crate) struct NaturalSizes {
80    pub width: Option<Au>,
81    pub height: Option<Au>,
82    pub ratio: Option<CSSFloat>,
83}
84
85impl NaturalSizes {
86    pub(crate) fn from_width_and_height(width: f32, height: f32) -> Self {
87        // https://drafts.csswg.org/css-images/#natural-aspect-ratio:
88        // "If an object has a degenerate natural aspect ratio (at least one part being
89        // zero or infinity), it is treated as having no natural aspect ratio.""
90        let ratio = if width.is_normal() && height.is_normal() {
91            Some(width / height)
92        } else {
93            None
94        };
95
96        Self {
97            width: Some(Au::from_f32_px(width)),
98            height: Some(Au::from_f32_px(height)),
99            ratio,
100        }
101    }
102
103    pub(crate) fn from_natural_size_in_dots(natural_size_in_dots: PhysicalSize<f64>) -> Self {
104        // FIXME: should 'image-resolution' (when implemented) be used *instead* of
105        // `script::dom::htmlimageelement::ImageRequest::current_pixel_density`?
106        // https://drafts.csswg.org/css-images-4/#the-image-resolution
107        let dppx = 1.0;
108        let width = natural_size_in_dots.width as f32 / dppx;
109        let height = natural_size_in_dots.height as f32 / dppx;
110        Self::from_width_and_height(width, height)
111    }
112
113    pub(crate) fn empty() -> Self {
114        Self {
115            width: None,
116            height: None,
117            ratio: None,
118        }
119    }
120}
121
122#[derive(Debug, MallocSizeOf)]
123pub(crate) struct CanvasInfo {
124    pub source: Option<ImageKey>,
125}
126
127#[derive(Debug, MallocSizeOf)]
128pub(crate) struct IFrameInfo {
129    pub pipeline_id: PipelineId,
130    pub browsing_context_id: BrowsingContextId,
131}
132
133#[derive(Debug, MallocSizeOf)]
134pub(crate) struct ImageInfo {
135    pub image: Option<Image>,
136    pub showing_broken_image_icon: bool,
137    pub url: Option<ServoUrl>,
138}
139
140#[derive(Debug, MallocSizeOf)]
141pub(crate) struct VideoInfo {
142    pub image_key: Option<ImageKey>,
143    pub poster_url: Option<ServoUrl>,
144}
145
146#[derive(Debug, MallocSizeOf)]
147pub(crate) enum ReplacedContentKind {
148    Image(ImageInfo),
149    IFrame(IFrameInfo),
150    Canvas(CanvasInfo),
151    Video(VideoInfo),
152    SVGElement {
153        vector_image: Option<VectorImage>,
154        has_viewbox: bool,
155    },
156    Audio,
157}
158
159impl ReplacedContents {
160    pub fn for_element(node: ServoLayoutNode<'_>, context: &LayoutContext) -> Option<Self> {
161        if let Some(ref data_attribute_string) = node.as_typeless_object_with_data_attribute() &&
162            let Some(url) = try_to_parse_image_data_url(data_attribute_string)
163        {
164            return Self::from_image_url(node, context, &ComputedUrl::Valid(ServoArc::new(url)));
165        }
166
167        let (kind, natural_size) = {
168            if let Some((image_info, natural_size_in_dots)) = node.as_image() {
169                if let Some(content_image) = Self::from_content_property(node, context) {
170                    return Some(content_image);
171                }
172                (
173                    ReplacedContentKind::Image(image_info),
174                    NaturalSizes::from_natural_size_in_dots(natural_size_in_dots),
175                )
176            } else if let Some((canvas_info, natural_size_in_dots)) = node.as_canvas() {
177                (
178                    ReplacedContentKind::Canvas(canvas_info),
179                    NaturalSizes::from_natural_size_in_dots(natural_size_in_dots),
180                )
181            } else if let Some(iframe_info) = node.as_iframe() {
182                (
183                    ReplacedContentKind::IFrame(iframe_info),
184                    NaturalSizes::empty(),
185                )
186            } else if let Some((video_info, natural_size_in_dots)) = node.as_video() {
187                (
188                    ReplacedContentKind::Video(video_info),
189                    natural_size_in_dots
190                        .map_or_else(NaturalSizes::empty, NaturalSizes::from_natural_size_in_dots),
191                )
192            } else if let Some(svg_data) = node.as_svg() {
193                Self::svg_kind_size(svg_data, context, node)
194            } else if node
195                .as_html_element()
196                .is_some_and(|element| element.local_name() == &local_name!("audio"))
197            {
198                let natural_size = NaturalSizes {
199                    width: None,
200                    // 40px is the height of the controls.
201                    // See /components/script/resources/media-controls.css
202                    height: Some(Au::from_px(40)),
203                    ratio: None,
204                };
205                (ReplacedContentKind::Audio, natural_size)
206            } else {
207                return Self::from_content_property(node, context);
208            }
209        };
210
211        if let ReplacedContentKind::Image(ImageInfo {
212            image: Some(Image::Raster(ref image)),
213            ..
214        }) = kind
215        {
216            context
217                .image_resolver
218                .handle_animated_image(node.opaque(), image.clone());
219        }
220
221        Some(Self {
222            kind,
223            is_content_replacement: false,
224            natural_size,
225            base_fragment_info: node.into(),
226        })
227    }
228
229    fn svg_kind_size(
230        svg_data: SVGElementData,
231        context: &LayoutContext,
232        node: ServoLayoutNode<'_>,
233    ) -> (ReplacedContentKind, NaturalSizes) {
234        let rule_cache_conditions = &mut RuleCacheConditions::default();
235        let mut tree_counting_caches = TreeCountingCaches::default();
236
237        let parent_style = node.style(&context.style_context);
238        let style_builder = StyleBuilder::new(
239            context.style_context.stylist.device(),
240            Some(context.style_context.stylist),
241            Some(&parent_style),
242            None,
243            None,
244            false,
245        );
246
247        // TODO: use the correct element context in order to properly resolve
248        // `sibling-index()`, like Blink. Or maybe do it like Gecko, and only
249        // accept literals, see https://github.com/w3c/csswg-drafts/issues/14117
250        let element_context = &DummyElementContext;
251
252        let to_computed_context = Context::new(
253            style_builder,
254            context.style_context.quirks_mode(),
255            rule_cache_conditions,
256            ContainerSizeQuery::none(),
257            RuleCascadeFlags::empty(),
258            element_context,
259            &mut tree_counting_caches,
260        );
261
262        let attr_to_computed = |attr_val: &AttrValue| {
263            if let AttrValue::LengthPercentage(_, length_percentage) = attr_val {
264                length_percentage
265                    .to_computed_value(&to_computed_context)?
266                    .to_length()
267            } else {
268                None
269            }
270        };
271        let width = svg_data.width.and_then(attr_to_computed);
272        let height = svg_data.height.and_then(attr_to_computed);
273
274        let ratio = match (width, height) {
275            (Some(width), Some(height)) if !width.is_zero() && !height.is_zero() => {
276                Some(width.px() / height.px())
277            },
278            _ => svg_data.ratio_from_view_box(),
279        };
280
281        let natural_size = NaturalSizes {
282            width: width.map(|w| Au::from_f32_px(w.px())),
283            height: height.map(|h| Au::from_f32_px(h.px())),
284            ratio,
285        };
286
287        let svg_source = match svg_data.source {
288            None => {
289                // The SVGSVGElement is not yet serialized, so we add it to a list
290                // and hand it over to script to peform the serialization.
291                context
292                    .image_resolver
293                    .queue_svg_element_for_serialization(node);
294                None
295            },
296            // If `svg_source_result` is `Err()`, it means that the previous attempt
297            // had errored, then don't attempt to serialize again.
298            Some(svg_source_result) => svg_source_result.ok(),
299        };
300
301        let cached_image = svg_source.and_then(|svg_source| {
302            context
303                .image_resolver
304                .get_cached_image_for_url(
305                    node.opaque(),
306                    svg_source,
307                    LayoutImageDestination::BoxTreeConstruction,
308                    InternalRequest::Yes,
309                )
310                .ok()
311        });
312
313        let vector_image = cached_image.map(|image| match image {
314            Image::Vector(mut vector_image) => {
315                vector_image.svg_id = Some(svg_data.svg_id);
316                vector_image
317            },
318            _ => unreachable!("SVG element can't contain a raster image."),
319        });
320
321        (
322            ReplacedContentKind::SVGElement {
323                vector_image,
324                has_viewbox: svg_data.view_box.is_some(),
325            },
326            natural_size,
327        )
328    }
329
330    fn from_content_property(node: ServoLayoutNode<'_>, context: &LayoutContext) -> Option<Self> {
331        // If the `content` property is a single image URL, non-replaced boxes
332        // and images get replaced with the given image.
333        if let Content::Items(GenericContentItems { items, .. }) =
334            node.style(&context.style_context).clone_content() &&
335            let [GenericContentItem::Image(image)] = items.as_slice()
336        {
337            // Invalid images are treated as zero-sized.
338            let mut replaced_contents = Self::from_image(node, context, image)
339                .unwrap_or_else(|| Self::zero_sized_invalid_image(node));
340
341            replaced_contents.is_content_replacement = true;
342            node.clear_fragments_and_dirty_fragment_caches_of_descendants();
343            return Some(replaced_contents);
344        }
345        None
346    }
347
348    pub fn from_image_url(
349        node: ServoLayoutNode<'_>,
350        context: &LayoutContext,
351        image_url: &ComputedUrl,
352    ) -> Option<Self> {
353        let ComputedUrl::Valid(image_url) = image_url else {
354            return None;
355        };
356        let (image, width, height) = match context.image_resolver.get_or_request_image_or_meta(
357            node.opaque(),
358            image_url.clone().into(),
359            LayoutImageDestination::BoxTreeConstruction,
360            InternalRequest::No,
361        ) {
362            LayoutImageCacheResult::DataAvailable(img_or_meta) => match img_or_meta {
363                ImageOrMetadataAvailable::ImageAvailable { image, .. } => {
364                    if let Image::Raster(image) = &image {
365                        context
366                            .image_resolver
367                            .handle_animated_image(node.opaque(), image.clone());
368                    }
369                    let metadata = image.metadata();
370                    (Some(image), metadata.width as f32, metadata.height as f32)
371                },
372                ImageOrMetadataAvailable::MetadataAvailable(metadata, _id) => {
373                    (None, metadata.width as f32, metadata.height as f32)
374                },
375            },
376            LayoutImageCacheResult::Pending | LayoutImageCacheResult::LoadError => return None,
377        };
378        Some(Self {
379            kind: ReplacedContentKind::Image(ImageInfo {
380                image,
381                showing_broken_image_icon: false,
382                url: Some(image_url.clone().into()),
383            }),
384            is_content_replacement: false,
385            natural_size: NaturalSizes::from_width_and_height(width, height),
386            base_fragment_info: node.into(),
387        })
388    }
389
390    pub fn from_image(
391        element: ServoLayoutNode<'_>,
392        context: &LayoutContext,
393        image: &ComputedImage,
394    ) -> Option<Self> {
395        match image {
396            ComputedImage::Url(image_url) => Self::from_image_url(element, context, image_url),
397            _ => None, // TODO
398        }
399    }
400
401    pub(crate) fn zero_sized_invalid_image(node: ServoLayoutNode<'_>) -> Self {
402        Self {
403            kind: ReplacedContentKind::Image(ImageInfo {
404                image: None,
405                showing_broken_image_icon: false,
406                url: None,
407            }),
408            is_content_replacement: false,
409            natural_size: NaturalSizes::from_width_and_height(0., 0.),
410            base_fragment_info: node.into(),
411        }
412    }
413
414    #[inline]
415    fn is_broken_image(&self) -> bool {
416        matches!(&self.kind, ReplacedContentKind::Image(image_info) if image_info.showing_broken_image_icon)
417    }
418
419    #[inline]
420    fn content_size(
421        &self,
422        axis: Direction,
423        preferred_aspect_ratio: Option<AspectRatio>,
424        get_size_in_opposite_axis: &dyn Fn() -> SizeConstraint,
425        get_fallback_size: &dyn Fn() -> Au,
426    ) -> Au {
427        let Some(ratio) = preferred_aspect_ratio else {
428            return get_fallback_size();
429        };
430        let transfer = |size| ratio.compute_dependent_size(axis, size);
431        match get_size_in_opposite_axis() {
432            SizeConstraint::Definite(size) => transfer(size),
433            SizeConstraint::MinMax(min_size, max_size) => get_fallback_size()
434                .clamp_between_extremums(transfer(min_size), max_size.map(transfer)),
435        }
436    }
437
438    fn calculate_fragment_rect(
439        &self,
440        style: &ServoArc<ComputedValues>,
441        size: PhysicalSize<Au>,
442    ) -> (PhysicalSize<Au>, PhysicalRect<Au>) {
443        if let ReplacedContentKind::Image(ImageInfo {
444            image: Some(Image::Raster(image)),
445            showing_broken_image_icon: true,
446            url: _,
447        }) = &self.kind
448        {
449            let size = Size2D::new(
450                Au::from_f32_px(image.metadata.width as f32),
451                Au::from_f32_px(image.metadata.height as f32),
452            )
453            .min(size);
454            return (PhysicalSize::zero(), size.into());
455        }
456
457        let natural_size = PhysicalSize::new(
458            self.natural_size.width.unwrap_or(size.width),
459            self.natural_size.height.unwrap_or(size.height),
460        );
461
462        let object_fit_size = self.natural_size.ratio.map_or(size, |width_over_height| {
463            let preserve_aspect_ratio_with_comparison =
464                |size: PhysicalSize<Au>, comparison: fn(&Au, &Au) -> bool| {
465                    let candidate_width = size.height.scale_by(width_over_height);
466                    if comparison(&candidate_width, &size.width) {
467                        return PhysicalSize::new(candidate_width, size.height);
468                    }
469
470                    let candidate_height = size.width.scale_by(1. / width_over_height);
471                    debug_assert!(comparison(&candidate_height, &size.height));
472                    PhysicalSize::new(size.width, candidate_height)
473                };
474
475            match style.clone_object_fit() {
476                ObjectFit::Fill => size,
477                ObjectFit::Contain => preserve_aspect_ratio_with_comparison(size, PartialOrd::le),
478                ObjectFit::Cover => preserve_aspect_ratio_with_comparison(size, PartialOrd::ge),
479                ObjectFit::None => natural_size,
480                ObjectFit::ScaleDown => {
481                    preserve_aspect_ratio_with_comparison(size.min(natural_size), PartialOrd::le)
482                },
483            }
484        });
485
486        let object_position = style.clone_object_position();
487        let horizontal_position = object_position
488            .horizontal
489            .to_used_value(size.width - object_fit_size.width);
490        let vertical_position = object_position
491            .vertical
492            .to_used_value(size.height - object_fit_size.height);
493
494        let object_position = PhysicalPoint::new(horizontal_position, vertical_position);
495        (
496            object_fit_size,
497            PhysicalRect::new(object_position, object_fit_size),
498        )
499    }
500
501    pub fn make_fragments(
502        &self,
503        layout_context: &LayoutContext,
504        style: &ServoArc<ComputedValues>,
505        size: PhysicalSize<Au>,
506    ) -> Vec<Fragment> {
507        let (object_fit_size, rect) = self.calculate_fragment_rect(style, size);
508        let clip = PhysicalRect::new(PhysicalPoint::origin(), size);
509
510        let base = BaseFragment::new(self.base_fragment_info, rect);
511        match &self.kind {
512            ReplacedContentKind::Image(image_info) => image_info
513                .image
514                .as_ref()
515                .and_then(|image| {
516                    let scale = layout_context.style_context.device_pixel_ratio();
517                    let size = Size2D::new(
518                        object_fit_size.width.scale_by(scale.0).to_px(),
519                        object_fit_size.height.scale_by(scale.0).to_px(),
520                    );
521                    layout_context.image_resolver.image_key_from_cached_image(
522                        image,
523                        size,
524                        self.base_fragment_info.tag.map(|tag| tag.node),
525                    )
526                })
527                .map(|image_key| {
528                    Fragment::Image(Arc::new(ImageFragment {
529                        base,
530                        style: style.clone().into(),
531                        clip,
532                        image_key: Some(image_key),
533                        showing_broken_image_icon: image_info.showing_broken_image_icon,
534                        url: image_info.url.clone(),
535                        natural_width: self.natural_size.width,
536                        natural_height: self.natural_size.height,
537                    }))
538                })
539                .into_iter()
540                .collect(),
541            ReplacedContentKind::Video(video_info) => {
542                vec![Fragment::Image(Arc::new(ImageFragment {
543                    base,
544                    style: style.clone().into(),
545                    clip,
546                    image_key: video_info.image_key,
547                    showing_broken_image_icon: false,
548                    url: video_info.poster_url.clone(),
549                    natural_width: self.natural_size.width,
550                    natural_height: self.natural_size.height,
551                }))]
552            },
553            ReplacedContentKind::IFrame(iframe) => {
554                let size = Size2D::new(rect.size.width.to_f32_px(), rect.size.height.to_f32_px());
555                let hidpi_scale_factor = layout_context.style_context.device_pixel_ratio();
556
557                layout_context.iframe_sizes.lock().insert(
558                    iframe.browsing_context_id,
559                    IFrameSize {
560                        browsing_context_id: iframe.browsing_context_id,
561                        pipeline_id: iframe.pipeline_id,
562                        viewport_details: ViewportDetails {
563                            size,
564                            hidpi_scale_factor: Scale::new(hidpi_scale_factor.0),
565                            device_size: layout_context.device_size.cast_unit(),
566                        },
567                    },
568                );
569                vec![Fragment::IFrame(Arc::new(IFrameFragment {
570                    base,
571                    style: style.clone().into(),
572                    pipeline_id: iframe.pipeline_id,
573                }))]
574            },
575            ReplacedContentKind::Canvas(canvas_info) => {
576                if self.natural_size.width == Some(Au::zero()) ||
577                    self.natural_size.height == Some(Au::zero())
578                {
579                    return vec![];
580                }
581
582                let Some(image_key) = canvas_info.source else {
583                    return vec![];
584                };
585
586                vec![Fragment::Image(Arc::new(ImageFragment {
587                    base,
588                    style: style.clone().into(),
589                    clip,
590                    image_key: Some(image_key),
591                    showing_broken_image_icon: false,
592                    url: None,
593                    natural_width: self.natural_size.width,
594                    natural_height: self.natural_size.height,
595                }))]
596            },
597            ReplacedContentKind::SVGElement {
598                vector_image,
599                has_viewbox,
600            } => {
601                let Some(vector_image) = vector_image else {
602                    return vec![];
603                };
604
605                if !has_viewbox {
606                    base.set_rect(
607                        PhysicalSize::new(
608                            vector_image
609                                .metadata
610                                .width
611                                .try_into()
612                                .map_or(MAX_AU, Au::from_px),
613                            vector_image
614                                .metadata
615                                .height
616                                .try_into()
617                                .map_or(MAX_AU, Au::from_px),
618                        )
619                        .into(),
620                    );
621                }
622
623                let scale = layout_context.style_context.device_pixel_ratio();
624                let content_size = base.rect().size;
625                let raster_size = Size2D::new(
626                    content_size.width.scale_by(scale.0).to_px(),
627                    content_size.height.scale_by(scale.0).to_px(),
628                );
629
630                let tag = self.base_fragment_info.tag.unwrap();
631                layout_context
632                    .image_resolver
633                    .rasterize_vector_image(
634                        vector_image.id,
635                        raster_size,
636                        tag.node,
637                        vector_image.svg_id,
638                    )
639                    .and_then(|image| image.id)
640                    .map(|image_key| {
641                        Fragment::Image(Arc::new(ImageFragment {
642                            base,
643                            style: style.clone().into(),
644                            clip,
645                            image_key: Some(image_key),
646                            showing_broken_image_icon: false,
647                            url: None,
648                            natural_width: self.natural_size.width,
649                            natural_height: self.natural_size.height,
650                        }))
651                    })
652                    .into_iter()
653                    .collect()
654            },
655            ReplacedContentKind::Audio => vec![],
656        }
657    }
658
659    pub(crate) fn preferred_aspect_ratio(
660        &self,
661        style: &ComputedValues,
662        padding_border_sums: &LogicalVec2<Au>,
663    ) -> Option<AspectRatio> {
664        if matches!(self.kind, ReplacedContentKind::Audio) {
665            // This isn't specified, but other browsers don't support `aspect-ratio` on `<audio>`.
666            // See <https://phabricator.services.mozilla.com/D118245>
667            return None;
668        }
669        if self.is_broken_image() {
670            // This isn't specified, but when an image is broken, we should prefer to the aspect
671            // ratio from the style, rather than the aspect ratio from the broken image icon.
672            // Note that the broken image icon *does* affect the content size of the image
673            // though as we want the image to be as big as the icon if the size was not specified
674            // in the style.
675            style.preferred_aspect_ratio(None, padding_border_sums)
676        } else {
677            style.preferred_aspect_ratio(self.natural_size.ratio, padding_border_sums)
678        }
679    }
680
681    /// The inline size that would result from combining the natural size
682    /// and the default object size, but disregarding the specified size.
683    /// <https://drafts.csswg.org/css-images-3/#natural-dimensions>
684    /// <https://drafts.csswg.org/css-images-3/#default-object-size>
685    /// <https://drafts.csswg.org/css-images-3/#specified-size>
686    pub(crate) fn fallback_inline_size(&self, writing_mode: WritingMode) -> Au {
687        if writing_mode.is_horizontal() {
688            self.natural_size.width.unwrap_or_else(|| Au::from_px(300))
689        } else {
690            self.natural_size.height.unwrap_or_else(|| Au::from_px(150))
691        }
692    }
693
694    /// The block size that would result from combining the natural size
695    /// and the default object size, but disregarding the specified size.
696    /// <https://drafts.csswg.org/css-images-3/#natural-dimensions>
697    /// <https://drafts.csswg.org/css-images-3/#default-object-size>
698    /// <https://drafts.csswg.org/css-images-3/#specified-size>
699    pub(crate) fn fallback_block_size(&self, writing_mode: WritingMode) -> Au {
700        if writing_mode.is_horizontal() {
701            self.natural_size.height.unwrap_or_else(|| Au::from_px(150))
702        } else {
703            self.natural_size.width.unwrap_or_else(|| Au::from_px(300))
704        }
705    }
706
707    pub(crate) fn logical_natural_sizes(
708        &self,
709        writing_mode: WritingMode,
710    ) -> LogicalVec2<Option<Au>> {
711        if writing_mode.is_horizontal() {
712            LogicalVec2 {
713                inline: self.natural_size.width,
714                block: self.natural_size.height,
715            }
716        } else {
717            LogicalVec2 {
718                inline: self.natural_size.height,
719                block: self.natural_size.width,
720            }
721        }
722    }
723
724    #[inline]
725    pub(crate) fn layout_style<'a>(&self, base: &'a LayoutBoxBase) -> LayoutStyle<'a> {
726        LayoutStyle::Default(&base.style)
727    }
728
729    pub(crate) fn layout(
730        &self,
731        layout_context: &LayoutContext,
732        containing_block_for_children: &ContainingBlock,
733        preferred_aspect_ratio: Option<AspectRatio>,
734        base: &LayoutBoxBase,
735        lazy_block_size: &LazySize,
736    ) -> IndependentFormattingContextLayoutResult {
737        let writing_mode = base.style.writing_mode;
738        let inline_size = containing_block_for_children.size.inline;
739        let content_block_size = self.content_size(
740            Direction::Block,
741            preferred_aspect_ratio,
742            &|| SizeConstraint::Definite(inline_size),
743            &|| self.fallback_block_size(writing_mode),
744        );
745        let size = LogicalVec2 {
746            inline: inline_size,
747            block: lazy_block_size.resolve(|| content_block_size),
748        }
749        .to_physical_size(writing_mode);
750        IndependentFormattingContextLayoutResult {
751            baselines: Default::default(),
752            collapsible_margins_in_children: CollapsedBlockMargins::zero(),
753            content_block_size,
754            content_inline_size_for_table: None,
755            // The result doesn't depend on `containing_block_for_children.size.block`,
756            // but it depends on `lazy_block_size`, which is probably tied to that.
757            depends_on_block_constraints: true,
758            fragments: self.make_fragments(layout_context, &base.style, size),
759            specific_layout_info: None,
760        }
761    }
762}
763
764impl ComputeInlineContentSizes for ReplacedContents {
765    fn compute_inline_content_sizes(
766        &self,
767        _: &LayoutContext,
768        constraint_space: &ConstraintSpace,
769    ) -> InlineContentSizesResult {
770        let inline_content_size = self.content_size(
771            Direction::Inline,
772            constraint_space.preferred_aspect_ratio,
773            &|| constraint_space.block_size,
774            &|| self.fallback_inline_size(constraint_space.style.writing_mode),
775        );
776        InlineContentSizesResult {
777            sizes: inline_content_size.into(),
778            depends_on_block_constraints: constraint_space.preferred_aspect_ratio.is_some(),
779        }
780    }
781}
782
783fn try_to_parse_image_data_url(string: &str) -> Option<Url> {
784    if !string.starts_with("data:") {
785        return None;
786    }
787    let data_url = DataUrl::process(string).ok()?;
788    let mime_type = data_url.mime_type();
789    if mime_type.type_ != "image" {
790        return None;
791    }
792
793    // TODO: Find a better way to test for supported image formats. Currently this type of check is
794    // repeated several places in Servo, but should be centralized somehow.
795    if !matches!(
796        mime_type.subtype.as_str(),
797        "png" | "jpeg" | "gif" | "webp" | "bmp" | "ico"
798    ) {
799        return None;
800    }
801
802    Url::parse(string).ok()
803}