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