Auto merge of #25512 - servo:background-image, r=nox

Render `background-image: url(…)`

… and support most `background-*` properties.

Still to do:

* `background-attachment`
* Gradients
This commit is contained in:
bors-servo 2020-01-17 10:52:38 -05:00 committed by GitHub
commit 1de92906e8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
314 changed files with 1275 additions and 136 deletions

View file

@ -18,12 +18,15 @@ atomic_refcell = "0.1"
cssparser = "0.27"
embedder_traits = {path = "../embedder_traits"}
euclid = "0.20"
fnv = "1.0"
gfx = {path = "../gfx"}
gfx_traits = {path = "../gfx_traits"}
ipc-channel = "0.12"
libc = "0.2"
msg = {path = "../msg"}
mitochondria = "1.1.2"
net_traits = {path = "../net_traits"}
parking_lot = "0.9"
range = {path = "../range"}
rayon = "1"
rayon_croissant = "0.2.0"
@ -32,6 +35,7 @@ script_traits = {path = "../script_traits"}
serde = "1.0"
servo_arc = { path = "../servo_arc" }
servo_geometry = {path = "../geometry"}
servo_url = {path = "../url"}
style = {path = "../style", features = ["servo", "servo-layout-2020"]}
style_traits = {path = "../style_traits"}
unicode-script = {version = "0.3", features = ["harfbuzz"]}

View file

