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). 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    /// A animação: `"noto:fogo"` (do pacote de animações da IDE) ou um caminho no projeto
70    /// (`assets/lottie/carregando.json`).
71    pub source: String,
72    /// A animação anda; desligado, fica parada na `position`.
73    pub playing: bool,
74    /// Recomeça ao chegar ao fim; desligado, toca uma vez e para no último quadro.
75    pub repeat: bool,
76    /// Velocidade (1 = normal, 2 = o dobro).
77    pub speed: f32,
78    /// O ponto da animação, em segundos: onde ela fica parada e de onde começa a tocar.
79    pub position: f32,
80    /// Como a animação ocupa o controle: caber inteira, cobrir, esticar...
81    pub fit: ImageFit,
82    animation: Option<Rc<Animation>>,
83    loaded: RefCell<Option<(String, Option<Rc<Animation>>)>>,
84    /// O instante (relógio da pintura) que corresponde ao começo da animação.
85    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    /// Usa uma animação lida pelo código (vale mais que `source`).
113    pub fn set_animation(&mut self, animation: Option<Animation>) {
114        self.animation = animation.map(Rc::new);
115        self.started.set(None);
116    }
117
118    /// Lê o JSON e usa a animação.
119    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    /// Para onde está (continua dali com `play`).
130    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    /// Para e volta ao começo.
139    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
207// ===========================================================================
208// Svg
209// ===========================================================================
210
211/// Imagem SVG desenhada como vetor. `source` é o
212/// arquivo no projeto (`assets/images/logo.svg`); `color` é o `currentColor` (sem ela,
213/// a cor de texto do tema: ícones em SVG acompanham o tema claro e o escuro).
214///
215/// Para mapas: `highlight` pinta os elementos com esses `id` (separados por `;`) com
216/// `highlight_color` (sem ela, a cor de destaque do tema) e `zoom_to` mostra só a área do
217/// elemento com esse `id` (o município dentro do mapa do estado).
218pub struct Svg {
219    pub base: ControlBase,
220    /// O arquivo SVG no projeto (`assets/images/logo.svg`).
221    pub source: String,
222    /// A cor do `currentColor` do SVG; sem cor, a cor de texto do tema.
223    pub color: Option<Color>,
224    /// Como a imagem ocupa o controle: caber inteira, cobrir, esticar...
225    pub fit: ImageFit,
226    /// Os `id` dos elementos pintados com `highlight_color`, separados por `;`; vazio: nenhum.
227    pub highlight: String,
228    /// A cor dos elementos do `highlight`; sem cor, a cor de destaque do tema.
229    pub highlight_color: Option<Color>,
230    /// O `id` do elemento cuja área é mostrada (o município dentro do mapa); vazio: o SVG inteiro.
231    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    /// Usa um SVG dado pelo código (texto), no lugar de `source`.
260    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
281/// O SVG lido de um arquivo, dividido entre os `Svg` que mostram o mesmo conteúdo (o mapa
282/// do estado aparece inteiro e com zoom no município): lido uma vez só.
283fn 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        // zoom_to: a área do elemento com uma folga (a de um ponto ganha um tamanho mínimo).
321        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        // Guardado como imagem: um mapa com centenas de áreas só é redesenhado quando o
336        // tamanho, a área, o destaque ou as cores mudam (repintar a tela não o refaz).
337        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}