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, PathElement, Point, Rect, Result,
7    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
850#[derive(Clone, Default)]
851pub struct Scene {
852    commands: Arc<Vec<SceneCommand>>,
853    bounds: SceneBoundsSummary,
854}
855
856impl std::fmt::Debug for Scene {
857    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
858        formatter
859            .debug_struct("Scene")
860            .field("commands", &self.commands)
861            .finish()
862    }
863}
864
865impl PartialEq for Scene {
866    fn eq(&self, other: &Self) -> bool {
867        self.commands == other.commands
868    }
869}
870
871impl Scene {
872    pub fn new() -> Self {
873        Self::default()
874    }
875
876    pub fn push(&mut self, command: SceneCommand) {
877        self.bounds.push(&command);
878        Arc::make_mut(&mut self.commands).push(command);
879    }
880
881    pub fn append(&mut self, scene: Scene) {
882        if self.bounds.state.is_balanced() && scene.bounds.state.is_balanced() {
883            self.bounds.extend(&scene.bounds);
884        } else {
885            for command in scene.commands.iter() {
886                self.bounds.push(command);
887            }
888        }
889        Arc::make_mut(&mut self.commands).append(&mut Arc::unwrap_or_clone(scene.commands));
890    }
891
892    /// Append a retained scene without allocating an intermediate command vector.
893    pub fn append_ref(&mut self, scene: &Scene) {
894        if self.bounds.state.is_balanced() && scene.bounds.state.is_balanced() {
895            self.bounds.extend(&scene.bounds);
896        } else {
897            for command in scene.commands.iter() {
898                self.bounds.push(command);
899            }
900        }
901        Arc::make_mut(&mut self.commands).extend(scene.commands.iter().cloned());
902    }
903
904    pub fn clear(&mut self) {
905        if let Some(commands) = Arc::get_mut(&mut self.commands) {
906            commands.clear();
907        } else {
908            self.commands = Arc::default();
909        }
910        self.bounds = SceneBoundsSummary::default();
911    }
912
913    pub fn commands(&self) -> &[SceneCommand] {
914        &self.commands
915    }
916
917    /// Whether two immutable snapshots share the same command storage.
918    /// Any mutation detaches shared storage before changing commands.
919    pub fn shares_commands_with(&self, other: &Self) -> bool {
920        Arc::ptr_eq(&self.commands, &other.commands)
921    }
922
923    pub fn visit_commands(&self, visitor: &mut dyn FnMut(&SceneCommand)) {
924        for command in self.commands.iter() {
925            visitor(command);
926            if let SceneCommand::Layer(layer) = command {
927                layer.scene.visit_commands(visitor);
928            }
929        }
930    }
931
932    pub fn visit_layers(&self, visitor: &mut dyn FnMut(&SceneLayer)) {
933        for command in self.commands.iter() {
934            if let SceneCommand::Layer(layer) = command {
935                visitor(layer);
936                layer.scene.visit_layers(visitor);
937            }
938        }
939    }
940
941    pub fn visit_layers_mut(&mut self, visitor: &mut dyn FnMut(&mut SceneLayer)) {
942        for command in Arc::make_mut(&mut self.commands) {
943            if let SceneCommand::Layer(layer) = command {
944                visitor(layer);
945                if layer
946                    .scene
947                    .commands()
948                    .iter()
949                    .any(|command| matches!(command, SceneCommand::Layer(_)))
950                {
951                    Arc::make_mut(&mut layer.scene).visit_layers_mut(visitor);
952                }
953            }
954        }
955        self.rebuild_bounds();
956    }
957
958    pub fn content_bounds(&self) -> Option<Rect> {
959        self.bounds.content
960    }
961
962    pub fn paint_bounds(&self) -> Option<Rect> {
963        self.bounds.paint
964    }
965
966    pub fn replace_layer(&mut self, widget_id: WidgetId, replacement: SceneLayer) -> bool {
967        let mut replaced = false;
968        for command in Arc::make_mut(&mut self.commands) {
969            match command {
970                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
971                    *command = SceneCommand::Layer(replacement);
972                    replaced = true;
973                    break;
974                }
975                SceneCommand::Layer(layer) => {
976                    if Arc::make_mut(&mut layer.scene).replace_layer(widget_id, replacement.clone())
977                    {
978                        replaced = true;
979                        break;
980                    }
981                }
982                _ => {}
983            }
984        }
985
986        if replaced {
987            self.rebuild_bounds();
988        }
989        replaced
990    }
991
992    pub fn translate(&mut self, delta: Vector) {
993        if delta == Vector::ZERO {
994            return;
995        }
996        for command in Arc::make_mut(&mut self.commands) {
997            translate_command(command, delta);
998        }
999        self.rebuild_bounds();
1000    }
1001
1002    pub fn translate_layer(&mut self, widget_id: WidgetId, delta: Vector) -> bool {
1003        let mut translated = false;
1004        for command in Arc::make_mut(&mut self.commands) {
1005            match command {
1006                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
1007                    layer.translate(delta);
1008                    translated = true;
1009                    break;
1010                }
1011                SceneCommand::Layer(layer) => {
1012                    if Arc::make_mut(&mut layer.scene).translate_layer(widget_id, delta) {
1013                        translated = true;
1014                        break;
1015                    }
1016                }
1017                _ => {}
1018            }
1019        }
1020
1021        if translated {
1022            self.rebuild_bounds();
1023        }
1024        translated
1025    }
1026
1027    pub fn replace_layer_descriptor(
1028        &mut self,
1029        widget_id: WidgetId,
1030        descriptor: SceneLayerDescriptor,
1031    ) -> bool {
1032        let mut replaced = false;
1033        for command in Arc::make_mut(&mut self.commands) {
1034            match command {
1035                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
1036                    layer.descriptor = descriptor;
1037                    replaced = true;
1038                    break;
1039                }
1040                SceneCommand::Layer(layer) => {
1041                    if Arc::make_mut(&mut layer.scene)
1042                        .replace_layer_descriptor(widget_id, descriptor.clone())
1043                    {
1044                        replaced = true;
1045                        break;
1046                    }
1047                }
1048                _ => {}
1049            }
1050        }
1051
1052        if replaced {
1053            self.rebuild_bounds();
1054        }
1055        replaced
1056    }
1057
1058    pub fn layer_scene(&self, widget_id: WidgetId) -> Option<&Scene> {
1059        for command in self.commands.iter() {
1060            match command {
1061                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
1062                    return Some(&layer.scene);
1063                }
1064                SceneCommand::Layer(layer) => {
1065                    if let Some(scene) = layer.scene.layer_scene(widget_id) {
1066                        return Some(scene);
1067                    }
1068                }
1069                _ => {}
1070            }
1071        }
1072
1073        None
1074    }
1075
1076    pub fn reorder_stack_surfaces(&mut self) {
1077        let mut stack_layers = self
1078            .commands
1079            .iter()
1080            .enumerate()
1081            .filter_map(|(index, command)| match command {
1082                SceneCommand::Layer(layer) if layer.descriptor.is_stack_surface => {
1083                    Some((index, layer.clone()))
1084                }
1085                _ => None,
1086            })
1087            .collect::<Vec<_>>();
1088
1089        stack_layers.sort_by_key(|(index, layer)| (layer.descriptor.stack_order, *index));
1090
1091        let mut sorted_layers = stack_layers.into_iter().map(|(_, layer)| layer);
1092        for command in Arc::make_mut(&mut self.commands) {
1093            if let SceneCommand::Layer(layer) = command {
1094                if layer
1095                    .scene
1096                    .commands()
1097                    .iter()
1098                    .any(|command| matches!(command, SceneCommand::Layer(_)))
1099                {
1100                    Arc::make_mut(&mut layer.scene).reorder_stack_surfaces();
1101                }
1102                if layer.descriptor.is_stack_surface
1103                    && let Some(replacement) = sorted_layers.next()
1104                {
1105                    *layer = replacement;
1106                }
1107            }
1108        }
1109        self.rebuild_bounds();
1110    }
1111
1112    fn rebuild_bounds(&mut self) {
1113        self.bounds = SceneBoundsSummary::from_commands(&self.commands);
1114    }
1115}
1116
1117#[derive(Debug, Clone, Default, PartialEq)]
1118struct SceneBoundsSummary {
1119    state: SceneBoundsState,
1120    content: Option<Rect>,
1121    paint: Option<Rect>,
1122}
1123
1124impl SceneBoundsSummary {
1125    fn from_commands(commands: &[SceneCommand]) -> Self {
1126        let mut summary = Self::default();
1127        for command in commands {
1128            summary.push(command);
1129        }
1130        summary
1131    }
1132
1133    fn push(&mut self, command: &SceneCommand) {
1134        let (content, paint) = self.state.command_bounds(command);
1135        Self::include(&mut self.content, content);
1136        Self::include(&mut self.paint, paint);
1137    }
1138
1139    fn extend(&mut self, other: &Self) {
1140        debug_assert!(self.state.is_balanced());
1141        debug_assert!(other.state.is_balanced());
1142        Self::include(&mut self.content, other.content);
1143        Self::include(&mut self.paint, other.paint);
1144    }
1145
1146    fn include(bounds: &mut Option<Rect>, additional: Option<Rect>) {
1147        let Some(additional) = additional else {
1148            return;
1149        };
1150        *bounds = Some(match *bounds {
1151            Some(existing) => existing.union(additional),
1152            None => additional,
1153        });
1154    }
1155}
1156
1157#[derive(Debug, Clone, Default, PartialEq)]
1158struct SceneBoundsState {
1159    transform: Transform,
1160    transform_stack: Vec<Transform>,
1161    clip_stack: Vec<Rect>,
1162}
1163
1164impl SceneBoundsState {
1165    fn is_balanced(&self) -> bool {
1166        self.transform.is_identity()
1167            && self.transform_stack.is_empty()
1168            && self.clip_stack.is_empty()
1169    }
1170
1171    fn command_bounds(&mut self, command: &SceneCommand) -> (Option<Rect>, Option<Rect>) {
1172        match command {
1173            SceneCommand::Clear(_) => {
1174                let clip = self.current_clip();
1175                (clip, clip)
1176            }
1177            SceneCommand::FillRect { rect, .. } => self.apply_rect(*rect),
1178            SceneCommand::StrokeRect { rect, stroke, .. } => {
1179                self.apply_rect(rect.inflate(stroke.width * 0.5, stroke.width * 0.5))
1180            }
1181            SceneCommand::FillPath { path, .. } => self.apply_rect(path.bounds()),
1182            SceneCommand::StrokePath { path, stroke, .. } => self.apply_rect(
1183                path.bounds()
1184                    .inflate(stroke.width * 0.5, stroke.width * 0.5),
1185            ),
1186            SceneCommand::DrawText(text) => self.apply_rect(text.rect),
1187            SceneCommand::DrawShapedText(text) => self.apply_rect(text.translated_bounds()),
1188            SceneCommand::DrawShapedTextWindow(text) => self.apply_rect(text.translated_bounds()),
1189            SceneCommand::DrawImage { rect, .. } => self.apply_rect(*rect),
1190            SceneCommand::DrawImageQuad { points, .. } => self.apply_points(*points),
1191            SceneCommand::DrawShaderRect { rect, .. } => self.apply_rect(*rect),
1192            SceneCommand::PushClip { rect } => {
1193                let clip = self.transform.transform_rect_bbox(*rect);
1194                self.push_clip(clip);
1195                (None, None)
1196            }
1197            SceneCommand::PushClipPath { path } => {
1198                let clip = self.transform.transform_rect_bbox(path.bounds());
1199                self.push_clip(clip);
1200                (None, None)
1201            }
1202            SceneCommand::PopClip => {
1203                self.clip_stack.pop();
1204                (None, None)
1205            }
1206            SceneCommand::PushTransform { transform } => {
1207                self.transform_stack.push(self.transform);
1208                self.transform = self.transform.then(*transform);
1209                (None, None)
1210            }
1211            SceneCommand::PopTransform => {
1212                self.transform = self.transform_stack.pop().unwrap_or_default();
1213                (None, None)
1214            }
1215            SceneCommand::PushTextRenderPolicy { .. } | SceneCommand::PopTextRenderPolicy => {
1216                (None, None)
1217            }
1218            SceneCommand::Layer(layer) => self.apply_distinct_rects(
1219                layer.descriptor.content_bounds,
1220                layer.descriptor.paint_bounds,
1221            ),
1222            SceneCommand::FillRoundedRect { rect, shadow, .. } => {
1223                let bounds = match shadow {
1224                    Some(shadow) if shadow.placement != ShadowPlacement::Inside => {
1225                        let extent = shadow.extent();
1226                        let shadow_rect = rect
1227                            .inflate(extent, extent)
1228                            .translate(Vector::new(shadow.offset_x, shadow.offset_y));
1229                        rect.union(shadow_rect)
1230                    }
1231                    Some(_) | None => *rect,
1232                };
1233                self.apply_rect(bounds)
1234            }
1235            SceneCommand::Label { rect, .. } => self.apply_rect(*rect),
1236        }
1237    }
1238
1239    fn apply_rect(&self, rect: Rect) -> (Option<Rect>, Option<Rect>) {
1240        let transformed = self.transform.transform_rect_bbox(rect);
1241        (Some(transformed), self.clip_rect(transformed))
1242    }
1243
1244    fn apply_distinct_rects(&self, content: Rect, paint: Rect) -> (Option<Rect>, Option<Rect>) {
1245        let content = self.transform.transform_rect_bbox(content);
1246        let paint = self.transform.transform_rect_bbox(paint);
1247        (Some(content), self.clip_rect(paint))
1248    }
1249
1250    fn apply_points(&self, points: [Point; 4]) -> (Option<Rect>, Option<Rect>) {
1251        let transformed = points.map(|point| self.transform.transform_point(point));
1252        let bounds = points_bounds(&transformed);
1253        (Some(bounds), self.clip_rect(bounds))
1254    }
1255
1256    fn push_clip(&mut self, clip: Rect) {
1257        let clip = self.clip_rect(clip).unwrap_or(Rect::ZERO);
1258        self.clip_stack.push(clip);
1259    }
1260
1261    fn clip_rect(&self, rect: Rect) -> Option<Rect> {
1262        let mut clipped = rect;
1263        for clip in &self.clip_stack {
1264            clipped = clipped.intersection(*clip)?;
1265        }
1266        Some(clipped)
1267    }
1268
1269    fn current_clip(&self) -> Option<Rect> {
1270        self.clip_stack.last().copied()
1271    }
1272}
1273
1274impl SceneLayer {
1275    fn translate(&mut self, delta: Vector) {
1276        self.descriptor = self.descriptor.clone().translate(delta);
1277        Arc::make_mut(&mut self.scene).translate(delta);
1278    }
1279}
1280
1281fn translate_command(command: &mut SceneCommand, delta: Vector) {
1282    match command {
1283        SceneCommand::Clear(_)
1284        | SceneCommand::PopClip
1285        | SceneCommand::PopTransform
1286        | SceneCommand::PushTextRenderPolicy { .. }
1287        | SceneCommand::PopTextRenderPolicy => {}
1288        SceneCommand::FillRect { rect, brush } | SceneCommand::StrokeRect { rect, brush, .. } => {
1289            *rect = rect.translate(delta);
1290            translate_brush(brush, delta);
1291        }
1292        SceneCommand::DrawImage { rect, .. }
1293        | SceneCommand::DrawShaderRect { rect, .. }
1294        | SceneCommand::PushClip { rect }
1295        | SceneCommand::Label { rect, .. } => {
1296            *rect = rect.translate(delta);
1297        }
1298        SceneCommand::DrawImageQuad { points, .. } => {
1299            for point in points {
1300                *point += delta;
1301            }
1302        }
1303        SceneCommand::FillPath { path, brush } | SceneCommand::StrokePath { path, brush, .. } => {
1304            *path = translate_path(path, delta);
1305            translate_brush(brush, delta);
1306        }
1307        SceneCommand::PushClipPath { path } => {
1308            *path = translate_path(path, delta);
1309        }
1310        SceneCommand::DrawText(text) => {
1311            text.rect = text.rect.translate(delta);
1312        }
1313        SceneCommand::DrawShapedText(text) => {
1314            text.origin += delta;
1315        }
1316        SceneCommand::DrawShapedTextWindow(text) => {
1317            text.origin += delta;
1318        }
1319        SceneCommand::PushTransform { .. } => {}
1320        SceneCommand::Layer(layer) => {
1321            layer.translate(delta);
1322        }
1323        SceneCommand::FillRoundedRect { rect, brush, .. } => {
1324            *rect = rect.translate(delta);
1325            translate_brush(brush, delta);
1326        }
1327    }
1328}
1329
1330/// Gradient axes are in scene coordinates, so they move with their shape.
1331fn translate_brush(brush: &mut Brush, delta: Vector) {
1332    if let Brush::LinearGradient { start, end, .. } = brush {
1333        *start += delta;
1334        *end += delta;
1335    }
1336}
1337
1338fn points_bounds(points: &[Point]) -> Rect {
1339    let mut min_x = f32::INFINITY;
1340    let mut min_y = f32::INFINITY;
1341    let mut max_x = f32::NEG_INFINITY;
1342    let mut max_y = f32::NEG_INFINITY;
1343    for point in points {
1344        min_x = min_x.min(point.x);
1345        min_y = min_y.min(point.y);
1346        max_x = max_x.max(point.x);
1347        max_y = max_y.max(point.y);
1348    }
1349    Rect::from_points(Point::new(min_x, min_y), Point::new(max_x, max_y))
1350}
1351
1352fn translate_path(path: &Path, delta: Vector) -> Path {
1353    let mut builder = Path::builder();
1354    for element in path.elements() {
1355        match element {
1356            PathElement::MoveTo(point) => {
1357                builder.move_to(*point + delta);
1358            }
1359            PathElement::LineTo(point) => {
1360                builder.line_to(*point + delta);
1361            }
1362            PathElement::QuadTo { ctrl, to } => {
1363                builder.quad_to(*ctrl + delta, *to + delta);
1364            }
1365            PathElement::CubicTo { ctrl1, ctrl2, to } => {
1366                builder.cubic_to(*ctrl1 + delta, *ctrl2 + delta, *to + delta);
1367            }
1368            PathElement::Close => {
1369                builder.close();
1370            }
1371        }
1372    }
1373    builder.build()
1374}
1375
1376impl From<TextRun> for SceneCommand {
1377    fn from(value: TextRun) -> Self {
1378        Self::DrawText(value)
1379    }
1380}
1381
1382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1383pub enum RegisteredImageFormat {
1384    Rgba8,
1385}
1386
1387impl RegisteredImageFormat {
1388    const fn bytes_per_pixel(self) -> usize {
1389        match self {
1390            Self::Rgba8 => 4,
1391        }
1392    }
1393}
1394
1395#[derive(Debug, Clone, PartialEq, Eq)]
1396pub struct RegisteredImage {
1397    data: Arc<[u8]>,
1398    width: u32,
1399    height: u32,
1400    format: RegisteredImageFormat,
1401    svg: Option<Arc<[u8]>>,
1402    mipmaps_enabled: bool,
1403}
1404
1405/// Renderer-neutral metadata for an image whose pixels are owned outside the
1406/// frame's CPU image registry.
1407///
1408/// The renderer backend is responsible for resolving the matching
1409/// [`ImageHandle`] to a backend resource. Keeping only dimensions in the scene
1410/// frame lets widgets participate in normal image layout, clipping, sampling,
1411/// and retained rendering without making the scene model depend on a GPU API.
1412#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1413pub struct RegisteredExternalImage {
1414    width: u32,
1415    height: u32,
1416}
1417
1418impl RegisteredExternalImage {
1419    pub fn new(width: u32, height: u32) -> Result<Self> {
1420        if width == 0 || height == 0 {
1421            return Err(Error::new(
1422                "external image dimensions must both be non-zero",
1423            ));
1424        }
1425        Ok(Self { width, height })
1426    }
1427
1428    pub const fn width(self) -> u32 {
1429        self.width
1430    }
1431
1432    pub const fn height(self) -> u32 {
1433        self.height
1434    }
1435}
1436
1437impl RegisteredImage {
1438    pub fn from_rgba8(width: u32, height: u32, data: impl Into<Vec<u8>>) -> Result<Self> {
1439        Self::from_pixels(width, height, RegisteredImageFormat::Rgba8, data)
1440    }
1441
1442    pub fn from_svg(svg: impl AsRef<[u8]>) -> Result<Self> {
1443        let svg = Arc::<[u8]>::from(svg.as_ref());
1444        let tree = parse_svg_image(&svg)?;
1445        let size = tree.size().to_int_size();
1446        let mut image = Self::from_svg_tree_at_size(&tree, size.width(), size.height())?;
1447        image.svg = Some(svg);
1448        Ok(image)
1449    }
1450
1451    pub fn from_svg_at_size(width: u32, height: u32, svg: impl AsRef<[u8]>) -> Result<Self> {
1452        let svg = Arc::<[u8]>::from(svg.as_ref());
1453        let tree = parse_svg_image(&svg)?;
1454        let mut image = Self::from_svg_tree_at_size(&tree, width, height)?;
1455        image.svg = Some(svg);
1456        Ok(image)
1457    }
1458
1459    pub fn from_pixels(
1460        width: u32,
1461        height: u32,
1462        format: RegisteredImageFormat,
1463        data: impl Into<Vec<u8>>,
1464    ) -> Result<Self> {
1465        let data = data.into();
1466        let expected_len = width as usize * height as usize * format.bytes_per_pixel();
1467        if data.len() != expected_len {
1468            return Err(Error::new(format!(
1469                "image data length {} does not match expected size {} for a {}x{} {:?} image",
1470                data.len(),
1471                expected_len,
1472                width,
1473                height,
1474                format
1475            )));
1476        }
1477
1478        Ok(Self {
1479            data: Arc::<[u8]>::from(data),
1480            width,
1481            height,
1482            format,
1483            svg: None,
1484            mipmaps_enabled: true,
1485        })
1486    }
1487
1488    /// Disables mipmap generation for this image.
1489    ///
1490    /// This is useful for frequently updated bitmap resources such as paint
1491    /// canvases, where rebuilding a full mip pyramid for every content update
1492    /// costs more than base-level linear filtering.
1493    pub const fn without_mipmaps(mut self) -> Self {
1494        self.mipmaps_enabled = false;
1495        self
1496    }
1497
1498    pub const fn mipmaps_enabled(&self) -> bool {
1499        self.mipmaps_enabled
1500    }
1501
1502    pub fn bytes(&self) -> &[u8] {
1503        &self.data
1504    }
1505
1506    pub const fn width(&self) -> u32 {
1507        self.width
1508    }
1509
1510    pub const fn height(&self) -> u32 {
1511        self.height
1512    }
1513
1514    pub const fn format(&self) -> RegisteredImageFormat {
1515        self.format
1516    }
1517
1518    pub fn is_svg(&self) -> bool {
1519        self.svg.is_some()
1520    }
1521
1522    pub fn svg_bytes(&self) -> Option<&[u8]> {
1523        self.svg.as_deref()
1524    }
1525
1526    pub fn rasterize_svg_at_size(&self, width: u32, height: u32) -> Result<Option<Self>> {
1527        let Some(svg) = &self.svg else {
1528            return Ok(None);
1529        };
1530        let tree = parse_svg_image(svg)?;
1531        Self::from_svg_tree_at_size(&tree, width, height).map(Some)
1532    }
1533
1534    fn from_svg_tree_at_size(tree: &resvg::usvg::Tree, width: u32, height: u32) -> Result<Self> {
1535        if width == 0 || height == 0 {
1536            return Err(Error::new("SVG raster dimensions must be non-zero"));
1537        }
1538
1539        let source_size = tree.size();
1540        let scale_x = width as f32 / source_size.width();
1541        let scale_y = height as f32 / source_size.height();
1542        let mut pixmap = resvg::tiny_skia::Pixmap::new(width, height)
1543            .ok_or_else(|| Error::new("failed to allocate SVG raster pixmap"))?;
1544        resvg::render(
1545            tree,
1546            resvg::tiny_skia::Transform::from_scale(scale_x, scale_y),
1547            &mut pixmap.as_mut(),
1548        );
1549
1550        let mut data = Vec::with_capacity(width as usize * height as usize * 4);
1551        for pixel in pixmap.pixels() {
1552            if pixel.alpha() == 0 {
1553                data.extend_from_slice(&[0, 0, 0, 0]);
1554            } else {
1555                let color = pixel.demultiply();
1556                data.extend_from_slice(&[color.red(), color.green(), color.blue(), color.alpha()]);
1557            }
1558        }
1559
1560        Self::from_rgba8(width, height, data)
1561    }
1562}
1563
1564fn parse_svg_image(svg: &[u8]) -> Result<resvg::usvg::Tree> {
1565    let options = resvg::usvg::Options::default();
1566    resvg::usvg::Tree::from_data(svg, &options)
1567        .map_err(|err| Error::new(format!("failed to parse SVG image: {err}")))
1568}
1569
1570#[derive(Debug, Clone, PartialEq, Eq, Default)]
1571pub struct ImageRegistry {
1572    images: HashMap<ImageHandle, RegisteredImage>,
1573    external_images: HashMap<ImageHandle, RegisteredExternalImage>,
1574}
1575
1576impl ImageRegistry {
1577    pub fn new() -> Self {
1578        Self::default()
1579    }
1580
1581    pub fn insert(
1582        &mut self,
1583        handle: ImageHandle,
1584        image: RegisteredImage,
1585    ) -> Option<RegisteredImage> {
1586        self.external_images.remove(&handle);
1587        self.images.insert(handle, image)
1588    }
1589
1590    pub fn insert_external(
1591        &mut self,
1592        handle: ImageHandle,
1593        image: RegisteredExternalImage,
1594    ) -> Option<RegisteredExternalImage> {
1595        self.images.remove(&handle);
1596        self.external_images.insert(handle, image)
1597    }
1598
1599    pub fn get(&self, handle: ImageHandle) -> Option<&RegisteredImage> {
1600        self.images.get(&handle)
1601    }
1602
1603    pub fn get_external(&self, handle: ImageHandle) -> Option<&RegisteredExternalImage> {
1604        self.external_images.get(&handle)
1605    }
1606
1607    pub fn dimensions(&self, handle: ImageHandle) -> Option<(u32, u32)> {
1608        self.get(handle)
1609            .map(|image| (image.width(), image.height()))
1610            .or_else(|| {
1611                self.get_external(handle)
1612                    .map(|image| (image.width(), image.height()))
1613            })
1614    }
1615
1616    pub fn contains(&self, handle: ImageHandle) -> bool {
1617        self.images.contains_key(&handle) || self.external_images.contains_key(&handle)
1618    }
1619
1620    pub fn iter(&self) -> impl Iterator<Item = (ImageHandle, &RegisteredImage)> {
1621        self.images.iter().map(|(handle, image)| (*handle, image))
1622    }
1623
1624    pub fn iter_external(&self) -> impl Iterator<Item = (ImageHandle, &RegisteredExternalImage)> {
1625        self.external_images
1626            .iter()
1627            .map(|(handle, image)| (*handle, image))
1628    }
1629
1630    pub fn len(&self) -> usize {
1631        self.images.len() + self.external_images.len()
1632    }
1633
1634    pub fn is_empty(&self) -> bool {
1635        self.images.is_empty() && self.external_images.is_empty()
1636    }
1637}
1638
1639#[derive(Debug, Clone, PartialEq)]
1640pub struct SceneFrame {
1641    /// Host render target for this frame. The target may be a platform window
1642    /// or an embedded viewport/region represented by SUI's `WindowId`.
1643    pub window_id: WindowId,
1644    pub viewport: Size,
1645    pub surface_size: Size,
1646    pub scale_factor: f32,
1647    pub dirty_regions: Vec<DirtyRegion>,
1648    pub layer_updates: Vec<SceneLayerUpdate>,
1649    pub scene: Scene,
1650    pub font_registry: Arc<FontRegistry>,
1651    pub image_registry: Arc<ImageRegistry>,
1652    pub text_layout_registry: Arc<TextLayoutRegistry>,
1653}
1654
1655impl SceneFrame {
1656    pub fn new(window_id: WindowId, viewport: Size) -> Self {
1657        Self {
1658            window_id,
1659            viewport,
1660            surface_size: viewport,
1661            scale_factor: 1.0,
1662            dirty_regions: Vec::new(),
1663            layer_updates: Vec::new(),
1664            scene: Scene::new(),
1665            font_registry: Arc::new(FontRegistry::new()),
1666            image_registry: Arc::new(ImageRegistry::new()),
1667            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
1668        }
1669    }
1670}
1671
1672#[cfg(test)]
1673mod tests {
1674    use super::{
1675        Brush, ImageRegistry, ImageSource, LayerCompositionMode, LayerProperties,
1676        RegisteredExternalImage, RegisteredImage, RegisteredImageFormat, Scene, SceneBoundsSummary,
1677        SceneCommand, SceneFrame, SceneLayer, SceneLayerDescriptor, SceneLayerId, SceneLayerUpdate,
1678        SceneLayerUpdateKind, ShadowParams, ShadowPlacement, StrokeStyle, TextRenderCoveragePolicy,
1679        TextRenderMode, TextRenderPolicy, TextSubpixelOrder, WidgetShader,
1680    };
1681    use std::sync::Arc;
1682    use sui_core::{
1683        Color, FontHandle, ImageHandle, Path, Point, Rect, Transform, Vector, WidgetId, WindowId,
1684    };
1685    use sui_text::{
1686        FontRegistry, RegisteredFont, ShapedText, ShapedTextWindow, TextRun, TextStyle, TextSystem,
1687    };
1688
1689    fn assert_send_sync<T: Send + Sync>() {}
1690
1691    fn assert_bounds_summary_matches_commands(scene: &Scene) {
1692        let recomputed = SceneBoundsSummary::from_commands(&scene.commands);
1693        assert_eq!(scene.bounds, recomputed);
1694        assert_eq!(scene.content_bounds(), recomputed.content);
1695        assert_eq!(scene.paint_bounds(), recomputed.paint);
1696    }
1697
1698    #[test]
1699    fn scene_frame_is_send_sync() {
1700        assert_send_sync::<SceneFrame>();
1701    }
1702
1703    #[test]
1704    fn layer_scale_maps_around_its_anchor() {
1705        let bounds = Rect::new(100.0, 50.0, 200.0, 100.0);
1706        let centered = LayerProperties::default().with_scale(0.5);
1707
1708        assert_eq!(
1709            centered.map_rect(bounds, bounds),
1710            Rect::new(150.0, 75.0, 100.0, 50.0)
1711        );
1712        let top = centered
1713            .with_scale_anchor(Vector::new(0.5, 0.0))
1714            .with_translation(Vector::new(0.0, 8.0));
1715        assert_eq!(
1716            top.map_rect(bounds, bounds),
1717            Rect::new(150.0, 58.0, 100.0, 50.0)
1718        );
1719        let transform = top.transform(bounds);
1720        let corner = transform.transform_point(Point::new(100.0, 50.0));
1721        assert_eq!(corner, Point::new(150.0, 58.0));
1722        assert!(!LayerProperties::default().is_scaled());
1723    }
1724
1725    #[test]
1726    fn translating_a_scene_moves_gradient_axes_with_their_shapes() {
1727        let gradient = |start: Point, end: Point| Brush::LinearGradient {
1728            start,
1729            end,
1730            stops: vec![
1731                super::GradientStop {
1732                    offset: 0.0,
1733                    color: Color::rgba(1.0, 0.0, 0.0, 1.0),
1734                },
1735                super::GradientStop {
1736                    offset: 1.0,
1737                    color: Color::rgba(0.0, 0.0, 1.0, 1.0),
1738                },
1739            ],
1740        };
1741        let axis = |brush: &Brush| match brush {
1742            Brush::LinearGradient { start, end, .. } => (*start, *end),
1743            Brush::Solid(_) => panic!("a gradient brush"),
1744        };
1745        let (start, end) = (Point::new(10.0, 5.0), Point::new(90.0, 5.0));
1746        let mut path = Path::builder();
1747        path.move_to(Point::new(10.0, 0.0));
1748        path.line_to(Point::new(90.0, 0.0));
1749        path.line_to(Point::new(90.0, 10.0));
1750        path.close();
1751        let path = path.build();
1752        let mut scene = Scene::new();
1753        scene.push(SceneCommand::FillRect {
1754            rect: Rect::new(10.0, 0.0, 80.0, 10.0),
1755            brush: gradient(start, end),
1756        });
1757        scene.push(SceneCommand::StrokeRect {
1758            rect: Rect::new(10.0, 0.0, 80.0, 10.0),
1759            brush: gradient(start, end),
1760            stroke: StrokeStyle::new(1.0),
1761        });
1762        scene.push(SceneCommand::FillPath {
1763            path: path.clone(),
1764            brush: gradient(start, end),
1765        });
1766        scene.push(SceneCommand::StrokePath {
1767            path,
1768            brush: gradient(start, end),
1769            stroke: StrokeStyle::new(1.0),
1770        });
1771        scene.push(SceneCommand::FillRoundedRect {
1772            rect: Rect::new(10.0, 0.0, 80.0, 10.0),
1773            radii: [4.0; 4],
1774            brush: gradient(start, end),
1775            border: None,
1776            shadow: None,
1777        });
1778
1779        let delta = Vector::new(3.0, 40.0);
1780        scene.translate(delta);
1781        let moved = (start + delta, end + delta);
1782        for command in scene.commands() {
1783            let brush = match command {
1784                SceneCommand::FillRect { brush, .. }
1785                | SceneCommand::StrokeRect { brush, .. }
1786                | SceneCommand::FillPath { brush, .. }
1787                | SceneCommand::StrokePath { brush, .. }
1788                | SceneCommand::FillRoundedRect { brush, .. } => brush,
1789                other => panic!("unexpected command {other:?}"),
1790            };
1791            assert_eq!(axis(brush), moved, "{command:?}");
1792        }
1793    }
1794
1795    #[test]
1796    fn borrowed_append_preserves_commands_bounds_and_source_under_nested_scopes() {
1797        for inherited in [false, true] {
1798            for unbalanced_source in [false, true] {
1799                let mut source = Scene::new();
1800                source.push(SceneCommand::PushTransform {
1801                    transform: Transform::translation(4.0, 7.0),
1802                });
1803                source.push(SceneCommand::FillRect {
1804                    rect: Rect::new(2.0, 3.0, 20.0, 30.0),
1805                    brush: Color::WHITE.into(),
1806                });
1807                if !unbalanced_source {
1808                    source.push(SceneCommand::PopTransform);
1809                }
1810                let snapshot = source.clone();
1811                let mut actual = Scene::new();
1812                if inherited {
1813                    actual.push(SceneCommand::PushClip {
1814                        rect: Rect::new(0.0, 0.0, 16.0, 18.0),
1815                    });
1816                    actual.push(SceneCommand::PushTransform {
1817                        transform: Transform::translation(1.0, 2.0),
1818                    });
1819                }
1820                let mut expected = actual.clone();
1821                expected.append(source.clone());
1822                actual.append_ref(&source);
1823                assert_eq!(actual, expected);
1824                assert_eq!(source, snapshot);
1825                assert_bounds_summary_matches_commands(&actual);
1826                source.clear();
1827                assert_eq!(actual, expected);
1828            }
1829        }
1830    }
1831
1832    #[test]
1833    fn scene_command_variants_store_extended_primitives() {
1834        let text = SceneCommand::DrawText(TextRun {
1835            rect: Rect::new(4.0, 8.0, 120.0, 24.0),
1836            text: "hello".to_string(),
1837            style: TextStyle::new(Color::WHITE),
1838        });
1839        let shaped_layout = TextSystem::new()
1840            .shape_text_persistent(
1841                None,
1842                "hello",
1843                sui_core::Size::new(120.0, 24.0),
1844                TextStyle::new(Color::WHITE),
1845                &FontRegistry::new(),
1846            )
1847            .unwrap();
1848        let shaped_text = SceneCommand::DrawShapedText(ShapedText {
1849            origin: Point::new(4.0, 8.0),
1850            layout_handle: shaped_layout.handle(),
1851            layout_version: shaped_layout.version(),
1852            bounds: shaped_layout.measurement().bounds,
1853            color_override: None,
1854        });
1855        let shaped_window = SceneCommand::DrawShapedTextWindow(ShapedTextWindow::new(
1856            Point::new(4.0, 8.0),
1857            &shaped_layout,
1858            0..1,
1859        ));
1860        let image = SceneCommand::DrawImage {
1861            rect: Rect::new(0.0, 0.0, 32.0, 32.0),
1862            source: ImageSource::new(ImageHandle::new(7))
1863                .with_tint(Color::rgba(1.0, 0.0, 0.0, 1.0)),
1864        };
1865        let shader = SceneCommand::DrawShaderRect {
1866            rect: Rect::new(0.0, 0.0, 32.0, 8.0),
1867            shader: WidgetShader::ColorPickerHueBar,
1868        };
1869        let stroke = SceneCommand::StrokeRect {
1870            rect: Rect::new(1.0, 2.0, 30.0, 12.0),
1871            brush: Brush::Solid(Color::BLACK),
1872            stroke: StrokeStyle::new(2.0),
1873        };
1874        let path_fill = SceneCommand::FillPath {
1875            path: Path::from(Rect::new(3.0, 4.0, 12.0, 10.0)),
1876            brush: Brush::Solid(Color::WHITE),
1877        };
1878        let clip_path = SceneCommand::PushClipPath {
1879            path: Path::circle(sui_core::Point::new(10.0, 10.0), 4.0),
1880        };
1881        let transform = SceneCommand::PushTransform {
1882            transform: Transform::translation(3.0, 5.0),
1883        };
1884        let text_policy = SceneCommand::PushTextRenderPolicy {
1885            policy: TextRenderPolicy::new()
1886                .with_render_mode(TextRenderMode::LcdSubpixel)
1887                .with_subpixel_order(TextSubpixelOrder::Rgb)
1888                .with_coverage_policy(TextRenderCoveragePolicy::TwoCoverageMinusCoverageSq),
1889        };
1890        let layer = SceneCommand::Layer(SceneLayer::new(
1891            WidgetId::new(9),
1892            Rect::new(1.0, 2.0, 30.0, 12.0),
1893            Scene::new(),
1894        ));
1895
1896        assert!(matches!(text, SceneCommand::DrawText(_)));
1897        assert!(matches!(shaped_text, SceneCommand::DrawShapedText(_)));
1898        assert!(matches!(
1899            shaped_window,
1900            SceneCommand::DrawShapedTextWindow(_)
1901        ));
1902        assert!(matches!(image, SceneCommand::DrawImage { .. }));
1903        assert!(matches!(shader, SceneCommand::DrawShaderRect { .. }));
1904        assert!(matches!(stroke, SceneCommand::StrokeRect { .. }));
1905        assert!(matches!(path_fill, SceneCommand::FillPath { .. }));
1906        assert!(matches!(clip_path, SceneCommand::PushClipPath { .. }));
1907        assert!(matches!(transform, SceneCommand::PushTransform { .. }));
1908        assert!(matches!(
1909            text_policy,
1910            SceneCommand::PushTextRenderPolicy { .. }
1911        ));
1912        assert!(matches!(layer, SceneCommand::Layer(_)));
1913    }
1914
1915    #[test]
1916    fn scene_frame_can_share_font_registry_snapshots() {
1917        let mut registry = FontRegistry::new();
1918        registry.insert(
1919            FontHandle::new(9),
1920            RegisteredFont::from_bytes(vec![1, 2, 3]),
1921        );
1922
1923        let mut frame = SceneFrame::new(WindowId::new(4), sui_core::Size::new(32.0, 24.0));
1924        frame.font_registry = Arc::new(registry);
1925
1926        assert_eq!(frame.font_registry.len(), 1);
1927        assert!(frame.font_registry.contains(FontHandle::new(9)));
1928        assert!(frame.layer_updates.is_empty());
1929    }
1930
1931    #[test]
1932    fn scene_frame_can_share_image_registry_snapshots() {
1933        let mut registry = ImageRegistry::new();
1934        registry.insert(
1935            ImageHandle::new(5),
1936            RegisteredImage::from_rgba8(1, 1, vec![255, 128, 64, 255]).unwrap(),
1937        );
1938
1939        let mut frame = SceneFrame::new(WindowId::new(8), sui_core::Size::new(48.0, 32.0));
1940        frame.image_registry = Arc::new(registry);
1941
1942        assert_eq!(frame.image_registry.len(), 1);
1943        assert!(frame.image_registry.contains(ImageHandle::new(5)));
1944        assert!(frame.layer_updates.is_empty());
1945
1946        let descriptor = SceneLayerDescriptor::new(
1947            SceneLayerId::new(12),
1948            WidgetId::new(4),
1949            Rect::new(2.0, 3.0, 40.0, 20.0),
1950        )
1951        .with_content_bounds(Rect::new(0.0, 0.0, 80.0, 32.0))
1952        .with_paint_bounds(Rect::new(2.0, 3.0, 40.0, 20.0))
1953        .with_composition_mode(LayerCompositionMode::Scroll);
1954        let update = SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Transform, descriptor)
1955            .with_damage(Rect::new(1.0, 2.0, 42.0, 24.0));
1956
1957        assert_eq!(update.layer_id.get(), 12);
1958        assert_eq!(update.owner, WidgetId::new(4));
1959        assert_eq!(update.kind, SceneLayerUpdateKind::Transform);
1960        assert_eq!(update.damage, Some(Rect::new(1.0, 2.0, 42.0, 24.0)));
1961    }
1962
1963    #[test]
1964    fn image_registry_tracks_external_dimensions_and_one_backing_per_handle() {
1965        let handle = ImageHandle::new(15);
1966        let mut registry = ImageRegistry::new();
1967        registry.insert_external(handle, RegisteredExternalImage::new(640, 360).unwrap());
1968
1969        assert!(registry.contains(handle));
1970        assert_eq!(registry.dimensions(handle), Some((640, 360)));
1971        assert!(registry.get(handle).is_none());
1972        assert!(registry.get_external(handle).is_some());
1973
1974        registry.insert(
1975            handle,
1976            RegisteredImage::from_rgba8(1, 1, vec![1, 2, 3, 255]).unwrap(),
1977        );
1978        assert_eq!(registry.dimensions(handle), Some((1, 1)));
1979        assert!(registry.get(handle).is_some());
1980        assert!(registry.get_external(handle).is_none());
1981    }
1982
1983    #[test]
1984    fn scene_layer_descriptor_defaults_to_identity_layer_properties() {
1985        let descriptor = SceneLayerDescriptor::new(
1986            SceneLayerId::new(19),
1987            WidgetId::new(7),
1988            Rect::new(10.0, 12.0, 48.0, 24.0),
1989        );
1990
1991        assert_eq!(descriptor.properties, LayerProperties::default());
1992        assert_eq!(descriptor.properties.opacity, 1.0);
1993        assert_eq!(descriptor.properties.translation, Vector::ZERO);
1994        assert_eq!(descriptor.presented_bounds(), descriptor.bounds);
1995        assert_eq!(descriptor.presented_paint_bounds(), descriptor.paint_bounds);
1996    }
1997
1998    #[test]
1999    fn scene_layer_update_preserves_dynamic_layer_properties() {
2000        let descriptor = SceneLayerDescriptor::new(
2001            SceneLayerId::new(27),
2002            WidgetId::new(11),
2003            Rect::new(4.0, 6.0, 32.0, 18.0),
2004        )
2005        .with_content_bounds(Rect::new(4.0, 6.0, 32.0, 18.0))
2006        .with_paint_bounds(Rect::new(2.0, 4.0, 36.0, 22.0))
2007        .with_properties(
2008            LayerProperties::default()
2009                .with_opacity(0.35)
2010                .with_translation(Vector::new(14.0, -3.0)),
2011        );
2012        let update =
2013            SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Effect, descriptor.clone());
2014
2015        assert_eq!(update.properties.opacity, 0.35);
2016        assert_eq!(update.properties.translation, Vector::new(14.0, -3.0));
2017        assert_eq!(
2018            descriptor.presented_paint_bounds(),
2019            Rect::new(16.0, 1.0, 36.0, 22.0)
2020        );
2021    }
2022
2023    #[test]
2024    fn registered_image_validates_pixel_buffer_length() {
2025        let error = RegisteredImage::from_rgba8(2, 2, vec![0, 1, 2]).unwrap_err();
2026
2027        assert!(
2028            error
2029                .to_string()
2030                .contains("image data length 3 does not match")
2031        );
2032    }
2033
2034    #[test]
2035    fn registered_image_rasterizes_svg_at_natural_size() {
2036        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>"##;
2037
2038        let image = RegisteredImage::from_svg(svg).unwrap();
2039
2040        assert_eq!(image.width(), 4);
2041        assert_eq!(image.height(), 2);
2042        assert_eq!(image.format(), RegisteredImageFormat::Rgba8);
2043        assert_eq!(image.bytes().len(), 4 * 2 * 4);
2044        assert_eq!(&image.bytes()[0..4], &[0x33, 0x66, 0x99, 0xff]);
2045        assert!(image.is_svg());
2046        assert_eq!(image.svg_bytes(), Some(svg.as_slice()));
2047
2048        let larger = image
2049            .rasterize_svg_at_size(12, 6)
2050            .unwrap()
2051            .expect("retained SVG should rerasterize");
2052        assert_eq!((larger.width(), larger.height()), (12, 6));
2053        assert!(!larger.is_svg());
2054    }
2055
2056    #[test]
2057    fn registered_image_rasterizes_svg_at_requested_size() {
2058        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>"##;
2059
2060        let image = RegisteredImage::from_svg_at_size(16, 8, svg).unwrap();
2061
2062        assert_eq!(image.width(), 16);
2063        assert_eq!(image.height(), 8);
2064        assert_eq!(image.bytes().len(), 16 * 8 * 4);
2065        assert!(image.bytes().chunks_exact(4).any(|pixel| pixel[3] > 0));
2066    }
2067
2068    #[test]
2069    fn registered_image_rejects_invalid_svg() {
2070        let error = RegisteredImage::from_svg(b"not svg").unwrap_err();
2071
2072        assert!(error.to_string().contains("failed to parse SVG image"));
2073    }
2074
2075    #[test]
2076    fn scene_replace_layer_updates_nested_widget_scene() {
2077        let mut child_scene = Scene::new();
2078        child_scene.push(SceneCommand::FillRect {
2079            rect: Rect::new(2.0, 2.0, 6.0, 6.0),
2080            brush: Brush::Solid(Color::WHITE),
2081        });
2082
2083        let mut root = Scene::new();
2084        root.push(SceneCommand::FillRect {
2085            rect: Rect::new(0.0, 0.0, 20.0, 20.0),
2086            brush: Brush::Solid(Color::BLACK),
2087        });
2088        root.push(SceneCommand::Layer(SceneLayer::new(
2089            WidgetId::new(2),
2090            Rect::new(1.0, 1.0, 10.0, 10.0),
2091            child_scene,
2092        )));
2093
2094        let mut replacement = Scene::new();
2095        replacement.push(SceneCommand::FillRect {
2096            rect: Rect::new(4.0, 4.0, 8.0, 8.0),
2097            brush: Brush::Solid(Color::rgba(0.0, 1.0, 0.0, 1.0)),
2098        });
2099
2100        assert!(root.replace_layer(
2101            WidgetId::new(2),
2102            SceneLayer::new(
2103                WidgetId::new(2),
2104                Rect::new(1.0, 1.0, 10.0, 10.0),
2105                replacement
2106            ),
2107        ));
2108
2109        let mut command_count = 0usize;
2110        let mut saw_nested_fill = false;
2111        root.visit_commands(&mut |command| {
2112            command_count += 1;
2113            if let SceneCommand::FillRect { rect, .. } = command
2114                && *rect == Rect::new(4.0, 4.0, 8.0, 8.0)
2115            {
2116                saw_nested_fill = true;
2117            }
2118        });
2119
2120        assert_eq!(command_count, 3);
2121        assert!(saw_nested_fill);
2122    }
2123
2124    #[test]
2125    fn scene_clones_share_storage_and_detach_all_mutations() {
2126        let child_id = WidgetId::new(501);
2127        let mut child = Scene::new();
2128        child.push(SceneCommand::FillRect {
2129            rect: Rect::new(2.0, 3.0, 10.0, 12.0),
2130            brush: Color::WHITE.into(),
2131        });
2132        let mut scene = Scene::new();
2133        scene.push(SceneCommand::Layer(SceneLayer::new(
2134            child_id,
2135            Rect::new(0.0, 0.0, 20.0, 20.0),
2136            child,
2137        )));
2138        let expected_commands = scene.commands().to_vec();
2139        let expected_bounds = scene.paint_bounds();
2140        for mutation in 0..7 {
2141            let mut edited = scene.clone();
2142            assert!(edited.shares_commands_with(&scene));
2143            match mutation {
2144                0 => edited.push(SceneCommand::Clear(Color::BLACK)),
2145                1 => edited.append(scene.clone()),
2146                2 => edited.append_ref(&scene),
2147                3 => edited.clear(),
2148                4 => edited.translate(Vector::new(9.0, 4.0)),
2149                5 => {
2150                    assert!(edited.translate_layer(child_id, Vector::new(9.0, 4.0)));
2151                }
2152                _ => {
2153                    edited.visit_layers_mut(&mut |layer| layer.descriptor.properties.opacity = 0.5)
2154                }
2155            }
2156            assert!(!edited.shares_commands_with(&scene));
2157            assert_eq!(scene.commands(), expected_commands);
2158            assert_eq!(scene.paint_bounds(), expected_bounds);
2159            assert_bounds_summary_matches_commands(&edited);
2160            assert_bounds_summary_matches_commands(&scene);
2161        }
2162    }
2163
2164    #[test]
2165    fn shadows_reach_three_deviations_of_half_their_blur_except_inside() {
2166        let rect = Rect::new(20.0, 20.0, 40.0, 30.0);
2167        let bounds = |shadow: ShadowParams| {
2168            let mut scene = Scene::new();
2169            scene.push(SceneCommand::FillRoundedRect {
2170                rect,
2171                radii: [4.0; 4],
2172                brush: Brush::Solid(Color::WHITE),
2173                border: None,
2174                shadow: Some(shadow),
2175            });
2176            scene.content_bounds()
2177        };
2178        let black = Color::BLACK;
2179        // Blur 8 is a deviation of 4: 12 px of reach, plus the spread, moved
2180        // by the offset.
2181        let behind = ShadowParams::new(0.0, 6.0, 8.0, 2.0, black);
2182        assert_eq!(behind.sigma(), 4.0);
2183        assert_eq!(behind.extent(), 12.0 + 2.0 + 6.0);
2184        assert_eq!(
2185            bounds(behind),
2186            Some(rect.union(rect.inflate(20.0, 20.0).translate(Vector::new(0.0, 6.0))))
2187        );
2188        let glow = ShadowParams::glow(8.0, 0.0, black);
2189        assert_eq!(glow.placement, ShadowPlacement::Outside);
2190        assert_eq!(bounds(glow), Some(rect.inflate(12.0, 12.0)));
2191        let inset = ShadowParams::inset(0.0, 6.0, 8.0, 2.0, black);
2192        assert_eq!(inset.extent(), 0.0);
2193        assert_eq!(
2194            bounds(inset),
2195            Some(rect),
2196            "an inset shadow stays in its box"
2197        );
2198    }
2199
2200    #[test]
2201    fn scene_bounds_summary_stays_exact_through_all_mutation_paths() {
2202        let mut scene = Scene::default();
2203        assert_eq!(scene.content_bounds(), None);
2204        assert_eq!(scene.paint_bounds(), None);
2205        assert_bounds_summary_matches_commands(&scene);
2206
2207        scene.push(SceneCommand::PushClip {
2208            rect: Rect::new(0.0, 0.0, 50.0, 50.0),
2209        });
2210        scene.push(SceneCommand::PushTransform {
2211            transform: Transform::translation(10.0, 5.0),
2212        });
2213        scene.push(SceneCommand::FillRect {
2214            rect: Rect::new(30.0, 30.0, 40.0, 40.0),
2215            brush: Brush::Solid(Color::WHITE),
2216        });
2217        assert_eq!(
2218            scene.content_bounds(),
2219            Some(Rect::new(40.0, 35.0, 40.0, 40.0))
2220        );
2221        assert_eq!(
2222            scene.paint_bounds(),
2223            Some(Rect::new(40.0, 35.0, 10.0, 15.0))
2224        );
2225        assert_bounds_summary_matches_commands(&scene);
2226
2227        let mut appended = Scene::new();
2228        appended.push(SceneCommand::FillRect {
2229            rect: Rect::new(-8.0, -6.0, 4.0, 3.0),
2230            brush: Brush::Solid(Color::BLACK),
2231        });
2232        appended.push(SceneCommand::PushClip {
2233            rect: Rect::new(-10.0, -10.0, 20.0, 20.0),
2234        });
2235        appended.push(SceneCommand::Clear(Color::BLACK));
2236        appended.push(SceneCommand::PopClip);
2237        assert_bounds_summary_matches_commands(&appended);
2238
2239        // The destination has an open clip and transform, so append must replay the
2240        // incoming commands against that state rather than just unioning its bounds.
2241        scene.append(appended);
2242        scene.push(SceneCommand::PopTransform);
2243        scene.push(SceneCommand::PopClip);
2244        assert_bounds_summary_matches_commands(&scene);
2245
2246        let child_id = WidgetId::new(41);
2247        let grandchild_id = WidgetId::new(42);
2248        let mut grandchild_scene = Scene::new();
2249        grandchild_scene.push(SceneCommand::FillRect {
2250            rect: Rect::new(4.0, 6.0, 12.0, 8.0),
2251            brush: Brush::Solid(Color::WHITE),
2252        });
2253        let mut child_scene = Scene::new();
2254        child_scene.push(SceneCommand::Layer(SceneLayer::new(
2255            grandchild_id,
2256            Rect::new(4.0, 6.0, 12.0, 8.0),
2257            grandchild_scene,
2258        )));
2259        scene.push(SceneCommand::Layer(SceneLayer::new(
2260            child_id,
2261            Rect::new(2.0, 3.0, 24.0, 18.0),
2262            child_scene,
2263        )));
2264        assert_bounds_summary_matches_commands(&scene);
2265
2266        let mut replacement_scene = Scene::new();
2267        replacement_scene.push(SceneCommand::FillRect {
2268            rect: Rect::new(20.0, 22.0, 14.0, 10.0),
2269            brush: Brush::Solid(Color::BLACK),
2270        });
2271        assert!(scene.replace_layer(
2272            grandchild_id,
2273            SceneLayer::new(
2274                grandchild_id,
2275                Rect::new(20.0, 22.0, 14.0, 10.0),
2276                replacement_scene,
2277            ),
2278        ));
2279        assert_bounds_summary_matches_commands(&scene);
2280
2281        assert!(scene.translate_layer(grandchild_id, Vector::new(7.0, -2.0)));
2282        assert_bounds_summary_matches_commands(&scene);
2283
2284        let replacement_descriptor = SceneLayerDescriptor::new(
2285            SceneLayerId::from_widget(grandchild_id),
2286            grandchild_id,
2287            Rect::new(27.0, 20.0, 14.0, 10.0),
2288        )
2289        .with_content_bounds(Rect::new(25.0, 18.0, 18.0, 14.0))
2290        .with_paint_bounds(Rect::new(24.0, 17.0, 20.0, 16.0));
2291        assert!(scene.replace_layer_descriptor(grandchild_id, replacement_descriptor));
2292        assert_bounds_summary_matches_commands(&scene);
2293
2294        scene.visit_layers_mut(&mut |layer| {
2295            layer.descriptor.paint_bounds = layer.descriptor.paint_bounds.inflate(1.0, 2.0);
2296            Arc::make_mut(&mut layer.scene).push(SceneCommand::Label {
2297                rect: Rect::new(1.0, 2.0, 3.0, 4.0),
2298                text: "cache mutation".to_string(),
2299                color: Color::WHITE,
2300            });
2301        });
2302        assert_bounds_summary_matches_commands(&scene);
2303
2304        let mut reordered = Scene::new();
2305        reordered.push(SceneCommand::PushClip {
2306            rect: Rect::new(0.0, 0.0, 10.0, 10.0),
2307        });
2308        reordered.push(SceneCommand::Layer(SceneLayer::from_descriptor(
2309            SceneLayerDescriptor::new(
2310                SceneLayerId::new(91),
2311                WidgetId::new(91),
2312                Rect::new(0.0, 0.0, 100.0, 10.0),
2313            )
2314            .with_is_stack_surface(true)
2315            .with_stack_order(1),
2316            Scene::new(),
2317        )));
2318        reordered.push(SceneCommand::PopClip);
2319        reordered.push(SceneCommand::PushClip {
2320            rect: Rect::new(50.0, 0.0, 10.0, 10.0),
2321        });
2322        reordered.push(SceneCommand::Layer(SceneLayer::from_descriptor(
2323            SceneLayerDescriptor::new(
2324                SceneLayerId::new(92),
2325                WidgetId::new(92),
2326                Rect::new(50.0, 0.0, 100.0, 10.0),
2327            )
2328            .with_is_stack_surface(true)
2329            .with_stack_order(0),
2330            Scene::new(),
2331        )));
2332        reordered.push(SceneCommand::PopClip);
2333        assert_eq!(
2334            reordered.paint_bounds(),
2335            Some(Rect::new(0.0, 0.0, 60.0, 10.0))
2336        );
2337        reordered.reorder_stack_surfaces();
2338        assert_eq!(
2339            reordered.paint_bounds(),
2340            Some(Rect::new(50.0, 0.0, 10.0, 10.0))
2341        );
2342        assert_bounds_summary_matches_commands(&reordered);
2343        scene.append(reordered);
2344        assert_bounds_summary_matches_commands(&scene);
2345
2346        scene.translate(Vector::new(-3.0, 9.0));
2347        assert_bounds_summary_matches_commands(&scene);
2348
2349        // A balanced scene can be appended by merging summaries without replaying
2350        // its command stream. The result must still match a complete recomputation.
2351        let mut balanced = Scene::new();
2352        balanced.push(SceneCommand::PushTransform {
2353            transform: Transform::translation(2.0, 4.0),
2354        });
2355        balanced.push(SceneCommand::FillRect {
2356            rect: Rect::new(0.0, 0.0, 5.0, 7.0),
2357            brush: Brush::Solid(Color::WHITE),
2358        });
2359        balanced.push(SceneCommand::PopTransform);
2360        scene.append(balanced);
2361        assert_bounds_summary_matches_commands(&scene);
2362
2363        let clone = scene.clone();
2364        assert_eq!(scene, clone);
2365        assert_bounds_summary_matches_commands(&clone);
2366
2367        scene.clear();
2368        assert_eq!(scene, Scene::default());
2369        assert_eq!(scene.content_bounds(), None);
2370        assert_eq!(scene.paint_bounds(), None);
2371        assert_bounds_summary_matches_commands(&scene);
2372    }
2373}