Skip to main content

cranpose_ui_graphics/
geometry.rs

1//! Geometric primitives: Size, Rect, Insets, Path
2
3use std::{ops::AddAssign, rc::Rc};
4
5use crate::{
6    ArcRecordArgs, Brush, Color, ColorFilter, CommandRecorder, CommandRecording, DrawGroup,
7    DrawTransform, GroupMarker, ImageBitmap, ImageSampling, PathFillRule, Point, Trapezoid,
8    normalized_band,
9    path::{DrawStyle, Path},
10    path_recording::{record_path, record_vector_path, vector_mask_rect},
11    stroke::Stroke,
12    text_primitive::{TextBlockAt, TextPrimitive, measured_text, text_primitive},
13    typography::{DrawTextMeasurer, DrawTextStyle, TextMeasurement},
14    vector_path_mask::PathSide,
15};
16
17/// A width and a height, in logical pixels.
18#[derive(Clone, Copy, Debug, PartialEq, Default)]
19pub struct Size {
20    /// Width, in logical pixels.
21    pub width: f32,
22    /// Height, in logical pixels.
23    pub height: f32,
24}
25
26impl Size {
27    /// Creates a size from a width and a height.
28    pub const fn new(width: f32, height: f32) -> Self {
29        Self { width, height }
30    }
31
32    /// A size of zero width and zero height.
33    pub const ZERO: Self = Self {
34        width: 0.0,
35        height: 0.0,
36    };
37}
38
39/// An axis-aligned rectangle given by its top-left corner and its size, in logical pixels.
40#[derive(Clone, Copy, Debug, Default, PartialEq)]
41pub struct Rect {
42    /// Left edge, in logical pixels.
43    pub x: f32,
44    /// Top edge, in logical pixels.
45    pub y: f32,
46    /// Width, in logical pixels.
47    pub width: f32,
48    /// Height, in logical pixels.
49    pub height: f32,
50}
51
52impl Rect {
53    /// The rect that holds nothing: what two clips that do not overlap
54    /// resolve to, so a clip that meets nothing stays a clip instead of
55    /// lifting.
56    pub const EMPTY: Self = Self {
57        x: 0.0,
58        y: 0.0,
59        width: 0.0,
60        height: 0.0,
61    };
62
63    /// Creates a rectangle with its top-left corner at `origin` and the given `size`.
64    pub fn from_origin_size(origin: Point, size: Size) -> Self {
65        Self {
66            x: origin.x,
67            y: origin.y,
68            width: size.width,
69            height: size.height,
70        }
71    }
72
73    /// Creates a rectangle of `size` with its top-left corner at the origin.
74    pub fn from_size(size: Size) -> Self {
75        Self::from_origin_size(Point::ZERO, size)
76    }
77
78    /// The rectangle's width and height, as Compose's `Rect.size`.
79    pub fn size(&self) -> Size {
80        Size::new(self.width, self.height)
81    }
82
83    /// Returns the rectangle moved by `dx` horizontally and `dy` vertically.
84    pub fn translate(&self, dx: f32, dy: f32) -> Self {
85        Self {
86            x: self.x + dx,
87            y: self.y + dy,
88            width: self.width,
89            height: self.height,
90        }
91    }
92
93    /// Whether the point `(x, y)` lies inside the rectangle, edges included.
94    pub fn contains(&self, x: f32, y: f32) -> bool {
95        x >= self.x && y >= self.y && x <= self.x + self.width && y <= self.y + self.height
96    }
97
98    /// Whether the rect covers no area, so nothing clipped to it can paint.
99    pub fn is_empty(&self) -> bool {
100        self.width <= 0.0 || self.height <= 0.0
101    }
102
103    /// Returns the intersection of two rectangles, or `None` if they don't overlap.
104    pub fn intersect(&self, other: Self) -> Option<Self> {
105        let left = self.x.max(other.x);
106        let top = self.y.max(other.y);
107        let right = (self.x + self.width).min(other.x + other.width);
108        let bottom = (self.y + self.height).min(other.y + other.height);
109        let width = right - left;
110        let height = bottom - top;
111        if width <= 0.0 || height <= 0.0 {
112            None
113        } else {
114            Some(Self {
115                x: left,
116                y: top,
117                width,
118                height,
119            })
120        }
121    }
122
123    /// Returns the smallest rectangle that contains both rectangles.
124    pub fn union(&self, other: Self) -> Self {
125        let left = self.x.min(other.x);
126        let top = self.y.min(other.y);
127        let right = (self.x + self.width).max(other.x + other.width);
128        let bottom = (self.y + self.height).max(other.y + other.height);
129        Self {
130            x: left,
131            y: top,
132            width: (right - left).max(0.0),
133            height: (bottom - top).max(0.0),
134        }
135    }
136}
137
138/// Padding values for each edge of a rectangle.
139#[derive(Clone, Copy, Debug, Default, PartialEq)]
140pub struct EdgeInsets {
141    /// Inset on the left edge, in logical pixels.
142    pub left: f32,
143    /// Inset on the top edge, in logical pixels.
144    pub top: f32,
145    /// Inset on the right edge, in logical pixels.
146    pub right: f32,
147    /// Inset on the bottom edge, in logical pixels.
148    pub bottom: f32,
149}
150
151impl EdgeInsets {
152    /// Creates insets with `all` on every edge.
153    pub fn uniform(all: f32) -> Self {
154        Self {
155            left: all,
156            top: all,
157            right: all,
158            bottom: all,
159        }
160    }
161
162    /// Creates insets with `horizontal` on the left and right and 0.0 on the top and bottom.
163    pub fn horizontal(horizontal: f32) -> Self {
164        Self {
165            left: horizontal,
166            right: horizontal,
167            ..Self::default()
168        }
169    }
170
171    /// Creates insets with `vertical` on the top and bottom and 0.0 on the left and right.
172    pub fn vertical(vertical: f32) -> Self {
173        Self {
174            top: vertical,
175            bottom: vertical,
176            ..Self::default()
177        }
178    }
179
180    /// Creates insets with `horizontal` on the left and right and `vertical` on the top and bottom.
181    pub fn symmetric(horizontal: f32, vertical: f32) -> Self {
182        Self {
183            left: horizontal,
184            right: horizontal,
185            top: vertical,
186            bottom: vertical,
187        }
188    }
189
190    /// Creates insets from separate left, top, right and bottom values.
191    pub fn from_components(left: f32, top: f32, right: f32, bottom: f32) -> Self {
192        Self {
193            left,
194            top,
195            right,
196            bottom,
197        }
198    }
199
200    /// Whether all four insets are 0.0.
201    pub fn is_zero(&self) -> bool {
202        self.left == 0.0 && self.top == 0.0 && self.right == 0.0 && self.bottom == 0.0
203    }
204
205    /// The sum of the left and right insets.
206    pub fn horizontal_sum(&self) -> f32 {
207        self.left + self.right
208    }
209
210    /// The sum of the top and bottom insets.
211    pub fn vertical_sum(&self) -> f32 {
212        self.top + self.bottom
213    }
214
215    /// The part of a `size` rect these insets leave, at the leading insets;
216    /// it never shrinks below zero.
217    pub fn inset_rect(&self, size: Size) -> Rect {
218        Rect {
219            x: self.left,
220            y: self.top,
221            width: (size.width - self.horizontal_sum()).max(0.0),
222            height: (size.height - self.vertical_sum()).max(0.0),
223        }
224    }
225}
226
227impl AddAssign for EdgeInsets {
228    fn add_assign(&mut self, rhs: Self) {
229        self.left += rhs.left;
230        self.top += rhs.top;
231        self.right += rhs.right;
232        self.bottom += rhs.bottom;
233    }
234}
235
236/// The radius of each corner of a rounded rectangle, in logical pixels.
237#[derive(Clone, Copy, Debug, Default, PartialEq)]
238pub struct CornerRadii {
239    /// Radius of the top-left corner, in logical pixels.
240    pub top_left: f32,
241    /// Radius of the top-right corner, in logical pixels.
242    pub top_right: f32,
243    /// Radius of the bottom-right corner, in logical pixels.
244    pub bottom_right: f32,
245    /// Radius of the bottom-left corner, in logical pixels.
246    pub bottom_left: f32,
247}
248
249impl CornerRadii {
250    /// Creates radii with the same value on all four corners.
251    pub fn uniform(radius: f32) -> Self {
252        Self {
253            top_left: radius,
254            top_right: radius,
255            bottom_right: radius,
256            bottom_left: radius,
257        }
258    }
259}
260
261/// A rectangle shape with rounded corners. Compose's `RoundedCornerShape`.
262#[derive(Clone, Copy, Debug, PartialEq)]
263pub struct RoundedCornerShape {
264    radii: CornerRadii,
265}
266
267impl RoundedCornerShape {
268    /// Creates a shape with a separate radius for each corner, in logical pixels.
269    pub fn new(top_left: f32, top_right: f32, bottom_right: f32, bottom_left: f32) -> Self {
270        Self {
271            radii: CornerRadii {
272                top_left,
273                top_right,
274                bottom_right,
275                bottom_left,
276            },
277        }
278    }
279
280    /// Creates a shape with the same radius on all four corners.
281    pub fn uniform(radius: f32) -> Self {
282        Self {
283            radii: CornerRadii::uniform(radius),
284        }
285    }
286
287    /// Creates a shape from a `CornerRadii` value.
288    pub fn with_radii(radii: CornerRadii) -> Self {
289        Self { radii }
290    }
291
292    /// Returns the radii for a rectangle of `width` by `height`, with each radius limited to half
293    /// the width and half the height so the corners fit.
294    pub fn resolve(&self, width: f32, height: f32) -> CornerRadii {
295        let mut resolved = self.radii;
296        let max_width = (width / 2.0).max(0.0);
297        let max_height = (height / 2.0).max(0.0);
298        resolved.top_left = resolved.top_left.clamp(0.0, max_width).min(max_height);
299        resolved.top_right = resolved.top_right.clamp(0.0, max_width).min(max_height);
300        resolved.bottom_right = resolved.bottom_right.clamp(0.0, max_width).min(max_height);
301        resolved.bottom_left = resolved.bottom_left.clamp(0.0, max_width).min(max_height);
302        resolved
303    }
304
305    /// The radii as given, before any clamping to a size.
306    pub fn radii(&self) -> CornerRadii {
307        self.radii
308    }
309}
310
311/// The pivot point for scaling and rotating a layer, given as fractions of its size. Compose's
312/// `TransformOrigin`.
313#[derive(Clone, Copy, Debug, PartialEq)]
314pub struct TransformOrigin {
315    /// Horizontal pivot as a fraction of the layer's width, from 0.0 (left) to 1.0 (right).
316    pub pivot_fraction_x: f32,
317    /// Vertical pivot as a fraction of the layer's height, from 0.0 (top) to 1.0 (bottom).
318    pub pivot_fraction_y: f32,
319}
320
321impl TransformOrigin {
322    /// Creates an origin from fractions of the layer's width and height.
323    pub const fn new(pivot_fraction_x: f32, pivot_fraction_y: f32) -> Self {
324        Self {
325            pivot_fraction_x,
326            pivot_fraction_y,
327        }
328    }
329
330    /// Pivot at the center of the layer.
331    pub const CENTER: Self = Self::new(0.5, 0.5);
332}
333
334impl Default for TransformOrigin {
335    fn default() -> Self {
336        Self::CENTER
337    }
338}
339
340/// The outline of a graphics layer, used for clipping and for its shadow.
341#[derive(Clone, Copy, Debug, Default, PartialEq)]
342pub enum LayerShape {
343    /// Square corners.
344    #[default]
345    Rectangle,
346    /// Corners rounded by the given shape.
347    Rounded(RoundedCornerShape),
348}
349
350/// The transform, opacity, clip, shadow and effect properties of a layer. Compose's
351/// `GraphicsLayerScope`.
352#[derive(Clone, Debug, PartialEq)]
353pub struct GraphicsLayer {
354    /// Opacity of the layer, from 0.0 (transparent) to 1.0 (opaque).
355    pub alpha: f32,
356    /// Uniform scale factor for both axes. 1.0 leaves the size unchanged.
357    pub scale: f32,
358    /// Horizontal scale factor, multiplied with `scale`. 1.0 leaves the width unchanged.
359    pub scale_x: f32,
360    /// Vertical scale factor, multiplied with `scale`. 1.0 leaves the height unchanged.
361    pub scale_y: f32,
362    /// Rotation around the x axis, in degrees.
363    pub rotation_x: f32,
364    /// Rotation around the y axis, in degrees.
365    pub rotation_y: f32,
366    /// Rotation around the z axis, in degrees. Positive values turn clockwise on screen.
367    pub rotation_z: f32,
368    /// Distance of the camera from the layer plane. It sets the strength of the perspective for
369    /// `rotation_x` and `rotation_y`; larger values flatten it.
370    pub camera_distance: f32,
371    /// The point that scaling and rotation turn around, as fractions of the layer's size.
372    pub transform_origin: TransformOrigin,
373    /// Horizontal translation, in layout coordinates.
374    pub translation_x: f32,
375    /// Vertical translation, in layout coordinates.
376    pub translation_y: f32,
377    /// Where the layer sits in 3D: it shows a scene, or its content is drawn
378    /// on a mesh in its parent's scene. `None` keeps it flat. The scale,
379    /// rotation and translation above do not apply to a mesh surface, which
380    /// its own transform places.
381    pub space: Option<std::sync::Arc<crate::space::LayerSpace>>,
382    /// Shadow elevation in layout units. A value of 0.0 or less draws no shadow.
383    pub shadow_elevation: f32,
384    /// Color of the ambient shadow.
385    pub ambient_shadow_color: Color,
386    /// Color of the spot shadow.
387    pub spot_shadow_color: Color,
388    /// Outline used for clipping and for the shadow.
389    pub shape: LayerShape,
390    /// Whether content is clipped to `shape`.
391    pub clip: bool,
392    /// Whether the layer renders offscreen before it is composited.
393    pub compositing_strategy: CompositingStrategy,
394    /// How the layer's content combines with what is already drawn behind it.
395    pub blend_mode: BlendMode,
396    /// Color filter applied to the layer's content, or `None` for none.
397    pub color_filter: Option<ColorFilter>,
398    /// Filter applied to the layer's rendered content as a whole, such as a blur. `None` applies
399    /// none.
400    pub render_effect: Option<crate::render_effect::RenderEffect>,
401    /// Filters the pixels behind this layer. The result shares the layer's
402    /// group opacity and blend mode with its content; `ModulateAlpha` applies
403    /// opacity independently to the backdrop and each content draw.
404    pub backdrop_effect: Option<crate::render_effect::RenderEffect>,
405}
406
407impl GraphicsLayer {
408    /// Default properties for an untransformed, opaque layer without effects.
409    pub const DEFAULT: Self = Self {
410        alpha: 1.0,
411        scale: 1.0,
412        scale_x: 1.0,
413        scale_y: 1.0,
414        rotation_x: 0.0,
415        rotation_y: 0.0,
416        rotation_z: 0.0,
417        camera_distance: 8.0,
418        transform_origin: TransformOrigin::CENTER,
419        translation_x: 0.0,
420        translation_y: 0.0,
421        space: None,
422        shadow_elevation: 0.0,
423        ambient_shadow_color: Color::BLACK,
424        spot_shadow_color: Color::BLACK,
425        shape: LayerShape::Rectangle,
426        clip: false,
427        compositing_strategy: CompositingStrategy::Auto,
428        blend_mode: BlendMode::SrcOver,
429        color_filter: None,
430        render_effect: None,
431        backdrop_effect: None,
432    };
433
434    /// The alpha an isolated layer is composited at: an **eight-bit** one,
435    /// truncated.
436    ///
437    /// The platform never composites a layer at a float alpha. HWUI hands an
438    /// isolated `RenderNode` to the rasterizer as
439    /// `canvas->saveLayerAlpha(&bounds, (int)(properties.getAlpha() * 255))`
440    /// (`frameworks/base/libs/hwui/pipeline/skia/RenderNodeDrawable.cpp`,
441    /// `setViewProperties`), and `(int)` truncates — 0.5 composites at 127/255,
442    /// not at 128/255. The fraction below that byte is gone before a single pixel
443    /// is blended, so anything that keeps it lands a level out wherever the byte
444    /// and the float fall on opposite sides of a half.
445    ///
446    /// The sibling branch is a float on purpose: where `getHasOverlappingRendering()`
447    /// is false HWUI takes `*alphaMultiplier = properties.getAlpha()` and folds it
448    /// into each draw without ever making a byte of it. That is what
449    /// `CompositingStrategy::ModulateAlpha` names.
450    ///
451    /// Truncating here and **rounding** in [`Color::srgb_8bit`] is not an
452    /// inconsistency: they are different call sites in the platform. A colour's own
453    /// alpha is snapped by `Color`'s constructor, which adds the half; a layer's
454    /// alpha is snapped by HWUI's cast, which does not. Anything modelling a faded
455    /// layer without allocating one — a canvas drawing a list row's fade by hand,
456    /// say — wants this rule and not the other.
457    pub fn composite_alpha_8bit(alpha: f32) -> f32 {
458        (alpha.clamp(0.0, 1.0) * 255.0).floor() / 255.0
459    }
460}
461
462impl Default for GraphicsLayer {
463    fn default() -> Self {
464        Self::DEFAULT
465    }
466}
467
468/// Blend mode used for draw primitives.
469///
470/// This mirrors Jetpack Compose's blend-mode vocabulary while the renderer
471/// currently guarantees `SrcOver` and `DstOut` behavior.
472#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
473pub enum BlendMode {
474    /// Clears the destination to transparent where the source draws.
475    Clear,
476    /// Replaces the destination with the source.
477    Src,
478    /// Keeps the destination and discards the source.
479    Dst,
480    /// Draws the source over the destination. This is the default.
481    #[default]
482    SrcOver,
483    /// Draws the destination over the source.
484    DstOver,
485    /// Keeps the source only where the destination is opaque.
486    SrcIn,
487    /// Keeps the destination only where the source is opaque.
488    DstIn,
489    /// Keeps the source only where the destination is transparent.
490    SrcOut,
491    /// Keeps the destination only where the source is transparent.
492    DstOut,
493    /// Draws the source over the destination, only where the destination is opaque.
494    SrcAtop,
495    /// Draws the destination over the source, only where the source is opaque.
496    DstAtop,
497    /// Keeps the source and the destination where the other is transparent.
498    Xor,
499    /// Adds the source and destination colors and alphas.
500    Plus,
501    /// Multiplies the source and destination colors and alphas.
502    Modulate,
503    /// Inverts, multiplies and inverts again, which lightens the result.
504    Screen,
505    /// Multiplies or screens depending on the destination color, which raises contrast.
506    Overlay,
507    /// Keeps the darker color of each channel.
508    Darken,
509    /// Keeps the lighter color of each channel.
510    Lighten,
511    /// Brightens the destination by the source color.
512    ColorDodge,
513    /// Darkens the destination by the source color.
514    ColorBurn,
515    /// Multiplies or screens depending on the source color.
516    HardLight,
517    /// A softer version of `HardLight`: darkens or lightens depending on the source color.
518    SoftLight,
519    /// Subtracts the darker color from the lighter one in each channel.
520    Difference,
521    /// Like `Difference` with lower contrast.
522    Exclusion,
523    /// Multiplies the source and destination colors, which darkens the result.
524    Multiply,
525    /// Takes the hue of the source with the saturation and luminosity of the destination.
526    Hue,
527    /// Takes the saturation of the source with the hue and luminosity of the destination.
528    Saturation,
529    /// Takes the hue and saturation of the source with the luminosity of the destination.
530    Color,
531    /// Takes the luminosity of the source with the hue and saturation of the destination.
532    Luminosity,
533}
534
535impl BlendMode {
536    /// Every mode in declaration order, so `mode as u32` indexes it.
537    pub const ALL: [Self; 29] = [
538        Self::Clear,
539        Self::Src,
540        Self::Dst,
541        Self::SrcOver,
542        Self::DstOver,
543        Self::SrcIn,
544        Self::DstIn,
545        Self::SrcOut,
546        Self::DstOut,
547        Self::SrcAtop,
548        Self::DstAtop,
549        Self::Xor,
550        Self::Plus,
551        Self::Modulate,
552        Self::Screen,
553        Self::Overlay,
554        Self::Darken,
555        Self::Lighten,
556        Self::ColorDodge,
557        Self::ColorBurn,
558        Self::HardLight,
559        Self::SoftLight,
560        Self::Difference,
561        Self::Exclusion,
562        Self::Multiply,
563        Self::Hue,
564        Self::Saturation,
565        Self::Color,
566        Self::Luminosity,
567    ];
568}
569
570/// How a [`GraphicsLayer`] is composited into its parent. Compose's `CompositingStrategy`.
571#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
572pub enum CompositingStrategy {
573    /// Use renderer heuristics (default).
574    #[default]
575    Auto,
576    /// Render this layer to an offscreen target, then composite.
577    Offscreen,
578    /// Multiply alpha on source colors without allocating an offscreen layer.
579    ModulateAlpha,
580}
581
582/// One recorded draw operation, in scope coordinates. Renderers consume these in draw order.
583#[derive(Clone, Debug, PartialEq)]
584pub enum DrawPrimitive {
585    /// Marker emitted by `draw_content()` inside `draw_with_content`.
586    /// This is consumed by the modifier pipeline and never rendered directly.
587    Content,
588    /// Wrapper to associate a draw primitive with a non-default blend mode.
589    Blend {
590        /// The primitive drawn with `blend_mode`.
591        primitive: Box<Self>,
592        /// How the wrapped primitive combines with what is already drawn.
593        blend_mode: BlendMode,
594    },
595    /// A rectangle, filled or stroked.
596    Rect {
597        /// The rectangle in scope coordinates.
598        rect: Rect,
599        /// Paint for the fill or the stroke.
600        brush: Brush,
601        /// `None` fills the rect; `Some` strokes its outline, centered on the
602        /// edge (so it bleeds `width / 2` outside `rect`).
603        stroke: Option<Stroke>,
604    },
605    /// A rectangle with rounded corners, filled or stroked.
606    RoundRect {
607        /// The rectangle in scope coordinates.
608        rect: Rect,
609        /// Paint for the fill or the stroke.
610        brush: Brush,
611        /// Corner radii of the rectangle, in logical pixels.
612        radii: CornerRadii,
613        /// `None` fills the rounded rect; `Some` strokes its outline, centered
614        /// on the edge.
615        stroke: Option<Stroke>,
616    },
617    /// A circular band: a stroked arc, or a filled annular sector / pie wedge.
618    ///
619    /// Angles are radians, `0` = +X, increasing **clockwise** on screen (see
620    /// `crate::stroke` for the full convention).
621    ///
622    /// * `stroke = Some(_)` — the band is `radius ± width/2`, its ends shaped
623    ///   by the stroke cap. `inner_radius` is ignored.
624    /// * `stroke = None` — the band is `inner_radius ..= radius` with flat
625    ///   (butt) radial ends; `inner_radius = 0` is a filled pie wedge.
626    Arc {
627        /// Tight bounding box of the rendered band, caps included. Kept as the
628        /// first field (like every other variant) so bbox/culling/clip logic
629        /// treats an arc exactly like any other primitive.
630        rect: Rect,
631        /// Paint for the arc.
632        brush: Brush,
633        /// Center of the circle the arc lies on, in scope coordinates.
634        center: Point,
635        /// Radius of the stroked centerline, or the outer radius of a filled sector, in logical
636        /// pixels.
637        radius: f32,
638        /// Where the arc starts, in radians. `0` points along +X and angles increase clockwise on
639        /// screen.
640        start_angle: f32,
641        /// Angle swept from `start_angle`, in radians. A negative value sweeps counter-clockwise.
642        sweep_angle: f32,
643        /// `Some` strokes the arc; `None` fills the sector between `inner_radius` and `radius`.
644        stroke: Option<Stroke>,
645        /// `> 0` turns a filled wedge into an annular sector.
646        inner_radius: f32,
647    },
648    /// A stroked straight segment from `start` to `end`, its ends shaped by
649    /// the stroke's cap: Compose's `drawLine`.
650    Line {
651        /// The box of the two ends; the stroke reaches half its width past
652        /// it, as a stroked rect's does past its rect.
653        rect: Rect,
654        /// Paint for the line.
655        brush: Brush,
656        /// Start of the segment, in scope coordinates.
657        start: Point,
658        /// End of the segment, in scope coordinates.
659        end: Point,
660        /// Width and cap of the line.
661        stroke: Stroke,
662    },
663    /// One slice of a filled path, which the draw scope cuts a fill into
664    /// so the GPU draws it: see [`Trapezoid`].
665    Trapezoid {
666        /// The rect `brush` resolves against: the draw scope's own, as a
667        /// path's brush resolves in Compose.
668        rect: Rect,
669        /// Paint for the slice.
670        brush: Brush,
671        /// The slice to fill.
672        trapezoid: Trapezoid,
673    },
674    /// An image drawn into a destination rectangle.
675    Image {
676        /// Destination rectangle in scope coordinates. The image is stretched to fill it.
677        rect: Rect,
678        /// The image to draw.
679        image: ImageBitmap,
680        /// Opacity from 0.0 (transparent) to 1.0 (opaque).
681        alpha: f32,
682        /// Color filter applied to the image, or `None` for none.
683        color_filter: Option<ColorFilter>,
684        /// How pixels are sampled when the image is scaled.
685        sampling: ImageSampling,
686        /// Optional source rectangle in image-pixel coordinates.
687        /// When `None`, the entire image is drawn. When `Some`, only the
688        /// specified sub-region of the source image is sampled.
689        src_rect: Option<Rect>,
690    },
691    /// A laid-out run of text. See [`TextPrimitive`].
692    Text(Box<TextPrimitive>),
693    /// Shadow that requires blur processing. The renderer decides technique
694    /// (GPU blur, CPU approximation, etc.).
695    Shadow(ShadowPrimitive),
696    /// Where a group of draws that [`DrawScope::with_transform`] places starts
697    /// or ends. The primitives between are in the group's coordinates.
698    Group(GroupMarker),
699}
700
701impl DrawPrimitive {
702    /// The primitive moved by `dx`, `dy`. Brush geometry is relative to the
703    /// primitive's rect, so it moves along.
704    pub fn translate(self, dx: f32, dy: f32) -> Self {
705        match self {
706            Self::Content => Self::Content,
707            Self::Blend {
708                primitive,
709                blend_mode,
710            } => Self::Blend {
711                primitive: Box::new(primitive.translate(dx, dy)),
712                blend_mode,
713            },
714            Self::Rect {
715                rect,
716                brush,
717                stroke,
718            } => Self::Rect {
719                rect: rect.translate(dx, dy),
720                brush,
721                stroke,
722            },
723            Self::RoundRect {
724                rect,
725                brush,
726                radii,
727                stroke,
728            } => Self::RoundRect {
729                rect: rect.translate(dx, dy),
730                brush,
731                radii,
732                stroke,
733            },
734            Self::Arc {
735                rect,
736                brush,
737                center,
738                radius,
739                start_angle,
740                sweep_angle,
741                stroke,
742                inner_radius,
743            } => Self::Arc {
744                rect: rect.translate(dx, dy),
745                brush,
746                center: Point::new(center.x + dx, center.y + dy),
747                radius,
748                start_angle,
749                sweep_angle,
750                stroke,
751                inner_radius,
752            },
753            Self::Line {
754                rect,
755                brush,
756                start,
757                end,
758                stroke,
759            } => Self::Line {
760                rect: rect.translate(dx, dy),
761                brush,
762                start: Point::new(start.x + dx, start.y + dy),
763                end: Point::new(end.x + dx, end.y + dy),
764                stroke,
765            },
766            Self::Trapezoid {
767                rect,
768                brush,
769                trapezoid,
770            } => Self::Trapezoid {
771                rect: rect.translate(dx, dy),
772                brush,
773                trapezoid: trapezoid.translate(dx, dy),
774            },
775            Self::Image {
776                rect,
777                image,
778                alpha,
779                color_filter,
780                sampling,
781                src_rect,
782            } => Self::Image {
783                rect: rect.translate(dx, dy),
784                image,
785                alpha,
786                color_filter,
787                sampling,
788                src_rect,
789            },
790            Self::Text(mut text) => {
791                text.rect = text.rect.translate(dx, dy);
792                Self::Text(text)
793            }
794            Self::Shadow(ShadowPrimitive::Drop {
795                shape,
796                cutout,
797                blur_radius,
798                blend_mode,
799            }) => Self::Shadow(ShadowPrimitive::Drop {
800                shape: Box::new(shape.translate(dx, dy)),
801                cutout: cutout.map(|cutout| Box::new(cutout.translate(dx, dy))),
802                blur_radius,
803                blend_mode,
804            }),
805            Self::Shadow(ShadowPrimitive::Inner {
806                fill,
807                cutout,
808                blur_radius,
809                blend_mode,
810                clip_rect,
811            }) => Self::Shadow(ShadowPrimitive::Inner {
812                fill: Box::new(fill.translate(dx, dy)),
813                cutout: Box::new(cutout.translate(dx, dy)),
814                blur_radius,
815                blend_mode,
816                clip_rect: clip_rect.translate(dx, dy),
817            }),
818            Self::Group(GroupMarker::Start(group)) => {
819                Self::Group(GroupMarker::Start(group.translate(dx, dy)))
820            }
821            Self::Group(GroupMarker::End) => Self::Group(GroupMarker::End),
822        }
823    }
824}
825
826/// A shadow that needs blur processing. Each renderer chooses how to blur. See
827/// [`DrawPrimitive::Shadow`].
828#[derive(Clone, Debug, PartialEq)]
829pub enum ShadowPrimitive {
830    /// Drop shadow: render shape behind content, blurred. `cutout` knocks
831    /// the element's own (unoffset) shape out of the silhouette before the
832    /// blur so translucent surfaces never sample their own shadow.
833    Drop {
834        /// The shape drawn and blurred behind the content.
835        shape: Box<DrawPrimitive>,
836        /// `Some` cuts the element's own unoffset shape out of the silhouette before the blur.
837        cutout: Option<Box<DrawPrimitive>>,
838        /// Blur radius of the shadow, in logical pixels.
839        blur_radius: f32,
840        /// How the shadow combines with what is already drawn.
841        blend_mode: BlendMode,
842    },
843    /// Inner shadow: render fill + cutout to offscreen, blur, clip to bounds.
844    Inner {
845        /// The shape drawn and blurred to make the shadow.
846        fill: Box<DrawPrimitive>,
847        /// The shape cut out of the shadow's silhouette, so it appears only outside that shape.
848        cutout: Box<DrawPrimitive>,
849        /// Blur radius of the shadow, in logical pixels.
850        blur_radius: f32,
851        /// How the shadow combines with what is already drawn.
852        blend_mode: BlendMode,
853        /// Element bounds — blurred result must be clipped here.
854        clip_rect: Rect,
855    },
856}
857
858/// The drawing surface passed to draw modifiers. Compose's `DrawScope`. Every method records a
859/// primitive in scope coordinates, with the origin at the top-left corner of the node, and the
860/// `_blend` forms composite with a given blend mode instead of `SrcOver`.
861pub trait DrawScope {
862    /// Size of the drawing area, in logical pixels.
863    fn size(&self) -> Size;
864    /// Marks where the node's own content draws, as Compose's `drawContent()` does in
865    /// `drawWithContent`. Draws recorded before the marker paint under the content and draws after
866    /// it paint over it.
867    fn draw_content(&mut self);
868    /// Fills the whole scope rect with `brush`.
869    fn draw_rect(&mut self, brush: Brush);
870    /// As `draw_rect`, composited with `blend_mode` instead of `SrcOver`.
871    fn draw_rect_blend(&mut self, brush: Brush, blend_mode: BlendMode);
872    /// Draws a rectangle at the specified position and size.
873    fn draw_rect_at(&mut self, rect: Rect, brush: Brush);
874    /// As `draw_rect_at`, composited with `blend_mode` instead of `SrcOver`.
875    fn draw_rect_at_blend(&mut self, rect: Rect, brush: Brush, blend_mode: BlendMode);
876    /// Fills the whole scope rect with rounded corners of `radii`.
877    fn draw_round_rect(&mut self, brush: Brush, radii: CornerRadii);
878    /// As `draw_round_rect`, composited with `blend_mode` instead of `SrcOver`.
879    fn draw_round_rect_blend(&mut self, brush: Brush, radii: CornerRadii, blend_mode: BlendMode);
880    /// Draws a rounded rectangle at the specified position and size.
881    fn draw_round_rect_at(&mut self, rect: Rect, brush: Brush, radii: CornerRadii);
882    /// Fills a circle of `radius` around `center`, in scope coordinates.
883    fn draw_circle(&mut self, brush: Brush, center: Point, radius: f32);
884    /// As `draw_circle`, composited with `blend_mode` instead of `SrcOver`.
885    fn draw_circle_blend(
886        &mut self,
887        brush: Brush,
888        center: Point,
889        radius: f32,
890        blend_mode: BlendMode,
891    );
892
893    /// Strokes the outline of the whole scope rect.
894    fn draw_rect_stroked(&mut self, brush: Brush, stroke: Stroke);
895    /// As `draw_rect_stroked`, composited with `blend_mode` instead of `SrcOver`.
896    fn draw_rect_stroked_blend(&mut self, brush: Brush, stroke: Stroke, blend_mode: BlendMode);
897    /// Strokes the outline of `rect`.
898    fn draw_rect_at_stroked(&mut self, rect: Rect, brush: Brush, stroke: Stroke);
899    /// As `draw_rect_at_stroked`, composited with `blend_mode` instead of `SrcOver`.
900    fn draw_rect_at_stroked_blend(
901        &mut self,
902        rect: Rect,
903        brush: Brush,
904        stroke: Stroke,
905        blend_mode: BlendMode,
906    );
907    /// Strokes the outline of the whole scope rect with rounded corners.
908    fn draw_round_rect_stroked(&mut self, brush: Brush, radii: CornerRadii, stroke: Stroke);
909    /// As `draw_round_rect_stroked`, composited with `blend_mode` instead of `SrcOver`.
910    fn draw_round_rect_stroked_blend(
911        &mut self,
912        brush: Brush,
913        radii: CornerRadii,
914        stroke: Stroke,
915        blend_mode: BlendMode,
916    );
917    /// Strokes the outline of `rect` with rounded corners.
918    fn draw_round_rect_at_stroked(
919        &mut self,
920        rect: Rect,
921        brush: Brush,
922        radii: CornerRadii,
923        stroke: Stroke,
924    );
925    /// As `draw_round_rect_at_stroked`, composited with `blend_mode` instead of `SrcOver`.
926    fn draw_round_rect_at_stroked_blend(
927        &mut self,
928        rect: Rect,
929        brush: Brush,
930        radii: CornerRadii,
931        stroke: Stroke,
932        blend_mode: BlendMode,
933    );
934    /// Strokes a circle outline. Lowers to a stroked rounded rect, so it shares
935    /// the fill pipeline and batches with every other shape.
936    fn draw_circle_stroked(&mut self, brush: Brush, center: Point, radius: f32, stroke: Stroke);
937    /// As `draw_circle_stroked`, composited with `blend_mode` instead of `SrcOver`.
938    fn draw_circle_stroked_blend(
939        &mut self,
940        brush: Brush,
941        center: Point,
942        radius: f32,
943        stroke: Stroke,
944        blend_mode: BlendMode,
945    );
946
947    /// Strokes a circular arc.
948    ///
949    /// Angles are in **radians**, `0` points along **+X**, and increasing
950    /// angles sweep **clockwise on screen** (Cranpose uses y-down device
951    /// coordinates, so this matches `atan2(dy, dx)` and the sweep-gradient
952    /// brush). A negative `sweep_angle` sweeps counter-clockwise; `|sweep| >=
953    /// 2π` draws a closed ring.
954    ///
955    /// The stroke is centered on `radius`, so the band covers
956    /// `radius ± width/2`. [`StrokeCap`](crate::StrokeCap) shapes the two ends.
957    /// Nothing is drawn for a zero sweep, a non-positive width, or non-finite
958    /// input.
959    fn draw_arc(
960        &mut self,
961        brush: Brush,
962        center: Point,
963        radius: f32,
964        start_angle: f32,
965        sweep_angle: f32,
966        stroke: Stroke,
967    );
968    /// As `draw_arc`, composited with `blend_mode` instead of `SrcOver`.
969    #[expect(clippy::too_many_arguments, reason = "Compose's parameters")]
970    fn draw_arc_blend(
971        &mut self,
972        brush: Brush,
973        center: Point,
974        radius: f32,
975        start_angle: f32,
976        sweep_angle: f32,
977        stroke: Stroke,
978        blend_mode: BlendMode,
979    );
980
981    /// Strokes the straight segment from `start` to `end`, centred on it and
982    /// `stroke.width` wide, its ends shaped by `stroke.cap`: Compose's
983    /// `drawLine(brush, start, end, strokeWidth, cap)`. Nothing is drawn
984    /// for a non-positive width, a non-finite end, or a segment of no length
985    /// between butt caps; round and square caps draw a dot there.
986    fn draw_line(&mut self, brush: Brush, start: Point, end: Point, stroke: Stroke);
987    /// As `draw_line`, composited with `blend_mode` instead of `SrcOver`.
988    fn draw_line_blend(
989        &mut self,
990        brush: Brush,
991        start: Point,
992        end: Point,
993        stroke: Stroke,
994        blend_mode: BlendMode,
995    );
996
997    /// Fills or strokes `path` with `brush`: Compose's
998    /// `drawPath(path, brush, style)`. A fill closes every contour and
999    /// rasterizes it as [`draw_vector_path`](Self::draw_vector_path) does. A
1000    /// stroke covers each flattened edge as a line, capped at an open
1001    /// contour's ends and joined at its corners as [`crate::for_each_stroke_line`]
1002    /// describes; a dashed stroke covers the dashes its effect cuts. A stroke
1003    /// that is not opaque, or blends other than source-over, fills what its
1004    /// lines cover once, so its corners are no deeper than its edges.
1005    fn draw_path(&mut self, path: &Path, brush: Brush, style: DrawStyle);
1006    /// As `draw_path`, composited with `blend_mode` instead of `SrcOver`.
1007    fn draw_path_blend(
1008        &mut self,
1009        path: &Path,
1010        brush: Brush,
1011        style: DrawStyle,
1012        blend_mode: BlendMode,
1013    );
1014
1015    /// Fills an annular sector — the region between `inner_radius` and
1016    /// `outer_radius`, limited to an angular sweep, with **flat radial ends**.
1017    ///
1018    /// This is the shape a stroked arc cannot express: its ends are straight
1019    /// lines through the center, not caps. `inner_radius = 0` fills a pie
1020    /// wedge. Angle convention is identical to [`draw_arc`](Self::draw_arc).
1021    /// Nothing is drawn when `inner_radius >= outer_radius`, the sweep is zero,
1022    /// or any input is non-finite.
1023    fn draw_annular_sector(
1024        &mut self,
1025        brush: Brush,
1026        center: Point,
1027        inner_radius: f32,
1028        outer_radius: f32,
1029        start_angle: f32,
1030        sweep_angle: f32,
1031    );
1032    /// As `draw_annular_sector`, composited with `blend_mode` instead of `SrcOver`.
1033    #[expect(clippy::too_many_arguments, reason = "Compose's parameters")]
1034    fn draw_annular_sector_blend(
1035        &mut self,
1036        brush: Brush,
1037        center: Point,
1038        inner_radius: f32,
1039        outer_radius: f32,
1040        start_angle: f32,
1041        sweep_angle: f32,
1042        blend_mode: BlendMode,
1043    );
1044
1045    /// Draws `image` stretched over the whole scope rect.
1046    fn draw_image(&mut self, image: ImageBitmap);
1047    /// As `draw_image`, composited with `blend_mode` instead of `SrcOver`.
1048    fn draw_image_blend(&mut self, image: ImageBitmap, blend_mode: BlendMode);
1049    /// Draws `image` stretched into `rect`, with `alpha` from 0.0 to 1.0 and an optional
1050    /// `color_filter`.
1051    fn draw_image_at(
1052        &mut self,
1053        rect: Rect,
1054        image: ImageBitmap,
1055        alpha: f32,
1056        color_filter: Option<ColorFilter>,
1057    );
1058    /// As `draw_image_at`, sampling the image with `sampling` instead of nearest-neighbor.
1059    fn draw_image_at_sampled(
1060        &mut self,
1061        rect: Rect,
1062        image: ImageBitmap,
1063        alpha: f32,
1064        color_filter: Option<ColorFilter>,
1065        sampling: ImageSampling,
1066    );
1067    /// As `draw_image_at`, composited with `blend_mode` instead of `SrcOver`.
1068    fn draw_image_at_blend(
1069        &mut self,
1070        rect: Rect,
1071        image: ImageBitmap,
1072        alpha: f32,
1073        color_filter: Option<ColorFilter>,
1074        blend_mode: BlendMode,
1075    );
1076    /// Draws a sub-region of an image. `src_rect` is in image-pixel
1077    /// coordinates; `dst_rect` is in scope coordinates.
1078    fn draw_image_src(
1079        &mut self,
1080        image: ImageBitmap,
1081        src_rect: Rect,
1082        dst_rect: Rect,
1083        alpha: f32,
1084        color_filter: Option<ColorFilter>,
1085    );
1086    /// As `draw_image_src`, sampling the source region with `sampling` instead of nearest-neighbor.
1087    fn draw_image_src_sampled(
1088        &mut self,
1089        image: ImageBitmap,
1090        src_rect: Rect,
1091        dst_rect: Rect,
1092        alpha: f32,
1093        color_filter: Option<ColorFilter>,
1094        sampling: ImageSampling,
1095    );
1096    /// As `draw_image_src_sampled`, composited with `blend_mode` instead of `SrcOver`.
1097    fn draw_image_src_blend(
1098        &mut self,
1099        image: ImageBitmap,
1100        src_rect: Rect,
1101        dst_rect: Rect,
1102        alpha: f32,
1103        color_filter: Option<ColorFilter>,
1104        blend_mode: BlendMode,
1105    );
1106    /// Fills a parsed SVG path in scope coordinates (path units are dp).
1107    ///
1108    /// The fill is rasterized on the CPU into a supersampled, anti-aliased
1109    /// bitmap covering the path bounds and drawn as an image primitive, so
1110    /// it works on every render backend. Parse the path once with
1111    /// [`crate::VectorPath::parse`] and redraw it per frame. A gradient brush
1112    /// resolves against the scope's size, as other fills do.
1113    fn draw_vector_path(&mut self, path: &crate::VectorPath, brush: Brush);
1114    /// Parses SVG path data (the `d` attribute syntax: `M/m L/l H/h V/v
1115    /// C/c S/s Q/q T/t A/a Z/z`) and fills it. Invalid path data draws
1116    /// nothing. Prefer [`crate::VectorPath::parse`] +
1117    /// [`draw_vector_path`](Self::draw_vector_path) to avoid re-parsing
1118    /// and to surface parse errors.
1119    fn draw_svg_path(&mut self, d: &str, brush: Brush) {
1120        if let Ok(path) = crate::VectorPath::parse(d) {
1121            self.draw_vector_path(&path, brush);
1122        }
1123    }
1124
1125    /// The block size, line height and first baseline `text` would occupy in
1126    /// `style`.
1127    ///
1128    /// Free to call repeatedly: the underlying text stack caches metrics on
1129    /// `(text, style)`, so a game can measure every label every frame to center
1130    /// it without touching a font file more than once.
1131    fn measure_text(&self, text: &str, style: &DrawTextStyle) -> TextMeasurement;
1132
1133    /// Draws `text` inside the whole scope rect, positioned by
1134    /// [`DrawTextStyle::align`] and [`DrawTextStyle::vertical_align`].
1135    fn draw_text(&mut self, brush: Brush, text: &str, style: &DrawTextStyle) {
1136        self.draw_text_at(Rect::from_size(self.size()), brush, text, style);
1137    }
1138
1139    /// Draws `text` inside `rect`, positioned by [`DrawTextStyle::align`] and
1140    /// [`DrawTextStyle::vertical_align`].
1141    ///
1142    /// The glyphs are *not* clipped to `rect` — it is an alignment box, not a
1143    /// viewport. A `rect` narrower than the measured text overflows in the
1144    /// direction the alignment implies; clip the layer if that matters.
1145    fn draw_text_at(&mut self, rect: Rect, brush: Brush, text: &str, style: &DrawTextStyle);
1146
1147    /// Draws `text` with the top-left corner of its block at `top_left`.
1148    ///
1149    /// Alignment is a no-op here because the box is the measurement — this is
1150    /// the "I already know where it goes" form, and the one to pair with
1151    /// [`measure_text`](Self::measure_text) for hand-rolled centering.
1152    fn draw_text_from(&mut self, top_left: Point, brush: Brush, text: &str, style: &DrawTextStyle);
1153
1154    /// Draws `block` with every primitive it records, text and images
1155    /// included, placed by `transform`'s steps in order, each inside the
1156    /// ones before it: Compose's `withTransform`. The block sees the scope
1157    /// size the steps leave. Content that `draw_content` draws inside the
1158    /// block keeps its place: only the block's own draws move.
1159    fn with_transform(
1160        &mut self,
1161        transform: &[DrawTransform<'_>],
1162        block: &mut dyn FnMut(&mut dyn DrawScope),
1163    );
1164
1165    /// Draws `block` moved by `dx`, `dy`. Compose's `translate`.
1166    fn translate(&mut self, dx: f32, dy: f32, block: &mut dyn FnMut(&mut dyn DrawScope)) {
1167        self.with_transform(&[DrawTransform::Translate { dx, dy }], block);
1168    }
1169
1170    /// Draws `block` scaled by `scale_x`, `scale_y` about `pivot`, which
1171    /// stays where it is. Compose's `scale`.
1172    fn scale(
1173        &mut self,
1174        scale_x: f32,
1175        scale_y: f32,
1176        pivot: Point,
1177        block: &mut dyn FnMut(&mut dyn DrawScope),
1178    ) {
1179        self.with_transform(
1180            &[DrawTransform::Scale {
1181                scale_x,
1182                scale_y,
1183                pivot,
1184            }],
1185            block,
1186        );
1187    }
1188
1189    /// Draws `block` turned clockwise by `degrees` about `pivot`. Compose's
1190    /// `rotate`.
1191    fn rotate(&mut self, degrees: f32, pivot: Point, block: &mut dyn FnMut(&mut dyn DrawScope)) {
1192        self.with_transform(&[DrawTransform::Rotate { degrees, pivot }], block);
1193    }
1194
1195    /// Draws `block` in the scope shrunk by the four insets: it sees the
1196    /// smaller size and draws moved by `left`, `top`. Compose's `inset`.
1197    fn inset(
1198        &mut self,
1199        left: f32,
1200        top: f32,
1201        right: f32,
1202        bottom: f32,
1203        block: &mut dyn FnMut(&mut dyn DrawScope),
1204    ) {
1205        self.with_transform(
1206            &[DrawTransform::Inset {
1207                left,
1208                top,
1209                right,
1210                bottom,
1211            }],
1212            block,
1213        );
1214    }
1215
1216    /// Draws `block` cut to `rect`. Compose's `clipRect`.
1217    fn clip_rect(&mut self, rect: Rect, block: &mut dyn FnMut(&mut dyn DrawScope)) {
1218        self.with_transform(&[DrawTransform::ClipRect(rect)], block);
1219    }
1220
1221    /// Draws `block` cut to the fill of `path`, its edge anti-aliased.
1222    /// Compose's `clipPath`.
1223    fn clip_path(&mut self, path: &Path, block: &mut dyn FnMut(&mut dyn DrawScope)) {
1224        self.with_transform(&[DrawTransform::ClipPath(path)], block);
1225    }
1226
1227    /// Consumes the scope and returns the recorded primitives in draw order, including the
1228    /// `Content` markers.
1229    fn into_primitives(self) -> Vec<DrawPrimitive>;
1230}
1231
1232/// The `DrawScope` the framework passes to draw closures. It records the primitives drawn in draw
1233/// order, in place, into a [`CommandRecording`] its caller holds: a recording
1234/// kept from an earlier frame is drawn again in the storage it has.
1235pub struct DrawScopeDefault<'a> {
1236    size: Size,
1237    recording: CommandRecorder<'a>,
1238    text_measurer: Option<Rc<dyn DrawTextMeasurer>>,
1239}
1240
1241impl<'a> DrawScopeDefault<'a> {
1242    /// Creates a scope of `size` recording into `recording` anew, without a
1243    /// text measurer, so text is measured by an estimate.
1244    pub fn new(size: Size, recording: &'a mut CommandRecording) -> Self {
1245        Self::with_storage(size, None, recording)
1246    }
1247
1248    /// A scope that measures text with the app's fonts.
1249    ///
1250    /// The framework calls this for every draw closure it runs; `new` exists
1251    /// for callers that never draw text.
1252    pub fn with_text_measurer(
1253        size: Size,
1254        text_measurer: Rc<dyn DrawTextMeasurer>,
1255        recording: &'a mut CommandRecording,
1256    ) -> Self {
1257        Self::with_storage(size, Some(text_measurer), recording)
1258    }
1259
1260    fn with_storage(
1261        size: Size,
1262        text_measurer: Option<Rc<dyn DrawTextMeasurer>>,
1263        recording: &'a mut CommandRecording,
1264    ) -> Self {
1265        Self {
1266            size,
1267            recording: recording.record(),
1268            text_measurer,
1269        }
1270    }
1271
1272    /// How many `draw_content` markers this scope has recorded.
1273    pub fn content_marker_count(&self) -> u32 {
1274        self.recording.content_markers()
1275    }
1276
1277    /// Runs `draw` in this scope's rect shrunk by `insets`, where a draw
1278    /// modifier placed after layout padding draws: `draw` sees the inner
1279    /// size, and what it records lands offset by the leading insets.
1280    pub fn draw_inset(&mut self, insets: EdgeInsets, draw: impl FnOnce(&mut DrawScopeDefault<'_>)) {
1281        let inner = insets.inset_rect(self.size);
1282        let mut recording = CommandRecording::default();
1283        let mut scope = DrawScopeDefault::with_storage(
1284            inner.size(),
1285            self.text_measurer.clone(),
1286            &mut recording,
1287        );
1288        draw(&mut scope);
1289        scope.finish();
1290        self.push_recorded(crate::translate_recorded(
1291            recording.primitives_with_markers(),
1292            inner.x,
1293            inner.y,
1294        ));
1295    }
1296
1297    /// Records primitives already built, as if each had been drawn here.
1298    pub fn push_recorded(&mut self, primitives: impl IntoIterator<Item = DrawPrimitive>) {
1299        for primitive in primitives {
1300            self.recording.push_primitive(primitive);
1301        }
1302    }
1303
1304    /// Completes the recording in the storage the scope records into.
1305    pub fn finish(self) {
1306        self.recording.finish();
1307    }
1308
1309    fn push_blended_primitive(&mut self, primitive: DrawPrimitive, blend_mode: BlendMode) {
1310        if blend_mode != BlendMode::SrcOver {
1311            self.recording.push_other(DrawPrimitive::Blend {
1312                primitive: Box::new(primitive),
1313                blend_mode,
1314            });
1315            return;
1316        }
1317        self.recording.push_other(primitive);
1318    }
1319
1320    #[inline]
1321    fn push_arc(&mut self, args: &ArcRecordArgs<'_>) {
1322        let geometry = normalized_band(args);
1323        if geometry.is_degenerate() {
1324            return;
1325        }
1326        self.recording.push_scope_arc(args, &geometry);
1327    }
1328
1329    /// Draws `block` under the `rest` of its steps in a group that `mask`'s
1330    /// fill cuts. The group ends with a mask that erases what lies outside
1331    /// the fill: a blend every renderer draws, where keeping what lies inside
1332    /// is not.
1333    fn with_path_mask(
1334        &mut self,
1335        mask: &crate::VectorPath,
1336        rest: &[DrawTransform<'_>],
1337        block: &mut dyn FnMut(&mut dyn DrawScope),
1338    ) {
1339        let rect = vector_mask_rect(mask.bounds());
1340        self.recording.push_group_start(DrawGroup::masked(rect));
1341        self.with_transform(rest, block);
1342        record_vector_path(
1343            &mut self.recording,
1344            mask,
1345            &Brush::solid(Color::BLACK),
1346            rect,
1347            BlendMode::DstOut,
1348            PathSide::Outside,
1349        );
1350        self.recording.push_group_end();
1351    }
1352}
1353
1354impl DrawScope for DrawScopeDefault<'_> {
1355    fn size(&self) -> Size {
1356        self.size
1357    }
1358
1359    fn with_transform(
1360        &mut self,
1361        transform: &[DrawTransform<'_>],
1362        block: &mut dyn FnMut(&mut dyn DrawScope),
1363    ) {
1364        let Some((step, rest)) = transform.split_first() else {
1365            block(self);
1366            return;
1367        };
1368        let outer = self.size;
1369        let (group, size) = match *step {
1370            DrawTransform::Translate { dx, dy } => (DrawGroup::moved(dx, dy, outer), outer),
1371            DrawTransform::Scale {
1372                scale_x,
1373                scale_y,
1374                pivot,
1375            } => (DrawGroup::about(pivot, scale_x, scale_y, 0.0, outer), outer),
1376            DrawTransform::Rotate { degrees, pivot } => {
1377                (DrawGroup::about(pivot, 1.0, 1.0, degrees, outer), outer)
1378            }
1379            DrawTransform::Inset {
1380                left,
1381                top,
1382                right,
1383                bottom,
1384            } => {
1385                let inner = Size::new(
1386                    (outer.width - left - right).max(0.0),
1387                    (outer.height - top - bottom).max(0.0),
1388                );
1389                (DrawGroup::moved(left, top, inner), inner)
1390            }
1391            DrawTransform::ClipRect(rect) => (DrawGroup::clipped(rect), outer),
1392            DrawTransform::ClipPath(path) => {
1393                let mask = path.to_vector_path(PathFillRule::NonZero);
1394                if !mask.is_empty() {
1395                    self.with_path_mask(&mask, rest, block);
1396                    return;
1397                }
1398                // A path with no fill leaves nothing of the block.
1399                (DrawGroup::clipped(Rect::EMPTY), outer)
1400            }
1401        };
1402        self.recording.push_group_start(group);
1403        self.size = size;
1404        self.with_transform(rest, block);
1405        self.size = outer;
1406        self.recording.push_group_end();
1407    }
1408
1409    fn draw_content(&mut self) {
1410        self.recording.push_content();
1411    }
1412
1413    fn draw_rect(&mut self, brush: Brush) {
1414        self.draw_rect_blend(brush, BlendMode::SrcOver);
1415    }
1416
1417    fn draw_rect_blend(&mut self, brush: Brush, blend_mode: BlendMode) {
1418        self.recording
1419            .push_rect(Rect::from_size(self.size), &brush, None, blend_mode);
1420    }
1421
1422    fn draw_rect_at(&mut self, rect: Rect, brush: Brush) {
1423        self.draw_rect_at_blend(rect, brush, BlendMode::SrcOver);
1424    }
1425
1426    fn draw_rect_at_blend(&mut self, rect: Rect, brush: Brush, blend_mode: BlendMode) {
1427        self.recording.push_rect(rect, &brush, None, blend_mode);
1428    }
1429
1430    fn draw_round_rect(&mut self, brush: Brush, radii: CornerRadii) {
1431        self.draw_round_rect_blend(brush, radii, BlendMode::SrcOver);
1432    }
1433
1434    fn draw_round_rect_blend(&mut self, brush: Brush, radii: CornerRadii, blend_mode: BlendMode) {
1435        self.recording
1436            .push_round_rect(Rect::from_size(self.size), &brush, radii, None, blend_mode);
1437    }
1438
1439    fn draw_round_rect_at(&mut self, rect: Rect, brush: Brush, radii: CornerRadii) {
1440        self.recording
1441            .push_round_rect(rect, &brush, radii, None, BlendMode::SrcOver);
1442    }
1443
1444    fn draw_rect_stroked(&mut self, brush: Brush, stroke: Stroke) {
1445        self.draw_rect_stroked_blend(brush, stroke, BlendMode::SrcOver);
1446    }
1447
1448    fn draw_rect_stroked_blend(&mut self, brush: Brush, stroke: Stroke, blend_mode: BlendMode) {
1449        self.draw_rect_at_stroked_blend(Rect::from_size(self.size), brush, stroke, blend_mode);
1450    }
1451
1452    fn draw_rect_at_stroked(&mut self, rect: Rect, brush: Brush, stroke: Stroke) {
1453        self.draw_rect_at_stroked_blend(rect, brush, stroke, BlendMode::SrcOver);
1454    }
1455
1456    fn draw_rect_at_stroked_blend(
1457        &mut self,
1458        rect: Rect,
1459        brush: Brush,
1460        stroke: Stroke,
1461        blend_mode: BlendMode,
1462    ) {
1463        if !stroke.is_visible() {
1464            return;
1465        }
1466        self.recording
1467            .push_rect(rect, &brush, Some(stroke), blend_mode);
1468    }
1469
1470    fn draw_round_rect_stroked(&mut self, brush: Brush, radii: CornerRadii, stroke: Stroke) {
1471        self.draw_round_rect_stroked_blend(brush, radii, stroke, BlendMode::SrcOver);
1472    }
1473
1474    fn draw_round_rect_stroked_blend(
1475        &mut self,
1476        brush: Brush,
1477        radii: CornerRadii,
1478        stroke: Stroke,
1479        blend_mode: BlendMode,
1480    ) {
1481        self.draw_round_rect_at_stroked_blend(
1482            Rect::from_size(self.size),
1483            brush,
1484            radii,
1485            stroke,
1486            blend_mode,
1487        );
1488    }
1489
1490    fn draw_round_rect_at_stroked(
1491        &mut self,
1492        rect: Rect,
1493        brush: Brush,
1494        radii: CornerRadii,
1495        stroke: Stroke,
1496    ) {
1497        self.draw_round_rect_at_stroked_blend(rect, brush, radii, stroke, BlendMode::SrcOver);
1498    }
1499
1500    fn draw_round_rect_at_stroked_blend(
1501        &mut self,
1502        rect: Rect,
1503        brush: Brush,
1504        radii: CornerRadii,
1505        stroke: Stroke,
1506        blend_mode: BlendMode,
1507    ) {
1508        if !stroke.is_visible() {
1509            return;
1510        }
1511        self.recording
1512            .push_round_rect(rect, &brush, radii, Some(stroke), blend_mode);
1513    }
1514
1515    fn draw_circle_stroked(&mut self, brush: Brush, center: Point, radius: f32, stroke: Stroke) {
1516        self.draw_circle_stroked_blend(brush, center, radius, stroke, BlendMode::SrcOver);
1517    }
1518
1519    fn draw_circle_stroked_blend(
1520        &mut self,
1521        brush: Brush,
1522        center: Point,
1523        radius: f32,
1524        stroke: Stroke,
1525        blend_mode: BlendMode,
1526    ) {
1527        if !stroke.is_visible() || !radius.is_finite() {
1528            return;
1529        }
1530        let radius = radius.max(0.0);
1531        let diameter = radius * 2.0;
1532        self.draw_round_rect_at_stroked_blend(
1533            Rect {
1534                x: center.x - radius,
1535                y: center.y - radius,
1536                width: diameter,
1537                height: diameter,
1538            },
1539            brush,
1540            CornerRadii::uniform(radius),
1541            stroke,
1542            blend_mode,
1543        );
1544    }
1545
1546    fn draw_arc(
1547        &mut self,
1548        brush: Brush,
1549        center: Point,
1550        radius: f32,
1551        start_angle: f32,
1552        sweep_angle: f32,
1553        stroke: Stroke,
1554    ) {
1555        self.draw_arc_blend(
1556            brush,
1557            center,
1558            radius,
1559            start_angle,
1560            sweep_angle,
1561            stroke,
1562            BlendMode::SrcOver,
1563        );
1564    }
1565
1566    fn draw_arc_blend(
1567        &mut self,
1568        brush: Brush,
1569        center: Point,
1570        radius: f32,
1571        start_angle: f32,
1572        sweep_angle: f32,
1573        stroke: Stroke,
1574        blend_mode: BlendMode,
1575    ) {
1576        if !stroke.is_visible() {
1577            return;
1578        }
1579        self.push_arc(&ArcRecordArgs {
1580            brush: &brush,
1581            center,
1582            radius,
1583            start_angle,
1584            sweep_angle,
1585            stroke: Some(stroke),
1586            inner_radius: 0.0,
1587            blend_mode,
1588        });
1589    }
1590
1591    fn draw_line(&mut self, brush: Brush, start: Point, end: Point, stroke: Stroke) {
1592        self.draw_line_blend(brush, start, end, stroke, BlendMode::SrcOver);
1593    }
1594
1595    fn draw_line_blend(
1596        &mut self,
1597        brush: Brush,
1598        start: Point,
1599        end: Point,
1600        stroke: Stroke,
1601        blend_mode: BlendMode,
1602    ) {
1603        self.recording
1604            .line_run(&brush, stroke, blend_mode)
1605            .push(start, end, stroke.cap);
1606    }
1607
1608    fn draw_path(&mut self, path: &Path, brush: Brush, style: DrawStyle) {
1609        self.draw_path_blend(path, brush, style, BlendMode::SrcOver);
1610    }
1611
1612    fn draw_path_blend(
1613        &mut self,
1614        path: &Path,
1615        brush: Brush,
1616        style: DrawStyle,
1617        blend_mode: BlendMode,
1618    ) {
1619        record_path(
1620            &mut self.recording,
1621            self.size,
1622            path,
1623            &brush,
1624            style,
1625            blend_mode,
1626        );
1627    }
1628
1629    fn draw_annular_sector(
1630        &mut self,
1631        brush: Brush,
1632        center: Point,
1633        inner_radius: f32,
1634        outer_radius: f32,
1635        start_angle: f32,
1636        sweep_angle: f32,
1637    ) {
1638        self.draw_annular_sector_blend(
1639            brush,
1640            center,
1641            inner_radius,
1642            outer_radius,
1643            start_angle,
1644            sweep_angle,
1645            BlendMode::SrcOver,
1646        );
1647    }
1648
1649    fn draw_annular_sector_blend(
1650        &mut self,
1651        brush: Brush,
1652        center: Point,
1653        inner_radius: f32,
1654        outer_radius: f32,
1655        start_angle: f32,
1656        sweep_angle: f32,
1657        blend_mode: BlendMode,
1658    ) {
1659        self.push_arc(&ArcRecordArgs {
1660            brush: &brush,
1661            center,
1662            radius: outer_radius,
1663            start_angle,
1664            sweep_angle,
1665            stroke: None,
1666            inner_radius,
1667            blend_mode,
1668        });
1669    }
1670
1671    fn draw_circle(&mut self, brush: Brush, center: Point, radius: f32) {
1672        self.draw_circle_blend(brush, center, radius, BlendMode::SrcOver);
1673    }
1674
1675    fn draw_circle_blend(
1676        &mut self,
1677        brush: Brush,
1678        center: Point,
1679        radius: f32,
1680        blend_mode: BlendMode,
1681    ) {
1682        let radius = radius.max(0.0);
1683        let diameter = radius * 2.0;
1684        self.recording.push_round_rect(
1685            Rect {
1686                x: center.x - radius,
1687                y: center.y - radius,
1688                width: diameter,
1689                height: diameter,
1690            },
1691            &brush,
1692            CornerRadii::uniform(radius),
1693            None,
1694            blend_mode,
1695        );
1696    }
1697
1698    fn draw_image(&mut self, image: ImageBitmap) {
1699        self.draw_image_blend(image, BlendMode::SrcOver);
1700    }
1701
1702    fn draw_image_blend(&mut self, image: ImageBitmap, blend_mode: BlendMode) {
1703        self.push_blended_primitive(
1704            DrawPrimitive::Image {
1705                rect: Rect::from_size(self.size),
1706                image,
1707                alpha: 1.0,
1708                color_filter: None,
1709                sampling: ImageSampling::Nearest,
1710                src_rect: None,
1711            },
1712            blend_mode,
1713        );
1714    }
1715
1716    fn draw_image_at(
1717        &mut self,
1718        rect: Rect,
1719        image: ImageBitmap,
1720        alpha: f32,
1721        color_filter: Option<ColorFilter>,
1722    ) {
1723        self.draw_image_at_sampled(rect, image, alpha, color_filter, ImageSampling::Nearest);
1724    }
1725
1726    fn draw_image_at_sampled(
1727        &mut self,
1728        rect: Rect,
1729        image: ImageBitmap,
1730        alpha: f32,
1731        color_filter: Option<ColorFilter>,
1732        sampling: ImageSampling,
1733    ) {
1734        self.push_blended_primitive(
1735            DrawPrimitive::Image {
1736                rect,
1737                image,
1738                alpha: alpha.clamp(0.0, 1.0),
1739                color_filter,
1740                sampling,
1741                src_rect: None,
1742            },
1743            BlendMode::SrcOver,
1744        );
1745    }
1746
1747    fn draw_image_at_blend(
1748        &mut self,
1749        rect: Rect,
1750        image: ImageBitmap,
1751        alpha: f32,
1752        color_filter: Option<ColorFilter>,
1753        blend_mode: BlendMode,
1754    ) {
1755        self.push_blended_primitive(
1756            DrawPrimitive::Image {
1757                rect,
1758                image,
1759                alpha: alpha.clamp(0.0, 1.0),
1760                color_filter,
1761                sampling: ImageSampling::Nearest,
1762                src_rect: None,
1763            },
1764            blend_mode,
1765        );
1766    }
1767
1768    fn draw_image_src(
1769        &mut self,
1770        image: ImageBitmap,
1771        src_rect: Rect,
1772        dst_rect: Rect,
1773        alpha: f32,
1774        color_filter: Option<ColorFilter>,
1775    ) {
1776        self.draw_image_src_blend(
1777            image,
1778            src_rect,
1779            dst_rect,
1780            alpha,
1781            color_filter,
1782            BlendMode::SrcOver,
1783        );
1784    }
1785
1786    fn draw_image_src_sampled(
1787        &mut self,
1788        image: ImageBitmap,
1789        src_rect: Rect,
1790        dst_rect: Rect,
1791        alpha: f32,
1792        color_filter: Option<ColorFilter>,
1793        sampling: ImageSampling,
1794    ) {
1795        self.push_blended_primitive(
1796            DrawPrimitive::Image {
1797                rect: dst_rect,
1798                image,
1799                alpha: alpha.clamp(0.0, 1.0),
1800                color_filter,
1801                sampling,
1802                src_rect: Some(src_rect),
1803            },
1804            BlendMode::SrcOver,
1805        );
1806    }
1807
1808    fn draw_image_src_blend(
1809        &mut self,
1810        image: ImageBitmap,
1811        src_rect: Rect,
1812        dst_rect: Rect,
1813        alpha: f32,
1814        color_filter: Option<ColorFilter>,
1815        blend_mode: BlendMode,
1816    ) {
1817        self.push_blended_primitive(
1818            DrawPrimitive::Image {
1819                rect: dst_rect,
1820                image,
1821                alpha: alpha.clamp(0.0, 1.0),
1822                color_filter,
1823                sampling: ImageSampling::Nearest,
1824                src_rect: Some(src_rect),
1825            },
1826            blend_mode,
1827        );
1828    }
1829
1830    fn draw_vector_path(&mut self, path: &crate::VectorPath, brush: Brush) {
1831        record_vector_path(
1832            &mut self.recording,
1833            path,
1834            &brush,
1835            Rect::from_size(self.size),
1836            BlendMode::SrcOver,
1837            PathSide::Inside,
1838        );
1839    }
1840
1841    fn measure_text(&self, text: &str, style: &DrawTextStyle) -> TextMeasurement {
1842        measured_text(self.text_measurer.as_deref(), text, style).measurement
1843    }
1844
1845    fn draw_text_at(&mut self, rect: Rect, brush: Brush, text: &str, style: &DrawTextStyle) {
1846        let at = TextBlockAt::Aligned(rect);
1847        let measurer = self.text_measurer.as_deref();
1848        if let Some(text) = text_primitive(measurer, at, brush, text, style) {
1849            self.recording.push_other(text);
1850        }
1851    }
1852
1853    fn draw_text_from(&mut self, top_left: Point, brush: Brush, text: &str, style: &DrawTextStyle) {
1854        let at = TextBlockAt::From(top_left);
1855        let measurer = self.text_measurer.as_deref();
1856        if let Some(text) = text_primitive(measurer, at, brush, text, style) {
1857            self.recording.push_other(text);
1858        }
1859    }
1860
1861    fn into_primitives(self) -> Vec<DrawPrimitive> {
1862        self.recording.into_primitives()
1863    }
1864}
1865
1866#[cfg(test)]
1867#[path = "tests/geometry_tests.rs"]
1868mod tests;