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