1use std::cell::{Cell, RefCell};
4use std::rc::Rc;
5
6use aylis_core::{Canvas, Color, Component, ControlBase, ImageFit, PaintCtx, RectF, SizeF, Stroke, properties};
7
8use crate::geom::Affine;
9use crate::lottie::Animation;
10use crate::svg::SvgImage;
11
12macro_rules! leaf_control {
14 ($name:literal) => {
15 fn class_name(&self) -> &'static str {
16 $name
17 }
18
19 fn control(&self) -> Option<&ControlBase> {
20 Some(&self.base)
21 }
22
23 fn control_mut(&mut self) -> Option<&mut ControlBase> {
24 Some(&mut self.base)
25 }
26 };
27}
28
29pub fn lottie_path(source: &str) -> String {
32 match source.split_once(':') {
33 Some((pack, name)) if !pack.is_empty() && !name.contains('/') && !source.contains('/') => {
34 format!("assets/lottie/{pack}/{name}.json")
35 }
36 _ => source.to_string(),
37 }
38}
39
40fn fit_rect(fit: ImageFit, content: SizeF, r: RectF) -> RectF {
42 let (src, dest) = fit.place(content, r);
43 let m = Affine::rect_to_rect(src, dest);
44 let a = m.apply(aylis_core::PointF::new(0.0, 0.0));
45 let b = m.apply(aylis_core::PointF::new(content.width, content.height));
46 RectF::new(a.x, a.y, b.x - a.x, b.y - a.y)
47}
48
49fn placeholder(canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
50 if ctx.design {
51 let color = ctx.theme.color("text_muted").with_opacity(0.6);
52 canvas.stroke_rect(ctx.rect.inflate(-0.5), 4.0, &Stroke::new(color, 1.0).dashed(vec![4.0, 3.0]));
53 }
54}
55
56pub struct Lottie {
68 pub base: ControlBase,
69 pub source: String,
70 pub playing: bool,
71 pub repeat: bool,
72 pub speed: f32,
73 pub position: f32,
74 pub fit: ImageFit,
75 animation: Option<Rc<Animation>>,
76 loaded: RefCell<Option<(String, Option<Rc<Animation>>)>>,
77 started: Cell<Option<f64>>,
79}
80
81impl Default for Lottie {
82 fn default() -> Self {
83 let mut base = ControlBase::new(96.0, 96.0);
84 base.set_hit_test(false);
85 Self {
86 base,
87 source: String::new(),
88 playing: true,
89 repeat: true,
90 speed: 1.0,
91 position: 0.0,
92 fit: ImageFit::Contain,
93 animation: None,
94 loaded: RefCell::new(None),
95 started: Cell::new(None),
96 }
97 }
98}
99
100impl Lottie {
101 pub fn new(source: impl Into<String>) -> Self {
102 Self { source: source.into(), ..Default::default() }
103 }
104
105 pub fn set_animation(&mut self, animation: Option<Animation>) {
107 self.animation = animation.map(Rc::new);
108 self.started.set(None);
109 }
110
111 pub fn load_json(&mut self, json: &[u8]) -> Result<(), String> {
113 self.set_animation(Some(Animation::parse(json)?));
114 Ok(())
115 }
116
117 pub fn play(&mut self) {
118 self.playing = true;
119 self.started.set(None);
120 }
121
122 pub fn pause(&mut self, now: f64) {
124 if let Some(start) = self.started.get() {
125 self.position = ((now - start) as f32) * self.speed;
126 }
127 self.playing = false;
128 self.started.set(None);
129 }
130
131 pub fn stop(&mut self) {
133 self.playing = false;
134 self.position = 0.0;
135 self.started.set(None);
136 }
137
138 fn sync(&mut self, name: &str) {
139 if matches!(name, "playing" | "position" | "speed" | "source") {
140 self.started.set(None);
141 }
142 }
143
144 fn current(&self, ctx: &PaintCtx<'_>) -> Option<Rc<Animation>> {
145 if let Some(a) = &self.animation {
146 return Some(a.clone());
147 }
148 if self.source.is_empty() {
149 return None;
150 }
151 let mut loaded = self.loaded.borrow_mut();
152 if loaded.as_ref().is_none_or(|(s, _)| *s != self.source) {
153 let anim = ctx.resource(&lottie_path(&self.source)).and_then(|d| Animation::parse(&d).ok()).map(Rc::new);
154 *loaded = Some((self.source.clone(), anim));
155 }
156 loaded.as_ref().and_then(|(_, a)| a.clone())
157 }
158}
159
160impl Component for Lottie {
161 leaf_control!("Lottie");
162
163 properties! {
164 source: String => "Appearance",
165 playing: bool => "Behavior",
166 repeat: bool => "Behavior",
167 speed: f32 => "Behavior",
168 position: f32 => "Behavior",
169 fit: ImageFit => "Appearance";
170 on_set: sync
171 }
172
173 fn paint(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
174 let Some(anim) = self.current(ctx) else {
175 placeholder(canvas, ctx);
176 return;
177 };
178 let seconds = if self.playing && self.speed != 0.0 {
179 let start = self.started.get().unwrap_or_else(|| {
180 let s = ctx.time - (self.position / self.speed) as f64;
181 self.started.set(Some(s));
182 s
183 });
184 ((ctx.time - start) as f32) * self.speed
185 } else {
186 self.position
187 };
188 let (w, h) = anim.size();
189 let dest = fit_rect(self.fit, SizeF::new(w, h), ctx.rect);
190 canvas.save();
191 canvas.clip_rect(ctx.rect);
192 anim.render(canvas, anim.frame_at(seconds, self.repeat), dest);
193 canvas.restore();
194 if self.playing && (self.repeat || seconds < anim.duration()) {
195 ctx.request_frame();
196 }
197 }
198}
199
200pub struct Svg {
212 pub base: ControlBase,
213 pub source: String,
214 pub color: Option<Color>,
215 pub fit: ImageFit,
216 pub highlight: String,
217 pub highlight_color: Option<Color>,
218 pub zoom_to: String,
219 image: Option<Rc<SvgImage>>,
220 loaded: RefCell<Option<(String, Option<Rc<SvgImage>>)>>,
221}
222
223impl Default for Svg {
224 fn default() -> Self {
225 let mut base = ControlBase::new(64.0, 64.0);
226 base.set_hit_test(false);
227 Self {
228 base,
229 source: String::new(),
230 color: None,
231 fit: ImageFit::Contain,
232 highlight: String::new(),
233 highlight_color: None,
234 zoom_to: String::new(),
235 image: None,
236 loaded: RefCell::new(None),
237 }
238 }
239}
240
241impl Svg {
242 pub fn new(source: impl Into<String>) -> Self {
243 Self { source: source.into(), ..Default::default() }
244 }
245
246 pub fn set_svg(&mut self, text: &str) -> Result<(), String> {
248 self.image = Some(Rc::new(SvgImage::parse(text)?));
249 Ok(())
250 }
251
252 fn current(&self, ctx: &PaintCtx<'_>) -> Option<Rc<SvgImage>> {
253 if let Some(i) = &self.image {
254 return Some(i.clone());
255 }
256 if self.source.is_empty() {
257 return None;
258 }
259 let mut loaded = self.loaded.borrow_mut();
260 if loaded.as_ref().is_none_or(|(s, _)| *s != self.source) {
261 let image = ctx.resource(&self.source).and_then(|d| shared_svg(&d));
262 *loaded = Some((self.source.clone(), image));
263 }
264 loaded.as_ref().and_then(|(_, i)| i.clone())
265 }
266}
267
268fn shared_svg(data: &[u8]) -> Option<Rc<SvgImage>> {
271 use std::hash::{Hash, Hasher};
272 thread_local! {
273 static LOADED: RefCell<Vec<(u64, std::rc::Weak<SvgImage>)>> = const { RefCell::new(Vec::new()) };
274 }
275 let mut h = std::collections::hash_map::DefaultHasher::new();
276 data.hash(&mut h);
277 let key = h.finish();
278 LOADED.with(|l| {
279 let mut l = l.borrow_mut();
280 l.retain(|(_, w)| w.strong_count() > 0);
281 if let Some(image) = l.iter().find(|(k, _)| *k == key).and_then(|(_, w)| w.upgrade()) {
282 return Some(image);
283 }
284 let image = Rc::new(SvgImage::parse(std::str::from_utf8(data).ok()?).ok()?);
285 l.push((key, Rc::downgrade(&image)));
286 Some(image)
287 })
288}
289
290impl Component for Svg {
291 leaf_control!("Svg");
292
293 properties! {
294 source: String => "Appearance",
295 color: Option<Color> => "Appearance",
296 fit: ImageFit => "Appearance",
297 highlight: String => "Appearance",
298 highlight_color: Option<Color> => "Appearance",
299 zoom_to: String => "Appearance",
300 }
301
302 fn paint(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
303 let Some(image) = self.current(ctx) else {
304 placeholder(canvas, ctx);
305 return;
306 };
307 let view = match image.bounds_of(self.zoom_to.trim()).filter(|_| !self.zoom_to.trim().is_empty()) {
309 Some(b) => {
310 let full = image.view_box();
311 let pad = (b.width.max(b.height) * 0.08).max(full.width.max(full.height) * 0.005);
312 RectF::new(b.x - pad, b.y - pad, b.width + 2.0 * pad, b.height + 2.0 * pad)
313 }
314 None => image.view_box(),
315 };
316 let dest = fit_rect(self.fit, SizeF::new(view.width, view.height), ctx.rect);
317 let color = self.color.unwrap_or(ctx.style.text);
318 let highlight: Vec<&str> = self.highlight.split(';').map(str::trim).filter(|s| !s.is_empty()).collect();
319 let highlight_color = self.highlight_color.unwrap_or_else(|| ctx.theme.color("primary"));
320 canvas.save();
321 canvas.clip_rect(ctx.rect);
322 let key = {
325 use std::hash::{Hash, Hasher};
326 let mut h = std::collections::hash_map::DefaultHasher::new();
327 (Rc::as_ptr(&image) as usize, color, highlight_color, &highlight).hash(&mut h);
328 for v in [view.x, view.y, view.width, view.height, dest.x - ctx.rect.x, dest.y - ctx.rect.y, dest.width, dest.height] {
329 v.to_bits().hash(&mut h);
330 }
331 h.finish()
332 };
333 if !canvas.begin_cached(key, ctx.rect) {
334 image.render_visible(canvas, view, dest, Some(ctx.rect), color, &highlight, highlight_color);
335 canvas.end_cached();
336 }
337 canvas.restore();
338 }
339}