Skip to main content

aylis_vector/
controls.rs

1//! Os componentes: `Lottie` (animação) e `Svg` (imagem vetorial).
2
3use 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
12/// `class_name`, `control` e `control_mut` de um controle com `base`.
13macro_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
29/// `"pacote:nome"` vira `assets/lottie/<pacote>/<nome>.json` (as animações que a IDE
30/// copia para o projeto); o resto é um caminho dentro do projeto.
31pub 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
40/// O retângulo (na tela) da área `content` encaixada em `r` com `fit`.
41fn 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
56// ===========================================================================
57// Lottie
58// ===========================================================================
59
60/// Animação Lottie (o JSON do After Effects/Bodymovin), como o `TLottieAnimation`. Desenha
61/// vetor: nítida em qualquer tamanho, em qualquer renderizador.
62///
63/// - `source`: `"noto:fogo"` (pacote de animações da IDE; o app leva só as citadas) ou um
64///   caminho no projeto (`assets/lottie/carregando.json`);
65/// - `playing`, `repeat`, `speed` (1 = normal) e `position` (segundos; onde fica parada);
66/// - pelo código: [`Lottie::set_animation`] com uma [`Animation`] lida de qualquer lugar.
67pub 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    /// O instante (relógio da pintura) que corresponde ao começo da animação.
78    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    /// Usa uma animação lida pelo código (vale mais que `source`).
106    pub fn set_animation(&mut self, animation: Option<Animation>) {
107        self.animation = animation.map(Rc::new);
108        self.started.set(None);
109    }
110
111    /// Lê o JSON e usa a animação.
112    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    /// Para onde está (continua dali com `play`).
123    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    /// Para e volta ao começo.
132    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
200// ===========================================================================
201// Svg
202// ===========================================================================
203
204/// Imagem SVG desenhada como vetor (o `TPath` com um arquivo inteiro). `source` é o
205/// arquivo no projeto (`assets/images/logo.svg`); `color` é o `currentColor` (sem ela,
206/// a cor de texto do tema: ícones em SVG acompanham o tema claro e o escuro).
207///
208/// Para mapas: `highlight` pinta os elementos com esses `id` (separados por `;`) com
209/// `highlight_color` (sem ela, a cor de destaque do tema) e `zoom_to` mostra só a área do
210/// elemento com esse `id` (o município dentro do mapa do estado).
211pub 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    /// Usa um SVG dado pelo código (texto), no lugar de `source`.
247    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
268/// O SVG lido de um arquivo, dividido entre os `Svg` que mostram o mesmo conteúdo (o mapa
269/// do estado aparece inteiro e com zoom no município): lido uma vez só.
270fn 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        // zoom_to: a área do elemento com uma folga (a de um ponto ganha um tamanho mínimo).
308        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        // Guardado como imagem: um mapa com centenas de áreas só é redesenhado quando o
323        // tamanho, a área, o destaque ou as cores mudam (repintar a tela não o refaz).
324        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}