diff --git a/crates/ui/src/html/mod.rs b/crates/ui/src/html/mod.rs index 3d27a1b21..f55a22446 100644 --- a/crates/ui/src/html/mod.rs +++ b/crates/ui/src/html/mod.rs @@ -20,6 +20,7 @@ mod style; mod svg; mod text; +use std::cell::RefCell; use std::collections::HashMap; use std::rc::Rc; use std::sync::Arc; @@ -51,7 +52,7 @@ pub(crate) const CONTEXT: &str = "HtmlView"; /// repaints neither parse nor cascade. pub struct HtmlState { source: Arc, - doc: Document, + doc: Rc, sheet: Stylesheet, media: MediaSlots, computed: Option>, @@ -67,7 +68,7 @@ pub struct HtmlState { impl HtmlState { pub fn new(html: impl Into>) -> Self { let source: Arc = html.into(); - let doc = Document::parse(&source); + let doc = Rc::new(Document::parse(&source)); let sheet = Stylesheet::parse_all(&doc.stylesheets); Self { source, @@ -141,7 +142,7 @@ impl HtmlState { return; } self.source = Arc::from(html); - self.doc = Document::parse(&self.source); + self.doc = Rc::new(Document::parse(&self.source)); self.sheet = Stylesheet::parse_all(&self.doc.stylesheets); self.media.clear(); self.computed = None; @@ -217,6 +218,11 @@ struct Computed { before: HashMap, after: HashMap, pictures: HashMap, + /// The ``s of the page's ``s, which any of them may draw. + symbols: Vec<(String, String)>, + /// For a grid or a table, the width of the widest item of each of its + /// columns; `None` until [`render::measure`] has found them. + measures: RefCell>>>, /// The cascade's [`Budget`] ran out, or a value was drawn at a limit. left_out: bool, } @@ -244,7 +250,18 @@ impl Computed { before: HashMap::new(), after: HashMap::new(), pictures: HashMap::new(), + symbols: doc + .nodes + .iter() + .filter_map(|node| match &node.kind { + dom::NodeKind::Element(el) => el.raw_svg.as_deref(), + dom::NodeKind::Text(_) => None, + }) + .filter(|raw| raw.contains(" { let raw = el.raw_svg.as_deref().unwrap_or_default(); + if svg::draws_nothing(raw) { + self.styles[id] = Some(style); + continue; + } + let raw = svg::with_css_size(raw, style.width_px(), style.height_px()); + let raw = svg::with_symbols(&raw, &self.symbols); let css = PageCss::of(page_css, doc, &style, &self.theme); let cost = (raw.len() + css.len()) / 64; if cascade.budget.spend(cost) { - let picture = - match svg::prepare_svg(raw, style.color, &style.vars, &css) { - Some(prepared) => PictureOf::Svg { - content: prepared.content(), - natural: prepared.natural, - }, - None => PictureOf::SvgTooLong, - }; + let page = self.theme.svg_page(&style); + let paint = style.svg_paint.as_deref(); + let picture = match svg::prepare_svg(&raw, &page, &css, paint) { + Some(prepared) => PictureOf::Svg { + content: prepared.content(), + natural: prepared.natural, + }, + None => PictureOf::SvgTooLong, + }; self.pictures.insert(id, picture); } } @@ -329,6 +353,17 @@ impl Computed { self.after.get(&id) } + fn measured(&self, id: NodeId) -> Option> { + self.measures.borrow().as_ref()?.get(&id).cloned() + } + + fn set_measured(&self, id: NodeId, widths: Vec) { + self.measures + .borrow_mut() + .get_or_insert_default() + .insert(id, widths.into()); + } + fn picture(&self, id: NodeId) -> Option<&PictureOf> { self.pictures.get(&id) } @@ -339,8 +374,11 @@ impl Computed { fn prepare_svg(&self, doc: &Document, node: NodeId) -> Option { let style = self.style(node)?; let raw = doc.element(node)?.raw_svg.as_deref()?; + let raw = svg::with_css_size(raw, style.width_px(), style.height_px()); + let raw = svg::with_symbols(&raw, &self.symbols); let css = PageCss::of(&mut Vec::new(), doc, style, &self.theme); - svg::prepare_svg(raw, style.color, &style.vars, &css) + let page = self.theme.svg_page(style); + svg::prepare_svg(&raw, &page, &css, style.svg_paint.as_deref()) } } @@ -366,13 +404,7 @@ impl PageCss { { return page.css.clone(); } - let css: Rc = svg::page_css( - &doc.stylesheets, - style.color, - &style.vars, - theme.font_sans(), - ) - .into(); + let css: Rc = svg::page_css(&doc.stylesheets, &theme.svg_page(style)).into(); known.push(Self { vars: style.vars.clone(), color: style.color, @@ -411,6 +443,11 @@ impl RenderOnce for HtmlView { let theme = Palette::of(cx.theme()); let env = media_env(&theme, self.viewport_width.unwrap_or(fallback_width)); let computed = self.state.update(cx, |state, _| state.computed(theme, env)); + if computed.measures.borrow().is_none() { + let doc = self.state.read(cx).doc.clone(); + computed.measures.replace(Some(HashMap::new())); + render::measure(&doc, &computed, env.viewport_width, window, cx); + } let state = self.state.read(cx); let (element, mut frame) = render::render_document(state, &computed, env.viewport_width, cx); @@ -736,6 +773,56 @@ pub(crate) mod tests { assert!(drawn(&narrow("1 0 0 %"), cx).size.height > line); } + /// Three boxes that fit on one line of a box 600 pixels wide and wrap in + /// a narrower one, so the height says which the box was. + const ROW: &str = r#"
"#; + + #[gpui::test] + fn an_auto_track_is_as_wide_as_what_it_holds(cx: &mut TestAppContext) { + let label = r#""#; + let html = format!( + r#"
{label}{ROW}{label}