@ -2,18 +2,51 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::display_list::WebRenderImageInfo;
use fnv::FnvHashMap;
use gfx::font_cache_thread::FontCacheThread;
use gfx::font_context::FontContext;
use msg::constellation_msg::PipelineId;
use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState};
use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder};
use parking_lot::RwLock;
use script_layout_interface::{PendingImage, PendingImageState};
use servo_url::{ImmutableOrigin, ServoUrl};
use std::cell::RefCell;
use std::sync::Mutex;
use std::sync::{Arc, Mutex};
use style::context::SharedStyleContext;
use style::dom::OpaqueNode;
pub struct LayoutContext<'a> {
pub id: PipelineId,
pub use_rayon: bool,
pub origin: ImmutableOrigin,
/// Bits shared by the layout and style system.
pub style_context: SharedStyleContext<'a>,
/// Interface to the font cache thread.
pub font_cache_thread: Mutex<FontCacheThread>,
/// Reference to the script thread image cache.
pub image_cache: Arc<dyn ImageCache>,
/// A list of in-progress image loads to be shared with the script thread.
/// A None value means that this layout was not initiated by the script thread.
pub pending_images: Option<Mutex<Vec<PendingImage>>>,
pub webrender_image_cache:
Arc<RwLock<FnvHashMap<(ServoUrl, UsePlaceholder), WebRenderImageInfo>>>,
}
impl<'a> Drop for LayoutContext<'a> {
fn drop(&mut self) {
if !std::thread::panicking() {
if let Some(ref pending_images) = self.pending_images {
assert!(pending_images.lock().unwrap().is_empty());
}
}
}
}
impl<'a> LayoutContext<'a> {
@ -21,6 +54,100 @@ impl<'a> LayoutContext<'a> {
pub fn shared_context(&self) -> &SharedStyleContext {
&self.style_context
}
pub fn get_or_request_image_or_meta(
&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder,
) -> Option<ImageOrMetadataAvailable> {
//XXXjdm For cases where we do not request an image, we still need to
// ensure the node gets another script-initiated reflow or it
// won't be requested at all.
let can_request = if self.pending_images.is_some() {
CanRequestImages::Yes
} else {
CanRequestImages::No
};
// See if the image is already available
let result = self.image_cache.find_image_or_metadata(
url.clone(),
self.origin.clone(),
None,
use_placeholder,
can_request,
);
match result {
Ok(image_or_metadata) => Some(image_or_metadata),
// Image failed to load, so just return nothing
Err(ImageState::LoadError) => None,
// Not yet requested - request image or metadata from the cache
Err(ImageState::NotRequested(id)) => {
let image = PendingImage {
state: PendingImageState::Unrequested(url),
node: node.into(),
id: id,
};
self.pending_images
.as_ref()
.unwrap()
.lock()
.unwrap()
.push(image);
None
},
// Image has been requested, is still pending. Return no image for this paint loop.
// When the image loads it will trigger a reflow and/or repaint.
Err(ImageState::Pending(id)) => {
//XXXjdm if self.pending_images is not available, we should make sure that
// this node gets marked dirty again so it gets a script-initiated
// reflow that deals with this properly.
if let Some(ref pending_images) = self.pending_images {
let image = PendingImage {
state: PendingImageState::PendingResponse,
node: node.into(),
id: id,
};
pending_images.lock().unwrap().push(image);
}
None
},
}
}
pub fn get_webrender_image_for_url(
&self,
node: OpaqueNode,
url: ServoUrl,
use_placeholder: UsePlaceholder,
) -> Option<WebRenderImageInfo> {
if let Some(existing_webrender_image) = self
.webrender_image_cache
.read()
.get(&(url.clone(), use_placeholder))
{
return Some((*existing_webrender_image).clone());
}
match self.get_or_request_image_or_meta(node, url.clone(), use_placeholder) {
Some(ImageOrMetadataAvailable::ImageAvailable(image, _)) => {
let image_info = WebRenderImageInfo {
width: image.width,
height: image.height,
key: image.id,
};
if image_info.key.is_none() {
Some(image_info)
} else {
let mut webrender_image_cache = self.webrender_image_cache.write();
webrender_image_cache.insert((url, use_placeholder), image_info);
Some(image_info)
}
},
None | Some(ImageOrMetadataAvailable::MetadataAvailable(_)) => None,
}
}
}
pub(crate) type LayoutFontContext = FontContext<FontCacheThread>;

View file

@ -2,11 +2,15 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::context::LayoutContext;
use crate::fragments::{BoxFragment, Fragment};
use crate::geom::physical::{Rect, Vec2};
use crate::replaced::IntrinsicSizes;
use embedder_traits::Cursor;
use euclid::{Point2D, SideOffsets2D, Size2D};
use euclid::{Point2D, SideOffsets2D, Size2D, Vector2D};
use gfx::text::glyph::GlyphStore;
use mitochondria::OnceCell;
use net_traits::image_cache::UsePlaceholder;
use std::sync::Arc;
use style::dom::OpaqueNode;
use style::properties::ComputedValues;
@ -14,12 +18,20 @@ use style::values::computed::{BorderStyle, Length, LengthPercentage};
use style::values::specified::ui::CursorKind;
use webrender_api::{self as wr, units};
#[derive(Clone, Copy)]
pub struct WebRenderImageInfo {
pub width: u32,
pub height: u32,
pub key: Option<wr::ImageKey>,
}
// `webrender_api::display_item::ItemTag` is private
type ItemTag = (u64, u16);
type HitInfo = Option<ItemTag>;
pub struct DisplayListBuilder {
pub struct DisplayListBuilder<'a> {
current_space_and_clip: wr::SpaceAndClipInfo,
pub context: &'a LayoutContext<'a>,
pub wr: wr::DisplayListBuilder,
/// Contentful paint, for the purpose of
@ -29,11 +41,16 @@ pub struct DisplayListBuilder {
pub is_contentful: bool,
}
impl DisplayListBuilder {
pub fn new(pipeline_id: wr::PipelineId, viewport_size: wr::units::LayoutSize) -> Self {
impl<'a> DisplayListBuilder<'a> {
pub fn new(
pipeline_id: wr::PipelineId,
context: &'a LayoutContext,
viewport_size: wr::units::LayoutSize,
) -> Self {
Self {
current_space_and_clip: wr::SpaceAndClipInfo::root_scroll(pipeline_id),
is_contentful: false,
context,
wr: wr::DisplayListBuilder::new(pipeline_id, viewport_size),
}
}
@ -60,9 +77,7 @@ impl Fragment {
containing_block: &Rect<Length>,
) {
match self {
Fragment::Box(b) => {
BuilderForBoxFragment::new(b, containing_block).build(builder, containing_block)
},
Fragment::Box(b) => BuilderForBoxFragment::new(b, containing_block).build(builder),
Fragment::Anonymous(a) => {
let rect = a
.rect
@ -92,7 +107,6 @@ impl Fragment {
.push_text(&common, rect.into(), &glyphs, t.font_key, rgba(color), None);
},
Fragment::Image(i) => {
use style::computed_values::image_rendering::T as ImageRendering;
builder.is_contentful = true;
let rect = i
.rect
@ -102,11 +116,7 @@ impl Fragment {
builder.wr.push_image(
&common,
rect.into(),
match i.style.get_inherited_box().image_rendering {
ImageRendering::Auto => wr::ImageRendering::Auto,
ImageRendering::CrispEdges => wr::ImageRendering::CrispEdges,
ImageRendering::Pixelated => wr::ImageRendering::Pixelated,
},
image_rendering(i.style.get_inherited_box().image_rendering),
wr::AlphaType::PremultipliedAlpha,
i.image_key,
wr::ColorF::WHITE,
@ -118,16 +128,16 @@ impl Fragment {
struct BuilderForBoxFragment<'a> {
fragment: &'a BoxFragment,
containing_block: &'a Rect<Length>,
border_rect: units::LayoutRect,
padding_rect: OnceCell<units::LayoutRect>,
content_rect: OnceCell<units::LayoutRect>,
border_radius: wr::BorderRadius,
// Outer `Option` is `None`: not initialized yet
// Inner `Option` is `None`: no border radius, no need to clip
border_edge_clip_id: Option<Option<wr::ClipId>>,
border_edge_clip_id: OnceCell<Option<wr::ClipId>>,
}
impl<'a> BuilderForBoxFragment<'a> {
fn new(fragment: &'a BoxFragment, containing_block: &Rect<Length>) -> Self {
fn new(fragment: &'a BoxFragment, containing_block: &'a Rect<Length>) -> Self {
let border_rect: units::LayoutRect = fragment
.border_rect()
.to_physical(fragment.style.writing_mode, containing_block)
@ -155,29 +165,50 @@ impl<'a> BuilderForBoxFragment<'a> {
Self {
fragment,
containing_block,
border_rect,
border_radius,
border_edge_clip_id: None,
padding_rect: OnceCell::new(),
content_rect: OnceCell::new(),
border_edge_clip_id: OnceCell::new(),
}
}
fn content_rect(&self) -> &units::LayoutRect {
self.content_rect.init_once(|| {
self.fragment
.content_rect
.to_physical(self.fragment.style.writing_mode, self.containing_block)
.translate(&self.containing_block.top_left)
.into()
})
}
fn padding_rect(&self) -> &units::LayoutRect {
self.padding_rect.init_once(|| {
self.fragment
.padding_rect()
.to_physical(self.fragment.style.writing_mode, self.containing_block)
.translate(&self.containing_block.top_left)
.into()
})
}
fn with_border_edge_clip(
&mut self,
builder: &mut DisplayListBuilder,
common: &mut wr::CommonItemProperties,
) {
let border_radius = &self.border_radius;
let border_rect = &self.border_rect;
let initialized = self.border_edge_clip_id.get_or_insert_with(|| {
if border_radius.is_zero() {
let initialized = self.border_edge_clip_id.init_once(|| {
if self.border_radius.is_zero() {
None
} else {
Some(builder.wr.define_clip(
&builder.current_space_and_clip,
*border_rect,
self.border_rect,
Some(wr::ComplexClipRegion {
rect: *border_rect,
radii: *border_radius,
rect: self.border_rect,
radii: self.border_radius,
mode: wr::ClipMode::Clip,
}),
None,
@ -189,7 +220,7 @@ impl<'a> BuilderForBoxFragment<'a> {
}
}
fn build(&mut self, builder: &mut DisplayListBuilder, containing_block: &Rect<Length>) {
fn build(&mut self, builder: &mut DisplayListBuilder) {
let hit_info = hit_info(&self.fragment.style, self.fragment.tag, Cursor::Default);
if hit_info.is_some() {
let mut common = builder.common_properties(self.border_rect);
@ -198,31 +229,308 @@ impl<'a> BuilderForBoxFragment<'a> {
builder.wr.push_hit_test(&common)
}
self.background_display_items(builder);
self.border_display_items(builder);
self.build_background(builder);
self.build_border(builder);
let content_rect = self
.fragment
.content_rect
.to_physical(self.fragment.style.writing_mode, containing_block)
.translate(&containing_block.top_left);
.to_physical(self.fragment.style.writing_mode, self.containing_block)
.translate(&self.containing_block.top_left);
for child in &self.fragment.children {
child.build_display_list(builder, &content_rect)
}
}
fn background_display_items(&mut self, builder: &mut DisplayListBuilder) {
let background_color = self
.fragment
.style
.resolve_color(self.fragment.style.clone_background_color());
fn build_background(&mut self, builder: &mut DisplayListBuilder) {
use style::values::computed::image::{Image, ImageLayer};
let b = self.fragment.style.get_background();
let background_color = self.fragment.style.resolve_color(b.background_color);
if background_color.alpha > 0 {
let mut common = builder.common_properties(self.border_rect);
self.with_border_edge_clip(builder, &mut common);
builder.wr.push_rect(&common, rgba(background_color))
}
// Reverse because the property is top layer first, we want to paint bottom layer first.
for (index, layer) in b.background_image.0.iter().enumerate().rev() {
match layer {
ImageLayer::None => {},
ImageLayer::Image(image) => match image {
Image::Gradient(_gradient) => {
// TODO
},
Image::Url(image_url) => {
if let Some(url) = image_url.url() {
let webrender_image = builder.context.get_webrender_image_for_url(
self.fragment.tag,
url.clone(),
UsePlaceholder::No,
);
if let Some(WebRenderImageInfo {
width,
height,
key: Some(key),
}) = webrender_image
{
// FIXME: https://drafts.csswg.org/css-images-4/#the-image-resolution
let dppx = 1.0;
let intrinsic = IntrinsicSizes {
width: Some(Length::new(width as f32 / dppx)),
height: Some(Length::new(height as f32 / dppx)),
// FIXME https://github.com/w3c/csswg-drafts/issues/4572
ratio: Some(width as f32 / height as f32),
};
self.build_background_raster_image(builder, index, intrinsic, key)
}
}
},
// Gecko-only value, represented as a (boxed) empty enum on non-Gecko.
Image::Rect(rect) => match **rect {},
},
}
}
}
fn border_display_items(&mut self, builder: &mut DisplayListBuilder) {
fn build_background_raster_image(
&mut self,
builder: &mut DisplayListBuilder,
index: usize,
intrinsic: IntrinsicSizes,
key: wr::ImageKey,
) {
use style::computed_values::background_clip::single_value::T as Clip;
use style::computed_values::background_origin::single_value::T as Origin;
use style::values::computed::background::BackgroundSize as Size;
use style::values::specified::background::BackgroundRepeat as RepeatXY;
use style::values::specified::background::BackgroundRepeatKeyword as Repeat;
fn get_cyclic<T>(values: &[T], index: usize) -> &T {
&values[index % values.len()]
}
let b = self.fragment.style.get_background();
let clipping_area = match get_cyclic(&b.background_clip.0, index) {
Clip::ContentBox => self.content_rect(),
Clip::PaddingBox => self.padding_rect(),
Clip::BorderBox => &self.border_rect,
};
let positioning_area = match get_cyclic(&b.background_origin.0, index) {
Origin::ContentBox => self.content_rect(),
Origin::PaddingBox => self.padding_rect(),
Origin::BorderBox => &self.border_rect,
};
// https://drafts.csswg.org/css-backgrounds/#background-size
enum ContainOrCover {
Contain,
Cover,
}
let size_contain_or_cover = |background_size| {
let mut tile_size = positioning_area.size;
if let Some(intrinsic_ratio) = intrinsic.ratio {
let positioning_ratio = positioning_area.size.width / positioning_area.size.height;
// Whether the tile width (as opposed to height)
// is scaled to that of the positioning area
let fit_width = match background_size {
ContainOrCover::Contain => positioning_ratio <= intrinsic_ratio,
ContainOrCover::Cover => positioning_ratio > intrinsic_ratio,
};
// The other dimension needs to be adjusted
if fit_width {
tile_size.height = tile_size.width / intrinsic_ratio
} else {
tile_size.width = tile_size.height * intrinsic_ratio
}
}
tile_size
};
let mut tile_size = match get_cyclic(&b.background_size.0, index) {
Size::Contain => size_contain_or_cover(ContainOrCover::Contain),
Size::Cover => size_contain_or_cover(ContainOrCover::Cover),
Size::ExplicitSize { width, height } => {
let mut width = width.non_auto().map(|lp| {
lp.0.percentage_relative_to(Length::new(positioning_area.size.width))
});
let mut height = height.non_auto().map(|lp| {
lp.0.percentage_relative_to(Length::new(positioning_area.size.height))
});
if width.is_none() && height.is_none() {
// Both computed values are 'auto':
// use intrinsic sizes, treating missing width or height as 'auto'
width = intrinsic.width;
height = intrinsic.height;
}
match (width, height) {
(Some(w), Some(h)) => units::LayoutSize::new(w.px(), h.px()),
(Some(w), None) => {
let h = if let Some(intrinsic_ratio) = intrinsic.ratio {
w / intrinsic_ratio
} else if let Some(intrinsic_height) = intrinsic.height {
intrinsic_height
} else {
// Treated as 100%
Length::new(positioning_area.size.height)
};
units::LayoutSize::new(w.px(), h.px())
},
(None, Some(h)) => {
let w = if let Some(intrinsic_ratio) = intrinsic.ratio {
h * intrinsic_ratio
} else if let Some(intrinsic_width) = intrinsic.width {
intrinsic_width
} else {
// Treated as 100%
Length::new(positioning_area.size.width)
};
units::LayoutSize::new(w.px(), h.px())
},
// Both comptued values were 'auto', and neither intrinsic size is present
(None, None) => size_contain_or_cover(ContainOrCover::Contain),
}
},
};
if tile_size.width == 0.0 || tile_size.height == 0.0 {
return;
}
struct Layout1DResult {
repeat: bool,
bounds_origin: f32,
bounds_size: f32,
}
/// Abstract over the horizontal or vertical dimension
/// Coordinates (0, 0) for the purpose of this function are the positioning areas origin.
fn layout_1d(
tile_size: &mut f32,
tile_spacing: &mut f32,
mut repeat: Repeat,
position: &LengthPercentage,
clipping_area_origin: f32,
clipping_area_size: f32,
positioning_area_size: f32,
) -> Layout1DResult {
// https://drafts.csswg.org/css-backgrounds/#background-repeat
if let Repeat::Round = repeat {
*tile_size = positioning_area_size / (positioning_area_size / *tile_size).round();
}
// https://drafts.csswg.org/css-backgrounds/#background-position
let mut position = position
.percentage_relative_to(Length::new(positioning_area_size - *tile_size))
.px();
// https://drafts.csswg.org/css-backgrounds/#background-repeat
if let Repeat::Space = repeat {
// The most entire tiles we can fit
let tile_count = (positioning_area_size / *tile_size).floor();
if tile_count >= 2.0 {
position = 0.0;
// Make the outsides of the first and last of that many tiles
// touch the edges of the positioning area:
let total_space = positioning_area_size - *tile_size * tile_count;
let spaces_count = tile_count - 1.0;
*tile_spacing = total_space / spaces_count;
} else {
repeat = Repeat::NoRepeat
}
}
match repeat {
Repeat::Repeat | Repeat::Round | Repeat::Space => {
// WebRenders `RepeatingImageDisplayItem` contains a `bounds` rectangle and:
//
// * The tiling is clipped to the intersection of `clip_rect` and `bounds`
// * The origin (top-left corner) of `bounds` is the position
// of the “first” (top-left-most) tile.
//
// In the general case that first tile is not the one that is positioned by
// `background-position`.
// We want it to be the top-left-most tile that intersects with `clip_rect`.
// We find it by offsetting by a whole number of strides,
// then compute `bounds` such that:
//
// * Its bottom-right is the bottom-right of `clip_rect`
// * Its top-left is the top-left of first tile.
let tile_stride = *tile_size + *tile_spacing;
let offset = position - clipping_area_origin;
let bounds_origin = position - tile_stride * (offset / tile_stride).ceil();
let bounds_size = clipping_area_size - bounds_origin - clipping_area_origin;
Layout1DResult {
repeat: true,
bounds_origin,
bounds_size,
}
},
Repeat::NoRepeat => {
// `RepeatingImageDisplayItem` always repeats in both dimension.
// When we want only one of the dimensions to repeat,
// we use the `bounds` rectangle to clip the tiling to one tile
// in that dimension.
Layout1DResult {
repeat: false,
bounds_origin: position,
bounds_size: *tile_size,
}
},
}
}
let mut tile_spacing = units::LayoutSize::zero();
let RepeatXY(repeat_x, repeat_y) = *get_cyclic(&b.background_repeat.0, index);
let result_x = layout_1d(
&mut tile_size.width,
&mut tile_spacing.width,
repeat_x,
get_cyclic(&b.background_position_x.0, index),
clipping_area.origin.x - positioning_area.origin.x,
clipping_area.size.width,
positioning_area.size.width,
);
let result_y = layout_1d(
&mut tile_size.height,
&mut tile_spacing.height,
repeat_y,
get_cyclic(&b.background_position_y.0, index),
clipping_area.origin.y - positioning_area.origin.y,
clipping_area.size.height,
positioning_area.size.height,
);
let bounds = units::LayoutRect::new(
positioning_area.origin + Vector2D::new(result_x.bounds_origin, result_y.bounds_origin),
Size2D::new(result_x.bounds_size, result_y.bounds_size),
);
// The 'backgound-clip' property maps directly to `clip_rect` in `CommonItemProperties`:
let mut common = builder.common_properties(*clipping_area);
self.with_border_edge_clip(builder, &mut common);
if result_x.repeat || result_y.repeat {
builder.wr.push_repeating_image(
&common,
bounds,
tile_size,
tile_spacing,
image_rendering(self.fragment.style.clone_image_rendering()),
wr::AlphaType::PremultipliedAlpha,
key,
wr::ColorF::WHITE,
)
} else {
builder.wr.push_image(
&common,
bounds,
image_rendering(self.fragment.style.clone_image_rendering()),
wr::AlphaType::PremultipliedAlpha,
key,
wr::ColorF::WHITE,
)
}
}
fn build_border(&mut self, builder: &mut DisplayListBuilder) {
let b = self.fragment.style.get_border();
let widths = SideOffsets2D::new(
b.border_top_width.px(),
@ -349,3 +657,12 @@ fn cursor(kind: CursorKind, auto_cursor: Cursor) -> Cursor {
CursorKind::ZoomOut => Cursor::ZoomOut,
}
}
fn image_rendering(ir: style::computed_values::image_rendering::T) -> wr::ImageRendering {
use style::computed_values::image_rendering::T as ImageRendering;
match ir {
ImageRendering::Auto => wr::ImageRendering::Auto,
ImageRendering::CrispEdges => wr::ImageRendering::CrispEdges,
ImageRendering::Pixelated => wr::ImageRendering::Pixelated,
}
}

View file

@ -20,21 +20,25 @@ use style::Zero;
#[derive(Debug)]
pub(crate) struct ReplacedContent {
pub kind: ReplacedContentKind,
intrinsic: IntrinsicSizes,
}
/// * Raster images always have an instrinsic width and height, with 1 image pixel = 1px.
/// The intrinsic ratio should be based on dividing those.
/// See https://github.com/w3c/csswg-drafts/issues/4572 for the case where either is zero.
/// PNG specifically disallows this but I (SimonSapin) am not sure about other formats.
///
/// * Form controls have both intrinsic width and height **but no intrinsic ratio**.
/// See https://github.com/w3c/csswg-drafts/issues/1044 and
/// https://drafts.csswg.org/css-images/#intrinsic-dimensions “In general, […]”
///
/// * For SVG, see https://svgwg.org/svg2-draft/coords.html#SizingSVGInCSS
/// and again https://github.com/w3c/csswg-drafts/issues/4572.
intrinsic_width: Option<Length>,
intrinsic_height: Option<Length>,
intrinsic_ratio: Option<CSSFloat>,
/// * Raster images always have an instrinsic width and height, with 1 image pixel = 1px.
/// The intrinsic ratio should be based on dividing those.
/// See https://github.com/w3c/csswg-drafts/issues/4572 for the case where either is zero.
/// PNG specifically disallows this but I (SimonSapin) am not sure about other formats.
///
/// * Form controls have both intrinsic width and height **but no intrinsic ratio**.
/// See https://github.com/w3c/csswg-drafts/issues/1044 and
/// https://drafts.csswg.org/css-images/#intrinsic-dimensions “In general, […]”
///
/// * For SVG, see https://svgwg.org/svg2-draft/coords.html#SizingSVGInCSS
/// and again https://github.com/w3c/csswg-drafts/issues/4572.
#[derive(Debug)]
pub(crate) struct IntrinsicSizes {
pub width: Option<Length>,
pub height: Option<Length>,
pub ratio: Option<CSSFloat>,
}
#[derive(Debug)]
@ -55,10 +59,12 @@ impl ReplacedContent {
let height = (intrinsic_size_in_dots.y as CSSFloat) / dppx;
return Some(Self {
kind: ReplacedContentKind::Image(image),
intrinsic_width: Some(Length::new(width)),
intrinsic_height: Some(Length::new(height)),
// FIXME https://github.com/w3c/csswg-drafts/issues/4572
intrinsic_ratio: Some(width / height),
intrinsic: IntrinsicSizes {
width: Some(Length::new(width)),
height: Some(Length::new(height)),
// FIXME https://github.com/w3c/csswg-drafts/issues/4572
ratio: Some(width / height),
},
});
}
None
@ -66,8 +72,8 @@ impl ReplacedContent {
fn flow_relative_intrinsic_size(&self, style: &ComputedValues) -> Vec2<Option<Length>> {
let intrinsic_size = physical::Vec2 {
x: self.intrinsic_width,
y: self.intrinsic_height,
x: self.intrinsic.width,
y: self.intrinsic.height,
};
intrinsic_size.size_to_flow_relative(style.writing_mode)
}
@ -76,7 +82,7 @@ impl ReplacedContent {
&self,
style: &ComputedValues,
) -> Option<CSSFloat> {
self.intrinsic_ratio.map(|width_over_height| {
self.intrinsic.ratio.map(|width_over_height| {
if style.writing_mode.is_vertical() {
1. / width_over_height
} else {

View file

@ -32,6 +32,7 @@ malloc_size_of = { path = "../malloc_size_of" }
metrics = {path = "../metrics"}
msg = {path = "../msg"}
net_traits = {path = "../net_traits"}
parking_lot = { version = "0.9", features = ["nightly"] }
profile_traits = {path = "../profile_traits"}
range = {path = "../range"}
script = {path = "../script"}

View file

@ -35,7 +35,7 @@ use gfx_traits::{node_id_from_scroll_id, Epoch};
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use ipc_channel::router::ROUTER;
use layout::context::LayoutContext;
use layout::display_list::DisplayListBuilder;
use layout::display_list::{DisplayListBuilder, WebRenderImageInfo};
use layout::query::{
process_content_box_request, process_content_boxes_request, LayoutRPCImpl, LayoutThreadData,
};
@ -56,7 +56,8 @@ use msg::constellation_msg::{
};
use msg::constellation_msg::{LayoutHangAnnotation, MonitoredComponentType, PipelineId};
use msg::constellation_msg::{MonitoredComponentId, TopLevelBrowsingContextId};
use net_traits::image_cache::ImageCache;
use net_traits::image_cache::{ImageCache, UsePlaceholder};
use parking_lot::RwLock;
use profile_traits::mem::{self as profile_mem, Report, ReportKind, ReportsChan};
use profile_traits::time::{self as profile_time, profile, TimerMetadata};
use profile_traits::time::{TimerMetadataFrameType, TimerMetadataReflowType};
@ -147,6 +148,9 @@ pub struct LayoutThread {
/// The channel on which messages can be sent to the memory profiler.
mem_profiler_chan: profile_mem::ProfilerChan,
/// Reference to the script thread image cache.
image_cache: Arc<dyn ImageCache>,
/// Public interface to the font cache thread.
font_cache_thread: FontCacheThread,
@ -189,6 +193,8 @@ pub struct LayoutThread {
/// All the other elements of this struct are read-only.
rw_data: Arc<Mutex<LayoutThreadData>>,
webrender_image_cache: Arc<RwLock<FnvHashMap<(ServoUrl, UsePlaceholder), WebRenderImageInfo>>>,
/// The executors for paint worklets.
registered_painters: RegisteredPaintersImpl,
@ -211,11 +217,23 @@ pub struct LayoutThread {
/// Load web fonts synchronously to avoid non-deterministic network-driven reflows.
load_webfonts_synchronously: bool,
/// Dumps the display list form after a layout.
dump_display_list: bool,
/// Dumps the display list in JSON form after a layout.
dump_display_list_json: bool,
/// Dumps the DOM after restyle.
dump_style_tree: bool,
/// Dumps the flow tree after a layout.
dump_rule_tree: bool,
/// Dumps the flow tree after a layout.
dump_flow_tree: bool,
/// Emits notifications when there is a relayout.
relayout_event: bool,
/// Dumps the fragment tree after a layout.
dump_fragment_tree: bool,
}
impl LayoutThreadFactory for LayoutThread {
@ -232,7 +250,7 @@ impl LayoutThreadFactory for LayoutThread {
background_hang_monitor_register: Box<dyn BackgroundHangMonitorRegister>,
constellation_chan: IpcSender<ConstellationMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
_image_cache: Arc<dyn ImageCache>,
image_cache: Arc<dyn ImageCache>,
font_cache_thread: FontCacheThread,
time_profiler_chan: profile_time::ProfilerChan,
mem_profiler_chan: profile_mem::ProfilerChan,
@ -242,10 +260,10 @@ impl LayoutThreadFactory for LayoutThread {
busy: Arc<AtomicBool>,
load_webfonts_synchronously: bool,
window_size: WindowSizeData,
_dump_display_list: bool,
_dump_display_list_json: bool,
_dump_style_tree: bool,
_dump_rule_tree: bool,
dump_display_list: bool,
dump_display_list_json: bool,
dump_style_tree: bool,
dump_rule_tree: bool,
relayout_event: bool,
_nonincremental_layout: bool,
_trace_layout: bool,
@ -280,6 +298,7 @@ impl LayoutThreadFactory for LayoutThread {
background_hang_monitor,
constellation_chan,
script_chan,
image_cache,
font_cache_thread,
time_profiler_chan,
mem_profiler_chan.clone(),
@ -290,6 +309,10 @@ impl LayoutThreadFactory for LayoutThread {
load_webfonts_synchronously,
window_size,
relayout_event,
dump_display_list,
dump_display_list_json,
dump_style_tree,
dump_rule_tree,
dump_flow_tree,
);
@ -443,6 +466,7 @@ impl LayoutThread {
background_hang_monitor: Box<dyn BackgroundHangMonitor>,
constellation_chan: IpcSender<ConstellationMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
image_cache: Arc<dyn ImageCache>,
font_cache_thread: FontCacheThread,
time_profiler_chan: profile_time::ProfilerChan,
mem_profiler_chan: profile_mem::ProfilerChan,
@ -453,7 +477,11 @@ impl LayoutThread {
load_webfonts_synchronously: bool,
window_size: WindowSizeData,
relayout_event: bool,
dump_fragment_tree: bool,
dump_display_list: bool,
dump_display_list_json: bool,
dump_style_tree: bool,
dump_rule_tree: bool,
dump_flow_tree: bool,
) -> LayoutThread {
// Let webrender know about this pipeline by sending an empty display list.
webrender_api_sender.send_initial_transaction(webrender_document, id.to_webrender());
@ -489,6 +517,7 @@ impl LayoutThread {
time_profiler_chan: time_profiler_chan,
mem_profiler_chan: mem_profiler_chan,
registered_painters: RegisteredPaintersImpl(Default::default()),
image_cache,
font_cache_thread: font_cache_thread,
first_reflow: Cell::new(true),
font_cache_receiver: font_cache_receiver,
@ -523,6 +552,7 @@ impl LayoutThread {
element_inner_text_response: String::new(),
inner_window_dimensions_response: None,
})),
webrender_image_cache: Default::default(),
timer: if pref!(layout.animations.test.enabled) {
Timer::test_mode()
} else {
@ -532,7 +562,11 @@ impl LayoutThread {
busy,
load_webfonts_synchronously,
relayout_event,
dump_fragment_tree,
dump_display_list,
dump_display_list_json,
dump_style_tree,
dump_rule_tree,
dump_flow_tree,
}
}
@ -553,6 +587,7 @@ impl LayoutThread {
fn build_layout_context<'a>(
&'a self,
guards: StylesheetGuards<'a>,
script_initiated_layout: bool,
snapshot_map: &'a SnapshotMap,
) -> LayoutContext<'a> {
let thread_local_style_context_creation_data =
@ -560,6 +595,7 @@ impl LayoutThread {
LayoutContext {
id: self.id,
origin: self.url.origin(),
style_context: SharedStyleContext {
stylist: &self.stylist,
options: GLOBAL_STYLE_DATA.options.clone(),
@ -573,7 +609,14 @@ impl LayoutThread {
traversal_flags: TraversalFlags::empty(),
snapshot_map: snapshot_map,
},
image_cache: self.image_cache.clone(),
font_cache_thread: Mutex::new(self.font_cache_thread.clone()),
webrender_image_cache: self.webrender_image_cache.clone(),
pending_images: if script_initiated_layout {
Some(Mutex::new(Vec::new()))
} else {
None
},
use_rayon: STYLE_THREAD_POOL.pool().is_some(),
}
}
@ -817,14 +860,14 @@ impl LayoutThread {
info.layout_is_busy,
self.load_webfonts_synchronously,
info.window_size,
false, // dump_display_list
false, // dump_display_list_json
false, // dump_style_tree
false, // dump_rule_tree
self.dump_display_list,
self.dump_display_list_json,
self.dump_style_tree,
self.dump_rule_tree,
self.relayout_event,
true, // nonincremental_layout
false, // trace_layout
false, // dump_flow_tree
self.dump_flow_tree,
);
}
@ -1074,7 +1117,7 @@ impl LayoutThread {
self.stylist.flush(&guards, Some(element), Some(&map));
// Create a layout context for use throughout the following passes.
let mut layout_context = self.build_layout_context(guards.clone(), &map);
let mut layout_context = self.build_layout_context(guards.clone(), true, &map);
let traversal = RecalcStyle::new(layout_context);
let token = {
@ -1121,6 +1164,21 @@ impl LayoutThread {
unsafe { element.unset_snapshot_flags() }
}
if self.dump_style_tree {
println!(
"{:?}",
style::dom::ShowSubtreeDataAndPrimaryValues(element.as_node())
);
}
if self.dump_rule_tree {
layout_context
.style_context
.stylist
.rule_tree()
.dump_stdout(&guards);
}
// GC the rule tree if some heuristics are met.
unsafe {
layout_context.style_context.stylist.rule_tree().maybe_gc();
@ -1128,11 +1186,21 @@ impl LayoutThread {
// Perform post-style recalculation layout passes.
if let Some(root) = &*self.fragment_tree_root.borrow() {
self.perform_post_style_recalc_layout_passes(root, &data.reflow_goal, Some(&document));
self.perform_post_style_recalc_layout_passes(
root,
&data.reflow_goal,
Some(&document),
&mut layout_context,
);
}
self.first_reflow.set(false);
self.respond_to_query_if_necessary(&data.reflow_goal, &mut *rw_data, &mut layout_context);
self.respond_to_query_if_necessary(
&data.reflow_goal,
&mut *rw_data,
&mut layout_context,
data.result.borrow_mut().as_mut().unwrap(),
);
}
fn respond_to_query_if_necessary(
@ -1140,7 +1208,13 @@ impl LayoutThread {
reflow_goal: &ReflowGoal,
rw_data: &mut LayoutThreadData,
context: &mut LayoutContext,
reflow_result: &mut ReflowComplete,
) {
let pending_images = match &context.pending_images {
Some(pending) => std::mem::take(&mut *pending.lock().unwrap()),
None => Vec::new(),
};
reflow_result.pending_images = pending_images;
match *reflow_goal {
ReflowGoal::LayoutQuery(ref querymsg, _) => match querymsg {
&QueryMsg::ContentBoxQuery(node) => {
@ -1262,12 +1336,20 @@ impl LayoutThread {
let author_shared_lock = self.document_shared_lock.clone().unwrap();
let author_guard = author_shared_lock.read();
let ua_or_user_guard = UA_STYLESHEETS.shared_lock.read();
let _guards = StylesheetGuards {
let guards = StylesheetGuards {
author: &author_guard,
ua_or_user: &ua_or_user_guard,
};
let snapshots = SnapshotMap::new();
let mut layout_context = self.build_layout_context(guards, false, &snapshots);
self.perform_post_style_recalc_layout_passes(root, &ReflowGoal::TickAnimations, None);
self.perform_post_style_recalc_layout_passes(
root,
&ReflowGoal::TickAnimations,
None,
&mut layout_context,
);
assert!(layout_context.pending_images.is_none());
}
}
@ -1276,6 +1358,7 @@ impl LayoutThread {
fragment_tree: &layout::FragmentTreeRoot,
reflow_goal: &ReflowGoal,
document: Option<&ServoLayoutDocument>,
context: &mut LayoutContext,
) {
if !reflow_goal.needs_display() {
// Defer the paint step until the next ForDisplay.
@ -1295,12 +1378,16 @@ impl LayoutThread {
self.viewport_size.width.to_f32_px(),
self.viewport_size.height.to_f32_px(),
));
let mut display_list = DisplayListBuilder::new(self.id.to_webrender(), viewport_size);
let mut display_list =
DisplayListBuilder::new(self.id.to_webrender(), context, viewport_size);
fragment_tree.build_display_list(&mut display_list, viewport_size);
if self.dump_fragment_tree {
if self.dump_flow_tree {
fragment_tree.print();
}
if self.dump_display_list {
display_list.wr.print_display_list();
}
debug!("Layout done!");

View file

@ -90,6 +90,12 @@ malloc_size_of_is_0!(UntrustedNodeAddress);
#[allow(unsafe_code)]
unsafe impl Send for UntrustedNodeAddress {}
impl From<style_traits::dom::OpaqueNode> for UntrustedNodeAddress {
fn from(o: style_traits::dom::OpaqueNode) -> Self {
UntrustedNodeAddress(o.0 as *const c_void)
}
}
impl Serialize for UntrustedNodeAddress {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
(self.0 as usize).serialize(s)

View file

@ -32,26 +32,7 @@ use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Deref;
/// An opaque handle to a node, which, unlike UnsafeNode, cannot be transformed
/// back into a non-opaque representation. The only safe operation that can be
/// performed on this node is to compare it to another opaque handle or to another
/// OpaqueNode.
///
/// Layout and Graphics use this to safely represent nodes for comparison purposes.
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf, Deserialize, Serialize))]
pub struct OpaqueNode(pub usize);
impl OpaqueNode {
/// Returns the address of this node, for debugging purposes.
#[inline]
pub fn id(&self) -> usize {
self.0
}
}
pub use style_traits::dom::OpaqueNode;
/// Simple trait to provide basic information about the type of an element.
///

View file

@ -23,7 +23,6 @@ ${helpers.predefined_type(
"background-image",
"ImageLayer",
engines="gecko servo-2013 servo-2020",
servo_2020_pref="layout.2020.unimplemented",
initial_value="computed::ImageLayer::none()",
initial_specified_value="specified::ImageLayer::none()",
spec="https://drafts.csswg.org/css-backgrounds/#the-background-image",
@ -36,7 +35,7 @@ ${helpers.predefined_type(
${helpers.predefined_type(
"background-position-" + axis,
"position::" + direction + "Position",
engines="gecko servo-2013",
engines="gecko servo-2013 servo-2020",
initial_value="computed::LengthPercentage::zero()",
initial_specified_value="SpecifiedValue::initial_specified_value()",
spec="https://drafts.csswg.org/css-backgrounds-4/#propdef-background-position-" + axis,
@ -50,7 +49,7 @@ ${helpers.predefined_type(
"background-repeat",
"BackgroundRepeat",
"computed::BackgroundRepeat::repeat()",
engines="gecko servo-2013",
engines="gecko servo-2013 servo-2020",
initial_specified_value="specified::BackgroundRepeat::repeat()",
animation_value_type="discrete",
vector=True,
@ -59,8 +58,8 @@ ${helpers.predefined_type(
${helpers.single_keyword(
"background-attachment",
"scroll fixed" + (" local" if engine == "gecko" else ""),
engines="gecko servo-2013",
"scroll" + (" fixed" if engine in ["gecko", "servo-2013"] else "") + (" local" if engine == "gecko" else ""),
engines="gecko servo-2013 servo-2020",
vector=True,
gecko_enum_prefix="StyleImageLayerAttachment",
spec="https://drafts.csswg.org/css-backgrounds/#the-background-attachment",
@ -70,7 +69,7 @@ ${helpers.single_keyword(
${helpers.single_keyword(
"background-clip",
"border-box padding-box content-box",
engines="gecko servo-2013",
engines="gecko servo-2013 servo-2020",
extra_gecko_values="text",
vector=True, extra_prefixes="webkit",
gecko_enum_prefix="StyleGeometryBox",
@ -82,7 +81,7 @@ ${helpers.single_keyword(
${helpers.single_keyword(
"background-origin",
"padding-box border-box content-box",
engines="gecko servo-2013",
engines="gecko servo-2013 servo-2020",
vector=True, extra_prefixes="webkit",
gecko_enum_prefix="StyleGeometryBox",
gecko_inexhaustive=True,
@ -93,7 +92,7 @@ ${helpers.single_keyword(
${helpers.predefined_type(
"background-size",
"BackgroundSize",
engines="gecko servo-2013",
engines="gecko servo-2013 servo-2020",
initial_value="computed::BackgroundSize::auto()",
initial_specified_value="specified::BackgroundSize::auto()",
spec="https://drafts.csswg.org/css-backgrounds/#the-background-size",

View file

@ -6,7 +6,7 @@
// TODO: other background-* properties
<%helpers:shorthand name="background"
engines="gecko servo-2013"
engines="gecko servo-2013 servo-2020"
sub_properties="background-color background-position-x background-position-y background-repeat
background-attachment background-image background-size background-origin
background-clip"
@ -193,31 +193,8 @@
}
</%helpers:shorthand>
<%helpers:shorthand name="background"
engines="servo-2020"
sub_properties="background-color"
spec="https://drafts.csswg.org/css-backgrounds/#the-background">
use crate::values::specified::Color;
use crate::parser::Parse;
pub fn parse_value<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Longhands, ParseError<'i>> {
Ok(expanded! {
background_color: Color::parse(context, input)?
})
}
impl<'a> ToCss for LonghandsToSerialize<'a> {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write {
self.background_color.to_css(dest)
}
}
</%helpers:shorthand>
<%helpers:shorthand name="background-position"
engines="gecko servo-2013"
engines="gecko servo-2013 servo-2020"
flags="SHORTHAND_IN_GETCS"
sub_properties="background-position-x background-position-y"
spec="https://drafts.csswg.org/css-backgrounds-4/#the-background-position">

View file

@ -0,0 +1,26 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Types used to access the DOM from style calculation.
/// An opaque handle to a node, which, unlike UnsafeNode, cannot be transformed
/// back into a non-opaque representation. The only safe operation that can be
/// performed on this node is to compare it to another opaque handle or to another
/// OpaqueNode.
///
/// Layout and Graphics use this to safely represent nodes for comparison purposes.
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf, Deserialize, Serialize))]
pub struct OpaqueNode(pub usize);
impl OpaqueNode {
/// Returns the address of this node, for debugging purposes.
#[inline]
pub fn id(&self) -> usize {
self.0
}
}

View file

@ -86,6 +86,7 @@ pub enum CSSPixel {}
// / desktop_zoom => CSSPixel
pub mod arc_slice;
pub mod dom;
pub mod specified_value_info;
#[macro_use]
pub mod values;