1use std::{
2 f32::consts::TAU,
3 fs,
4 hash::{Hash, Hasher},
5 path::Path,
6 sync::Arc,
7 time::Duration,
8};
9
10use crate::{
11 App, Asset, Bounds, Element, GlobalElementId, Hitbox, InspectorElementId, InteractiveElement,
12 Interactivity, LayoutId, Pixels, Point, Radians, SharedString, Size, SpriteAnimation,
13 StyleRefinement, Styled, TransformationMatrix, Window, ease_in_out, ease_out_quint, heartbeat,
14 linear, point, px, quadratic, radians, size,
15};
16use gpui_util::ResultExt;
17
18pub struct Svg {
20 interactivity: Interactivity,
21 transformation: Option<TimedTransformation>,
22 path: Option<SharedString>,
23 external_path: Option<SharedString>,
24 data: Option<Arc<[u8]>>,
25 data_path: Option<SharedString>,
26}
27
28#[track_caller]
30pub fn svg() -> Svg {
31 Svg {
32 interactivity: Interactivity::new(),
33 transformation: None,
34 path: None,
35 external_path: None,
36 data: None,
37 data_path: None,
38 }
39}
40
41impl Svg {
42 pub fn path(mut self, path: impl Into<SharedString>) -> Self {
44 self.path = Some(path.into());
45 self
46 }
47
48 pub fn external_path(mut self, path: impl Into<SharedString>) -> Self {
50 self.external_path = Some(path.into());
51 self
52 }
53
54 pub fn data(mut self, data: &[u8]) -> Self {
57 let mut hasher = std::collections::hash_map::DefaultHasher::new();
59 data.hash(&mut hasher);
60 let hash = hasher.finish();
61 let path = SharedString::from(format!("__binary_svg__{}", hash));
62 self.data = Some(Arc::from(data));
63 self.data_path = Some(path);
64 self
65 }
66
67 pub fn with_transformation(mut self, transformation: Transformation) -> Self {
70 self.transformation = Some(transformation.into());
71 self
72 }
73
74 pub fn with_timed_transformation(mut self, transformation: TimedTransformation) -> Self {
84 self.transformation = Some(transformation);
85 self
86 }
87}
88
89impl Element for Svg {
90 type RequestLayoutState = ();
91 type PrepaintState = Option<Hitbox>;
92
93 fn id(&self) -> Option<crate::ElementId> {
94 self.interactivity.element_id.clone()
95 }
96
97 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
98 self.interactivity.source_location()
99 }
100
101 fn request_layout(
102 &mut self,
103 global_id: Option<&GlobalElementId>,
104 inspector_id: Option<&InspectorElementId>,
105 window: &mut Window,
106 cx: &mut App,
107 ) -> (LayoutId, Self::RequestLayoutState) {
108 let layout_id = self.interactivity.request_layout(
109 global_id,
110 inspector_id,
111 window,
112 cx,
113 |style, window, cx| window.request_layout(style, None, cx),
114 );
115 (layout_id, ())
116 }
117
118 fn prepaint(
119 &mut self,
120 global_id: Option<&GlobalElementId>,
121 inspector_id: Option<&InspectorElementId>,
122 bounds: Bounds<Pixels>,
123 _request_layout: &mut Self::RequestLayoutState,
124 window: &mut Window,
125 cx: &mut App,
126 ) -> Option<Hitbox> {
127 self.interactivity.prepaint(
128 global_id,
129 inspector_id,
130 bounds,
131 bounds.size,
132 window,
133 cx,
134 |_, _, hitbox, _, _| hitbox,
135 )
136 }
137
138 fn paint(
139 &mut self,
140 global_id: Option<&GlobalElementId>,
141 inspector_id: Option<&InspectorElementId>,
142 bounds: Bounds<Pixels>,
143 _request_layout: &mut Self::RequestLayoutState,
144 hitbox: &mut Option<Hitbox>,
145 window: &mut Window,
146 cx: &mut App,
147 ) where
148 Self: Sized,
149 {
150 self.interactivity.paint(
151 global_id,
152 inspector_id,
153 bounds,
154 hitbox.as_ref(),
155 window,
156 cx,
157 |style, window, cx| {
158 let center = bounds.center();
159 let scale_factor = window.scale_factor();
160 let animation = self
161 .transformation
162 .filter(|timed| timed.is_animated() && !cx.reduce_motion())
163 .map(|timed| SpriteAnimation::new(timed, center, scale_factor));
164 let pose = self.transformation.map(|timed| timed.from);
167 let transformation = pose
168 .map(|pose| pose.into_matrix(center, scale_factor))
169 .unwrap_or_default();
170 let alpha = match animation {
173 Some(_) => 1.,
174 None => pose.map_or(1., |pose| pose.alpha_factor()),
175 };
176
177 if let Some((data, path)) = self.data.as_ref().zip(self.data_path.as_ref()) {
178 if let Some(color) = style.text.color {
179 window
180 .paint_animated_svg(
181 bounds,
182 path.clone(),
183 Some(&**data),
184 transformation,
185 animation,
186 color.opacity(alpha),
187 cx,
188 )
189 .log_err();
190 }
191 } else if let Some((path, color)) =
192 self.external_path.as_ref().zip(style.text.color)
193 {
194 let Some(bytes) = window
195 .use_asset::<SvgAsset>(path, cx)
196 .and_then(|asset| asset.log_err())
197 else {
198 return;
199 };
200
201 window
202 .paint_animated_svg(
203 bounds,
204 path.clone(),
205 Some(&bytes),
206 transformation,
207 animation,
208 color.opacity(alpha),
209 cx,
210 )
211 .log_err();
212 } else if let Some((path, color)) = self.path.as_ref().zip(style.text.color) {
213 window
214 .paint_animated_svg(
215 bounds,
216 path.clone(),
217 None,
218 transformation,
219 animation,
220 color.opacity(alpha),
221 cx,
222 )
223 .log_err();
224 }
225 },
226 )
227 }
228}
229
230impl Styled for Svg {
231 fn style(&mut self) -> &mut StyleRefinement {
232 &mut self.interactivity.base_style
233 }
234}
235
236impl InteractiveElement for Svg {
237 fn interactivity(&mut self) -> &mut Interactivity {
238 &mut self.interactivity
239 }
240}
241
242#[derive(Clone, Copy, Debug, PartialEq)]
244pub struct Transformation {
245 scale: Size<f32>,
246 translate: Point<Pixels>,
247 rotate: Radians,
248 alpha: f32,
249}
250
251impl Default for Transformation {
252 fn default() -> Self {
253 Self {
254 scale: size(1.0, 1.0),
255 translate: point(px(0.0), px(0.0)),
256 rotate: radians(0.0),
257 alpha: 1.0,
258 }
259 }
260}
261
262impl Transformation {
263 pub fn scale(scale: Size<f32>) -> Self {
265 Self {
266 scale,
267 ..Self::default()
268 }
269 }
270
271 pub fn translate(translate: Point<Pixels>) -> Self {
273 Self {
274 translate,
275 ..Self::default()
276 }
277 }
278
279 pub fn rotate(rotate: impl Into<Radians>) -> Self {
281 let rotate = rotate.into();
282 Self {
283 rotate,
284 ..Self::default()
285 }
286 }
287
288 pub fn alpha(alpha: f32) -> Self {
290 Self {
291 alpha,
292 ..Self::default()
293 }
294 }
295
296 pub fn with_alpha(mut self, alpha: f32) -> Self {
299 self.alpha = alpha;
300 self
301 }
302
303 pub(crate) fn alpha_factor(&self) -> f32 {
304 self.alpha
305 }
306
307 pub fn with_scaling(mut self, scale: Size<f32>) -> Self {
309 self.scale = scale;
310 self
311 }
312
313 pub fn with_translation(mut self, translate: Point<Pixels>) -> Self {
315 self.translate = translate;
316 self
317 }
318
319 pub fn with_rotation(mut self, rotate: impl Into<Radians>) -> Self {
321 self.rotate = rotate.into();
322 self
323 }
324
325 pub(crate) fn into_matrix(
326 self,
327 center: Point<Pixels>,
328 scale_factor: f32,
329 ) -> TransformationMatrix {
330 TransformationMatrix::unit()
332 .translate(center.scale(scale_factor) + self.translate.scale(scale_factor))
333 .rotate(self.rotate)
334 .scale(self.scale)
335 .translate(center.scale(-scale_factor))
336 }
337}
338
339#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
341pub enum Easing {
342 #[default]
344 Linear,
345 Quadratic,
347 EaseInOut,
349 EaseOutQuint,
351 Heartbeat,
355}
356
357impl Easing {
358 fn apply(self, delta: f32) -> f32 {
359 match self {
360 Easing::Linear => linear(delta),
361 Easing::Quadratic => quadratic(delta),
362 Easing::EaseInOut => ease_in_out(delta),
363 Easing::EaseOutQuint => ease_out_quint()(delta),
364 Easing::Heartbeat => heartbeat(delta),
365 }
366 }
367}
368
369#[derive(Clone, Copy, Debug, PartialEq)]
375pub struct TimedTransformation {
376 period: Duration,
377 from: Transformation,
378 to: Transformation,
379 scale_easing: Easing,
380 translation_easing: Easing,
381 rotation_easing: Easing,
382 alpha_easing: Easing,
383 alternate: bool,
384 min_frame_interval: Option<Duration>,
385}
386
387impl TimedTransformation {
388 pub fn new(period: Duration) -> Self {
391 Self {
392 period,
393 from: Transformation::default(),
394 to: Transformation::default(),
395 scale_easing: Easing::Linear,
396 translation_easing: Easing::Linear,
397 rotation_easing: Easing::Linear,
398 alpha_easing: Easing::Linear,
399 alternate: false,
400 min_frame_interval: None,
401 }
402 }
403
404 pub fn rotation(period: Duration, from: Transformation) -> Self {
407 Self::new(period)
408 .from(from)
409 .to(from.with_rotation(radians(from.rotate.0 + TAU)))
410 }
411
412 fn is_animated(&self) -> bool {
413 !self.period.is_zero() && self.from != self.to
414 }
415
416 pub fn from(mut self, transformation: Transformation) -> Self {
418 self.from = transformation;
419 self
420 }
421
422 pub fn to(mut self, transformation: Transformation) -> Self {
424 self.to = transformation;
425 self
426 }
427
428 pub fn with_easing(mut self, easing: Easing) -> Self {
430 self.scale_easing = easing;
431 self.translation_easing = easing;
432 self.rotation_easing = easing;
433 self.alpha_easing = easing;
434 self
435 }
436
437 pub fn with_scale_easing(mut self, easing: Easing) -> Self {
439 self.scale_easing = easing;
440 self
441 }
442
443 pub fn with_translation_easing(mut self, easing: Easing) -> Self {
445 self.translation_easing = easing;
446 self
447 }
448
449 pub fn with_rotation_easing(mut self, easing: Easing) -> Self {
451 self.rotation_easing = easing;
452 self
453 }
454
455 pub fn with_alpha_easing(mut self, easing: Easing) -> Self {
457 self.alpha_easing = easing;
458 self
459 }
460
461 pub fn alternate(mut self) -> Self {
464 self.alternate = true;
465 self
466 }
467
468 pub fn with_max_fps(mut self, max_fps: f32) -> Self {
472 if max_fps.is_finite() && max_fps > 0.0 {
473 self.min_frame_interval = Some(Duration::from_secs_f64(1.0 / max_fps as f64));
474 }
475 self
476 }
477
478 pub(crate) fn min_frame_interval(&self) -> Option<Duration> {
479 self.min_frame_interval
480 }
481
482 pub(crate) fn at(&self, elapsed: Duration) -> Transformation {
484 let period_nanos = self.period.as_nanos();
485 if period_nanos == 0 {
486 return self.from;
487 }
488 let mut delta = Duration::from_nanos((elapsed.as_nanos() % period_nanos) as u64)
489 .as_secs_f32()
490 / self.period.as_secs_f32();
491 if self.alternate {
492 delta = 1.0 - (2.0 * delta - 1.0).abs();
493 }
494
495 let interpolate =
496 |from: f32, to: f32, easing: Easing| from + (to - from) * easing.apply(delta);
497 let (from, to) = (self.from, self.to);
498 Transformation {
499 scale: size(
500 interpolate(from.scale.width, to.scale.width, self.scale_easing),
501 interpolate(from.scale.height, to.scale.height, self.scale_easing),
502 ),
503 translate: point(
504 px(interpolate(
505 from.translate.x.0,
506 to.translate.x.0,
507 self.translation_easing,
508 )),
509 px(interpolate(
510 from.translate.y.0,
511 to.translate.y.0,
512 self.translation_easing,
513 )),
514 ),
515 rotate: radians(interpolate(
516 from.rotate.0,
517 to.rotate.0,
518 self.rotation_easing,
519 )),
520 alpha: interpolate(from.alpha, to.alpha, self.alpha_easing),
521 }
522 }
523}
524
525impl From<Transformation> for TimedTransformation {
526 fn from(transformation: Transformation) -> Self {
528 Self::new(Duration::ZERO)
529 .from(transformation)
530 .to(transformation)
531 }
532}
533
534enum SvgAsset {}
535
536impl Asset for SvgAsset {
537 type Source = SharedString;
538 type Output = Result<Arc<[u8]>, Arc<std::io::Error>>;
539
540 fn load(
541 source: Self::Source,
542 _cx: &mut App,
543 ) -> impl Future<Output = Self::Output> + Send + 'static {
544 async move {
545 let bytes = fs::read(Path::new(source.as_ref())).map_err(|e| Arc::new(e))?;
546 let bytes = Arc::from(bytes);
547 Ok(bytes)
548 }
549 }
550}
551
552#[cfg(test)]
553mod tests {
554 use std::{cell::Cell, f32::consts::FRAC_PI_2, rc::Rc, time::Duration};
555
556 use crate::{
557 Context, Easing, IntoElement, Render, SpriteAnimationId, Styled, TestAppContext,
558 TimedTransformation, Transformation, VisualTestContext, Window, div, prelude::*, px, red,
559 size, svg,
560 };
561
562 const SQUARE_SVG: &[u8] =
563 br#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="8" height="16"/></svg>"#;
564
565 struct AnimatedSvgView {
566 transformation: TimedTransformation,
567 renders: Rc<Cell<usize>>,
568 }
569
570 impl Render for AnimatedSvgView {
571 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
572 self.renders.set(self.renders.get() + 1);
573 div().child(
574 svg()
575 .data(SQUARE_SVG)
576 .size(px(16.))
577 .text_color(red())
578 .with_timed_transformation(self.transformation),
579 )
580 }
581 }
582
583 struct Pose {
584 rotation_scale: [[f32; 2]; 2],
585 center_offset: [f32; 2],
586 alpha: f32,
587 }
588
589 fn animate(
593 transformation: TimedTransformation,
594 cx: &mut TestAppContext,
595 ) -> (impl FnMut(Duration) -> Pose, Rc<Cell<usize>>) {
596 let renders = Rc::new(Cell::new(0));
597 let (_, cx) = cx.add_window_view({
598 let renders = renders.clone();
599 move |_, _| AnimatedSvgView {
600 transformation,
601 renders,
602 }
603 });
604 cx.run_until_parked();
605 let cx: &mut VisualTestContext = cx;
606 let pose_after = move |advance: Duration| {
607 cx.executor().advance_clock(advance);
608 cx.update(|window, cx| {
609 window.simulate_next_frame(cx);
610 window.advance_scene_animations(cx);
611 let sprite = window
612 .rendered_frame
613 .scene
614 .monochrome_sprites
615 .iter()
616 .find(|sprite| sprite.animation != SpriteAnimationId::NONE)
617 .expect("the SVG should be painted as an animated sprite");
618 let center = sprite.bounds.center();
619 let [[a, b], [c, d]] = sprite.transformation.rotation_scale;
620 let [x, y] = sprite.transformation.translation;
621 Pose {
622 rotation_scale: sprite.transformation.rotation_scale,
623 center_offset: [
624 a * center.x.0 + b * center.y.0 + x - center.x.0,
625 c * center.x.0 + d * center.y.0 + y - center.y.0,
626 ],
627 alpha: sprite.color.a,
628 }
629 })
630 };
631 (pose_after, renders)
632 }
633
634 #[crate::test]
635 fn test_rotation_advances_without_rerendering(cx: &mut TestAppContext) {
636 let (mut pose_after, renders) = animate(
637 TimedTransformation::rotation(Duration::from_secs(1), Transformation::default()),
638 cx,
639 );
640 let renders_before_frames = renders.get();
641
642 for quarter in 0..4 {
643 let pose = pose_after(if quarter == 0 {
644 Duration::ZERO
645 } else {
646 Duration::from_millis(250)
647 });
648 let (sin, cos) = (quarter as f32 * FRAC_PI_2).sin_cos();
649 let expected = [[cos, -sin], [sin, cos]];
650 for (actual, expected) in pose
651 .rotation_scale
652 .as_flattened()
653 .iter()
654 .zip(expected.as_flattened())
655 {
656 assert!((actual - expected).abs() < 1e-5, "quarter {quarter}");
657 }
658 assert!(pose.center_offset.iter().all(|offset| offset.abs() < 1e-3));
659 }
660 assert_eq!(renders.get(), renders_before_frames);
661 }
662
663 #[crate::test]
664 fn test_timed_transformation_eases_each_value_separately(cx: &mut TestAppContext) {
665 let (mut pose_after, renders) = animate(
666 TimedTransformation::new(Duration::from_secs(1))
667 .from(Transformation::alpha(0.4))
668 .to(Transformation::scale(size(1.5, 1.5)).with_alpha(0.))
669 .with_scale_easing(Easing::EaseOutQuint),
670 cx,
671 );
672 let renders_before_frames = renders.get();
673
674 let pose = pose_after(Duration::ZERO);
675 assert!((pose.rotation_scale[0][0] - 1.).abs() < 1e-5);
676 assert!((pose.alpha - 0.4).abs() < 1e-5);
677
678 let pose = pose_after(Duration::from_millis(500));
681 assert!((pose.rotation_scale[0][0] - (1. + 0.5 * (1. - 0.5f32.powi(5)))).abs() < 1e-5);
682 assert!((pose.alpha - 0.2).abs() < 1e-5);
683 assert_eq!(renders.get(), renders_before_frames);
684 }
685
686 #[crate::test]
687 fn test_heartbeat_returns_to_its_start(cx: &mut TestAppContext) {
688 let (mut pose_after, _) = animate(
689 TimedTransformation::new(Duration::from_secs(1))
690 .to(Transformation::scale(size(1.12, 1.12)))
691 .with_scale_easing(Easing::Heartbeat),
692 cx,
693 );
694
695 assert!((pose_after(Duration::ZERO).rotation_scale[0][0] - 1.).abs() < 1e-3);
696 assert!((pose_after(Duration::from_millis(200)).rotation_scale[0][0] - 1.12).abs() < 1e-3);
697 let second_beat = pose_after(Duration::from_millis(200)).rotation_scale[0][0];
699 assert!(second_beat > 1.05 && second_beat < 1.09);
700 assert!((pose_after(Duration::from_millis(599)).rotation_scale[0][0] - 1.).abs() < 1e-3);
701 }
702
703 #[crate::test]
704 fn test_scene_presents_as_often_as_its_least_capped_animation(cx: &mut TestAppContext) {
705 let spin = TimedTransformation::rotation(Duration::from_secs(1), Transformation::default());
706 let (_, cx) = cx.add_window_view(move |_, _| CappedView { spin });
707 cx.run_until_parked();
708 cx.update(|window, _| {
709 assert_eq!(
710 window.rendered_frame.scene.animation_frame_interval(),
711 Some(Duration::from_millis(50))
712 );
713 });
714 }
715
716 struct CappedView {
717 spin: TimedTransformation,
718 }
719
720 impl Render for CappedView {
721 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
722 let icon = || svg().data(SQUARE_SVG).size(px(16.)).text_color(red());
723 div()
724 .child(icon().with_timed_transformation(self.spin.with_max_fps(10.)))
725 .child(icon().with_timed_transformation(self.spin.with_max_fps(20.)))
726 .child(icon().with_transformation(Transformation::alpha(0.5)))
727 }
728 }
729}