"# + ); + // The view is 640 wide: a first track of the 20 pixels it holds + // leaves the row its 600, and both rows of the grid are one high. + assert_eq!(drawn(&html, cx).size.height, px(20.0)); + } + + #[gpui::test] + fn a_table_column_is_as_wide_in_every_row(cx: &mut TestAppContext) { + let html = format!( + r#" + +
{ROW}
"# + ); + // The width the head gives the first column is the second row's too. + assert_eq!(drawn(&html, cx).size.height, px(10.0)); + } + + #[gpui::test] + fn a_width_is_the_content_box_unless_the_page_says(cx: &mut TestAppContext) { + let boxed = |sizing: &str| { + format!(r#"
{ROW}
"#) + }; + assert_eq!(drawn(&boxed(""), &mut cx.new_app()).size.height, px(10.0)); + let border_box = drawn(&boxed("box-sizing:border-box"), cx); + assert_eq!(border_box.size.height, px(20.0)); + } + + #[gpui::test] + fn text_beside_a_box_wraps_in_its_line(cx: &mut TestAppContext) { + let words = "a ".repeat(40); + let line = drawn("
a
", &mut cx.new_app()).size.height; + // After an inline box, as a badge before its sentence is. + let badge = r#""#; + let inline = format!(r#"
{badge} {words}
"#); + assert!(drawn(&inline, &mut cx.new_app()).size.height >= line * 3.0); + // As an item of a row, as a label beside its icon is. + let icon = r#""#; + let item = format!(r#"
{icon}{words}
"#); + assert!(drawn(&item, cx).size.height >= line * 3.0); + } + #[gpui::test] fn a_visual_cut_at_a_limit_says_so(cx: &mut TestAppContext) { let cases = [ diff --git a/crates/ui/src/html/render.rs b/crates/ui/src/html/render.rs index ba0b93c11..578fc1af3 100644 --- a/crates/ui/src/html/render.rs +++ b/crates/ui/src/html/render.rs @@ -5,17 +5,18 @@ use std::collections::HashSet; use std::ops::Range; use gpui::{ - AnyElement, App, DefiniteLength, HighlightStyle, Hsla, InteractiveElement as _, - IntoElement as _, Length, ObjectFit, Overflow, ParentElement as _, - StatefulInteractiveElement as _, StrikethroughStyle, Styled as _, StyledImage as _, TextAlign, - UnderlineStyle, div, img, px, relative, + AbsoluteLength, AlignItems, AnyElement, App, AvailableSpace, DefiniteLength, HighlightStyle, + Hsla, InteractiveElement as _, IntoElement as _, Length, ObjectFit, Overflow, + ParentElement as _, Position, StatefulInteractiveElement as _, StrikethroughStyle, Styled as _, + StyledImage as _, TextAlign, UnderlineStyle, Window, div, img, linear_color_stop, + linear_gradient, prelude::FluentBuilder as _, px, relative, size, }; use gpui_base::{h_flex, v_flex}; use super::dom::{Document, ElementData, MAX_DEPTH, MAX_NODES, NodeId, NodeKind}; use super::style::{ ComputedStyle, DisplayKind, GridColumns, GridTrack, ListStyleType, TextTransform, - WhiteSpaceMode, + VerticalAlign, WhiteSpaceMode, }; use super::svg::{MediaSlots, RasterKey, RasterState}; use super::text::{PageText, TextSink}; @@ -29,6 +30,15 @@ use crate::widgets::tooltip::{Tooltip, TooltipTrigger as _}; /// HTML's own limit on `colspan`. const MAX_COLSPAN: usize = 1000; +/// The most columns a table is laid out in. +const MAX_COLUMNS: usize = 256; +/// The most boxes the text of a page's lines is cut into, a box for a word. +/// Past it a text is one box, which wraps inside itself and not around the +/// boxes beside it. +const MAX_WORDS: usize = 20_000; +/// The most cells whose widths are measured for a page: each is laid out +/// once more than it is drawn. +const MAX_MEASURED: usize = 4000; /// A picture a frame had no drawing of. pub(crate) enum Wanted { @@ -61,6 +71,14 @@ struct RenderCtx<'a> { viewport_width: f32, frame: Frame, text: TextSink, + /// The next box built fills the height of the grid area it is put in. + stretch: bool, + /// The next box built is in a column that does not stretch it across, + /// where GPUI makes it as wide as what it holds: it is no wider than + /// the column. + capped: bool, + /// The boxes the text of lines has been cut into, of [`MAX_WORDS`]. + words: usize, } pub(crate) fn render_document( @@ -79,6 +97,9 @@ pub(crate) fn render_document( viewport_width, frame: Frame::default(), text: TextSink::selecting(state.selecting()), + stretch: false, + capped: false, + words: 0, }; let children = render_children(&doc.roots, root_style, None, &mut ctx, cx); @@ -147,24 +168,59 @@ fn render_children( let mut inline_run: Vec = Vec::new(); let mut list_counter = list_ctx.map_or(1, |l| l.index); - let is_flex_or_grid = matches!( + let is_grid = matches!( parent_style.display, - DisplayKind::Flex | DisplayKind::InlineFlex | DisplayKind::Grid | DisplayKind::InlineGrid + DisplayKind::Grid | DisplayKind::InlineGrid ); + let is_flex = matches!( + parent_style.display, + DisplayKind::Flex | DisplayKind::InlineFlex + ); + let is_flex_or_grid = is_flex || is_grid; + // A row that sets its items on one baseline: GPUI knows no box's + // baseline and sets them on their bottom edges, which is right between + // lines of text and puts a box with no text below the line. + let in_column = is_flex + && matches!( + parent_style.flex_direction, + Some(gpui::FlexDirection::Column | gpui::FlexDirection::ColumnReverse) + ); + let on_baseline = + is_flex && !in_column && parent_style.align_items == Some(AlignItems::Baseline); + // A grid sets each item across its column; GPUI's grid has only the + // setting down its row, so a box around the item sets it across. + let across = |item: AnyElement| match parent_style.justify_items.filter(|_| is_grid) { + Some(AlignItems::Center) => div() + .flex() + .min_w_0() + .justify_center() + .child(item) + .into_any_element(), + Some(AlignItems::FlexEnd) => div() + .flex() + .min_w_0() + .justify_end() + .child(item) + .into_any_element(), + Some(AlignItems::FlexStart) => div().flex().min_w_0().child(item).into_any_element(), + _ => item, + }; for &cid in child_ids { match &ctx.doc.nodes[cid].kind { NodeKind::Text(t) => { if is_flex_or_grid { + // White space around the text of an item is not part of it. let normalized = normalize_text(t, parent_style.white_space); - if !normalized.trim().is_empty() { - let transformed = - apply_text_transform(&normalized, parent_style.text_transform); - out.push( - text_box(&transformed) - .child(ctx.text.run(transformed, Vec::new())) - .into_any_element(), - ); + let text = normalized.trim(); + if !text.is_empty() { + let transformed = apply_text_transform(text, parent_style.text_transform); + let mut item = text_box(&transformed, parent_style.font_size); + if parent_style.white_space == WhiteSpaceMode::NoWrap { + item = item.whitespace_nowrap(); + } + let item = item.child(ctx.text.run(transformed, Vec::new())); + out.push(across(item.into_any_element())); } } else { inline_run.push(cid); @@ -191,8 +247,25 @@ fn render_children( } l }); + let held_across = style.align_self.or(parent_style.align_items); + ctx.capped = + in_column && held_across.is_some_and(|across| across != AlignItems::Stretch); if let Some(rendered) = render_element(cid, el, style, item_list, ctx, cx) { - out.push(rendered); + let lifted = on_baseline + && style.position != Position::Absolute + && !has_text(ctx.doc, cid); + out.push(if lifted { + div() + .flex_none() + .relative() + .top(px(-baseline_from_bottom(parent_style))) + .child(rendered) + .into_any_element() + } else if style.position == Position::Absolute { + rendered + } else { + across(rendered) + }); } } } @@ -206,6 +279,113 @@ fn render_children( out } +/// Whether the element at `id` may be made narrower than what it holds: it +/// clips what it holds, or holds text that wraps. GPUI takes a text's +/// narrowest width to be its whole line, so a box of text that wraps is +/// told it may be narrower; a box of none, or of text that does not wrap, +/// is as wide as what it holds at the least, as a browser has it. +fn narrows(doc: &Document, computed: &Computed, id: NodeId, style: &ComputedStyle) -> bool { + if matches!(style.overflow_x, Some(Overflow::Hidden | Overflow::Scroll)) { + return true; + } + let wraps = + style.white_space != WhiteSpaceMode::NoWrap && style.white_space != WhiteSpaceMode::Pre; + doc.nodes[id] + .children + .iter() + .any(|&child| match &doc.nodes[child].kind { + NodeKind::Text(text) => wraps && can_wrap(text), + NodeKind::Element(_) => computed + .shown(child) + .is_some_and(|style| narrows(doc, computed, child, style)), + }) +} + +/// Whether the element at `id` holds any text that is drawn. +fn has_text(doc: &Document, id: NodeId) -> bool { + doc.nodes[id] + .children + .iter() + .any(|&child| match &doc.nodes[child].kind { + NodeKind::Text(text) => !text.trim().is_empty(), + NodeKind::Element(_) => has_text(doc, child), + }) +} + +/// How far above the bottom of a line of `style`'s text its baseline is, +/// reckoned from the shape of the interface font: GPUI gives a box no +/// baseline to set another box by. +fn baseline_from_bottom(style: &ComputedStyle) -> f32 { + let size = style.font_size; + let line = match style.line_height { + Some(DefiniteLength::Fraction(share)) => share * size, + Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(pixels))) => f32::from(pixels), + _ => 1.5 * size, + }; + (line - 1.19 * size) / 2.0 + 0.24 * size +} + +/// What a box is drawn with that GPUI's own background and border cannot +/// draw: a gradient of more than two stops, and borders of other colours +/// than the box's. Each is a box laid over the box's own. +fn decorations(style: &ComputedStyle) -> Vec { + let mut out = Vec::new(); + if let Some(gradient) = &style.gradient { + let mut under = div() + .absolute() + .top_0() + .left_0() + .size_full() + .flex() + .overflow_hidden(); + if !gradient.horizontal { + under = under.flex_col(); + } + under.style().corner_radii.top_left = style.radius_tl; + under.style().corner_radii.top_right = style.radius_tr; + under.style().corner_radii.bottom_right = style.radius_br; + under.style().corner_radii.bottom_left = style.radius_bl; + let angle = if gradient.horizontal { 90.0 } else { 180.0 }; + let along = |share: f32| { + let part = div().flex_none(); + if gradient.horizontal { + part.h_full().w(relative(share)) + } else { + part.w_full().h(relative(share)) + } + }; + let stops = &gradient.stops; + if let Some(first) = stops.first().filter(|first| first.1 > 0.0) { + under = under.child(along(first.1).bg(first.0)); + } + for pair in stops.windows(2) { + let (from, to) = (pair[0], pair[1]); + if to.1 > from.1 { + under = under.child(along(to.1 - from.1).bg(linear_gradient( + angle, + linear_color_stop(from.0, 0.0), + linear_color_stop(to.0, 1.0), + ))); + } + } + if let Some(last) = stops.last().filter(|last| last.1 < 1.0) { + under = under.child(along(1.0 - last.1).bg(last.0)); + } + out.push(under.into_any_element()); + } + for (side, width, color) in style.border_plan().strips { + let strip = div().absolute().bg(color); + let strip = match side { + 0 => strip.top_0().left_0().w_full().h(px(width)), + 1 => strip.top_0().right_0().h_full().w(px(width)), + 2 => strip.bottom_0().left_0().w_full().h(px(width)), + _ => strip.top_0().left_0().h_full().w(px(width)), + }; + out.push(strip.into_any_element()); + } + out +} + fn render_element( node_id: NodeId, el: &ElementData, @@ -214,6 +394,8 @@ fn render_element( ctx: &mut RenderCtx<'_>, cx: &App, ) -> Option { + let stretch = std::mem::take(&mut ctx.stretch); + let capped = std::mem::take(&mut ctx.capped); // Specialized semantic & media elements. match el.tag.as_str() { "svg" => return render_svg_element(node_id, el, style, ctx, cx), @@ -233,11 +415,21 @@ fn render_element( if matches!(style.display, DisplayKind::Grid | DisplayKind::InlineGrid) && let Some(GridColumns::Tracks(tracks)) = &style.grid_columns { + ctx.stretch = stretch; return Some(render_track_grid(node_id, style, tracks, ctx, cx)); } - let mut container = div().min_w_0(); + let mut container = div(); + if narrows(ctx.doc, ctx.computed, node_id, style) { + container = container.min_w_0(); + } style.apply_to(container.style(), ctx.viewport_width); + if stretch { + container.style().flex_grow = Some(1.0); + } + if capped && style.max_width.is_none() { + container.style().max_size.width = Some(relative(1.0).into()); + } if matches!(style.grid_columns, Some(GridColumns::AutoFit { .. })) && let Some(columns) = &mut container.style().grid_cols { @@ -285,7 +477,7 @@ fn render_element( } } - let mut children = Vec::new(); + let mut children = decorations(style); if let Some(before) = ctx.computed.before(node_id) { children.push(render_pseudo(before, ctx)); } @@ -344,6 +536,7 @@ fn render_pseudo(style: &ComputedStyle, ctx: &mut RenderCtx<'_>) -> AnyElement { let transformed = apply_text_transform(&text, style.text_transform); let mut el = div().flex_shrink_0(); style.apply_to(el.style(), ctx.viewport_width); + el = el.children(decorations(style)); if !transformed.is_empty() { el = el.child(transformed); } @@ -612,6 +805,53 @@ fn render_static_input( /// Render a CSS Grid whose `grid-template-columns` specifies non-uniform tracks /// (e.g. `180px 1fr`, `1fr 2fr`, `120px 1fr 120px`). +/// What a grid of named tracks lays out, in the order it places them: each +/// item with the track it starts in and how many it spans, row by row. +fn track_items( + doc: &Document, + computed: &Computed, + node_id: NodeId, + col_count: usize, +) -> Vec<(NodeId, usize, usize)> { + let mut items = Vec::new(); + let mut cursor = 0usize; + for &cid in &doc.nodes[node_id].children { + let span = match &doc.nodes[cid].kind { + NodeKind::Text(text) if text.trim().is_empty() => continue, + NodeKind::Text(_) => 1, + NodeKind::Element(_) => { + let Some(style) = computed.shown(cid) else { + continue; + }; + if style.position == Position::Absolute { + continue; + } + style.grid_location.as_ref().map_or(1, |loc| { + match (&loc.column.start, &loc.column.end) { + (gpui::GridPlacement::Span(n), _) | (_, gpui::GridPlacement::Span(n)) => { + (*n as usize).clamp(1, col_count) + } + (gpui::GridPlacement::Line(s), gpui::GridPlacement::Line(e)) if *e > *s => { + ((*e - *s) as usize).clamp(1, col_count) + } + _ => 1, + } + }) + } + }; + if cursor > 0 && cursor + span > col_count { + cursor = 0; + } + items.push((cid, cursor, span)); + cursor = (cursor + span) % col_count; + } + items +} + +/// A grid of named tracks, as rows of boxes: GPUI's grid has only tracks of +/// one size. Every row gives a track the same room, which is its length, its +/// share of what is left, or for an `auto` track the width +/// [`measure`] found its widest item to have. fn render_track_grid( node_id: NodeId, style: &ComputedStyle, @@ -620,106 +860,273 @@ fn render_track_grid( cx: &App, ) -> AnyElement { let col_count = tracks.len().max(1); - let mut items: Vec<(usize, AnyElement)> = Vec::new(); - - for &cid in &ctx.doc.nodes[node_id].children { - if let NodeKind::Element(el) = &ctx.doc.nodes[cid].kind { - let Some(child_style) = ctx.computed.shown(cid) else { - continue; - }; - let span = child_style.grid_location.as_ref().map_or(1, |loc| { - match (&loc.column.start, &loc.column.end) { - (gpui::GridPlacement::Span(n), _) | (_, gpui::GridPlacement::Span(n)) => { - (*n as usize).clamp(1, col_count) - } - (gpui::GridPlacement::Line(s), gpui::GridPlacement::Line(e)) if *e > *s => { - ((*e - *s) as usize).clamp(1, col_count) - } - _ => 1, - } - }); - if let Some(rendered) = render_element(cid, el, child_style, None, ctx, cx) { - items.push((span, rendered)); - } - } - } + let measured = ctx.computed.measured(node_id); + let gap = match style.col_gap { + Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(pixels))) => f32::from(pixels), + _ => 0.0, + }; + let room = TrackRoom { + tracks, + measured: measured + .as_deref() + .map(|widths| &widths[..widths.len() / 2]), + shares: tracks.iter().any(|track| matches!(track, GridTrack::Fr(_))), + gap, + }; let mut outer = v_flex().w_full().min_w_0(); style.apply_to(outer.style(), ctx.viewport_width); outer.style().display = Some(gpui::Display::Flex); outer.style().flex_direction = Some(gpui::FlexDirection::Column); - - let mut cursor = 0usize; - let mut current_row = make_track_row(style); - - for (span, child) in items { - let span = span.min(col_count); - if cursor > 0 && cursor + span > col_count { - outer = outer.child(current_row); - current_row = make_track_row(style); - cursor = 0; + outer.style().align_items = Some(AlignItems::Stretch); + outer.style().justify_content = None; + if std::mem::take(&mut ctx.stretch) { + outer.style().flex_grow = Some(1.0); + } + outer = outer.children(decorations(style)); + + let mut row = make_track_row(style); + let mut filled = 0usize; + for (cid, start, span) in track_items(ctx.doc, ctx.computed, node_id, col_count) { + if start == 0 && filled > 0 { + outer = outer.child(room.close(row, filled)); + row = make_track_row(style); } - let mut cell = div().min_w_0(); - apply_track_span( - cell.style(), - &tracks[cursor..(cursor + span).min(col_count)], - ); - current_row = current_row.child(cell.child(child)); - cursor += span; - if cursor >= col_count { - outer = outer.child(current_row); - current_row = make_track_row(style); - cursor = 0; + let mut cell = div().flex().flex_col(); + let narrows = match &ctx.doc.nodes[cid].kind { + NodeKind::Text(text) => can_wrap(text), + NodeKind::Element(_) => ctx + .computed + .shown(cid) + .is_some_and(|child| narrows(ctx.doc, ctx.computed, cid, child)), + }; + if narrows { + cell = cell.min_w_0(); } + room.apply(cell.style(), start, span); + let mut down = style.align_items.unwrap_or(AlignItems::Stretch); + let rendered = match &ctx.doc.nodes[cid].kind { + NodeKind::Text(text) => { + let normalized = normalize_text(text, style.white_space); + let transformed = apply_text_transform(normalized.trim(), style.text_transform); + Some( + text_box(&transformed, style.font_size) + .child(ctx.text.run(transformed, Vec::new())) + .into_any_element(), + ) + } + NodeKind::Element(el) => ctx.computed.shown(cid).and_then(|child| { + down = child.align_self.unwrap_or(down); + ctx.stretch = down == AlignItems::Stretch; + let rendered = render_element(cid, el, child, None, ctx, cx); + ctx.stretch = false; + rendered + }), + }; + cell = match down { + AlignItems::Center => cell.justify_center(), + AlignItems::FlexEnd => cell.justify_end(), + _ => cell, + }; + cell = match style.justify_items { + Some(AlignItems::Center) => cell.items_center(), + Some(AlignItems::FlexEnd) => cell.items_end(), + Some(AlignItems::FlexStart | AlignItems::Baseline) => cell.items_start(), + _ => cell, + }; + row = row.child(cell.children(rendered)); + filled = start + span; } - if cursor > 0 { - outer = outer.child(current_row); + if filled > 0 { + outer = outer.child(room.close(row, filled)); + } + // What the grid positions itself is no item of it. + for &cid in &ctx.doc.nodes[node_id].children { + if let NodeKind::Element(el) = &ctx.doc.nodes[cid].kind + && let Some(child) = ctx.computed.shown(cid) + && child.position == Position::Absolute + { + outer = outer.children(render_element(cid, el, child, None, ctx, cx)); + } } - outer.into_any_element() } fn make_track_row(style: &ComputedStyle) -> gpui::Div { - let mut row = h_flex().w_full().min_w_0(); + let mut row = h_flex().w_full().min_w_0().items_stretch().flex_grow(1.0); if let Some(gap) = style.col_gap { row.style().gap.width = Some(gap); } - if let Some(ai) = style.align_items { - row.style().align_items = Some(ai); - } row } -fn apply_track_span(style: &mut gpui::StyleRefinement, slice: &[GridTrack]) { - let mut total_fr = 0.0f32; - let mut total_px = 0.0f32; - let mut total_pct = 0.0f32; - let mut has_auto = false; - for tr in slice { - match tr { - GridTrack::Fr(f) => total_fr += *f, - GridTrack::Px(p) => total_px += *p, - GridTrack::Percent(pct) => total_pct += *pct, - GridTrack::Auto => has_auto = true, +/// The room each track of a grid has in every one of its rows. +struct TrackRoom<'a> { + tracks: &'a [GridTrack], + /// The width of each track's widest item, for the `auto` tracks. + measured: Option<&'a [f32]>, + /// Some track takes a share of what is left; else the `auto` tracks do. + shares: bool, + gap: f32, +} + +impl TrackRoom<'_> { + /// Give `cell` the room of the `span` tracks from `start`. + fn apply(&self, cell: &mut gpui::StyleRefinement, start: usize, span: usize) { + let end = (start + span).min(self.tracks.len()); + let slice = &self.tracks[start.min(end)..end]; + let mut share = 0.0f32; + let mut pixels = self.gap * slice.len().saturating_sub(1) as f32; + let mut percent = 0.0f32; + let mut fits_content = false; + let mut gives = false; + for (index, track) in slice.iter().enumerate() { + match track { + GridTrack::Fr(fr) => share += *fr, + GridTrack::Px(px) => pixels += *px, + GridTrack::Percent(pct) => percent += *pct, + GridTrack::Auto => { + gives = true; + match self.measured.and_then(|widths| widths.get(start + index)) { + Some(width) => pixels += *width, + None => fits_content = true, + } + if !self.shares { + share += 1.0; + } + } + } + } + if percent > 0.0 && share == 0.0 { + cell.size.width = Some(relative(percent.clamp(0.0, 1.0)).into()); + cell.flex_shrink = Some(0.0); + } else if fits_content { + cell.flex_grow = Some(share); + cell.flex_shrink = Some(1.0); + } else { + cell.flex_basis = Some(px(pixels).into()); + cell.flex_grow = Some(share); + cell.flex_shrink = Some(if share > 0.0 || gives { 1.0 } else { 0.0 }); } } - if total_fr > 0.0 { - style.flex_grow = Some(total_fr); - style.flex_shrink = Some(1.0); - style.flex_basis = Some(px(0.0).into()); - } else if total_pct > 0.0 { - style.size.width = Some(relative(total_pct.clamp(0.0, 1.0)).into()); - style.flex_shrink = Some(0.0); - } else if total_px > 0.0 { - style.size.width = Some(px(total_px).into()); - style.flex_shrink = Some(0.0); - } else if has_auto { - style.flex_grow = Some(1.0); + + /// `row`, which has items in its first `filled` tracks, with the room of + /// the tracks it has none in left empty. + fn close(&self, mut row: gpui::Div, filled: usize) -> gpui::Div { + for start in filled..self.tracks.len() { + let mut cell = div().min_w_0(); + self.apply(cell.style(), start, 1); + row = row.child(cell); + } + row } } +/// The rows of a table: each with its style, whether it is of the head, and +/// its cells with the column each starts in and how many it spans. +struct TableRows<'a> { + caption: Option, + rows: Vec>, + columns: usize, +} + +struct TableRow<'a> { + style: &'a ComputedStyle, + head: bool, + cells: Vec<(NodeId, &'a ComputedStyle, usize, usize)>, +} + +fn table_rows<'a>(doc: &Document, computed: &'a Computed, node_id: NodeId) -> TableRows<'a> { + let mut table = TableRows { + caption: None, + rows: Vec::new(), + columns: 0, + }; + for &cid in &doc.nodes[node_id].children { + let (Some(el), Some(_)) = (doc.element(cid), computed.shown(cid)) else { + continue; + }; + match el.tag.as_str() { + "caption" => table.caption = Some(cid), + "thead" | "tbody" | "tfoot" => { + for &rid in &doc.nodes[cid].children { + if doc.element(rid).is_some_and(|row| row.tag == "tr") + && let Some(style) = computed.shown(rid) + { + let mut cells = Vec::new(); + let mut column = 0usize; + for &cell_id in &doc.nodes[rid].children { + if let Some(cell) = doc.element(cell_id) + && matches!(cell.tag.as_str(), "td" | "th") + && let Some(cell_style) = computed.shown(cell_id) + && column < MAX_COLUMNS + { + let span = cell + .attr("colspan") + .and_then(|s| s.parse::().ok()) + .unwrap_or(1) + .clamp(1, MAX_COLSPAN) + .min(MAX_COLUMNS - column); + cells.push((cell_id, cell_style, column, span)); + column += span; + } + } + table.columns = table.columns.max(column); + table.rows.push(TableRow { + style, + head: el.tag == "thead", + cells, + }); + } + } + } + _ => {} + } + } + table +} + +/// The room a column of a table has in every row. +#[derive(Clone, Copy)] +enum ColumnRoom { + /// The width a cell of the column names, in pixels. + Pixels(f32), + /// The share of the table a cell of the column names. + Share(f32), + /// The width of the column's widest cell, which it gives and takes of + /// what the table has over or under in that measure. + Content(f32), + /// An equal part of what is left. + Even, +} + +/// A table cell's box and what it holds, before its column gives it room. +fn table_cell( + cell_id: NodeId, + cell_style: &ComputedStyle, + ctx: &mut RenderCtx<'_>, + cx: &App, +) -> gpui::Div { + let mut cell_div = v_flex().min_w_0(); + cell_style.apply_to(cell_div.style(), ctx.viewport_width); + cell_div.style().size.width = None; + cell_div = match cell_style.vertical_align { + VerticalAlign::Top => cell_div.justify_start(), + VerticalAlign::Bottom => cell_div.justify_end(), + _ => cell_div.justify_center(), + }; + let outer_cell = ctx.text.enter_cell(); + let children = render_children(&ctx.doc.nodes[cell_id].children, cell_style, None, ctx, cx); + ctx.text.leave(outer_cell); + cell_div + .children(decorations(cell_style)) + .children(children) +} + /// Native GPUI HTML `` renderer with header styling, borders, `colspan`, -/// caption support, and horizontal scrolling for wide tables. +/// caption support, and horizontal scrolling for wide tables. A column has +/// the same room in every row: the width a cell of it names, else the width +/// [`measure`] found its widest cell to have. fn render_table( node_id: NodeId, table_style: &ComputedStyle, @@ -727,81 +1134,124 @@ fn render_table( cx: &App, ) -> AnyElement { let computed = ctx.computed; - let mut caption_el: Option = None; - let mut rows: Vec<(NodeId, &ComputedStyle, bool)> = Vec::new(); + let parts = table_rows(ctx.doc, computed, node_id); + let caption_el = parts.caption.and_then(|cid| { + render_element( + cid, + ctx.doc.element(cid)?, + computed.shown(cid)?, + None, + ctx, + cx, + ) + }); - for &cid in &ctx.doc.nodes[node_id].children { - if let NodeKind::Element(el) = &ctx.doc.nodes[cid].kind { - let Some(cs) = computed.shown(cid) else { + let measured = computed.measured(node_id); + let fills = table_style.width.is_some(); + let mut columns: Vec> = vec![None; parts.columns]; + for row in &parts.rows { + for &(_, cell_style, column, span) in &row.cells { + if span != 1 || columns[column].is_some() { continue; + } + columns[column] = match cell_style.width { + Some(Length::Definite(DefiniteLength::Absolute(AbsoluteLength::Pixels(w)))) => { + let chrome = if cell_style.border_box { + 0.0 + } else { + cell_style.chrome().0 + }; + Some(ColumnRoom::Pixels(f32::from(w) + chrome)) + } + Some(Length::Definite(DefiniteLength::Fraction(share))) => { + Some(ColumnRoom::Share(share)) + } + _ => None, }; - match el.tag.as_str() { - "caption" => { - caption_el = render_element(cid, el, cs, None, ctx, cx); + } + } + let columns: Vec = columns + .into_iter() + .enumerate() + .map(|(index, named)| { + named.unwrap_or_else(|| { + match measured.as_deref().and_then(|widths| widths.get(index)) { + Some(width) if !table_style.table_fixed => ColumnRoom::Content(*width), + _ => ColumnRoom::Even, } - "thead" | "tbody" | "tfoot" => { - let is_head = el.tag == "thead"; - for &rid in &ctx.doc.nodes[cid].children { - if ctx.doc.element(rid).is_some_and(|row| row.tag == "tr") - && let Some(rs) = computed.shown(rid) - { - rows.push((rid, rs, is_head)); - } + }) + }) + .collect(); + let table_width = ctx.viewport_width; + let room = |cell: &mut gpui::StyleRefinement, column: usize, span: usize| { + let slice = &columns[column..(column + span).min(columns.len())]; + if let [ColumnRoom::Share(share)] = slice { + cell.size.width = Some(relative(share.clamp(0.0, 1.0)).into()); + cell.flex_shrink = Some(0.0); + return; + } + if slice.len() == columns.len() && slice.len() > 1 { + cell.size.width = Some(relative(1.0).into()); + return; + } + let mut pixels = 0.0f32; + let mut grows = 0.0f32; + let mut gives = false; + let rigid: f32 = (column..(column + span).min(columns.len())) + .filter_map(|index| measured.as_deref()?.get(columns.len() + index)) + .sum(); + if rigid > 0.0 { + cell.min_size.width = Some(px(rigid).into()); + } + for column in slice { + match *column { + ColumnRoom::Pixels(width) => pixels += width, + ColumnRoom::Share(share) => pixels += share * table_width, + ColumnRoom::Content(width) => { + pixels += width; + gives = true; + if fills { + grows += width.max(1.0); } } - _ => {} + ColumnRoom::Even => { + gives = true; + grows += 1.0; + } } } - } + cell.flex_basis = Some(px(pixels).into()); + cell.flex_grow = Some(grows); + cell.flex_shrink = Some(if gives { 1.0 } else { 0.0 }); + }; - let mut table = v_flex().w_full().min_w_0(); + let mut table = v_flex().min_w_0(); table_style.apply_to(table.style(), ctx.viewport_width); table.style().display = Some(gpui::Display::Flex); table.style().flex_direction = Some(gpui::FlexDirection::Column); - let row_count = rows.len(); - for (row_idx, (rid, row_style, is_head)) in rows.into_iter().enumerate() { + let row_count = parts.rows.len(); + for (row_idx, row) in parts.rows.into_iter().enumerate() { let outer_row = ctx.text.enter_row(); let mut row_div = h_flex().w_full().min_w_0().items_stretch(); - row_style.apply_to(row_div.style(), ctx.viewport_width); + row.style.apply_to(row_div.style(), ctx.viewport_width); row_div.style().display = Some(gpui::Display::Flex); row_div.style().flex_direction = Some(gpui::FlexDirection::Row); // Subtle default row divider if author did not explicitly clear borders. - if row_style.border_bottom_w.is_none() && (is_head || row_idx + 1 < row_count) { + if row.style.border_bottom_w.is_none() && (row.head || row_idx + 1 < row_count) { row_div = row_div .border_b_1() - .border_color(ctx.theme.border.opacity(if is_head { 0.9 } else { 0.5 })); + .border_color(ctx.theme.border.opacity(if row.head { 0.9 } else { 0.5 })); } - if is_head && row_style.background.is_none() { + if row.head && row.style.background.is_none() { row_div = row_div.bg(ctx.theme.muted.opacity(0.6)); } - for &cell_id in &ctx.doc.nodes[rid].children { - if let NodeKind::Element(cel) = &ctx.doc.nodes[cell_id].kind - && matches!(cel.tag.as_str(), "td" | "th") - && let Some(cell_style) = computed.shown(cell_id) - { - let colspan = cel - .attr("colspan") - .and_then(|s| s.parse::().ok()) - .unwrap_or(1) - .clamp(1, MAX_COLSPAN); - let mut cell_div = v_flex().min_w_0().justify_center(); - cell_style.apply_to(cell_div.style(), ctx.viewport_width); - if cell_style.width.is_none() { - cell_div.style().flex_grow = Some(colspan as f32); - cell_div.style().flex_shrink = Some(1.0); - cell_div.style().flex_basis = Some(px(0.0).into()); - } else { - cell_div.style().flex_shrink = Some(0.0); - } - let outer_cell = ctx.text.enter_cell(); - let children = - render_children(&ctx.doc.nodes[cell_id].children, cell_style, None, ctx, cx); - ctx.text.leave(outer_cell); - row_div = row_div.child(cell_div.children(children)); - } + for (cell_id, cell_style, column, span) in row.cells { + let mut cell_div = table_cell(cell_id, cell_style, ctx, cx); + room(cell_div.style(), column, span); + row_div = row_div.child(cell_div); } ctx.text.leave(outer_row); table = table.child(row_div); @@ -810,18 +1260,130 @@ fn render_table( v_flex() .w_full() .min_w_0() + .items_start() .children(caption_el) .child( div() .id(("html-table", node_id)) - .w_full() + .max_w_full() .min_w_0() + .when(fills, |this| this.w_full()) .overflow_x_scroll_area() .child(table), ) .into_any_element() } +/// Find the widths [`render_track_grid`] and [`render_table`] give their +/// columns by: for each `auto` track of a grid and each column of a table, +/// the width its widest item has when nothing narrows it. GPUI lays a row +/// out by itself, so what the rows of one column share is found first, by +/// laying each item out alone. +/// +/// An element is laid out under the styles of what is around the visual, +/// so each item is put in a box with the page's own. +pub(crate) fn measure( + doc: &Document, + computed: &Computed, + viewport_width: f32, + window: &mut Window, + cx: &mut App, +) { + let media = MediaSlots::default(); + let mut left = MAX_MEASURED; + // Last first: what is inside is measured before what holds it. + for node_id in (0..doc.nodes.len()).rev() { + let (Some(el), Some(style)) = (doc.element(node_id), computed.shown(node_id)) else { + continue; + }; + // Each item to measure, with its column and whether it is a cell. + let (count, items): (usize, Vec<(NodeId, usize, bool)>) = if el.tag == "table" { + let parts = table_rows(doc, computed, node_id); + let cells = parts + .rows + .iter() + .flat_map(|row| &row.cells) + .filter(|cell| cell.3 == 1) + .map(|cell| (cell.0, cell.2, true)) + .collect(); + (parts.columns, cells) + } else if matches!(style.display, DisplayKind::Grid | DisplayKind::InlineGrid) + && let Some(GridColumns::Tracks(tracks)) = &style.grid_columns + && tracks.contains(&GridTrack::Auto) + { + let items = track_items(doc, computed, node_id, tracks.len()) + .into_iter() + .filter(|&(cid, start, span)| { + span == 1 && tracks[start] == GridTrack::Auto && doc.element(cid).is_some() + }) + .map(|(cid, start, _)| (cid, start, false)) + .collect(); + (tracks.len(), items) + } else { + continue; + }; + if items.is_empty() || items.len() > left { + continue; + } + left -= items.len(); + // After the widths, as many more: the width each column cannot be + // narrower than, which is that of its widest item that does not wrap. + let mut widths = vec![0.0f32; count * 2]; + for (item, column, is_cell) in items { + let built = { + let mut ctx = RenderCtx { + doc, + computed, + media: &media, + theme: cx.theme(), + viewport_width, + frame: Frame::default(), + text: TextSink::default(), + stretch: false, + capped: false, + words: 0, + }; + let (Some(el), Some(style)) = (doc.element(item), computed.shown(item)) else { + continue; + }; + if is_cell { + Some(table_cell(item, style, &mut ctx, cx).into_any_element()) + } else { + render_element(item, el, style, None, &mut ctx, cx) + } + }; + let Some(built) = built else { + continue; + }; + let root = &computed.root; + let mut alone = div() + .flex() + .flex_col() + .items_start() + .font_family(root.font_family.clone()) + .text_size(px(root.font_size)) + .child(built) + .into_any_element(); + let natural = alone.layout_as_root( + size(AvailableSpace::MaxContent, AvailableSpace::MaxContent), + window, + cx, + ); + // A width in whole pixels and one over: a line as wide as its + // box to a fraction wraps. + let natural = f32::from(natural.width).ceil() + 1.0; + widths[column] = widths[column].max(natural); + if computed + .shown(item) + .is_some_and(|style| style.white_space == WhiteSpaceMode::NoWrap) + { + widths[count + column] = widths[count + column].max(natural); + } + } + computed.set_measured(node_id, widths); + } +} + /// Render a contiguous run of inline nodes. /// /// Pure text + styled spans (`strong`, `em`, `span`, `mark`, `small`, `br`, etc.) @@ -865,7 +1427,7 @@ fn render_inline_run( } else if text.is_empty() { return None; } - let styled = text_box(&text).w_full().min_w_0(); + let styled = text_box(&text, parent_style.font_size).w_full(); return Some( styled .child(ctx.text.run(text, highlights)) @@ -873,49 +1435,396 @@ fn render_inline_run( ); } - // Rich inline flow (contains badges, inline-blocks, links, inline SVGs, etc.) - let mut row = h_flex().w_full().min_w_0().flex_wrap().items_center(); + // A line of text with boxes in it: badges, pictures, links, text of + // another size. GPUI wraps the text of one box and nothing around it, so + // the line is a wrapping row of the boxes and of the text between them, + // word by word. + let mut row = h_flex().w_full().min_w_0().items_baseline(); + if parent_style.white_space != WhiteSpaceMode::NoWrap { + row = row.flex_wrap(); + } match parent_style.text_align { Some(TextAlign::Center) => row = row.justify_center(), Some(TextAlign::Right) => row = row.justify_end(), _ => {} } - let mut any_visible = false; let outer = ctx.text.enter_flow(); - for &nid in nodes { - match &ctx.doc.nodes[nid].kind { - NodeKind::Text(t) => { - let norm = normalize_text(t, parent_style.white_space); - if norm.trim().is_empty() { - if !norm.is_empty() { - ctx.text.space(); + let mut flow = InlineFlow { + block: parent_style, + items: Vec::new(), + space: None, + fresh: true, + }; + flow.nodes(nodes, parent_style, None, ctx, cx); + ctx.text.leave(outer); + (!flow.items.is_empty()).then(|| row.children(flow.items).into_any_element()) +} + +/// The boxes of a line as it is built, in order. +struct InlineFlow<'a> { + /// The style of the block the line is in. + block: &'a ComputedStyle, + items: Vec, + /// White space stands between the last box and the next, in text of this + /// style and background. + space: Option<(&'a ComputedStyle, Option)>, + /// Nothing is on the line yet. + fresh: bool, +} + +impl<'a> InlineFlow<'a> { + fn nodes<'c: 'a>( + &mut self, + nodes: &[NodeId], + style: &'a ComputedStyle, + background: Option, + ctx: &mut RenderCtx<'c>, + cx: &App, + ) { + for &nid in nodes { + match &ctx.doc.nodes[nid].kind { + NodeKind::Text(text) => self.text(text, style, background, ctx), + NodeKind::Element(el) => { + if el.tag == "br" { + self.line_break(ctx); + continue; + } + let Some(child) = ctx.computed.shown(nid) else { + continue; + }; + if flows_as_text(nid, el, child, ctx) { + let background = child.background_hsla.or(background); + self.nodes(&ctx.doc.nodes[nid].children, child, background, ctx, cx); + continue; } + self.spaced(ctx); + if let Some(rendered) = render_element(nid, el, child, None, ctx, cx) { + self.items.push(self.on_line(rendered, nid, child, ctx)); + self.fresh = false; + } + } + } + } + } + + fn text( + &mut self, + text: &str, + style: &'a ComputedStyle, + background: Option, + ctx: &mut RenderCtx<'_>, + ) { + let normalized = normalize_text(text, style.white_space); + let kept = matches!( + style.white_space, + WhiteSpaceMode::Pre | WhiteSpaceMode::PreWrap | WhiteSpaceMode::PreLine + ); + for (index, line) in normalized.split('\n').enumerate() { + if index > 0 { + if kept { + self.line_break(ctx); } else { - let transformed = apply_text_transform(&norm, parent_style.text_transform); - row = row - .child(text_box(&transformed).child(ctx.text.run(transformed, Vec::new()))); - any_visible = true; + self.space = Some((style, background)); } } - NodeKind::Element(el) => { - if el.tag == "br" { - row = row.child(div().w(relative(1.0)).h(px(0.0))); - ctx.text.line_break(); - any_visible = true; - continue; + match style.white_space { + // A line of `pre` is one box, its spaces as written. + WhiteSpaceMode::Pre | WhiteSpaceMode::NoWrap => { + if !line.trim().is_empty() || (kept && !line.is_empty()) { + let line = if kept { + line + } else { + self.inner(line, style, background) + }; + if !line.is_empty() { + self.spaced(ctx); + self.piece(line, style, background, ctx); + } + } else if !line.is_empty() && !self.fresh { + self.space = Some((style, background)); + } } - let Some(style) = ctx.computed.shown(nid) else { - continue; - }; - if let Some(child_el) = render_element(nid, el, style, None, ctx, cx) { - row = row.child(child_el); - any_visible = true; + _ if ctx.words >= MAX_WORDS => { + if !line.trim().is_empty() { + self.spaced(ctx); + let text = apply_text_transform(line.trim(), style.text_transform); + let mut piece = text_box(&text, style.font_size); + style.apply_text_to(piece.style()); + self.items.push( + piece + .child(ctx.text.run(text, Vec::new())) + .into_any_element(), + ); + self.fresh = false; + } + } + _ => { + for word in words(line) { + ctx.words += 1; + if word.trim().is_empty() { + if !self.fresh { + self.space = Some((style, background)); + } + } else { + self.spaced(ctx); + self.piece(word, style, background, ctx); + } + } } } } } - ctx.text.leave(outer); - any_visible.then(|| row.into_any_element()) + + /// `line` without the white space at its ends, which is kept as the + /// space before the next box. + fn inner<'t>( + &mut self, + line: &'t str, + style: &'a ComputedStyle, + background: Option, + ) -> &'t str { + if line.starts_with(char::is_whitespace) && !self.fresh { + self.space = Some((style, background)); + } + line.trim_start() + } + + /// The white space before the next box, as a box: it is drawn where a + /// line goes on, and a line that ends at it loses only its width. + fn spaced(&mut self, ctx: &mut RenderCtx<'_>) { + if let Some((style, background)) = self.space.take() + && !self.fresh + { + self.piece(" ", style, background, ctx); + } + } + + fn piece( + &mut self, + text: &str, + style: &ComputedStyle, + background: Option, + ctx: &mut RenderCtx<'_>, + ) { + let text = apply_text_transform(text, style.text_transform); + let mut piece = div().flex_none().whitespace_nowrap(); + style.apply_text_to(piece.style()); + if let Some(background) = background { + piece = piece.bg(background); + } + // No line breaks before what closes a phrase, whatever box it + // follows: the two are one box of the row. + // CoreText measures a line without the blank half of a full-width + // mark at either end of it, as a line of a paragraph is set. A word + // is a line to it and is no line's end here, so the half is put back. + if cfg!(target_vendor = "apple") { + let half = px(style.font_size / 2.0); + if text.ends_with([ + ',', '。', '、', ';', ':', '!', '?', ')', '」', '』', '】', '》', + ]) { + piece = piece.pr(half); + } + if text.starts_with(['(', '「', '『', '【', '《']) { + piece = piece.pl(half); + } + } + let glued = !self.fresh && self.space.is_none() && text.starts_with(closes_phrase); + let piece = piece + .child(ctx.text.run(text, Vec::new())) + .into_any_element(); + match self.items.pop() { + Some(before) if glued => self.items.push( + h_flex() + .flex_none() + .items_baseline() + .child(before) + .child(piece) + .into_any_element(), + ), + before => { + self.items.extend(before); + self.items.push(piece); + } + } + self.fresh = false; + } + + fn line_break(&mut self, ctx: &mut RenderCtx<'_>) { + // A line with nothing on it is still a line. + let height = if self.fresh { + line_height(self.block) + } else { + 0.0 + }; + self.items + .push(div().w(relative(1.0)).h(px(height)).into_any_element()); + ctx.text.line_break(); + self.space = None; + self.fresh = true; + } + + /// A box on the line, where the line's text puts it: the row sets every + /// box on its bottom edge, and a box whose own baseline is not as far + /// above that edge as the line's is drawn that much higher. + fn on_line( + &self, + rendered: AnyElement, + node: NodeId, + style: &ComputedStyle, + ctx: &RenderCtx<'_>, + ) -> AnyElement { + // A box as wide as a share of its line is given that width by the + // line, which a box around it would come between. + if matches!( + style.width, + Some(Length::Definite(DefiniteLength::Fraction(_))) + ) { + return rendered; + } + let line = baseline_from_bottom(self.block); + // A box of text stands on its own last line, which is never above + // the line's: only a box with none is moved up to it. + let stands = if has_text(ctx.doc, node) { + (line - baseline_from_bottom(style) - style.chrome_below()).max(0.0) + } else { + line + }; + let lift = match style.vertical_align { + VerticalAlign::Middle => { + return div() + .flex_none() + .self_center() + .child(rendered) + .into_any_element(); + } + VerticalAlign::Top => { + return div() + .flex_none() + .self_start() + .child(rendered) + .into_any_element(); + } + VerticalAlign::Bottom => return rendered, + VerticalAlign::Baseline => stands, + VerticalAlign::Raised(by) => stands + by, + }; + if lift.abs() < 0.5 { + return rendered; + } + div() + .flex_none() + .relative() + .top(px(-lift)) + .child(rendered) + .into_any_element() + } +} + +/// The height of a line of `style`'s text. +fn line_height(style: &ComputedStyle) -> f32 { + match style.line_height { + Some(DefiniteLength::Fraction(share)) => share * style.font_size, + Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(pixels))) => f32::from(pixels), + _ => 1.5 * style.font_size, + } +} + +/// Whether an inline element is drawn as text of its line, which wraps +/// inside it: it has no box of its own, and nothing put before or after it. +fn flows_as_text( + nid: NodeId, + el: &ElementData, + style: &ComputedStyle, + ctx: &RenderCtx<'_>, +) -> bool { + style.display.is_pure_inline() + && !style.has_inline_box() + && !matches!( + el.tag.as_str(), + "a" | "svg" | "img" | "progress" | "meter" | "input" | "button" + ) + && ctx.computed.before(nid).is_none() + && ctx.computed.after(nid).is_none() +} + +/// Whether `c` closes a phrase, so that no line begins with it. +fn closes_phrase(c: char) -> bool { + matches!( + c, + ',' | '.' + | ';' + | ':' + | '!' + | '?' + | ')' + | ']' + | '}' + | '%' + | ',' + | '。' + | '、' + | ';' + | ':' + | '!' + | '?' + | ')' + | '」' + | '』' + | '】' + | '》' + | '〉' + | '”' + | '’' + | '…' + | '·' + ) +} + +fn is_cjk(c: char) -> bool { + matches!( + c, + '\u{2e80}'..='\u{30ff}' + | '\u{3400}'..='\u{4dbf}' + | '\u{4e00}'..='\u{9fff}' + | '\u{ac00}'..='\u{d7af}' + | '\u{f900}'..='\u{faff}' + | '\u{ff00}'..='\u{ffef}' + | '\u{20000}'..='\u{2fa1f}' + ) +} + +/// `text` cut where a line may break: after white space, and on either side +/// of a CJK character, but never before what closes a phrase nor after what +/// opens one. White space after a word stays with it. +fn words(text: &str) -> Vec<&str> { + let closes = closes_phrase; + let opens = |c: char| { + matches!( + c, + '(' | '[' | '{' | '(' | '「' | '『' | '【' | '《' | '〈' | '“' | '‘' + ) + }; + let mut out = Vec::new(); + let mut start = 0; + let mut before: Option = None; + for (at, c) in text.char_indices() { + if let Some(before) = before { + let breaks = if before.is_whitespace() { + !c.is_whitespace() + } else { + !c.is_whitespace() && !closes(c) && !opens(before) && (is_cjk(before) || is_cjk(c)) + }; + if breaks { + out.push(&text[start..at]); + start = at; + } + } + before = Some(c); + } + if start < text.len() { + out.push(&text[start..]); + } + out } fn can_flatten_inline(nodes: &[NodeId], parent_style: &ComputedStyle, ctx: &RenderCtx<'_>) -> bool { @@ -941,6 +1850,10 @@ fn can_flatten_inline(nodes: &[NodeId], parent_style: &ComputedStyle, ctx: &Rend if !style.display.is_pure_inline() || style.has_inline_box() { return false; } + // One run of text has one background shape: its lines'. + if style.background.is_some() && style.radius_tl.is_some() { + return false; + } if (style.font_size - parent_style.font_size).abs() > 0.5 || style.font_family != parent_style.font_family { @@ -1279,28 +2192,35 @@ fn fitted_media_size( (w.max(1.0), h.max(1.0)) } -/// The box a run of text is drawn in. GPUI breaks a word that is wider than -/// its box wherever the box ends, `100%` into `100` and `%`; a browser -/// breaks only at a break opportunity and lets the word overflow. A run that -/// plainly has none, neither whitespace nor a CJK character, is not wrapped. -fn text_box(text: &str) -> gpui::Div { - let breaks = |c: char| { - c.is_whitespace() - || matches!( - c, - '\u{3040}'..='\u{30ff}' - | '\u{3400}'..='\u{4dbf}' - | '\u{4e00}'..='\u{9fff}' - | '\u{ac00}'..='\u{d7af}' - | '\u{f900}'..='\u{faff}' - | '\u{20000}'..='\u{2fa1f}' - ) - }; - if text.trim().chars().any(breaks) { - div() - } else { - div().whitespace_nowrap() +/// The box a run of text set at `font_size` is drawn in. GPUI breaks a +/// word that is wider than its box wherever the box ends, `100%` into `100` +/// and `%`; a browser breaks only at a break opportunity and lets the word +/// overflow. So a run that has none is not wrapped, and one that has is no +/// narrower than its longest word, as near as that is known before the text +/// is set: three fifths of its size for each letter, its size for a CJK character. +fn text_box(text: &str, font_size: f32) -> gpui::Div { + if !can_wrap(text) { + return div().whitespace_nowrap(); } + let mut longest = 0.0f32; + let mut word = 0.0f32; + for c in text.chars() { + if c.is_whitespace() { + word = 0.0; + } else if is_cjk(c) { + word = 0.0; + longest = longest.max(1.0); + } else { + word += 0.6; + longest = longest.max(word); + } + } + div().min_w(px(longest * font_size)) +} + +/// Whether `text` has anywhere a line may break in it. +fn can_wrap(text: &str) -> bool { + text.trim().chars().any(|c| c.is_whitespace() || is_cjk(c)) } fn normalize_text(text: &str, mode: WhiteSpaceMode) -> String { diff --git a/crates/ui/src/html/style.rs b/crates/ui/src/html/style.rs index 3b8a6e821..3c1b06ce8 100644 --- a/crates/ui/src/html/style.rs +++ b/crates/ui/src/html/style.rs @@ -32,6 +32,8 @@ const MAX_FACTOR: f32 = 10_000.0; /// The most grid tracks a template or a placement may name; layout walks /// every track for every item. pub(crate) const MAX_GRID_TRACKS: u16 = 256; +/// The most stops of a gradient that are read. +const MAX_GRADIENT_STOPS: usize = 16; /// The most shadows one box is painted with. const MAX_SHADOWS: usize = 8; @@ -113,6 +115,40 @@ pub(crate) enum ListStyleType { Decimal, } +/// Where an inline box sits on its line. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum VerticalAlign { + Baseline, + Top, + Middle, + Bottom, + /// Raised by this many pixels from the baseline. + Raised(f32), +} + +/// A gradient of more stops than GPUI's two, along one axis of its box. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct StopGradient { + /// Along the box's width, else down its height. + pub(crate) horizontal: bool, + /// Each stop's colour and where along the axis it is, from 0 to 1 and + /// never before the stop it follows. + pub(crate) stops: Vec<(Hsla, f32)>, +} + +/// How a box's four borders are drawn by GPUI, which draws one colour. +#[derive(Clone, Debug, Default, PartialEq)] +pub(crate) struct BorderPlan { + /// The colour of the borders GPUI draws. + pub(crate) color: Option, + /// Top, right, bottom, left: a border not drawn as one keeps its room as + /// padding of this width. + pub(crate) padded: [f32; 4], + /// Borders of another colour than the box's, drawn as strips over the + /// room kept for them: the side, its width and its colour. + pub(crate) strips: Vec<(usize, f32, Hsla)>, +} + /// Complete resolved style for one DOM element. #[derive(Clone, Debug)] pub(crate) struct ComputedStyle { @@ -210,6 +246,20 @@ pub(crate) struct ComputedStyle { // Pseudo-element static content pub(crate) content: Option, + + /// `box-sizing: border-box`: a size is the box's, not its content's. + pub(crate) border_box: bool, + pub(crate) justify_items: Option, + pub(crate) line_clamp: Option, + /// `transform: translate()`, in pixels. + pub(crate) translate: (f32, f32), + pub(crate) vertical_align: VerticalAlign, + pub(crate) gradient: Option>, + /// The paint an `` is styled with from outside itself, as + /// declarations. + pub(crate) svg_paint: Option>, + /// `table-layout: fixed`: columns are not sized by what they hold. + pub(crate) table_fixed: bool, } impl ComputedStyle { @@ -289,6 +339,14 @@ impl ComputedStyle { overflow_x: None, overflow_y: None, content: None, + border_box: false, + justify_items: None, + line_clamp: None, + translate: (0.0, 0.0), + vertical_align: VerticalAlign::Baseline, + gradient: None, + svg_paint: None, + table_fixed: false, } } @@ -367,21 +425,34 @@ impl ComputedStyle { overflow_x: None, overflow_y: None, content: None, + border_box: false, + justify_items: None, + line_clamp: None, + translate: (0.0, 0.0), + vertical_align: VerticalAlign::Baseline, + gradient: None, + svg_paint: None, + table_fixed: false, } } - /// True when this element draws a box (padding, border, background, shadow, - /// or explicit size) that cannot be flattened into a plain `StyledText` run. + /// True when this inline element draws a box its line's text cannot + /// wrap inside: a border, room to its sides, a size, a shadow, or a + /// background that is no one colour. A background of one colour and + /// room above and below are drawn behind the text line by line. pub(crate) fn has_inline_box(&self) -> bool { - self.padding_top.is_some() - || self.padding_right.is_some() - || self.padding_bottom.is_some() - || self.padding_left.is_some() - || self.border_top_w.is_some() - || self.border_right_w.is_some() - || self.border_bottom_w.is_some() - || self.border_left_w.is_some() - || self.radius_tl.is_some() + let wide = |padding: Option| { + padding.is_some_and(|padding| padding != DefiniteLength::from(px(0.0))) + }; + let drawn = |border: Option| { + border.is_some_and(|border| border != AbsoluteLength::from(px(0.0))) + }; + wide(self.padding_right) + || wide(self.padding_left) + || drawn(self.border_top_w) + || drawn(self.border_right_w) + || drawn(self.border_bottom_w) + || drawn(self.border_left_w) || self.width.is_some() || self.height.is_some() || !self.box_shadows.is_empty() @@ -390,6 +461,29 @@ impl ComputedStyle { || (self.background.is_some() && self.background_hsla.is_none()) } + /// The width the box is given, where it is given in pixels. + pub(crate) fn width_px(&self) -> Option { + definite_to_px(self.width.and_then(definite), self.font_size) + } + + /// The height the box is given, where it is given in pixels. + pub(crate) fn height_px(&self) -> Option { + definite_to_px(self.height.and_then(definite), self.font_size) + } + + /// The room below the box's content that is its own: padding and border. + pub(crate) fn chrome_below(&self) -> f32 { + let padding = match self.padding_bottom { + Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(pixels))) => f32::from(pixels), + _ => 0.0, + }; + let border = match self.border_bottom_w { + Some(AbsoluteLength::Pixels(pixels)) => f32::from(pixels), + _ => 0.0, + }; + padding + border + } + /// Apply this computed style onto a GPUI `StyleRefinement`. pub(crate) fn apply_to(&self, style: &mut StyleRefinement, viewport_width: f32) { self.apply_flow_to(style, viewport_width); @@ -446,12 +540,8 @@ impl ComputedStyle { }); } } - DisplayKind::InlineBlock => { - style.display = Some(Display::Flex); - style.flex_direction = Some(FlexDirection::Row); - style.align_items = Some(AlignItems::Center); - } DisplayKind::Block + | DisplayKind::InlineBlock | DisplayKind::ListItem | DisplayKind::Table | DisplayKind::TableRowGroup @@ -509,23 +599,45 @@ impl ComputedStyle { style.inset.left = self.left; } + // GPUI sizes the border box; CSS sizes the content box unless told + // otherwise, so a length in pixels grows by the padding and border + // around it. A percentage is left as it is. + let (chrome_x, chrome_y) = if self.border_box { + (0.0, 0.0) + } else { + self.chrome() + }; + let sized = |length: Option, chrome: f32| match length { + Some(Length::Definite(DefiniteLength::Absolute(AbsoluteLength::Pixels(pixels)))) => { + Some(Length::from(px(f32::from(pixels) + chrome))) + } + other => other, + }; if self.width.is_some() { - style.size.width = self.width; + style.size.width = sized(self.width, chrome_x); } if self.height.is_some() { - style.size.height = self.height; + style.size.height = sized(self.height, chrome_y); } if self.min_width.is_some() { - style.min_size.width = self.min_width; + style.min_size.width = sized(self.min_width, chrome_x); } if self.min_height.is_some() { - style.min_size.height = self.min_height; + style.min_size.height = sized(self.min_height, chrome_y); } if self.max_width.is_some() { - style.max_size.width = self.max_width; + style.max_size.width = sized(self.max_width, chrome_x); } if self.max_height.is_some() { - style.max_size.height = self.max_height; + style.max_size.height = sized(self.max_height, chrome_y); + } + if self.translate != (0.0, 0.0) && self.position != Position::Absolute { + if self.left.is_none() && self.right.is_none() { + style.inset.left = Some(px(self.translate.0).into()); + } + if self.top.is_none() && self.bottom.is_none() { + style.inset.top = Some(px(self.translate.1).into()); + } } if self.aspect_ratio.is_some() { style.aspect_ratio = self.aspect_ratio; @@ -561,34 +673,45 @@ impl ComputedStyle { style.padding.left = self.padding_left; } - if self.border_top_w.is_some() { - style.border_widths.top = self.border_top_w; - } - if self.border_right_w.is_some() { - style.border_widths.right = self.border_right_w; - } - if self.border_bottom_w.is_some() { - style.border_widths.bottom = self.border_bottom_w; - } - if self.border_left_w.is_some() { - style.border_widths.left = self.border_left_w; + let plan = self.border_plan(); + let widths = [ + ( + self.border_top_w, + &mut style.border_widths.top, + &mut style.padding.top, + ), + ( + self.border_right_w, + &mut style.border_widths.right, + &mut style.padding.right, + ), + ( + self.border_bottom_w, + &mut style.border_widths.bottom, + &mut style.padding.bottom, + ), + ( + self.border_left_w, + &mut style.border_widths.left, + &mut style.padding.left, + ), + ]; + for ((width, border, padding), padded) in widths.into_iter().zip(plan.padded) { + if padded > 0.0 { + *border = Some(px(0.0).into()); + let inner = match *padding { + Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(pixels))) => { + f32::from(pixels) + } + _ => 0.0, + }; + *padding = Some(px(inner + padded).into()); + } else if width.is_some() { + *border = width; + } } - // A box is drawn in one border colour, as GPUI draws it: the one - // given for the whole box, else a side's. - if let Some(color) = self - .border_color - .or(self.border_left_color) - .or(self.border_top_color) - .or(self.border_bottom_color) - .or(self.border_right_color) - { + if let Some(color) = plan.color { style.border_color = Some(color); - } else if self.border_top_w.is_some() - || self.border_right_w.is_some() - || self.border_bottom_w.is_some() - || self.border_left_w.is_some() - { - style.border_color = Some(self.color); } if self.border_style != BorderStyle::Solid { style.border_style = Some(self.border_style); @@ -623,7 +746,7 @@ impl ComputedStyle { style.grid_location = Some(loc.clone()); } - if let Some(bg) = &self.background { + if let Some(bg) = self.background.as_ref().filter(|_| self.gradient.is_none()) { style.background = Some(bg.clone()); } if !self.box_shadows.is_empty() { @@ -642,7 +765,26 @@ impl ComputedStyle { style.overflow.y = Some(clip(oy)); } - // Typography + self.apply_text_to(style); + if matches!(self.white_space, WhiteSpaceMode::NoWrap) { + style.text.white_space = Some(WhiteSpace::Nowrap); + } + if self.text_ellipsis + && matches!(self.white_space, WhiteSpaceMode::NoWrap) + && matches!(self.overflow_x, Some(Overflow::Hidden)) + { + style.text.text_overflow = Some(gpui::TextOverflow::Truncate(SharedString::from("…"))); + } + if let Some(lines) = self.line_clamp + && matches!(self.overflow_y, Some(Overflow::Hidden)) + { + style.text.line_clamp = Some(lines); + style.text.text_overflow = Some(gpui::TextOverflow::Truncate(SharedString::from("…"))); + } + } + + /// The type the box's text is set in. + pub(crate) fn apply_text_to(&self, style: &mut StyleRefinement) { style.text.color = Some(self.color); style.text.font_size = Some(AbsoluteLength::Pixels(px(self.font_size))); style.text.font_weight = Some(self.font_weight); @@ -667,15 +809,88 @@ impl ComputedStyle { color: Some(self.color), }); } - if matches!(self.white_space, WhiteSpaceMode::NoWrap) { - style.text.white_space = Some(WhiteSpace::Nowrap); - } - if self.text_ellipsis - && matches!(self.white_space, WhiteSpaceMode::NoWrap) - && matches!(self.overflow_x, Some(Overflow::Hidden)) - { - style.text.text_overflow = Some(gpui::TextOverflow::Truncate(SharedString::from("…"))); + } + + /// The width and the height the box's padding and borders take, where + /// they are given in pixels. + pub(crate) fn chrome(&self) -> (f32, f32) { + let padding = |length: Option| match length { + Some(DefiniteLength::Absolute(AbsoluteLength::Pixels(pixels))) => f32::from(pixels), + _ => 0.0, + }; + let border = |length: Option| match length { + Some(AbsoluteLength::Pixels(pixels)) => f32::from(pixels), + _ => 0.0, + }; + ( + padding(self.padding_left) + + padding(self.padding_right) + + border(self.border_left_w) + + border(self.border_right_w), + padding(self.padding_top) + + padding(self.padding_bottom) + + border(self.border_top_w) + + border(self.border_bottom_w), + ) + } + + /// GPUI draws a box's borders in one colour. The colour most of the + /// borders have is the box's; a transparent border keeps its room and is + /// not drawn, and on a box of square corners a border of another colour + /// is drawn as a strip. + pub(crate) fn border_plan(&self) -> BorderPlan { + let width = |length: Option| match length { + Some(AbsoluteLength::Pixels(pixels)) => f32::from(pixels), + Some(AbsoluteLength::Rems(rems)) => rems.0 * BASE_FONT_PX, + None => 0.0, + }; + let sides = [ + (width(self.border_top_w), self.border_top_color), + (width(self.border_right_w), self.border_right_color), + (width(self.border_bottom_w), self.border_bottom_color), + (width(self.border_left_w), self.border_left_color), + ] + .map(|(width, color)| (width, color.or(self.border_color).unwrap_or(self.color))); + let drawn = |(width, color): &(f32, Hsla)| *width > 0.0 && color.a > 0.0; + let mut plan = BorderPlan::default(); + if !sides.iter().any(|(width, _)| *width > 0.0) { + return plan; + } + let votes = |color: Hsla| { + sides + .iter() + .filter(|side| drawn(side) && side.1 == color) + .count() + }; + plan.color = sides + .iter() + .filter(|side| drawn(side)) + .map(|side| side.1) + .reduce(|best, color| { + if votes(color) > votes(best) { + color + } else { + best + } + }); + let Some(main) = plan.color else { + // Every border is transparent: each keeps its room. + plan.color = Some(Hsla::transparent_black()); + return plan; + }; + let square = self.radius_tl.is_none(); + for (index, (width, color)) in sides.into_iter().enumerate() { + if width <= 0.0 || color == main { + continue; + } + if color.a <= 0.0 { + plan.padded[index] = width; + } else if square { + plan.padded[index] = width; + plan.strips.push((index, width, color)); + } } + plan } } @@ -737,8 +952,15 @@ impl Palette { } } - pub(crate) fn font_sans(&self) -> &str { - &self.font_sans + /// What of the page an `` styled `style` is drawn with. + pub(crate) fn svg_page<'a>(&'a self, style: &'a ComputedStyle) -> super::svg::SvgPage<'a> { + super::svg::SvgPage { + color: style.color, + vars: &style.vars, + dark: self.dark, + font_sans: &self.font_sans, + font_mono: &self.font_mono, + } } /// The custom properties `tcode_visualize` documents to the model. @@ -870,7 +1092,8 @@ fn apply_ua_defaults(style: &mut ComputedStyle, el: &ElementData, theme: &Palett match el.tag.as_str() { "span" | "a" | "strong" | "b" | "em" | "i" | "u" | "s" | "del" | "strike" | "small" | "sub" | "sup" | "code" | "kbd" | "samp" | "mark" | "abbr" | "cite" | "time" | "q" - | "label" | "var" | "wbr" => { + | "label" | "var" | "wbr" | "ins" | "dfn" | "bdi" | "bdo" | "big" | "tt" | "font" + | "data" => { style.display = DisplayKind::Inline; } "button" | "badge" | "progress" | "meter" | "input" | "select" | "img" | "svg" => { @@ -946,7 +1169,7 @@ fn apply_ua_defaults(style: &mut ComputedStyle, el: &ElementData, theme: &Palett "em" | "i" | "cite" => { style.font_style = FontStyle::Italic; } - "u" => { + "u" | "ins" => { style.underline = true; } "s" | "del" | "strike" => { @@ -962,9 +1185,6 @@ fn apply_ua_defaults(style: &mut ComputedStyle, el: &ElementData, theme: &Palett "code" | "kbd" | "samp" => { style.font_family = theme.font_mono.clone(); style.font_size = (style.font_size * 0.92).max(11.0); - let bg = theme.muted; - style.background_hsla = Some(bg); - style.background = Some(Fill::Color(bg.into())); } "pre" => { style.font_family = theme.font_mono.clone(); @@ -1239,6 +1459,10 @@ fn apply_declaration( "border-color" => { if let Some(c) = parse_color_for_mode(val, dark) { style.border_color = Some(c.resolve(style.color)); + style.border_top_color = None; + style.border_right_color = None; + style.border_bottom_color = None; + style.border_left_color = None; } } "border-top-color" => { @@ -1343,9 +1567,43 @@ fn apply_declaration( let parts: Vec<&str> = val.split_whitespace().collect(); if let Some(first) = parts.first() { style.align_items = parse_align_items(first); - if let Some(jc) = parse_justify_content(parts.get(1).unwrap_or(first)) { - style.justify_content = Some(jc); - } + style.justify_items = parse_align_items(parts.get(1).unwrap_or(first)); + } + } + "justify-items" => style.justify_items = parse_align_items(val), + "table-layout" => style.table_fixed = val.eq_ignore_ascii_case("fixed"), + "box-sizing" => style.border_box = val.eq_ignore_ascii_case("border-box"), + "line-clamp" | "-webkit-line-clamp" => { + style.line_clamp = number(val) + .filter(|lines| *lines >= 1.0) + .map(|lines| lines.min(1000.0) as usize); + } + "transform" => style.translate = parse_translate(val, em), + "vertical-align" => { + style.vertical_align = match val.to_ascii_lowercase().as_str() { + "top" | "text-top" => VerticalAlign::Top, + "middle" => VerticalAlign::Middle, + "bottom" | "text-bottom" => VerticalAlign::Bottom, + "baseline" => VerticalAlign::Baseline, + _ => match parse_px_f32(val, em) { + Some(raised) => VerticalAlign::Raised(bounded_px(raised)), + None => style.vertical_align, + }, + }; + } + "fill" | "stroke" | "stroke-width" | "stroke-linecap" | "stroke-linejoin" => { + // Put into the ``'s own `style`, which nothing in it may end. + if !val.contains(['"', '<', '>', '&', ';', '{', '}']) { + let value = match parse_color_for_mode(val, dark) { + Some(color) => hsla_to_css(color.resolve(style.color)), + None => val.to_owned(), + }; + let paint = format!( + "{}{}:{value};", + style.svg_paint.as_deref().unwrap_or_default(), + decl.name + ); + style.svg_paint = Some(paint.into()); } } "place-content" => { @@ -1393,12 +1651,14 @@ fn apply_declaration( } } "background" | "background-image" => { + style.gradient = None; if val.eq_ignore_ascii_case("none") { style.background = None; style.background_hsla = None; - } else if let Some(grad) = parse_linear_gradient(val, style.color, dark) { + } else if let Some((grad, stops)) = parse_linear_gradient(val, style.color, dark) { style.background = Some(Fill::Color(grad)); style.background_hsla = None; + style.gradient = stops.map(Rc::new); } else if let Some(c) = parse_color_for_mode(val, dark) { let resolved = c.resolve(style.color); style.background_hsla = Some(resolved); @@ -1932,6 +2192,13 @@ pub(crate) fn parse_px_f32(raw: &str, em: f32) -> Option { Some(bounded_px(value * unit)) } +fn definite(length: Length) -> Option { + match length { + Length::Definite(length) => Some(length), + Length::Auto => None, + } +} + fn definite_to_px(len: Option, em: f32) -> Option { match len? { DefiniteLength::Absolute(AbsoluteLength::Pixels(p)) => Some(f32::from(p)), @@ -2237,7 +2504,14 @@ fn parse_grid_line_range(val: &str, clamped: &mut bool) -> Option Option { +/// A `linear-gradient()` as GPUI draws one, from its first stop to its +/// last, and its stops where it has more than those two and runs along an +/// axis of its box, which is then drawn stop by stop. +fn parse_linear_gradient( + val: &str, + current: Hsla, + dark: bool, +) -> Option<(Background, Option)> { let lower = val.to_ascii_lowercase(); let open = lower.find("linear-gradient(")?; let rest = &val[open + "linear-gradient(".len()..]; @@ -2269,22 +2543,112 @@ fn parse_linear_gradient(val: &str, current: Hsla, dark: bool) -> Option)> = parts[start_idx..] + let mut stops: Vec<(Hsla, Option)> = parts[start_idx..] .iter() + .take(MAX_GRADIENT_STOPS) .filter_map(|part| parse_gradient_stop(part, current, dark)) .collect(); if stops.len() < 2 { return None; } - let first = stops.first()?; - let last = stops.last()?; - Some(linear_gradient( + // `transparent` fades the colour beside it out; it is not black. + for index in 0..stops.len() { + if stops[index].0.a <= 0.0 { + let beside = [index.checked_sub(1), Some(index + 1)] + .into_iter() + .flatten() + .filter_map(|other| stops.get(other)) + .find(|other| other.0.a > 0.0) + .map(|other| other.0); + if let Some(beside) = beside { + stops[index].0 = beside.alpha(0.0); + } + } + } + let first = stops[0]; + let last = stops[stops.len() - 1]; + let background = linear_gradient( angle, linear_color_stop(first.0, first.1.unwrap_or(0.0)), linear_color_stop(last.0, last.1.unwrap_or(1.0)), + ); + let quarter = (angle / 90.0).round(); + if stops.len() == 2 || (angle - quarter * 90.0).abs() > 0.5 { + return Some((background, None)); + } + // A stop with no place stands evenly between those placed around it, + // and no stop stands before the one it follows. + let count = stops.len(); + stops[0].1.get_or_insert(0.0); + stops[count - 1].1.get_or_insert(1.0); + let mut placed: Vec<(Hsla, f32)> = Vec::with_capacity(count); + let mut index = 0; + while index < count { + let Some(at) = stops[index].1 else { + let before = placed.last().map_or(0.0, |stop| stop.1); + let next = (index..count) + .find(|&later| stops[later].1.is_some()) + .unwrap_or(count - 1); + let after = stops[next].1.unwrap_or(1.0).max(before); + let steps = (next - index + 1) as f32; + for (step, stop) in stops[index..next].iter().enumerate() { + placed.push(( + stop.0, + before + (after - before) * (step + 1) as f32 / steps, + )); + } + index = next; + continue; + }; + placed.push(( + stops[index].0, + at.max(placed.last().map_or(0.0, |stop| stop.1)), + )); + index += 1; + } + let quarter = quarter.rem_euclid(4.0) as u8; + if matches!(quarter, 0 | 3) { + // Up, or to the left: the same stops from the other end. + placed.reverse(); + for stop in &mut placed { + stop.1 = 1.0 - stop.1; + } + } + Some(( + background, + Some(StopGradient { + horizontal: matches!(quarter, 1 | 3), + stops: placed, + }), )) } +/// `transform` as far as it moves a box by a length in pixels. +fn parse_translate(val: &str, em: f32) -> (f32, f32) { + let lower = val.to_ascii_lowercase(); + let mut moved = (0.0f32, 0.0f32); + let mut rest = lower.as_str(); + while let Some(open) = rest.find('(') { + let name = rest[..open].trim(); + let Some(close) = rest[open..].find(')') else { + break; + }; + let args: Vec = rest[open + 1..open + close] + .split(',') + .map(|arg| parse_px_f32(arg.trim(), em).unwrap_or(0.0)) + .collect(); + let arg = |index: usize| bounded_px(args.get(index).copied().unwrap_or(0.0)); + match name { + "translate" => moved = (moved.0 + arg(0), moved.1 + arg(1)), + "translatex" => moved.0 += arg(0), + "translatey" => moved.1 += arg(0), + _ => {} + } + rest = &rest[open + close + 1..]; + } + moved +} + fn parse_gradient_direction(raw: &str) -> Option { let s = raw.trim().to_ascii_lowercase(); if let Some(deg) = s.strip_suffix("deg") { diff --git a/crates/ui/src/html/svg.rs b/crates/ui/src/html/svg.rs index 93473304b..74bbfd537 100644 --- a/crates/ui/src/html/svg.rs +++ b/crates/ui/src/html/svg.rs @@ -16,7 +16,7 @@ use base64::Engine as _; use gpui::{Context, Hsla, Pixels, RenderImage, SharedString, Size, SvgRenderer, Task, px, size}; use super::HtmlState; -use super::color::hsla_to_css; +use super::color::{hsla_to_css, parse_color_for_mode}; use super::css::{Vars, number, resolve_vars_in_text}; use super::raster::{self, Picture, Recent}; @@ -184,29 +184,91 @@ impl PreparedSvg { } } -/// The page's stylesheets as an inline `` of an element with `vars` and -/// `current_color` takes them, after a rule giving its text the page's font. -/// A sheet that would not fit, or would end the section it is put in, is -/// left out. -pub(crate) fn page_css( - stylesheets: &[String], - current_color: Hsla, - vars: &Vars, - font_family: &str, -) -> String { - let color = hsla_to_css(current_color); - let families = (!font_family.is_empty()) - .then_some(font_family) - .into_iter() - .chain(crate::i18n::cjk_fallback_families().iter().copied()) - .map(|family| format!("\"{family}\", ")) - .collect::(); - let mut css = format!("text, tspan {{ font-family: {families}sans-serif; fill: {color}; }}"); +/// What of the page around it an inline `` is drawn with. +pub(crate) struct SvgPage<'a> { + /// The text colour of the element, which `currentColor` is. + pub(crate) color: Hsla, + pub(crate) vars: &'a Vars, + pub(crate) dark: bool, + pub(crate) font_sans: &'a str, + pub(crate) font_mono: &'a str, +} + +impl SvgPage<'_> { + /// The families `usvg` sets the page's text in: the theme's font names + /// a face of the system's that `usvg` finds by its fallbacks only. + fn sans(&self) -> String { + (!self.font_sans.is_empty()) + .then_some(self.font_sans) + .into_iter() + .chain(crate::i18n::cjk_fallback_families().iter().copied()) + .map(|family| format!("'{family}', ")) + .collect::() + + "sans-serif" + } + + /// `text` as `usvg` reads it: the custom properties and `currentColor` + /// by their values, the theme's fonts as families it can look up, and a + /// colour only CSS writes as one SVG writes. `None` past `limit`. + fn resolve(&self, text: &str, limit: usize) -> Option { + let mono = format!("'{}', monospace", self.font_mono); + let text = replace_ascii_case_insensitive(text, "var(--font-sans)", &self.sans()); + let text = replace_ascii_case_insensitive(&text, "var(--font-mono)", &mono); + let text = resolve_vars_in_text(&text, self.vars, limit)?; + let color = hsla_to_css(self.color); + let text = replace_ascii_case_insensitive(&text, "currentcolor", &color); + Some(self.with_plain_colors(&text)) + } + + /// `color-mix()` and `light-dark()`, which `usvg` reads as no colour and + /// paints black, as the colours they come to. + fn with_plain_colors(&self, text: &str) -> String { + let bytes = text.as_bytes(); + let mut out = String::with_capacity(text.len()); + let mut copied = 0; + let mut at = 0; + while at < bytes.len() { + let function = [&b"color-mix("[..], b"light-dark("] + .into_iter() + .filter_map(|name| { + find_ascii_case_insensitive(&bytes[at..], name).map(|found| at + found) + }) + .min(); + let Some(start) = function else { + break; + }; + let mut depth = 0usize; + let end = bytes[start..].iter().position(|&b| { + match b { + b'(' => depth += 1, + b')' => depth -= 1, + _ => {} + } + b == b')' && depth == 0 + }); + let Some(end) = end.map(|end| start + end + 1) else { + break; + }; + at = end; + if let Some(color) = parse_color_for_mode(&text[start..end], self.dark) { + out.push_str(&text[copied..start]); + out.push_str(&hsla_to_css(color.resolve(self.color))); + copied = end; + } + } + out.push_str(&text[copied..]); + out + } +} + +/// The page's stylesheets as an inline `` of `page` takes them. A sheet +/// that would not fit, or would end the section it is put in, is left out. +pub(crate) fn page_css(stylesheets: &[String], page: &SvgPage<'_>) -> String { + let mut css = String::new(); for sheet in stylesheets { - let Some(resolved) = resolve_vars_in_text(sheet, vars, MAX_SVG_BYTES - css.len()) else { + let Some(resolved) = page.resolve(sheet, MAX_SVG_BYTES - css.len()) else { continue; }; - let resolved = replace_ascii_case_insensitive(&resolved, "currentcolor", &color); if !resolved.contains("]]>") && css.len() + resolved.len() < MAX_SVG_BYTES { css.push('\n'); css.push_str(&resolved); @@ -215,25 +277,173 @@ pub(crate) fn page_css( css } +/// Whether an `` is written to take no room: a sheet of ``s +/// other ``s draw from. +pub(crate) fn draws_nothing(raw_svg: &str) -> bool { + let open = open_tag_end(raw_svg).map_or(raw_svg, |gt| &raw_svg[..gt]); + let zero = |name: &str| { + read_svg_attr(open, name).is_some_and(|value| { + let value = value.trim(); + number(value.strip_suffix("px").unwrap_or(value)) == Some(0.0) + }) + }; + zero("width") || zero("height") +} + +/// The ``s of an `` that have a name, each with its text. +pub(crate) fn symbols_of(raw_svg: &str) -> Vec<(String, String)> { + let bytes = raw_svg.as_bytes(); + let mut symbols = Vec::new(); + let mut at = 0; + while let Some(found) = find_ascii_case_insensitive(&bytes[at..], b"") else { + break; + }; + let end = start + close + "".len(); + if let Some(id) = read_svg_attr(&raw_svg[start..start + open], "id") { + symbols.push((id.to_owned(), raw_svg[start..end].to_owned())); + } + at = end; + } + symbols +} + +/// An `` that draws a `` of another `` of the page, with +/// that symbol in it: `usvg` draws one `` and knows no other. +pub(crate) fn with_symbols<'a>(raw_svg: &'a str, symbols: &[(String, String)]) -> Cow<'a, str> { + if symbols.is_empty() || !raw_svg.contains("href") { + return Cow::Borrowed(raw_svg); + } + let wanted: String = symbols + .iter() + .filter(|(id, _)| { + [format!("\"#{id}\""), format!("'#{id}'")] + .iter() + .any(|reference| raw_svg.contains(reference.as_str())) + && ![format!("id=\"{id}\""), format!("id='{id}'")] + .iter() + .any(|own| raw_svg.contains(own.as_str())) + }) + .map(|(_, symbol)| symbol.as_str()) + .collect(); + match open_tag_end(raw_svg) { + Some(gt) if !wanted.is_empty() && raw_svg.as_bytes()[gt - 1] != b'/' => { + Cow::Owned(format!( + "{}{wanted}{}", + &raw_svg[..=gt], + &raw_svg[gt + 1..] + )) + } + _ => Cow::Borrowed(raw_svg), + } +} + +/// An `` that names no size and no view box, with the size the +/// page's styles give it: what it draws is then drawn to that size, as a +/// browser draws it, and not to the size of an `` that has none. +pub(crate) fn with_css_size<'a>( + raw_svg: &'a str, + width: Option, + height: Option, +) -> Cow<'a, str> { + let (Some(width), Some(height)) = (width, height) else { + return Cow::Borrowed(raw_svg); + }; + let Some(gt) = open_tag_end(raw_svg) else { + return Cow::Borrowed(raw_svg); + }; + let open = &raw_svg[..gt]; + let named = ["width", "height", "viewBox"] + .iter() + .any(|name| read_svg_attr(open, name).is_some()); + if named || width < 1.0 || height < 1.0 { + return Cow::Borrowed(raw_svg); + } + let at = if open.ends_with('/') { gt - 1 } else { gt }; + Cow::Owned(format!( + r#"{} width="{width}" height="{height}"{}"#, + &raw_svg[..at], + &raw_svg[at..] + )) +} + +/// `xml` with `fill` on each `` that neither has one nor is inside an +/// element that has: text is the page's text colour where a browser would +/// paint it black, which a dark theme could not show. An attribute, so that +/// whatever the page says of the text's paint is said over it. +fn with_text_fill(xml: &str, color: &str) -> String { + let bytes = xml.as_bytes(); + let mut out = String::with_capacity(xml.len() + 64); + let mut copied = 0; + // For each element open here, whether it or one around it has a fill. + let mut filled: Vec = Vec::new(); + let mut at = 0; + while let Some(found) = bytes[at..].iter().position(|&b| b == b'<') { + let start = at + found; + let rest = &xml[start..]; + if rest.starts_with("").map_or(bytes.len(), |end| start + end + 3); + continue; + } + if rest.starts_with("") { + at = rest.find("").map_or(bytes.len(), |end| start + end + 3); + continue; + } + let Some(gt) = open_tag_end(rest) else { + break; + }; + let tag = &rest[..gt]; + at = start + gt + 1; + if tag.starts_with("` for `usvg`/`resvg`: /// - resolves `var(--...)` custom properties /// - replaces `currentColor` with the element's resolved foreground color /// - takes out references to anything outside the text itself /// - ensures `xmlns="http://www.w3.org/2000/svg"` is present /// - puts `css`, the [`page_css`], inside it so classes inside SVG work +/// - puts `paint`, what the page's rules give the `` itself, on it /// - determines natural dimensions from `width`/`height`/`viewBox` /// /// `None` when the result would be longer than [`MAX_SVG_BYTES`]. pub(crate) fn prepare_svg( raw_svg: &str, - current_color: Hsla, - vars: &Vars, + page: &SvgPage<'_>, css: &str, + paint: Option<&str>, ) -> Option { - let xml = resolve_vars_in_text(raw_svg, vars, MAX_SVG_BYTES)?; - let cur_css = hsla_to_css(current_color); - let xml = replace_ascii_case_insensitive(&xml, "currentcolor", &cur_css); - let mut xml = without_external_references(&xml); + let xml = page.resolve(raw_svg, MAX_SVG_BYTES)?; + let cur_css = hsla_to_css(page.color); + let xml = without_external_references(&xml); + let mut xml = with_text_fill(&xml, &cur_css); let natural = extract_svg_dimensions(&xml); @@ -248,6 +458,15 @@ pub(crate) fn prepare_svg( if !open_tag.to_ascii_lowercase().contains("color=") { additions.push_str(&format!(r#" color="{cur_css}""#)); } + if read_svg_attr(open_tag, "font-family").is_none() { + additions.push_str(&format!(r#" font-family="{}""#, page.sans())); + } + let own_style = read_svg_attr(open_tag, "style").map(str::to_owned); + if let Some(paint) = paint + && own_style.is_none() + { + additions.push_str(&format!(r#" style="{paint}""#)); + } let width_is_pct = read_svg_attr(open_tag, "width").is_some_and(|w| w.trim().ends_with('%')); let height_is_pct = @@ -610,6 +829,31 @@ mod tests { image.as_bytes(0).unwrap().to_vec() } + #[gpui::test] + fn an_svg_draws_a_symbol_of_another(cx: &mut TestAppContext) { + // A sheet of symbols that takes no room, and an icon drawn from it + // at the size the page's styles give it: one picture, the icon's. + let html = r##" + + "##; + let drawn = pixels(html, cx); + assert!(drawn.chunks(4).all(|pixel| pixel[3] == 255), "{drawn:?}"); + } + + #[gpui::test] + fn an_svg_is_painted_in_a_colour_css_mixes(cx: &mut TestAppContext) { + let html = r##""##; + let drawn = pixels(html, cx); + // Half of white over nothing, and not the black an unread paint is. + assert!( + drawn + .chunks(4) + .all(|pixel| pixel[3] > 100 && pixel[3] < 155 && pixel[0] > 100), + "{drawn:?}" + ); + } + #[gpui::test] fn an_svg_draws_no_file_it_names(cx: &mut TestAppContext) { let mut png = std::io::Cursor::new(Vec::new()); diff --git a/crates/ui/src/html/text.rs b/crates/ui/src/html/text.rs index d99f8ac13..21c64bc64 100644 --- a/crates/ui/src/html/text.rs +++ b/crates/ui/src/html/text.rs @@ -26,8 +26,6 @@ use crate::markdown::selection::{ enum Lead { #[default] Nothing, - /// White space the page had between the two boxes. - Space, /// A `
`. Break, } @@ -85,7 +83,6 @@ impl EntryText for PageText { text.push_str(if same(before.flow, segment.flow) { match segment.lead { Lead::Nothing => "", - Lead::Space => " ", Lead::Break => "\n", } } else if same(before.row, segment.row) && before.cell != segment.cell { @@ -206,13 +203,6 @@ impl TextSink { (outer.row, outer.cell, outer.flow, outer.link); } - /// The page had white space between the box before and the next. - pub(super) fn space(&mut self) { - if self.lead == Lead::Nothing { - self.lead = Lead::Space; - } - } - /// The page breaks the line between the box before and the next. pub(super) fn line_break(&mut self) { self.lead = Lead::Break;