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,
72 pub playing: bool,
74 pub repeat: bool,
76 pub speed: f32,
78 pub position: f32,
80 pub fit: ImageFit,
82 animation: Option<Rc<Animation>>,
83 loaded: RefCell<Option<(String, Option<Rc<Animation>>)>>,
84 started: Cell<Option<f64>>,
86}
87
88impl Default for Lottie {
89 fn default() -> Self {
90 let mut base = ControlBase::new(96.0, 96.0);
91 base.set_hit_test(false);
92 Self {
93 base,
94 source: String::new(),
95 playing: true,
96 repeat: true,
97 speed: 1.0,
98 position: 0.0,
99 fit: ImageFit::Contain,
100 animation: None,
101 loaded: RefCell::new(None),
102 started: Cell::new(None),
103 }
104 }
105}
106
107impl Lottie {
108 pub fn new(source: impl Into<String>) -> Self {
109 Self { source: source.into(), ..Default::default() }
110 }
111
112 pub fn set_animation(&mut self, animation: Option<Animation>) {
114 self.animation = animation.map(Rc::new);
115 self.started.set(None);
116 }
117
118 pub fn load_json(&mut self, json: &[u8]) -> Result<(), String> {
120 self.set_animation(Some(Animation::parse(json)?));
121 Ok(())
122 }
123
124 pub fn play(&mut self) {
125 self.playing = true;
126 self.started.set(None);
127 }
128
129 pub fn pause(&mut self, now: f64) {
131 if let Some(start) = self.started.get() {
132 self.position = ((now - start) as f32) * self.speed;
133 }
134 self.playing = false;
135 self.started.set(None);
136 }
137
138 pub fn stop(&mut self) {
140 self.playing = false;
141 self.position = 0.0;
142 self.started.set(None);
143 }
144
145 fn sync(&mut self, name: &str) {
146 if matches!(name, "playing" | "position" | "speed" | "source") {
147 self.started.set(None);
148 }
149 }
150
151 fn current(&self, ctx: &PaintCtx<'_>) -> Option<Rc<Animation>> {
152 if let Some(a) = &self.animation {
153 return Some(a.clone());
154 }
155 if self.source.is_empty() {
156 return None;
157 }
158 let mut loaded = self.loaded.borrow_mut();
159 if loaded.as_ref().is_none_or(|(s, _)| *s != self.source) {
160 let anim = ctx.resource(&lottie_path(&self.source)).and_then(|d| Animation::parse(&d).ok()).map(Rc::new);
161 *loaded = Some((self.source.clone(), anim));
162 }
163 loaded.as_ref().and_then(|(_, a)| a.clone())
164 }
165}
166
167impl Component for Lottie {
168 leaf_control!("Lottie");
169
170 properties! {
171 source: String => "Appearance",
172 playing: bool => "Behavior",
173 repeat: bool => "Behavior",
174 speed: f32 => "Behavior",
175 position: f32 => "Behavior",
176 fit: ImageFit => "Appearance";
177 on_set: sync
178 }
179
180 fn paint(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
181 let Some(anim) = self.current(ctx) else {
182 placeholder(canvas, ctx);
183 return;
184 };
185 let seconds = if self.playing && self.speed != 0.0 {
186 let start = self.started.get().unwrap_or_else(|| {
187 let s = ctx.time - (self.position / self.speed) as f64;
188 self.started.set(Some(s));
189 s
190 });
191 ((ctx.time - start) as f32) * self.speed
192 } else {
193 self.position
194 };
195 let (w, h) = anim.size();
196 let dest = fit_rect(self.fit, SizeF::new(w, h), ctx.rect);
197 canvas.save();
198 canvas.clip_rect(ctx.rect);
199 anim.render(canvas, anim.frame_at(seconds, self.repeat), dest);
200 canvas.restore();
201 if self.playing && (self.repeat || seconds < anim.duration()) {
202 ctx.request_frame();
203 }
204 }
205}
206
207pub struct Svg {
219 pub base: ControlBase,
220 pub source: String,
222 pub color: Option<Color>,
224 pub fit: ImageFit,
226 pub highlight: String,
228 pub highlight_color: Option<Color>,
230 pub zoom_to: String,
232 image: Option<Rc<SvgImage>>,
233 loaded: RefCell<Option<(String, Option<Rc<SvgImage>>)>>,
234}
235
236impl Default for Svg {
237 fn default() -> Self {
238 let mut base = ControlBase::new(64.0, 64.0);
239 base.set_hit_test(false);
240 Self {
241 base,
242 source: String::new(),
243 color: None,
244 fit: ImageFit::Contain,
245 highlight: String::new(),
246 highlight_color: None,
247 zoom_to: String::new(),
248 image: None,
249 loaded: RefCell::new(None),
250 }
251 }
252}
253
254impl Svg {
255 pub fn new(source: impl Into<String>) -> Self {
256 Self { source: source.into(), ..Default::default() }
257 }
258
259 pub fn set_svg(&mut self, text: &str) -> Result<(), String> {
261 self.image = Some(Rc::new(SvgImage::parse(text)?));
262 Ok(())
263 }
264
265 fn current(&self, ctx: &PaintCtx<'_>) -> Option<Rc<SvgImage>> {
266 if let Some(i) = &self.image {
267 return Some(i.clone());
268 }
269 if self.source.is_empty() {
270 return None;
271 }
272 let mut loaded = self.loaded.borrow_mut();
273 if loaded.as_ref().is_none_or(|(s, _)| *s != self.source) {
274 let image = ctx.resource(&self.source).and_then(|d| shared_svg(&d));
275 *loaded = Some((self.source.clone(), image));
276 }
277 loaded.as_ref().and_then(|(_, i)| i.clone())
278 }
279}
280
281fn shared_svg(data: &[u8]) -> Option<Rc<SvgImage>> {
284 use std::hash::{Hash, Hasher};
285 thread_local! {
286 static LOADED: RefCell<Vec<(u64, std::rc::Weak<SvgImage>)>> = const { RefCell::new(Vec::new()) };
287 }
288 let mut h = std::collections::hash_map::DefaultHasher::new();
289 data.hash(&mut h);
290 let key = h.finish();
291 LOADED.with(|l| {
292 let mut l = l.borrow_mut();
293 l.retain(|(_, w)| w.strong_count() > 0);
294 if let Some(image) = l.iter().find(|(k, _)| *k == key).and_then(|(_, w)| w.upgrade()) {
295 return Some(image);
296 }
297 let image = Rc::new(SvgImage::parse(std::str::from_utf8(data).ok()?).ok()?);
298 l.push((key, Rc::downgrade(&image)));
299 Some(image)
300 })
301}
302
303impl Component for Svg {
304 leaf_control!("Svg");
305
306 properties! {
307 source: String => "Appearance",
308 color: Option<Color> => "Appearance",
309 fit: ImageFit => "Appearance",
310 highlight: String as List => "Appearance",
311 highlight_color: Option<Color> => "Appearance",
312 zoom_to: String => "Appearance",
313 }
314
315 fn paint(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
316 let Some(image) = self.current(ctx) else {
317 placeholder(canvas, ctx);
318 return;
319 };
320 let view = match image.bounds_of(self.zoom_to.trim()).filter(|_| !self.zoom_to.trim().is_empty()) {
322 Some(b) => {
323 let full = image.view_box();
324 let pad = (b.width.max(b.height) * 0.08).max(full.width.max(full.height) * 0.005);
325 RectF::new(b.x - pad, b.y - pad, b.width + 2.0 * pad, b.height + 2.0 * pad)
326 }
327 None => image.view_box(),
328 };
329 let dest = fit_rect(self.fit, SizeF::new(view.width, view.height), ctx.rect);
330 let color = self.color.unwrap_or(ctx.style.text);
331 let highlight: Vec<&str> = self.highlight.split(';').map(str::trim).filter(|s| !s.is_empty()).collect();
332 let highlight_color = self.highlight_color.unwrap_or_else(|| ctx.theme.color("primary"));
333 canvas.save();
334 canvas.clip_rect(ctx.rect);
335 let key = {
338 use std::hash::{Hash, Hasher};
339 let mut h = std::collections::hash_map::DefaultHasher::new();
340 (Rc::as_ptr(&image) as usize, color, highlight_color, &highlight).hash(&mut h);
341 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] {
342 v.to_bits().hash(&mut h);
343 }
344 h.finish()
345 };
346 if !canvas.begin_cached(key, ctx.rect) {
347 image.render_visible(canvas, view, dest, Some(ctx.rect), color, &highlight, highlight_color);
348 canvas.end_cached();
349 }
350 canvas.restore();
351 }
352}