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