Skip to main content

sui_scene/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::{collections::HashMap, sync::Arc};
4
5use sui_core::{
6    Color, ColorSpace, DirtyRegion, Error, ImageHandle, Path, PathBuilder, PathElement, Point,
7    Rect, Result, Size, Transform, Vector, WidgetId, WindowId,
8};
9use sui_text::{FontRegistry, ShapedText, ShapedTextWindow, TextLayoutRegistry, TextRun};
10
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct Border {
13    pub width: f32,
14    pub color: Color,
15}
16
17/// Where a shadow falls relative to the rounded box that casts it.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
19pub enum ShadowPlacement {
20    /// Around the box and beneath it, as CSS `box-shadow`. A fill drawn over
21    /// the box hides the part beneath it.
22    #[default]
23    Behind,
24    /// Around the box only, leaving the box clear. The shadow looks the same
25    /// under a translucent fill, and it can be drawn over the box: a glow.
26    Outside,
27    /// Inside the box, along its edges, as CSS `box-shadow: inset`.
28    Inside,
29}
30
31/// A soft shadow of a rounded box, as CSS `box-shadow` describes one.
32#[derive(Debug, Clone, Copy, PartialEq)]
33pub struct ShadowParams {
34    pub offset_x: f32,
35    pub offset_y: f32,
36    /// The blur radius, as in CSS: the shadow's edge is blurred by a Gaussian
37    /// whose standard deviation is half of it.
38    pub blur: f32,
39    /// How far the shadow's box grows past the casting box before it is
40    /// blurred; an inside shadow's box shrinks by it instead.
41    pub spread: f32,
42    pub color: Color,
43    pub placement: ShadowPlacement,
44}
45
46impl ShadowParams {
47    /// A shadow drawn behind its box.
48    pub const fn new(offset_x: f32, offset_y: f32, blur: f32, spread: f32, color: Color) -> Self {
49        Self {
50            offset_x,
51            offset_y,
52            blur,
53            spread,
54            color,
55            placement: ShadowPlacement::Behind,
56        }
57    }
58
59    /// A glow: a halo with no offset, drawn outside its box only.
60    pub const fn glow(blur: f32, spread: f32, color: Color) -> Self {
61        Self::new(0.0, 0.0, blur, spread, color).with_placement(ShadowPlacement::Outside)
62    }
63
64    /// An inner shadow, as CSS `box-shadow: inset`.
65    pub const fn inset(offset_x: f32, offset_y: f32, blur: f32, spread: f32, color: Color) -> Self {
66        Self::new(offset_x, offset_y, blur, spread, color).with_placement(ShadowPlacement::Inside)
67    }
68
69    pub const fn with_placement(mut self, placement: ShadowPlacement) -> Self {
70        self.placement = placement;
71        self
72    }
73
74    /// The Gaussian's standard deviation.
75    pub fn sigma(&self) -> f32 {
76        self.blur.max(0.0) * 0.5
77    }
78
79    /// Logical-pixel reach beyond the box's edge, where the Gaussian has all
80    /// but faded out; used to size the shadow's quad and bounds. An inside
81    /// shadow stays within its box.
82    pub fn extent(&self) -> f32 {
83        match self.placement {
84            ShadowPlacement::Inside => 0.0,
85            ShadowPlacement::Behind | ShadowPlacement::Outside => {
86                3.0 * self.sigma()
87                    + self.spread.max(0.0)
88                    + self.offset_x.abs().max(self.offset_y.abs())
89            }
90        }
91    }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq)]
95pub struct GradientStop {
96    pub offset: f32,
97    pub color: Color,
98}
99
100pub const MAX_GRADIENT_STOPS: usize = 8;
101
102#[derive(Debug, Clone, PartialEq)]
103pub enum Brush {
104    Solid(Color),
105    LinearGradient {
106        start: Point,
107        end: Point,
108        stops: Vec<GradientStop>,
109    },
110}
111
112impl From<Color> for Brush {
113    fn from(value: Color) -> Self {
114        Self::Solid(value)
115    }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
119pub enum StrokeCap {
120    #[default]
121    Butt,
122    Round,
123    Square,
124}
125
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
127pub enum StrokeJoin {
128    #[default]
129    Miter,
130    Round,
131    Bevel,
132}
133
134#[derive(Debug, Clone, Copy, PartialEq)]
135pub struct StrokeStyle {
136    pub width: f32,
137    pub cap: StrokeCap,
138    pub join: StrokeJoin,
139}
140
141impl StrokeStyle {
142    pub const fn new(width: f32) -> Self {
143        Self {
144            width,
145            cap: StrokeCap::Butt,
146            join: StrokeJoin::Miter,
147        }
148    }
149
150    pub const fn with_cap(mut self, cap: StrokeCap) -> Self {
151        self.cap = cap;
152        self
153    }
154
155    pub const fn with_join(mut self, join: StrokeJoin) -> Self {
156        self.join = join;
157        self
158    }
159}
160
161impl Default for StrokeStyle {
162    fn default() -> Self {
163        Self::new(1.0)
164    }
165}
166
167#[derive(Debug, Clone, PartialEq)]
168pub struct ImageSource {
169    pub image: ImageHandle,
170    pub source_rect: Option<Rect>,
171    pub tint: Option<Color>,
172    pub sampling: ImageSampling,
173    pub pixel_snap: ImagePixelSnap,
174}
175
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
177pub enum ImageSampling {
178    Nearest,
179    #[default]
180    Linear,
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
184pub enum ImagePixelSnap {
185    None,
186    #[default]
187    Physical,
188}
189
190impl ImageSource {
191    pub const fn new(image: ImageHandle) -> Self {
192        Self {
193            image,
194            source_rect: None,
195            tint: None,
196            sampling: ImageSampling::Linear,
197            pixel_snap: ImagePixelSnap::Physical,
198        }
199    }
200
201    pub const fn with_source_rect(mut self, source_rect: Rect) -> Self {
202        self.source_rect = Some(source_rect);
203        self
204    }
205
206    pub const fn with_tint(mut self, tint: Color) -> Self {
207        self.tint = Some(tint);
208        self
209    }
210
211    pub const fn with_sampling(mut self, sampling: ImageSampling) -> Self {
212        self.sampling = sampling;
213        self
214    }
215
216    pub const fn with_pixel_snap(mut self, pixel_snap: ImagePixelSnap) -> Self {
217        self.pixel_snap = pixel_snap;
218        self
219    }
220}
221
222#[derive(Debug, Clone, Copy, PartialEq)]
223pub enum WidgetShader {
224    ColorWheel,
225    ColorPickerHueBar,
226    ColorPickerSaturationValuePlane {
227        color_space: ColorSpace,
228        hue: f32,
229        max_value: f32,
230    },
231    ColorPickerSaturationBar {
232        color_space: ColorSpace,
233        hue: f32,
234        value: f32,
235    },
236    ColorPickerValueBar {
237        color_space: ColorSpace,
238        hue: f32,
239        saturation: f32,
240        max_value: f32,
241    },
242    ColorPickerAlphaBar {
243        color: Color,
244    },
245    ColorPickerRgbChannelBar {
246        color: Color,
247        channel: u32,
248        max_value: f32,
249    },
250}
251
252#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
253pub enum TextRenderMode {
254    #[default]
255    Grayscale,
256    LcdSubpixel,
257}
258
259#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
260pub enum TextSubpixelOrder {
261    #[default]
262    None,
263    Rgb,
264    Bgr,
265}
266
267#[derive(Debug, Clone, Copy, PartialEq)]
268pub enum TextRenderHinting {
269    None,
270    Slight { max_ppem: f32 },
271}
272
273/// The largest size, in pixels per em, that the default hinting hints.
274pub const DEFAULT_TEXT_HINTING_MAX_PPEM: f32 = 96.0;
275
276impl Default for TextRenderHinting {
277    fn default() -> Self {
278        Self::Slight {
279            max_ppem: DEFAULT_TEXT_HINTING_MAX_PPEM,
280        }
281    }
282}
283
284impl TextRenderHinting {
285    pub fn normalized(self) -> Self {
286        match self {
287            Self::None => Self::None,
288            Self::Slight { max_ppem } if max_ppem.is_finite() && max_ppem > 0.0 => {
289                Self::Slight { max_ppem }
290            }
291            Self::Slight { .. } => Self::None,
292        }
293    }
294
295    /// Whether text `ppem` pixels per em is hinted.
296    pub fn should_hint(self, ppem: f32) -> bool {
297        match self.normalized() {
298            Self::None => false,
299            Self::Slight { max_ppem } => ppem.is_finite() && ppem <= max_ppem,
300        }
301    }
302}
303
304#[derive(Debug, Clone, Copy, PartialEq, Default)]
305pub enum TextRenderStemDarkening {
306    #[default]
307    None,
308    Enabled {
309        max_ppem: f32,
310        amount: f32,
311    },
312}
313
314impl TextRenderStemDarkening {
315    pub fn normalized(self) -> Self {
316        match self {
317            Self::None => Self::None,
318            Self::Enabled { max_ppem, amount }
319                if max_ppem.is_finite() && max_ppem > 0.0 && amount.is_finite() && amount > 0.0 =>
320            {
321                Self::Enabled {
322                    max_ppem,
323                    amount: amount.clamp(0.0, 1.0),
324                }
325            }
326            Self::Enabled { .. } => Self::None,
327        }
328    }
329
330    /// How much stems of text `ppem` pixels per em are darkened.
331    pub fn effective_amount(self, ppem: f32) -> f32 {
332        match self.normalized() {
333            Self::None => 0.0,
334            Self::Enabled { max_ppem, amount } if ppem.is_finite() && ppem <= max_ppem => amount,
335            Self::Enabled { .. } => 0.0,
336        }
337    }
338}
339
340#[derive(Debug, Clone, Copy, PartialEq, Default)]
341pub enum TextRenderCoveragePolicy {
342    #[default]
343    Perceptual,
344    Linear,
345    Gamma(f32),
346    CoverageBoost(f32),
347    TwoCoverageMinusCoverageSq,
348}
349
350impl TextRenderCoveragePolicy {
351    pub fn normalized(self) -> Self {
352        match self {
353            Self::Perceptual => Self::Perceptual,
354            Self::Linear => Self::Linear,
355            Self::Gamma(gamma) if gamma.is_finite() && gamma > 0.0 => Self::Gamma(gamma),
356            Self::Gamma(_) => Self::Linear,
357            Self::CoverageBoost(amount) if amount.is_finite() && amount > 0.0 => {
358                Self::CoverageBoost(amount.clamp(0.0, 1.0))
359            }
360            Self::CoverageBoost(_) => Self::Linear,
361            Self::TwoCoverageMinusCoverageSq => Self::TwoCoverageMinusCoverageSq,
362        }
363    }
364}
365
366#[derive(Debug, Clone, Copy, PartialEq, Default)]
367pub struct TextRenderPolicy {
368    pub render_mode: Option<TextRenderMode>,
369    pub subpixel_order: Option<TextSubpixelOrder>,
370    pub hinting: Option<TextRenderHinting>,
371    pub stem_darkening: Option<TextRenderStemDarkening>,
372    pub coverage_policy: Option<TextRenderCoveragePolicy>,
373}
374
375impl TextRenderPolicy {
376    pub const fn new() -> Self {
377        Self {
378            render_mode: None,
379            subpixel_order: None,
380            hinting: None,
381            stem_darkening: None,
382            coverage_policy: None,
383        }
384    }
385
386    pub const fn with_render_mode(mut self, mode: TextRenderMode) -> Self {
387        self.render_mode = Some(mode);
388        self
389    }
390
391    pub const fn with_subpixel_order(mut self, order: TextSubpixelOrder) -> Self {
392        self.subpixel_order = Some(order);
393        self
394    }
395
396    pub const fn with_hinting(mut self, hinting: TextRenderHinting) -> Self {
397        self.hinting = Some(hinting);
398        self
399    }
400
401    pub const fn with_stem_darkening(mut self, darkening: TextRenderStemDarkening) -> Self {
402        self.stem_darkening = Some(darkening);
403        self
404    }
405
406    pub const fn with_coverage_policy(mut self, policy: TextRenderCoveragePolicy) -> Self {
407        self.coverage_policy = Some(policy);
408        self
409    }
410
411    pub fn normalized(self) -> Self {
412        Self {
413            render_mode: self.render_mode,
414            subpixel_order: self.subpixel_order,
415            hinting: self.hinting.map(TextRenderHinting::normalized),
416            stem_darkening: self.stem_darkening.map(TextRenderStemDarkening::normalized),
417            coverage_policy: self
418                .coverage_policy
419                .map(TextRenderCoveragePolicy::normalized),
420        }
421    }
422}
423
424/// How a retained layer is presented without repainting it: faded, moved,
425/// and scaled. Changing these updates the composited layer only.
426#[derive(Debug, Clone, Copy, PartialEq)]
427pub struct LayerProperties {
428    pub opacity: f32,
429    pub translation: Vector,
430    /// Scale factors along x and y, applied around `scale_anchor` before
431    /// `translation`. `(1, 1)` presents the layer as painted.
432    pub scale: Vector,
433    /// The point scaling keeps fixed, as a fraction of the layer's bounds:
434    /// `(0.5, 0.5)` is the center, `(0.5, 0.0)` the middle of the top edge.
435    pub scale_anchor: Vector,
436}
437
438impl LayerProperties {
439    pub const IDENTITY_SCALE: Vector = Vector::new(1.0, 1.0);
440    pub const CENTER: Vector = Vector::new(0.5, 0.5);
441
442    pub const fn new(opacity: f32, translation: Vector) -> Self {
443        Self {
444            opacity,
445            translation,
446            scale: Self::IDENTITY_SCALE,
447            scale_anchor: Self::CENTER,
448        }
449    }
450
451    pub const fn with_opacity(mut self, opacity: f32) -> Self {
452        self.opacity = opacity;
453        self
454    }
455
456    pub const fn with_translation(mut self, translation: Vector) -> Self {
457        self.translation = translation;
458        self
459    }
460
461    /// Scale uniformly by `scale` around the scale anchor.
462    pub const fn with_scale(mut self, scale: f32) -> Self {
463        self.scale = Vector::new(scale, scale);
464        self
465    }
466
467    /// Scale by `scale.x` horizontally and `scale.y` vertically.
468    pub const fn with_scale_xy(mut self, scale: Vector) -> Self {
469        self.scale = scale;
470        self
471    }
472
473    /// Scale around this point, as a fraction of the layer's bounds.
474    pub const fn with_scale_anchor(mut self, anchor: Vector) -> Self {
475        self.scale_anchor = anchor;
476        self
477    }
478
479    pub fn is_scaled(&self) -> bool {
480        self.scale != Self::IDENTITY_SCALE
481    }
482
483    /// The point in window coordinates that scaling keeps fixed for a layer
484    /// laid out at `bounds`.
485    pub fn anchor_point(&self, bounds: Rect) -> Point {
486        Point::new(
487            bounds.x() + bounds.width() * self.scale_anchor.x,
488            bounds.y() + bounds.height() * self.scale_anchor.y,
489        )
490    }
491
492    /// Where `point` is presented for a layer laid out at `bounds`.
493    pub fn map_point(&self, bounds: Rect, point: Point) -> Point {
494        let anchor = self.anchor_point(bounds);
495        Point::new(
496            anchor.x + (point.x - anchor.x) * self.scale.x + self.translation.x,
497            anchor.y + (point.y - anchor.y) * self.scale.y + self.translation.y,
498        )
499    }
500
501    /// Where `rect` is presented for a layer laid out at `bounds`.
502    pub fn map_rect(&self, bounds: Rect, rect: Rect) -> Rect {
503        if !self.is_scaled() {
504            return rect.translate(self.translation);
505        }
506        let first = self.map_point(bounds, rect.origin);
507        let second = self.map_point(bounds, Point::new(rect.max_x(), rect.max_y()));
508        Rect::new(
509            first.x.min(second.x),
510            first.y.min(second.y),
511            (second.x - first.x).abs(),
512            (second.y - first.y).abs(),
513        )
514    }
515
516    /// The presentation as a transform of window coordinates, for a layer
517    /// laid out at `bounds`.
518    pub fn transform(&self, bounds: Rect) -> Transform {
519        let presented = self.map_point(bounds, Point::ZERO);
520        Transform::new(
521            self.scale.x,
522            0.0,
523            0.0,
524            self.scale.y,
525            presented.x,
526            presented.y,
527        )
528    }
529}
530
531impl Default for LayerProperties {
532    fn default() -> Self {
533        Self::new(1.0, Vector::ZERO)
534    }
535}
536
537#[derive(Debug, Clone, PartialEq)]
538pub struct SceneLayerDescriptor {
539    pub id: SceneLayerId,
540    pub owner: WidgetId,
541    pub bounds: Rect,
542    pub content_bounds: Rect,
543    pub paint_bounds: Rect,
544    pub hit_test: bool,
545    pub clip_to_ancestors: bool,
546    pub properties: LayerProperties,
547    pub stack_host: WidgetId,
548    pub stack_order: usize,
549    pub transient_owner_surface: Option<WidgetId>,
550    pub is_stack_surface: bool,
551    pub composition_mode: LayerCompositionMode,
552}
553
554impl SceneLayerDescriptor {
555    pub fn new(id: SceneLayerId, owner: WidgetId, bounds: Rect) -> Self {
556        Self {
557            id,
558            owner,
559            bounds,
560            content_bounds: bounds,
561            paint_bounds: bounds,
562            hit_test: true,
563            clip_to_ancestors: true,
564            properties: LayerProperties::default(),
565            stack_host: owner,
566            stack_order: 0,
567            transient_owner_surface: None,
568            is_stack_surface: false,
569            composition_mode: LayerCompositionMode::Normal,
570        }
571    }
572
573    pub const fn with_content_bounds(mut self, content_bounds: Rect) -> Self {
574        self.content_bounds = content_bounds;
575        self
576    }
577
578    pub const fn with_paint_bounds(mut self, paint_bounds: Rect) -> Self {
579        self.paint_bounds = paint_bounds;
580        self
581    }
582
583    pub const fn with_hit_test(mut self, hit_test: bool) -> Self {
584        self.hit_test = hit_test;
585        self
586    }
587
588    pub const fn with_clip_to_ancestors(mut self, clip: bool) -> Self {
589        self.clip_to_ancestors = clip;
590        self
591    }
592
593    pub const fn with_properties(mut self, properties: LayerProperties) -> Self {
594        self.properties = properties;
595        self
596    }
597
598    pub const fn with_opacity(mut self, opacity: f32) -> Self {
599        self.properties.opacity = opacity;
600        self
601    }
602
603    pub const fn with_translation(mut self, translation: Vector) -> Self {
604        self.properties.translation = translation;
605        self
606    }
607
608    pub const fn with_stack_host(mut self, stack_host: WidgetId) -> Self {
609        self.stack_host = stack_host;
610        self
611    }
612
613    pub const fn with_stack_order(mut self, stack_order: usize) -> Self {
614        self.stack_order = stack_order;
615        self
616    }
617
618    pub const fn with_transient_owner_surface(
619        mut self,
620        transient_owner_surface: Option<WidgetId>,
621    ) -> Self {
622        self.transient_owner_surface = transient_owner_surface;
623        self
624    }
625
626    pub const fn with_is_stack_surface(mut self, is_stack_surface: bool) -> Self {
627        self.is_stack_surface = is_stack_surface;
628        self
629    }
630
631    pub const fn with_composition_mode(mut self, composition_mode: LayerCompositionMode) -> Self {
632        self.composition_mode = composition_mode;
633        self
634    }
635
636    pub fn translate(mut self, delta: Vector) -> Self {
637        self.bounds = self.bounds.translate(delta);
638        self.content_bounds = self.content_bounds.translate(delta);
639        self.paint_bounds = self.paint_bounds.translate(delta);
640        self
641    }
642
643    pub fn presented_bounds(&self) -> Rect {
644        self.properties.map_rect(self.bounds, self.bounds)
645    }
646
647    pub fn presented_content_bounds(&self) -> Rect {
648        self.properties.map_rect(self.bounds, self.content_bounds)
649    }
650
651    pub fn presented_paint_bounds(&self) -> Rect {
652        self.properties.map_rect(self.bounds, self.paint_bounds)
653    }
654}
655
656#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
657pub struct SceneLayerId(u64);
658
659impl SceneLayerId {
660    pub const fn new(id: u64) -> Self {
661        Self(id)
662    }
663
664    pub const fn from_widget(widget_id: WidgetId) -> Self {
665        Self(widget_id.get())
666    }
667
668    pub const fn get(self) -> u64 {
669        self.0
670    }
671}
672
673impl From<WidgetId> for SceneLayerId {
674    fn from(value: WidgetId) -> Self {
675        Self::from_widget(value)
676    }
677}
678
679#[derive(Debug, Clone, Copy, PartialEq, Eq)]
680pub enum LayerCompositionMode {
681    Normal,
682    Scroll,
683    Overlay,
684    Effect,
685}
686
687#[derive(Debug, Clone, PartialEq)]
688pub struct SceneLayer {
689    pub descriptor: SceneLayerDescriptor,
690    pub scene: Arc<Scene>,
691}
692
693impl SceneLayer {
694    pub fn new(widget_id: WidgetId, bounds: Rect, scene: Scene) -> Self {
695        let content_bounds = scene.content_bounds().unwrap_or(bounds);
696        let paint_bounds = scene.paint_bounds().unwrap_or(bounds);
697        Self {
698            descriptor: SceneLayerDescriptor::new(
699                SceneLayerId::from_widget(widget_id),
700                widget_id,
701                bounds,
702            )
703            .with_content_bounds(content_bounds)
704            .with_paint_bounds(paint_bounds),
705            scene: Arc::new(scene),
706        }
707    }
708
709    pub fn from_descriptor(descriptor: SceneLayerDescriptor, scene: Scene) -> Self {
710        Self {
711            descriptor,
712            scene: Arc::new(scene),
713        }
714    }
715
716    pub fn from_shared_descriptor(descriptor: SceneLayerDescriptor, scene: Arc<Scene>) -> Self {
717        Self { descriptor, scene }
718    }
719
720    pub const fn layer_id(&self) -> SceneLayerId {
721        self.descriptor.id
722    }
723
724    pub const fn widget_id(&self) -> WidgetId {
725        self.descriptor.owner
726    }
727
728    pub const fn bounds(&self) -> Rect {
729        self.descriptor.bounds
730    }
731}
732
733#[derive(Debug, Clone, Copy, PartialEq, Eq)]
734pub enum SceneLayerUpdateKind {
735    Ordering,
736    Content,
737    Transform,
738    Clip,
739    Effect,
740    Visibility,
741    Resources,
742}
743
744#[derive(Debug, Clone, PartialEq)]
745pub struct SceneLayerUpdate {
746    pub layer_id: SceneLayerId,
747    pub owner: WidgetId,
748    pub kind: SceneLayerUpdateKind,
749    pub bounds: Rect,
750    pub content_bounds: Rect,
751    pub paint_bounds: Rect,
752    pub properties: LayerProperties,
753    pub stack_host: WidgetId,
754    pub stack_order: usize,
755    pub transient_owner_surface: Option<WidgetId>,
756    pub is_stack_surface: bool,
757    pub damage: Option<Rect>,
758}
759
760impl SceneLayerUpdate {
761    pub fn from_descriptor(kind: SceneLayerUpdateKind, descriptor: SceneLayerDescriptor) -> Self {
762        Self {
763            layer_id: descriptor.id,
764            owner: descriptor.owner,
765            kind,
766            bounds: descriptor.bounds,
767            content_bounds: descriptor.content_bounds,
768            paint_bounds: descriptor.paint_bounds,
769            properties: descriptor.properties,
770            stack_host: descriptor.stack_host,
771            stack_order: descriptor.stack_order,
772            transient_owner_surface: descriptor.transient_owner_surface,
773            is_stack_surface: descriptor.is_stack_surface,
774            damage: None,
775        }
776    }
777
778    pub const fn with_damage(mut self, damage: Rect) -> Self {
779        self.damage = Some(damage);
780        self
781    }
782}
783
784#[derive(Debug, Clone, PartialEq)]
785pub enum SceneCommand {
786    Clear(Color),
787    FillRect {
788        rect: Rect,
789        brush: Brush,
790    },
791    StrokeRect {
792        rect: Rect,
793        brush: Brush,
794        stroke: StrokeStyle,
795    },
796    FillPath {
797        path: Path,
798        brush: Brush,
799    },
800    StrokePath {
801        path: Path,
802        brush: Brush,
803        stroke: StrokeStyle,
804    },
805    DrawText(TextRun),
806    DrawShapedText(ShapedText),
807    DrawShapedTextWindow(ShapedTextWindow),
808    DrawImage {
809        rect: Rect,
810        source: ImageSource,
811    },
812    DrawImageQuad {
813        points: [Point; 4],
814        source: ImageSource,
815    },
816    DrawShaderRect {
817        rect: Rect,
818        shader: WidgetShader,
819    },
820    PushClip {
821        rect: Rect,
822    },
823    PushClipPath {
824        path: Path,
825    },
826    PopClip,
827    PushTransform {
828        transform: Transform,
829    },
830    PopTransform,
831    PushTextRenderPolicy {
832        policy: TextRenderPolicy,
833    },
834    PopTextRenderPolicy,
835    Layer(SceneLayer),
836    FillRoundedRect {
837        rect: Rect,
838        radii: [f32; 4],
839        brush: Brush,
840        border: Option<Border>,
841        shadow: Option<ShadowParams>,
842    },
843    Label {
844        rect: Rect,
845        text: String,
846        color: Color,
847    },
848}
849
850impl SceneCommand {
851    /// Returns the command category used in diagnostic breakdowns and snapshots.
852    ///
853    /// Both image rectangles and image quads are grouped under `DrawImage`.
854    pub const fn diagnostic_name(&self) -> &'static str {
855        match self {
856            Self::Clear(_) => "Clear",
857            Self::FillRect { .. } => "FillRect",
858            Self::StrokeRect { .. } => "StrokeRect",
859            Self::FillPath { .. } => "FillPath",
860            Self::StrokePath { .. } => "StrokePath",
861            Self::DrawText(_) => "DrawText",
862            Self::DrawShapedText(_) => "DrawShapedText",
863            Self::DrawShapedTextWindow(_) => "DrawShapedTextWindow",
864            Self::DrawImage { .. } | Self::DrawImageQuad { .. } => "DrawImage",
865            Self::DrawShaderRect { .. } => "DrawShaderRect",
866            Self::PushClip { .. } => "PushClip",
867            Self::PushClipPath { .. } => "PushClipPath",
868            Self::PopClip => "PopClip",
869            Self::PushTransform { .. } => "PushTransform",
870            Self::PopTransform => "PopTransform",
871            Self::PushTextRenderPolicy { .. } => "PushTextRenderPolicy",
872            Self::PopTextRenderPolicy => "PopTextRenderPolicy",
873            Self::Layer(_) => "Layer",
874            Self::FillRoundedRect { .. } => "FillRoundedRect",
875            Self::Label { .. } => "Label",
876        }
877    }
878}
879
880#[derive(Clone, Default)]
881pub struct Scene {
882    commands: Arc<Vec<SceneCommand>>,
883    bounds: SceneBoundsSummary,
884}
885
886impl std::fmt::Debug for Scene {
887    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
888        formatter
889            .debug_struct("Scene")
890            .field("commands", &self.commands)
891            .finish()
892    }
893}
894
895impl PartialEq for Scene {
896    fn eq(&self, other: &Self) -> bool {
897        self.commands == other.commands
898    }
899}
900
901impl Scene {
902    pub fn new() -> Self {
903        Self::default()
904    }
905
906    pub fn push(&mut self, command: SceneCommand) {
907        self.bounds.push(&command);
908        Arc::make_mut(&mut self.commands).push(command);
909    }
910
911    pub fn append(&mut self, scene: Scene) {
912        // Appending to an empty scene shares the command list instead of
913        // copying it, which keeps single-child wrappers from duplicating
914        // their subtree's commands.
915        if self.commands.is_empty() {
916            *self = scene;
917            return;
918        }
919        if self.bounds.state.is_balanced() && scene.bounds.state.is_balanced() {
920            self.bounds.extend(&scene.bounds);
921        } else {
922            for command in scene.commands.iter() {
923                self.bounds.push(command);
924            }
925        }
926        Arc::make_mut(&mut self.commands).append(&mut Arc::unwrap_or_clone(scene.commands));
927    }
928
929    /// Append a retained scene without allocating an intermediate command vector.
930    pub fn append_ref(&mut self, scene: &Scene) {
931        if self.commands.is_empty() {
932            self.clone_from(scene);
933            return;
934        }
935        if self.bounds.state.is_balanced() && scene.bounds.state.is_balanced() {
936            self.bounds.extend(&scene.bounds);
937        } else {
938            for command in scene.commands.iter() {
939                self.bounds.push(command);
940            }
941        }
942        Arc::make_mut(&mut self.commands).extend(scene.commands.iter().cloned());
943    }
944
945    pub fn clear(&mut self) {
946        if let Some(commands) = Arc::get_mut(&mut self.commands) {
947            commands.clear();
948        } else {
949            self.commands = Arc::default();
950        }
951        self.bounds = SceneBoundsSummary::default();
952    }
953
954    pub fn commands(&self) -> &[SceneCommand] {
955        &self.commands
956    }
957
958    /// Whether two immutable snapshots share the same command storage.
959    /// Any mutation detaches shared storage before changing commands.
960    pub fn shares_commands_with(&self, other: &Self) -> bool {
961        Arc::ptr_eq(&self.commands, &other.commands)
962    }
963
964    pub fn visit_commands(&self, visitor: &mut dyn FnMut(&SceneCommand)) {
965        for command in self.commands.iter() {
966            visitor(command);
967            if let SceneCommand::Layer(layer) = command {
968                layer.scene.visit_commands(visitor);
969            }
970        }
971    }
972
973    pub fn visit_layers(&self, visitor: &mut dyn FnMut(&SceneLayer)) {
974        for command in self.commands.iter() {
975            if let SceneCommand::Layer(layer) = command {
976                visitor(layer);
977                layer.scene.visit_layers(visitor);
978            }
979        }
980    }
981
982    pub fn visit_layers_mut(&mut self, visitor: &mut dyn FnMut(&mut SceneLayer)) {
983        for command in Arc::make_mut(&mut self.commands) {
984            if let SceneCommand::Layer(layer) = command {
985                visitor(layer);
986                if layer
987                    .scene
988                    .commands()
989                    .iter()
990                    .any(|command| matches!(command, SceneCommand::Layer(_)))
991                {
992                    Arc::make_mut(&mut layer.scene).visit_layers_mut(visitor);
993                }
994            }
995        }
996        self.rebuild_bounds();
997    }
998
999    pub fn content_bounds(&self) -> Option<Rect> {
1000        self.bounds.content
1001    }
1002
1003    pub fn paint_bounds(&self) -> Option<Rect> {
1004        self.bounds.paint
1005    }
1006
1007    pub fn replace_layer(&mut self, widget_id: WidgetId, replacement: SceneLayer) -> bool {
1008        let mut replaced = false;
1009        for command in Arc::make_mut(&mut self.commands) {
1010            match command {
1011                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
1012                    *command = SceneCommand::Layer(replacement);
1013                    replaced = true;
1014                    break;
1015                }
1016                SceneCommand::Layer(layer) => {
1017                    if Arc::make_mut(&mut layer.scene).replace_layer(widget_id, replacement.clone())
1018                    {
1019                        replaced = true;
1020                        break;
1021                    }
1022                }
1023                _ => {}
1024            }
1025        }
1026
1027        if replaced {
1028            self.rebuild_bounds();
1029        }
1030        replaced
1031    }
1032
1033    pub fn translate(&mut self, delta: Vector) {
1034        if delta == Vector::ZERO {
1035            return;
1036        }
1037        for command in Arc::make_mut(&mut self.commands) {
1038            translate_command(command, delta);
1039        }
1040        self.rebuild_bounds();
1041    }
1042
1043    pub fn translate_layer(&mut self, widget_id: WidgetId, delta: Vector) -> bool {
1044        let mut translated = false;
1045        for command in Arc::make_mut(&mut self.commands) {
1046            match command {
1047                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
1048                    layer.translate(delta);
1049                    translated = true;
1050                    break;
1051                }
1052                SceneCommand::Layer(layer) => {
1053                    if Arc::make_mut(&mut layer.scene).translate_layer(widget_id, delta) {
1054                        translated = true;
1055                        break;
1056                    }
1057                }
1058                _ => {}
1059            }
1060        }
1061
1062        if translated {
1063            self.rebuild_bounds();
1064        }
1065        translated
1066    }
1067
1068    pub fn replace_layer_descriptor(
1069        &mut self,
1070        widget_id: WidgetId,
1071        descriptor: SceneLayerDescriptor,
1072    ) -> bool {
1073        let mut replaced = false;
1074        for command in Arc::make_mut(&mut self.commands) {
1075            match command {
1076                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
1077                    layer.descriptor = descriptor;
1078                    replaced = true;
1079                    break;
1080                }
1081                SceneCommand::Layer(layer) => {
1082                    if Arc::make_mut(&mut layer.scene)
1083                        .replace_layer_descriptor(widget_id, descriptor.clone())
1084                    {
1085                        replaced = true;
1086                        break;
1087                    }
1088                }
1089                _ => {}
1090            }
1091        }
1092
1093        if replaced {
1094            self.rebuild_bounds();
1095        }
1096        replaced
1097    }
1098
1099    pub fn layer_scene(&self, widget_id: WidgetId) -> Option<&Scene> {
1100        for command in self.commands.iter() {
1101            match command {
1102                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
1103                    return Some(&layer.scene);
1104                }
1105                SceneCommand::Layer(layer) => {
1106                    if let Some(scene) = layer.scene.layer_scene(widget_id) {
1107                        return Some(scene);
1108                    }
1109                }
1110                _ => {}
1111            }
1112        }
1113
1114        None
1115    }
1116
1117    pub fn reorder_stack_surfaces(&mut self) {
1118        let mut stack_layers = self
1119            .commands
1120            .iter()
1121            .enumerate()
1122            .filter_map(|(index, command)| match command {
1123                SceneCommand::Layer(layer) if layer.descriptor.is_stack_surface => {
1124                    Some((index, layer.clone()))
1125                }
1126                _ => None,
1127            })
1128            .collect::<Vec<_>>();
1129
1130        stack_layers.sort_by_key(|(index, layer)| (layer.descriptor.stack_order, *index));
1131
1132        let mut sorted_layers = stack_layers.into_iter().map(|(_, layer)| layer);
1133        for command in Arc::make_mut(&mut self.commands) {
1134            if let SceneCommand::Layer(layer) = command {
1135                if layer
1136                    .scene
1137                    .commands()
1138                    .iter()
1139                    .any(|command| matches!(command, SceneCommand::Layer(_)))
1140                {
1141                    Arc::make_mut(&mut layer.scene).reorder_stack_surfaces();
1142                }
1143                if layer.descriptor.is_stack_surface
1144                    && let Some(replacement) = sorted_layers.next()
1145                {
1146                    *layer = replacement;
1147                }
1148            }
1149        }
1150        self.rebuild_bounds();
1151    }
1152
1153    fn rebuild_bounds(&mut self) {
1154        self.bounds = SceneBoundsSummary::from_commands(&self.commands);
1155    }
1156}
1157
1158#[derive(Debug, Clone, Default, PartialEq)]
1159struct SceneBoundsSummary {
1160    state: SceneBoundsState,
1161    content: Option<Rect>,
1162    paint: Option<Rect>,
1163}
1164
1165impl SceneBoundsSummary {
1166    fn from_commands(commands: &[SceneCommand]) -> Self {
1167        let mut summary = Self::default();
1168        for command in commands {
1169            summary.push(command);
1170        }
1171        summary
1172    }
1173
1174    fn push(&mut self, command: &SceneCommand) {
1175        let (content, paint) = self.state.command_bounds(command);
1176        Self::include(&mut self.content, content);
1177        Self::include(&mut self.paint, paint);
1178    }
1179
1180    fn extend(&mut self, other: &Self) {
1181        debug_assert!(self.state.is_balanced());
1182        debug_assert!(other.state.is_balanced());
1183        Self::include(&mut self.content, other.content);
1184        Self::include(&mut self.paint, other.paint);
1185    }
1186
1187    fn include(bounds: &mut Option<Rect>, additional: Option<Rect>) {
1188        let Some(additional) = additional else {
1189            return;
1190        };
1191        *bounds = Some(match *bounds {
1192            Some(existing) => existing.union(additional),
1193            None => additional,
1194        });
1195    }
1196}
1197
1198#[derive(Debug, Clone, Default, PartialEq)]
1199struct SceneBoundsState {
1200    transform: Transform,
1201    transform_stack: Vec<Transform>,
1202    clip_stack: Vec<Rect>,
1203}
1204
1205impl SceneBoundsState {
1206    fn is_balanced(&self) -> bool {
1207        self.transform.is_identity()
1208            && self.transform_stack.is_empty()
1209            && self.clip_stack.is_empty()
1210    }
1211
1212    fn command_bounds(&mut self, command: &SceneCommand) -> (Option<Rect>, Option<Rect>) {
1213        match command {
1214            SceneCommand::Clear(_) => {
1215                let clip = self.current_clip();
1216                (clip, clip)
1217            }
1218            SceneCommand::FillRect { rect, .. } => self.apply_rect(*rect),
1219            SceneCommand::StrokeRect { rect, stroke, .. } => {
1220                self.apply_rect(rect.inflate(stroke.width * 0.5, stroke.width * 0.5))
1221            }
1222            SceneCommand::FillPath { path, .. } => self.apply_rect(path.bounds()),
1223            SceneCommand::StrokePath { path, stroke, .. } => self.apply_rect(
1224                path.bounds()
1225                    .inflate(stroke.width * 0.5, stroke.width * 0.5),
1226            ),
1227            SceneCommand::DrawText(text) => self.apply_rect(text.rect),
1228            SceneCommand::DrawShapedText(text) => self.apply_rect(text.translated_bounds()),
1229            SceneCommand::DrawShapedTextWindow(text) => self.apply_rect(text.translated_bounds()),
1230            SceneCommand::DrawImage { rect, .. } => self.apply_rect(*rect),
1231            SceneCommand::DrawImageQuad { points, .. } => self.apply_points(*points),
1232            SceneCommand::DrawShaderRect { rect, .. } => self.apply_rect(*rect),
1233            SceneCommand::PushClip { rect } => {
1234                let clip = self.transform.transform_rect_bbox(*rect);
1235                self.push_clip(clip);
1236                (None, None)
1237            }
1238            SceneCommand::PushClipPath { path } => {
1239                let clip = self.transform.transform_rect_bbox(path.bounds());
1240                self.push_clip(clip);
1241                (None, None)
1242            }
1243            SceneCommand::PopClip => {
1244                self.clip_stack.pop();
1245                (None, None)
1246            }
1247            SceneCommand::PushTransform { transform } => {
1248                self.transform_stack.push(self.transform);
1249                self.transform = self.transform.then(*transform);
1250                (None, None)
1251            }
1252            SceneCommand::PopTransform => {
1253                self.transform = self.transform_stack.pop().unwrap_or_default();
1254                (None, None)
1255            }
1256            SceneCommand::PushTextRenderPolicy { .. } | SceneCommand::PopTextRenderPolicy => {
1257                (None, None)
1258            }
1259            SceneCommand::Layer(layer) => self.apply_distinct_rects(
1260                layer.descriptor.content_bounds,
1261                layer.descriptor.paint_bounds,
1262            ),
1263            SceneCommand::FillRoundedRect { rect, shadow, .. } => {
1264                let bounds = match shadow {
1265                    Some(shadow) if shadow.placement != ShadowPlacement::Inside => {
1266                        let extent = shadow.extent();
1267                        let shadow_rect = rect
1268                            .inflate(extent, extent)
1269                            .translate(Vector::new(shadow.offset_x, shadow.offset_y));
1270                        rect.union(shadow_rect)
1271                    }
1272                    Some(_) | None => *rect,
1273                };
1274                self.apply_rect(bounds)
1275            }
1276            SceneCommand::Label { rect, .. } => self.apply_rect(*rect),
1277        }
1278    }
1279
1280    fn apply_rect(&self, rect: Rect) -> (Option<Rect>, Option<Rect>) {
1281        let transformed = self.transform.transform_rect_bbox(rect);
1282        (Some(transformed), self.clip_rect(transformed))
1283    }
1284
1285    fn apply_distinct_rects(&self, content: Rect, paint: Rect) -> (Option<Rect>, Option<Rect>) {
1286        let content = self.transform.transform_rect_bbox(content);
1287        let paint = self.transform.transform_rect_bbox(paint);
1288        (Some(content), self.clip_rect(paint))
1289    }
1290
1291    fn apply_points(&self, points: [Point; 4]) -> (Option<Rect>, Option<Rect>) {
1292        let transformed = points.map(|point| self.transform.transform_point(point));
1293        let bounds = points_bounds(&transformed);
1294        (Some(bounds), self.clip_rect(bounds))
1295    }
1296
1297    fn push_clip(&mut self, clip: Rect) {
1298        let clip = self.clip_rect(clip).unwrap_or(Rect::ZERO);
1299        self.clip_stack.push(clip);
1300    }
1301
1302    fn clip_rect(&self, rect: Rect) -> Option<Rect> {
1303        let mut clipped = rect;
1304        for clip in &self.clip_stack {
1305            clipped = clipped.intersection(*clip)?;
1306        }
1307        Some(clipped)
1308    }
1309
1310    fn current_clip(&self) -> Option<Rect> {
1311        self.clip_stack.last().copied()
1312    }
1313}
1314
1315impl SceneLayer {
1316    fn translate(&mut self, delta: Vector) {
1317        self.descriptor = self.descriptor.clone().translate(delta);
1318        Arc::make_mut(&mut self.scene).translate(delta);
1319    }
1320}
1321
1322fn translate_command(command: &mut SceneCommand, delta: Vector) {
1323    match command {
1324        SceneCommand::Clear(_)
1325        | SceneCommand::PopClip
1326        | SceneCommand::PopTransform
1327        | SceneCommand::PushTextRenderPolicy { .. }
1328        | SceneCommand::PopTextRenderPolicy => {}
1329        SceneCommand::FillRect { rect, brush } | SceneCommand::StrokeRect { rect, brush, .. } => {
1330            *rect = rect.translate(delta);
1331            translate_brush(brush, delta);
1332        }
1333        SceneCommand::DrawImage { rect, .. }
1334        | SceneCommand::DrawShaderRect { rect, .. }
1335        | SceneCommand::PushClip { rect }
1336        | SceneCommand::Label { rect, .. } => {
1337            *rect = rect.translate(delta);
1338        }
1339        SceneCommand::DrawImageQuad { points, .. } => {
1340            for point in points {
1341                *point += delta;
1342            }
1343        }
1344        SceneCommand::FillPath { path, brush } | SceneCommand::StrokePath { path, brush, .. } => {
1345            *path = translate_path(path, delta);
1346            translate_brush(brush, delta);
1347        }
1348        SceneCommand::PushClipPath { path } => {
1349            *path = translate_path(path, delta);
1350        }
1351        SceneCommand::DrawText(text) => {
1352            text.rect = text.rect.translate(delta);
1353        }
1354        SceneCommand::DrawShapedText(text) => {
1355            text.origin += delta;
1356        }
1357        SceneCommand::DrawShapedTextWindow(text) => {
1358            text.origin += delta;
1359        }
1360        SceneCommand::PushTransform { .. } => {}
1361        SceneCommand::Layer(layer) => {
1362            layer.translate(delta);
1363        }
1364        SceneCommand::FillRoundedRect { rect, brush, .. } => {
1365            *rect = rect.translate(delta);
1366            translate_brush(brush, delta);
1367        }
1368    }
1369}
1370
1371/// Gradient axes are in scene coordinates, so they move with their shape.
1372fn translate_brush(brush: &mut Brush, delta: Vector) {
1373    if let Brush::LinearGradient { start, end, .. } = brush {
1374        *start += delta;
1375        *end += delta;
1376    }
1377}
1378
1379fn points_bounds(points: &[Point]) -> Rect {
1380    let mut min_x = f32::INFINITY;
1381    let mut min_y = f32::INFINITY;
1382    let mut max_x = f32::NEG_INFINITY;
1383    let mut max_y = f32::NEG_INFINITY;
1384    for point in points {
1385        min_x = min_x.min(point.x);
1386        min_y = min_y.min(point.y);
1387        max_x = max_x.max(point.x);
1388        max_y = max_y.max(point.y);
1389    }
1390    Rect::from_points(Point::new(min_x, min_y), Point::new(max_x, max_y))
1391}
1392
1393fn translate_path(path: &Path, delta: Vector) -> Path {
1394    let mut builder = PathBuilder::with_capacity(path.elements().len());
1395    for element in path.elements() {
1396        match element {
1397            PathElement::MoveTo(point) => {
1398                builder.move_to(*point + delta);
1399            }
1400            PathElement::LineTo(point) => {
1401                builder.line_to(*point + delta);
1402            }
1403            PathElement::QuadTo { ctrl, to } => {
1404                builder.quad_to(*ctrl + delta, *to + delta);
1405            }
1406            PathElement::CubicTo { ctrl1, ctrl2, to } => {
1407                builder.cubic_to(*ctrl1 + delta, *ctrl2 + delta, *to + delta);
1408            }
1409            PathElement::Close => {
1410                builder.close();
1411            }
1412        }
1413    }
1414    builder.build()
1415}
1416
1417impl From<TextRun> for SceneCommand {
1418    fn from(value: TextRun) -> Self {
1419        Self::DrawText(value)
1420    }
1421}
1422
1423#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1424pub enum RegisteredImageFormat {
1425    Rgba8,
1426}
1427
1428impl RegisteredImageFormat {
1429    const fn bytes_per_pixel(self) -> usize {
1430        match self {
1431            Self::Rgba8 => 4,
1432        }
1433    }
1434}
1435
1436#[derive(Debug, Clone, PartialEq, Eq)]
1437pub struct RegisteredImage {
1438    data: Arc<[u8]>,
1439    width: u32,
1440    height: u32,
1441    format: RegisteredImageFormat,
1442    svg: Option<Arc<[u8]>>,
1443    mipmaps_enabled: bool,
1444}
1445
1446/// Renderer-neutral metadata for an image whose pixels are owned outside the
1447/// frame's CPU image registry.
1448///
1449/// The renderer backend is responsible for resolving the matching
1450/// [`ImageHandle`] to a backend resource. Keeping only dimensions in the scene
1451/// frame lets widgets participate in normal image layout, clipping, sampling,
1452/// and retained rendering without making the scene model depend on a GPU API.
1453#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1454pub struct RegisteredExternalImage {
1455    width: u32,
1456    height: u32,
1457}
1458
1459impl RegisteredExternalImage {
1460    pub fn new(width: u32, height: u32) -> Result<Self> {
1461        if width == 0 || height == 0 {
1462            return Err(Error::new(
1463                "external image dimensions must both be non-zero",
1464            ));
1465        }
1466        Ok(Self { width, height })
1467    }
1468
1469    pub const fn width(self) -> u32 {
1470        self.width
1471    }
1472
1473    pub const fn height(self) -> u32 {
1474        self.height
1475    }
1476}
1477
1478impl RegisteredImage {
1479    pub fn from_rgba8(width: u32, height: u32, data: impl Into<Vec<u8>>) -> Result<Self> {
1480        Self::from_pixels(width, height, RegisteredImageFormat::Rgba8, data)
1481    }
1482
1483    pub fn from_svg(svg: impl AsRef<[u8]>) -> Result<Self> {
1484        let svg = Arc::<[u8]>::from(svg.as_ref());
1485        let tree = parse_svg_image(&svg)?;
1486        let size = tree.size().to_int_size();
1487        let mut image = Self::from_svg_tree_at_size(&tree, size.width(), size.height())?;
1488        image.svg = Some(svg);
1489        Ok(image)
1490    }
1491
1492    pub fn from_svg_at_size(width: u32, height: u32, svg: impl AsRef<[u8]>) -> Result<Self> {
1493        let svg = Arc::<[u8]>::from(svg.as_ref());
1494        let tree = parse_svg_image(&svg)?;
1495        let mut image = Self::from_svg_tree_at_size(&tree, width, height)?;
1496        image.svg = Some(svg);
1497        Ok(image)
1498    }
1499
1500    pub fn from_pixels(
1501        width: u32,
1502        height: u32,
1503        format: RegisteredImageFormat,
1504        data: impl Into<Vec<u8>>,
1505    ) -> Result<Self> {
1506        let data = data.into();
1507        let expected_len = width as usize * height as usize * format.bytes_per_pixel();
1508        if data.len() != expected_len {
1509            return Err(Error::new(format!(
1510                "image data length {} does not match expected size {} for a {}x{} {:?} image",
1511                data.len(),
1512                expected_len,
1513                width,
1514                height,
1515                format
1516            )));
1517        }
1518
1519        Ok(Self {
1520            data: Arc::<[u8]>::from(data),
1521            width,
1522            height,
1523            format,
1524            svg: None,
1525            mipmaps_enabled: true,
1526        })
1527    }
1528
1529    /// Disables mipmap generation for this image.
1530    ///
1531    /// This is useful for frequently updated bitmap resources such as paint
1532    /// canvases, where rebuilding a full mip pyramid for every content update
1533    /// costs more than base-level linear filtering.
1534    pub const fn without_mipmaps(mut self) -> Self {
1535        self.mipmaps_enabled = false;
1536        self
1537    }
1538
1539    pub const fn mipmaps_enabled(&self) -> bool {
1540        self.mipmaps_enabled
1541    }
1542
1543    pub fn bytes(&self) -> &[u8] {
1544        &self.data
1545    }
1546
1547    pub const fn width(&self) -> u32 {
1548        self.width
1549    }
1550
1551    pub const fn height(&self) -> u32 {
1552        self.height
1553    }
1554
1555    pub const fn format(&self) -> RegisteredImageFormat {
1556        self.format
1557    }
1558
1559    pub fn is_svg(&self) -> bool {
1560        self.svg.is_some()
1561    }
1562
1563    pub fn svg_bytes(&self) -> Option<&[u8]> {
1564        self.svg.as_deref()
1565    }
1566
1567    pub fn rasterize_svg_at_size(&self, width: u32, height: u32) -> Result<Option<Self>> {
1568        let Some(svg) = &self.svg else {
1569            return Ok(None);
1570        };
1571        let tree = parse_svg_image(svg)?;
1572        Self::from_svg_tree_at_size(&tree, width, height).map(Some)
1573    }
1574
1575    fn from_svg_tree_at_size(tree: &resvg::usvg::Tree, width: u32, height: u32) -> Result<Self> {
1576        if width == 0 || height == 0 {
1577            return Err(Error::new("SVG raster dimensions must be non-zero"));
1578        }
1579
1580        let source_size = tree.size();
1581        let scale_x = width as f32 / source_size.width();
1582        let scale_y = height as f32 / source_size.height();
1583        let mut pixmap = resvg::tiny_skia::Pixmap::new(width, height)
1584            .ok_or_else(|| Error::new("failed to allocate SVG raster pixmap"))?;
1585        resvg::render(
1586            tree,
1587            resvg::tiny_skia::Transform::from_scale(scale_x, scale_y),
1588            &mut pixmap.as_mut(),
1589        );
1590
1591        let mut data = Vec::with_capacity(width as usize * height as usize * 4);
1592        for pixel in pixmap.pixels() {
1593            if pixel.alpha() == 0 {
1594                data.extend_from_slice(&[0, 0, 0, 0]);
1595            } else {
1596                let color = pixel.demultiply();
1597                data.extend_from_slice(&[color.red(), color.green(), color.blue(), color.alpha()]);
1598            }
1599        }
1600
1601        Self::from_rgba8(width, height, data)
1602    }
1603}
1604
1605fn parse_svg_image(svg: &[u8]) -> Result<resvg::usvg::Tree> {
1606    let options = resvg::usvg::Options::default();
1607    resvg::usvg::Tree::from_data(svg, &options)
1608        .map_err(|err| Error::new(format!("failed to parse SVG image: {err}")))
1609}
1610
1611#[derive(Debug, Clone, PartialEq, Eq, Default)]
1612pub struct ImageRegistry {
1613    images: HashMap<ImageHandle, RegisteredImage>,
1614    external_images: HashMap<ImageHandle, RegisteredExternalImage>,
1615}
1616
1617impl ImageRegistry {
1618    pub fn new() -> Self {
1619        Self::default()
1620    }
1621
1622    pub fn insert(
1623        &mut self,
1624        handle: ImageHandle,
1625        image: RegisteredImage,
1626    ) -> Option<RegisteredImage> {
1627        self.external_images.remove(&handle);
1628        self.images.insert(handle, image)
1629    }
1630
1631    pub fn insert_external(
1632        &mut self,
1633        handle: ImageHandle,
1634        image: RegisteredExternalImage,
1635    ) -> Option<RegisteredExternalImage> {
1636        self.images.remove(&handle);
1637        self.external_images.insert(handle, image)
1638    }
1639
1640    pub fn get(&self, handle: ImageHandle) -> Option<&RegisteredImage> {
1641        self.images.get(&handle)
1642    }
1643
1644    pub fn get_external(&self, handle: ImageHandle) -> Option<&RegisteredExternalImage> {
1645        self.external_images.get(&handle)
1646    }
1647
1648    pub fn dimensions(&self, handle: ImageHandle) -> Option<(u32, u32)> {
1649        self.get(handle)
1650            .map(|image| (image.width(), image.height()))
1651            .or_else(|| {
1652                self.get_external(handle)
1653                    .map(|image| (image.width(), image.height()))
1654            })
1655    }
1656
1657    pub fn contains(&self, handle: ImageHandle) -> bool {
1658        self.images.contains_key(&handle) || self.external_images.contains_key(&handle)
1659    }
1660
1661    pub fn iter(&self) -> impl Iterator<Item = (ImageHandle, &RegisteredImage)> {
1662        self.images.iter().map(|(handle, image)| (*handle, image))
1663    }
1664
1665    pub fn iter_external(&self) -> impl Iterator<Item = (ImageHandle, &RegisteredExternalImage)> {
1666        self.external_images
1667            .iter()
1668            .map(|(handle, image)| (*handle, image))
1669    }
1670
1671    pub fn len(&self) -> usize {
1672        self.images.len() + self.external_images.len()
1673    }
1674
1675    pub fn is_empty(&self) -> bool {
1676        self.images.is_empty() && self.external_images.is_empty()
1677    }
1678}
1679
1680#[derive(Debug, Clone, PartialEq)]
1681pub struct SceneFrame {
1682    /// Host render target for this frame. The target may be a platform window
1683    /// or an embedded viewport/region represented by SUI's `WindowId`.
1684    pub window_id: WindowId,
1685    pub viewport: Size,
1686    pub surface_size: Size,
1687    pub scale_factor: f32,
1688    pub dirty_regions: Vec<DirtyRegion>,
1689    pub layer_updates: Vec<SceneLayerUpdate>,
1690    pub scene: Scene,
1691    pub font_registry: Arc<FontRegistry>,
1692    pub image_registry: Arc<ImageRegistry>,
1693    pub text_layout_registry: Arc<TextLayoutRegistry>,
1694}
1695
1696impl SceneFrame {
1697    pub fn new(window_id: WindowId, viewport: Size) -> Self {
1698        Self {
1699            window_id,
1700            viewport,
1701            surface_size: viewport,
1702            scale_factor: 1.0,
1703            dirty_regions: Vec::new(),
1704            layer_updates: Vec::new(),
1705            scene: Scene::new(),
1706            font_registry: Arc::new(FontRegistry::new()),
1707            image_registry: Arc::new(ImageRegistry::new()),
1708            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
1709        }
1710    }
1711}
1712
1713#[cfg(test)]
1714mod tests {
1715    use super::{
1716        Brush, ImageRegistry, ImageSource, LayerCompositionMode, LayerProperties,
1717        RegisteredExternalImage, RegisteredImage, RegisteredImageFormat, Scene, SceneBoundsSummary,
1718        SceneCommand, SceneFrame, SceneLayer, SceneLayerDescriptor, SceneLayerId, SceneLayerUpdate,
1719        SceneLayerUpdateKind, ShadowParams, ShadowPlacement, StrokeStyle, TextRenderCoveragePolicy,
1720        TextRenderMode, TextRenderPolicy, TextSubpixelOrder, WidgetShader,
1721    };
1722    use std::sync::Arc;
1723    use sui_core::{
1724        Color, FontHandle, ImageHandle, Path, Point, Rect, Transform, Vector, WidgetId, WindowId,
1725    };
1726    use sui_text::{
1727        FontRegistry, RegisteredFont, ShapedText, ShapedTextWindow, TextRun, TextStyle, TextSystem,
1728    };
1729
1730    fn assert_send_sync<T: Send + Sync>() {}
1731
1732    fn assert_bounds_summary_matches_commands(scene: &Scene) {
1733        let recomputed = SceneBoundsSummary::from_commands(&scene.commands);
1734        assert_eq!(scene.bounds, recomputed);
1735        assert_eq!(scene.content_bounds(), recomputed.content);
1736        assert_eq!(scene.paint_bounds(), recomputed.paint);
1737    }
1738
1739    #[test]
1740    fn scene_frame_is_send_sync() {
1741        assert_send_sync::<SceneFrame>();
1742    }
1743
1744    #[test]
1745    fn layer_scale_maps_around_its_anchor() {
1746        let bounds = Rect::new(100.0, 50.0, 200.0, 100.0);
1747        let centered = LayerProperties::default().with_scale(0.5);
1748
1749        assert_eq!(
1750            centered.map_rect(bounds, bounds),
1751            Rect::new(150.0, 75.0, 100.0, 50.0)
1752        );
1753        let top = centered
1754            .with_scale_anchor(Vector::new(0.5, 0.0))
1755            .with_translation(Vector::new(0.0, 8.0));
1756        assert_eq!(
1757            top.map_rect(bounds, bounds),
1758            Rect::new(150.0, 58.0, 100.0, 50.0)
1759        );
1760        let transform = top.transform(bounds);
1761        let corner = transform.transform_point(Point::new(100.0, 50.0));
1762        assert_eq!(corner, Point::new(150.0, 58.0));
1763        assert!(!LayerProperties::default().is_scaled());
1764    }
1765
1766    #[test]
1767    fn translating_a_scene_moves_gradient_axes_with_their_shapes() {
1768        let gradient = |start: Point, end: Point| Brush::LinearGradient {
1769            start,
1770            end,
1771            stops: vec![
1772                super::GradientStop {
1773                    offset: 0.0,
1774                    color: Color::rgba(1.0, 0.0, 0.0, 1.0),
1775                },
1776                super::GradientStop {
1777                    offset: 1.0,
1778                    color: Color::rgba(0.0, 0.0, 1.0, 1.0),
1779                },
1780            ],
1781        };
1782        let axis = |brush: &Brush| match brush {
1783            Brush::LinearGradient { start, end, .. } => (*start, *end),
1784            Brush::Solid(_) => panic!("a gradient brush"),
1785        };
1786        let (start, end) = (Point::new(10.0, 5.0), Point::new(90.0, 5.0));
1787        let mut path = Path::builder();
1788        path.move_to(Point::new(10.0, 0.0));
1789        path.line_to(Point::new(90.0, 0.0));
1790        path.line_to(Point::new(90.0, 10.0));
1791        path.close();
1792        let path = path.build();
1793        let mut scene = Scene::new();
1794        scene.push(SceneCommand::FillRect {
1795            rect: Rect::new(10.0, 0.0, 80.0, 10.0),
1796            brush: gradient(start, end),
1797        });
1798        scene.push(SceneCommand::StrokeRect {
1799            rect: Rect::new(10.0, 0.0, 80.0, 10.0),
1800            brush: gradient(start, end),
1801            stroke: StrokeStyle::new(1.0),
1802        });
1803        scene.push(SceneCommand::FillPath {
1804            path: path.clone(),
1805            brush: gradient(start, end),
1806        });
1807        scene.push(SceneCommand::StrokePath {
1808            path,
1809            brush: gradient(start, end),
1810            stroke: StrokeStyle::new(1.0),
1811        });
1812        scene.push(SceneCommand::FillRoundedRect {
1813            rect: Rect::new(10.0, 0.0, 80.0, 10.0),
1814            radii: [4.0; 4],
1815            brush: gradient(start, end),
1816            border: None,
1817            shadow: None,
1818        });
1819
1820        let delta = Vector::new(3.0, 40.0);
1821        scene.translate(delta);
1822        let moved = (start + delta, end + delta);
1823        for command in scene.commands() {
1824            let brush = match command {
1825                SceneCommand::FillRect { brush, .. }
1826                | SceneCommand::StrokeRect { brush, .. }
1827                | SceneCommand::FillPath { brush, .. }
1828                | SceneCommand::StrokePath { brush, .. }
1829                | SceneCommand::FillRoundedRect { brush, .. } => brush,
1830                other => panic!("unexpected command {other:?}"),
1831            };
1832            assert_eq!(axis(brush), moved, "{command:?}");
1833        }
1834    }
1835
1836    #[test]
1837    fn borrowed_append_preserves_commands_bounds_and_source_under_nested_scopes() {
1838        for inherited in [false, true] {
1839            for unbalanced_source in [false, true] {
1840                let mut source = Scene::new();
1841                source.push(SceneCommand::PushTransform {
1842                    transform: Transform::translation(4.0, 7.0),
1843                });
1844                source.push(SceneCommand::FillRect {
1845                    rect: Rect::new(2.0, 3.0, 20.0, 30.0),
1846                    brush: Color::WHITE.into(),
1847                });
1848                if !unbalanced_source {
1849                    source.push(SceneCommand::PopTransform);
1850                }
1851                let snapshot = source.clone();
1852                let mut actual = Scene::new();
1853                if inherited {
1854                    actual.push(SceneCommand::PushClip {
1855                        rect: Rect::new(0.0, 0.0, 16.0, 18.0),
1856                    });
1857                    actual.push(SceneCommand::PushTransform {
1858                        transform: Transform::translation(1.0, 2.0),
1859                    });
1860                }
1861                let mut expected = actual.clone();
1862                expected.append(source.clone());
1863                actual.append_ref(&source);
1864                assert_eq!(actual, expected);
1865                assert_eq!(source, snapshot);
1866                assert_bounds_summary_matches_commands(&actual);
1867                source.clear();
1868                assert_eq!(actual, expected);
1869            }
1870        }
1871    }
1872
1873    #[test]
1874    fn scene_command_variants_store_extended_primitives() {
1875        let text = SceneCommand::DrawText(TextRun {
1876            rect: Rect::new(4.0, 8.0, 120.0, 24.0),
1877            text: "hello".to_string(),
1878            style: TextStyle::new(Color::WHITE),
1879        });
1880        let shaped_layout = TextSystem::new()
1881            .shape_text_persistent(
1882                None,
1883                "hello",
1884                sui_core::Size::new(120.0, 24.0),
1885                TextStyle::new(Color::WHITE),
1886                &FontRegistry::new(),
1887            )
1888            .unwrap();
1889        let shaped_text = SceneCommand::DrawShapedText(ShapedText {
1890            origin: Point::new(4.0, 8.0),
1891            layout_handle: shaped_layout.handle(),
1892            layout_version: shaped_layout.version(),
1893            bounds: shaped_layout.measurement().bounds,
1894            color_override: None,
1895        });
1896        let shaped_window = SceneCommand::DrawShapedTextWindow(ShapedTextWindow::new(
1897            Point::new(4.0, 8.0),
1898            &shaped_layout,
1899            0..1,
1900        ));
1901        let image = SceneCommand::DrawImage {
1902            rect: Rect::new(0.0, 0.0, 32.0, 32.0),
1903            source: ImageSource::new(ImageHandle::new(7))
1904                .with_tint(Color::rgba(1.0, 0.0, 0.0, 1.0)),
1905        };
1906        let shader = SceneCommand::DrawShaderRect {
1907            rect: Rect::new(0.0, 0.0, 32.0, 8.0),
1908            shader: WidgetShader::ColorPickerHueBar,
1909        };
1910        let stroke = SceneCommand::StrokeRect {
1911            rect: Rect::new(1.0, 2.0, 30.0, 12.0),
1912            brush: Brush::Solid(Color::BLACK),
1913            stroke: StrokeStyle::new(2.0),
1914        };
1915        let path_fill = SceneCommand::FillPath {
1916            path: Path::from(Rect::new(3.0, 4.0, 12.0, 10.0)),
1917            brush: Brush::Solid(Color::WHITE),
1918        };
1919        let clip_path = SceneCommand::PushClipPath {
1920            path: Path::circle(sui_core::Point::new(10.0, 10.0), 4.0),
1921        };
1922        let transform = SceneCommand::PushTransform {
1923            transform: Transform::translation(3.0, 5.0),
1924        };
1925        let text_policy = SceneCommand::PushTextRenderPolicy {
1926            policy: TextRenderPolicy::new()
1927                .with_render_mode(TextRenderMode::LcdSubpixel)
1928                .with_subpixel_order(TextSubpixelOrder::Rgb)
1929                .with_coverage_policy(TextRenderCoveragePolicy::TwoCoverageMinusCoverageSq),
1930        };
1931        let layer = SceneCommand::Layer(SceneLayer::new(
1932            WidgetId::new(9),
1933            Rect::new(1.0, 2.0, 30.0, 12.0),
1934            Scene::new(),
1935        ));
1936
1937        assert!(matches!(text, SceneCommand::DrawText(_)));
1938        assert!(matches!(shaped_text, SceneCommand::DrawShapedText(_)));
1939        assert!(matches!(
1940            shaped_window,
1941            SceneCommand::DrawShapedTextWindow(_)
1942        ));
1943        assert!(matches!(image, SceneCommand::DrawImage { .. }));
1944        assert!(matches!(shader, SceneCommand::DrawShaderRect { .. }));
1945        assert!(matches!(stroke, SceneCommand::StrokeRect { .. }));
1946        assert!(matches!(path_fill, SceneCommand::FillPath { .. }));
1947        assert!(matches!(clip_path, SceneCommand::PushClipPath { .. }));
1948        assert!(matches!(transform, SceneCommand::PushTransform { .. }));
1949        assert!(matches!(
1950            text_policy,
1951            SceneCommand::PushTextRenderPolicy { .. }
1952        ));
1953        assert!(matches!(layer, SceneCommand::Layer(_)));
1954    }
1955
1956    #[test]
1957    fn scene_frame_can_share_font_registry_snapshots() {
1958        let mut registry = FontRegistry::new();
1959        registry.insert(
1960            FontHandle::new(9),
1961            RegisteredFont::from_bytes(vec![1, 2, 3]),
1962        );
1963
1964        let mut frame = SceneFrame::new(WindowId::new(4), sui_core::Size::new(32.0, 24.0));
1965        frame.font_registry = Arc::new(registry);
1966
1967        assert_eq!(frame.font_registry.len(), 1);
1968        assert!(frame.font_registry.contains(FontHandle::new(9)));
1969        assert!(frame.layer_updates.is_empty());
1970    }
1971
1972    #[test]
1973    fn scene_frame_can_share_image_registry_snapshots() {
1974        let mut registry = ImageRegistry::new();
1975        registry.insert(
1976            ImageHandle::new(5),
1977            RegisteredImage::from_rgba8(1, 1, vec![255, 128, 64, 255]).unwrap(),
1978        );
1979
1980        let mut frame = SceneFrame::new(WindowId::new(8), sui_core::Size::new(48.0, 32.0));
1981        frame.image_registry = Arc::new(registry);
1982
1983        assert_eq!(frame.image_registry.len(), 1);
1984        assert!(frame.image_registry.contains(ImageHandle::new(5)));
1985        assert!(frame.layer_updates.is_empty());
1986
1987        let descriptor = SceneLayerDescriptor::new(
1988            SceneLayerId::new(12),
1989            WidgetId::new(4),
1990            Rect::new(2.0, 3.0, 40.0, 20.0),
1991        )
1992        .with_content_bounds(Rect::new(0.0, 0.0, 80.0, 32.0))
1993        .with_paint_bounds(Rect::new(2.0, 3.0, 40.0, 20.0))
1994        .with_composition_mode(LayerCompositionMode::Scroll);
1995        let update = SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Transform, descriptor)
1996            .with_damage(Rect::new(1.0, 2.0, 42.0, 24.0));
1997
1998        assert_eq!(update.layer_id.get(), 12);
1999        assert_eq!(update.owner, WidgetId::new(4));
2000        assert_eq!(update.kind, SceneLayerUpdateKind::Transform);
2001        assert_eq!(update.damage, Some(Rect::new(1.0, 2.0, 42.0, 24.0)));
2002    }
2003
2004    #[test]
2005    fn image_registry_tracks_external_dimensions_and_one_backing_per_handle() {
2006        let handle = ImageHandle::new(15);
2007        let mut registry = ImageRegistry::new();
2008        registry.insert_external(handle, RegisteredExternalImage::new(640, 360).unwrap());
2009
2010        assert!(registry.contains(handle));
2011        assert_eq!(registry.dimensions(handle), Some((640, 360)));
2012        assert!(registry.get(handle).is_none());
2013        assert!(registry.get_external(handle).is_some());
2014
2015        registry.insert(
2016            handle,
2017            RegisteredImage::from_rgba8(1, 1, vec![1, 2, 3, 255]).unwrap(),
2018        );
2019        assert_eq!(registry.dimensions(handle), Some((1, 1)));
2020        assert!(registry.get(handle).is_some());
2021        assert!(registry.get_external(handle).is_none());
2022    }
2023
2024    #[test]
2025    fn scene_layer_descriptor_defaults_to_identity_layer_properties() {
2026        let descriptor = SceneLayerDescriptor::new(
2027            SceneLayerId::new(19),
2028            WidgetId::new(7),
2029            Rect::new(10.0, 12.0, 48.0, 24.0),
2030        );
2031
2032        assert_eq!(descriptor.properties, LayerProperties::default());
2033        assert_eq!(descriptor.properties.opacity, 1.0);
2034        assert_eq!(descriptor.properties.translation, Vector::ZERO);
2035        assert_eq!(descriptor.presented_bounds(), descriptor.bounds);
2036        assert_eq!(descriptor.presented_paint_bounds(), descriptor.paint_bounds);
2037    }
2038
2039    #[test]
2040    fn scene_layer_update_preserves_dynamic_layer_properties() {
2041        let descriptor = SceneLayerDescriptor::new(
2042            SceneLayerId::new(27),
2043            WidgetId::new(11),
2044            Rect::new(4.0, 6.0, 32.0, 18.0),
2045        )
2046        .with_content_bounds(Rect::new(4.0, 6.0, 32.0, 18.0))
2047        .with_paint_bounds(Rect::new(2.0, 4.0, 36.0, 22.0))
2048        .with_properties(
2049            LayerProperties::default()
2050                .with_opacity(0.35)
2051                .with_translation(Vector::new(14.0, -3.0)),
2052        );
2053        let update =
2054            SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Effect, descriptor.clone());
2055
2056        assert_eq!(update.properties.opacity, 0.35);
2057        assert_eq!(update.properties.translation, Vector::new(14.0, -3.0));
2058        assert_eq!(
2059            descriptor.presented_paint_bounds(),
2060            Rect::new(16.0, 1.0, 36.0, 22.0)
2061        );
2062    }
2063
2064    #[test]
2065    fn registered_image_validates_pixel_buffer_length() {
2066        let error = RegisteredImage::from_rgba8(2, 2, vec![0, 1, 2]).unwrap_err();
2067
2068        assert!(
2069            error
2070                .to_string()
2071                .contains("image data length 3 does not match")
2072        );
2073    }
2074
2075    #[test]
2076    fn registered_image_rasterizes_svg_at_natural_size() {
2077        let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="2" viewBox="0 0 4 2"><rect width="4" height="2" fill="#336699"/></svg>"##;
2078
2079        let image = RegisteredImage::from_svg(svg).unwrap();
2080
2081        assert_eq!(image.width(), 4);
2082        assert_eq!(image.height(), 2);
2083        assert_eq!(image.format(), RegisteredImageFormat::Rgba8);
2084        assert_eq!(image.bytes().len(), 4 * 2 * 4);
2085        assert_eq!(&image.bytes()[0..4], &[0x33, 0x66, 0x99, 0xff]);
2086        assert!(image.is_svg());
2087        assert_eq!(image.svg_bytes(), Some(svg.as_slice()));
2088
2089        let larger = image
2090            .rasterize_svg_at_size(12, 6)
2091            .unwrap()
2092            .expect("retained SVG should rerasterize");
2093        assert_eq!((larger.width(), larger.height()), (12, 6));
2094        assert!(!larger.is_svg());
2095    }
2096
2097    #[test]
2098    fn registered_image_rasterizes_svg_at_requested_size() {
2099        let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4 4"><circle cx="2" cy="2" r="2" fill="white"/></svg>"##;
2100
2101        let image = RegisteredImage::from_svg_at_size(16, 8, svg).unwrap();
2102
2103        assert_eq!(image.width(), 16);
2104        assert_eq!(image.height(), 8);
2105        assert_eq!(image.bytes().len(), 16 * 8 * 4);
2106        assert!(
2107            image
2108                .bytes()
2109                .as_chunks::<4>()
2110                .0
2111                .iter()
2112                .any(|pixel| pixel[3] > 0)
2113        );
2114    }
2115
2116    #[test]
2117    fn registered_image_rejects_invalid_svg() {
2118        let error = RegisteredImage::from_svg(b"not svg").unwrap_err();
2119
2120        assert!(error.to_string().contains("failed to parse SVG image"));
2121    }
2122
2123    #[test]
2124    fn scene_replace_layer_updates_nested_widget_scene() {
2125        let mut child_scene = Scene::new();
2126        child_scene.push(SceneCommand::FillRect {
2127            rect: Rect::new(2.0, 2.0, 6.0, 6.0),
2128            brush: Brush::Solid(Color::WHITE),
2129        });
2130
2131        let mut root = Scene::new();
2132        root.push(SceneCommand::FillRect {
2133            rect: Rect::new(0.0, 0.0, 20.0, 20.0),
2134            brush: Brush::Solid(Color::BLACK),
2135        });
2136        root.push(SceneCommand::Layer(SceneLayer::new(
2137            WidgetId::new(2),
2138            Rect::new(1.0, 1.0, 10.0, 10.0),
2139            child_scene,
2140        )));
2141
2142        let mut replacement = Scene::new();
2143        replacement.push(SceneCommand::FillRect {
2144            rect: Rect::new(4.0, 4.0, 8.0, 8.0),
2145            brush: Brush::Solid(Color::rgba(0.0, 1.0, 0.0, 1.0)),
2146        });
2147
2148        assert!(root.replace_layer(
2149            WidgetId::new(2),
2150            SceneLayer::new(
2151                WidgetId::new(2),
2152                Rect::new(1.0, 1.0, 10.0, 10.0),
2153                replacement
2154            ),
2155        ));
2156
2157        let mut command_count = 0usize;
2158        let mut saw_nested_fill = false;
2159        root.visit_commands(&mut |command| {
2160            command_count += 1;
2161            if let SceneCommand::FillRect { rect, .. } = command
2162                && *rect == Rect::new(4.0, 4.0, 8.0, 8.0)
2163            {
2164                saw_nested_fill = true;
2165            }
2166        });
2167
2168        assert_eq!(command_count, 3);
2169        assert!(saw_nested_fill);
2170    }
2171
2172    #[test]
2173    fn scene_clones_share_storage_and_detach_all_mutations() {
2174        let child_id = WidgetId::new(501);
2175        let mut child = Scene::new();
2176        child.push(SceneCommand::FillRect {
2177            rect: Rect::new(2.0, 3.0, 10.0, 12.0),
2178            brush: Color::WHITE.into(),
2179        });
2180        let mut scene = Scene::new();
2181        scene.push(SceneCommand::Layer(SceneLayer::new(
2182            child_id,
2183            Rect::new(0.0, 0.0, 20.0, 20.0),
2184            child,
2185        )));
2186        let expected_commands = scene.commands().to_vec();
2187        let expected_bounds = scene.paint_bounds();
2188        for mutation in 0..7 {
2189            let mut edited = scene.clone();
2190            assert!(edited.shares_commands_with(&scene));
2191            match mutation {
2192                0 => edited.push(SceneCommand::Clear(Color::BLACK)),
2193                1 => edited.append(scene.clone()),
2194                2 => edited.append_ref(&scene),
2195                3 => edited.clear(),
2196                4 => edited.translate(Vector::new(9.0, 4.0)),
2197                5 => {
2198                    assert!(edited.translate_layer(child_id, Vector::new(9.0, 4.0)));
2199                }
2200                _ => {
2201                    edited.visit_layers_mut(&mut |layer| layer.descriptor.properties.opacity = 0.5)
2202                }
2203            }
2204            assert!(!edited.shares_commands_with(&scene));
2205            assert_eq!(scene.commands(), expected_commands);
2206            assert_eq!(scene.paint_bounds(), expected_bounds);
2207            assert_bounds_summary_matches_commands(&edited);
2208            assert_bounds_summary_matches_commands(&scene);
2209        }
2210    }
2211
2212    #[test]
2213    fn shadows_reach_three_deviations_of_half_their_blur_except_inside() {
2214        let rect = Rect::new(20.0, 20.0, 40.0, 30.0);
2215        let bounds = |shadow: ShadowParams| {
2216            let mut scene = Scene::new();
2217            scene.push(SceneCommand::FillRoundedRect {
2218                rect,
2219                radii: [4.0; 4],
2220                brush: Brush::Solid(Color::WHITE),
2221                border: None,
2222                shadow: Some(shadow),
2223            });
2224            scene.content_bounds()
2225        };
2226        let black = Color::BLACK;
2227        // Blur 8 is a deviation of 4: 12 px of reach, plus the spread, moved
2228        // by the offset.
2229        let behind = ShadowParams::new(0.0, 6.0, 8.0, 2.0, black);
2230        assert_eq!(behind.sigma(), 4.0);
2231        assert_eq!(behind.extent(), 12.0 + 2.0 + 6.0);
2232        assert_eq!(
2233            bounds(behind),
2234            Some(rect.union(rect.inflate(20.0, 20.0).translate(Vector::new(0.0, 6.0))))
2235        );
2236        let glow = ShadowParams::glow(8.0, 0.0, black);
2237        assert_eq!(glow.placement, ShadowPlacement::Outside);
2238        assert_eq!(bounds(glow), Some(rect.inflate(12.0, 12.0)));
2239        let inset = ShadowParams::inset(0.0, 6.0, 8.0, 2.0, black);
2240        assert_eq!(inset.extent(), 0.0);
2241        assert_eq!(
2242            bounds(inset),
2243            Some(rect),
2244            "an inset shadow stays in its box"
2245        );
2246    }
2247
2248    #[test]
2249    fn scene_bounds_summary_stays_exact_through_all_mutation_paths() {
2250        let mut scene = Scene::default();
2251        assert_eq!(scene.content_bounds(), None);
2252        assert_eq!(scene.paint_bounds(), None);
2253        assert_bounds_summary_matches_commands(&scene);
2254
2255        scene.push(SceneCommand::PushClip {
2256            rect: Rect::new(0.0, 0.0, 50.0, 50.0),
2257        });
2258        scene.push(SceneCommand::PushTransform {
2259            transform: Transform::translation(10.0, 5.0),
2260        });
2261        scene.push(SceneCommand::FillRect {
2262            rect: Rect::new(30.0, 30.0, 40.0, 40.0),
2263            brush: Brush::Solid(Color::WHITE),
2264        });
2265        assert_eq!(
2266            scene.content_bounds(),
2267            Some(Rect::new(40.0, 35.0, 40.0, 40.0))
2268        );
2269        assert_eq!(
2270            scene.paint_bounds(),
2271            Some(Rect::new(40.0, 35.0, 10.0, 15.0))
2272        );
2273        assert_bounds_summary_matches_commands(&scene);
2274
2275        let mut appended = Scene::new();
2276        appended.push(SceneCommand::FillRect {
2277            rect: Rect::new(-8.0, -6.0, 4.0, 3.0),
2278            brush: Brush::Solid(Color::BLACK),
2279        });
2280        appended.push(SceneCommand::PushClip {
2281            rect: Rect::new(-10.0, -10.0, 20.0, 20.0),
2282        });
2283        appended.push(SceneCommand::Clear(Color::BLACK));
2284        appended.push(SceneCommand::PopClip);
2285        assert_bounds_summary_matches_commands(&appended);
2286
2287        // The destination has an open clip and transform, so append must replay the
2288        // incoming commands against that state rather than just unioning its bounds.
2289        scene.append(appended);
2290        scene.push(SceneCommand::PopTransform);
2291        scene.push(SceneCommand::PopClip);
2292        assert_bounds_summary_matches_commands(&scene);
2293
2294        let child_id = WidgetId::new(41);
2295        let grandchild_id = WidgetId::new(42);
2296        let mut grandchild_scene = Scene::new();
2297        grandchild_scene.push(SceneCommand::FillRect {
2298            rect: Rect::new(4.0, 6.0, 12.0, 8.0),
2299            brush: Brush::Solid(Color::WHITE),
2300        });
2301        let mut child_scene = Scene::new();
2302        child_scene.push(SceneCommand::Layer(SceneLayer::new(
2303            grandchild_id,
2304            Rect::new(4.0, 6.0, 12.0, 8.0),
2305            grandchild_scene,
2306        )));
2307        scene.push(SceneCommand::Layer(SceneLayer::new(
2308            child_id,
2309            Rect::new(2.0, 3.0, 24.0, 18.0),
2310            child_scene,
2311        )));
2312        assert_bounds_summary_matches_commands(&scene);
2313
2314        let mut replacement_scene = Scene::new();
2315        replacement_scene.push(SceneCommand::FillRect {
2316            rect: Rect::new(20.0, 22.0, 14.0, 10.0),
2317            brush: Brush::Solid(Color::BLACK),
2318        });
2319        assert!(scene.replace_layer(
2320            grandchild_id,
2321            SceneLayer::new(
2322                grandchild_id,
2323                Rect::new(20.0, 22.0, 14.0, 10.0),
2324                replacement_scene,
2325            ),
2326        ));
2327        assert_bounds_summary_matches_commands(&scene);
2328
2329        assert!(scene.translate_layer(grandchild_id, Vector::new(7.0, -2.0)));
2330        assert_bounds_summary_matches_commands(&scene);
2331
2332        let replacement_descriptor = SceneLayerDescriptor::new(
2333            SceneLayerId::from_widget(grandchild_id),
2334            grandchild_id,
2335            Rect::new(27.0, 20.0, 14.0, 10.0),
2336        )
2337        .with_content_bounds(Rect::new(25.0, 18.0, 18.0, 14.0))
2338        .with_paint_bounds(Rect::new(24.0, 17.0, 20.0, 16.0));
2339        assert!(scene.replace_layer_descriptor(grandchild_id, replacement_descriptor));
2340        assert_bounds_summary_matches_commands(&scene);
2341
2342        scene.visit_layers_mut(&mut |layer| {
2343            layer.descriptor.paint_bounds = layer.descriptor.paint_bounds.inflate(1.0, 2.0);
2344            Arc::make_mut(&mut layer.scene).push(SceneCommand::Label {
2345                rect: Rect::new(1.0, 2.0, 3.0, 4.0),
2346                text: "cache mutation".to_string(),
2347                color: Color::WHITE,
2348            });
2349        });
2350        assert_bounds_summary_matches_commands(&scene);
2351
2352        let mut reordered = Scene::new();
2353        reordered.push(SceneCommand::PushClip {
2354            rect: Rect::new(0.0, 0.0, 10.0, 10.0),
2355        });
2356        reordered.push(SceneCommand::Layer(SceneLayer::from_descriptor(
2357            SceneLayerDescriptor::new(
2358                SceneLayerId::new(91),
2359                WidgetId::new(91),
2360                Rect::new(0.0, 0.0, 100.0, 10.0),
2361            )
2362            .with_is_stack_surface(true)
2363            .with_stack_order(1),
2364            Scene::new(),
2365        )));
2366        reordered.push(SceneCommand::PopClip);
2367        reordered.push(SceneCommand::PushClip {
2368            rect: Rect::new(50.0, 0.0, 10.0, 10.0),
2369        });
2370        reordered.push(SceneCommand::Layer(SceneLayer::from_descriptor(
2371            SceneLayerDescriptor::new(
2372                SceneLayerId::new(92),
2373                WidgetId::new(92),
2374                Rect::new(50.0, 0.0, 100.0, 10.0),
2375            )
2376            .with_is_stack_surface(true)
2377            .with_stack_order(0),
2378            Scene::new(),
2379        )));
2380        reordered.push(SceneCommand::PopClip);
2381        assert_eq!(
2382            reordered.paint_bounds(),
2383            Some(Rect::new(0.0, 0.0, 60.0, 10.0))
2384        );
2385        reordered.reorder_stack_surfaces();
2386        assert_eq!(
2387            reordered.paint_bounds(),
2388            Some(Rect::new(50.0, 0.0, 10.0, 10.0))
2389        );
2390        assert_bounds_summary_matches_commands(&reordered);
2391        scene.append(reordered);
2392        assert_bounds_summary_matches_commands(&scene);
2393
2394        scene.translate(Vector::new(-3.0, 9.0));
2395        assert_bounds_summary_matches_commands(&scene);
2396
2397        // A balanced scene can be appended by merging summaries without replaying
2398        // its command stream. The result must still match a complete recomputation.
2399        let mut balanced = Scene::new();
2400        balanced.push(SceneCommand::PushTransform {
2401            transform: Transform::translation(2.0, 4.0),
2402        });
2403        balanced.push(SceneCommand::FillRect {
2404            rect: Rect::new(0.0, 0.0, 5.0, 7.0),
2405            brush: Brush::Solid(Color::WHITE),
2406        });
2407        balanced.push(SceneCommand::PopTransform);
2408        scene.append(balanced);
2409        assert_bounds_summary_matches_commands(&scene);
2410
2411        let clone = scene.clone();
2412        assert_eq!(scene, clone);
2413        assert_bounds_summary_matches_commands(&clone);
2414
2415        scene.clear();
2416        assert_eq!(scene, Scene::default());
2417        assert_eq!(scene.content_bounds(), None);
2418        assert_eq!(scene.paint_bounds(), None);
2419        assert_bounds_summary_matches_commands(&scene);
2420    }
2421}