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