Skip to main content

aylis_core/
component.rs

1//! O modelo de componentes: [`Component`] e [`ControlBase`] (os dados
2//! comuns de todo controle visual).
3
4use std::any::Any;
5use std::fmt;
6
7use crate::align::{Align, Anchors, SelfAlign};
8use crate::canvas::Canvas;
9use crate::error::{Error, Result};
10use crate::event::{EventArgs, EventCtx, KeyEvent, PointerEvent, WheelEvent};
11use crate::geometry::{Bounds, PointF, RectF, SizeF};
12use crate::paint::PaintCtx;
13use crate::platform::CursorShape;
14use crate::prop::{PropInfo, PropKind, PropValue};
15
16/// Identificador de um componente dentro do [`Ui`](crate::Ui).
17///
18/// É "geracional": depois que o componente é liberado, o id antigo nunca mais aponta
19/// para nada (as consultas devolvem `None` em vez de acessar memória inválida).
20#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
21pub struct ComponentId {
22    pub(crate) index: u32,
23    pub(crate) generation: u32,
24}
25
26impl ComponentId {
27    /// Número estável para identificar o componente fora do Rust (C ABI, protocolo).
28    pub fn to_u64(self) -> u64 {
29        (self.generation as u64) << 32 | self.index as u64
30    }
31
32    /// O inverso de [`to_u64`](Self::to_u64). O `Ui` recusa ids de componentes liberados.
33    pub fn from_u64(value: u64) -> Self {
34        Self { index: value as u32, generation: (value >> 32) as u32 }
35    }
36}
37
38impl fmt::Display for ComponentId {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        write!(f, "#{}v{}", self.index, self.generation)
41    }
42}
43
44/// Estado visual de um controle, usado pelo tema e pela pintura.
45#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
46pub struct ControlState {
47    pub hover: bool,
48    pub pressed: bool,
49    pub focused: bool,
50    pub checked: bool,
51    /// Calculado na pintura: o controle ou algum ancestral está com `enabled = false`.
52    pub disabled: bool,
53}
54
55/// Componente: a base de tudo que vive no [`Ui`](crate::Ui), visual ou não.
56///
57/// Todos os métodos, exceto [`class_name`](Component::class_name), têm implementação
58/// padrão — sobrescreva só o que precisar.
59///
60/// ## Controle visual
61/// Um componente é um **controle** quando devolve um [`ControlBase`] em
62/// [`control`](Component::control) / [`control_mut`](Component::control_mut).
63///
64/// ## "Herança" por composição
65/// Para criar um componente a partir de outro, guarde o componente base num campo e
66/// devolva-o em [`inner`](Component::inner) / [`inner_mut`](Component::inner_mut).
67/// Tudo que você não sobrescrever (pintura, eventos, propriedades, `ControlBase`) é
68/// repassado automaticamente para ele. Para chamar o comportamento original dentro de
69/// um método sobrescrito (o `inherited`), chame o método no campo:
70///
71/// ```ignore
72/// struct GlowButton { base: Button }
73///
74/// impl Component for GlowButton {
75///     fn class_name(&self) -> &'static str { "GlowButton" }
76///     fn inner(&self) -> Option<&dyn Component> { Some(&self.base) }
77///     fn inner_mut(&mut self) -> Option<&mut dyn Component> { Some(&mut self.base) }
78///
79///     fn paint(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx) {
80///         self.base.paint(canvas, ctx); // inherited Paint
81///         // ...desenho extra
82///     }
83/// }
84/// ```
85pub trait Component: Any {
86    /// Nome da classe ("Button", "ClientDataSet"...). É o nome usado no registro de
87    /// classes, nos arquivos de layout e nos estilos do tema.
88    fn class_name(&self) -> &'static str;
89
90    /// O componente "pai" na composição, se houver (o equivalente ao ancestral).
91    fn inner(&self) -> Option<&dyn Component> {
92        None
93    }
94
95    fn inner_mut(&mut self) -> Option<&mut dyn Component> {
96        None
97    }
98
99    /// Cadeia de classes, da mais derivada para a base. Usada pelo tema: um
100    /// `GlowButton` sem estilo próprio usa o estilo de `Button`.
101    fn class_chain(&self, out: &mut Vec<&'static str>) {
102        out.push(self.class_name());
103        if let Some(inner) = self.inner() {
104            inner.class_chain(out);
105        }
106    }
107
108    /// Dados de controle visual. Componentes não visuais devolvem `None`.
109    fn control(&self) -> Option<&ControlBase> {
110        self.inner().and_then(|i| i.control())
111    }
112
113    fn control_mut(&mut self) -> Option<&mut ControlBase> {
114        self.inner_mut().and_then(|i| i.control_mut())
115    }
116
117    /// Propriedades publicadas **desta camada**. As do componente base (`inner`) e as do
118    /// [`ControlBase`] são incluídas automaticamente pelo `Ui`.
119    fn props(&self) -> &'static [PropInfo] {
120        &[]
121    }
122
123    /// O evento padrão: o duplo clique no designer cria o handler dele e abre o código.
124    /// `None`: a IDE escolhe pelo nome (o `on_change` da classe, o
125    /// `on_timer`... ou o `on_click`).
126    fn default_event(&self) -> Option<&'static str> {
127        self.inner().and_then(|c| c.default_event())
128    }
129
130    /// Lê uma propriedade desta camada; `None` se não for dela.
131    fn get_prop(&self, _name: &str) -> Option<PropValue> {
132        None
133    }
134
135    /// Grava uma propriedade desta camada. Devolva [`Error::UnknownProperty`] se não for
136    /// dela (o `Ui` então tenta a camada base).
137    fn set_prop(&mut self, name: &str, _value: PropValue) -> Result<()> {
138        Err(Error::UnknownProperty(name.to_string()))
139    }
140
141    /// Avisa que um componente foi liberado (como `Notification(AComponent, opRemove)`).
142    /// Quem guarda referências para outros componentes deve limpá-las aqui.
143    fn notification(&mut self, freed: ComponentId) {
144        if let Some(inner) = self.inner_mut() {
145            inner.notification(freed);
146        }
147    }
148
149    /// Pinta o controle. O canvas já está na origem do controle; `ctx.rect` é a área dele.
150    fn paint(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
151        if let Some(inner) = self.inner() {
152            inner.paint(canvas, ctx);
153        }
154    }
155
156    /// O controle não tem fundo (um texto, uma caixa de seleção, um medidor): com o `fill`
157    /// próprio, o `Ui` pinta o fundo dele inteiro. Os que têm
158    /// fundo usam o `fill` no desenho deles.
159    fn transparent_background(&self) -> bool {
160        self.inner().is_some_and(|i| i.transparent_background())
161    }
162
163    /// O `paint` deste estilo cobre o retângulo inteiro do controle com cor opaca (um painel
164    /// de fundo sólido sem cantos arredondados, um form). Com `true`, o que fica inteiro atrás
165    /// dele (um irmão pintado antes) não é pintado: um medidor animando embaixo de uma tela que
166    /// o cobre não pede quadros. Na dúvida, `false` (o padrão): só se perde a economia.
167    fn opaque(&self, style: &crate::theme::ResolvedStyle) -> bool {
168        self.inner().is_some_and(|i| i.opaque(style))
169    }
170
171    /// Pinta por cima dos filhos (bordas, anel de foco...).
172    fn paint_after(&self, canvas: &mut dyn Canvas, ctx: &PaintCtx<'_>) {
173        if let Some(inner) = self.inner() {
174            inner.paint_after(canvas, ctx);
175        }
176    }
177
178    /// A pintura (`paint` e `paint_after`) só lê: sem efeito colateral (nada de evento, de
179    /// cache que avança, de quadro de vídeo consumido) e o mesmo desenho para o mesmo estado,
180    /// estilo e propriedades. Com `true`, o `Ui` pode ensaiar o desenho fora do quadro e não
181    /// repintar o controle quando ele não mudou (o fundo de um contêiner quando o mouse entra
182    /// nele). Os contêineres simples dizem `true`; o padrão é `false`, mesmo com `inner`
183    /// (quem herda de um contêiner e pinta por cima precisa dizer de novo).
184    fn paint_is_pure(&self) -> bool {
185        false
186    }
187
188    /// Um componente provedor (item 25): o que ele oferece aos componentes que o apontam pela
189    /// propriedade `provider` (veja [`crate::providers`]). O padrão: nada.
190    fn provided(&self) -> Option<crate::providers::Provided<'_>> {
191        None
192    }
193
194    /// O tamanho real (`bounds`) mudou depois de um layout (como o `Resize`).
195    fn resized(&mut self, ctx: &mut EventCtx<'_>) {
196        if let Some(inner) = self.inner_mut() {
197            inner.resized(ctx);
198        }
199    }
200
201    /// Clique (como `Click`). O padrão dispara o evento `on_click`.
202    fn click(&mut self, ctx: &mut EventCtx<'_>) {
203        match self.inner_mut() {
204            Some(inner) => inner.click(ctx),
205            None => ctx.fire("on_click", EventArgs::None),
206        }
207    }
208
209    fn pointer_down(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
210        if let Some(inner) = self.inner_mut() {
211            inner.pointer_down(ctx, event);
212        }
213    }
214
215    fn pointer_up(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
216        if let Some(inner) = self.inner_mut() {
217            inner.pointer_up(ctx, event);
218        }
219    }
220
221    fn pointer_move(&mut self, ctx: &mut EventCtx<'_>, event: &PointerEvent) {
222        if let Some(inner) = self.inner_mut() {
223            inner.pointer_move(ctx, event);
224        }
225    }
226
227    fn pointer_enter(&mut self, ctx: &mut EventCtx<'_>) {
228        if let Some(inner) = self.inner_mut() {
229            inner.pointer_enter(ctx);
230        }
231    }
232
233    fn pointer_leave(&mut self, ctx: &mut EventCtx<'_>) {
234        if let Some(inner) = self.inner_mut() {
235            inner.pointer_leave(ctx);
236        }
237    }
238
239    fn wheel(&mut self, ctx: &mut EventCtx<'_>, event: &WheelEvent) {
240        if let Some(inner) = self.inner_mut() {
241            inner.wheel(ctx, event);
242        }
243    }
244
245    /// Pinça/giro de dois dedos. Marque como tratado (`ctx.set_handled()`) para não subir
246    /// para os pais.
247    fn gesture(&mut self, ctx: &mut EventCtx<'_>, event: &crate::event::GestureEvent) {
248        if let Some(inner) = self.inner_mut() {
249            inner.gesture(ctx, event);
250        }
251    }
252
253    /// Um deslizar do dedo (o `Carousel` troca de item, o `TabControl` de página). Marque
254    /// como tratado (`ctx.set_handled()`) para não subir para os pais.
255    fn swipe(&mut self, ctx: &mut EventCtx<'_>, event: &crate::event::SwipeEvent) {
256        if let Some(inner) = self.inner_mut() {
257            inner.swipe(ctx, event);
258        }
259    }
260
261    /// O dedo que arrastava (rolando) saiu da tela: quem segue o arrasto por dentro (a linha da
262    /// lista deslizada para mostrar as ações) fecha ou fica aberto. Vai ao controle tocado e a
263    /// todos os pais.
264    fn touch_end(&mut self, ctx: &mut EventCtx<'_>) {
265        if let Some(inner) = self.inner_mut() {
266            inner.touch_end(ctx);
267        }
268    }
269
270    /// Um deslizar que começou na borda do form (`event.start` nas coordenadas do form) e que
271    /// ninguém tratou: a `NavigationDrawer` abre. `true` se tratou.
272    fn edge_swipe(&mut self, ctx: &mut EventCtx<'_>, event: &crate::event::SwipeEvent) -> bool {
273        match self.inner_mut() {
274            Some(inner) => inner.edge_swipe(ctx, event),
275            None => false,
276        }
277    }
278
279    /// O menu de contexto próprio do controle (o de texto do `Edit` e do `Memo`: Recortar,
280    /// Copiar, Colar, Selecionar tudo). O `Ui` chama no botão direito e no toque longo
281    /// (`touch`), subindo do controle tocado pelos pais, só quando nem ele nem um pai tem
282    /// `popup_menu` (o menu do app vence). `at` é o ponto local. `true` se abriu um menu.
283    fn context_menu(&mut self, ctx: &mut EventCtx<'_>, at: PointF, touch: bool) -> bool {
284        match self.inner_mut() {
285            Some(inner) => inner.context_menu(ctx, at, touch),
286            None => false,
287        }
288    }
289
290    fn key_down(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
291        if let Some(inner) = self.inner_mut() {
292            inner.key_down(ctx, event);
293        }
294    }
295
296    fn key_up(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
297        if let Some(inner) = self.inner_mut() {
298            inner.key_up(ctx, event);
299        }
300    }
301
302    /// Tecla de atalho que ninguém tratou (como o atalho de um item de menu): o `Ui`
303    /// oferece a todos os componentes do form. Marque como tratado
304    /// ([`EventCtx::set_handled`]) se for sua.
305    fn shortcut(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
306        if let Some(inner) = self.inner_mut() {
307            inner.shortcut(ctx, event);
308        }
309    }
310
311    /// Os ganchos raros (barra de tarefas, bandeja, vista nativa, conector, arquivos soltos),
312    /// se este componente usa: devolva `Some(self)` e implemente [`PlatformHooks`].
313    fn platform_hooks(&self) -> Option<&dyn PlatformHooks> {
314        self.inner().and_then(|i| i.platform_hooks())
315    }
316
317    fn platform_hooks_mut(&mut self) -> Option<&mut dyn PlatformHooks> {
318        self.inner_mut().and_then(|i| i.platform_hooks_mut())
319    }
320
321    /// Os ganchos do designer (pontos que se arrastam dentro do controle), se este
322    /// componente usa: devolva `Some(self)` e implemente [`DesignHooks`].
323    fn design_hooks(&self) -> Option<&dyn DesignHooks> {
324        self.inner().and_then(|i| i.design_hooks())
325    }
326
327    fn design_hooks_mut(&mut self) -> Option<&mut dyn DesignHooks> {
328        self.inner_mut().and_then(|i| i.design_hooks_mut())
329    }
330
331    /// O ponto (coordenadas do controle, já sem a rotação) acerta o controle? Padrão: o
332    /// retângulo inteiro. As formas (círculo, estrela, linha...) respondem só na figura.
333    fn contains_point(&self, local: PointF, size: SizeF) -> bool {
334        self.inner().map_or(true, |i| i.contains_point(local, size))
335    }
336
337    /// Quanto o controle recebe o mouse além do próprio retângulo (as alças de uma moldura
338    /// desenhadas do lado de fora). Fora do retângulo, quem decide é o
339    /// [`contains_point`](Component::contains_point) (que recebe o ponto fora dele). Padrão: 0.
340    fn hit_slop(&self) -> f32 {
341        self.inner().map_or(0.0, |i| i.hit_slop())
342    }
343
344    /// Em que eixos o conteúdo rola (horizontal, vertical): o [`Ui::reveal`](crate::Ui::reveal)
345    /// rola estes contêineres para mostrar um controle de dentro (o campo sob o teclado).
346    fn scroll_axes(&self) -> (bool, bool) {
347        self.inner().map_or((false, false), |i| i.scroll_axes())
348    }
349
350    /// O componente edita texto. No celular, quando ele tem o foco a plataforma abre o
351    /// teclado virtual.
352    /// O que vai num arrasto que começa neste controle sem `drag_data` nem handler: as listas
353    /// e as grades mandam o item (o texto, a chave do registro) e o rótulo. `None`: nada.
354    fn drag_item(&self, _ui: &crate::Ui) -> Option<(String, String)> {
355        None
356    }
357
358    /// O que acompanha o cursor num arrasto, quando este componente é o `drag_image` de um
359    /// controle (o `DragImage`); `source` é o controle arrastado. `None`: nada.
360    fn drag_visual(&self, _ui: &crate::Ui, _source: ComponentId) -> Option<crate::DragVisual> {
361        None
362    }
363
364    /// O próprio componente recebe este arrasto (sem `accepts_drops` nem eventos): as abas
365    /// que passam de uma faixa para outra. Vale também quando ele é a origem (a aba que volta
366    /// para a faixa de onde saiu). Com `true`, recebe [`drop_hover`](Self::drop_hover),
367    /// [`drop_leave`](Self::drop_leave) e [`drop_receive`](Self::drop_receive).
368    fn drop_accepts(&self, _ui: &crate::Ui, _id: ComponentId, _data: &str) -> bool {
369        false
370    }
371
372    /// O arrasto aceito por [`drop_accepts`](Self::drop_accepts) está sobre o componente, no
373    /// ponto `position` (coordenadas dele); chamado a cada movimento.
374    fn drop_hover(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
375
376    /// O arrasto saiu de cima do componente (ou foi cancelado).
377    fn drop_leave(&mut self, _ctx: &mut EventCtx<'_>) {}
378
379    /// Soltou o arrasto aceito sobre o componente, em `position` (coordenadas dele).
380    fn drop_receive(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
381
382    /// O arrasto que começou neste componente acabou (`on_drag_end` também dispara).
383    fn drag_ended(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _end: crate::DragEnd) {}
384
385    fn accepts_text(&self) -> bool {
386        self.inner().is_some_and(|i| i.accepts_text())
387    }
388
389    /// O controle usa a tecla (o Enter de um Memo, as setas de uma lista): ela não vira o
390    /// Tab do form (`tab_keys`).
391    fn captures_key(&self, event: &KeyEvent) -> bool {
392        self.inner().is_some_and(|i| i.captures_key(event))
393    }
394
395    /// A legenda com o `&` da letra do atalho (`"&Salvar"`: Alt+S), para os controles que
396    /// aceitam (botões, caixas de marcar, rótulos, grupos).
397    fn mnemonic_text(&self) -> Option<&str> {
398        self.inner().and_then(|i| i.mnemonic_text())
399    }
400
401    /// No Alt+letra, o foco vai para o primeiro filho (um grupo) em vez de clicar.
402    fn mnemonic_focuses_child(&self) -> bool {
403        self.inner().is_some_and(|i| i.mnemonic_focuses_child())
404    }
405
406    /// Texto digitado (já com acentos e IME resolvidos pela plataforma).
407    fn text_input(&mut self, ctx: &mut EventCtx<'_>, text: &str) {
408        if let Some(inner) = self.inner_mut() {
409            inner.text_input(ctx, text);
410        }
411    }
412
413    fn focus_enter(&mut self, ctx: &mut EventCtx<'_>) {
414        if let Some(inner) = self.inner_mut() {
415            inner.focus_enter(ctx);
416        }
417    }
418
419    fn focus_exit(&mut self, ctx: &mut EventCtx<'_>) {
420        if let Some(inner) = self.inner_mut() {
421            inner.focus_exit(ctx);
422        }
423    }
424
425    /// Uma propriedade publicada mudou por nome ([`Ui::set_prop`](crate::Ui::set_prop): JSON,
426    /// Object Inspector, protocolo). É o lugar dos efeitos colaterais da mudança: aqui
427    /// o componente tem o `Ui` (por exemplo, o TabControl mostra a aba nova).
428    fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
429        if let Some(inner) = self.inner_mut() {
430            inner.property_changed(ctx, name);
431        }
432    }
433
434    /// A marca do controle agora (`checked`), lida pelo núcleo na pintura: o tema reflete a
435    /// marca mesmo quando o campo muda direto, sem o `set_prop` (C02 do Tabernáculo).
436    fn checked_state(&self) -> Option<bool> {
437        self.inner().and_then(|i| i.checked_state())
438    }
439
440    /// Os argumentos do `on_change` quando a propriedade de valor `name` muda pelo código
441    /// ([`Ui::set_prop`](crate::Ui::set_prop): o acesso tipado, o protocolo);
442    /// `value` é o valor novo. O padrão é `EventArgs::Value(value)`: o controle que dispara
443    /// outro argumento quando o usuário muda (o texto do item, numa ComboBox) devolve o mesmo
444    /// aqui, e `None` não dispara. Quais propriedades contam: [`is_value_property`].
445
446    fn change_args(&self, name: &str, value: &PropValue) -> Option<EventArgs> {
447        match self.inner() {
448            Some(inner) => inner.change_args(name, value),
449            None => Some(EventArgs::Value(value.clone())),
450        }
451    }
452
453    /// A propriedade `name` só muda a pintura (o valor de um medidor, o giro de um 3D): o
454    /// `set_prop` dela repinta sem refazer o layout da tela. As do controle (cores, opacidade,
455    /// giro, deslocamento, cursor, dica) o `Ui` já conhece; aqui vão as do componente. Na
456    /// dúvida, `false` (refazer o layout nunca está errado, só custa).
457    fn paint_only_property(&self, name: &str) -> bool {
458        self.inner().is_some_and(|inner| inner.paint_only_property(name))
459    }
460
461    /// Intervalo do timer deste componente, em segundos (`None` = parado). O `Ui` dispara
462    /// `on_timer` a cada intervalo; ver [`Ui::sync_timer`](crate::Ui::sync_timer).
463    fn timer_interval(&self) -> Option<f64> {
464        self.inner().and_then(|i| i.timer_interval())
465    }
466
467    /// Quanto o timer pode atrasar ([`TimerPrecision`](crate::TimerPrecision)).
468    fn timer_precision(&self) -> crate::TimerPrecision {
469        self.inner().map(|i| i.timer_precision()).unwrap_or_default()
470    }
471
472    /// O timer conta numa thread própria (não espera o laço da tela, que pode estar
473    /// ocupado); o `on_timer` chega à tela pelo [`Poster`](crate::Poster).
474    fn timer_background(&self) -> bool {
475        self.inner().is_some_and(|i| i.timer_background())
476    }
477
478    /// Quanto o disparo que vem a seguir atrasou, em segundos (antes de [`timer`](Component::timer)).
479    fn timer_late(&mut self, late: f64) {
480        if let Some(inner) = self.inner_mut() {
481            inner.timer_late(late);
482        }
483    }
484
485    /// Um quadro vai ser pintado (pedido com [`Ui::request_frames`](crate::Ui::request_frames)):
486    /// chamado antes da pintura, com o tempo do quadro em `ctx.ui.time()`, para um movimento
487    /// que acompanha o monitor (a rolagem com deslize). Devolve se quer o próximo quadro.
488    fn frame(&mut self, ctx: &mut EventCtx<'_>) -> bool {
489        self.inner_mut().is_some_and(|inner| inner.frame(ctx))
490    }
491
492    /// O timer venceu (ver [`timer_interval`](Component::timer_interval)). O padrão dispara o
493    /// evento `on_timer`.
494    fn timer(&mut self, ctx: &mut EventCtx<'_>) {
495        match self.inner_mut() {
496            Some(inner) => inner.timer(ctx),
497            None => ctx.fire("on_timer", EventArgs::None),
498        }
499    }
500
501    /// Organiza os filhos com `align = None` (grade, fluxo...): recebe a área livre (já
502    /// sem o padding e sem o que os filhos encaixados ocuparam) e o tamanho pedido e as
503    /// margens de cada filho; devolve o retângulo de cada um, na mesma ordem. `None` (o
504    /// padrão) = posição livre.
505    fn arrange(&self, area: RectF, children: &[ArrangeItem]) -> Option<Vec<RectF>> {
506        self.inner().and_then(|i| i.arrange(area, children))
507    }
508
509    /// A linha de base do texto do controle, em pixels do topo dele, na altura `height` (para
510    /// o `FlowLayout` com `baseline` alinhar os textos de uma fileira; L12 do Tabernáculo).
511    /// `None` (o padrão): o controle não tem texto, e fica pelo fundo.
512    fn baseline(&self, ui: &crate::Ui, id: ComponentId, height: f32) -> Option<f32> {
513        self.inner().and_then(|i| i.baseline(ui, id, height))
514    }
515
516    /// O vão entre os filhos encaixados (Top, Left...), em pixels: o `gap` do `Layout` e do
517    /// `Panel` (o `gap` do CSS; L05 do Tabernáculo). Padrão: 0.
518    fn dock_gap(&self) -> f32 {
519        self.inner().map_or(0.0, |i| i.dock_gap())
520    }
521
522    /// A altura que o conteúdo pede na largura `width` (o texto de um Label quebrado nela),
523    /// para o `auto_size`. `None` (o padrão): o controle não mede o conteúdo (um contêiner
524    /// com `auto_size` fica da altura dos filhos encaixados em cima e embaixo).
525    fn auto_height(&self, ui: &crate::Ui, id: ComponentId, width: f32) -> Option<f32> {
526        self.inner().and_then(|i| i.auto_height(ui, id, width))
527    }
528
529    /// A largura que o conteúdo pede (o texto de um Label sem quebra), para o `auto_size` de
530    /// quem não é esticado na largura (`align` left, right ou none). `None` (o padrão): a
531    /// largura fica a pedida.
532    fn auto_width(&self, ui: &crate::Ui, id: ComponentId) -> Option<f32> {
533        self.inner().and_then(|i| i.auto_width(ui, id))
534    }
535
536    /// Uma camada aberta por outro (a lista de um ComboBox, as sugestões de um campo), posta
537    /// direto no form: o mouse apertado fora dela e fora de quem a abriu ([`dies_with`]) a
538    /// libera, mesmo que o clique caia onde não recebe foco (o fundo da tela, um rótulo). O
539    /// dono fica sabendo pelo [`notification`](Component::notification). Padrão: `false`.
540    ///
541    /// [`dies_with`]: Component::dies_with
542    fn closes_on_outside_press(&self) -> bool {
543        false
544    }
545
546    /// O clique fora fechou a camada ([`closes_on_outside_press`]): `true` se ela mesma se
547    /// escondeu e deve continuar existindo (o `Popover`, desenhado no form com os filhos);
548    /// `false` (o padrão), o núcleo a libera.
549    ///
550    /// [`closes_on_outside_press`]: Component::closes_on_outside_press
551    fn dismissed(&mut self, ctx: &mut EventCtx<'_>) -> bool {
552        let _ = ctx;
553        false
554    }
555
556    /// Este componente só vive enquanto `dies_with` existir: liberar aquele libera este
557    /// também. É o que a lista aberta de um ComboBox (uma camada sobre o form) usa: se o
558    /// ComboBox some (a tela foi refeita), a lista não fica órfã na tela.
559    fn dies_with(&self) -> Option<ComponentId> {
560        self.inner().and_then(|i| i.dies_with())
561    }
562
563    /// Os itens que o controle desenha sozinho (abas, linhas, itens de menu, células), para
564    /// leitores de tela, automação e testes ([`crate::automation`]). `id` é este controle.
565    fn access_items(&self, ui: &crate::Ui, id: ComponentId) -> Vec<crate::automation::AccessItem> {
566        self.inner().map_or_else(Vec::new, |i| i.access_items(ui, id))
567    }
568
569    /// Clica ou seleciona o item `index` de [`access_items`](Self::access_items). Devolve
570    /// `false` se não fez nada.
571    fn access_action(&mut self, ctx: &mut EventCtx<'_>, index: usize, action: crate::automation::ItemAction) -> bool {
572        self.inner_mut().is_some_and(|i| i.access_action(ctx, index, action))
573    }
574
575    /// Prende o controle a um irmão (mesmo pai): devolve o alvo e o ponto dele onde o
576    /// centro deste controle fica (`0..1` na largura e na altura: `(1, 0)` é o canto de
577    /// cima à direita). É o que deixa um `Badge` no canto de um botão.
578    fn attach(&self) -> Option<(ComponentId, f32, f32)> {
579        self.inner().and_then(|i| i.attach())
580    }
581
582    /// Dados extras de um evento que está sendo entregue (chave e texto), para quem recebe
583    /// os eventos fora do Rust: o protocolo os manda no `info` do evento (o `on_message` do
584    /// WebView manda a URL de quem mandou).
585    fn event_info(&self, event: &str) -> Vec<(&'static str, String)> {
586        self.inner().map(|i| i.event_info(event)).unwrap_or_default()
587    }
588
589    /// Mensagem enviada por outro componente com [`Ui::send_message`](crate::Ui::send_message).
590    /// O tipo da mensagem é livre: cada camada
591    /// (por exemplo a de dados) define as suas e o componente faz `downcast_ref`.
592    fn message(&mut self, ctx: &mut EventCtx<'_>, message: &dyn Any) {
593        if let Some(inner) = self.inner_mut() {
594            inner.message(ctx, message);
595        }
596    }
597
598    /// Os métodos que [`invoke`](Component::invoke) atende, com os tipos (o catálogo do
599    /// acesso tipado nas linguagens: `frmPaint.pcDesenho.Undo`).
600    fn methods(&self) -> &'static [MethodInfo] {
601        &[]
602    }
603
604    /// Um método pelo nome ([`Ui::invoke`](crate::Ui::invoke), o comando `invoke` do
605    /// protocolo): o que não é propriedade, como `undo`, `clear` ou `save`. Funciona igual
606    /// em Rust e nas outras linguagens (pelo protocolo). Devolve o resultado ou o erro.
607    fn invoke(&mut self, ctx: &mut EventCtx<'_>, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
608        let class = self.class_name();
609        match self.inner_mut() {
610            Some(inner) => inner.invoke(ctx, method, args),
611            None => Err(format!("{class} não tem o método '{method}'")),
612        }
613    }
614
615}
616
617/// Os ganchos que só uns poucos componentes usam: fora do [`Component`], para a lista de
618/// métodos de um controle comum ficar curta. O componente que usa devolve `Some(self)` em
619/// [`Component::platform_hooks`] e [`Component::platform_hooks_mut`].
620pub trait PlatformHooks {
621    /// O que este componente quer no botão da barra de tarefas (o `Taskbar`).
622    fn taskbar(&self) -> Option<crate::taskbar::TaskbarSpec> {
623        None
624    }
625
626    /// Ícone na bandeja do sistema que este componente quer mostrar (o `TrayIcon`).
627    fn tray(&self) -> Option<crate::tray::TraySpec> {
628        None
629    }
630
631    /// Vista nativa que a plataforma põe por cima do controle (um navegador embutido...).
632    /// O controle continua sendo pintado por baixo (o que aparece onde a plataforma não
633    /// tem a vista, como no designer).
634    fn native_view(&self) -> Option<NativeView> {
635        None
636    }
637
638    /// Comandos pendentes para a vista nativa (a plataforma pega e executa).
639    fn take_native_commands(&self) -> Vec<NativeCommand> {
640        Vec::new()
641    }
642
643    /// Um conector (cano, fio) preso a dois irmãos: os pontos de ligação deles (`0..1` na
644    /// largura e na altura). O layout põe o conector em volta do caminho entre os dois; ele
645    /// segue os componentes quando eles mudam de lugar.
646    fn connection(&self) -> Option<Connection> {
647        None
648    }
649
650    /// Arquivos soltos sobre o controle (arrastados do sistema). Devolve `true` se aceitou
651    /// (senão eles vão para o pai).
652    fn files_dropped(&mut self, _ctx: &mut EventCtx<'_>, _paths: &[String]) -> bool {
653        false
654    }
655
656    /// Arquivos do sistema passando por cima (`Some`, com os caminhos) ou saindo, soltos ou
657    /// cancelados (`None`). Devolve `true` se o controle os receberia.
658    fn files_hovering(&mut self, _ctx: &mut EventCtx<'_>, _paths: Option<&[String]>) -> bool {
659        false
660    }
661}
662
663/// Os ganchos do designer: pontos que se arrastam dentro do controle (o separador das
664/// colunas de uma grade). O componente que usa devolve `Some(self)` em
665/// [`Component::design_hooks`] e [`Component::design_hooks_mut`].
666pub trait DesignHooks {
667    /// Um ponto que se arrasta dentro do controle, em coordenadas do controle. Devolve o
668    /// índice do ponto.
669    fn design_grip(&self, _local: PointF) -> Option<usize> {
670        None
671    }
672
673    /// O ponto `grip` foi arrastado `delta` desde o começo (`begin` no primeiro movimento).
674    /// Devolve a propriedade a gravar (o designer grava, com o desfazer): o componente
675    /// (`None` = este), o nome e o valor.
676    fn design_drag(&mut self, _grip: usize, _delta: PointF, _begin: bool) -> Option<(Option<ComponentId>, &'static str, PropValue)> {
677        None
678    }
679}
680
681/// Um filho para [`Component::arrange`]: o tamanho pedido e as margens.
682#[derive(Clone, Copy, Debug, PartialEq)]
683pub struct ArrangeItem {
684    pub id: ComponentId,
685    pub size: SizeF,
686    /// Já com a escala de espaços da vista ativa.
687    pub margins: Bounds,
688    /// Quantas colunas o filho pede numa grade ([`ControlBase::column_span`]).
689    pub span: u32,
690    /// Quantas linhas ([`ControlBase::row_span`]).
691    pub row_span: u32,
692    /// O lugar fixo na grade ([`ControlBase::grid_cell`]).
693    pub cell: Option<(u32, u32)>,
694    /// A parte do espaço livre da linha que ele toma ([`ControlBase::grow`]).
695    pub grow: f32,
696    /// A linha de base do texto dele, do topo ([`Component::baseline`]); posta pelo layout.
697    pub baseline: Option<f32>,
698    /// A escala de espaços da vista ativa do form: o contêiner multiplica os espaços dele
699    /// (`gap`) por ela.
700    pub spacing: f32,
701}
702
703impl ArrangeItem {
704    /// O item de um controle.
705    pub fn of(id: ComponentId, cb: &ControlBase) -> Self {
706        ArrangeItem {
707            id,
708            size: SizeF::new(cb.width(), cb.height()),
709            margins: cb.margins(),
710            span: cb.column_span(),
711            row_span: cb.row_span(),
712            cell: cb.grid_cell(),
713            grow: cb.grow(),
714            baseline: None,
715            spacing: cb.spacing_scale(),
716        }
717    }
718}
719
720/// Uma vista nativa pedida por um componente ([`Component::native_view`]).
721#[derive(Clone, Debug, PartialEq)]
722pub enum NativeView {
723    /// Navegador embutido: abre `url` ou, sem ela, mostra `html`. Quando `generation`
724    /// muda, a plataforma carrega de novo. `navigation`: os endereços (origens ou prefixos)
725    /// para onde a página pode navegar (vazia, todos); `sandbox`: o atributo do `<iframe>`
726    /// no navegador.
727    ///
728    /// O ambiente do navegador (só ao criar a vista; o relatório do Tabernáculo, W07):
729    /// `background` é a cor antes da primeira pintura da página; `data_dir`, a pasta de dados
730    /// (vazia: a do sistema); `browser_args`, os argumentos do navegador do sistema (o WebView2).
731    Web { url: String, html: String, generation: u64, navigation: Vec<String>, sandbox: String, background: Option<crate::Color>, data_dir: String, browser_args: String },
732}
733
734/// Mensagem de uma página do navegador embutido para o app: o texto e a URL de quem mandou.
735/// A plataforma entrega ao componente com [`Ui::send_message`](crate::Ui::send_message); ele
736/// decide se a origem vale e dispara o `on_message`.
737#[derive(Clone, Debug, PartialEq)]
738pub struct WebMessage {
739    pub text: String,
740    pub url: String,
741}
742
743/// A navegação do navegador embutido para `url` é permitida pela lista (o
744/// `allowed_navigation` do WebView)? O conteúdo interno (`about:`, `data:`) sempre. Um item só
745/// com a origem (`https://site.com`) libera o site inteiro; com caminho, só o que começa por ele.
746pub fn navigation_allowed(allowed: &[String], url: &str) -> bool {
747    allowed.is_empty()
748        || url.starts_with("about:")
749        || url.starts_with("data:")
750        || allowed.iter().any(|a| {
751            let a = a.trim_end_matches('/');
752            url == a || url.starts_with(&format!("{a}/")) || url.starts_with(&format!("{a}?")) || (a.matches('/').count() <= 2 && url_origin(url) == url_origin(a))
753        })
754}
755
756/// A origem (`https://site.com:8080`) de um endereço, para comparar com uma lista.
757pub fn url_origin(url: &str) -> String {
758    let Some((scheme, rest)) = url.split_once("://") else { return url.to_string() };
759    let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
760    format!("{}://{}", scheme.to_ascii_lowercase(), host.to_ascii_lowercase())
761}
762
763/// Um método de [`Component::invoke`]: o nome, o tipo de cada argumento e o do resultado
764/// (`None`: não devolve nada que interesse).
765#[derive(Clone, Copy, Debug, PartialEq)]
766pub struct MethodInfo {
767    pub name: &'static str,
768    pub args: &'static [PropKind],
769    pub returns: Option<PropKind>,
770    /// O nome de cada argumento (`path`), que o acesso tipado gerado usa nas assinaturas;
771    /// vazio: sem nome (o gerado numera, `a1`, `a2`).
772    pub params: &'static [&'static str],
773}
774
775impl MethodInfo {
776    pub const fn new(name: &'static str, args: &'static [PropKind], returns: Option<PropKind>) -> Self {
777        Self { name, args, returns, params: &[] }
778    }
779
780    /// Os nomes dos argumentos, na ordem de `args`:
781    /// `MethodInfo::new("save_to", &[PropKind::String], None).params(&["path"])`.
782    pub const fn params(self, names: &'static [&'static str]) -> Self {
783        Self { params: names, ..self }
784    }
785}
786
787/// Comando para uma vista nativa.
788#[derive(Clone, Debug, PartialEq)]
789pub enum NativeCommand {
790    /// Roda JavaScript na página.
791    Eval(String),
792    Back,
793    Forward,
794    Reload,
795}
796
797/// Uma vista nativa a mostrar: o controle, onde (relativo ao form) e o que é.
798#[derive(Clone, Debug, PartialEq)]
799pub struct NativeViewSlot {
800    pub id: ComponentId,
801    pub rect: crate::RectF,
802    /// A parte que aparece (os pais que recortam, como uma caixa rolada, cortam o resto),
803    /// nas mesmas coordenadas de `rect`; `None`: inteira.
804    pub clip: Option<crate::RectF>,
805    pub visible: bool,
806    pub view: NativeView,
807    pub commands: Vec<NativeCommand>,
808}
809
810/// Todas as propriedades publicadas de um componente: as da classe, as das camadas de
811/// composição e as do [`ControlBase`] (sem `name` nem os eventos ligados no `Ui`).
812///
813/// Trabalha direto no componente, sem precisar do [`Ui`](crate::Ui): serve, por exemplo,
814/// para ler os valores padrão de uma instância nova da classe.
815pub fn prop_infos_of(component: &dyn Component) -> Vec<PropInfo> {
816    let mut out: Vec<PropInfo> = Vec::new();
817    // Os nomes já vistos num conjunto: procurar na lista a cada propriedade era quadrático
818    // (~90 por controle), e isso roda para cada componente no índice de referências.
819    let mut seen = std::collections::HashSet::new();
820    let mut push = |info: &PropInfo| {
821        if seen.insert(info.name) {
822            out.push(*info);
823        }
824    };
825    let mut layer = Some(component);
826    while let Some(l) = layer {
827        l.props().iter().for_each(&mut push);
828        layer = l.inner();
829    }
830    if component.control().is_some() {
831        ControlBase::PROPS.iter().for_each(&mut push);
832    }
833    out
834}
835
836/// A descrição de uma propriedade pelo nome, na mesma ordem de [`prop_infos_of`] (a camada
837/// de fora vence), sem montar a lista inteira: todo `get_prop`/`set_prop` passa por aqui.
838pub fn prop_info_of(component: &dyn Component, name: &str) -> Option<PropInfo> {
839    let mut layer = Some(component);
840    while let Some(l) = layer {
841        if let Some(info) = l.props().iter().find(|p| p.name == name) {
842            return Some(*info);
843        }
844        layer = l.inner();
845    }
846    if component.control().is_some() {
847        return ControlBase::PROPS.iter().find(|p| p.name == name).copied();
848    }
849    None
850}
851
852/// Lê uma propriedade (que não seja evento) direto no componente, procurando em todas as
853/// camadas e no [`ControlBase`].
854/// As propriedades que são "o valor" de um controle (o que o usuário muda e o `on_change`
855/// avisa), quando publicadas em `Data` (ou `Runtime`, como o `value` da ComboBox).
856pub const VALUE_PROPERTIES: [&str; 19] = [
857    "text", "checked", "value", "item_index", "selected", "date", "end_date", "time", "color", "files", "html", "index", "page", "hotkey",
858    "angle", "pressed", "position", "low", "high",
859];
860
861/// Mudar a propriedade pelo código dispara o `on_change` do controle (se ele tiver um):
862/// as de [`VALUE_PROPERTIES`] (fora das de aparência, como o `text` de um
863/// CheckBox, que é a legenda), a aba escolhida e o aberto/fechado.
864pub fn is_value_property(info: &PropInfo) -> bool {
865    match info.name {
866        "tab_index" | "expanded" => true,
867        name => matches!(info.category, "Data" | "Runtime") && VALUE_PROPERTIES.contains(&name),
868    }
869}
870
871pub fn read_prop(component: &dyn Component, name: &str) -> Option<PropValue> {
872    let mut layer = Some(component);
873    while let Some(l) = layer {
874        if let Some(v) = l.get_prop(name) {
875            return Some(v);
876        }
877        layer = l.inner();
878    }
879    component.control().and_then(|cb| cb.get_prop(name))
880}
881
882/// Referência guardada pelas âncoras: tamanho do pai e retângulo do controle no momento
883/// em que a posição foi definida.
884#[derive(Clone, Copy, Debug, PartialEq)]
885pub(crate) struct AnchorRef {
886    pub(crate) parent: SizeF,
887    pub(crate) rect: RectF,
888}
889
890/// Dados comuns de todo controle visual.
891///
892/// `left`, `top`, `width` e `height` são os valores **pedidos**. A posição e o tamanho
893/// **reais**, calculados pelo layout (Align/Anchors), ficam em [`bounds`](Self::bounds).
894#[derive(Clone, Debug)]
895pub struct ControlBase {
896    /// Posição a partir do canto do pai; só vale com `align: none`.
897    left: f32,
898    /// Posição a partir do topo do pai; só vale com `align: none`.
899    top: f32,
900    /// Largura pedida; o `align` pode esticar (top, bottom, client).
901    width: f32,
902    /// Altura pedida; o `align` pode esticar (left, right, client).
903    height: f32,
904    /// Espaço por fora, até os vizinhos e a borda do pai: número, `[h, v]` ou `[esquerda, cima, direita, baixo]`.
905    margins: Bounds,
906    /// Espaço por dentro, até os filhos: número, `[h, v]` ou `[esquerda, cima, direita, baixo]`.
907    padding: Bounds,
908    /// Encaixe no pai: `top`/`bottom` esticam na largura, `left`/`right` na altura, `client` ocupa o resto; `none` usa `left`/`top`.
909    align: Align,
910    /// Com `align: none`, os lados que acompanham o pai quando ele muda de tamanho: `left,right` estica na largura, só `right` anda junto com a borda direita.
911    anchors: Anchors,
912    /// Aparece; escondido não ocupa lugar no layout.
913    visible: bool,
914    /// Aceita clique e teclado; desligado aparece apagado, e os filhos também.
915    enabled: bool,
916    /// Recebe o mouse; desligado, o clique passa para o que está embaixo.
917    hit_test: bool,
918    /// Corta o desenho dos filhos na borda dele.
919    clip_children: bool,
920    /// Pinta com o estado do pai (`hover`, `pressed`, `checked`): o rótulo da linha marcada
921    /// fica com a cor de marcado do tema sem trocar o estilo filho a filho (C25 do Tabernáculo).
922    inherit_state: bool,
923    /// Os textos dele passam pela tradução do app (o padrão). Desligado, ficam como estão e
924    /// não entram na lista do que traduzir: um nome próprio, um código, um valor de exemplo
925    /// (G19 do Tabernáculo).
926    translatable: bool,
927    /// A roda do mouse em cima dele fica com ele (não rola os contêineres de fora), mesmo
928    /// sem ele rolar: uma prévia que dá zoom com a roda, um mapa, um gráfico.
929    captures_wheel: bool,
930    /// A pinça e o deslizar em cima dele ficam com ele: o `on_gesture`/`on_swipe` dele roda e
931    /// os pais não recebem (a linha do tempo que amplia dentro de um palco que também amplia).
932    captures_gesture: bool,
933    /// Pode receber o foco do teclado (clique ou Tab).
934    can_focus: bool,
935    /// Pode ser arrastado (o `drag` diz o que vai junto).
936    draggable: bool,
937    /// Aceita o que é solto em cima dele (`on_drop`).
938    accepts_drops: bool,
939    /// O arrasto declarado (sem handler): o que vai (`"cliente:123"`, o tipo antes do primeiro
940    /// `:`) e o rótulo que acompanha o mouse; os tipos que este destino aceita (`"cliente;produto"`).
941    drag: Option<Box<DragDecl>>,
942    /// Entra na ordem do Tab.
943    tab_stop: bool,
944    /// No toque, arrastar rola o contêiner de fora em vez de ir para o controle.
945    pan_on_touch: bool,
946    /// Menu de contexto: abre no clique direito.
947    pub(crate) popup_menu: Option<ComponentId>,
948    /// O cursor do mouse em cima dele.
949    cursor: CursorShape,
950    /// Transparência de 0 (invisível) a 1, com os filhos; continua no layout e clicável.
951    opacity: f32,
952    /// Como o controle (com os filhos) se junta ao que está por baixo (o `mix-blend-mode`
953    /// do CSS): `difference` com branco é o negativo, como a marca d'água sobre um vídeo.
954    blend_mode: crate::BlendMode,
955    /// Giro em graus, em torno do centro.
956    rotation: f32,
957    /// A escala do controle e de tudo dentro dele (1 = normal): ele ocupa o
958    /// mesmo retângulo no pai, e o desenho dele e o layout dos filhos acontecem num espaço do
959    /// tamanho do retângulo dividido pela escala, ampliado na pintura. O clique, o foco e a
960    /// área a repintar acompanham ([`ControlBase::inner_size`]).
961    scale: f32,
962    /// Deslocamento só do desenho (não muda o layout): animações e transições.
963    translate: PointF,
964    /// O desenho dele e dos filhos guardado numa imagem, refeita só quando algo lá dentro
965    /// muda: um painel pesado que desliza ou some aos poucos.
966    cache_layer: bool,
967    /// Proporção fixa (largura ÷ altura; 0 = livre), como o `VResponsive` do Vuetify.
968    aspect_ratio: f32,
969    /// Largura máxima (0 = sem limite), como o `max-width` do CSS com margem automática.
970    max_width: f32,
971    /// Largura mínima, altura mínima e máxima (0 = sem limite).
972    min_width: f32,
973    /// Altura mínima: o layout e o `auto_size` não o deixam mais baixo (0 = sem limite).
974    min_height: f32,
975    /// Altura máxima: o layout e o `auto_size` não o deixam mais alto (0 = sem limite; a mínima vence).
976    max_height: f32,
977    /// Encaixado: estica na faixa ou fica com o próprio tamanho no começo, meio ou fim.
978    self_align: SelfAlign,
979    /// O tamanho sai do conteúdo: a altura; num Label encaixado à esquerda ou à direita, também a largura.
980    auto_size: bool,
981    /// Quantas colunas ocupa num `GridLayout` (o `colspan`; 1 ou 0: uma).
982    column_span: u32,
983    /// O lugar fixo num `GridLayout`: linha e coluna (-1: segue a ordem) e
984    /// quantas linhas ocupa. O relatório do Tabernáculo, G12.
985    grid_row: i16,
986    /// A coluna fixa num `GridLayout`, contando de 0 (-1: segue a ordem); vale junto com o `grid_row`.
987    grid_column: i16,
988    /// Quantas linhas ocupa num `GridLayout` (1 ou 0: uma).
989    row_span: u16,
990    /// Quanto do espaço que sobra na linha de um `FlowLayout` ele toma (o `flex-grow`): um
991    /// `Layout` vazio com `grow` 1 é o espaçador que empurra o resto para o fim (L04).
992    grow: f32,
993    /// As escalas de fonte e de espaços da vista ativa do form (postas pelo layout; veja
994    /// `views.rs`): os getters de `margins`/`padding` e a fonte da pintura já saem escalados.
995    pub(crate) text_scale: f32,
996    pub(crate) spacing_scale: f32,
997    /// Sombra do controle; quando há, vale no lugar da sombra do estilo.
998    shadow: Option<crate::canvas::Shadow>,
999    /// Um número livre para o código (não muda nada na tela).
1000    tag: i64,
1001    /// Os textos que quase nenhum controle usa (o `tag_string`, o `accessible_name`), numa
1002    /// caixa só, criada quando um deles tem algo: 8 bytes por controle.
1003    rare: Option<Box<RareTexts>>,
1004    /// A variante do tema (`primary`, `outline`, `flat`, `card`...): o estilo `Classe.variante`.
1005    style: String,
1006    /// Tema próprio (pelo nome), que vale também para os filhos. Vazio = o do pai.
1007    theme: String,
1008    /// Dica mostrada com o mouse parado em cima.
1009    hint: String,
1010    state: ControlState,
1011    pub(crate) bounds: RectF,
1012    pub(crate) anchor_ref: Option<AnchorRef>,
1013    /// Controle flutuante preso a outro (ver [`Ui::follow`](crate::Ui::follow)): o alvo e a
1014    /// distância do canto dele (medida no primeiro layout).
1015    pub(crate) follow: Option<(ComponentId, Option<PointF>)>,
1016    /// `visible` desligado pela propriedade no designer: o controle continua no layout e
1017    /// clicável, pintado translúcido (em execução ele some).
1018    pub(crate) design_hidden: bool,
1019    /// Só aparece no designer (o relatório: em execução, só a visualização o mostra).
1020    pub(crate) design_only: bool,
1021    /// Fica da esquerda para a direita mesmo com a interface espelhada (árabe), ele e os
1022    /// filhos: o designer da IDE, um gráfico, um mapa.
1023    pub(crate) keep_left_to_right: bool,
1024    /// As cores próprias (vazio = as do tema).
1025    pub(crate) colors: ColorOverride,
1026    /// A fonte própria; o que ficar sem valor vem do pai.
1027    pub(crate) font: FontOverride,
1028    /// Quanto o conteúdo está rolado.
1029    scroll_offset: PointF,
1030    /// A rolagem com que o último layout pôs os filhos: a posição de um filho no conteúdo é a
1031    /// dele mais esta, mesmo antes do próximo layout.
1032    pub(crate) laid_out_scroll: PointF,
1033    /// Faixas da tela cobertas pelo sistema (só no form; ver [`Ui::set_safe_area`](crate::Ui::set_safe_area)).
1034    pub(crate) safe_area: Bounds,
1035    /// Tamanho ocupado pelos filhos, calculado no layout (sem a rolagem).
1036    pub(crate) content_size: SizeF,
1037}
1038
1039impl Default for ControlBase {
1040    fn default() -> Self {
1041        Self::new(100.0, 100.0)
1042    }
1043}
1044
1045impl ControlBase {
1046    /// Propriedades publicadas comuns a todos os controles.
1047    pub const PROPS: &'static [PropInfo] = &[
1048        PropInfo::new("left", PropKind::Float, "Layout"),
1049        PropInfo::new("top", PropKind::Float, "Layout"),
1050        PropInfo::new("width", PropKind::Float, "Layout"),
1051        PropInfo::new("height", PropKind::Float, "Layout"),
1052        PropInfo::new("align", PropKind::Enum(<Align as crate::prop::PropEnum>::NAMES), "Layout"),
1053        PropInfo::new("anchors", PropKind::Set(&Anchors::NAMES), "Layout"),
1054        PropInfo::new("margins", PropKind::Bounds, "Layout"),
1055        PropInfo::new("padding", PropKind::Bounds, "Layout"),
1056        PropInfo::new("visible", PropKind::Bool, "Behavior"),
1057        PropInfo::new("enabled", PropKind::Bool, "Behavior"),
1058        PropInfo::new("hit_test", PropKind::Bool, "Behavior"),
1059        PropInfo::new("clip_children", PropKind::Bool, "Behavior"),
1060        PropInfo::new("inherit_state", PropKind::Bool, "Appearance"),
1061        PropInfo::new("translate", PropKind::Bool, "Behavior"),
1062        PropInfo::new("captures_wheel", PropKind::Bool, "Behavior"),
1063        PropInfo::new("captures_gesture", PropKind::Bool, "Behavior"),
1064        PropInfo::new("can_focus", PropKind::Bool, "Behavior"),
1065        PropInfo::new("draggable", PropKind::Bool, "Behavior"),
1066        PropInfo::new("accepts_drops", PropKind::Bool, "Behavior"),
1067        PropInfo::new("drag_data", PropKind::String, "Behavior"),
1068        PropInfo::new("drag_label", PropKind::String, "Behavior"),
1069        PropInfo::new("drag_image", PropKind::Component, "Behavior"),
1070        PropInfo::new("drop_types", PropKind::String, "Behavior"),
1071        PropInfo::new("tab_stop", PropKind::Bool, "Behavior"),
1072        PropInfo::new("cursor", PropKind::Enum(<CursorShape as crate::prop::PropEnum>::NAMES), "Behavior"),
1073        PropInfo::new("opacity", PropKind::Float, "Appearance"),
1074        PropInfo::new("blend_mode", PropKind::Enum(<crate::BlendMode as crate::prop::PropEnum>::NAMES), "Appearance"),
1075        PropInfo::new("cache_layer", PropKind::Bool, "Appearance"),
1076        PropInfo::new("rotation", PropKind::Angle, "Layout"),
1077        PropInfo::new("scale", PropKind::Float, "Layout"),
1078        PropInfo::new("translate_x", PropKind::Float, "Appearance"),
1079        PropInfo::new("translate_y", PropKind::Float, "Appearance"),
1080        PropInfo::new("aspect_ratio", PropKind::Float, "Layout"),
1081        PropInfo::new("max_width", PropKind::Float, "Layout"),
1082        PropInfo::new("min_width", PropKind::Float, "Layout"),
1083        PropInfo::new("min_height", PropKind::Float, "Layout"),
1084        PropInfo::new("max_height", PropKind::Float, "Layout"),
1085        PropInfo::new("self_align", PropKind::Enum(<SelfAlign as crate::prop::PropEnum>::NAMES), "Layout"),
1086        PropInfo::new("auto_size", PropKind::Bool, "Layout"),
1087        PropInfo::new("column_span", PropKind::Int, "Layout"),
1088        PropInfo::new("grid_row", PropKind::Int, "Layout"),
1089        PropInfo::new("grid_column", PropKind::Int, "Layout"),
1090        PropInfo::new("row_span", PropKind::Int, "Layout"),
1091        PropInfo::new("grow", PropKind::Float, "Layout"),
1092        PropInfo::new("shadow", PropKind::Shadow, "Appearance"),
1093        PropInfo::new("style", PropKind::String, "Appearance"),
1094        PropInfo::new("theme", PropKind::String, "Appearance"),
1095        PropInfo::new("fill", PropKind::Color, "Appearance"),
1096        PropInfo::new("border_color", PropKind::Color, "Appearance"),
1097        PropInfo::new("text_color", PropKind::Color, "Appearance"),
1098        PropInfo::new("accent_color", PropKind::Color, "Appearance"),
1099        PropInfo::new("success_color", PropKind::Color, "Appearance"),
1100        PropInfo::new("warning_color", PropKind::Color, "Appearance"),
1101        PropInfo::new("danger_color", PropKind::Color, "Appearance"),
1102        PropInfo::new("font_family", PropKind::String, "Font"),
1103        PropInfo::new("font_size", PropKind::Float, "Font"),
1104        PropInfo::new("font_weight", PropKind::Enum(&FONT_WEIGHTS), "Font"),
1105        PropInfo::new("font_italic", PropKind::Bool, "Font"),
1106        PropInfo::new("font_underline", PropKind::Bool, "Font"),
1107        PropInfo::new("font_strikeout", PropKind::Bool, "Font"),
1108        PropInfo::new("hint", PropKind::String, "Behavior"),
1109        PropInfo::new("tag", PropKind::Int, "Misc"),
1110        PropInfo::new("tag_string", PropKind::String, "Misc"),
1111        PropInfo::new("accessible_name", PropKind::String, "Behavior"),
1112        PropInfo::new("popup_menu", PropKind::Component, "Behavior"),
1113        PropInfo::new("on_click", PropKind::Event, "Events"),
1114        PropInfo::new("on_dbl_click", PropKind::Event, "Events"),
1115        PropInfo::new("on_long_press", PropKind::Event, "Events"),
1116        PropInfo::new("on_pointer_down", PropKind::Event, "Events"),
1117        PropInfo::new("on_pointer_up", PropKind::Event, "Events"),
1118        PropInfo::new("on_pointer_move", PropKind::Event, "Events"),
1119        PropInfo::new("on_pointer_enter", PropKind::Event, "Events"),
1120        PropInfo::new("on_pointer_leave", PropKind::Event, "Events"),
1121        PropInfo::new("on_wheel", PropKind::Event, "Events"),
1122        PropInfo::new("on_gesture", PropKind::Event, "Events"),
1123        PropInfo::new("on_swipe", PropKind::Event, "Events"),
1124        PropInfo::new("on_key_down", PropKind::Event, "Events"),
1125        PropInfo::new("on_key_press", PropKind::Event, "Events"),
1126        PropInfo::new("on_key_up", PropKind::Event, "Events"),
1127        PropInfo::new("on_enter", PropKind::Event, "Events"),
1128        PropInfo::new("on_exit", PropKind::Event, "Events"),
1129        PropInfo::new("on_resize", PropKind::Event, "Events"),
1130        PropInfo::new("on_drag_start", PropKind::Event, "Events"),
1131        PropInfo::new("on_drag_over", PropKind::Event, "Events"),
1132        PropInfo::new("on_drag_move", PropKind::Event, "Events"),
1133        PropInfo::new("on_drag_leave", PropKind::Event, "Events"),
1134        PropInfo::new("on_drag_drop", PropKind::Event, "Events"),
1135        PropInfo::new("on_drag_end", PropKind::Event, "Events"),
1136    ];
1137
1138    pub fn new(width: f32, height: f32) -> Self {
1139        Self {
1140            left: 0.0,
1141            top: 0.0,
1142            width,
1143            height,
1144            margins: Bounds::ZERO,
1145            padding: Bounds::ZERO,
1146            align: Align::None,
1147            anchors: Anchors::default(),
1148            visible: true,
1149            enabled: true,
1150            hit_test: true,
1151            clip_children: false,
1152            inherit_state: false,
1153            translatable: true,
1154            captures_wheel: false,
1155            captures_gesture: false,
1156            can_focus: false,
1157            draggable: false,
1158            accepts_drops: false,
1159            drag: None,
1160            tab_stop: true,
1161            pan_on_touch: true,
1162            popup_menu: None,
1163            cursor: CursorShape::Default,
1164            opacity: 1.0,
1165            blend_mode: crate::BlendMode::Normal,
1166            rotation: 0.0,
1167            scale: 1.0,
1168            translate: PointF::ZERO,
1169            cache_layer: false,
1170            aspect_ratio: 0.0,
1171            max_width: 0.0,
1172            min_width: 0.0,
1173            min_height: 0.0,
1174            max_height: 0.0,
1175            self_align: SelfAlign::Stretch,
1176            auto_size: false,
1177            column_span: 1,
1178            grid_row: -1,
1179            grid_column: -1,
1180            row_span: 1,
1181            grow: 0.0,
1182            text_scale: 1.0,
1183            spacing_scale: 1.0,
1184            shadow: None,
1185            tag: 0,
1186            rare: None,
1187            style: String::new(),
1188            theme: String::new(),
1189            hint: String::new(),
1190            state: ControlState::default(),
1191            bounds: RectF::new(0.0, 0.0, width, height),
1192            anchor_ref: None,
1193            follow: None,
1194            design_hidden: false,
1195            design_only: false,
1196            keep_left_to_right: false,
1197            colors: ColorOverride::default(),
1198            font: FontOverride::default(),
1199            scroll_offset: PointF::ZERO,
1200            laid_out_scroll: PointF::ZERO,
1201            content_size: SizeF::ZERO,
1202            safe_area: Bounds::default(),
1203        }
1204    }
1205
1206    // ----- leitura -----
1207
1208    pub fn left(&self) -> f32 {
1209        self.left
1210    }
1211
1212    pub fn top(&self) -> f32 {
1213        self.top
1214    }
1215
1216    pub fn width(&self) -> f32 {
1217        self.width
1218    }
1219
1220    pub fn height(&self) -> f32 {
1221        self.height
1222    }
1223
1224    pub fn position(&self) -> PointF {
1225        PointF::new(self.left, self.top)
1226    }
1227
1228    pub fn size(&self) -> SizeF {
1229        SizeF::new(self.width, self.height)
1230    }
1231
1232    /// As margens que valem no layout (com a escala de espaços da vista ativa; a propriedade
1233    /// guarda a do desenho).
1234    pub fn margins(&self) -> Bounds {
1235        if self.spacing_scale == 1.0 { self.margins } else { self.margins.scaled(self.spacing_scale) }
1236    }
1237
1238    /// O padding que vale no layout, como as [`margins`](Self::margins).
1239    pub fn padding(&self) -> Bounds {
1240        if self.spacing_scale == 1.0 { self.padding } else { self.padding.scaled(self.spacing_scale) }
1241    }
1242
1243    pub fn align(&self) -> Align {
1244        self.align
1245    }
1246
1247    pub fn anchors(&self) -> Anchors {
1248        self.anchors
1249    }
1250
1251    pub fn visible(&self) -> bool {
1252        self.visible
1253    }
1254
1255    /// Só aparece no designer (em execução não é pintado nem recebe o mouse).
1256    pub fn design_only(&self) -> bool {
1257        self.design_only
1258    }
1259
1260    /// As cores próprias.
1261    pub fn colors(&self) -> ColorOverride {
1262        self.colors
1263    }
1264
1265    pub fn set_colors(&mut self, colors: ColorOverride) -> &mut Self {
1266        self.colors = colors;
1267        self
1268    }
1269
1270    pub fn set_design_only(&mut self, on: bool) -> &mut Self {
1271        self.design_only = on;
1272        self
1273    }
1274
1275    /// Fica da esquerda para a direita (ele e os filhos) com a interface espelhada.
1276    pub fn keep_left_to_right(&self) -> bool {
1277        self.keep_left_to_right
1278    }
1279
1280    pub fn set_keep_left_to_right(&mut self, on: bool) -> &mut Self {
1281        self.keep_left_to_right = on;
1282        self
1283    }
1284
1285    pub fn enabled(&self) -> bool {
1286        self.enabled
1287    }
1288
1289    pub fn hit_test(&self) -> bool {
1290        self.hit_test
1291    }
1292
1293    pub fn translatable(&self) -> bool {
1294        self.translatable
1295    }
1296
1297    pub fn set_translatable(&mut self, v: bool) -> &mut Self {
1298        self.translatable = v;
1299        self
1300    }
1301
1302    pub fn inherit_state(&self) -> bool {
1303        self.inherit_state
1304    }
1305
1306    pub fn set_inherit_state(&mut self, v: bool) -> &mut Self {
1307        self.inherit_state = v;
1308        self
1309    }
1310
1311    pub fn clip_children(&self) -> bool {
1312        self.clip_children
1313    }
1314
1315    pub fn captures_wheel(&self) -> bool {
1316        self.captures_wheel
1317    }
1318
1319    pub fn captures_gesture(&self) -> bool {
1320        self.captures_gesture
1321    }
1322
1323    /// Pode receber o foco do teclado (como `CanFocus`).
1324    /// Arrastável: passar de alguns pontos com o
1325    /// botão pressionado dispara `on_drag_start`, e o handler começa o arrasto com
1326    /// [`Ui::begin_drag`](crate::Ui::begin_drag).
1327    pub fn draggable(&self) -> bool {
1328        self.draggable
1329    }
1330
1331    pub fn set_draggable(&mut self, v: bool) -> &mut Self {
1332        self.draggable = v;
1333        self
1334    }
1335
1336    /// Recebe o que é arrastado: `on_drag_over` ao entrar (o handler recusa com
1337    /// [`Ui::reject_drop`](crate::Ui::reject_drop)) e `on_drag_drop` ao soltar.
1338    pub fn accepts_drops(&self) -> bool {
1339        self.accepts_drops
1340    }
1341
1342    pub fn set_accepts_drops(&mut self, v: bool) -> &mut Self {
1343        self.accepts_drops = v;
1344        self
1345    }
1346
1347    /// O que vai no arrasto declarado (vazio: só com o `on_drag_start`).
1348    pub fn drag_data(&self) -> &str {
1349        self.drag.as_ref().map_or("", |d| d.data.as_str())
1350    }
1351
1352    pub fn drag_label(&self) -> &str {
1353        self.drag.as_ref().map_or("", |d| d.label.as_str())
1354    }
1355
1356    /// O `DragImage` do arrasto (a imagem que acompanha o cursor).
1357    pub fn drag_image(&self) -> Option<ComponentId> {
1358        self.drag.as_ref().and_then(|d| d.image)
1359    }
1360
1361    /// O `DragImage` foi liberado: a referência sai.
1362    pub(crate) fn forget_drag_image(&mut self, doomed: &[ComponentId]) {
1363        if let Some(d) = self.drag.as_mut().filter(|d| d.image.is_some_and(|i| doomed.contains(&i))) {
1364            d.image = None;
1365        }
1366    }
1367
1368    /// Os tipos aceitos ao soltar (vazio: decide o `on_drag_over`).
1369    pub fn drop_types(&self) -> &str {
1370        self.drag.as_ref().map_or("", |d| d.drop_types.as_str())
1371    }
1372
1373    fn drag_decl(&mut self) -> &mut DragDecl {
1374        self.drag.get_or_insert_with(Default::default)
1375    }
1376
1377    pub fn can_focus(&self) -> bool {
1378        self.can_focus
1379    }
1380
1381    /// Participa da navegação com Tab (como `TabStop`).
1382    pub fn tab_stop(&self) -> bool {
1383        self.tab_stop
1384    }
1385
1386    /// Menu de contexto do controle.
1387    pub fn popup_menu(&self) -> Option<ComponentId> {
1388        self.popup_menu
1389    }
1390
1391    pub fn set_popup_menu(&mut self, menu: Option<ComponentId>) -> &mut Self {
1392        self.popup_menu = menu;
1393        self
1394    }
1395
1396    /// Ver [`set_pan_on_touch`](Self::set_pan_on_touch).
1397    pub fn pan_on_touch(&self) -> bool {
1398        self.pan_on_touch
1399    }
1400
1401    /// Cursor do mouse sobre o controle. `Default` herda o do pai.
1402    pub fn cursor(&self) -> CursorShape {
1403        self.cursor
1404    }
1405
1406    pub fn opacity(&self) -> f32 {
1407        self.opacity
1408    }
1409
1410    /// Como o controle se junta ao que está por baixo (veja o campo).
1411    pub fn blend_mode(&self) -> crate::BlendMode {
1412        self.blend_mode
1413    }
1414
1415    pub fn set_blend_mode(&mut self, mode: crate::BlendMode) -> &mut Self {
1416        self.blend_mode = mode;
1417        self
1418    }
1419
1420    /// O desenho guardado numa imagem (veja o campo).
1421    pub fn cache_layer(&self) -> bool {
1422        self.cache_layer
1423    }
1424
1425    pub fn set_cache_layer(&mut self, on: bool) -> &mut Self {
1426        self.cache_layer = on;
1427        self
1428    }
1429
1430    /// Giro em graus, em torno do centro. Só a pintura gira; o clique usa o retângulo
1431    /// sem giro.
1432    pub fn rotation(&self) -> f32 {
1433        self.rotation
1434    }
1435
1436    /// A escala dele e de tudo dentro dele ([`set_scale`](Self::set_scale); 1 = normal).
1437    pub fn scale(&self) -> f32 {
1438        self.scale
1439    }
1440
1441    /// O tamanho do espaço de dentro: o do retângulo dividido pela escala. É nele que o
1442    /// controle se desenha (`PaintCtx::rect`) e que os filhos são arrumados.
1443    pub fn inner_size(&self) -> SizeF {
1444        let s = self.scale;
1445        if s == 1.0 { self.bounds.size() } else { SizeF::new(self.bounds.width / s, self.bounds.height / s) }
1446    }
1447
1448    pub fn shadow(&self) -> Option<crate::canvas::Shadow> {
1449        self.shadow
1450    }
1451
1452    /// Proporção fixa (largura ÷ altura); 0 = livre. No layout, a altura sai da largura
1453    /// (Top, Bottom, Horizontal, None), a largura sai da altura (Left, Right, Vertical) ou
1454    /// o controle cabe na área mantendo a proporção (Client, Center).
1455    pub fn aspect_ratio(&self) -> f32 {
1456        self.aspect_ratio
1457    }
1458
1459    pub fn set_aspect_ratio(&mut self, ratio: f32) -> &mut Self {
1460        self.aspect_ratio = if ratio.is_finite() { ratio.max(0.0) } else { 0.0 };
1461        self
1462    }
1463
1464    /// Largura máxima (0 = sem limite). O controle não passa dela; alinhado em cima, embaixo ou
1465    /// no cliente, fica no meio da área (o conteúdo de uma página que não se espalha numa tela
1466    /// larga). No form, é a largura máxima da janela.
1467    pub fn max_width(&self) -> f32 {
1468        self.max_width
1469    }
1470
1471    pub fn set_max_width(&mut self, width: f32) -> &mut Self {
1472        self.max_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1473        self
1474    }
1475
1476    /// Largura mínima (0 = sem limite). O layout não deixa o controle mais estreito que ela,
1477    /// mesmo alinhado (`top`, `client`...): o que passar da área do pai fica cortado (ou rola,
1478    /// num ScrollBox), e um texto com `wrap` para de quebrar nessa largura. No form, é a
1479    /// largura mínima da janela.
1480    pub fn min_width(&self) -> f32 {
1481        self.min_width
1482    }
1483
1484    pub fn set_min_width(&mut self, width: f32) -> &mut Self {
1485        self.min_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1486        self
1487    }
1488
1489    /// Altura mínima (0 = sem limite), como a [`min_width`](Self::min_width).
1490    pub fn min_height(&self) -> f32 {
1491        self.min_height
1492    }
1493
1494    pub fn set_min_height(&mut self, height: f32) -> &mut Self {
1495        self.min_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1496        self
1497    }
1498
1499    /// Altura máxima (0 = sem limite). No form, é a altura máxima da janela.
1500    pub fn max_height(&self) -> f32 {
1501        self.max_height
1502    }
1503
1504    pub fn set_max_height(&mut self, height: f32) -> &mut Self {
1505        self.max_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1506        self
1507    }
1508
1509    /// A largura que o controle ocupa numa faixa de `available` (com a `max_width` e a
1510    /// `min_width`; a mínima vence).
1511    pub fn clamp_width(&self, available: f32) -> f32 {
1512        let w = if self.max_width > 0.0 { available.min(self.max_width) } else { available };
1513        w.max(self.min_width)
1514    }
1515
1516    /// A altura dentro da `min_height` e da `max_height` (a mínima vence).
1517    pub fn clamp_height(&self, height: f32) -> f32 {
1518        let h = if self.max_height > 0.0 { height.min(self.max_height) } else { height };
1519        h.max(self.min_height)
1520    }
1521
1522    /// Encaixado, estica na faixa (`stretch`) ou fica com o próprio tamanho no começo, no
1523    /// meio ou no fim: veja [`SelfAlign`].
1524    pub fn self_align(&self) -> SelfAlign {
1525        self.self_align
1526    }
1527
1528    pub fn set_self_align(&mut self, align: SelfAlign) -> &mut Self {
1529        self.self_align = align;
1530        self
1531    }
1532
1533    /// A largura numa faixa horizontal de `available` (encaixado em cima ou embaixo): a faixa
1534    /// toda ou, com `self_align`, a própria `width`; com `self_align` e `max_width`, a faixa até
1535    /// a máxima (o `width: 100%; max-width` do CSS). Sempre dentro dos limites.
1536    pub fn band_width(&self, available: f32) -> f32 {
1537        match self.self_align {
1538            SelfAlign::Stretch => self.clamp_width(available),
1539            _ if self.max_width > 0.0 => self.clamp_width(available),
1540            _ => self.clamp_width(self.width),
1541        }
1542    }
1543
1544    /// A altura numa faixa vertical de `available` (encaixado à esquerda ou à direita), como a
1545    /// [`band_width`](Self::band_width).
1546    pub fn band_height(&self, available: f32) -> f32 {
1547        match self.self_align {
1548            SelfAlign::Stretch => self.clamp_height(available),
1549            _ if self.max_height > 0.0 => self.clamp_height(available),
1550            _ => self.clamp_height(self.height),
1551        }
1552    }
1553
1554    /// Onde começa um tamanho `size` numa faixa de `available`: no começo, no meio (o
1555    /// `stretch` com a largura máxima sobrando) ou no fim. Passando da faixa, no começo.
1556    pub fn band_offset(&self, available: f32, size: f32) -> f32 {
1557        let spare = (available - size).max(0.0);
1558        match self.self_align {
1559            SelfAlign::Start => 0.0,
1560            SelfAlign::End => spare,
1561            SelfAlign::Stretch | SelfAlign::Center => spare / 2.0,
1562        }
1563    }
1564
1565    /// A altura sai do conteúdo, na largura que o controle tem:
1566    /// um Label com `wrap` fica da altura do texto quebrado; um contêiner, da
1567    /// altura dos filhos encaixados em cima e embaixo (mais o padding). Vale com `align`
1568    /// `top`, `bottom` ou `none`.
1569    pub fn auto_size(&self) -> bool {
1570        self.auto_size
1571    }
1572
1573    pub fn set_auto_size(&mut self, on: bool) -> &mut Self {
1574        self.auto_size = on;
1575        self
1576    }
1577
1578    /// Quantas colunas ocupa num `GridLayout` (pelo menos 1; numa grade com menos colunas,
1579    /// ocupa a linha inteira).
1580    pub fn column_span(&self) -> u32 {
1581        self.column_span.max(1)
1582    }
1583
1584    /// O lugar fixo na grade: (linha, coluna), ou `None` (segue a ordem dos filhos).
1585    pub fn grid_cell(&self) -> Option<(u32, u32)> {
1586        (self.grid_row >= 0 && self.grid_column >= 0).then(|| (self.grid_row as u32, self.grid_column as u32))
1587    }
1588
1589    pub fn set_grid_cell(&mut self, cell: Option<(u32, u32)>) -> &mut Self {
1590        let (r, c) = cell.map_or((-1, -1), |(r, c)| (r.min(i16::MAX as u32) as i16, c.min(i16::MAX as u32) as i16));
1591        self.grid_row = r;
1592        self.grid_column = c;
1593        self
1594    }
1595
1596    /// Quantas linhas ocupa num `GridLayout` (o `rowspan`).
1597    pub fn row_span(&self) -> u32 {
1598        u32::from(self.row_span.max(1))
1599    }
1600
1601    pub fn set_row_span(&mut self, span: u32) -> &mut Self {
1602        self.row_span = span.clamp(1, 64) as u16;
1603        self
1604    }
1605
1606    pub fn grow(&self) -> f32 {
1607        self.grow
1608    }
1609
1610    pub fn set_grow(&mut self, grow: f32) -> &mut Self {
1611        self.grow = grow.max(0.0);
1612        self
1613    }
1614
1615    pub fn set_column_span(&mut self, span: u32) -> &mut Self {
1616        self.column_span = span.max(1);
1617        self
1618    }
1619
1620    /// A escala de fonte da vista ativa do form (1 sem vista).
1621    pub fn text_scale(&self) -> f32 {
1622        self.text_scale
1623    }
1624
1625    /// A escala de espaços da vista ativa do form (1 sem vista).
1626    pub fn spacing_scale(&self) -> f32 {
1627        self.spacing_scale
1628    }
1629
1630    pub fn tag(&self) -> i64 {
1631        self.tag
1632    }
1633
1634    /// O nome que o leitor de tela fala (o `aria-label`), no lugar do texto do controle: um
1635    /// botão só com ícone, um campo sem rótulo. O relatório do Tabernáculo, C29.
1636    pub fn accessible_name(&self) -> &str {
1637        self.rare.as_ref().map_or("", |r| &r.accessible_name)
1638    }
1639
1640    pub fn set_accessible_name(&mut self, v: &str) -> &mut Self {
1641        self.rare_mut(|r| r.accessible_name = v.into());
1642        self
1643    }
1644
1645    fn rare_mut(&mut self, change: impl FnOnce(&mut RareTexts)) {
1646        let rare = self.rare.get_or_insert_with(Default::default);
1647        change(rare);
1648        if rare.tag_string.is_empty() && rare.accessible_name.is_empty() {
1649            self.rare = None;
1650        }
1651    }
1652
1653    pub fn tag_string(&self) -> &str {
1654        self.rare.as_ref().map_or("", |r| &r.tag_string)
1655    }
1656
1657    /// Variante de estilo do tema ("primary", "danger", "flat"...). Vazio = estilo da classe.
1658    pub fn style(&self) -> &str {
1659        &self.style
1660    }
1661
1662    /// Tema próprio do controle (e dos filhos), pelo nome. Vazio = o do pai.
1663    pub fn theme_name(&self) -> &str {
1664        &self.theme
1665    }
1666
1667    pub fn set_theme_name(&mut self, v: impl Into<String>) -> &mut Self {
1668        self.theme = v.into();
1669        self
1670    }
1671
1672    /// Dica (balão) mostrada com o mouse parado sobre o controle. Vazio = a do pai.
1673    pub fn hint(&self) -> &str {
1674        &self.hint
1675    }
1676
1677    pub fn set_hint(&mut self, v: impl Into<String>) -> &mut Self {
1678        self.hint = v.into();
1679        self
1680    }
1681
1682    pub fn state(&self) -> ControlState {
1683        self.state
1684    }
1685
1686    /// Posição e tamanho reais, relativos ao pai, calculados pelo layout.
1687    pub fn bounds(&self) -> RectF {
1688        self.bounds
1689    }
1690
1691    /// Quanto o conteúdo está rolado: os filhos são deslocados por este valor.
1692    pub fn scroll_offset(&self) -> PointF {
1693        self.scroll_offset
1694    }
1695
1696    /// A rolagem com que o último layout pôs os filhos ([`scroll_offset`](Self::scroll_offset)
1697    /// muda na hora; esta, no layout): somada à posição de um filho, dá onde ele está no conteúdo.
1698    pub fn laid_out_scroll(&self) -> PointF {
1699        self.laid_out_scroll
1700    }
1701
1702    /// Rola o conteúdo. Chame `invalidate` (ou mude por `ui.control_mut`) para refazer o
1703    /// layout.
1704    pub fn set_scroll_offset(&mut self, offset: PointF) -> &mut Self {
1705        self.scroll_offset = offset;
1706        self
1707    }
1708
1709    /// Tamanho ocupado pelos filhos visíveis (com margens e padding), calculado no
1710    /// layout. Serve para saber até onde rolar.
1711    pub fn content_size(&self) -> SizeF {
1712        self.content_size
1713    }
1714
1715    // ----- escrita (encadeável) -----
1716
1717    // A posição e o tamanho pedidos mudaram: as âncoras medem de novo a partir daqui. Só quando
1718    // o valor muda de fato: regravar o mesmo valor a cada arrumação (o `auto_size`) refazia a
1719    // referência sempre, e o controle ancorado nunca acompanhava o pai (relatório do InsightDB,
1720    // 11/11: nem a célula do GridLayout, nem a janela em tela cheia).
1721    pub fn set_left(&mut self, v: f32) -> &mut Self {
1722        if self.left != v {
1723            self.left = v;
1724            self.anchor_ref = None;
1725        }
1726        self
1727    }
1728
1729    pub fn set_top(&mut self, v: f32) -> &mut Self {
1730        if self.top != v {
1731            self.top = v;
1732            self.anchor_ref = None;
1733        }
1734        self
1735    }
1736
1737    pub fn set_position(&mut self, left: f32, top: f32) -> &mut Self {
1738        self.set_left(left).set_top(top)
1739    }
1740
1741    pub fn set_width(&mut self, v: f32) -> &mut Self {
1742        if self.width != v.max(0.0) {
1743            self.width = v.max(0.0);
1744            self.anchor_ref = None;
1745        }
1746        self
1747    }
1748
1749    pub fn set_height(&mut self, v: f32) -> &mut Self {
1750        if self.height != v.max(0.0) {
1751            self.height = v.max(0.0);
1752            self.anchor_ref = None;
1753        }
1754        self
1755    }
1756
1757    /// A largura que o próprio layout mede (o `auto_size`), como [`set_measured_height`].
1758    pub(crate) fn set_measured_width(&mut self, v: f32) {
1759        self.width = v.max(0.0);
1760        if let Some(r) = self.anchor_ref.as_mut() {
1761            r.rect.width = self.width;
1762        }
1763    }
1764
1765    /// A altura que o próprio layout mede (o `auto_size`): muda o tamanho sem perder a
1766    /// referência das âncoras (a altura guardada nela acompanha).
1767    pub(crate) fn set_measured_height(&mut self, v: f32) {
1768        self.height = v.max(0.0);
1769        if let Some(r) = self.anchor_ref.as_mut() {
1770            r.rect.height = self.height;
1771        }
1772    }
1773
1774    pub fn set_size(&mut self, width: f32, height: f32) -> &mut Self {
1775        self.set_width(width).set_height(height)
1776    }
1777
1778    /// Define posição e tamanho de uma vez.
1779    pub fn set_rect(&mut self, left: f32, top: f32, width: f32, height: f32) -> &mut Self {
1780        self.set_position(left, top).set_size(width, height)
1781    }
1782
1783    pub fn set_margins(&mut self, v: impl Into<Bounds>) -> &mut Self {
1784        self.margins = v.into();
1785        self
1786    }
1787
1788    pub fn set_padding(&mut self, v: impl Into<Bounds>) -> &mut Self {
1789        self.padding = v.into();
1790        self
1791    }
1792
1793    pub fn set_align(&mut self, v: Align) -> &mut Self {
1794        self.align = v;
1795        self.anchor_ref = None;
1796        self
1797    }
1798
1799    pub fn set_anchors(&mut self, v: Anchors) -> &mut Self {
1800        self.anchors = v;
1801        self.anchor_ref = None;
1802        self
1803    }
1804
1805    pub fn set_visible(&mut self, v: bool) -> &mut Self {
1806        self.visible = v;
1807        self
1808    }
1809
1810    pub fn set_enabled(&mut self, v: bool) -> &mut Self {
1811        self.enabled = v;
1812        self
1813    }
1814
1815    pub fn set_hit_test(&mut self, v: bool) -> &mut Self {
1816        self.hit_test = v;
1817        self
1818    }
1819
1820    pub fn set_clip_children(&mut self, v: bool) -> &mut Self {
1821        self.clip_children = v;
1822        self
1823    }
1824
1825    pub fn set_captures_wheel(&mut self, v: bool) -> &mut Self {
1826        self.captures_wheel = v;
1827        self
1828    }
1829
1830    pub fn set_captures_gesture(&mut self, v: bool) -> &mut Self {
1831        self.captures_gesture = v;
1832        self
1833    }
1834
1835    pub fn set_can_focus(&mut self, v: bool) -> &mut Self {
1836        self.can_focus = v;
1837        self
1838    }
1839
1840    /// Arrastar o dedo sobre o controle rola o conteúdo (vira roda para o ScrollBox ou o
1841    /// DataGrid de baixo). Ligado por padrão; controles que precisam do arrasto em si (um
1842    /// Splitter, um designer) desligam.
1843    pub fn set_pan_on_touch(&mut self, v: bool) -> &mut Self {
1844        self.pan_on_touch = v;
1845        self
1846    }
1847
1848    pub fn set_tab_stop(&mut self, v: bool) -> &mut Self {
1849        self.tab_stop = v;
1850        self
1851    }
1852
1853    pub fn set_cursor(&mut self, v: CursorShape) -> &mut Self {
1854        self.cursor = v;
1855        self
1856    }
1857
1858    pub fn set_opacity(&mut self, v: f32) -> &mut Self {
1859        self.opacity = v.clamp(0.0, 1.0);
1860        self
1861    }
1862
1863    /// Deslocamento do desenho (sem mexer no layout).
1864    pub fn translate(&self) -> PointF {
1865        self.translate
1866    }
1867
1868    pub fn set_translate(&mut self, offset: PointF) -> &mut Self {
1869        self.translate = if offset.x.is_finite() && offset.y.is_finite() { offset } else { PointF::ZERO };
1870        self
1871    }
1872
1873    /// A escala dele e dos filhos (1 = normal; de 0,05 a 20).
1874    pub fn set_scale(&mut self, scale: f32) -> &mut Self {
1875        self.scale = if scale.is_finite() && scale > 0.0 { scale.clamp(0.05, 20.0) } else { 1.0 };
1876        self
1877    }
1878
1879    pub fn set_rotation(&mut self, degrees: f32) -> &mut Self {
1880        self.rotation = if degrees.is_finite() { degrees % 360.0 } else { 0.0 };
1881        self
1882    }
1883
1884    pub fn set_shadow(&mut self, shadow: Option<crate::canvas::Shadow>) -> &mut Self {
1885        self.shadow = shadow;
1886        self
1887    }
1888
1889    pub fn set_tag(&mut self, v: i64) -> &mut Self {
1890        self.tag = v;
1891        self
1892    }
1893
1894    pub fn set_tag_string(&mut self, v: &str) -> &mut Self {
1895        self.rare_mut(|r| r.tag_string = v.into());
1896        self
1897    }
1898
1899    pub fn set_style(&mut self, v: impl Into<String>) -> &mut Self {
1900        self.style = v.into();
1901        self
1902    }
1903
1904    /// Estado visual (hover, pressed...). Normalmente quem altera é o despacho de eventos;
1905    /// controles como CheckBox alteram `checked`.
1906    pub fn state_mut(&mut self) -> &mut ControlState {
1907        &mut self.state
1908    }
1909
1910    // ----- propriedades por nome -----
1911
1912    pub fn get_prop(&self, name: &str) -> Option<PropValue> {
1913        Some(match name {
1914            "left" => self.left.into(),
1915            "top" => self.top.into(),
1916            "width" => self.width.into(),
1917            "height" => self.height.into(),
1918            "align" => self.align.into(),
1919            "anchors" => self.anchors.into(),
1920            "margins" => self.margins.into(),
1921            "padding" => self.padding.into(),
1922            "visible" => self.visible.into(),
1923            "enabled" => self.enabled.into(),
1924            "hit_test" => self.hit_test.into(),
1925            "clip_children" => self.clip_children.into(),
1926            "inherit_state" => self.inherit_state.into(),
1927            "translate" => self.translatable.into(),
1928            "captures_wheel" => self.captures_wheel.into(),
1929            "captures_gesture" => self.captures_gesture.into(),
1930            "can_focus" => self.can_focus.into(),
1931            "draggable" => self.draggable.into(),
1932            "accepts_drops" => self.accepts_drops.into(),
1933            "drag_data" => self.drag_data().into(),
1934            "drag_label" => self.drag_label().into(),
1935            "drag_image" => PropValue::Component(self.drag_image()),
1936            "drop_types" => self.drop_types().into(),
1937            "tab_stop" => self.tab_stop.into(),
1938            "cursor" => PropValue::enum_value(self.cursor),
1939            "opacity" => self.opacity.into(),
1940            "blend_mode" => PropValue::enum_value(self.blend_mode),
1941            "cache_layer" => self.cache_layer.into(),
1942            "rotation" => self.rotation.into(),
1943            "scale" => self.scale.into(),
1944            "translate_x" => self.translate.x.into(),
1945            "translate_y" => self.translate.y.into(),
1946            "aspect_ratio" => self.aspect_ratio.into(),
1947            "max_width" => self.max_width.into(),
1948            "min_width" => self.min_width.into(),
1949            "min_height" => self.min_height.into(),
1950            "max_height" => self.max_height.into(),
1951            "self_align" => PropValue::enum_value(self.self_align),
1952            "auto_size" => self.auto_size.into(),
1953            "column_span" => (self.column_span() as i64).into(),
1954            "grid_row" => i64::from(self.grid_row).into(),
1955            "grid_column" => i64::from(self.grid_column).into(),
1956            "row_span" => (self.row_span() as i64).into(),
1957            "grow" => f64::from(self.grow).into(),
1958            "shadow" => crate::prop::PropType::to_value(&self.shadow),
1959            "style" => self.style.clone().into(),
1960            "fill" => crate::prop::PropType::to_value(&self.colors.fill),
1961            "border_color" => crate::prop::PropType::to_value(&self.colors.border),
1962            "text_color" => crate::prop::PropType::to_value(&self.colors.text),
1963            "accent_color" => crate::prop::PropType::to_value(&self.colors.accent),
1964            "success_color" => crate::prop::PropType::to_value(&self.colors.success),
1965            "warning_color" => crate::prop::PropType::to_value(&self.colors.warning),
1966            "danger_color" => crate::prop::PropType::to_value(&self.colors.danger),
1967            "font_family" => self.font.family.clone().into(),
1968            "font_size" => crate::prop::PropType::to_value(&self.font.size),
1969            "font_weight" => PropValue::Enum(FONT_WEIGHTS[self.font.weight.map_or(0, |w| w as usize + 1)].into()),
1970            "font_italic" => self.font.italic.into(),
1971            "font_underline" => self.font.underline.into(),
1972            "font_strikeout" => self.font.strikeout.into(),
1973            "theme" => self.theme.clone().into(),
1974            "hint" => self.hint.clone().into(),
1975            "tag" => self.tag.into(),
1976            "tag_string" => self.tag_string().to_string().into(),
1977            "accessible_name" => self.accessible_name().to_string().into(),
1978            "popup_menu" => PropValue::Component(self.popup_menu),
1979            _ => return None,
1980        })
1981    }
1982
1983    pub fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
1984        match name {
1985            "left" => self.set_left(value.to_f32()?),
1986            "top" => self.set_top(value.to_f32()?),
1987            "width" => self.set_width(value.to_f32()?),
1988            "height" => self.set_height(value.to_f32()?),
1989            "align" => self.set_align(value.to_enum()?),
1990            "anchors" => self.set_anchors(value.to_anchors()?),
1991            "margins" => self.set_margins(value.to_bounds()?),
1992            "padding" => self.set_padding(value.to_bounds()?),
1993            "visible" => self.set_visible(value.to_bool()?),
1994            "enabled" => self.set_enabled(value.to_bool()?),
1995            "hit_test" => self.set_hit_test(value.to_bool()?),
1996            "clip_children" => self.set_clip_children(value.to_bool()?),
1997            "inherit_state" => self.set_inherit_state(value.to_bool()?),
1998            "translate" => self.set_translatable(value.to_bool()?),
1999            "captures_wheel" => self.set_captures_wheel(value.to_bool()?),
2000            "captures_gesture" => self.set_captures_gesture(value.to_bool()?),
2001            "can_focus" => self.set_can_focus(value.to_bool()?),
2002            "draggable" => self.set_draggable(value.to_bool()?),
2003            "accepts_drops" => self.set_accepts_drops(value.to_bool()?),
2004            "drag_data" => {
2005                self.drag_decl().data = value.to_str()?.to_string();
2006                self
2007            }
2008            "drag_label" => {
2009                self.drag_decl().label = value.to_str()?.to_string();
2010                self
2011            }
2012            "drag_image" => {
2013                self.drag_decl().image = value.to_component()?;
2014                self
2015            }
2016            "drop_types" => {
2017                self.drag_decl().drop_types = value.to_str()?.to_string();
2018                self
2019            }
2020            "tab_stop" => self.set_tab_stop(value.to_bool()?),
2021            "cursor" => self.set_cursor(value.to_enum()?),
2022            "opacity" => self.set_opacity(value.to_f32()?),
2023            "blend_mode" => self.set_blend_mode(value.to_enum()?),
2024            "cache_layer" => self.set_cache_layer(value.to_bool()?),
2025            "rotation" => self.set_rotation(value.to_f32()?),
2026            "scale" => self.set_scale(value.to_f32()?),
2027            "translate_x" => self.set_translate(PointF::new(value.to_f32()?, self.translate.y)),
2028            "translate_y" => self.set_translate(PointF::new(self.translate.x, value.to_f32()?)),
2029            "aspect_ratio" => self.set_aspect_ratio(value.to_f32()?),
2030            "max_width" => self.set_max_width(value.to_f32()?),
2031            "min_width" => self.set_min_width(value.to_f32()?),
2032            "min_height" => self.set_min_height(value.to_f32()?),
2033            "max_height" => self.set_max_height(value.to_f32()?),
2034            "self_align" => self.set_self_align(value.to_enum()?),
2035            "auto_size" => self.set_auto_size(value.to_bool()?),
2036            "column_span" => self.set_column_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2037            "grid_row" => {
2038                self.grid_row = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2039                self
2040            }
2041            "grid_column" => {
2042                self.grid_column = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2043                self
2044            }
2045            "row_span" => self.set_row_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2046            "grow" => self.set_grow(value.to_f32()?),
2047            "shadow" => self.set_shadow(crate::prop::PropType::from_value(value)?),
2048            "style" => self.set_style(value.to_str()?),
2049            "fill" => {
2050                self.colors.fill = crate::prop::PropType::from_value(value)?;
2051                self
2052            }
2053            "border_color" => {
2054                self.colors.border = crate::prop::PropType::from_value(value)?;
2055                self
2056            }
2057            "text_color" => {
2058                self.colors.text = crate::prop::PropType::from_value(value)?;
2059                self
2060            }
2061            "accent_color" => {
2062                self.colors.accent = crate::prop::PropType::from_value(value)?;
2063                self
2064            }
2065            "success_color" => {
2066                self.colors.success = crate::prop::PropType::from_value(value)?;
2067                self
2068            }
2069            "warning_color" => {
2070                self.colors.warning = crate::prop::PropType::from_value(value)?;
2071                self
2072            }
2073            "danger_color" => {
2074                self.colors.danger = crate::prop::PropType::from_value(value)?;
2075                self
2076            }
2077            "font_family" => {
2078                self.font.family = value.to_str()?.to_string();
2079                self
2080            }
2081            "font_size" => {
2082                self.font.size = crate::prop::PropType::from_value(value)?;
2083                self
2084            }
2085            "font_weight" => {
2086                self.font.weight = font_weight_named(value.to_str()?)?;
2087                self
2088            }
2089            "font_italic" => {
2090                self.font.italic = value.to_bool()?;
2091                self
2092            }
2093            "font_underline" => {
2094                self.font.underline = value.to_bool()?;
2095                self
2096            }
2097            "font_strikeout" => {
2098                self.font.strikeout = value.to_bool()?;
2099                self
2100            }
2101            "theme" => self.set_theme_name(value.to_str()?),
2102            "hint" => self.set_hint(value.to_str()?),
2103            "tag" => self.set_tag(value.to_i64()?),
2104            "tag_string" => self.set_tag_string(value.to_str()?),
2105            "accessible_name" => self.set_accessible_name(value.to_str()?),
2106            "popup_menu" => {
2107                self.popup_menu = value.to_component()?;
2108                self
2109            }
2110            _ => return Err(Error::UnknownProperty(name.to_string())),
2111        };
2112        Ok(())
2113    }
2114}
2115
2116/// Os pesos da propriedade `font_weight`; `default` é o do pai (ou do tema).
2117pub const FONT_WEIGHTS: [&str; 8] = ["default", "thin", "light", "normal", "medium", "semibold", "bold", "black"];
2118
2119fn font_weight_named(name: &str) -> Result<Option<crate::canvas::FontWeight>> {
2120    use crate::canvas::FontWeight::*;
2121    let all = [Thin, Light, Normal, Medium, SemiBold, Bold, Black];
2122    match FONT_WEIGHTS.iter().position(|n| n.eq_ignore_ascii_case(name)) {
2123        Some(0) => Ok(None),
2124        Some(i) => Ok(Some(all[i - 1])),
2125        None => Err(Error::invalid(format!("valor '{name}' inválido; use um de: {}", FONT_WEIGHTS.join(", ")))),
2126    }
2127}
2128
2129/// A fonte de um controle por cima da do tema: família, tamanho,
2130/// peso, itálico, sublinhado e tachado. O que não tem valor vem do pai:
2131/// a fonte posta no form vale para tudo dentro dele.
2132#[derive(Clone, Debug, Default, PartialEq)]
2133pub struct FontOverride {
2134    /// A família da fonte (`"Segoe UI"`, `"monospace"`); vazio: a do pai.
2135    pub family: String,
2136    /// O tamanho da fonte, em pontos; sem valor: o do pai.
2137    pub size: Option<f32>,
2138    /// O peso da fonte (`normal`, `bold`...); sem valor: o do pai.
2139    pub weight: Option<crate::canvas::FontWeight>,
2140    /// Itálico; ligado vale também para os filhos.
2141    pub italic: bool,
2142    /// Sublinhado; ligado vale também para os filhos.
2143    pub underline: bool,
2144    /// Tachado (uma linha no meio do texto); ligado vale também para os filhos.
2145    pub strikeout: bool,
2146}
2147
2148impl FontOverride {
2149    pub fn is_empty(&self) -> bool {
2150        *self == Self::default()
2151    }
2152
2153    /// Esta fonte com o que faltar vindo de `parent`.
2154    pub fn over(&self, parent: &FontOverride) -> FontOverride {
2155        FontOverride {
2156            family: if self.family.is_empty() { parent.family.clone() } else { self.family.clone() },
2157            size: self.size.or(parent.size),
2158            weight: self.weight.or(parent.weight),
2159            italic: self.italic || parent.italic,
2160            underline: self.underline || parent.underline,
2161            strikeout: self.strikeout || parent.strikeout,
2162        }
2163    }
2164
2165    /// Aplica na fonte do estilo (a do tema).
2166    pub fn apply(&self, font: &mut crate::canvas::FontSpec) {
2167        if !self.family.is_empty() {
2168            font.family = self.family.clone();
2169        }
2170        if let Some(size) = self.size.filter(|s| *s > 0.0) {
2171            font.size = size;
2172        }
2173        if let Some(weight) = self.weight {
2174            font.weight = weight;
2175        }
2176        font.italic |= self.italic;
2177        font.underline |= self.underline;
2178        font.strikeout |= self.strikeout;
2179    }
2180}
2181
2182impl ControlBase {
2183    /// A fonte própria do controle (sem a herdada).
2184    pub fn font(&self) -> &FontOverride {
2185        &self.font
2186    }
2187
2188    pub fn set_font(&mut self, font: FontOverride) -> &mut Self {
2189        self.font = font;
2190        self
2191    }
2192}
2193
2194/// As cores próprias de um controle (vazio = as do tema):
2195/// valem para qualquer controle (`fill`, `border_color`, `text_color`, `accent_color` e as de
2196/// sentido: `success_color`, `warning_color`, `danger_color`).
2197/// O `Ui` as põe no estilo resolvido e no tema que o controle vê (`primary` e as variações,
2198/// `text`, `border`), então até os controles que leem o tema direto as seguem.
2199#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2200pub struct ColorOverride {
2201    /// A cor do fundo; vazio: a do tema.
2202    pub fill: Option<crate::Color>,
2203    /// A cor da borda; vazio: a do tema.
2204    pub border: Option<crate::Color>,
2205    /// A cor do texto; vazio: a do tema.
2206    pub text: Option<crate::Color>,
2207    /// O destaque: a marca da caixa de seleção, a barra do progresso, o trilho preenchido,
2208    /// a seleção, o foco.
2209    pub accent: Option<crate::Color>,
2210    /// As cores de sentido: subir/positivo, atenção e cair/erro (candles, variações, avisos).
2211    /// Esta é a de subir/positivo; vazio: a do tema.
2212    pub success: Option<crate::Color>,
2213    /// A cor de sentido de atenção (avisos); vazio: a do tema.
2214    pub warning: Option<crate::Color>,
2215    /// A cor de sentido de cair/erro (candles em queda, variações negativas, erros); vazio: a do tema.
2216    pub danger: Option<crate::Color>,
2217}
2218
2219impl ColorOverride {
2220    pub fn is_empty(&self) -> bool {
2221        *self == Self::default()
2222    }
2223
2224    /// Muda alguma cor do tema (não só o estilo).
2225    pub(crate) fn recolors_theme(&self) -> bool {
2226        !self.is_empty()
2227    }
2228
2229    /// O tema com as cores próprias por cima.
2230    pub(crate) fn apply_theme(&self, theme: &crate::Theme) -> crate::Theme {
2231        use crate::Color;
2232        let mut t = theme.clone();
2233        let mut set = |name: &str, c: Color| {
2234            t.colors.insert(name.to_string(), c);
2235        };
2236        if let Some(a) = self.accent {
2237            let dark = luminance(a) < 0.5;
2238            set("primary", a);
2239            set("primary_hover", a.lerp(if dark { Color::WHITE } else { Color::BLACK }, 0.12));
2240            set("primary_pressed", a.lerp(if dark { Color::BLACK } else { Color::BLACK }, 0.15));
2241            set("on_primary", if luminance(a) < 0.6 { Color::WHITE } else { Color::BLACK });
2242            set("focus_ring", a);
2243            set("selection", a.with_opacity(0.25));
2244            set("primary_soft", a.with_opacity(0.1));
2245            set("primary_container", a.lerp(Color::WHITE, 0.82));
2246        }
2247        if let Some(c) = self.fill {
2248            // O fundo: o da superfície e o das áreas de dentro (um pouco mais escuro ou claro).
2249            let toward = if luminance(c) < 0.5 { Color::WHITE } else { Color::BLACK };
2250            set("surface", c);
2251            set("background", c);
2252            set("surface_2", c.lerp(toward.with_opacity(c.a as f32 / 255.0), 0.06));
2253        }
2254        if let Some(c) = self.text {
2255            set("text", c);
2256            set("text_muted", c.with_opacity(0.65));
2257            for on in ["on_primary", "on_danger", "on_success", "on_primary_container"] {
2258                set(on, c);
2259            }
2260        }
2261        if let Some(c) = self.border {
2262            set("border", c);
2263            set("track", c);
2264        }
2265        for (token, color) in [("success", self.success), ("warning", self.warning), ("danger", self.danger)] {
2266            if let Some(c) = color {
2267                set(token, c);
2268                set(&format!("{token}_soft"), c.with_opacity(0.1));
2269                set(&format!("{token}_hover"), c.lerp(Color::WHITE, 0.12));
2270                set(&format!("{token}_pressed"), c.lerp(Color::BLACK, 0.15));
2271                if token == "success" {
2272                    set("meter_low", c);
2273                } else if token == "danger" {
2274                    set("meter_high", c);
2275                } else {
2276                    set("meter_mid", c);
2277                }
2278            }
2279        }
2280        t
2281    }
2282}
2283
2284/// Luminância relativa (0 escuro, 1 claro).
2285pub(crate) fn luminance(c: crate::Color) -> f32 {
2286    (0.299 * c.r as f32 + 0.587 * c.g as f32 + 0.114 * c.b as f32) / 255.0
2287}
2288
2289/// As duas pontas de um conector ([`Component::connection`]).
2290#[derive(Clone, Copy, Debug, PartialEq)]
2291pub struct Connection {
2292    pub from: ComponentId,
2293    /// O ponto de ligação em `from` (`(1, 0.5)`: o meio do lado direito).
2294    pub from_at: (f32, f32),
2295    pub to: ComponentId,
2296    pub to_at: (f32, f32),
2297}
2298
2299impl Connection {
2300    /// Quanto a ponta sai do componente antes da primeira dobra.
2301    pub const STUB: f32 = 16.0;
2302
2303    /// A direção para fora do lado onde está o ponto (`(1, 0.5)` → direita).
2304    fn normal(at: (f32, f32)) -> PointF {
2305        let (x, y) = at;
2306        let d = [(x, PointF::new(-1.0, 0.0)), (1.0 - x, PointF::new(1.0, 0.0)), (y, PointF::new(0.0, -1.0)), (1.0 - y, PointF::new(0.0, 1.0))];
2307        d.iter().min_by(|a, b| a.0.total_cmp(&b.0)).map_or(PointF::new(1.0, 0.0), |d| d.1)
2308    }
2309
2310    /// O caminho em ângulos retos entre os dois pontos (nas coordenadas do pai), dados os
2311    /// retângulos dos dois componentes.
2312    pub fn route(&self, from: RectF, to: RectF) -> Vec<PointF> {
2313        let p0 = PointF::new(from.x + from.width * self.from_at.0, from.y + from.height * self.from_at.1);
2314        let p1 = PointF::new(to.x + to.width * self.to_at.0, to.y + to.height * self.to_at.1);
2315        let (n0, n1) = (Self::normal(self.from_at), Self::normal(self.to_at));
2316        let s0 = PointF::new(p0.x + n0.x * Self::STUB, p0.y + n0.y * Self::STUB);
2317        let s1 = PointF::new(p1.x + n1.x * Self::STUB, p1.y + n1.y * Self::STUB);
2318        let mut points = vec![p0, s0];
2319        if n0.x != 0.0 {
2320            // Sai na horizontal: anda até o meio em x, desce/sobe, segue.
2321            let mx = (s0.x + s1.x) / 2.0;
2322            points.push(PointF::new(mx, s0.y));
2323            points.push(PointF::new(mx, s1.y));
2324        } else {
2325            let my = (s0.y + s1.y) / 2.0;
2326            points.push(PointF::new(s0.x, my));
2327            points.push(PointF::new(s1.x, my));
2328        }
2329        points.push(s1);
2330        points.push(p1);
2331        points.dedup_by(|a, b| (a.x - b.x).abs() < 0.01 && (a.y - b.y).abs() < 0.01);
2332        points
2333    }
2334}
2335
2336/// O arrasto declarado de um controle (fica fora do `ControlBase` comum: quase nenhum tem).
2337#[derive(Clone, Debug, Default, PartialEq)]
2338pub struct DragDecl {
2339    /// O que vai num arrasto que começa nele, sem handler (`"cliente:123"`: o tipo é o que vem
2340    /// antes do primeiro `:`); vazio: o arrasto declarado não leva nada.
2341    pub data: String,
2342    /// O texto que acompanha o mouse durante o arrasto; vazio: sem rótulo.
2343    pub label: String,
2344    /// Os tipos que este destino aceita, separados por `;` (`"cliente;produto"`); vazio: quem
2345    /// decide é o `on_drag_over`.
2346    pub drop_types: String,
2347    /// O `DragImage` que acompanha o cursor no arrasto (a imagem e o tamanho).
2348    pub image: Option<ComponentId>,
2349}
2350
2351/// Os textos raros do [`ControlBase`].
2352#[derive(Clone, Debug, Default)]
2353struct RareTexts {
2354    /// Um texto livre para o código (um id, um caminho, um JSON pequeno).
2355    tag_string: Box<str>,
2356    /// O nome que o leitor de tela fala, no lugar do texto do controle (um botão só com
2357    /// ícone, um campo sem rótulo); vazio: o texto do próprio controle.
2358    accessible_name: Box<str>,
2359}