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: Box<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: Box::new(scene),
534        }
535    }
536
537    pub fn from_descriptor(descriptor: SceneLayerDescriptor, scene: Scene) -> Self {
538        Self {
539            descriptor,
540            scene: Box::new(scene),
541        }
542    }
543
544    pub const fn layer_id(&self) -> SceneLayerId {
545        self.descriptor.id
546    }
547
548    pub const fn widget_id(&self) -> WidgetId {
549        self.descriptor.owner
550    }
551
552    pub const fn bounds(&self) -> Rect {
553        self.descriptor.bounds
554    }
555}
556
557#[derive(Debug, Clone, Copy, PartialEq, Eq)]
558pub enum SceneLayerUpdateKind {
559    Ordering,
560    Content,
561    Transform,
562    Clip,
563    Effect,
564    Visibility,
565    Resources,
566}
567
568#[derive(Debug, Clone, PartialEq)]
569pub struct SceneLayerUpdate {
570    pub layer_id: SceneLayerId,
571    pub owner: WidgetId,
572    pub kind: SceneLayerUpdateKind,
573    pub bounds: Rect,
574    pub content_bounds: Rect,
575    pub paint_bounds: Rect,
576    pub properties: LayerProperties,
577    pub stack_host: WidgetId,
578    pub stack_order: usize,
579    pub transient_owner_surface: Option<WidgetId>,
580    pub is_stack_surface: bool,
581    pub damage: Option<Rect>,
582}
583
584impl SceneLayerUpdate {
585    pub fn from_descriptor(kind: SceneLayerUpdateKind, descriptor: SceneLayerDescriptor) -> Self {
586        Self {
587            layer_id: descriptor.id,
588            owner: descriptor.owner,
589            kind,
590            bounds: descriptor.bounds,
591            content_bounds: descriptor.content_bounds,
592            paint_bounds: descriptor.paint_bounds,
593            properties: descriptor.properties,
594            stack_host: descriptor.stack_host,
595            stack_order: descriptor.stack_order,
596            transient_owner_surface: descriptor.transient_owner_surface,
597            is_stack_surface: descriptor.is_stack_surface,
598            damage: None,
599        }
600    }
601
602    pub const fn with_damage(mut self, damage: Rect) -> Self {
603        self.damage = Some(damage);
604        self
605    }
606}
607
608#[derive(Debug, Clone, PartialEq)]
609pub enum SceneCommand {
610    Clear(Color),
611    FillRect {
612        rect: Rect,
613        brush: Brush,
614    },
615    StrokeRect {
616        rect: Rect,
617        brush: Brush,
618        stroke: StrokeStyle,
619    },
620    FillPath {
621        path: Path,
622        brush: Brush,
623    },
624    StrokePath {
625        path: Path,
626        brush: Brush,
627        stroke: StrokeStyle,
628    },
629    DrawText(TextRun),
630    DrawShapedText(ShapedText),
631    DrawShapedTextWindow(ShapedTextWindow),
632    DrawImage {
633        rect: Rect,
634        source: ImageSource,
635    },
636    DrawImageQuad {
637        points: [Point; 4],
638        source: ImageSource,
639    },
640    DrawShaderRect {
641        rect: Rect,
642        shader: WidgetShader,
643    },
644    PushClip {
645        rect: Rect,
646    },
647    PushClipPath {
648        path: Path,
649    },
650    PopClip,
651    PushTransform {
652        transform: Transform,
653    },
654    PopTransform,
655    PushTextRenderPolicy {
656        policy: TextRenderPolicy,
657    },
658    PopTextRenderPolicy,
659    Layer(SceneLayer),
660    FillRoundedRect {
661        rect: Rect,
662        radii: [f32; 4],
663        brush: Brush,
664        border: Option<Border>,
665        shadow: Option<ShadowParams>,
666    },
667    Label {
668        rect: Rect,
669        text: String,
670        color: Color,
671    },
672}
673
674#[derive(Clone, Default)]
675pub struct Scene {
676    commands: Vec<SceneCommand>,
677    bounds: SceneBoundsSummary,
678}
679
680impl std::fmt::Debug for Scene {
681    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
682        formatter
683            .debug_struct("Scene")
684            .field("commands", &self.commands)
685            .finish()
686    }
687}
688
689impl PartialEq for Scene {
690    fn eq(&self, other: &Self) -> bool {
691        self.commands == other.commands
692    }
693}
694
695impl Scene {
696    pub fn new() -> Self {
697        Self::default()
698    }
699
700    pub fn push(&mut self, command: SceneCommand) {
701        self.bounds.push(&command);
702        self.commands.push(command);
703    }
704
705    pub fn append(&mut self, mut scene: Scene) {
706        if self.bounds.state.is_balanced() && scene.bounds.state.is_balanced() {
707            self.bounds.extend(&scene.bounds);
708        } else {
709            for command in &scene.commands {
710                self.bounds.push(command);
711            }
712        }
713        self.commands.append(&mut scene.commands);
714    }
715
716    pub fn clear(&mut self) {
717        self.commands.clear();
718        self.bounds = SceneBoundsSummary::default();
719    }
720
721    pub fn commands(&self) -> &[SceneCommand] {
722        &self.commands
723    }
724
725    pub fn visit_commands(&self, visitor: &mut dyn FnMut(&SceneCommand)) {
726        for command in &self.commands {
727            visitor(command);
728            if let SceneCommand::Layer(layer) = command {
729                layer.scene.visit_commands(visitor);
730            }
731        }
732    }
733
734    pub fn visit_layers(&self, visitor: &mut dyn FnMut(&SceneLayer)) {
735        for command in &self.commands {
736            if let SceneCommand::Layer(layer) = command {
737                visitor(layer);
738                layer.scene.visit_layers(visitor);
739            }
740        }
741    }
742
743    pub fn visit_layers_mut(&mut self, visitor: &mut dyn FnMut(&mut SceneLayer)) {
744        for command in &mut self.commands {
745            if let SceneCommand::Layer(layer) = command {
746                visitor(layer);
747                layer.scene.visit_layers_mut(visitor);
748            }
749        }
750        self.rebuild_bounds();
751    }
752
753    pub fn content_bounds(&self) -> Option<Rect> {
754        self.bounds.content
755    }
756
757    pub fn paint_bounds(&self) -> Option<Rect> {
758        self.bounds.paint
759    }
760
761    pub fn replace_layer(&mut self, widget_id: WidgetId, replacement: SceneLayer) -> bool {
762        let mut replaced = false;
763        for command in &mut self.commands {
764            match command {
765                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
766                    *command = SceneCommand::Layer(replacement);
767                    replaced = true;
768                    break;
769                }
770                SceneCommand::Layer(layer) => {
771                    if layer.scene.replace_layer(widget_id, replacement.clone()) {
772                        replaced = true;
773                        break;
774                    }
775                }
776                _ => {}
777            }
778        }
779
780        if replaced {
781            self.rebuild_bounds();
782        }
783        replaced
784    }
785
786    pub fn translate(&mut self, delta: Vector) {
787        if delta == Vector::ZERO {
788            return;
789        }
790        for command in &mut self.commands {
791            translate_command(command, delta);
792        }
793        self.rebuild_bounds();
794    }
795
796    pub fn translate_layer(&mut self, widget_id: WidgetId, delta: Vector) -> bool {
797        let mut translated = false;
798        for command in &mut self.commands {
799            match command {
800                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
801                    layer.translate(delta);
802                    translated = true;
803                    break;
804                }
805                SceneCommand::Layer(layer) => {
806                    if layer.scene.translate_layer(widget_id, delta) {
807                        translated = true;
808                        break;
809                    }
810                }
811                _ => {}
812            }
813        }
814
815        if translated {
816            self.rebuild_bounds();
817        }
818        translated
819    }
820
821    pub fn replace_layer_descriptor(
822        &mut self,
823        widget_id: WidgetId,
824        descriptor: SceneLayerDescriptor,
825    ) -> bool {
826        let mut replaced = false;
827        for command in &mut self.commands {
828            match command {
829                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
830                    layer.descriptor = descriptor;
831                    replaced = true;
832                    break;
833                }
834                SceneCommand::Layer(layer) => {
835                    if layer
836                        .scene
837                        .replace_layer_descriptor(widget_id, descriptor.clone())
838                    {
839                        replaced = true;
840                        break;
841                    }
842                }
843                _ => {}
844            }
845        }
846
847        if replaced {
848            self.rebuild_bounds();
849        }
850        replaced
851    }
852
853    pub fn layer_scene(&self, widget_id: WidgetId) -> Option<&Scene> {
854        for command in &self.commands {
855            match command {
856                SceneCommand::Layer(layer) if layer.widget_id() == widget_id => {
857                    return Some(&layer.scene);
858                }
859                SceneCommand::Layer(layer) => {
860                    if let Some(scene) = layer.scene.layer_scene(widget_id) {
861                        return Some(scene);
862                    }
863                }
864                _ => {}
865            }
866        }
867
868        None
869    }
870
871    pub fn reorder_stack_surfaces(&mut self) {
872        let mut stack_layers = self
873            .commands
874            .iter()
875            .enumerate()
876            .filter_map(|(index, command)| match command {
877                SceneCommand::Layer(layer) if layer.descriptor.is_stack_surface => {
878                    Some((index, layer.clone()))
879                }
880                _ => None,
881            })
882            .collect::<Vec<_>>();
883
884        stack_layers.sort_by_key(|(index, layer)| (layer.descriptor.stack_order, *index));
885
886        let mut sorted_layers = stack_layers.into_iter().map(|(_, layer)| layer);
887        for command in &mut self.commands {
888            if let SceneCommand::Layer(layer) = command {
889                layer.scene.reorder_stack_surfaces();
890                if layer.descriptor.is_stack_surface
891                    && let Some(replacement) = sorted_layers.next()
892                {
893                    *layer = replacement;
894                }
895            }
896        }
897        self.rebuild_bounds();
898    }
899
900    fn rebuild_bounds(&mut self) {
901        self.bounds = SceneBoundsSummary::from_commands(&self.commands);
902    }
903}
904
905#[derive(Debug, Clone, Default, PartialEq)]
906struct SceneBoundsSummary {
907    state: SceneBoundsState,
908    content: Option<Rect>,
909    paint: Option<Rect>,
910}
911
912impl SceneBoundsSummary {
913    fn from_commands(commands: &[SceneCommand]) -> Self {
914        let mut summary = Self::default();
915        for command in commands {
916            summary.push(command);
917        }
918        summary
919    }
920
921    fn push(&mut self, command: &SceneCommand) {
922        let (content, paint) = self.state.command_bounds(command);
923        Self::include(&mut self.content, content);
924        Self::include(&mut self.paint, paint);
925    }
926
927    fn extend(&mut self, other: &Self) {
928        debug_assert!(self.state.is_balanced());
929        debug_assert!(other.state.is_balanced());
930        Self::include(&mut self.content, other.content);
931        Self::include(&mut self.paint, other.paint);
932    }
933
934    fn include(bounds: &mut Option<Rect>, additional: Option<Rect>) {
935        let Some(additional) = additional else {
936            return;
937        };
938        *bounds = Some(match *bounds {
939            Some(existing) => existing.union(additional),
940            None => additional,
941        });
942    }
943}
944
945#[derive(Debug, Clone, Default, PartialEq)]
946struct SceneBoundsState {
947    transform: Transform,
948    transform_stack: Vec<Transform>,
949    clip_stack: Vec<Rect>,
950}
951
952impl SceneBoundsState {
953    fn is_balanced(&self) -> bool {
954        self.transform.is_identity()
955            && self.transform_stack.is_empty()
956            && self.clip_stack.is_empty()
957    }
958
959    fn command_bounds(&mut self, command: &SceneCommand) -> (Option<Rect>, Option<Rect>) {
960        match command {
961            SceneCommand::Clear(_) => {
962                let clip = self.current_clip();
963                (clip, clip)
964            }
965            SceneCommand::FillRect { rect, .. } => self.apply_rect(*rect),
966            SceneCommand::StrokeRect { rect, stroke, .. } => {
967                self.apply_rect(rect.inflate(stroke.width * 0.5, stroke.width * 0.5))
968            }
969            SceneCommand::FillPath { path, .. } => self.apply_rect(path.bounds()),
970            SceneCommand::StrokePath { path, stroke, .. } => self.apply_rect(
971                path.bounds()
972                    .inflate(stroke.width * 0.5, stroke.width * 0.5),
973            ),
974            SceneCommand::DrawText(text) => self.apply_rect(text.rect),
975            SceneCommand::DrawShapedText(text) => self.apply_rect(text.translated_bounds()),
976            SceneCommand::DrawShapedTextWindow(text) => self.apply_rect(text.translated_bounds()),
977            SceneCommand::DrawImage { rect, .. } => self.apply_rect(*rect),
978            SceneCommand::DrawImageQuad { points, .. } => self.apply_points(*points),
979            SceneCommand::DrawShaderRect { rect, .. } => self.apply_rect(*rect),
980            SceneCommand::PushClip { rect } => {
981                let clip = self.transform.transform_rect_bbox(*rect);
982                self.push_clip(clip);
983                (None, None)
984            }
985            SceneCommand::PushClipPath { path } => {
986                let clip = self.transform.transform_rect_bbox(path.bounds());
987                self.push_clip(clip);
988                (None, None)
989            }
990            SceneCommand::PopClip => {
991                self.clip_stack.pop();
992                (None, None)
993            }
994            SceneCommand::PushTransform { transform } => {
995                self.transform_stack.push(self.transform);
996                self.transform = self.transform.then(*transform);
997                (None, None)
998            }
999            SceneCommand::PopTransform => {
1000                self.transform = self.transform_stack.pop().unwrap_or_default();
1001                (None, None)
1002            }
1003            SceneCommand::PushTextRenderPolicy { .. } | SceneCommand::PopTextRenderPolicy => {
1004                (None, None)
1005            }
1006            SceneCommand::Layer(layer) => self.apply_distinct_rects(
1007                layer.descriptor.content_bounds,
1008                layer.descriptor.paint_bounds,
1009            ),
1010            SceneCommand::FillRoundedRect { rect, shadow, .. } => {
1011                let bounds = match shadow {
1012                    Some(shadow) => {
1013                        let extent = shadow.extent();
1014                        let shadow_rect = rect
1015                            .inflate(extent, extent)
1016                            .translate(Vector::new(shadow.offset_x, shadow.offset_y));
1017                        rect.union(shadow_rect)
1018                    }
1019                    None => *rect,
1020                };
1021                self.apply_rect(bounds)
1022            }
1023            SceneCommand::Label { rect, .. } => self.apply_rect(*rect),
1024        }
1025    }
1026
1027    fn apply_rect(&self, rect: Rect) -> (Option<Rect>, Option<Rect>) {
1028        let transformed = self.transform.transform_rect_bbox(rect);
1029        (Some(transformed), self.clip_rect(transformed))
1030    }
1031
1032    fn apply_distinct_rects(&self, content: Rect, paint: Rect) -> (Option<Rect>, Option<Rect>) {
1033        let content = self.transform.transform_rect_bbox(content);
1034        let paint = self.transform.transform_rect_bbox(paint);
1035        (Some(content), self.clip_rect(paint))
1036    }
1037
1038    fn apply_points(&self, points: [Point; 4]) -> (Option<Rect>, Option<Rect>) {
1039        let transformed = points.map(|point| self.transform.transform_point(point));
1040        let bounds = points_bounds(&transformed);
1041        (Some(bounds), self.clip_rect(bounds))
1042    }
1043
1044    fn push_clip(&mut self, clip: Rect) {
1045        let clip = self.clip_rect(clip).unwrap_or(Rect::ZERO);
1046        self.clip_stack.push(clip);
1047    }
1048
1049    fn clip_rect(&self, rect: Rect) -> Option<Rect> {
1050        let mut clipped = rect;
1051        for clip in &self.clip_stack {
1052            clipped = clipped.intersection(*clip)?;
1053        }
1054        Some(clipped)
1055    }
1056
1057    fn current_clip(&self) -> Option<Rect> {
1058        self.clip_stack.last().copied()
1059    }
1060}
1061
1062impl SceneLayer {
1063    fn translate(&mut self, delta: Vector) {
1064        self.descriptor = self.descriptor.clone().translate(delta);
1065        self.scene.translate(delta);
1066    }
1067}
1068
1069fn translate_command(command: &mut SceneCommand, delta: Vector) {
1070    match command {
1071        SceneCommand::Clear(_)
1072        | SceneCommand::PopClip
1073        | SceneCommand::PopTransform
1074        | SceneCommand::PushTextRenderPolicy { .. }
1075        | SceneCommand::PopTextRenderPolicy => {}
1076        SceneCommand::FillRect { rect, .. }
1077        | SceneCommand::StrokeRect { rect, .. }
1078        | SceneCommand::DrawImage { rect, .. }
1079        | SceneCommand::DrawShaderRect { rect, .. }
1080        | SceneCommand::PushClip { rect }
1081        | SceneCommand::Label { rect, .. } => {
1082            *rect = rect.translate(delta);
1083        }
1084        SceneCommand::DrawImageQuad { points, .. } => {
1085            for point in points {
1086                *point += delta;
1087            }
1088        }
1089        SceneCommand::FillPath { path, .. }
1090        | SceneCommand::StrokePath { path, .. }
1091        | SceneCommand::PushClipPath { path } => {
1092            *path = translate_path(path, delta);
1093        }
1094        SceneCommand::DrawText(text) => {
1095            text.rect = text.rect.translate(delta);
1096        }
1097        SceneCommand::DrawShapedText(text) => {
1098            text.origin += delta;
1099        }
1100        SceneCommand::DrawShapedTextWindow(text) => {
1101            text.origin += delta;
1102        }
1103        SceneCommand::PushTransform { .. } => {}
1104        SceneCommand::Layer(layer) => {
1105            layer.translate(delta);
1106        }
1107        SceneCommand::FillRoundedRect { rect, brush, .. } => {
1108            *rect = rect.translate(delta);
1109            if let Brush::LinearGradient { start, end, .. } = brush {
1110                *start += delta;
1111                *end += delta;
1112            }
1113        }
1114    }
1115}
1116
1117fn points_bounds(points: &[Point]) -> Rect {
1118    let mut min_x = f32::INFINITY;
1119    let mut min_y = f32::INFINITY;
1120    let mut max_x = f32::NEG_INFINITY;
1121    let mut max_y = f32::NEG_INFINITY;
1122    for point in points {
1123        min_x = min_x.min(point.x);
1124        min_y = min_y.min(point.y);
1125        max_x = max_x.max(point.x);
1126        max_y = max_y.max(point.y);
1127    }
1128    Rect::from_points(Point::new(min_x, min_y), Point::new(max_x, max_y))
1129}
1130
1131fn translate_path(path: &Path, delta: Vector) -> Path {
1132    let mut builder = Path::builder();
1133    for element in path.elements() {
1134        match element {
1135            PathElement::MoveTo(point) => {
1136                builder.move_to(*point + delta);
1137            }
1138            PathElement::LineTo(point) => {
1139                builder.line_to(*point + delta);
1140            }
1141            PathElement::QuadTo { ctrl, to } => {
1142                builder.quad_to(*ctrl + delta, *to + delta);
1143            }
1144            PathElement::CubicTo { ctrl1, ctrl2, to } => {
1145                builder.cubic_to(*ctrl1 + delta, *ctrl2 + delta, *to + delta);
1146            }
1147            PathElement::Close => {
1148                builder.close();
1149            }
1150        }
1151    }
1152    builder.build()
1153}
1154
1155impl From<TextRun> for SceneCommand {
1156    fn from(value: TextRun) -> Self {
1157        Self::DrawText(value)
1158    }
1159}
1160
1161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1162pub enum RegisteredImageFormat {
1163    Rgba8,
1164}
1165
1166impl RegisteredImageFormat {
1167    const fn bytes_per_pixel(self) -> usize {
1168        match self {
1169            Self::Rgba8 => 4,
1170        }
1171    }
1172}
1173
1174#[derive(Debug, Clone, PartialEq, Eq)]
1175pub struct RegisteredImage {
1176    data: Arc<[u8]>,
1177    width: u32,
1178    height: u32,
1179    format: RegisteredImageFormat,
1180    svg: Option<Arc<[u8]>>,
1181    mipmaps_enabled: bool,
1182}
1183
1184/// Renderer-neutral metadata for an image whose pixels are owned outside the
1185/// frame's CPU image registry.
1186///
1187/// The renderer backend is responsible for resolving the matching
1188/// [`ImageHandle`] to a backend resource. Keeping only dimensions in the scene
1189/// frame lets widgets participate in normal image layout, clipping, sampling,
1190/// and retained rendering without making the scene model depend on a GPU API.
1191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1192pub struct RegisteredExternalImage {
1193    width: u32,
1194    height: u32,
1195}
1196
1197impl RegisteredExternalImage {
1198    pub fn new(width: u32, height: u32) -> Result<Self> {
1199        if width == 0 || height == 0 {
1200            return Err(Error::new(
1201                "external image dimensions must both be non-zero",
1202            ));
1203        }
1204        Ok(Self { width, height })
1205    }
1206
1207    pub const fn width(self) -> u32 {
1208        self.width
1209    }
1210
1211    pub const fn height(self) -> u32 {
1212        self.height
1213    }
1214}
1215
1216impl RegisteredImage {
1217    pub fn from_rgba8(width: u32, height: u32, data: impl Into<Vec<u8>>) -> Result<Self> {
1218        Self::from_pixels(width, height, RegisteredImageFormat::Rgba8, data)
1219    }
1220
1221    pub fn from_svg(svg: impl AsRef<[u8]>) -> Result<Self> {
1222        let svg = Arc::<[u8]>::from(svg.as_ref());
1223        let tree = parse_svg_image(&svg)?;
1224        let size = tree.size().to_int_size();
1225        let mut image = Self::from_svg_tree_at_size(&tree, size.width(), size.height())?;
1226        image.svg = Some(svg);
1227        Ok(image)
1228    }
1229
1230    pub fn from_svg_at_size(width: u32, height: u32, svg: impl AsRef<[u8]>) -> Result<Self> {
1231        let svg = Arc::<[u8]>::from(svg.as_ref());
1232        let tree = parse_svg_image(&svg)?;
1233        let mut image = Self::from_svg_tree_at_size(&tree, width, height)?;
1234        image.svg = Some(svg);
1235        Ok(image)
1236    }
1237
1238    pub fn from_pixels(
1239        width: u32,
1240        height: u32,
1241        format: RegisteredImageFormat,
1242        data: impl Into<Vec<u8>>,
1243    ) -> Result<Self> {
1244        let data = data.into();
1245        let expected_len = width as usize * height as usize * format.bytes_per_pixel();
1246        if data.len() != expected_len {
1247            return Err(Error::new(format!(
1248                "image data length {} does not match expected size {} for a {}x{} {:?} image",
1249                data.len(),
1250                expected_len,
1251                width,
1252                height,
1253                format
1254            )));
1255        }
1256
1257        Ok(Self {
1258            data: Arc::<[u8]>::from(data),
1259            width,
1260            height,
1261            format,
1262            svg: None,
1263            mipmaps_enabled: true,
1264        })
1265    }
1266
1267    /// Disables mipmap generation for this image.
1268    ///
1269    /// This is useful for frequently updated bitmap resources such as paint
1270    /// canvases, where rebuilding a full mip pyramid for every content update
1271    /// costs more than base-level linear filtering.
1272    pub const fn without_mipmaps(mut self) -> Self {
1273        self.mipmaps_enabled = false;
1274        self
1275    }
1276
1277    pub const fn mipmaps_enabled(&self) -> bool {
1278        self.mipmaps_enabled
1279    }
1280
1281    pub fn bytes(&self) -> &[u8] {
1282        &self.data
1283    }
1284
1285    pub const fn width(&self) -> u32 {
1286        self.width
1287    }
1288
1289    pub const fn height(&self) -> u32 {
1290        self.height
1291    }
1292
1293    pub const fn format(&self) -> RegisteredImageFormat {
1294        self.format
1295    }
1296
1297    pub fn is_svg(&self) -> bool {
1298        self.svg.is_some()
1299    }
1300
1301    pub fn svg_bytes(&self) -> Option<&[u8]> {
1302        self.svg.as_deref()
1303    }
1304
1305    pub fn rasterize_svg_at_size(&self, width: u32, height: u32) -> Result<Option<Self>> {
1306        let Some(svg) = &self.svg else {
1307            return Ok(None);
1308        };
1309        let tree = parse_svg_image(svg)?;
1310        Self::from_svg_tree_at_size(&tree, width, height).map(Some)
1311    }
1312
1313    fn from_svg_tree_at_size(tree: &resvg::usvg::Tree, width: u32, height: u32) -> Result<Self> {
1314        if width == 0 || height == 0 {
1315            return Err(Error::new("SVG raster dimensions must be non-zero"));
1316        }
1317
1318        let source_size = tree.size();
1319        let scale_x = width as f32 / source_size.width();
1320        let scale_y = height as f32 / source_size.height();
1321        let mut pixmap = resvg::tiny_skia::Pixmap::new(width, height)
1322            .ok_or_else(|| Error::new("failed to allocate SVG raster pixmap"))?;
1323        resvg::render(
1324            tree,
1325            resvg::tiny_skia::Transform::from_scale(scale_x, scale_y),
1326            &mut pixmap.as_mut(),
1327        );
1328
1329        let mut data = Vec::with_capacity(width as usize * height as usize * 4);
1330        for pixel in pixmap.pixels() {
1331            if pixel.alpha() == 0 {
1332                data.extend_from_slice(&[0, 0, 0, 0]);
1333            } else {
1334                let color = pixel.demultiply();
1335                data.extend_from_slice(&[color.red(), color.green(), color.blue(), color.alpha()]);
1336            }
1337        }
1338
1339        Self::from_rgba8(width, height, data)
1340    }
1341}
1342
1343fn parse_svg_image(svg: &[u8]) -> Result<resvg::usvg::Tree> {
1344    let options = resvg::usvg::Options::default();
1345    resvg::usvg::Tree::from_data(svg, &options)
1346        .map_err(|err| Error::new(format!("failed to parse SVG image: {err}")))
1347}
1348
1349#[derive(Debug, Clone, PartialEq, Eq, Default)]
1350pub struct ImageRegistry {
1351    images: HashMap<ImageHandle, RegisteredImage>,
1352    external_images: HashMap<ImageHandle, RegisteredExternalImage>,
1353}
1354
1355impl ImageRegistry {
1356    pub fn new() -> Self {
1357        Self::default()
1358    }
1359
1360    pub fn insert(
1361        &mut self,
1362        handle: ImageHandle,
1363        image: RegisteredImage,
1364    ) -> Option<RegisteredImage> {
1365        self.external_images.remove(&handle);
1366        self.images.insert(handle, image)
1367    }
1368
1369    pub fn insert_external(
1370        &mut self,
1371        handle: ImageHandle,
1372        image: RegisteredExternalImage,
1373    ) -> Option<RegisteredExternalImage> {
1374        self.images.remove(&handle);
1375        self.external_images.insert(handle, image)
1376    }
1377
1378    pub fn get(&self, handle: ImageHandle) -> Option<&RegisteredImage> {
1379        self.images.get(&handle)
1380    }
1381
1382    pub fn get_external(&self, handle: ImageHandle) -> Option<&RegisteredExternalImage> {
1383        self.external_images.get(&handle)
1384    }
1385
1386    pub fn dimensions(&self, handle: ImageHandle) -> Option<(u32, u32)> {
1387        self.get(handle)
1388            .map(|image| (image.width(), image.height()))
1389            .or_else(|| {
1390                self.get_external(handle)
1391                    .map(|image| (image.width(), image.height()))
1392            })
1393    }
1394
1395    pub fn contains(&self, handle: ImageHandle) -> bool {
1396        self.images.contains_key(&handle) || self.external_images.contains_key(&handle)
1397    }
1398
1399    pub fn iter(&self) -> impl Iterator<Item = (ImageHandle, &RegisteredImage)> {
1400        self.images.iter().map(|(handle, image)| (*handle, image))
1401    }
1402
1403    pub fn iter_external(&self) -> impl Iterator<Item = (ImageHandle, &RegisteredExternalImage)> {
1404        self.external_images
1405            .iter()
1406            .map(|(handle, image)| (*handle, image))
1407    }
1408
1409    pub fn len(&self) -> usize {
1410        self.images.len() + self.external_images.len()
1411    }
1412
1413    pub fn is_empty(&self) -> bool {
1414        self.images.is_empty() && self.external_images.is_empty()
1415    }
1416}
1417
1418#[derive(Debug, Clone, PartialEq)]
1419pub struct SceneFrame {
1420    /// Host render target for this frame. The target may be a platform window
1421    /// or an embedded viewport/region represented by SUI's `WindowId`.
1422    pub window_id: WindowId,
1423    pub viewport: Size,
1424    pub surface_size: Size,
1425    pub scale_factor: f32,
1426    pub dirty_regions: Vec<DirtyRegion>,
1427    pub layer_updates: Vec<SceneLayerUpdate>,
1428    pub scene: Scene,
1429    pub font_registry: Arc<FontRegistry>,
1430    pub image_registry: Arc<ImageRegistry>,
1431    pub text_layout_registry: Arc<TextLayoutRegistry>,
1432}
1433
1434impl SceneFrame {
1435    pub fn new(window_id: WindowId, viewport: Size) -> Self {
1436        Self {
1437            window_id,
1438            viewport,
1439            surface_size: viewport,
1440            scale_factor: 1.0,
1441            dirty_regions: Vec::new(),
1442            layer_updates: Vec::new(),
1443            scene: Scene::new(),
1444            font_registry: Arc::new(FontRegistry::new()),
1445            image_registry: Arc::new(ImageRegistry::new()),
1446            text_layout_registry: Arc::new(TextLayoutRegistry::default()),
1447        }
1448    }
1449}
1450
1451#[cfg(test)]
1452mod tests {
1453    use super::{
1454        Brush, ImageRegistry, ImageSource, LayerCompositionMode, LayerProperties,
1455        RegisteredExternalImage, RegisteredImage, RegisteredImageFormat, Scene, SceneBoundsSummary,
1456        SceneCommand, SceneFrame, SceneLayer, SceneLayerDescriptor, SceneLayerId, SceneLayerUpdate,
1457        SceneLayerUpdateKind, StrokeStyle, TextRenderCoveragePolicy, TextRenderMode,
1458        TextRenderPolicy, TextSubpixelOrder, WidgetShader,
1459    };
1460    use std::sync::Arc;
1461    use sui_core::{
1462        Color, FontHandle, ImageHandle, Path, Point, Rect, Transform, Vector, WidgetId, WindowId,
1463    };
1464    use sui_text::{
1465        FontRegistry, RegisteredFont, ShapedText, ShapedTextWindow, TextRun, TextStyle, TextSystem,
1466    };
1467
1468    fn assert_send_sync<T: Send + Sync>() {}
1469
1470    fn assert_bounds_summary_matches_commands(scene: &Scene) {
1471        let recomputed = SceneBoundsSummary::from_commands(&scene.commands);
1472        assert_eq!(scene.bounds, recomputed);
1473        assert_eq!(scene.content_bounds(), recomputed.content);
1474        assert_eq!(scene.paint_bounds(), recomputed.paint);
1475    }
1476
1477    #[test]
1478    fn scene_frame_is_send_sync() {
1479        assert_send_sync::<SceneFrame>();
1480    }
1481
1482    #[test]
1483    fn scene_command_variants_store_extended_primitives() {
1484        let text = SceneCommand::DrawText(TextRun {
1485            rect: Rect::new(4.0, 8.0, 120.0, 24.0),
1486            text: "hello".to_string(),
1487            style: TextStyle::new(Color::WHITE),
1488        });
1489        let shaped_layout = TextSystem::new()
1490            .shape_text_persistent(
1491                None,
1492                "hello",
1493                sui_core::Size::new(120.0, 24.0),
1494                TextStyle::new(Color::WHITE),
1495                &FontRegistry::new(),
1496            )
1497            .unwrap();
1498        let shaped_text = SceneCommand::DrawShapedText(ShapedText {
1499            origin: Point::new(4.0, 8.0),
1500            layout_handle: shaped_layout.handle(),
1501            layout_version: shaped_layout.version(),
1502            bounds: shaped_layout.measurement().bounds,
1503            color_override: None,
1504        });
1505        let shaped_window = SceneCommand::DrawShapedTextWindow(ShapedTextWindow::new(
1506            Point::new(4.0, 8.0),
1507            &shaped_layout,
1508            0..1,
1509        ));
1510        let image = SceneCommand::DrawImage {
1511            rect: Rect::new(0.0, 0.0, 32.0, 32.0),
1512            source: ImageSource::new(ImageHandle::new(7))
1513                .with_tint(Color::rgba(1.0, 0.0, 0.0, 1.0)),
1514        };
1515        let shader = SceneCommand::DrawShaderRect {
1516            rect: Rect::new(0.0, 0.0, 32.0, 8.0),
1517            shader: WidgetShader::ColorPickerHueBar,
1518        };
1519        let stroke = SceneCommand::StrokeRect {
1520            rect: Rect::new(1.0, 2.0, 30.0, 12.0),
1521            brush: Brush::Solid(Color::BLACK),
1522            stroke: StrokeStyle::new(2.0),
1523        };
1524        let path_fill = SceneCommand::FillPath {
1525            path: Path::from(Rect::new(3.0, 4.0, 12.0, 10.0)),
1526            brush: Brush::Solid(Color::WHITE),
1527        };
1528        let clip_path = SceneCommand::PushClipPath {
1529            path: Path::circle(sui_core::Point::new(10.0, 10.0), 4.0),
1530        };
1531        let transform = SceneCommand::PushTransform {
1532            transform: Transform::translation(3.0, 5.0),
1533        };
1534        let text_policy = SceneCommand::PushTextRenderPolicy {
1535            policy: TextRenderPolicy::new()
1536                .with_render_mode(TextRenderMode::LcdSubpixel)
1537                .with_subpixel_order(TextSubpixelOrder::Rgb)
1538                .with_coverage_policy(TextRenderCoveragePolicy::TwoCoverageMinusCoverageSq),
1539        };
1540        let layer = SceneCommand::Layer(SceneLayer::new(
1541            WidgetId::new(9),
1542            Rect::new(1.0, 2.0, 30.0, 12.0),
1543            Scene::new(),
1544        ));
1545
1546        assert!(matches!(text, SceneCommand::DrawText(_)));
1547        assert!(matches!(shaped_text, SceneCommand::DrawShapedText(_)));
1548        assert!(matches!(
1549            shaped_window,
1550            SceneCommand::DrawShapedTextWindow(_)
1551        ));
1552        assert!(matches!(image, SceneCommand::DrawImage { .. }));
1553        assert!(matches!(shader, SceneCommand::DrawShaderRect { .. }));
1554        assert!(matches!(stroke, SceneCommand::StrokeRect { .. }));
1555        assert!(matches!(path_fill, SceneCommand::FillPath { .. }));
1556        assert!(matches!(clip_path, SceneCommand::PushClipPath { .. }));
1557        assert!(matches!(transform, SceneCommand::PushTransform { .. }));
1558        assert!(matches!(
1559            text_policy,
1560            SceneCommand::PushTextRenderPolicy { .. }
1561        ));
1562        assert!(matches!(layer, SceneCommand::Layer(_)));
1563    }
1564
1565    #[test]
1566    fn scene_frame_can_share_font_registry_snapshots() {
1567        let mut registry = FontRegistry::new();
1568        registry.insert(
1569            FontHandle::new(9),
1570            RegisteredFont::from_bytes(vec![1, 2, 3]),
1571        );
1572
1573        let mut frame = SceneFrame::new(WindowId::new(4), sui_core::Size::new(32.0, 24.0));
1574        frame.font_registry = Arc::new(registry);
1575
1576        assert_eq!(frame.font_registry.len(), 1);
1577        assert!(frame.font_registry.contains(FontHandle::new(9)));
1578        assert!(frame.layer_updates.is_empty());
1579    }
1580
1581    #[test]
1582    fn scene_frame_can_share_image_registry_snapshots() {
1583        let mut registry = ImageRegistry::new();
1584        registry.insert(
1585            ImageHandle::new(5),
1586            RegisteredImage::from_rgba8(1, 1, vec![255, 128, 64, 255]).unwrap(),
1587        );
1588
1589        let mut frame = SceneFrame::new(WindowId::new(8), sui_core::Size::new(48.0, 32.0));
1590        frame.image_registry = Arc::new(registry);
1591
1592        assert_eq!(frame.image_registry.len(), 1);
1593        assert!(frame.image_registry.contains(ImageHandle::new(5)));
1594        assert!(frame.layer_updates.is_empty());
1595
1596        let descriptor = SceneLayerDescriptor::new(
1597            SceneLayerId::new(12),
1598            WidgetId::new(4),
1599            Rect::new(2.0, 3.0, 40.0, 20.0),
1600        )
1601        .with_content_bounds(Rect::new(0.0, 0.0, 80.0, 32.0))
1602        .with_paint_bounds(Rect::new(2.0, 3.0, 40.0, 20.0))
1603        .with_composition_mode(LayerCompositionMode::Scroll);
1604        let update = SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Transform, descriptor)
1605            .with_damage(Rect::new(1.0, 2.0, 42.0, 24.0));
1606
1607        assert_eq!(update.layer_id.get(), 12);
1608        assert_eq!(update.owner, WidgetId::new(4));
1609        assert_eq!(update.kind, SceneLayerUpdateKind::Transform);
1610        assert_eq!(update.damage, Some(Rect::new(1.0, 2.0, 42.0, 24.0)));
1611    }
1612
1613    #[test]
1614    fn image_registry_tracks_external_dimensions_and_one_backing_per_handle() {
1615        let handle = ImageHandle::new(15);
1616        let mut registry = ImageRegistry::new();
1617        registry.insert_external(handle, RegisteredExternalImage::new(640, 360).unwrap());
1618
1619        assert!(registry.contains(handle));
1620        assert_eq!(registry.dimensions(handle), Some((640, 360)));
1621        assert!(registry.get(handle).is_none());
1622        assert!(registry.get_external(handle).is_some());
1623
1624        registry.insert(
1625            handle,
1626            RegisteredImage::from_rgba8(1, 1, vec![1, 2, 3, 255]).unwrap(),
1627        );
1628        assert_eq!(registry.dimensions(handle), Some((1, 1)));
1629        assert!(registry.get(handle).is_some());
1630        assert!(registry.get_external(handle).is_none());
1631    }
1632
1633    #[test]
1634    fn scene_layer_descriptor_defaults_to_identity_layer_properties() {
1635        let descriptor = SceneLayerDescriptor::new(
1636            SceneLayerId::new(19),
1637            WidgetId::new(7),
1638            Rect::new(10.0, 12.0, 48.0, 24.0),
1639        );
1640
1641        assert_eq!(descriptor.properties, LayerProperties::default());
1642        assert_eq!(descriptor.properties.opacity, 1.0);
1643        assert_eq!(descriptor.properties.translation, Vector::ZERO);
1644        assert_eq!(descriptor.presented_bounds(), descriptor.bounds);
1645        assert_eq!(descriptor.presented_paint_bounds(), descriptor.paint_bounds);
1646    }
1647
1648    #[test]
1649    fn scene_layer_update_preserves_dynamic_layer_properties() {
1650        let descriptor = SceneLayerDescriptor::new(
1651            SceneLayerId::new(27),
1652            WidgetId::new(11),
1653            Rect::new(4.0, 6.0, 32.0, 18.0),
1654        )
1655        .with_content_bounds(Rect::new(4.0, 6.0, 32.0, 18.0))
1656        .with_paint_bounds(Rect::new(2.0, 4.0, 36.0, 22.0))
1657        .with_properties(
1658            LayerProperties::default()
1659                .with_opacity(0.35)
1660                .with_translation(Vector::new(14.0, -3.0)),
1661        );
1662        let update =
1663            SceneLayerUpdate::from_descriptor(SceneLayerUpdateKind::Effect, descriptor.clone());
1664
1665        assert_eq!(update.properties.opacity, 0.35);
1666        assert_eq!(update.properties.translation, Vector::new(14.0, -3.0));
1667        assert_eq!(
1668            descriptor.presented_paint_bounds(),
1669            Rect::new(16.0, 1.0, 36.0, 22.0)
1670        );
1671    }
1672
1673    #[test]
1674    fn registered_image_validates_pixel_buffer_length() {
1675        let error = RegisteredImage::from_rgba8(2, 2, vec![0, 1, 2]).unwrap_err();
1676
1677        assert!(
1678            error
1679                .to_string()
1680                .contains("image data length 3 does not match")
1681        );
1682    }
1683
1684    #[test]
1685    fn registered_image_rasterizes_svg_at_natural_size() {
1686        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>"##;
1687
1688        let image = RegisteredImage::from_svg(svg).unwrap();
1689
1690        assert_eq!(image.width(), 4);
1691        assert_eq!(image.height(), 2);
1692        assert_eq!(image.format(), RegisteredImageFormat::Rgba8);
1693        assert_eq!(image.bytes().len(), 4 * 2 * 4);
1694        assert_eq!(&image.bytes()[0..4], &[0x33, 0x66, 0x99, 0xff]);
1695        assert!(image.is_svg());
1696        assert_eq!(image.svg_bytes(), Some(svg.as_slice()));
1697
1698        let larger = image
1699            .rasterize_svg_at_size(12, 6)
1700            .unwrap()
1701            .expect("retained SVG should rerasterize");
1702        assert_eq!((larger.width(), larger.height()), (12, 6));
1703        assert!(!larger.is_svg());
1704    }
1705
1706    #[test]
1707    fn registered_image_rasterizes_svg_at_requested_size() {
1708        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>"##;
1709
1710        let image = RegisteredImage::from_svg_at_size(16, 8, svg).unwrap();
1711
1712        assert_eq!(image.width(), 16);
1713        assert_eq!(image.height(), 8);
1714        assert_eq!(image.bytes().len(), 16 * 8 * 4);
1715        assert!(image.bytes().chunks_exact(4).any(|pixel| pixel[3] > 0));
1716    }
1717
1718    #[test]
1719    fn registered_image_rejects_invalid_svg() {
1720        let error = RegisteredImage::from_svg(b"not svg").unwrap_err();
1721
1722        assert!(error.to_string().contains("failed to parse SVG image"));
1723    }
1724
1725    #[test]
1726    fn scene_replace_layer_updates_nested_widget_scene() {
1727        let mut child_scene = Scene::new();
1728        child_scene.push(SceneCommand::FillRect {
1729            rect: Rect::new(2.0, 2.0, 6.0, 6.0),
1730            brush: Brush::Solid(Color::WHITE),
1731        });
1732
1733        let mut root = Scene::new();
1734        root.push(SceneCommand::FillRect {
1735            rect: Rect::new(0.0, 0.0, 20.0, 20.0),
1736            brush: Brush::Solid(Color::BLACK),
1737        });
1738        root.push(SceneCommand::Layer(SceneLayer::new(
1739            WidgetId::new(2),
1740            Rect::new(1.0, 1.0, 10.0, 10.0),
1741            child_scene,
1742        )));
1743
1744        let mut replacement = Scene::new();
1745        replacement.push(SceneCommand::FillRect {
1746            rect: Rect::new(4.0, 4.0, 8.0, 8.0),
1747            brush: Brush::Solid(Color::rgba(0.0, 1.0, 0.0, 1.0)),
1748        });
1749
1750        assert!(root.replace_layer(
1751            WidgetId::new(2),
1752            SceneLayer::new(
1753                WidgetId::new(2),
1754                Rect::new(1.0, 1.0, 10.0, 10.0),
1755                replacement
1756            ),
1757        ));
1758
1759        let mut command_count = 0usize;
1760        let mut saw_nested_fill = false;
1761        root.visit_commands(&mut |command| {
1762            command_count += 1;
1763            if let SceneCommand::FillRect { rect, .. } = command
1764                && *rect == Rect::new(4.0, 4.0, 8.0, 8.0)
1765            {
1766                saw_nested_fill = true;
1767            }
1768        });
1769
1770        assert_eq!(command_count, 3);
1771        assert!(saw_nested_fill);
1772    }
1773
1774    #[test]
1775    fn scene_bounds_summary_stays_exact_through_all_mutation_paths() {
1776        let mut scene = Scene::default();
1777        assert_eq!(scene.content_bounds(), None);
1778        assert_eq!(scene.paint_bounds(), None);
1779        assert_bounds_summary_matches_commands(&scene);
1780
1781        scene.push(SceneCommand::PushClip {
1782            rect: Rect::new(0.0, 0.0, 50.0, 50.0),
1783        });
1784        scene.push(SceneCommand::PushTransform {
1785            transform: Transform::translation(10.0, 5.0),
1786        });
1787        scene.push(SceneCommand::FillRect {
1788            rect: Rect::new(30.0, 30.0, 40.0, 40.0),
1789            brush: Brush::Solid(Color::WHITE),
1790        });
1791        assert_eq!(
1792            scene.content_bounds(),
1793            Some(Rect::new(40.0, 35.0, 40.0, 40.0))
1794        );
1795        assert_eq!(
1796            scene.paint_bounds(),
1797            Some(Rect::new(40.0, 35.0, 10.0, 15.0))
1798        );
1799        assert_bounds_summary_matches_commands(&scene);
1800
1801        let mut appended = Scene::new();
1802        appended.push(SceneCommand::FillRect {
1803            rect: Rect::new(-8.0, -6.0, 4.0, 3.0),
1804            brush: Brush::Solid(Color::BLACK),
1805        });
1806        appended.push(SceneCommand::PushClip {
1807            rect: Rect::new(-10.0, -10.0, 20.0, 20.0),
1808        });
1809        appended.push(SceneCommand::Clear(Color::BLACK));
1810        appended.push(SceneCommand::PopClip);
1811        assert_bounds_summary_matches_commands(&appended);
1812
1813        // The destination has an open clip and transform, so append must replay the
1814        // incoming commands against that state rather than just unioning its bounds.
1815        scene.append(appended);
1816        scene.push(SceneCommand::PopTransform);
1817        scene.push(SceneCommand::PopClip);
1818        assert_bounds_summary_matches_commands(&scene);
1819
1820        let child_id = WidgetId::new(41);
1821        let grandchild_id = WidgetId::new(42);
1822        let mut grandchild_scene = Scene::new();
1823        grandchild_scene.push(SceneCommand::FillRect {
1824            rect: Rect::new(4.0, 6.0, 12.0, 8.0),
1825            brush: Brush::Solid(Color::WHITE),
1826        });
1827        let mut child_scene = Scene::new();
1828        child_scene.push(SceneCommand::Layer(SceneLayer::new(
1829            grandchild_id,
1830            Rect::new(4.0, 6.0, 12.0, 8.0),
1831            grandchild_scene,
1832        )));
1833        scene.push(SceneCommand::Layer(SceneLayer::new(
1834            child_id,
1835            Rect::new(2.0, 3.0, 24.0, 18.0),
1836            child_scene,
1837        )));
1838        assert_bounds_summary_matches_commands(&scene);
1839
1840        let mut replacement_scene = Scene::new();
1841        replacement_scene.push(SceneCommand::FillRect {
1842            rect: Rect::new(20.0, 22.0, 14.0, 10.0),
1843            brush: Brush::Solid(Color::BLACK),
1844        });
1845        assert!(scene.replace_layer(
1846            grandchild_id,
1847            SceneLayer::new(
1848                grandchild_id,
1849                Rect::new(20.0, 22.0, 14.0, 10.0),
1850                replacement_scene,
1851            ),
1852        ));
1853        assert_bounds_summary_matches_commands(&scene);
1854
1855        assert!(scene.translate_layer(grandchild_id, Vector::new(7.0, -2.0)));
1856        assert_bounds_summary_matches_commands(&scene);
1857
1858        let replacement_descriptor = SceneLayerDescriptor::new(
1859            SceneLayerId::from_widget(grandchild_id),
1860            grandchild_id,
1861            Rect::new(27.0, 20.0, 14.0, 10.0),
1862        )
1863        .with_content_bounds(Rect::new(25.0, 18.0, 18.0, 14.0))
1864        .with_paint_bounds(Rect::new(24.0, 17.0, 20.0, 16.0));
1865        assert!(scene.replace_layer_descriptor(grandchild_id, replacement_descriptor));
1866        assert_bounds_summary_matches_commands(&scene);
1867
1868        scene.visit_layers_mut(&mut |layer| {
1869            layer.descriptor.paint_bounds = layer.descriptor.paint_bounds.inflate(1.0, 2.0);
1870            layer.scene.push(SceneCommand::Label {
1871                rect: Rect::new(1.0, 2.0, 3.0, 4.0),
1872                text: "cache mutation".to_string(),
1873                color: Color::WHITE,
1874            });
1875        });
1876        assert_bounds_summary_matches_commands(&scene);
1877
1878        let mut reordered = Scene::new();
1879        reordered.push(SceneCommand::PushClip {
1880            rect: Rect::new(0.0, 0.0, 10.0, 10.0),
1881        });
1882        reordered.push(SceneCommand::Layer(SceneLayer::from_descriptor(
1883            SceneLayerDescriptor::new(
1884                SceneLayerId::new(91),
1885                WidgetId::new(91),
1886                Rect::new(0.0, 0.0, 100.0, 10.0),
1887            )
1888            .with_is_stack_surface(true)
1889            .with_stack_order(1),
1890            Scene::new(),
1891        )));
1892        reordered.push(SceneCommand::PopClip);
1893        reordered.push(SceneCommand::PushClip {
1894            rect: Rect::new(50.0, 0.0, 10.0, 10.0),
1895        });
1896        reordered.push(SceneCommand::Layer(SceneLayer::from_descriptor(
1897            SceneLayerDescriptor::new(
1898                SceneLayerId::new(92),
1899                WidgetId::new(92),
1900                Rect::new(50.0, 0.0, 100.0, 10.0),
1901            )
1902            .with_is_stack_surface(true)
1903            .with_stack_order(0),
1904            Scene::new(),
1905        )));
1906        reordered.push(SceneCommand::PopClip);
1907        assert_eq!(
1908            reordered.paint_bounds(),
1909            Some(Rect::new(0.0, 0.0, 60.0, 10.0))
1910        );
1911        reordered.reorder_stack_surfaces();
1912        assert_eq!(
1913            reordered.paint_bounds(),
1914            Some(Rect::new(50.0, 0.0, 10.0, 10.0))
1915        );
1916        assert_bounds_summary_matches_commands(&reordered);
1917        scene.append(reordered);
1918        assert_bounds_summary_matches_commands(&scene);
1919
1920        scene.translate(Vector::new(-3.0, 9.0));
1921        assert_bounds_summary_matches_commands(&scene);
1922
1923        // A balanced scene can be appended by merging summaries without replaying
1924        // its command stream. The result must still match a complete recomputation.
1925        let mut balanced = Scene::new();
1926        balanced.push(SceneCommand::PushTransform {
1927            transform: Transform::translation(2.0, 4.0),
1928        });
1929        balanced.push(SceneCommand::FillRect {
1930            rect: Rect::new(0.0, 0.0, 5.0, 7.0),
1931            brush: Brush::Solid(Color::WHITE),
1932        });
1933        balanced.push(SceneCommand::PopTransform);
1934        scene.append(balanced);
1935        assert_bounds_summary_matches_commands(&scene);
1936
1937        let clone = scene.clone();
1938        assert_eq!(scene, clone);
1939        assert_bounds_summary_matches_commands(&clone);
1940
1941        scene.clear();
1942        assert_eq!(scene, Scene::default());
1943        assert_eq!(scene.content_bounds(), None);
1944        assert_eq!(scene.paint_bounds(), None);
1945        assert_bounds_summary_matches_commands(&scene);
1946    }
1947}