Skip to main content

aylis_core/
transition.rs

1//! Transições entre páginas e forms: esmaecer e deslizar. A página nova entra enquanto a
2//! antiga sai, as duas desenhadas ao mesmo tempo (deslocadas com `translate_x`/`translate_y`
3//! e `opacity`, que não mexem no layout); no fim, a antiga é escondida (ou o form é
4//! fechado) e os valores voltam ao normal.
5//!
6//! Quem usa: o `TabControl` (propriedade `transition`), os forms empilhados do celular e
7//! do navegador (propriedade `transition` do form, ao abrir e fechar) e o app, por
8//! [`Ui::transition`].
9
10use crate::component::ComponentId;
11use crate::geometry::PointF;
12use crate::prop::PropEnum;
13use crate::ui::Ui;
14
15/// O tipo de transição. `slide_left`: o conteúdo anda para a esquerda (a página nova entra
16/// pela direita, como ao avançar); `slide_right`, o contrário (ao voltar).
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
18pub enum Transition {
19    #[default]
20    None,
21    Fade,
22    SlideLeft,
23    SlideRight,
24    SlideUp,
25    SlideDown,
26}
27
28impl Transition {
29    pub const ALL: [Transition; 6] =
30        [Transition::None, Transition::Fade, Transition::SlideLeft, Transition::SlideRight, Transition::SlideUp, Transition::SlideDown];
31
32    /// A transição de volta (para fechar o que abriu com esta).
33    pub fn reversed(self) -> Self {
34        match self {
35            Transition::SlideLeft => Transition::SlideRight,
36            Transition::SlideRight => Transition::SlideLeft,
37            Transition::SlideUp => Transition::SlideDown,
38            Transition::SlideDown => Transition::SlideUp,
39            other => other,
40        }
41    }
42}
43
44impl PropEnum for Transition {
45    const NAMES: &'static [&'static str] = &["none", "fade", "slide_left", "slide_right", "slide_up", "slide_down"];
46
47    fn from_index(index: usize) -> Option<Self> {
48        Transition::ALL.get(index).copied()
49    }
50
51    fn index(self) -> usize {
52        self as usize
53    }
54}
55
56/// Duração padrão, em milissegundos.
57pub const TRANSITION_MS: f32 = 250.0;
58
59#[derive(Clone, Copy, Debug)]
60pub(crate) struct Running {
61    from: Option<ComponentId>,
62    to: Option<ComponentId>,
63    kind: Transition,
64    start: f64,
65    duration: f64,
66    /// Opacidade de antes (volta no fim).
67    from_opacity: f32,
68    to_opacity: f32,
69    /// No fim, fecha o form `from` (em vez de só esconder).
70    close_from: bool,
71}
72
73impl Ui {
74    /// Troca `from` por `to` com uma transição: `to` fica visível e entra, `from` sai e no
75    /// fim fica invisível. Qualquer um dos dois pode faltar (só entrar, só sair).
76    pub fn transition(&mut self, from: Option<ComponentId>, to: Option<ComponentId>, kind: Transition, duration_ms: f32) {
77        self.start_transition(from, to, kind, duration_ms, false);
78    }
79
80    pub(crate) fn start_transition(&mut self, from: Option<ComponentId>, to: Option<ComponentId>, kind: Transition, duration_ms: f32, close_from: bool) {
81        // Uma transição em andamento nos mesmos controles termina na hora.
82        let pending: Vec<Running> = self
83            .transitions
84            .iter()
85            .filter(|r| [r.from, r.to].iter().flatten().any(|c| Some(*c) == from || Some(*c) == to))
86            .copied()
87            .collect();
88        for r in pending {
89            self.finish_transition(r);
90        }
91        self.transitions.retain(|r| ![r.from, r.to].iter().flatten().any(|c| Some(*c) == from || Some(*c) == to));
92        if let Some(t) = to {
93            if let Some(cb) = self.control_mut(t) {
94                cb.set_visible(true);
95            }
96        }
97        let opacity = |ui: &Ui, id: Option<ComponentId>| id.and_then(|c| ui.control(c)).map_or(1.0, |cb| cb.opacity());
98        let running = Running {
99            from,
100            to,
101            kind,
102            start: self.time,
103            duration: (duration_ms.max(0.0) / 1000.0) as f64,
104            from_opacity: opacity(self, from),
105            to_opacity: opacity(self, to),
106            close_from,
107        };
108        if kind == Transition::None || running.duration <= 0.0 {
109            self.finish_transition(running);
110            return;
111        }
112        self.apply_transition(&running, 0.0);
113        self.transitions.push(running);
114        self.invalidate();
115        self.request_repaint();
116    }
117
118    /// O controle está entrando (uma transição de entrada em andamento).
119    pub(crate) fn transitions_entering(&self, id: ComponentId) -> bool {
120        self.transitions.iter().any(|r| r.to == Some(id))
121    }
122
123    /// Há transição em andamento com este controle.
124    pub fn in_transition(&self, id: ComponentId) -> bool {
125        self.transitions.iter().any(|r| r.from == Some(id) || r.to == Some(id))
126    }
127
128    pub(crate) fn tick_transitions(&mut self) {
129        if self.transitions.is_empty() {
130            return;
131        }
132        let now = self.time;
133        let running = std::mem::take(&mut self.transitions);
134        let mut keep = Vec::new();
135        for r in running {
136            let t = ((now - r.start) / r.duration).clamp(0.0, 1.0) as f32;
137            if t >= 1.0 {
138                self.finish_transition(r);
139            } else {
140                self.apply_transition(&r, crate::anim::Easing::OutCubic.apply(t));
141                keep.push(r);
142            }
143        }
144        // Transições que começaram durante o fim de outra (um form fechando abre outro).
145        keep.append(&mut self.transitions);
146        self.transitions = keep;
147        // Sem `request_repaint`: o `apply_transition` marca só o lugar ou a transparência de
148        // quem anda (a janela inteira refazia as camadas guardadas a cada quadro, e as páginas
149        // eram repintadas controle por controle; medido em `medicoes/transicoes.json`).
150    }
151
152    /// O deslocamento de quem entra no começo (o tamanho do controle na direção).
153    fn slide_vector(&self, kind: Transition, id: ComponentId) -> PointF {
154        let size = self.control(id).map(|cb| cb.bounds().size()).unwrap_or_default();
155        match kind {
156            Transition::SlideLeft => PointF::new(size.width, 0.0),
157            Transition::SlideRight => PointF::new(-size.width, 0.0),
158            Transition::SlideUp => PointF::new(0.0, size.height),
159            Transition::SlideDown => PointF::new(0.0, -size.height),
160            _ => PointF::ZERO,
161        }
162    }
163
164    fn apply_transition(&mut self, r: &Running, p: f32) {
165        match r.kind {
166            Transition::Fade => {
167                if let Some(cb) = r.to.and_then(|c| self.cb_mut(c)) {
168                    cb.set_opacity(r.to_opacity * p);
169                }
170                if let Some(cb) = r.from.and_then(|c| self.cb_mut(c)) {
171                    cb.set_opacity(r.from_opacity * (1.0 - p));
172                }
173            }
174            Transition::None => return,
175            kind => {
176                if let Some(to) = r.to {
177                    let v = self.slide_vector(kind, to);
178                    if let Some(cb) = self.cb_mut(to) {
179                        cb.set_translate(PointF::new(v.x * (1.0 - p), v.y * (1.0 - p)));
180                    }
181                }
182                if let Some(from) = r.from {
183                    let v = self.slide_vector(kind, from);
184                    if let Some(cb) = self.cb_mut(from) {
185                        cb.set_translate(PointF::new(-v.x * p, -v.y * p));
186                    }
187                }
188            }
189        }
190        // Só o lugar ou a transparência mudou (por isso o `cb_mut`, e não o `control_mut`, que
191        // marcaria o desenho de dentro e o layout do form): a área antiga e a nova são
192        // repintadas, e a camada guardada de cada um (veja `paint_node`) continua valendo.
193        for id in [r.from, r.to].into_iter().flatten() {
194            self.damage_placement(id);
195        }
196    }
197
198    fn finish_transition(&mut self, r: Running) {
199        // As imagens das duas páginas não valem mais (a pintura do fim é inteira, e a página
200        // que sai some): saem do renderizador na próxima pintura, em vez de ocupar memória
201        // até passar do limite (`image_cache.layers_mb`).
202        for id in [r.from, r.to].into_iter().flatten() {
203            if let Some(key) = self.entry(id).and_then(|e| e.visual.borrow_mut().layer_key.take()) {
204                self.dead_layers.get_mut().push(key);
205            }
206        }
207        if let Some(cb) = r.to.and_then(|c| self.control_mut(c)) {
208            cb.set_translate(PointF::ZERO);
209            cb.set_opacity(r.to_opacity);
210            cb.set_visible(true);
211        }
212        if let Some(from) = r.from {
213            if let Some(cb) = self.control_mut(from) {
214                cb.set_translate(PointF::ZERO);
215                cb.set_opacity(r.from_opacity);
216            }
217            if r.close_from {
218                self.closing_now = Some(from);
219                self.close(from);
220                self.closing_now = None;
221            } else if let Some(cb) = self.control_mut(from) {
222                cb.set_visible(false);
223            }
224        }
225        self.invalidate();
226        self.request_repaint();
227    }
228}