use std::{
hash::{Hash, Hasher},
iter, mem,
ops::Range,
sync::Arc,
};
use crate::{
AbsoluteLength, App, Background, BackgroundTag, BorderStyle, Bounds, ContentMask, Corners,
CornersRefinement, CursorStyle, DefiniteLength, DevicePixels, Edges, EdgesRefinement,
EffectCrossFade, EffectSpec, Font,
FontFallbacks, FontFeatures, FontStyle, FontWeight, GridLocation, Hsla, Length, Pixels, Point,
PointRefinement, Rgba, SharedString, Size, SizeRefinement, Styled, TextRun, Window, black, phi,
TransformSpec, TransformationMatrix, VnClipOutline, VnFillRule, VnPathVerb, point, px, quad,
rems, size,
};
use collections::HashSet;
use refineable::Refineable;
#[cfg(feature = "schemars")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[cfg(debug_assertions)]
pub struct DebugBelow;
#[cfg(debug_assertions)]
impl crate::Global for DebugBelow {}
pub enum ObjectFit {
Fill,
Contain,
Cover,
ScaleDown,
None,
}
impl ObjectFit {
pub fn get_bounds(
&self,
bounds: Bounds<Pixels>,
image_size: Size<DevicePixels>,
) -> Bounds<Pixels> {
let fitted = self.get_bounds_at(bounds, image_size, ObjectPosition::default());
match self {
ObjectFit::None => Bounds {
origin: bounds.origin,
size: fitted.size,
},
_ => fitted,
}
}
pub fn get_bounds_at(
&self,
bounds: Bounds<Pixels>,
image_size: Size<DevicePixels>,
position: ObjectPosition,
) -> Bounds<Pixels> {
let image_size = image_size.map(|dimension| Pixels::from(u32::from(dimension)));
let image_ratio = image_size.width / image_size.height;
let bounds_ratio = bounds.size.width / bounds.size.height;
let contain = || {
if bounds_ratio > image_ratio {
size(
image_size.width * (bounds.size.height / image_size.height),
bounds.size.height,
)
} else {
size(
bounds.size.width,
image_size.height * (bounds.size.width / image_size.width),
)
}
};
let new_size = match self {
ObjectFit::Fill => bounds.size,
ObjectFit::Contain => contain(),
ObjectFit::ScaleDown => {
if image_size.width > bounds.size.width || image_size.height > bounds.size.height {
contain()
} else {
image_size
}
}
ObjectFit::Cover => {
if bounds_ratio > image_ratio {
size(
bounds.size.width,
image_size.height * (bounds.size.width / image_size.width),
)
} else {
size(
image_size.width * (bounds.size.height / image_size.height),
bounds.size.height,
)
}
}
ObjectFit::None => image_size,
};
Bounds {
origin: point(
bounds.origin.x
+ (bounds.size.width - new_size.width) * position.x_fraction
+ position.x_offset,
bounds.origin.y
+ (bounds.size.height - new_size.height) * position.y_fraction
+ position.y_offset,
),
size: new_size,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct ObjectPosition {
pub x_fraction: f32,
pub x_offset: Pixels,
pub y_fraction: f32,
pub y_offset: Pixels,
}
impl Default for ObjectPosition {
fn default() -> Self {
Self {
x_fraction: 0.5,
x_offset: Pixels::ZERO,
y_fraction: 0.5,
y_offset: Pixels::ZERO,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum GridTemplateMinSize {
#[default]
Zero,
MinContent,
MaxContent,
}
#[derive(
Copy, Clone, Refineable, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Serialize, Deserialize,
)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct GridTemplate {
pub repeat: u16,
pub min_size: GridTemplateMinSize,
}
#[derive(Copy, Clone, PartialEq, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum GridTrackSize {
#[default]
Auto,
MinContent,
MaxContent,
Px(f32),
Percent(f32),
Fr(f32),
}
#[derive(Copy, Clone, PartialEq, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct GridTrack {
pub min: GridTrackSize,
pub max: GridTrackSize,
}
impl GridTrack {
pub fn fixed(size: GridTrackSize) -> Self {
Self {
min: size,
max: size,
}
}
pub fn fr(flex: f32) -> Self {
Self {
min: GridTrackSize::Auto,
max: GridTrackSize::Fr(flex),
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct GridAutoRepeat {
pub fit: bool,
pub start: u16,
pub len: u16,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum GridAutoFlow {
#[default]
Row,
Column,
RowDense,
ColumnDense,
}
#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct Outline {
pub width: Pixels,
pub offset: Pixels,
pub color: Hsla,
pub style: BorderStyle,
}
#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct VnCornerRadius {
pub x: DefiniteLength,
pub y: DefiniteLength,
}
static VN_ELLIPSE_DRAWN_AS_CIRCLE: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
pub fn vn_take_ellipse_drawn_as_circle() -> bool {
VN_ELLIPSE_DRAWN_AS_CIRCLE.swap(false, std::sync::atomic::Ordering::Relaxed)
}
pub fn vn_resolve_corner_radii(
lengths: &Corners<AbsoluteLength>,
relative: &Corners<Option<VnCornerRadius>>,
size: Size<Pixels>,
rem_size: Pixels,
) -> Corners<Pixels> {
let (width, height) = (f32::from(size.width).max(0.), f32::from(size.height).max(0.));
let pair = |length: &AbsoluteLength, relative: &Option<VnCornerRadius>| -> (f32, f32) {
match relative {
Some(radius) => (
f32::from(radius.x.to_pixels(px(width).into(), rem_size)).max(0.),
f32::from(radius.y.to_pixels(px(height).into(), rem_size)).max(0.),
),
None => {
let radius = f32::from(length.to_pixels(rem_size)).max(0.);
(radius, radius)
}
}
};
let top_left = pair(&lengths.top_left, &relative.top_left);
let top_right = pair(&lengths.top_right, &relative.top_right);
let bottom_right = pair(&lengths.bottom_right, &relative.bottom_right);
let bottom_left = pair(&lengths.bottom_left, &relative.bottom_left);
let ratio = |side: f32, a: f32, b: f32| if a + b > side { side / (a + b) } else { 1. };
let factor = ratio(width, top_left.0, top_right.0)
.min(ratio(width, bottom_left.0, bottom_right.0))
.min(ratio(height, top_left.1, bottom_left.1))
.min(ratio(height, top_right.1, bottom_right.1));
let circle = |(x, y): (f32, f32)| {
let (x, y) = (x * factor, y * factor);
let radius = x.min(y);
if radius > 0. && (x - y).abs() > 0.5 {
VN_ELLIPSE_DRAWN_AS_CIRCLE.store(true, std::sync::atomic::Ordering::Relaxed);
}
px(radius)
};
Corners {
top_left: circle(top_left),
top_right: circle(top_right),
bottom_right: circle(bottom_right),
bottom_left: circle(bottom_left),
}
.clamp_radii_for_quad_size(size)
}
#[derive(Copy, Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum VnClipBox {
Margin,
#[default]
Border,
Padding,
Content,
}
#[derive(Copy, Clone, PartialEq, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum VnShapeRadius {
Length(DefiniteLength),
ClosestSide,
FarthestSide,
}
#[derive(Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum VnClipPath {
#[default]
None,
Box(VnClipBox),
Inset {
reference: VnClipBox,
insets: [DefiniteLength; 4],
radii: [VnCornerRadius; 4],
},
Ellipse {
reference: VnClipBox,
center: [DefiniteLength; 2],
radius: [VnShapeRadius; 2],
circle: bool,
},
Polygon {
reference: VnClipBox,
fill_rule: VnFillRule,
points: Arc<[[DefiniteLength; 2]]>,
},
Path {
reference: VnClipBox,
fill_rule: VnFillRule,
verbs: Arc<[VnPathVerb]>,
},
}
fn vn_clip_ellipse(
rect: Bounds<Pixels>,
center: &[DefiniteLength; 2],
radius: &[VnShapeRadius; 2],
circle: bool,
rem_size: Pixels,
) -> (Point<Pixels>, Pixels, Pixels) {
let (w, h) = (rect.size.width, rect.size.height);
let resolve = |length: &DefiniteLength, base: Pixels| length.to_pixels(AbsoluteLength::Pixels(base), rem_size);
let cx = rect.left() + resolve(¢er[0], w);
let cy = rect.top() + resolve(¢er[1], h);
let (near_x, far_x) = ((cx - rect.left()).abs(), (rect.right() - cx).abs());
let (near_y, far_y) = ((cy - rect.top()).abs(), (rect.bottom() - cy).abs());
let diagonal = px((f32::from(w).powi(2) + f32::from(h).powi(2)).sqrt() / 2f32.sqrt());
let one = |r: &VnShapeRadius, horizontal: bool| -> Pixels {
let (a, b) = if circle {
(near_x.min(far_x).min(near_y.min(far_y)), near_x.max(far_x).max(near_y.max(far_y)))
} else if horizontal {
(near_x.min(far_x), near_x.max(far_x))
} else {
(near_y.min(far_y), near_y.max(far_y))
};
match r {
VnShapeRadius::ClosestSide => a,
VnShapeRadius::FarthestSide => b,
VnShapeRadius::Length(l) => resolve(l, if circle { diagonal } else if horizontal { w } else { h }).max(px(0.)),
}
};
(point(cx, cy), one(&radius[0], true), one(&radius[1], false))
}
#[derive(Clone, Refineable, Debug)]
#[refineable(Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", refineable(JsonSchema))]
pub struct Style {
pub display: Display,
pub visibility: Visibility,
#[refineable]
pub overflow: Point<Overflow>,
pub scrollbar_width: AbsoluteLength,
pub allow_concurrent_scroll: bool,
pub restrict_scroll_to_axis: bool,
pub position: Position,
#[refineable]
pub inset: Edges<Length>,
#[refineable]
pub size: Size<Length>,
#[refineable]
pub min_size: Size<Length>,
#[refineable]
pub max_size: Size<Length>,
pub aspect_ratio: Option<f32>,
#[refineable]
pub margin: Edges<Length>,
#[refineable]
pub padding: Edges<DefiniteLength>,
#[refineable]
pub border_widths: Edges<AbsoluteLength>,
pub align_items: Option<AlignItems>,
pub align_self: Option<AlignSelf>,
pub align_content: Option<AlignContent>,
pub justify_content: Option<JustifyContent>,
#[refineable]
pub gap: Size<DefiniteLength>,
pub flex_direction: FlexDirection,
pub flex_wrap: FlexWrap,
pub flex_basis: Length,
pub flex_grow: f32,
pub flex_shrink: f32,
pub vn_order: i32,
pub vn_object_position: Option<ObjectPosition>,
pub background: Option<Fill>,
pub background_layers: Vec<Background>,
pub border_color: Option<Hsla>,
#[refineable]
pub vn_border_colors: Edges<Option<Hsla>>,
pub border_style: BorderStyle,
#[refineable]
pub corner_radii: Corners<AbsoluteLength>,
#[refineable]
pub vn_corner_radii: Corners<Option<VnCornerRadius>>,
pub box_shadow: Vec<BoxShadow>,
pub vn_shadow_under_box: bool,
pub backdrop_blur: Option<Pixels>,
pub vn_effect: Option<EffectSpec>,
pub vn_effect_fade: Option<EffectCrossFade>,
pub vn_transform: Option<TransformSpec>,
#[refineable]
pub text: TextStyleRefinement,
pub mouse_cursor: Option<CursorStyle>,
pub opacity: Option<f32>,
pub grid_cols: Option<GridTemplate>,
pub grid_rows: Option<GridTemplate>,
pub grid_location: Option<GridLocation>,
pub vn_grid_cols: Option<Vec<GridTrack>>,
pub vn_grid_rows: Option<Vec<GridTrack>>,
pub vn_grid_cols_auto: Option<GridAutoRepeat>,
pub vn_grid_rows_auto: Option<GridAutoRepeat>,
pub vn_grid_auto_cols: Option<Vec<GridTrack>>,
pub vn_grid_auto_rows: Option<Vec<GridTrack>>,
pub vn_grid_auto_flow: Option<GridAutoFlow>,
pub vn_justify_items: Option<AlignItems>,
pub vn_justify_self: Option<AlignSelf>,
pub vn_outline: Option<Outline>,
pub vn_mask_ring: bool,
pub vn_clip_path: VnClipPath,
pub vn_color_matrix: Option<crate::VnColorMatrix>,
pub vn_capture: Option<u64>,
pub vn_isolate: bool,
pub vn_text_fill: Option<VnTextFill>,
pub vn_mask: Option<VnMask>,
#[cfg(debug_assertions)]
pub debug: bool,
#[cfg(debug_assertions)]
pub debug_below: bool,
}
impl Styled for StyleRefinement {
fn style(&mut self) -> &mut StyleRefinement {
self
}
}
impl StyleRefinement {
pub fn grid_location_mut(&mut self) -> &mut GridLocation {
self.grid_location.get_or_insert_default()
}
}
#[derive(Default, Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum Visibility {
#[default]
Visible,
Hidden,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct BoxShadow {
pub color: Hsla,
pub offset: Point<Pixels>,
pub blur_radius: Pixels,
pub spread_radius: Pixels,
pub inset: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct TextShadow {
pub color: Option<Hsla>,
pub offset: Point<Pixels>,
pub blur_radius: Pixels,
}
impl BoxShadow {
pub fn new(offset_x: Pixels, offset_y: Pixels, color: Hsla) -> Self {
Self {
color,
offset: point(offset_x, offset_y),
blur_radius: px(0.),
spread_radius: px(0.),
inset: false,
}
}
pub fn blur_radius(mut self, blur_radius: Pixels) -> Self {
self.blur_radius = blur_radius;
self
}
pub fn spread_radius(mut self, spread_radius: Pixels) -> Self {
self.spread_radius = spread_radius;
self
}
pub fn inset(mut self) -> Self {
self.inset = true;
self
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum WhiteSpace {
#[default]
Normal,
Nowrap,
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum OverflowWrap {
#[default]
Normal,
BreakWord,
Anywhere,
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum WordBreak {
#[default]
Normal,
BreakAll,
KeepAll,
BreakWord,
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum Hyphens {
None,
#[default]
Manual,
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct TextWrap {
pub overflow_wrap: OverflowWrap,
pub word_break: WordBreak,
pub hyphens: Hyphens,
}
impl TextWrap {
pub const BREAK_WORD: Self = Self {
overflow_wrap: OverflowWrap::BreakWord,
word_break: WordBreak::Normal,
hyphens: Hyphens::Manual,
};
pub(crate) fn breaks_words(&self) -> bool {
self.overflow_wrap != OverflowWrap::Normal || self.word_break == WordBreak::BreakWord
}
pub(crate) fn min_content_breaks_words(&self) -> bool {
self.overflow_wrap == OverflowWrap::Anywhere || self.word_break == WordBreak::BreakWord
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum TextOverflow {
Truncate(SharedString),
TruncateStart(SharedString),
TruncateMiddle(SharedString),
}
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum TextAlign {
#[default]
Left,
Center,
Right,
}
pub type VnMaskPainter = std::rc::Rc<dyn Fn(Bounds<Pixels>, Option<Hsla>, &mut Window, &mut App)>;
#[derive(Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct VnMask {
pub luminance: bool,
pub tint_leaf: bool,
pub key: u64,
#[serde(skip)]
#[cfg_attr(feature = "schemars", schemars(skip))]
pub paint: Option<VnMaskPainter>,
}
impl std::fmt::Debug for VnMask {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VnMask")
.field("luminance", &self.luminance)
.field("tint_leaf", &self.tint_leaf)
.field("key", &self.key)
.finish_non_exhaustive()
}
}
impl PartialEq for VnMask {
fn eq(&self, other: &Self) -> bool {
(self.luminance, self.tint_leaf, self.key) == (other.luminance, other.tint_leaf, other.key)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct VnTextFill {
pub group_id: u64,
pub backgrounds: Vec<Background>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct VnTextPaint {
pub fill: VnTextFill,
pub bounds: [f32; 4],
pub inverse: [f32; 6],
pub scale_factor: f32,
#[serde(skip)]
#[cfg_attr(feature = "schemars", schemars(skip))]
pub geometry: Arc<crate::VnClipGeometry>,
#[serde(skip)]
#[cfg_attr(feature = "schemars", schemars(skip))]
pub content_mask: ContentMask<crate::ScaledPixels>,
}
#[derive(Refineable, Clone, Debug, PartialEq)]
#[refineable(Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", refineable(JsonSchema))]
pub struct TextStyle {
pub color: Hsla,
pub vn_text_paint: Option<Arc<VnTextPaint>>,
pub font_family: SharedString,
pub font_features: FontFeatures,
pub font_fallbacks: Option<FontFallbacks>,
pub font_size: AbsoluteLength,
pub line_height: DefiniteLength,
pub font_weight: FontWeight,
pub font_style: FontStyle,
pub background_color: Option<Hsla>,
pub underline: Option<UnderlineStyle>,
pub strikethrough: Option<StrikethroughStyle>,
pub white_space: WhiteSpace,
pub text_overflow: Option<TextOverflow>,
pub text_align: TextAlign,
pub line_clamp: Option<usize>,
pub letter_spacing: Pixels,
pub word_spacing: Pixels,
pub overflow_wrap: OverflowWrap,
pub word_break: WordBreak,
pub hyphens: Hyphens,
pub text_shadow: Vec<TextShadow>,
}
impl Default for TextStyle {
fn default() -> Self {
TextStyle {
color: black(),
vn_text_paint: None,
font_family: ".SystemUIFont".into(),
font_features: FontFeatures::default(),
font_fallbacks: None,
font_size: rems(1.).into(),
line_height: phi(),
font_weight: FontWeight::default(),
font_style: FontStyle::default(),
background_color: None,
underline: None,
strikethrough: None,
white_space: WhiteSpace::Normal,
text_overflow: None,
text_align: TextAlign::default(),
line_clamp: None,
letter_spacing: px(0.),
word_spacing: px(0.),
overflow_wrap: OverflowWrap::default(),
word_break: WordBreak::default(),
hyphens: Hyphens::default(),
text_shadow: Vec::new(),
}
}
}
impl TextStyle {
pub fn wrap(&self) -> TextWrap {
TextWrap {
overflow_wrap: self.overflow_wrap,
word_break: self.word_break,
hyphens: self.hyphens,
}
}
pub fn highlight(mut self, style: impl Into<HighlightStyle>) -> Self {
let style = style.into();
if let Some(weight) = style.font_weight {
self.font_weight = weight;
}
if let Some(style) = style.font_style {
self.font_style = style;
}
if let Some(color) = style.color {
self.color = self.color.blend(color);
}
if let Some(factor) = style.fade_out {
self.color.fade_out(factor);
}
if let Some(background_color) = style.background_color {
self.background_color = Some(background_color);
}
if let Some(underline) = style.underline {
self.underline = Some(underline);
}
if let Some(strikethrough) = style.strikethrough {
self.strikethrough = Some(strikethrough);
}
self
}
pub fn font(&self) -> Font {
Font {
family: self.font_family.clone(),
features: self.font_features.clone(),
fallbacks: self.font_fallbacks.clone(),
weight: self.font_weight,
style: self.font_style,
}
}
pub fn line_height_in_pixels(&self, rem_size: Pixels) -> Pixels {
self.line_height.to_pixels(self.font_size, rem_size).round()
}
pub fn to_run(&self, len: usize) -> TextRun {
TextRun {
len,
font: Font {
family: self.font_family.clone(),
features: self.font_features.clone(),
fallbacks: self.font_fallbacks.clone(),
weight: self.font_weight,
style: self.font_style,
},
color: self.color,
background_color: self.background_color,
underline: self.underline,
strikethrough: self.strikethrough,
tracking: self.letter_spacing,
word_spacing: self.word_spacing,
text_shadow: self.text_shadow.clone(),
}
}
}
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct HighlightStyle {
pub color: Option<Hsla>,
pub font_weight: Option<FontWeight>,
pub font_style: Option<FontStyle>,
pub background_color: Option<Hsla>,
pub underline: Option<UnderlineStyle>,
pub strikethrough: Option<StrikethroughStyle>,
pub fade_out: Option<f32>,
}
impl Eq for HighlightStyle {}
impl Hash for HighlightStyle {
fn hash<H: Hasher>(&self, state: &mut H) {
self.color.hash(state);
self.font_weight.hash(state);
self.font_style.hash(state);
self.background_color.hash(state);
self.underline.hash(state);
self.strikethrough.hash(state);
state.write_u32(u32::from_be_bytes(
self.fade_out.map(|f| f.to_be_bytes()).unwrap_or_default(),
));
}
}
fn representative_color(background: &Background) -> Hsla {
match background.tag {
BackgroundTag::Solid | BackgroundTag::PatternSlash | BackgroundTag::Checkerboard => {
background.solid
}
BackgroundTag::LinearGradient
| BackgroundTag::RadialGradient
| BackgroundTag::ConicGradient => background
.live_stops()
.first()
.map(|stop| stop.color)
.unwrap_or_default(),
}
}
impl Style {
pub fn has_opaque_background(&self) -> bool {
self.background
.as_ref()
.is_some_and(|fill| fill.color().is_some_and(|color| !color.is_transparent()))
}
pub fn text_style(&self) -> Option<&TextStyleRefinement> {
if self.text.is_some() {
Some(&self.text)
} else {
None
}
}
pub fn text_style_for_bounds(&self, bounds: Bounds<Pixels>, window: &Window) -> Option<TextStyleRefinement> {
let mut text = self.text.clone();
if let Some(fill) = &self.vn_text_fill {
text.vn_text_paint = Some(window.vn_text_paint(fill.clone(), bounds));
}
text.is_some().then_some(text)
}
pub fn corner_radii_for(&self, size: Size<Pixels>, rem_size: Pixels) -> Corners<Pixels> {
vn_resolve_corner_radii(&self.corner_radii, &self.vn_corner_radii, size, rem_size)
}
pub fn overflow_mask(
&self,
bounds: Bounds<Pixels>,
rem_size: Pixels,
) -> Option<ContentMask<Pixels>> {
match self.overflow {
Point {
x: Overflow::Visible,
y: Overflow::Visible,
} => None,
_ => {
let mut min = bounds.origin;
let mut max = bounds.bottom_right();
let border_box = bounds;
let painted = self
.vn_resolved_border_colors()
.map(|color| !color.is_transparent());
if painted.left {
min.x += self.border_widths.left.to_pixels(rem_size);
}
if painted.right {
max.x -= self.border_widths.right.to_pixels(rem_size);
}
if painted.top {
min.y += self.border_widths.top.to_pixels(rem_size);
}
if painted.bottom {
max.y -= self.border_widths.bottom.to_pixels(rem_size);
}
let bounds = match (
self.overflow.x == Overflow::Visible,
self.overflow.y == Overflow::Visible,
) {
(true, true) => return None,
(true, false) => Bounds::from_corners(
point(min.x, bounds.origin.y),
point(max.x, bounds.bottom_right().y),
),
(false, true) => Bounds::from_corners(
point(bounds.origin.x, min.y),
point(bounds.bottom_right().x, max.y),
),
(false, false) => Bounds::from_corners(min, max),
};
let insets = Edges {
top: bounds.top() - border_box.top(),
right: border_box.right() - bounds.right(),
bottom: border_box.bottom() - bounds.bottom(),
left: bounds.left() - border_box.left(),
};
let outer = self.corner_radii_for(border_box.size, rem_size);
let inner = |radius: Pixels, a: Pixels, b: Pixels| (radius - a.max(b)).max(px(0.));
let corner_radii = Corners {
top_left: inner(outer.top_left, insets.top, insets.left),
top_right: inner(outer.top_right, insets.top, insets.right),
bottom_right: inner(outer.bottom_right, insets.bottom, insets.right),
bottom_left: inner(outer.bottom_left, insets.bottom, insets.left),
}
.clamp_radii_for_quad_size(bounds.size);
Some(ContentMask {
bounds,
corner_radii,
})
}
}
}
pub fn vn_clip_mask(&self, bounds: Bounds<Pixels>, rem_size: Pixels) -> Option<ContentMask<Pixels>> {
let clip = &self.vn_clip_path;
let reference = match clip {
VnClipPath::None => return None,
VnClipPath::Polygon { .. } | VnClipPath::Path { .. } => {
let outline = self.vn_clip_outline(bounds, rem_size)?;
let rect = outline.control_bounds().unwrap_or(Bounds { origin: bounds.origin, size: Size::default() });
return Some(ContentMask::rect(rect));
}
VnClipPath::Box(reference)
| VnClipPath::Inset { reference, .. }
| VnClipPath::Ellipse { reference, .. } => *reference,
};
let (rect, rounded) = self.vn_clip_box(reference, bounds, rem_size);
let (w, h) = (rect.size.width, rect.size.height);
let resolve = |length: &DefiniteLength, base: Pixels| length.to_pixels(AbsoluteLength::Pixels(base), rem_size);
Some(match clip {
VnClipPath::None | VnClipPath::Polygon { .. } | VnClipPath::Path { .. } => return None,
VnClipPath::Box(_) => ContentMask { bounds: rect, corner_radii: rounded },
VnClipPath::Inset { insets, radii, .. } => {
let [top, right, bottom, left] = insets;
let (top, right) = (resolve(top, h), resolve(right, w));
let (bottom, left) = (resolve(bottom, h), resolve(left, w));
let shape = Bounds {
origin: point(rect.left() + left, rect.top() + top),
size: size((w - left - right).max(px(0.)), (h - top - bottom).max(px(0.))),
};
let pairs = radii.map(|r| {
let x = f32::from(resolve(&r.x, w)).max(0.);
let y = f32::from(resolve(&r.y, h)).max(0.);
(x, y)
});
let [tl, tr, br, bl] = pairs;
let (sw, sh) = (f32::from(shape.size.width), f32::from(shape.size.height));
let ratio = |side: f32, a: f32, b: f32| if a + b > side { side / (a + b) } else { 1. };
let factor = ratio(sw, tl.0, tr.0)
.min(ratio(sw, bl.0, br.0))
.min(ratio(sh, tl.1, bl.1))
.min(ratio(sh, tr.1, br.1));
let circle = |(x, y): (f32, f32)| px(x.min(y) * factor);
let corner_radii = Corners {
top_left: circle(tl),
top_right: circle(tr),
bottom_right: circle(br),
bottom_left: circle(bl),
}
.clamp_radii_for_quad_size(shape.size);
ContentMask { bounds: shape, corner_radii }
}
VnClipPath::Ellipse { center, radius, circle, .. } => {
let (c, rx, ry) = vn_clip_ellipse(rect, center, radius, *circle, rem_size);
let shape = Bounds { origin: point(c.x - rx, c.y - ry), size: size(rx * 2., ry * 2.) };
let corner_radii = if rx == ry { Corners::all(rx) } else { Corners::default() };
ContentMask { bounds: shape, corner_radii }
}
})
}
pub fn vn_clip_outline(&self, bounds: Bounds<Pixels>, rem_size: Pixels) -> Option<VnClipOutline> {
let resolve = |length: &DefiniteLength, base: Pixels| {
f32::from(length.to_pixels(AbsoluteLength::Pixels(base), rem_size))
};
match &self.vn_clip_path {
VnClipPath::Polygon { reference, fill_rule, points } => {
let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
let (x0, y0) = (f32::from(rect.left()), f32::from(rect.top()));
let (w, h) = (rect.size.width, rect.size.height);
let mut verbs = Vec::with_capacity(points.len() + 1);
for (i, [x, y]) in points.iter().enumerate() {
let p = [x0 + resolve(x, w), y0 + resolve(y, h)];
verbs.push(if i == 0 { VnPathVerb::MoveTo(p) } else { VnPathVerb::LineTo(p) });
}
if !verbs.is_empty() {
verbs.push(VnPathVerb::Close);
}
Some(VnClipOutline { fill_rule: *fill_rule, verbs })
}
VnClipPath::Path { reference, fill_rule, verbs } => {
let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
let (x0, y0) = (f32::from(rect.left()), f32::from(rect.top()));
let at = |p: [f32; 2]| [p[0] + x0, p[1] + y0];
let verbs = verbs
.iter()
.map(|v| match *v {
VnPathVerb::MoveTo(p) => VnPathVerb::MoveTo(at(p)),
VnPathVerb::LineTo(p) => VnPathVerb::LineTo(at(p)),
VnPathVerb::QuadTo(c, p) => VnPathVerb::QuadTo(at(c), at(p)),
VnPathVerb::CubicTo(c1, c2, p) => VnPathVerb::CubicTo(at(c1), at(c2), at(p)),
VnPathVerb::Close => VnPathVerb::Close,
})
.collect();
Some(VnClipOutline { fill_rule: *fill_rule, verbs })
}
VnClipPath::Ellipse { reference, center, radius, circle } => {
let (rect, _) = self.vn_clip_box(*reference, bounds, rem_size);
let (c, rx, ry) = vn_clip_ellipse(rect, center, radius, *circle, rem_size);
if rx == ry {
return None;
}
let (cx, cy, rx, ry) = (f32::from(c.x), f32::from(c.y), f32::from(rx), f32::from(ry));
let (kx, ky) = (0.552_284_8 * rx, 0.552_284_8 * ry);
use VnPathVerb::*;
Some(VnClipOutline {
fill_rule: VnFillRule::NonZero,
verbs: vec![
MoveTo([cx + rx, cy]),
CubicTo([cx + rx, cy + ky], [cx + kx, cy + ry], [cx, cy + ry]),
CubicTo([cx - kx, cy + ry], [cx - rx, cy + ky], [cx - rx, cy]),
CubicTo([cx - rx, cy - ky], [cx - kx, cy - ry], [cx, cy - ry]),
CubicTo([cx + kx, cy - ry], [cx + rx, cy - ky], [cx + rx, cy]),
Close,
],
})
}
VnClipPath::None | VnClipPath::Box(_) | VnClipPath::Inset { .. } => None,
}
}
fn vn_clip_box(&self, reference: VnClipBox, bounds: Bounds<Pixels>, rem_size: Pixels) -> (Bounds<Pixels>, Corners<Pixels>) {
let outer = self.corner_radii_for(bounds.size, rem_size);
let width = AbsoluteLength::Pixels(bounds.size.width);
let edges = match reference {
VnClipBox::Border => return (bounds, outer),
VnClipBox::Margin => {
let margin = |l: &Length| match l {
Length::Definite(l) => -l.to_pixels(width, rem_size),
Length::Auto => px(0.),
};
Edges {
top: margin(&self.margin.top),
right: margin(&self.margin.right),
bottom: margin(&self.margin.bottom),
left: margin(&self.margin.left),
}
}
VnClipBox::Padding | VnClipBox::Content => {
let border = self.border_widths.to_pixels(rem_size);
if reference == VnClipBox::Padding {
border
} else {
let padding = self.padding.to_pixels(size(width, width), rem_size);
Edges {
top: border.top + padding.top,
right: border.right + padding.right,
bottom: border.bottom + padding.bottom,
left: border.left + padding.left,
}
}
}
};
let rect = Bounds::from_corners(
point(bounds.left() + edges.left, bounds.top() + edges.top),
point(
(bounds.right() - edges.right).max(bounds.left() + edges.left),
(bounds.bottom() - edges.bottom).max(bounds.top() + edges.top),
),
);
let corner = |radius: Pixels, a: Pixels, b: Pixels| {
if a < px(0.) || b < px(0.) {
if radius > px(0.) { radius - a.min(b) } else { px(0.) }
} else {
(radius - a.max(b)).max(px(0.))
}
};
let corner_radii = Corners {
top_left: corner(outer.top_left, edges.top, edges.left),
top_right: corner(outer.top_right, edges.top, edges.right),
bottom_right: corner(outer.bottom_right, edges.bottom, edges.right),
bottom_left: corner(outer.bottom_left, edges.bottom, edges.left),
}
.clamp_radii_for_quad_size(rect.size);
(rect, corner_radii)
}
pub fn transform_matrix(&self, bounds: Bounds<Pixels>, scale_factor: f32) -> TransformationMatrix
{
self.vn_transform
.filter(|t| !t.is_identity())
.map(|t| t.to_matrix(bounds, scale_factor))
.unwrap_or_else(TransformationMatrix::unit)
}
pub fn paint(
&self,
bounds: Bounds<Pixels>,
window: &mut Window,
cx: &mut App,
continuation: impl FnOnce(&mut Window, &mut App),
) {
let transformation = if self.vn_capture.is_some() {
TransformationMatrix::unit()
} else {
self.transform_matrix(bounds, window.scale_factor())
};
let clip = self.vn_clip_mask(bounds, window.rem_size());
let outline = self.vn_clip_outline(bounds, window.rem_size());
let element = window.vn_take_effect_element();
let paint = |window: &mut Window| {
window.with_content_mask(clip, |window| {
window.vn_with_clip_shape(outline.as_ref(), |window| {
if let Some(tint) = self.vn_mask_tint()
&& let Some(paint) = self.vn_mask.as_ref().and_then(|mask| mask.paint.clone())
{
if !tint.is_transparent() {
window.with_element_opacity(Some(tint.a), |window| {
paint(bounds, Some(Hsla { a: 1., ..tint }), window, cx)
});
}
return continuation(window, cx);
}
window.vn_with_mask(self.vn_mask.as_ref(), bounds, cx, |window, cx| {
window.vn_with_color_matrix(self.vn_color_matrix, |window| {
window.vn_with_isolation(self.vn_isolate, |window| {
self.paint_shaded(bounds, element, window, cx, continuation)
})
})
})
})
})
};
if !transformation.is_unit() {
return window.with_element_transform(transformation, paint);
}
paint(window)
}
fn vn_mask_tint(&self) -> Option<Hsla> {
let mask = self.vn_mask.as_ref()?;
if !mask.tint_leaf
|| mask.luminance
|| self.vn_color_matrix.is_some()
|| !self.background_layers.is_empty()
|| !self.box_shadow.is_empty()
|| self.is_border_visible()
|| self.backdrop_blur.is_some_and(|radius| radius > px(0.))
|| self.vn_effect.is_some()
|| self.vn_effect_fade.is_some()
|| self.vn_mask_ring
|| self.vn_outline.is_some_and(|o| o.width > px(0.) && !o.color.is_transparent())
{
return None;
}
match self.background.as_ref().and_then(Fill::color) {
None => Some(Hsla::transparent_black()),
Some(background) => background.as_solid(),
}
}
fn vn_effects(&self, cx: &App) -> [Option<(EffectSpec, f32)>; 2] {
let reduce_motion = cx.reduce_motion();
let layer = |mut spec: EffectSpec, weight: f32| {
(spec.is_some() && !self.vn_mask_ring && weight > 0.).then(|| {
spec.animated &= !reduce_motion;
if reduce_motion {
spec.clock_mask = 0;
}
(spec, weight)
})
};
let progress = self
.vn_effect_fade
.map_or(1., |fade| fade.progress.clamp(0., 1.));
[
self.vn_effect_fade
.and_then(|fade| layer(fade.from, 1. - progress)),
self.vn_effect.and_then(|spec| layer(spec, progress)),
]
}
fn paint_shaded(
&self,
bounds: Bounds<Pixels>,
element: u64,
window: &mut Window,
cx: &mut App,
continuation: impl FnOnce(&mut Window, &mut App),
) {
let effects = self.vn_effects(cx);
let content = effects
.iter()
.flatten()
.any(|(spec, _)| spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT != 0);
if !content {
return self.paint_untransformed(
bounds,
window,
cx,
continuation,
&effects,
element,
false,
);
}
let corner_radii = self.corner_radii_for(bounds.size, window.rem_size());
self.paint_backdrop(bounds, corner_radii, window, cx, &effects, element);
let shaded: Vec<_> = effects
.iter()
.flatten()
.map(|(spec, weight)| {
let textures = crate::resolve_effect_textures(spec, window, cx);
(*spec, *weight, textures)
})
.collect();
window.vn_with_effect_content(bounds, corner_radii, &shaded, element, cx, |window, cx| {
self.paint_untransformed(bounds, window, cx, continuation, &effects, element, true)
})
}
pub fn vn_reads_content(&self) -> bool {
[self.vn_effect, self.vn_effect_fade.map(|fade| fade.from)]
.into_iter()
.flatten()
.any(|spec| spec.is_some() && spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT != 0)
}
fn paint_backdrop(
&self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
window: &mut Window,
cx: &mut App,
effects: &[Option<(EffectSpec, f32)>; 2],
element: u64,
) {
if let Some(radius) = self.backdrop_blur
&& radius > crate::px(0.)
&& !self.vn_mask_ring
{
window.paint_backdrop_blur_rect(
bounds,
corner_radii,
crate::BackdropBlurEffect::new(radius),
);
}
Self::paint_effects(bounds, corner_radii, window, cx, effects, element, true);
}
fn paint_effects(
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
window: &mut Window,
cx: &mut App,
effects: &[Option<(EffectSpec, f32)>; 2],
element: u64,
backdrop: bool,
) {
for (spec, weight) in effects.iter().flatten() {
if spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT == 0
&& (spec.flags & crate::EFFECT_FLAG_NEEDS_BACKDROP != 0) == backdrop
{
window.with_element_opacity((*weight < 1.).then_some(*weight), |window| {
window.vn_paint_textured_effect(bounds, corner_radii, *spec, element, cx)
});
}
}
}
#[allow(clippy::too_many_arguments)]
fn paint_untransformed(
&self,
bounds: Bounds<Pixels>,
window: &mut Window,
cx: &mut App,
continuation: impl FnOnce(&mut Window, &mut App),
effects: &[Option<(EffectSpec, f32)>; 2],
element: u64,
in_content: bool,
) {
#[cfg(debug_assertions)]
if self.debug_below {
cx.set_global(DebugBelow)
}
#[cfg(debug_assertions)]
if self.debug || cx.has_global::<DebugBelow>() {
window.paint_quad(crate::outline(bounds, crate::red(), BorderStyle::default()));
}
let rem_size = window.rem_size();
let corner_radii = self.corner_radii_for(bounds.size, rem_size);
let ring_widths = self.vn_mask_ring.then(|| {
let border = self.border_widths.to_pixels(rem_size);
let width = AbsoluteLength::Pixels(bounds.size.width);
let padding = self.padding.to_pixels(size(width, width), rem_size);
Edges {
top: border.top + padding.top,
right: border.right + padding.right,
bottom: border.bottom + padding.bottom,
left: border.left + padding.left,
}
});
let ring = ring_widths.is_some();
if !ring {
if self.vn_shadow_under_box {
window.paint_drop_shadows_under_box(bounds, corner_radii, &self.box_shadow);
} else {
window.paint_drop_shadows(bounds, corner_radii, &self.box_shadow);
}
}
if !in_content {
self.paint_backdrop(bounds, corner_radii, window, cx, effects, element);
}
let fill = |background: Background| match ring_widths {
Some(widths) => (background.ring(), widths),
None => (background, Edges::default()),
};
let background_color = self.background.as_ref().and_then(Fill::color);
if background_color.is_some_and(|color| !color.is_transparent()) {
let color = background_color.unwrap_or_default();
let mut border_color = representative_color(&color);
border_color.a = 0.;
let (color, widths) = fill(color);
window.paint_quad(quad(
bounds,
corner_radii,
color,
widths,
border_color,
self.border_style,
));
}
for layer in &self.background_layers {
if layer.is_transparent() {
continue;
}
let mut border_color = representative_color(layer);
border_color.a = 0.;
let (layer, widths) = fill(*layer);
window.paint_quad(quad(
bounds,
corner_radii,
layer,
widths,
border_color,
self.border_style,
));
}
if !ring {
window.paint_inset_shadows(bounds, corner_radii, &self.box_shadow);
}
Self::paint_effects(bounds, corner_radii, window, cx, effects, element, false);
continuation(window, cx);
if self.is_border_visible() {
let border_widths = self.border_widths.to_pixels(rem_size);
let colors = self.vn_resolved_border_colors();
if colors.top == colors.right && colors.top == colors.bottom && colors.top == colors.left {
window.paint_quad(quad(
bounds, corner_radii, Hsla::transparent_black(), border_widths,
colors.top, self.border_style,
));
} else {
let clips = Self::vn_border_side_clips(bounds, border_widths);
for (points, (color, width)) in clips.into_iter().zip([
(colors.top, border_widths.top), (colors.right, border_widths.right),
(colors.bottom, border_widths.bottom), (colors.left, border_widths.left),
]) {
if width <= px(0.) || color.is_transparent() || points.len() < 3 { continue; }
let mut verbs: Vec<_> = points.into_iter().enumerate().map(|(index, point)| {
if index == 0 { VnPathVerb::MoveTo(point) } else { VnPathVerb::LineTo(point) }
}).collect();
verbs.push(VnPathVerb::Close);
let outline = VnClipOutline { fill_rule: VnFillRule::NonZero, verbs };
window.vn_with_clip_shape(Some(&outline), |window| {
window.paint_quad(quad(bounds, corner_radii, Hsla::transparent_black(),
border_widths, color, self.border_style));
});
}
}
}
if let Some(outline) = self
.vn_outline
.filter(|o| o.width > px(0.) && !o.color.is_transparent() && !ring)
{
let grow = outline.offset + outline.width;
let ring = bounds.dilate(grow);
let radii = corner_radii.map(|r| {
if r.0 <= 0.0 {
px(0.)
} else {
px((r.0 + grow.0).max(0.0))
}
});
window.paint_quad(quad(
ring,
radii,
Hsla::transparent_black(),
Edges::all(outline.width),
outline.color,
outline.style,
));
}
#[cfg(debug_assertions)]
if self.debug_below {
cx.remove_global::<DebugBelow>();
}
}
fn vn_resolved_border_colors(&self) -> Edges<Hsla> {
let shared = self.border_color.unwrap_or_default();
self.vn_border_colors.map(|color| color.unwrap_or(shared))
}
fn vn_border_side_clips(bounds: Bounds<Pixels>, widths: Edges<Pixels>) -> [Vec<[f32; 2]>; 4] {
let (left, top, right, bottom) = (f32::from(bounds.left()), f32::from(bounds.top()),
f32::from(bounds.right()), f32::from(bounds.bottom()));
let widths = [widths.top, widths.right, widths.bottom, widths.left].map(|width| f32::from(width).max(0.));
let distances = [[0., 1., -top], [-1., 0., right], [0., -1., bottom], [1., 0., -left]];
std::array::from_fn(|side| {
if widths[side] <= 0. { return Vec::new(); }
let mut polygon = vec![[left, top], [right, top], [right, bottom], [left, bottom]];
for other in 0..4 {
if other == side || widths[other] <= 0. { continue; }
let plane: [f32; 3] = std::array::from_fn(|index|
distances[side][index] * widths[other] - distances[other][index] * widths[side]);
let distance = |point: [f32; 2]| plane[0] * point[0] + plane[1] * point[1] + plane[2];
let Some(mut previous) = polygon.last().copied() else { break };
let mut previous_distance = distance(previous);
let mut clipped = Vec::with_capacity(polygon.len() + 1);
for current in polygon {
let current_distance = distance(current);
if (previous_distance <= 0.) != (current_distance <= 0.) {
let fraction = previous_distance / (previous_distance - current_distance);
clipped.push([previous[0] + fraction * (current[0] - previous[0]),
previous[1] + fraction * (current[1] - previous[1])]);
}
if current_distance <= 0. { clipped.push(current); }
previous = current;
previous_distance = current_distance;
}
polygon = clipped;
}
polygon
})
}
fn is_border_visible(&self) -> bool {
self.vn_resolved_border_colors().any(|color| !color.is_transparent())
&& self.border_widths.any(|length| !length.is_zero())
}
}
impl Default for Style {
fn default() -> Self {
Style {
display: Display::Block,
visibility: Visibility::Visible,
overflow: Point {
x: Overflow::Visible,
y: Overflow::Visible,
},
allow_concurrent_scroll: false,
restrict_scroll_to_axis: false,
scrollbar_width: AbsoluteLength::default(),
position: Position::Relative,
inset: Edges::auto(),
margin: Edges::<Length>::zero(),
padding: Edges::<DefiniteLength>::zero(),
border_widths: Edges::<AbsoluteLength>::zero(),
size: Size::auto(),
min_size: Size::auto(),
max_size: Size::auto(),
aspect_ratio: None,
gap: Size::default(),
align_items: None,
align_self: None,
align_content: None,
justify_content: None,
flex_direction: FlexDirection::Row,
flex_wrap: FlexWrap::NoWrap,
flex_grow: 0.0,
flex_shrink: 1.0,
vn_order: 0,
vn_object_position: None,
flex_basis: Length::Auto,
background: None,
background_layers: Vec::new(),
border_color: None,
vn_border_colors: Edges::default(),
border_style: BorderStyle::default(),
corner_radii: Corners::default(),
box_shadow: Default::default(),
vn_shadow_under_box: false,
backdrop_blur: None,
vn_effect: None,
vn_effect_fade: None,
vn_transform: None,
text: TextStyleRefinement::default(),
mouse_cursor: None,
opacity: None,
grid_rows: None,
grid_cols: None,
grid_location: None,
vn_grid_cols: None,
vn_grid_rows: None,
vn_grid_cols_auto: None,
vn_grid_rows_auto: None,
vn_grid_auto_cols: None,
vn_grid_auto_rows: None,
vn_grid_auto_flow: None,
vn_justify_items: None,
vn_justify_self: None,
vn_outline: None,
vn_mask_ring: false,
vn_clip_path: VnClipPath::None,
vn_color_matrix: None,
vn_capture: None,
vn_isolate: false,
vn_text_fill: None,
vn_mask: None,
vn_corner_radii: Corners::default(),
#[cfg(debug_assertions)]
debug: false,
#[cfg(debug_assertions)]
debug_below: false,
}
}
}
#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct UnderlineStyle {
pub thickness: Pixels,
pub color: Option<Hsla>,
pub wavy: bool,
pub offset: Pixels,
}
#[derive(Refineable, Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub struct StrikethroughStyle {
pub thickness: Pixels,
pub color: Option<Hsla>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum Fill {
Color(Background),
}
impl Fill {
pub fn color(&self) -> Option<Background> {
match self {
Fill::Color(color) => Some(*color),
}
}
}
impl Default for Fill {
fn default() -> Self {
Self::Color(Background::default())
}
}
impl From<Hsla> for Fill {
fn from(color: Hsla) -> Self {
Self::Color(color.into())
}
}
impl From<Rgba> for Fill {
fn from(color: Rgba) -> Self {
Self::Color(color.into())
}
}
impl From<Background> for Fill {
fn from(background: Background) -> Self {
Self::Color(background)
}
}
impl From<TextStyle> for HighlightStyle {
fn from(other: TextStyle) -> Self {
Self::from(&other)
}
}
impl From<&TextStyle> for HighlightStyle {
fn from(other: &TextStyle) -> Self {
Self {
color: Some(other.color),
font_weight: Some(other.font_weight),
font_style: Some(other.font_style),
background_color: other.background_color,
underline: other.underline,
strikethrough: other.strikethrough,
fade_out: None,
}
}
}
impl HighlightStyle {
pub fn color(color: Hsla) -> Self {
Self {
color: Some(color),
..Default::default()
}
}
#[must_use]
pub fn highlight(self, other: HighlightStyle) -> Self {
Self {
color: other
.color
.map(|other_color| {
if let Some(color) = self.color {
color.blend(other_color)
} else {
other_color
}
})
.or(self.color),
font_weight: other.font_weight.or(self.font_weight),
font_style: other.font_style.or(self.font_style),
background_color: other.background_color.or(self.background_color),
underline: other.underline.or(self.underline),
strikethrough: other.strikethrough.or(self.strikethrough),
fade_out: other
.fade_out
.map(|source_fade| {
self.fade_out
.map(|dest_fade| (dest_fade * (1. + source_fade)).clamp(0., 1.))
.unwrap_or(source_fade)
})
.or(self.fade_out),
}
}
}
impl From<Hsla> for HighlightStyle {
fn from(color: Hsla) -> Self {
Self {
color: Some(color),
..Default::default()
}
}
}
impl From<FontWeight> for HighlightStyle {
fn from(font_weight: FontWeight) -> Self {
Self {
font_weight: Some(font_weight),
..Default::default()
}
}
}
impl From<FontStyle> for HighlightStyle {
fn from(font_style: FontStyle) -> Self {
Self {
font_style: Some(font_style),
..Default::default()
}
}
}
impl From<Rgba> for HighlightStyle {
fn from(color: Rgba) -> Self {
Self {
color: Some(color.into()),
..Default::default()
}
}
}
pub fn combine_highlights(
a: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
b: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
) -> impl Iterator<Item = (Range<usize>, HighlightStyle)> {
let mut endpoints = Vec::new();
let mut highlights = Vec::new();
for (range, highlight) in a.into_iter().chain(b) {
if !range.is_empty() {
let highlight_id = highlights.len();
endpoints.push((range.start, highlight_id, true));
endpoints.push((range.end, highlight_id, false));
highlights.push(highlight);
}
}
endpoints.sort_unstable_by_key(|(position, _, _)| *position);
let mut endpoints = endpoints.into_iter().peekable();
let mut active_styles = HashSet::default();
let mut ix = 0;
iter::from_fn(move || {
while let Some((endpoint_ix, highlight_id, is_start)) = endpoints.peek() {
let prev_index = mem::replace(&mut ix, *endpoint_ix);
if ix > prev_index && !active_styles.is_empty() {
let current_style = active_styles
.iter()
.fold(HighlightStyle::default(), |acc, highlight_id| {
acc.highlight(highlights[*highlight_id])
});
return Some((prev_index..ix, current_style));
}
if *is_start {
active_styles.insert(*highlight_id);
} else {
active_styles.remove(highlight_id);
}
endpoints.next();
}
None
})
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum AlignItems {
Start,
End,
FlexStart,
FlexEnd,
Center,
Baseline,
Stretch,
}
pub type JustifyItems = AlignItems;
pub type AlignSelf = AlignItems;
pub type JustifySelf = AlignItems;
#[derive(Copy, Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum AlignContent {
Start,
End,
FlexStart,
FlexEnd,
Center,
Stretch,
SpaceBetween,
SpaceEvenly,
SpaceAround,
SafeCenter,
}
pub type JustifyContent = AlignContent;
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum Display {
Block,
#[default]
Flex,
Grid,
None,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum FlexWrap {
#[default]
NoWrap,
Wrap,
WrapReverse,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum FlexDirection {
#[default]
Row,
Column,
RowReverse,
ColumnReverse,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum Overflow {
#[default]
Visible,
Clip,
Hidden,
Scroll,
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(JsonSchema))]
pub enum Position {
#[default]
Relative,
Absolute,
}
impl From<AlignItems> for taffy::style::AlignItems {
fn from(value: AlignItems) -> Self {
match value {
AlignItems::Start => Self::START,
AlignItems::End => Self::END,
AlignItems::FlexStart => Self::FLEX_START,
AlignItems::FlexEnd => Self::FLEX_END,
AlignItems::Center => Self::CENTER,
AlignItems::Baseline => Self::BASELINE,
AlignItems::Stretch => Self::STRETCH,
}
}
}
impl From<AlignContent> for taffy::style::AlignContent {
fn from(value: AlignContent) -> Self {
match value {
AlignContent::Start => Self::START,
AlignContent::End => Self::END,
AlignContent::FlexStart => Self::FLEX_START,
AlignContent::FlexEnd => Self::FLEX_END,
AlignContent::Center => Self::CENTER,
AlignContent::Stretch => Self::STRETCH,
AlignContent::SpaceBetween => Self::SPACE_BETWEEN,
AlignContent::SpaceEvenly => Self::SPACE_EVENLY,
AlignContent::SpaceAround => Self::SPACE_AROUND,
AlignContent::SafeCenter => Self::SAFE_CENTER,
}
}
}
impl From<Display> for taffy::style::Display {
fn from(value: Display) -> Self {
match value {
Display::Block => Self::Block,
Display::Flex => Self::Flex,
Display::Grid => Self::Grid,
Display::None => Self::None,
}
}
}
impl From<FlexWrap> for taffy::style::FlexWrap {
fn from(value: FlexWrap) -> Self {
match value {
FlexWrap::NoWrap => Self::NoWrap,
FlexWrap::Wrap => Self::Wrap,
FlexWrap::WrapReverse => Self::WrapReverse,
}
}
}
impl From<FlexDirection> for taffy::style::FlexDirection {
fn from(value: FlexDirection) -> Self {
match value {
FlexDirection::Row => Self::Row,
FlexDirection::Column => Self::Column,
FlexDirection::RowReverse => Self::RowReverse,
FlexDirection::ColumnReverse => Self::ColumnReverse,
}
}
}
impl From<Overflow> for taffy::style::Overflow {
fn from(value: Overflow) -> Self {
match value {
Overflow::Visible => Self::Visible,
Overflow::Clip => Self::Clip,
Overflow::Hidden => Self::Hidden,
Overflow::Scroll => Self::Scroll,
}
}
}
impl From<Position> for taffy::style::Position {
fn from(value: Position) -> Self {
match value {
Position::Relative => Self::Relative,
Position::Absolute => Self::Absolute,
}
}
}
#[cfg(test)]
mod tests {
use crate::{blue, green, px, red, yellow};
use super::*;
use util_macros::perf;
#[perf]
fn test_basic_highlight_style_combination() {
let style_a = HighlightStyle::default();
let style_b = HighlightStyle::default();
let style_a = style_a.highlight(style_b);
assert_eq!(
style_a,
HighlightStyle::default(),
"Combining empty styles should not produce a non-empty style."
);
let style_b = HighlightStyle {
color: Some(red()),
strikethrough: Some(StrikethroughStyle {
thickness: px(2.),
color: Some(blue()),
}),
fade_out: Some(0.),
font_style: Some(FontStyle::Italic),
font_weight: Some(FontWeight(300.)),
background_color: Some(yellow()),
underline: Some(UnderlineStyle {
thickness: px(2.),
color: Some(red()),
wavy: true,
offset: px(0.),
}),
};
let expected_style = style_b;
let style_a = style_a.highlight(style_b);
assert_eq!(
style_a, expected_style,
"Blending an empty style with another style should return the other style"
);
let style_b = style_b.highlight(Default::default());
assert_eq!(
style_b, expected_style,
"Blending a style with an empty style should not change the style."
);
let style_c = expected_style;
let style_d = HighlightStyle {
color: Some(blue().alpha(0.7)),
strikethrough: Some(StrikethroughStyle {
thickness: px(4.),
color: Some(crate::red()),
}),
fade_out: Some(0.),
font_style: Some(FontStyle::Oblique),
font_weight: Some(FontWeight(800.)),
background_color: Some(green()),
underline: Some(UnderlineStyle {
thickness: px(4.),
color: None,
wavy: false,
offset: px(0.),
}),
};
let expected_style = HighlightStyle {
color: Some(red().blend(blue().alpha(0.7))),
strikethrough: Some(StrikethroughStyle {
thickness: px(4.),
color: Some(red()),
}),
fade_out: Some(0.),
font_style: Some(FontStyle::Oblique),
font_weight: Some(FontWeight(800.)),
background_color: Some(green()),
underline: Some(UnderlineStyle {
thickness: px(4.),
color: None,
wavy: false,
offset: px(0.),
}),
};
let style_c = style_c.highlight(style_d);
assert_eq!(
style_c, expected_style,
"Blending styles should blend properties where possible and override all others"
);
}
#[perf]
fn test_combine_highlights() {
assert_eq!(
combine_highlights(
[
(0..5, green().into()),
(4..10, FontWeight::BOLD.into()),
(15..20, yellow().into()),
],
[
(2..6, FontStyle::Italic.into()),
(1..3, blue().into()),
(21..23, red().into()),
]
)
.collect::<Vec<_>>(),
[
(
0..1,
HighlightStyle {
color: Some(green()),
..Default::default()
}
),
(
1..2,
HighlightStyle {
color: Some(blue()),
..Default::default()
}
),
(
2..3,
HighlightStyle {
color: Some(blue()),
font_style: Some(FontStyle::Italic),
..Default::default()
}
),
(
3..4,
HighlightStyle {
color: Some(green()),
font_style: Some(FontStyle::Italic),
..Default::default()
}
),
(
4..5,
HighlightStyle {
color: Some(green()),
font_weight: Some(FontWeight::BOLD),
font_style: Some(FontStyle::Italic),
..Default::default()
}
),
(
5..6,
HighlightStyle {
font_weight: Some(FontWeight::BOLD),
font_style: Some(FontStyle::Italic),
..Default::default()
}
),
(
6..10,
HighlightStyle {
font_weight: Some(FontWeight::BOLD),
..Default::default()
}
),
(
15..20,
HighlightStyle {
color: Some(yellow()),
..Default::default()
}
),
(
21..23,
HighlightStyle {
color: Some(red()),
..Default::default()
}
)
]
);
}
#[perf]
fn test_text_style_refinement() {
let mut style = Style::default();
style.refine(&StyleRefinement::default().text_size(px(20.0)));
style.refine(&StyleRefinement::default().font_weight(FontWeight::SEMIBOLD));
assert_eq!(
Some(AbsoluteLength::from(px(20.0))),
style.text_style().unwrap().font_size
);
assert_eq!(
Some(FontWeight::SEMIBOLD),
style.text_style().unwrap().font_weight
);
}
}
#[cfg(test)]
mod vn_object_position_tests {
use super::*;
use crate::{px, size};
#[test]
fn the_position_places_the_fitted_image_in_the_free_space() {
let bounds = Bounds::new(point(px(10.), px(20.)), size(px(100.), px(50.)));
let square = size(DevicePixels(40), DevicePixels(40));
let at = |fit: ObjectFit, x: (f32, f32), y: (f32, f32)| {
let position = ObjectPosition {
x_fraction: x.0,
x_offset: px(x.1),
y_fraction: y.0,
y_offset: px(y.1),
};
let b = fit.get_bounds_at(bounds, square, position);
(f32::from(b.origin.x), f32::from(b.origin.y), f32::from(b.size.width), f32::from(b.size.height))
};
assert_eq!(at(ObjectFit::Contain, (0., 0.), (0., 0.)), (10., 20., 50., 50.));
assert_eq!(at(ObjectFit::Contain, (1., -5.), (0.5, 0.)), (55., 20., 50., 50.));
assert_eq!(at(ObjectFit::Cover, (0., 0.), (1., 0.)), (10., -30., 100., 100.));
assert_eq!(at(ObjectFit::None, (0.25, 0.), (0., 3.)), (25., 23., 40., 40.));
assert_eq!(at(ObjectFit::Fill, (0.5, 7.), (0.5, 0.)), (17., 20., 100., 50.));
let legacy = ObjectFit::None.get_bounds(bounds, square);
assert_eq!(legacy.origin, bounds.origin);
}
}
#[cfg(test)]
mod vn_safe_center_tests {
use crate::{AlignContent, Context, TestAppContext, Window, div, prelude::*, px, size};
struct Boxes;
impl Render for Boxes {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let block = |name: &'static str, child_h: f32| {
let mut d = div().w(px(100.)).h(px(100.));
d.style().align_content = Some(AlignContent::SafeCenter);
d.child(div().debug_selector(move || name.into()).w(px(10.)).h(px(child_h)))
};
div().child(block("FITS", 20.)).child(block("OVERFLOWS", 200.))
}
}
#[gpui::test]
fn safe_center_centres_what_fits_and_starts_what_overflows(cx: &mut TestAppContext) {
let window = cx.open_window(size(px(400.), px(600.)), |_, _| Boxes);
cx.run_until_parked();
window
.update(cx, |_, window, _| {
let at = |name: &str| window.rendered_frame.debug_bounds.get(name).copied().unwrap();
assert_eq!(at("FITS").origin.y, px(40.), "(100 - 20) / 2");
assert_eq!(at("OVERFLOWS").origin.y, px(100.), "at the start of the second box");
})
.unwrap();
}
}
#[cfg(test)]
mod vn_mask_ring_tests {
use crate::{
BoxShadow, Context, Hsla, TestAppContext, Window, color::BG_RING, div, point,
prelude::*, px, size,
};
struct Card {
ring: bool,
}
impl Render for Card {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let mut d = div()
.w(px(100.))
.h(px(60.))
.p(px(2.))
.border_1()
.border_color(Hsla::white())
.bg(Hsla::red())
.shadow(vec![BoxShadow {
color: Hsla::black(),
offset: point(px(0.), px(4.)),
blur_radius: px(8.),
spread_radius: px(0.),
inset: false,
}]);
d.style().vn_mask_ring = Some(self.ring);
d
}
}
fn paint(ring: bool, cx: &mut TestAppContext) -> (Vec<crate::Quad>, usize, f32) {
let window = cx.open_window(size(px(300.), px(300.)), move |_, _| Card { ring });
cx.run_until_parked();
window
.update(cx, |_, window, _| {
let shadows = window.rendered_frame.scene.shadows.len();
(window.painted_quads(), shadows, window.scale_factor())
})
.unwrap()
}
#[gpui::test]
fn a_ring_mask_paints_the_background_in_the_padding_and_border_only(
cx: &mut TestAppContext,
) {
let (quads, shadows, scale) = paint(false, cx);
let background = quads.iter().find(|q| q.background.as_solid() == Some(Hsla::red()));
let background = background.expect("the background quad");
assert_eq!(background.background.flags & BG_RING, 0);
assert_eq!(background.border_widths.top.0, 0.0, "a plain background fills the box");
assert_eq!(shadows, 1);
let (quads, shadows, _) = paint(true, cx);
let background = quads
.iter()
.find(|q| q.background.flags & BG_RING != 0)
.expect("the background quad, flagged");
assert_eq!(background.background.as_solid(), Some(Hsla::red()));
for width in [
background.border_widths.top,
background.border_widths.right,
background.border_widths.bottom,
background.border_widths.left,
] {
assert_eq!(width.0, 3.0 * scale, "1px border + 2px padding");
}
let border = quads
.iter()
.find(|q| q.border_color == Hsla::white())
.expect("the border still paints");
assert_eq!(border.border_widths.top.0, 1.0 * scale);
assert_eq!(shadows, 0, "the mask cuts the outer shadow");
}
}
#[cfg(test)]
mod vn_rounded_clip_tests {
use crate::{
Bounds, Context, Corners, DefiniteLength, Edges, Hsla, Overflow, Style, TestAppContext,
VnCornerRadius, Window, div, point, prelude::*, px, size, vn_resolve_corner_radii,
vn_take_ellipse_drawn_as_circle,
};
fn clipping(radius: f32, border: f32, border_color: Option<Hsla>) -> Style {
Style {
overflow: point(Overflow::Hidden, Overflow::Hidden),
corner_radii: Corners::all(px(radius)).map(|radius| (*radius).into()),
border_widths: Edges::all(px(border).into()),
border_color,
..Style::default()
}
}
#[test]
fn an_overflow_clip_takes_the_padding_box_curve() {
let rem = px(16.);
let bounds = Bounds::new(point(px(10.), px(20.)), size(px(200.), px(160.)));
let mask = clipping(24., 4., Some(Hsla::black())).overflow_mask(bounds, rem).unwrap();
assert_eq!(mask.bounds, Bounds::new(point(px(14.), px(24.)), size(px(192.), px(152.))));
assert_eq!(mask.corner_radii, Corners::all(px(20.)), "the radius less the border");
let mask = clipping(24., 4., None).overflow_mask(bounds, rem).unwrap();
assert_eq!(mask.bounds, bounds, "a transparent border is not inset");
assert_eq!(mask.corner_radii, Corners::all(px(24.)), "so it takes nothing off");
let mask = clipping(3., 4., Some(Hsla::black())).overflow_mask(bounds, rem).unwrap();
assert_eq!(mask.corner_radii, Corners::all(px(0.)), "a border wider than the radius");
let avatar = Bounds::new(point(px(0.), px(0.)), size(px(64.), px(64.)));
let mask = clipping(9999., 0., None).overflow_mask(avatar, rem).unwrap();
assert_eq!(mask.corner_radii, Corners::all(px(32.)), "a pill is a circle");
let mask = clipping(0., 0., None).overflow_mask(bounds, rem).unwrap();
assert!(!mask.is_rounded(), "no radius, the plain rect");
}
fn resolve(lengths: [f32; 4], relative: [Option<(DefiniteLength, DefiniteLength)>; 4], w: f32, h: f32) -> [f32; 4] {
let corner = |r: Option<(DefiniteLength, DefiniteLength)>| r.map(|(x, y)| VnCornerRadius { x, y });
let radii = vn_resolve_corner_radii(
&Corners {
top_left: px(lengths[0]).into(),
top_right: px(lengths[1]).into(),
bottom_right: px(lengths[2]).into(),
bottom_left: px(lengths[3]).into(),
},
&Corners {
top_left: corner(relative[0]),
top_right: corner(relative[1]),
bottom_right: corner(relative[2]),
bottom_left: corner(relative[3]),
},
size(px(w), px(h)),
px(16.),
);
[radii.top_left, radii.top_right, radii.bottom_right, radii.bottom_left].map(f32::from)
}
#[test]
fn percentages_resolve_against_the_box_and_overlaps_scale() {
let half = Some((DefiniteLength::Fraction(0.5), DefiniteLength::Fraction(0.5)));
let _ = vn_take_ellipse_drawn_as_circle();
assert_eq!(resolve([0.; 4], [half; 4], 64., 64.), [32.; 4], "50% of a square: a circle");
assert!(!vn_take_ellipse_drawn_as_circle());
assert_eq!(resolve([0.; 4], [half; 4], 120., 48.), [24.; 4]);
assert!(vn_take_ellipse_drawn_as_circle());
assert_eq!(resolve([9999.; 4], [None; 4], 100., 40.), [20.; 4]);
assert_eq!(resolve([9999., 0., 0., 9999.], [None; 4], 100., 40.), [20., 0., 0., 20.]);
assert_eq!(resolve([8., 4., 0., 12.], [None; 4], 100., 40.), [8., 4., 0., 12.]);
assert_eq!(resolve([40., 40., 0., 0.], [None; 4], 60., 200.), [30., 30., 0., 0.]);
let calc = DefiniteLength::Calc { fraction: 0.5, pixels: px(-4.) };
assert_eq!(resolve([0.; 4], [Some((calc, calc)); 4], 64., 64.), [28.; 4]);
let ellipse = Some((DefiniteLength::Absolute(px(10.).into()), DefiniteLength::Absolute(px(20.).into())));
assert_eq!(resolve([0.; 4], [ellipse; 4], 100., 100.), [10.; 4]);
assert!(vn_take_ellipse_drawn_as_circle());
}
#[test]
fn a_percentage_radius_clips_overflow_too() {
let mut avatar = clipping(0., 0., None);
let half = Some(VnCornerRadius {
x: DefiniteLength::Fraction(0.5),
y: DefiniteLength::Fraction(0.5),
});
avatar.vn_corner_radii = Corners {
top_left: half,
top_right: half,
bottom_right: half,
bottom_left: half,
};
let bounds = Bounds::new(point(px(0.), px(0.)), size(px(40.), px(40.)));
let mask = avatar.overflow_mask(bounds, px(16.)).unwrap();
assert_eq!(mask.corner_radii, Corners::all(px(20.)));
}
struct Clips;
impl Render for Clips {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
.child(
div()
.size(px(64.))
.rounded_full()
.overflow_hidden()
.child(div().size_full().bg(Hsla::red())),
)
.child(
div()
.w(px(200.))
.h(px(160.))
.rounded(px(24.))
.overflow_hidden()
.child(
div()
.id("list")
.size_full()
.overflow_y_scroll()
.child(div().w_full().h(px(400.)).bg(Hsla::green())),
),
)
}
}
#[gpui::test]
fn what_paints_inside_carries_the_rounded_mask(cx: &mut TestAppContext) {
let window = cx.open_window(size(px(400.), px(400.)), |_, _| Clips);
cx.run_until_parked();
let (quads, scale) = window
.update(cx, |_, window, _| (window.painted_quads(), window.scale_factor()))
.unwrap();
let quad = |color: Hsla| {
quads
.iter()
.find(|q| q.background.as_solid() == Some(color))
.copied()
.expect("the quad")
};
let avatar = quad(Hsla::red());
assert_eq!(avatar.content_mask.corner_radii, Corners::all(px(32.)).scale(scale));
assert_eq!(avatar.corner_radii, Corners::default(), "the image itself is square");
let rows = quad(Hsla::green());
assert_eq!(rows.content_mask.corner_radii, Corners::all(px(24.)).scale(scale));
assert_eq!(rows.content_mask.bounds.size, size(px(200.), px(160.)).scale(scale));
}
}
#[cfg(test)]
mod vn_clip_path_tests {
use crate::{
Bounds, BoxShadow, Context, Corners, DefiniteLength, Edges, Hsla, Length, Pixels, Style,
TestAppContext, VnClipBox, VnClipPath, VnCornerRadius, VnShapeRadius, Window, div, point,
prelude::*, px, relative, size,
};
const BOX: VnClipBox = VnClipBox::Border;
fn len(v: f32) -> DefiniteLength {
px(v).into()
}
fn round(x: DefiniteLength, y: DefiniteLength) -> [VnCornerRadius; 4] {
[VnCornerRadius { x, y }; 4]
}
fn mask(clip: VnClipPath, style: Style, bounds: [f32; 4]) -> ([f32; 4], [f32; 4]) {
let bounds = Bounds::new(point(px(bounds[0]), px(bounds[1])), size(px(bounds[2]), px(bounds[3])));
let m = Style { vn_clip_path: clip, ..style }.vn_clip_mask(bounds, px(16.)).expect("a mask");
let (b, r) = (m.bounds, m.corner_radii);
let at = |v: Pixels| (f32::from(v) * 100.).round() / 100.;
(
[b.origin.x, b.origin.y, b.size.width, b.size.height].map(at),
[r.top_left, r.top_right, r.bottom_right, r.bottom_left].map(at),
)
}
fn inset(insets: [DefiniteLength; 4], radii: [VnCornerRadius; 4]) -> VnClipPath {
VnClipPath::Inset { reference: BOX, insets, radii }
}
fn ellipse(center: [DefiniteLength; 2], radius: [VnShapeRadius; 2], circle: bool) -> VnClipPath {
VnClipPath::Ellipse { reference: BOX, center, radius, circle }
}
#[test]
fn inset_takes_its_insets_off_the_box_and_fits_its_radii() {
let none = Style::default;
let square = round(len(0.), len(0.));
assert_eq!(Style::default().vn_clip_mask(Bounds::default(), px(16.)), None, "none is no mask");
let insets = [len(10.), relative(0.2), len(10.), relative(0.2)];
assert_eq!(
mask(inset(insets, round(len(8.), len(8.))), none(), [10., 20., 200., 100.]),
([50., 30., 120., 80.], [8.; 4])
);
let half = relative(0.5);
assert_eq!(mask(inset([half; 4], square), none(), [0., 0., 30., 10.]).0, [15., 5., 0., 0.]);
assert_eq!(mask(inset([len(80.); 4], square), none(), [0., 0., 100., 100.]).0, [80., 80., 0., 0.]);
let strip = [len(40.), len(0.), len(40.), len(0.)];
assert_eq!(mask(inset(strip, round(len(30.), len(30.))), none(), [0., 0., 200., 100.]).1, [10.; 4]);
let ten = relative(0.1);
assert_eq!(mask(inset([len(0.); 4], round(ten, ten)), none(), [0., 0., 200., 100.]).1, [10.; 4]);
}
#[test]
fn circle_and_ellipse_resolve_against_the_box() {
let none = Style::default;
let mid = [relative(0.5), relative(0.5)];
let circle = ellipse(mid, [VnShapeRadius::Length(relative(0.5)); 2], true);
assert_eq!(mask(circle.clone(), none(), [0., 0., 60., 60.]), ([0., 0., 60., 60.], [30.; 4]));
assert_eq!(mask(circle, none(), [0., 0., 200., 100.]).1, [79.06; 4]);
let at = [relative(0.25), relative(0.5)];
assert_eq!(
mask(ellipse(at, [VnShapeRadius::ClosestSide; 2], true), none(), [0., 0., 200., 100.]),
([0., 0., 100., 100.], [50.; 4])
);
let far = ellipse(at, [VnShapeRadius::FarthestSide; 2], true);
assert_eq!(mask(far, none(), [0., 0., 200., 100.]).1, [150.; 4]);
let e = ellipse(mid, [VnShapeRadius::ClosestSide, VnShapeRadius::FarthestSide], false);
assert_eq!(mask(e.clone(), none(), [0., 0., 200., 100.]), ([0., 0., 200., 100.], [0.; 4]));
let bounds = Bounds::new(point(px(0.), px(0.)), size(px(200.), px(100.)));
let outline = Style { vn_clip_path: e, ..none() }.vn_clip_outline(bounds, px(16.)).expect("an outline");
let g = crate::VnClipGeometry::new(&outline, 1., crate::TransformationMatrix::unit());
assert!(g.contains([100., 50.]) && g.contains([2., 50.]) && g.contains([100., 2.]));
assert!(!g.contains([20., 10.]), "the corner a capsule would keep");
let right = [DefiniteLength::Calc { fraction: 1., pixels: px(-10.) }, relative(0.5)];
let e = ellipse(right, [VnShapeRadius::Length(len(10.)), VnShapeRadius::Length(relative(0.2))], false);
assert_eq!(mask(e, none(), [0., 0., 200., 100.]), ([180., 30., 20., 40.], [0.; 4]));
let c = Style { vn_clip_path: ellipse(mid, [VnShapeRadius::ClosestSide; 2], true), ..none() };
assert_eq!(c.vn_clip_outline(bounds, px(16.)), None);
}
#[test]
fn a_box_alone_is_rounded_as_the_border_radius_rounds_it() {
let style = || Style {
corner_radii: Corners::all(px(24.)).map(|r| (*r).into()),
border_widths: Edges::all(px(4.).into()),
padding: Edges::all(px(6.).into()),
margin: Edges { top: Length::Auto, ..Edges::all(len(8.).into()) },
..Style::default()
};
let at = [0., 0., 100., 80.];
assert_eq!(mask(VnClipPath::Box(VnClipBox::Border), style(), at), ([0., 0., 100., 80.], [24.; 4]));
assert_eq!(mask(VnClipPath::Box(VnClipBox::Padding), style(), at), ([4., 4., 92., 72.], [20.; 4]));
assert_eq!(mask(VnClipPath::Box(VnClipBox::Content), style(), at), ([10., 10., 80., 60.], [14.; 4]));
assert_eq!(mask(VnClipPath::Box(VnClipBox::Margin), style(), at), ([-8., 0., 116., 88.], [32.; 4]));
let clip = VnClipPath::Inset { reference: VnClipBox::Content, insets: [len(5.); 4], radii: round(len(0.), len(0.)) };
assert_eq!(mask(clip, style(), at), ([15., 15., 70., 50.], [0.; 4]));
}
struct Clipped;
impl Render for Clipped {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let mut d = div()
.size(px(60.))
.bg(Hsla::red())
.border_2()
.border_color(Hsla::white())
.shadow(vec![BoxShadow {
color: Hsla::black(),
offset: point(px(0.), px(4.)),
blur_radius: px(8.),
spread_radius: px(0.),
inset: false,
}])
.child(div().size(px(100.)).bg(Hsla::green()));
d.style().vn_clip_path = Some(VnClipPath::Ellipse {
reference: VnClipBox::Border,
center: [relative(0.5), relative(0.5)],
radius: [VnShapeRadius::Length(relative(0.5)); 2],
circle: true,
});
div().child(d)
}
}
#[gpui::test]
fn everything_the_element_paints_carries_the_mask(cx: &mut TestAppContext) {
let window = cx.open_window(size(px(200.), px(200.)), |_, _| Clipped);
cx.run_until_parked();
let (quads, shadows, scale) = window
.update(cx, |_, window, _| {
(window.painted_quads(), window.rendered_frame.scene.shadows.clone(), window.scale_factor())
})
.unwrap();
let disc = Bounds::new(point(px(0.), px(0.)), size(px(60.), px(60.))).scale(scale);
let radius = Corners::all(px(30.)).scale(scale);
for color in [Hsla::red(), Hsla::green()] {
let q = quads.iter().find(|q| q.background.as_solid() == Some(color)).expect("the quad");
assert_eq!((q.content_mask.bounds, q.content_mask.corner_radii), (disc, radius), "{color:?}");
}
let border = quads.iter().find(|q| q.border_color == Hsla::white()).expect("the border");
assert_eq!(border.content_mask.bounds, disc);
assert_eq!(shadows.len(), 1);
assert_eq!((shadows[0].content_mask.bounds, shadows[0].content_mask.corner_radii), (disc, radius));
}
fn polygon(reference: VnClipBox, fill_rule: crate::VnFillRule, points: &[[DefiniteLength; 2]]) -> VnClipPath {
VnClipPath::Polygon { reference, fill_rule, points: points.to_vec().into() }
}
fn outline(clip: VnClipPath, style: Style, at: [f32; 4]) -> crate::VnClipOutline {
let bounds = Bounds::new(point(px(at[0]), px(at[1])), size(px(at[2]), px(at[3])));
Style { vn_clip_path: clip, ..style }.vn_clip_outline(bounds, px(16.)).expect("an outline")
}
#[test]
fn a_polygon_resolves_its_percentages_against_the_reference_box() {
use crate::{VnFillRule, VnPathVerb::*};
let triangle = [[relative(0.5), len(0.)], [relative(1.), relative(1.)], [len(0.), relative(1.)]];
let o = outline(polygon(BOX, VnFillRule::NonZero, &triangle), Style::default(), [10., 20., 200., 100.]);
assert_eq!(o.verbs, vec![MoveTo([110., 20.]), LineTo([210., 120.]), LineTo([10., 120.]), Close]);
assert_eq!(
mask(polygon(BOX, VnFillRule::NonZero, &triangle), Style::default(), [10., 20., 200., 100.]),
([10., 20., 200., 100.], [0.; 4])
);
let style = || Style {
border_widths: Edges::all(px(4.).into()),
padding: Edges::all(px(6.).into()),
..Style::default()
};
let o = outline(polygon(VnClipBox::Content, VnFillRule::EvenOdd, &triangle), style(), [0., 0., 100., 100.]);
assert_eq!(o.fill_rule, VnFillRule::EvenOdd);
assert_eq!(o.verbs[0], MoveTo([50., 10.]));
assert_eq!(o.verbs[1], LineTo([90., 90.]));
let past = [[DefiniteLength::Calc { fraction: 1., pixels: px(-10.) }, relative(1.5)]];
assert_eq!(
outline(polygon(BOX, VnFillRule::NonZero, &past), Style::default(), [0., 0., 100., 40.]).verbs[0],
MoveTo([90., 60.])
);
}
#[test]
fn a_path_is_laid_from_the_reference_box_corner() {
use crate::{VnFillRule, VnPathVerb::*};
let verbs = vec![MoveTo([0., 0.]), QuadTo([10., 20.], [20., 0.]), Close];
let path = |reference| VnClipPath::Path { reference, fill_rule: VnFillRule::NonZero, verbs: verbs.clone().into() };
let o = outline(path(BOX), Style::default(), [5., 7., 50., 50.]);
assert_eq!(o.verbs, vec![MoveTo([5., 7.]), QuadTo([15., 27.], [25., 7.]), Close]);
let style = Style { padding: Edges::all(px(3.).into()), ..Style::default() };
let o = outline(path(VnClipBox::Content), style, [0., 0., 50., 50.]);
assert_eq!(o.verbs[0], MoveTo([3., 3.]));
assert_eq!(mask(path(BOX), Style::default(), [5., 7., 50., 50.]).0, [5., 7., 20., 20.]);
}
struct Triangle;
impl Render for Triangle {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let mut d = div()
.size(px(100.))
.bg(Hsla::red())
.cursor_pointer()
.child(div().size(px(100.)).bg(Hsla::green()))
.child(crate::deferred(div().absolute().top_0().left_0().size(px(50.)).bg(Hsla::blue())).clip_to_ancestors(true));
d.style().vn_clip_path = Some(polygon(
BOX,
crate::VnFillRule::NonZero,
&[[len(0.), len(0.)], [len(100.), len(0.)], [len(0.), len(100.)]],
));
div().child(d)
}
}
#[gpui::test]
fn a_polygon_paints_into_an_isolated_layer_and_cuts_the_hit_test(cx: &mut TestAppContext) {
let window = cx.open_window(size(px(200.), px(200.)), |_, _| Triangle);
cx.run_until_parked();
window
.update(cx, |_, window, _| {
let scale = window.scale_factor();
let scene = &window.rendered_frame.scene;
assert_eq!(scene.vn_layers.len(), 2, "{:?}", scene.vn_layers);
assert_eq!(scene.vn_group_count(), 3);
let root: Vec<_> = scene.vn_batches(0).collect();
assert!(root.iter().all(|b| matches!(b, crate::VnBatch::Layers(_))), "{root:?}");
let colors = |group: usize| -> Vec<Hsla> {
scene
.vn_batches(group)
.filter_map(|b| match b {
crate::VnBatch::Primitives(crate::PrimitiveBatch::Quads(r)) => Some(r),
_ => None,
})
.flat_map(|r| scene.quads[r].iter().filter_map(|q| q.background.as_solid()).collect::<Vec<_>>())
.collect()
};
let mut groups: Vec<Vec<Hsla>> = scene.vn_layers.iter().map(|l| colors(l.group as usize)).collect();
groups.sort_by_key(|g| g.len());
assert_eq!(groups, vec![vec![Hsla::blue()], vec![Hsla::red(), Hsla::green()]]);
for layer in &scene.vn_layers {
assert_eq!(layer.segment_count, 3);
assert_eq!(layer.fill_rule, 0);
assert!(layer.bounds.size.width.0 >= 100. * scale);
}
assert_eq!(scene.vn_clip_segments.len(), 6);
let flat = scene.batches().count();
assert!(flat >= 2, "{flat}");
let frame = &window.rendered_frame;
let clipped: Vec<_> = frame.hitboxes.iter().filter(|h| h.vn_clip.is_some()).collect();
assert_eq!(clipped.len(), 1);
let id = clipped[0].id;
let hits = |x: f32, y: f32| frame.hit_test(point(px(x), px(y)), scale).ids.contains(&id);
assert!(hits(10., 10.));
assert!(hits(40., 40.));
assert!(!hits(60., 60.), "inside the box, outside the triangle");
assert!(!hits(150., 10.));
})
.unwrap();
}
fn quad_mask(tint_leaf: bool) -> crate::VnMask {
crate::VnMask {
luminance: false,
tint_leaf,
key: 1,
paint: Some(std::rc::Rc::new(|bounds, tint, window: &mut Window, _: &mut crate::App| {
let half = Bounds::new(bounds.origin, size(bounds.size.width / 2., bounds.size.height));
window.paint_quad(crate::fill(half, tint.unwrap_or_else(Hsla::white)));
})),
}
}
struct Masked;
impl Render for Masked {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let deferred = crate::deferred(div().absolute().top_0().left_0().size(px(20.)).bg(Hsla::black()));
let mut boxed = div()
.size(px(40.))
.bg(Hsla::red())
.opacity(0.5)
.child(div().size(px(10.)).bg(Hsla::green()))
.child(deferred.clip_to_ancestors(true));
boxed.style().vn_mask = Some(quad_mask(false));
let mut icon = div().size(px(20.)).bg(Hsla::blue());
icon.style().vn_mask = Some(quad_mask(true));
div().child(boxed).child(icon)
}
}
#[gpui::test]
fn a_mask_composites_its_group_through_the_mask_group_and_a_leaf_is_tinted(cx: &mut TestAppContext) {
let window = cx.open_window(size(px(200.), px(200.)), |_, _| Masked);
cx.run_until_parked();
window
.update(cx, |_, window, _| {
let scene = &window.rendered_frame.scene;
assert_eq!(scene.vn_layers.len(), 2, "the box, the deferred child, and no layer for the leaf");
let colors = |group: usize| -> Vec<Hsla> {
scene
.vn_batches(group)
.filter_map(|b| match b {
crate::VnBatch::Primitives(crate::PrimitiveBatch::Quads(r)) => Some(r),
_ => None,
})
.flat_map(|r| scene.quads[r].iter().filter_map(|q| q.background.as_solid()).collect::<Vec<_>>())
.collect()
};
let mut groups = Vec::new();
for layer in &scene.vn_layers {
assert_eq!(layer.fill_rule, 1 << 1, "an alpha mask over a nonzero box");
let content = colors(layer.group as usize);
assert!(content.iter().all(|c| (c.a - 0.5).abs() < 1e-3), "{content:?}");
assert_eq!(colors(layer.group as usize + 1), vec![Hsla::white()], "the mask is not faded");
groups.push(content.len());
}
groups.sort();
assert_eq!(groups, vec![1, 2], "the deferred child paints through the mask again");
let root = colors(0);
assert_eq!(root, vec![Hsla::blue()], "the leaf paints the mask in its colour");
let leaf = scene.quads.iter().find(|q| q.background.as_solid() == Some(Hsla::blue())).unwrap();
assert_eq!(leaf.bounds.size.width.0, 10. * window.scale_factor());
})
.unwrap();
}
}
#[cfg(test)]
mod vn_border_color_tests {
use super::*;
#[test]
fn independent_border_colors_keep_shared_fallback_and_transparent_sides() {
let mut style = Style { border_color: Some(Hsla::red()), ..Default::default() };
style.vn_border_colors.left = Some(Hsla::transparent_black());
style.vn_border_colors.top = Some(Hsla::blue());
let colors = style.vn_resolved_border_colors();
assert_eq!(colors.top, Hsla::blue());
assert_eq!(colors.right, Hsla::red());
assert!(colors.left.is_transparent());
}
#[test]
fn overflow_is_clipped_inside_borders_coloured_per_side() {
let mut style = Style::default();
style.overflow = Point { x: Overflow::Hidden, y: Overflow::Hidden };
style.border_widths = Edges::all(px(4.).into());
style.vn_border_colors.top = Some(Hsla::blue());
style.vn_border_colors.left = Some(Hsla::red());
let bounds = Bounds::new(point(px(0.), px(0.)), size(px(100.), px(100.)));
let mask = style.overflow_mask(bounds, px(16.)).unwrap();
assert_eq!(mask.bounds, Bounds::from_corners(point(px(4.), px(4.)), point(px(100.), px(100.))));
}
#[test]
fn colored_border_partitions_cover_rounded_arcs_with_width_weighted_joins() {
let clips = Style::vn_border_side_clips(
Bounds::new(point(px(0.), px(0.)), size(px(80.), px(80.))), Edges::all(px(8.)),
);
let contains = |polygon: &Vec<[f32; 2]>, point: [f32; 2]| {
let mut sign = 0.;
for (a, b) in polygon.iter().zip(polygon.iter().cycle().skip(1)) {
let cross = (b[0] - a[0]) * (point[1] - a[1]) - (b[1] - a[1]) * (point[0] - a[0]);
if cross.abs() < 0.0001 { continue; }
if sign != 0. && cross.signum() != sign { return false; }
sign = cross.signum();
}
polygon.len() >= 3
};
assert!(contains(&clips[0], [15., 13.]), "top rounded arc extends below the rectangular inner top");
assert!(contains(&clips[3], [13., 15.]), "left rounded arc extends beyond the rectangular inner left");
for y in 0..80 {
for x in 0..80 {
assert!(clips.iter().any(|polygon| contains(polygon, [x as f32 + 0.25, y as f32 + 0.25])),
"coloured side clips must cover the entire quad, including rounded corners");
}
}
let clips = Style::vn_border_side_clips(
Bounds::new(point(px(0.), px(0.)), size(px(100.), px(60.))),
Edges { top: px(4.), right: px(8.), bottom: px(6.), left: px(2.) },
);
assert!(contains(&clips[0], [2., 3.]));
assert!(contains(&clips[3], [2., 5.]), "top/left join uses their2:4width ratio");
}
}