repose_core/view.rs
1use crate::shape::ResolvedShape;
2use crate::units::{Dp, Px, Sp};
3use crate::{
4 BaselineShift, Brush, ClipOp, Color, ColorFilter, CompositingStrategy, DrawStyle, FontStyle,
5 FontSynthesis, FontWeight, Modifier, Rect, TextAlign, TextDecoration, TextDirection, TextSpan,
6 Transform, Vec2,
7};
8use std::{fmt::Formatter, sync::Arc};
9
10/// The constraints that will be passed to a subcomposed child. Values are in
11/// [`Dp`], matching the units used by `Modifier`.
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub struct SubcomposeScope {
14 pub min_width: Dp,
15 pub max_width: Dp,
16 pub min_height: Dp,
17 pub max_height: Dp,
18}
19
20impl SubcomposeScope {
21 /// A scope with no finite upper bounds. Values are density-independent
22 /// pixels (`Dp`).
23 pub const UNBOUNDED: Self = Self {
24 min_width: Dp(0.0),
25 max_width: Dp(f32::INFINITY),
26 min_height: Dp(0.0),
27 max_height: Dp(f32::INFINITY),
28 };
29
30 /// Construct a scope from raw min/max [`Dp`] values. Non-finite minimums
31 /// and negative values are coerced to zero, a NaN maximum becomes
32 /// unbounded, and inverted bounds collapse to the maximum.
33 pub fn new(min_width: Dp, max_width: Dp, min_height: Dp, max_height: Dp) -> Self {
34 fn minimum(value: f32) -> f32 {
35 if value.is_nan() || value < 0.0 || !value.is_finite() {
36 0.0
37 } else {
38 value
39 }
40 }
41 fn maximum(value: f32) -> f32 {
42 if value.is_nan() || value < 0.0 {
43 if value.is_nan() { f32::INFINITY } else { 0.0 }
44 } else {
45 value
46 }
47 }
48 let mut scope = Self {
49 min_width: Dp(minimum(min_width.0)),
50 max_width: Dp(maximum(max_width.0)),
51 min_height: Dp(minimum(min_height.0)),
52 max_height: Dp(maximum(max_height.0)),
53 };
54 if scope.min_width.0 > scope.max_width.0 {
55 scope.min_width = scope.max_width;
56 }
57 if scope.min_height.0 > scope.max_height.0 {
58 scope.min_height = scope.max_height;
59 }
60 scope
61 }
62
63 pub fn has_bounded_width(&self) -> bool {
64 self.max_width.0.is_finite()
65 }
66
67 pub fn has_bounded_height(&self) -> bool {
68 self.max_height.0.is_finite()
69 }
70}
71
72/// Scope passed to [`BoxWithConstraints`](crate::prelude::BoxWithConstraints)
73/// content. All values are in [`Dp`].
74#[derive(Clone, Copy, Debug, PartialEq)]
75pub struct BoxWithConstraintsScope {
76 pub min_width: Dp,
77 pub max_width: Dp,
78 pub min_height: Dp,
79 pub max_height: Dp,
80}
81
82impl BoxWithConstraintsScope {
83 /// `true` if the width is bounded by the parent (i.e. not infinite).
84 pub fn has_bounded_width(&self) -> bool {
85 self.max_width.0.is_finite()
86 }
87
88 /// `true` if the height is bounded by the parent (i.e. not infinite).
89 pub fn has_bounded_height(&self) -> bool {
90 self.max_height.0.is_finite()
91 }
92}
93
94pub type ViewId = u64;
95
96pub type ImageHandle = u64;
97#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
98pub enum ImageFilter {
99 #[default]
100 Linear,
101 Nearest,
102}
103
104#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
105pub struct ImageSourceRect {
106 pub x: u32,
107 pub y: u32,
108 pub width: u32,
109 pub height: u32,
110}
111
112impl ImageSourceRect {
113 pub const fn new(x: u32, y: u32, width: u32, height: u32) -> Self {
114 Self {
115 x,
116 y,
117 width,
118 height,
119 }
120 }
121
122 pub const fn is_empty(self) -> bool {
123 self.width == 0 || self.height == 0
124 }
125}
126
127#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
128#[non_exhaustive]
129pub enum ImageFit {
130 /// ContentScale.Fit - default in Compose Image
131 #[default]
132 Contain,
133 /// ContentScale.Crop
134 Cover,
135 /// ContentScale.FillWidth
136 FitWidth,
137 /// ContentScale.FillHeight
138 FitHeight,
139 /// ContentScale.FillBounds - stretch, ignore aspect
140 FillBounds,
141 /// ContentScale.Inside - like Contain but never upscales
142 Inside,
143 /// ContentScale.None - no scaling; placement comes from [`ImageAlignment`]
144 None,
145 /// Repeat the source to fill the bounds (Godot `STRETCH_SCALE` + tile).
146 /// Unlike every other mode this ignores aspect ratio and may draw past a
147 /// `source_rect` edge, wrapping instead of clipping.
148 Tile,
149}
150
151/// Placement of scaled content inside the view bounds. Mirrors Godot's
152/// `AspectRatioContainer::AlignmentMode` and covers every fixed `Alignment` in
153/// Compose (`Begin`/`End` are physical left/right and top/bottom, not
154/// direction-aware).
155#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
156pub enum ImageAlignment {
157 /// Alignment.Center
158 #[default]
159 Center,
160 /// Alignment.TopLeft / BottomStart - left and top
161 Begin,
162 /// Alignment.TopRight / BottomEnd - right and bottom
163 End,
164}
165
166impl ImageFit {
167 /// Per-axis scale factors for drawing a `src`-sized source into `dst`.
168 /// Mirrors Compose's `ContentScale.computeScaleFactor`, which layout and
169 /// paint both need: layout sizes to it, paint draws with it.
170 pub fn scale_factor(self, src: (f32, f32), dst: (f32, f32)) -> (f32, f32) {
171 let fill_w = dst.0 / src.0;
172 let fill_h = dst.1 / src.1;
173 let uniform = |v: f32| (v, v);
174 match self {
175 Self::Contain => uniform(fill_w.min(fill_h)),
176 Self::Cover => uniform(fill_w.max(fill_h)),
177 Self::FitWidth => uniform(fill_w),
178 Self::FitHeight => uniform(fill_h),
179 Self::FillBounds => (fill_w, fill_h),
180 Self::Inside => {
181 if src.0 <= dst.0 && src.1 <= dst.1 {
182 uniform(1.0)
183 } else {
184 uniform(fill_w.min(fill_h))
185 }
186 }
187 Self::None | Self::Tile => uniform(1.0),
188 }
189 }
190}
191
192#[derive(Clone)]
193pub struct OverlayEntry {
194 pub id: u64,
195 pub view: Box<View>,
196}
197
198#[derive(Clone)]
199#[non_exhaustive]
200pub enum ViewKind {
201 Box,
202 Row,
203 Column,
204 ZStack,
205 OverlayHost,
206 Text {
207 text: String,
208 color: Color,
209 font_size: Sp,
210 soft_wrap: bool,
211 max_lines: Option<usize>,
212 overflow: TextOverflow,
213 font_family: Option<&'static str>,
214 annotations: Option<Arc<[TextSpan]>>,
215 text_align: TextAlign,
216 font_weight: FontWeight,
217 font_style: FontStyle,
218 text_decoration: TextDecoration,
219 letter_spacing: Sp,
220 line_height: Sp,
221 /// URL for clickable link text.
222 url: Option<Arc<str>>,
223 /// OpenType font variation settings (e.g. "wght 700, opsz 24").
224 font_variation_settings: Option<Arc<str>>,
225 /// Fill, outline, or both (faux-bold). Default `Fill`.
226 draw_style: DrawStyle,
227 },
228
229 Image {
230 handle: ImageHandle,
231 tint: Color,
232 fit: ImageFit,
233 filter: ImageFilter,
234 source_rect: Option<ImageSourceRect>,
235 alignment: ImageAlignment,
236 },
237 /// A layout whose children are produced by calling `content` with the
238 /// current `SubcomposeScope`. The closure is invoked during reconciliation
239 /// and returns a list of `(slot_id, view)` pairs. Each slot id is a stable
240 /// identity used to reconcile the returned view across frames. This is
241 /// the building block for `BoxWithConstraints` and other
242 /// constraints-driven layouts.
243 ///
244 /// Note: any `Modifier::key` set on a returned view is overwritten by its
245 /// slot id so the slot's identity is stable across frames.
246 SubcomposeLayout {
247 content: Arc<dyn Fn(&SubcomposeScope) -> Vec<(u64, View)>>,
248 },
249}
250
251impl std::fmt::Debug for ViewKind {
252 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
253 match self {
254 Self::Box => f.write_str("Box"),
255 Self::Row => f.write_str("Row"),
256 Self::Column => f.write_str("Column"),
257 Self::ZStack => f.write_str("ZStack"),
258 Self::OverlayHost => f.write_str("OverlayHost"),
259
260 Self::Image {
261 handle,
262 tint,
263 fit,
264 filter,
265 source_rect,
266 alignment,
267 } => f
268 .debug_struct("Image")
269 .field("handle", handle)
270 .field("tint", tint)
271 .field("fit", fit)
272 .field("filter", filter)
273 .field("source_rect", source_rect)
274 .field("alignment", alignment)
275 .finish(),
276 Self::SubcomposeLayout { .. } => f.write_str("SubcomposeLayout"),
277 Self::Text { text, .. } => write!(f, "Text({:?})", text),
278 }
279 }
280}
281
282#[derive(Clone, Debug)]
283pub struct View {
284 pub id: ViewId,
285 pub kind: ViewKind,
286 pub modifier: Modifier,
287 pub children: Vec<View>,
288 pub semantics: Option<crate::semantics::Semantics>,
289 /// Set by `scope!` macro to mark this as a scope boundary node.
290 /// Carries the scope key (e.g., "title", "color_buttons") for per-scope
291 /// TaffyTree isolation.
292 pub scope_key: Option<String>,
293}
294
295impl View {
296 pub fn new(id: ViewId, kind: ViewKind) -> Self {
297 View {
298 id,
299 kind,
300 modifier: Modifier::default(),
301 children: vec![],
302 semantics: None,
303 scope_key: None,
304 }
305 }
306 pub fn modifier(mut self, m: Modifier) -> Self {
307 self.modifier = m;
308 self
309 }
310 /// Mark this view as disabled - ignores pointer events.
311 pub fn disabled(mut self) -> Self {
312 self.modifier.disabled = true;
313 self
314 }
315 pub fn with_children(mut self, kids: Vec<View>) -> Self {
316 self.children = kids;
317 self
318 }
319 pub fn children(mut self, kids: impl Into<Vec<View>>) -> Self {
320 self.children = kids.into();
321 self
322 }
323 pub fn semantics(mut self, s: crate::semantics::Semantics) -> Self {
324 self.semantics = Some(s);
325 self
326 }
327}
328
329/// Renderable scene
330#[derive(Clone, Debug, Default)]
331pub struct Scene {
332 pub clear_color: Color,
333 pub nodes: Vec<SceneNode>,
334}
335
336/// Tunable text properties bundled for ergonomic [`Default`], so a
337/// [`SceneNode::Text`] stays `{ rect, text, color, size, style }` and simple
338/// nodes don't spell out every knob. `color` and `size` stay on the variant
339/// because a default for either would silently draw invisible text.
340#[derive(Clone, Debug, PartialEq, Default)]
341pub struct TextPaintStyle {
342 pub font_family: Option<&'static str>,
343 pub text_align: TextAlign,
344 pub font_weight: FontWeight,
345 pub font_style: FontStyle,
346 pub text_decoration: TextDecoration,
347 pub letter_spacing: Px,
348 pub line_height: Px,
349 pub text_direction: TextDirection,
350 /// Whether the font renderer may synthesize bold/italic/small-caps.
351 pub font_synthesis: FontSynthesis,
352 pub baseline_shift: BaselineShift,
353 /// Fill, outline, or both.
354 pub draw_style: DrawStyle,
355 /// URL for clickable link text.
356 pub url: Option<Arc<str>>,
357 /// OpenType font variation settings (e.g. "wght 700, opsz 24").
358 pub font_variation_settings: Option<Arc<str>>,
359}
360
361/// How an image is sampled and placed inside its [`Rect`], bundled for
362/// ergonomic [`Default`]. `tint` stays on [`SceneNode::Image`] because
363/// untinted is an explicit choice, not a neutral one.
364#[derive(Clone, Copy, Debug, PartialEq, Default)]
365pub struct ImagePaintStyle {
366 pub fit: ImageFit,
367 pub filter: ImageFilter,
368 /// Sub-region of the source texture to sample.
369 pub source_rect: Option<ImageSourceRect>,
370 pub alignment: ImageAlignment,
371}
372
373#[derive(Clone, Copy, Debug)]
374pub struct PaintCallbackInfo {
375 /// Viewport in physical pixels where the callback should paint.
376 pub viewport: Rect,
377 /// Clip rect in physical pixels (intersection of callback rect and current clip).
378 pub clip_rect: Rect,
379 /// Pixels per point (DPI scale).
380 pub pixels_per_point: f32,
381 /// Screen size in physical pixels.
382 pub screen_size_px: [u32; 2],
383}
384
385pub type PaintCallbackPayload = Arc<dyn std::any::Any + Send + Sync>;
386
387/// Paint-space scene graph. `Rect`/`Vec2` compounds carry physical pixels
388/// (like Compose `Offset`/`Size`/`Rect`); scalar lengths use [`Px`] so the
389/// dp→px boundary is explicit instead of unitless `f32`.
390#[derive(Clone, Debug)]
391#[non_exhaustive]
392pub enum SceneNode {
393 Rect {
394 rect: Rect,
395 brush: Brush,
396 radius: [Px; 4],
397 },
398 Border {
399 rect: Rect,
400 brush: Brush,
401 width: Px,
402 radius: [Px; 4],
403 },
404 /// Fill an arbitrary resolved [`Shape`] with a brush.
405 ShapeRect {
406 rect: Rect,
407 resolved: ResolvedShape,
408 brush: Brush,
409 },
410 /// Stroke an arbitrary resolved [`Shape`] with a brush.
411 ShapeBorder {
412 rect: Rect,
413 resolved: ResolvedShape,
414 brush: Brush,
415 width: Px,
416 },
417 Text {
418 rect: Rect,
419 text: Arc<str>,
420 color: Color,
421 size: Px,
422 style: TextPaintStyle,
423 },
424 Ellipse {
425 rect: Rect,
426 brush: Brush,
427 },
428 EllipseBorder {
429 rect: Rect,
430 brush: Brush,
431 width: Px,
432 },
433 PushClip {
434 rect: Rect,
435 radius: [Px; 4],
436 op: ClipOp,
437 },
438 /// Push a clip against an arbitrary resolved [`Shape`]. The matching
439 /// [`PopClip`](Self::PopClip) closes it, just as for `PushClip`.
440 PushShapeClip {
441 rect: Rect,
442 resolved: ResolvedShape,
443 op: ClipOp,
444 },
445 PopClip,
446 PushTransform {
447 transform: Transform,
448 },
449 PopTransform,
450 Image {
451 rect: Rect,
452 handle: ImageHandle,
453 tint: Color,
454 style: ImagePaintStyle,
455 },
456 /// [`Image`](Self::Image) composited with an explicit blend mode. Kept
457 /// additive so the existing `Image` constructors keep meaning Normal
458 /// source-over. Separable modes (`Add`, `Multiply`, `Screen`, `Darken`,
459 /// `Lighten`) use fixed-function blending; the rest isolate the image
460 /// into a graphics layer and composite it with the backdrop-blend shader,
461 /// exactly like [`VectorMesh`](Self::VectorMesh).
462 ImageBlended {
463 rect: Rect,
464 handle: ImageHandle,
465 tint: Color,
466 style: ImagePaintStyle,
467 blend: BlendMode,
468 },
469 /// Tinted A8 coverage mask: samples `handle` (registered with
470 /// `register_coverage_a8`) as coverage and composites `color` with
471 /// source-over. Lets hosts rasterize geometry once (e.g. cached glyph
472 /// coverage tiles) and re-composite it per frame with a new color or
473 /// position without re-uploading. `rect` positions the tile's top-left;
474 /// its size is the registered tile size.
475 Coverage {
476 rect: Rect,
477 handle: ImageHandle,
478 color: Color,
479 },
480 /// Shadow behind a rounded rect, typically driven by `StateElevation`.
481 /// The `elevation` field controls offset and alpha.
482 Shadow {
483 rect: Rect,
484 radius: [Px; 4],
485 elevation: Px,
486 color: Color,
487 },
488 /// Mark the start of a graphics layer: the contained subtree is rendered
489 /// into an offscreen texture and then composited back into the parent.
490 /// `alpha` is the group-compositing alpha applied at composite time.
491 /// `blur_radius_x` / `blur_radius_y` are the gaussian blur radii in [`Px`]
492 /// applied to the layer before compositing (zero = no blur on that axis).
493 /// `rectangle_edge` true = clamp edge pixels (Rectangle). False = transparent out-of-bounds (Unbounded).
494 /// `blend_mode`, `color_filter` and `compositing_strategy` control how the
495 /// layer is composited; their defaults preserve plain source-over blending.
496 BeginLayer {
497 rect: Rect,
498 layer_id: u32,
499 alpha: f32,
500 blur_radius_x: Px,
501 blur_radius_y: Px,
502 rectangle_edge: bool,
503 blend_mode: BlendMode,
504 color_filter: ColorFilter,
505 compositing_strategy: CompositingStrategy,
506 },
507 /// Closes the graphics layer opened by the matching `BeginLayer`.
508 EndLayer {
509 layer_id: u32,
510 },
511 /// Draws a blurred drop shadow underneath a previously-rendered layer.
512 /// Emitted between `EndLayer` and the layer's `CompositeLayer`. The
513 /// quad samples the layer's texture with a 3x3 Gaussian blur and an
514 /// optional vertical offset.
515 CompositeShadow {
516 layer_id: u32,
517 blur_px: Px,
518 offset_px: (Px, Px),
519 color: Color,
520 /// Corner radii shaping the shadow silhouette, in px. All zero = the
521 /// silhouette follows the layer alpha unchanged.
522 shape_px: [Px; 4],
523 /// Outward expansion of the shadow silhouette in px.
524 spread_px: Px,
525 /// Inset shadows clip to the inside of the silhouette.
526 inset: bool,
527 },
528 /// Arc stroke
529 Arc {
530 rect: Rect,
531 start_angle: f32,
532 sweep_angle: f32,
533 stroke_width: Px,
534 brush: Brush,
535 cap: StrokeCap,
536 },
537 /// Pre-tessellated vector mesh (fill or stroke geometry produced by the
538 /// host, e.g. lyon tessellation). Vertices live in the mesh's own local
539 /// space; `transform` is a 2x3 affine that maps local -> world pixels as
540 /// `[m00, m01, m10, m11, tx, ty]` (`out = M * local + t`; identity is
541 /// `[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]`) and is applied in the vertex shader.
542 /// The current scene `PushTransform` stack is folded in on top of
543 /// `transform`.
544 VectorMesh {
545 mesh: Arc<VectorMeshData>,
546 transform: [f32; 6],
547 paint: PaintDesc,
548 /// Reserved for explicit clip assignment. Clipping is otherwise
549 /// structural via `PushVectorClip`/`PopVectorClip`.
550 clip: Option<u32>,
551 blend: BlendMode,
552 },
553 /// One mesh, one paint, many placements, drawn as a single indexed draw
554 /// with one instance per transform. Placement order is the transform
555 /// order, so an alpha-blended run composites front-to-back last-wins
556 /// exactly as N separate `VectorMesh` nodes would. Use it when the same
557 /// geometry repeats - sprite frames, repeated icons, tiled fills - since
558 /// `VectorMesh` costs one draw and one paint uniform per placement.
559 VectorMeshInstanced {
560 mesh: Arc<VectorMeshData>,
561 transforms: Vec<[f32; 6]>,
562 paint: PaintDesc,
563 blend: BlendMode,
564 },
565 /// Screen-space overlays (handles, rubber bands, playhead). Each mesh
566 /// is positioned in final device pixels and ignores the world
567 /// PushTransform stack. Emit outside the viewport's world transform.
568 VectorOverlay {
569 meshes: Arc<[VectorMeshData]>,
570 },
571 /// Start a vector clip: the mesh is rendered into the stencil buffer
572 /// (increment) and subsequent content is masked to it. Mirrors the
573 /// rect-based `PushClip` but for arbitrary tessellated masks.
574 /// `op` selects intersection (keep content inside the mask, the common
575 /// case) or difference (cut the mask out, e.g. ASS `\iclip` drawings).
576 /// Difference is exact for a lone mask and for a mask nested inside
577 /// intersect clips; a normal clip nested inside a difference mask is
578 /// best-effort (see the renderer docs).
579 PushVectorClip {
580 mesh: Arc<VectorMeshData>,
581 op: ClipOp,
582 },
583 /// End a vector clip opened by `PushVectorClip`.
584 PopVectorClip,
585 /// Custom GPU paint callback (check `egui::PaintCallback`).
586 Callback {
587 rect: Rect,
588 payload: PaintCallbackPayload,
589 },
590}
591
592/// Graphics-layer ids live in non-overlapping bands because a single `Scene`
593/// routinely mixes layers from several producers. `1..` counts up from the
594/// producer side (`repose-ui`), the wgpu translator owns `0xE000_0000..` for
595/// separable-blur scratch textures and `0xF000_0000..` for perspective
596/// flattening, and canvas hosts own
597/// `CANVAS_LAYER_ID_BASE..0xE000_0000`.
598pub const CANVAS_LAYER_ID_BASE: u32 = 0x8000_0000;
599
600/// Shared vertex/index buffers for a tessellated vector mesh.
601#[derive(Clone, Debug, Default)]
602pub struct VectorMeshData {
603 pub vertices: Arc<[VectorVertex]>,
604 pub indices: Arc<[u32]>,
605}
606
607/// Pre-tessellated vertex: local position, premultiplied-linear color, and a
608/// free-form uv channel (unused for solid fills, reserved for texture/gradient
609/// sampling).
610#[derive(Clone, Copy, Debug, PartialEq)]
611#[repr(C)]
612pub struct VectorVertex {
613 pub pos: [f32; 2],
614 pub color: [f32; 4],
615 pub uv: [f32; 2],
616}
617
618/// Ceiling on the stops a multi-stop paint may carry. The renderer packs the
619/// table into the per-mesh uniform, so this is a hard structural limit rather
620/// than a soft recommendation; hosts should split longer ramps themselves.
621pub const MAX_GRADIENT_STOPS: usize = 8;
622
623/// One gradient stop. `offset` is parametric along the gradient axis (0 at the
624/// start, 1 at the end). A stored offset is unconstrained; packing clamps it to
625/// `0..=1` and forces it non-decreasing for the GPU, so a caller may set it
626/// freely through [`GradientStops::as_mut_slice`].
627#[derive(Clone, Copy, Debug, PartialEq, Default)]
628pub struct GradientStop {
629 pub offset: f32,
630 pub color: Color,
631}
632
633/// Inline stop table for [`PaintDesc::LinearStops`] / [`PaintDesc::RadialStops`].
634///
635/// Stored by value (no heap, no lifetime) so `PaintDesc` stays `Copy` and
636/// `SceneNode` stays lifetime-free. Longer input is truncated to the first
637/// [`MAX_GRADIENT_STOPS`]: [`from_slice`](Self::from_slice) logs the overflow,
638/// [`try_from_slice`](Self::try_from_slice) reports it instead.
639#[derive(Clone, Copy, Debug, PartialEq, Default)]
640pub struct GradientStops {
641 stops: [GradientStop; MAX_GRADIENT_STOPS],
642 len: u8,
643}
644
645impl GradientStops {
646 /// The first [`MAX_GRADIENT_STOPS`] of `slice`; logs how many were dropped.
647 pub fn from_slice(slice: &[GradientStop]) -> Self {
648 let mut stops = Self::default();
649 for stop in slice {
650 if !stops.push(*stop) {
651 log::warn!(
652 "gradient has {} stops; keeping the first {MAX_GRADIENT_STOPS}",
653 slice.len()
654 );
655 break;
656 }
657 }
658 stops
659 }
660
661 /// Like [`from_slice`](Self::from_slice) but `None` when `slice` does not
662 /// fit, so hosts can validate before submitting a draw.
663 pub fn try_from_slice(slice: &[GradientStop]) -> Option<Self> {
664 if slice.len() > MAX_GRADIENT_STOPS {
665 return None;
666 }
667 let mut stops = Self::default();
668 for stop in slice {
669 if !stops.push(*stop) {
670 return None;
671 }
672 }
673 Some(stops)
674 }
675
676 /// Append a stop; `false` when the table is already full.
677 pub fn push(&mut self, stop: GradientStop) -> bool {
678 let len = self.len as usize;
679 if len >= MAX_GRADIENT_STOPS {
680 return false;
681 }
682 self.stops[len] = stop;
683 self.len = (len + 1) as u8;
684 true
685 }
686
687 pub fn as_slice(&self) -> &[GradientStop] {
688 &self.stops[..self.len as usize]
689 }
690
691 pub fn as_mut_slice(&mut self) -> &mut [GradientStop] {
692 &mut self.stops[..self.len as usize]
693 }
694
695 pub fn len(&self) -> usize {
696 self.len as usize
697 }
698
699 pub fn is_empty(&self) -> bool {
700 self.len == 0
701 }
702
703 /// Lowest stop alpha in `0..=1`; `1.0` when empty (nothing is painted, so
704 /// the translucency fast path may treat it as opaque).
705 pub fn min_alpha(&self) -> f32 {
706 self.as_slice()
707 .iter()
708 .map(|stop| stop.color.3 as f32 / 255.0)
709 .fold(1.0, f32::min)
710 }
711}
712
713impl<'a> From<&'a [GradientStop]> for GradientStops {
714 fn from(slice: &'a [GradientStop]) -> Self {
715 Self::from_slice(slice)
716 }
717}
718
719/// How a `VectorMesh` is painted. Mirrors the [`Brush`] variants;
720/// gradient endpoints live in the mesh's local space.
721#[derive(Clone, Copy, Debug, PartialEq)]
722#[non_exhaustive]
723pub enum PaintDesc {
724 /// Use per-vertex color.
725 Solid,
726 /// Two-stop linear gradient in the mesh's local space.
727 Linear {
728 start: Vec2,
729 end: Vec2,
730 start_color: Color,
731 end_color: Color,
732 },
733 /// Radial gradient centered at `center` (mesh-local) with `radius`.
734 Radial {
735 center: Vec2,
736 radius: f32,
737 start_color: Color,
738 end_color: Color,
739 },
740 /// Angular sweep around `center` (mesh-local), clockwise from 3 o'clock.
741 Sweep {
742 center: Vec2,
743 start_color: Color,
744 end_color: Color,
745 },
746 /// Multi-stop linear gradient from `start` to `end` (mesh-local), evaluated
747 /// per fragment. With two stops at offsets 0 and 1 this renders identically
748 /// to [`Linear`](Self::Linear); beyond the end stops the color clamps
749 /// (`TileMode::Clamp`).
750 LinearStops {
751 start: Vec2,
752 end: Vec2,
753 stops: GradientStops,
754 },
755 /// Multi-stop radial gradient around `center` with `radius` (mesh-local),
756 /// evaluated per fragment. Two stops at offsets 0 and 1 render identically
757 /// to [`Radial`](Self::Radial).
758 RadialStops {
759 center: Vec2,
760 radius: f32,
761 stops: GradientStops,
762 },
763}
764
765impl PaintDesc {
766 /// Lowest alpha this paint can produce, for the renderer's translucency
767 /// fast path. `None` when translucency comes from per-vertex colors alone.
768 pub fn min_alpha(self) -> Option<f32> {
769 match self {
770 PaintDesc::Solid => None,
771 PaintDesc::Linear {
772 start_color,
773 end_color,
774 ..
775 }
776 | PaintDesc::Radial {
777 start_color,
778 end_color,
779 ..
780 }
781 | PaintDesc::Sweep {
782 start_color,
783 end_color,
784 ..
785 } => Some((start_color.3.min(end_color.3) as f32 / 255.0).clamp(0.0, 1.0)),
786 PaintDesc::LinearStops { stops, .. } | PaintDesc::RadialStops { stops, .. } => {
787 Some(stops.min_alpha())
788 }
789 }
790 }
791}
792
793/// Blend mode for a `VectorMesh`, following the CSS `mix-blend-mode`
794/// vocabulary used by SVG/Lottie-style artwork. All variants are wired into
795/// the renderer: separable modes use fixed-function blending, the rest
796/// (marked below) isolate the mesh into a graphics layer and composite it
797/// with a custom shader.
798#[derive(Clone, Copy, Debug, PartialEq, Eq)]
799#[non_exhaustive]
800#[derive(Default)]
801pub enum BlendMode {
802 /// Standard premultiplied alpha blending (`normal`).
803 #[default]
804 Alpha,
805 /// `screen`: `1 - (1 - S) * (1 - D)`. Fixed-function.
806 Screen,
807 /// `overlay`: `Multiply` for dark backdrops, `Screen` for light ones.
808 Overlay,
809 /// `darken`: per-channel `min(S, D)`. Fixed-function.
810 Darken,
811 /// `lighten`: per-channel `max(S, D)`. Fixed-function.
812 Lighten,
813 /// `color-dodge`: brightens the backdrop toward the source color.
814 ColorDodge,
815 /// `color-burn`: darkens the backdrop toward the source color.
816 ColorBurn,
817 /// `hard-light`: `Overlay` with source and backdrop swapped.
818 HardLight,
819 /// `soft-light`: subtle `Overlay` variant.
820 SoftLight,
821 /// `difference`: per-channel `|S - D|`.
822 /// Needs the backdrop (fixed-function subtract only covers `S - D`),
823 /// so it composites via an isolated layer.
824 Difference,
825 /// `exclusion`: like `difference` with lower contrast.
826 Exclusion,
827 /// `hue`: source hue with backdrop saturation and luminosity.
828 Hue,
829 /// `saturation`: source saturation with backdrop hue and luminosity.
830 Saturation,
831 /// `color`: source hue and saturation with backdrop luminosity.
832 Color,
833 /// `luminosity`: source luminosity with backdrop hue and saturation.
834 Luminosity,
835 /// Additive (screen-space light). Fixed-function.
836 Add,
837 /// `multiply`: per-channel `S * D`. Fixed-function.
838 Multiply,
839}
840
841impl BlendMode {
842 /// Modes implemented with fixed-function hardware blending on the mesh
843 /// pipeline. Everything else isolates the mesh into a graphics layer and
844 /// composites it with the backdrop-blend shader.
845 pub fn needs_isolation(self) -> bool {
846 !matches!(
847 self,
848 BlendMode::Alpha
849 | BlendMode::Add
850 | BlendMode::Multiply
851 | BlendMode::Screen
852 | BlendMode::Darken
853 | BlendMode::Lighten
854 )
855 }
856
857 /// Discriminant consumed by `blend_layer.wgsl` (`mode` flat varying).
858 pub fn shader_mode(self) -> u32 {
859 match self {
860 BlendMode::Alpha => 0,
861 BlendMode::Add => 1,
862 BlendMode::Multiply => 2,
863 BlendMode::Screen => 3,
864 BlendMode::Overlay => 4,
865 BlendMode::Darken => 5,
866 BlendMode::Lighten => 6,
867 BlendMode::ColorDodge => 7,
868 BlendMode::ColorBurn => 8,
869 BlendMode::HardLight => 9,
870 BlendMode::SoftLight => 10,
871 BlendMode::Difference => 11,
872 BlendMode::Exclusion => 12,
873 BlendMode::Hue => 13,
874 BlendMode::Saturation => 14,
875 BlendMode::Color => 15,
876 BlendMode::Luminosity => 16,
877 }
878 }
879}
880
881#[derive(Clone, Copy, Debug, PartialEq, Eq)]
882#[non_exhaustive]
883pub enum TextOverflow {
884 Visible,
885 Clip,
886 Ellipsis,
887}
888
889/// Controls how line segments are joined in a stroked path.
890#[derive(Clone, Copy, Debug, PartialEq, Default)]
891pub enum StrokeJoin {
892 #[default]
893 /// Sharp corner joins.
894 Miter,
895 /// Semi-circular joins.
896 Round,
897 /// Beveled (flat) joins.
898 Bevel,
899}
900
901/// Controls how the endpoints of a stroked arc are drawn.
902#[derive(Clone, Copy, Debug, PartialEq, Default)]
903pub enum StrokeCap {
904 #[default]
905 /// Flat ends at the exact arc endpoint. No extension.
906 Butt,
907 /// Semicircle with diameter equal to the stroke width, centered at the
908 /// arc endpoint.
909 Round,
910 /// Flat-ended rectangle extending half the stroke width beyond the arc
911 /// endpoint.
912 Square,
913}
914
915#[cfg(test)]
916mod tests {
917 use super::*;
918
919 #[test]
920 fn subcompose_scope_unbounded_has_infinite_max() {
921 let s = SubcomposeScope::UNBOUNDED;
922 assert!(!s.max_width.0.is_finite());
923 assert!(!s.max_height.0.is_finite());
924 assert_eq!(s.min_width, Dp(0.0));
925 assert_eq!(s.min_height, Dp(0.0));
926 }
927
928 #[test]
929 fn subcompose_scope_new_round_trips() {
930 let s = SubcomposeScope::new(Dp(10.0), Dp(200.0), Dp(20.0), Dp(300.0));
931 assert_eq!(s.min_width, Dp(10.0));
932 assert_eq!(s.max_width, Dp(200.0));
933 assert_eq!(s.min_height, Dp(20.0));
934 assert_eq!(s.max_height, Dp(300.0));
935 }
936
937 #[test]
938 fn box_with_constraints_scope_bounded_predicates() {
939 let bounded = BoxWithConstraintsScope {
940 min_width: Dp(0.0),
941 max_width: Dp(360.0),
942 min_height: Dp(0.0),
943 max_height: Dp(640.0),
944 };
945 assert!(bounded.has_bounded_width());
946 assert!(bounded.has_bounded_height());
947
948 let unbounded = BoxWithConstraintsScope {
949 min_width: Dp(0.0),
950 max_width: Dp(f32::INFINITY),
951 min_height: Dp(0.0),
952 max_height: Dp(f32::INFINITY),
953 };
954 assert!(!unbounded.has_bounded_width());
955 assert!(!unbounded.has_bounded_height());
956 }
957
958 #[test]
959 fn view_kind_subcompose_layout_holds_closure() {
960 let v: View = View {
961 id: 0,
962 kind: ViewKind::SubcomposeLayout {
963 content: std::sync::Arc::new(|scope| {
964 let _ = scope.max_width;
965 vec![(0, View::new(0, ViewKind::Box))]
966 }),
967 },
968 modifier: Modifier::default(),
969 children: vec![],
970 scope_key: None,
971 semantics: None,
972 };
973 match &v.kind {
974 ViewKind::SubcomposeLayout { .. } => {}
975 _ => panic!("expected SubcomposeLayout"),
976 }
977 }
978
979 #[test]
980 fn view_kind_subcompose_layout_supports_multiple_slots() {
981 let v: View = View {
982 id: 0,
983 kind: ViewKind::SubcomposeLayout {
984 content: std::sync::Arc::new(|_scope| {
985 vec![
986 (1, View::new(0, ViewKind::Box)),
987 (2, View::new(0, ViewKind::Box)),
988 (3, View::new(0, ViewKind::Box)),
989 ]
990 }),
991 },
992 modifier: Modifier::default(),
993 children: vec![],
994 scope_key: None,
995 semantics: None,
996 };
997 if let ViewKind::SubcomposeLayout { content } = &v.kind {
998 let slots = content(&SubcomposeScope::UNBOUNDED);
999 assert_eq!(slots.len(), 3);
1000 assert_eq!(slots[0].0, 1);
1001 assert_eq!(slots[1].0, 2);
1002 assert_eq!(slots[2].0, 3);
1003 } else {
1004 panic!("expected SubcomposeLayout");
1005 }
1006 }
1007}