Skip to main content

aylis_core/
component.rs

1//! O modelo de componentes: [`Component`] (o "TComponent") e [`ControlBase`] (os dados
2//! comuns de todo controle visual, como no `TControl`).
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 — funcionam como métodos `virtual` do Delphi: 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    /// (como no Delphi). `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 (como o `Color` do Delphi). 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    fn key_down(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
254        if let Some(inner) = self.inner_mut() {
255            inner.key_down(ctx, event);
256        }
257    }
258
259    fn key_up(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
260        if let Some(inner) = self.inner_mut() {
261            inner.key_up(ctx, event);
262        }
263    }
264
265    /// Tecla de atalho que ninguém tratou (como o `ShortCut` de um item de menu): o `Ui`
266    /// oferece a todos os componentes do form. Marque como tratado
267    /// ([`EventCtx::set_handled`]) se for sua.
268    fn shortcut(&mut self, ctx: &mut EventCtx<'_>, event: &KeyEvent) {
269        if let Some(inner) = self.inner_mut() {
270            inner.shortcut(ctx, event);
271        }
272    }
273
274    /// Os ganchos raros (barra de tarefas, bandeja, vista nativa, conector, arquivos soltos),
275    /// se este componente usa: devolva `Some(self)` e implemente [`PlatformHooks`].
276    fn platform_hooks(&self) -> Option<&dyn PlatformHooks> {
277        self.inner().and_then(|i| i.platform_hooks())
278    }
279
280    fn platform_hooks_mut(&mut self) -> Option<&mut dyn PlatformHooks> {
281        self.inner_mut().and_then(|i| i.platform_hooks_mut())
282    }
283
284    /// Os ganchos do designer (pontos que se arrastam dentro do controle), se este
285    /// componente usa: devolva `Some(self)` e implemente [`DesignHooks`].
286    fn design_hooks(&self) -> Option<&dyn DesignHooks> {
287        self.inner().and_then(|i| i.design_hooks())
288    }
289
290    fn design_hooks_mut(&mut self) -> Option<&mut dyn DesignHooks> {
291        self.inner_mut().and_then(|i| i.design_hooks_mut())
292    }
293
294    /// O ponto (coordenadas do controle, já sem a rotação) acerta o controle? Padrão: o
295    /// retângulo inteiro. As formas (círculo, estrela, linha...) respondem só na figura.
296    fn contains_point(&self, local: PointF, size: SizeF) -> bool {
297        self.inner().map_or(true, |i| i.contains_point(local, size))
298    }
299
300    /// Quanto o controle recebe o mouse além do próprio retângulo (as alças de uma moldura
301    /// desenhadas do lado de fora). Fora do retângulo, quem decide é o
302    /// [`contains_point`](Component::contains_point) (que recebe o ponto fora dele). Padrão: 0.
303    fn hit_slop(&self) -> f32 {
304        self.inner().map_or(0.0, |i| i.hit_slop())
305    }
306
307    /// Em que eixos o conteúdo rola (horizontal, vertical): o [`Ui::reveal`](crate::Ui::reveal)
308    /// rola estes contêineres para mostrar um controle de dentro (o campo sob o teclado).
309    fn scroll_axes(&self) -> (bool, bool) {
310        self.inner().map_or((false, false), |i| i.scroll_axes())
311    }
312
313    /// O componente edita texto. No celular, quando ele tem o foco a plataforma abre o
314    /// teclado virtual.
315    /// O que vai num arrasto que começa neste controle sem `drag_data` nem handler: as listas
316    /// e as grades mandam o item (o texto, a chave do registro) e o rótulo. `None`: nada.
317    fn drag_item(&self, _ui: &crate::Ui) -> Option<(String, String)> {
318        None
319    }
320
321    /// O que acompanha o cursor num arrasto, quando este componente é o `drag_image` de um
322    /// controle (o `DragImage`); `source` é o controle arrastado. `None`: nada.
323    fn drag_visual(&self, _ui: &crate::Ui, _source: ComponentId) -> Option<crate::DragVisual> {
324        None
325    }
326
327    /// O próprio componente recebe este arrasto (sem `accepts_drops` nem eventos): as abas
328    /// que passam de uma faixa para outra. Vale também quando ele é a origem (a aba que volta
329    /// para a faixa de onde saiu). Com `true`, recebe [`drop_hover`](Self::drop_hover),
330    /// [`drop_leave`](Self::drop_leave) e [`drop_receive`](Self::drop_receive).
331    fn drop_accepts(&self, _ui: &crate::Ui, _id: ComponentId, _data: &str) -> bool {
332        false
333    }
334
335    /// O arrasto aceito por [`drop_accepts`](Self::drop_accepts) está sobre o componente, no
336    /// ponto `position` (coordenadas dele); chamado a cada movimento.
337    fn drop_hover(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
338
339    /// O arrasto saiu de cima do componente (ou foi cancelado).
340    fn drop_leave(&mut self, _ctx: &mut EventCtx<'_>) {}
341
342    /// Soltou o arrasto aceito sobre o componente, em `position` (coordenadas dele).
343    fn drop_receive(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _position: PointF) {}
344
345    /// O arrasto que começou neste componente acabou (`on_drag_end` também dispara).
346    fn drag_ended(&mut self, _ctx: &mut EventCtx<'_>, _data: &str, _end: crate::DragEnd) {}
347
348    fn accepts_text(&self) -> bool {
349        self.inner().is_some_and(|i| i.accepts_text())
350    }
351
352    /// O controle usa a tecla (o Enter de um Memo, as setas de uma lista): ela não vira o
353    /// Tab do form (`tab_keys`).
354    fn captures_key(&self, event: &KeyEvent) -> bool {
355        self.inner().is_some_and(|i| i.captures_key(event))
356    }
357
358    /// A legenda com o `&` da letra do atalho (`"&Salvar"`: Alt+S), para os controles que
359    /// aceitam (botões, caixas de marcar, rótulos, grupos).
360    fn mnemonic_text(&self) -> Option<&str> {
361        self.inner().and_then(|i| i.mnemonic_text())
362    }
363
364    /// No Alt+letra, o foco vai para o primeiro filho (um grupo) em vez de clicar.
365    fn mnemonic_focuses_child(&self) -> bool {
366        self.inner().is_some_and(|i| i.mnemonic_focuses_child())
367    }
368
369    /// Texto digitado (já com acentos e IME resolvidos pela plataforma).
370    fn text_input(&mut self, ctx: &mut EventCtx<'_>, text: &str) {
371        if let Some(inner) = self.inner_mut() {
372            inner.text_input(ctx, text);
373        }
374    }
375
376    fn focus_enter(&mut self, ctx: &mut EventCtx<'_>) {
377        if let Some(inner) = self.inner_mut() {
378            inner.focus_enter(ctx);
379        }
380    }
381
382    fn focus_exit(&mut self, ctx: &mut EventCtx<'_>) {
383        if let Some(inner) = self.inner_mut() {
384            inner.focus_exit(ctx);
385        }
386    }
387
388    /// Uma propriedade publicada mudou por nome ([`Ui::set_prop`](crate::Ui::set_prop): JSON,
389    /// Object Inspector, protocolo). Como um *setter* do Delphi com efeitos colaterais: aqui
390    /// o componente tem o `Ui` (por exemplo, o TabControl mostra a aba nova).
391    fn property_changed(&mut self, ctx: &mut EventCtx<'_>, name: &str) {
392        if let Some(inner) = self.inner_mut() {
393            inner.property_changed(ctx, name);
394        }
395    }
396
397    /// Os argumentos do `on_change` quando a propriedade de valor `name` muda pelo código
398    /// ([`Ui::set_prop`](crate::Ui::set_prop): o acesso tipado, o protocolo), como na VCL;
399    /// `value` é o valor novo. O padrão é `EventArgs::Value(value)`: o controle que dispara
400    /// outro argumento quando o usuário muda (o texto do item, numa ComboBox) devolve o mesmo
401    /// aqui, e `None` não dispara. Quais propriedades contam: [`is_value_property`].
402    fn change_args(&self, name: &str, value: &PropValue) -> Option<EventArgs> {
403        match self.inner() {
404            Some(inner) => inner.change_args(name, value),
405            None => Some(EventArgs::Value(value.clone())),
406        }
407    }
408
409    /// A propriedade `name` só muda a pintura (o valor de um medidor, o giro de um 3D): o
410    /// `set_prop` dela repinta sem refazer o layout da tela. As do controle (cores, opacidade,
411    /// giro, deslocamento, cursor, dica) o `Ui` já conhece; aqui vão as do componente. Na
412    /// dúvida, `false` (refazer o layout nunca está errado, só custa).
413    fn paint_only_property(&self, name: &str) -> bool {
414        self.inner().is_some_and(|inner| inner.paint_only_property(name))
415    }
416
417    /// Intervalo do timer deste componente, em segundos (`None` = parado). O `Ui` dispara
418    /// `on_timer` a cada intervalo (como o `TTimer`); ver [`Ui::sync_timer`](crate::Ui::sync_timer).
419    fn timer_interval(&self) -> Option<f64> {
420        self.inner().and_then(|i| i.timer_interval())
421    }
422
423    /// Quanto o timer pode atrasar ([`TimerPrecision`](crate::TimerPrecision)).
424    fn timer_precision(&self) -> crate::TimerPrecision {
425        self.inner().map(|i| i.timer_precision()).unwrap_or_default()
426    }
427
428    /// O timer conta numa thread própria (não espera o laço da tela, que pode estar
429    /// ocupado); o `on_timer` chega à tela pelo [`Poster`](crate::Poster).
430    fn timer_background(&self) -> bool {
431        self.inner().is_some_and(|i| i.timer_background())
432    }
433
434    /// Quanto o disparo que vem a seguir atrasou, em segundos (antes de [`timer`](Component::timer)).
435    fn timer_late(&mut self, late: f64) {
436        if let Some(inner) = self.inner_mut() {
437            inner.timer_late(late);
438        }
439    }
440
441    /// Um quadro vai ser pintado (pedido com [`Ui::request_frames`](crate::Ui::request_frames)):
442    /// chamado antes da pintura, com o tempo do quadro em `ctx.ui.time()`, para um movimento
443    /// que acompanha o monitor (a rolagem com deslize). Devolve se quer o próximo quadro.
444    fn frame(&mut self, ctx: &mut EventCtx<'_>) -> bool {
445        self.inner_mut().is_some_and(|inner| inner.frame(ctx))
446    }
447
448    /// O timer venceu (ver [`timer_interval`](Component::timer_interval)). O padrão dispara o
449    /// evento `on_timer`.
450    fn timer(&mut self, ctx: &mut EventCtx<'_>) {
451        match self.inner_mut() {
452            Some(inner) => inner.timer(ctx),
453            None => ctx.fire("on_timer", EventArgs::None),
454        }
455    }
456
457    /// Organiza os filhos com `align = None` (grade, fluxo...): recebe a área livre (já
458    /// sem o padding e sem o que os filhos encaixados ocuparam) e o tamanho pedido e as
459    /// margens de cada filho; devolve o retângulo de cada um, na mesma ordem. `None` (o
460    /// padrão) = posição livre, como no FMX.
461    fn arrange(&self, area: RectF, children: &[ArrangeItem]) -> Option<Vec<RectF>> {
462        self.inner().and_then(|i| i.arrange(area, children))
463    }
464
465    /// A altura que o conteúdo pede na largura `width` (o texto de um Label quebrado nela),
466    /// para o `auto_size`. `None` (o padrão): o controle não mede o conteúdo (um contêiner
467    /// com `auto_size` fica da altura dos filhos encaixados em cima e embaixo).
468    fn auto_height(&self, ui: &crate::Ui, id: ComponentId, width: f32) -> Option<f32> {
469        self.inner().and_then(|i| i.auto_height(ui, id, width))
470    }
471
472    /// Uma camada aberta por outro (a lista de um ComboBox, as sugestões de um campo), posta
473    /// direto no form: o mouse apertado fora dela e fora de quem a abriu ([`dies_with`]) a
474    /// libera, mesmo que o clique caia onde não recebe foco (o fundo da tela, um rótulo). O
475    /// dono fica sabendo pelo [`notification`](Component::notification). Padrão: `false`.
476    ///
477    /// [`dies_with`]: Component::dies_with
478    fn closes_on_outside_press(&self) -> bool {
479        false
480    }
481
482    /// Este componente só vive enquanto `dies_with` existir: liberar aquele libera este
483    /// também. É o que a lista aberta de um ComboBox (uma camada sobre o form) usa: se o
484    /// ComboBox some (a tela foi refeita), a lista não fica órfã na tela.
485    fn dies_with(&self) -> Option<ComponentId> {
486        self.inner().and_then(|i| i.dies_with())
487    }
488
489    /// Os itens que o controle desenha sozinho (abas, linhas, itens de menu, células), para
490    /// leitores de tela, automação e testes ([`crate::automation`]). `id` é este controle.
491    fn access_items(&self, ui: &crate::Ui, id: ComponentId) -> Vec<crate::automation::AccessItem> {
492        self.inner().map_or_else(Vec::new, |i| i.access_items(ui, id))
493    }
494
495    /// Clica ou seleciona o item `index` de [`access_items`](Self::access_items). Devolve
496    /// `false` se não fez nada.
497    fn access_action(&mut self, ctx: &mut EventCtx<'_>, index: usize, action: crate::automation::ItemAction) -> bool {
498        self.inner_mut().is_some_and(|i| i.access_action(ctx, index, action))
499    }
500
501    /// Prende o controle a um irmão (mesmo pai): devolve o alvo e o ponto dele onde o
502    /// centro deste controle fica (`0..1` na largura e na altura: `(1, 0)` é o canto de
503    /// cima à direita). É o que deixa um `Badge` no canto de um botão.
504    fn attach(&self) -> Option<(ComponentId, f32, f32)> {
505        self.inner().and_then(|i| i.attach())
506    }
507
508    /// Dados extras de um evento que está sendo entregue (chave e texto), para quem recebe
509    /// os eventos fora do Rust: o protocolo os manda no `info` do evento (o `on_message` do
510    /// WebView manda a URL de quem mandou).
511    fn event_info(&self, event: &str) -> Vec<(&'static str, String)> {
512        self.inner().map(|i| i.event_info(event)).unwrap_or_default()
513    }
514
515    /// Mensagem enviada por outro componente com [`Ui::send_message`](crate::Ui::send_message)
516    /// (como o `Perform`/mensagens do Delphi). O tipo da mensagem é livre: cada camada
517    /// (por exemplo a de dados) define as suas e o componente faz `downcast_ref`.
518    fn message(&mut self, ctx: &mut EventCtx<'_>, message: &dyn Any) {
519        if let Some(inner) = self.inner_mut() {
520            inner.message(ctx, message);
521        }
522    }
523
524    /// Os métodos que [`invoke`](Component::invoke) atende, com os tipos (o catálogo do
525    /// acesso tipado nas linguagens: `frmPaint.pcDesenho.Undo`).
526    fn methods(&self) -> &'static [MethodInfo] {
527        &[]
528    }
529
530    /// Um método pelo nome ([`Ui::invoke`](crate::Ui::invoke), o comando `invoke` do
531    /// protocolo): o que não é propriedade, como `undo`, `clear` ou `save`. Funciona igual
532    /// em Rust e nas outras linguagens (pelo protocolo). Devolve o resultado ou o erro.
533    fn invoke(&mut self, ctx: &mut EventCtx<'_>, method: &str, args: &[PropValue]) -> std::result::Result<PropValue, String> {
534        let class = self.class_name();
535        match self.inner_mut() {
536            Some(inner) => inner.invoke(ctx, method, args),
537            None => Err(format!("{class} não tem o método '{method}'")),
538        }
539    }
540
541}
542
543/// Os ganchos que só uns poucos componentes usam: fora do [`Component`], para a lista de
544/// métodos de um controle comum ficar curta. O componente que usa devolve `Some(self)` em
545/// [`Component::platform_hooks`] e [`Component::platform_hooks_mut`].
546pub trait PlatformHooks {
547    /// O que este componente quer no botão da barra de tarefas (o `Taskbar`).
548    fn taskbar(&self) -> Option<crate::taskbar::TaskbarSpec> {
549        None
550    }
551
552    /// Ícone na bandeja do sistema que este componente quer mostrar (o `TrayIcon`).
553    fn tray(&self) -> Option<crate::tray::TraySpec> {
554        None
555    }
556
557    /// Vista nativa que a plataforma põe por cima do controle (um navegador embutido...).
558    /// O controle continua sendo pintado por baixo (o que aparece onde a plataforma não
559    /// tem a vista, como no designer).
560    fn native_view(&self) -> Option<NativeView> {
561        None
562    }
563
564    /// Comandos pendentes para a vista nativa (a plataforma pega e executa).
565    fn take_native_commands(&self) -> Vec<NativeCommand> {
566        Vec::new()
567    }
568
569    /// Um conector (cano, fio) preso a dois irmãos: os pontos de ligação deles (`0..1` na
570    /// largura e na altura). O layout põe o conector em volta do caminho entre os dois; ele
571    /// segue os componentes quando eles mudam de lugar.
572    fn connection(&self) -> Option<Connection> {
573        None
574    }
575
576    /// Arquivos soltos sobre o controle (arrastados do sistema). Devolve `true` se aceitou
577    /// (senão eles vão para o pai).
578    fn files_dropped(&mut self, _ctx: &mut EventCtx<'_>, _paths: &[String]) -> bool {
579        false
580    }
581}
582
583/// Os ganchos do designer: pontos que se arrastam dentro do controle (o separador das
584/// colunas de uma grade). O componente que usa devolve `Some(self)` em
585/// [`Component::design_hooks`] e [`Component::design_hooks_mut`].
586pub trait DesignHooks {
587    /// Um ponto que se arrasta dentro do controle, em coordenadas do controle. Devolve o
588    /// índice do ponto.
589    fn design_grip(&self, _local: PointF) -> Option<usize> {
590        None
591    }
592
593    /// O ponto `grip` foi arrastado `delta` desde o começo (`begin` no primeiro movimento).
594    /// Devolve a propriedade a gravar (o designer grava, com o desfazer): o componente
595    /// (`None` = este), o nome e o valor.
596    fn design_drag(&mut self, _grip: usize, _delta: PointF, _begin: bool) -> Option<(Option<ComponentId>, &'static str, PropValue)> {
597        None
598    }
599}
600
601/// Um filho para [`Component::arrange`]: o tamanho pedido e as margens.
602#[derive(Clone, Copy, Debug, PartialEq)]
603pub struct ArrangeItem {
604    pub id: ComponentId,
605    pub size: SizeF,
606    /// Já com a escala de espaços da vista ativa.
607    pub margins: Bounds,
608    /// Quantas colunas o filho pede numa grade ([`ControlBase::column_span`]).
609    pub span: u32,
610    /// A escala de espaços da vista ativa do form: o contêiner multiplica os espaços dele
611    /// (`gap`) por ela.
612    pub spacing: f32,
613}
614
615impl ArrangeItem {
616    /// O item de um controle.
617    pub fn of(id: ComponentId, cb: &ControlBase) -> Self {
618        ArrangeItem { id, size: SizeF::new(cb.width(), cb.height()), margins: cb.margins(), span: cb.column_span(), spacing: cb.spacing_scale() }
619    }
620}
621
622/// Uma vista nativa pedida por um componente ([`Component::native_view`]).
623#[derive(Clone, Debug, PartialEq)]
624pub enum NativeView {
625    /// Navegador embutido: abre `url` ou, sem ela, mostra `html`. Quando `generation`
626    /// muda, a plataforma carrega de novo. `navigation`: os endereços (origens ou prefixos)
627    /// para onde a página pode navegar (vazia, todos); `sandbox`: o atributo do `<iframe>`
628    /// no navegador.
629    Web { url: String, html: String, generation: u64, navigation: Vec<String>, sandbox: String },
630}
631
632/// Mensagem de uma página do navegador embutido para o app: o texto e a URL de quem mandou.
633/// A plataforma entrega ao componente com [`Ui::send_message`](crate::Ui::send_message); ele
634/// decide se a origem vale e dispara o `on_message`.
635#[derive(Clone, Debug, PartialEq)]
636pub struct WebMessage {
637    pub text: String,
638    pub url: String,
639}
640
641/// A navegação do navegador embutido para `url` é permitida pela lista (o
642/// `allowed_navigation` do WebView)? O conteúdo interno (`about:`, `data:`) sempre. Um item só
643/// com a origem (`https://site.com`) libera o site inteiro; com caminho, só o que começa por ele.
644pub fn navigation_allowed(allowed: &[String], url: &str) -> bool {
645    allowed.is_empty()
646        || url.starts_with("about:")
647        || url.starts_with("data:")
648        || allowed.iter().any(|a| {
649            let a = a.trim_end_matches('/');
650            url == a || url.starts_with(&format!("{a}/")) || url.starts_with(&format!("{a}?")) || (a.matches('/').count() <= 2 && url_origin(url) == url_origin(a))
651        })
652}
653
654/// A origem (`https://site.com:8080`) de um endereço, para comparar com uma lista.
655pub fn url_origin(url: &str) -> String {
656    let Some((scheme, rest)) = url.split_once("://") else { return url.to_string() };
657    let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
658    format!("{}://{}", scheme.to_ascii_lowercase(), host.to_ascii_lowercase())
659}
660
661/// Um método de [`Component::invoke`]: o nome, o tipo de cada argumento e o do resultado
662/// (`None`: não devolve nada que interesse).
663#[derive(Clone, Copy, Debug, PartialEq)]
664pub struct MethodInfo {
665    pub name: &'static str,
666    pub args: &'static [PropKind],
667    pub returns: Option<PropKind>,
668    /// O nome de cada argumento (`path`), que o acesso tipado gerado usa nas assinaturas;
669    /// vazio: sem nome (o gerado numera, `a1`, `a2`).
670    pub params: &'static [&'static str],
671}
672
673impl MethodInfo {
674    pub const fn new(name: &'static str, args: &'static [PropKind], returns: Option<PropKind>) -> Self {
675        Self { name, args, returns, params: &[] }
676    }
677
678    /// Os nomes dos argumentos, na ordem de `args`:
679    /// `MethodInfo::new("save_to", &[PropKind::String], None).params(&["path"])`.
680    pub const fn params(self, names: &'static [&'static str]) -> Self {
681        Self { params: names, ..self }
682    }
683}
684
685/// Comando para uma vista nativa.
686#[derive(Clone, Debug, PartialEq)]
687pub enum NativeCommand {
688    /// Roda JavaScript na página.
689    Eval(String),
690    Back,
691    Forward,
692    Reload,
693}
694
695/// Uma vista nativa a mostrar: o controle, onde (relativo ao form) e o que é.
696#[derive(Clone, Debug, PartialEq)]
697pub struct NativeViewSlot {
698    pub id: ComponentId,
699    pub rect: crate::RectF,
700    /// A parte que aparece (os pais que recortam, como uma caixa rolada, cortam o resto),
701    /// nas mesmas coordenadas de `rect`; `None`: inteira.
702    pub clip: Option<crate::RectF>,
703    pub visible: bool,
704    pub view: NativeView,
705    pub commands: Vec<NativeCommand>,
706}
707
708/// Todas as propriedades publicadas de um componente: as da classe, as das camadas de
709/// composição e as do [`ControlBase`] (sem `name` nem os eventos ligados no `Ui`).
710///
711/// Trabalha direto no componente, sem precisar do [`Ui`](crate::Ui): serve, por exemplo,
712/// para ler os valores padrão de uma instância nova da classe.
713pub fn prop_infos_of(component: &dyn Component) -> Vec<PropInfo> {
714    let mut out: Vec<PropInfo> = Vec::new();
715    // Os nomes já vistos num conjunto: procurar na lista a cada propriedade era quadrático
716    // (~90 por controle), e isso roda para cada componente no índice de referências.
717    let mut seen = std::collections::HashSet::new();
718    let mut push = |info: &PropInfo| {
719        if seen.insert(info.name) {
720            out.push(*info);
721        }
722    };
723    let mut layer = Some(component);
724    while let Some(l) = layer {
725        l.props().iter().for_each(&mut push);
726        layer = l.inner();
727    }
728    if component.control().is_some() {
729        ControlBase::PROPS.iter().for_each(&mut push);
730    }
731    out
732}
733
734/// A descrição de uma propriedade pelo nome, na mesma ordem de [`prop_infos_of`] (a camada
735/// de fora vence), sem montar a lista inteira: todo `get_prop`/`set_prop` passa por aqui.
736pub fn prop_info_of(component: &dyn Component, name: &str) -> Option<PropInfo> {
737    let mut layer = Some(component);
738    while let Some(l) = layer {
739        if let Some(info) = l.props().iter().find(|p| p.name == name) {
740            return Some(*info);
741        }
742        layer = l.inner();
743    }
744    if component.control().is_some() {
745        return ControlBase::PROPS.iter().find(|p| p.name == name).copied();
746    }
747    None
748}
749
750/// Lê uma propriedade (que não seja evento) direto no componente, procurando em todas as
751/// camadas e no [`ControlBase`].
752/// As propriedades que são "o valor" de um controle (o que o usuário muda e o `on_change`
753/// avisa), quando publicadas em `Data` (ou `Runtime`, como o `value` da ComboBox).
754pub const VALUE_PROPERTIES: [&str; 19] = [
755    "text", "checked", "value", "item_index", "selected", "date", "end_date", "time", "color", "files", "html", "index", "page", "hotkey",
756    "angle", "pressed", "position", "low", "high",
757];
758
759/// Mudar a propriedade pelo código dispara o `on_change` do controle (se ele tiver um),
760/// como na VCL: as de [`VALUE_PROPERTIES`] (fora das de aparência, como o `text` de um
761/// CheckBox, que é a legenda), a aba escolhida e o aberto/fechado.
762pub fn is_value_property(info: &PropInfo) -> bool {
763    match info.name {
764        "tab_index" | "expanded" => true,
765        name => matches!(info.category, "Data" | "Runtime") && VALUE_PROPERTIES.contains(&name),
766    }
767}
768
769pub fn read_prop(component: &dyn Component, name: &str) -> Option<PropValue> {
770    let mut layer = Some(component);
771    while let Some(l) = layer {
772        if let Some(v) = l.get_prop(name) {
773            return Some(v);
774        }
775        layer = l.inner();
776    }
777    component.control().and_then(|cb| cb.get_prop(name))
778}
779
780/// Referência guardada pelas âncoras: tamanho do pai e retângulo do controle no momento
781/// em que a posição foi definida.
782#[derive(Clone, Copy, Debug, PartialEq)]
783pub(crate) struct AnchorRef {
784    pub(crate) parent: SizeF,
785    pub(crate) rect: RectF,
786}
787
788/// Dados comuns de todo controle visual (o que o `TControl` tem).
789///
790/// `left`, `top`, `width` e `height` são os valores **pedidos**. A posição e o tamanho
791/// **reais**, calculados pelo layout (Align/Anchors), ficam em [`bounds`](Self::bounds).
792#[derive(Clone, Debug)]
793pub struct ControlBase {
794    left: f32,
795    top: f32,
796    width: f32,
797    height: f32,
798    margins: Bounds,
799    padding: Bounds,
800    align: Align,
801    anchors: Anchors,
802    visible: bool,
803    enabled: bool,
804    hit_test: bool,
805    clip_children: bool,
806    /// A roda do mouse em cima dele fica com ele (não rola os contêineres de fora), mesmo
807    /// sem ele rolar: uma prévia que dá zoom com a roda, um mapa, um gráfico.
808    captures_wheel: bool,
809    can_focus: bool,
810    draggable: bool,
811    accepts_drops: bool,
812    /// O arrasto declarado (sem handler): o que vai (`"cliente:123"`, o tipo antes do primeiro
813    /// `:`) e o rótulo que acompanha o mouse; os tipos que este destino aceita (`"cliente;produto"`).
814    drag: Option<Box<DragDecl>>,
815    tab_stop: bool,
816    pan_on_touch: bool,
817    /// Menu de contexto (como o `PopupMenu` do `TControl`): abre no clique direito.
818    pub(crate) popup_menu: Option<ComponentId>,
819    cursor: CursorShape,
820    opacity: f32,
821    /// Giro em graus, em torno do centro (o `RotationAngle` do FMX).
822    rotation: f32,
823    /// Deslocamento só do desenho (não muda o layout): animações e transições.
824    translate: PointF,
825    /// O desenho dele e dos filhos guardado numa imagem, refeita só quando algo lá dentro
826    /// muda (o `CacheAsBitmap`): um painel pesado que desliza ou some aos poucos.
827    cache_layer: bool,
828    /// Proporção fixa (largura ÷ altura; 0 = livre), como o `VResponsive` do Vuetify.
829    aspect_ratio: f32,
830    /// Largura máxima (0 = sem limite), como o `max-width` do CSS com margem automática.
831    max_width: f32,
832    /// Largura mínima, altura mínima e máxima (0 = sem limite), como o `Constraints` da VCL.
833    min_width: f32,
834    min_height: f32,
835    max_height: f32,
836    /// Encaixado: estica na faixa ou fica com o próprio tamanho no começo, meio ou fim.
837    self_align: SelfAlign,
838    /// A altura sai do conteúdo (como o `AutoSize` do Delphi): veja [`ControlBase::auto_size`].
839    auto_size: bool,
840    /// Quantas colunas ocupa num `GridLayout` (o `colspan`; 1 ou 0: uma).
841    column_span: u32,
842    /// As escalas de fonte e de espaços da vista ativa do form (postas pelo layout; veja
843    /// `views.rs`): os getters de `margins`/`padding` e a fonte da pintura já saem escalados.
844    pub(crate) text_scale: f32,
845    pub(crate) spacing_scale: f32,
846    /// Sombra do controle; quando há, vale no lugar da sombra do estilo.
847    shadow: Option<crate::canvas::Shadow>,
848    tag: i64,
849    style: String,
850    /// Tema próprio (pelo nome), que vale também para os filhos. Vazio = o do pai.
851    theme: String,
852    /// Dica mostrada com o mouse parado em cima (o `Hint` do Delphi).
853    hint: String,
854    state: ControlState,
855    pub(crate) bounds: RectF,
856    pub(crate) anchor_ref: Option<AnchorRef>,
857    /// Controle flutuante preso a outro (ver [`Ui::follow`](crate::Ui::follow)): o alvo e a
858    /// distância do canto dele (medida no primeiro layout).
859    pub(crate) follow: Option<(ComponentId, Option<PointF>)>,
860    /// `visible` desligado pela propriedade no designer: o controle continua no layout e
861    /// clicável, pintado translúcido (em execução ele some).
862    pub(crate) design_hidden: bool,
863    /// Só aparece no designer (o relatório: em execução, só a visualização o mostra).
864    pub(crate) design_only: bool,
865    /// Fica da esquerda para a direita mesmo com a interface espelhada (árabe), ele e os
866    /// filhos: o designer da IDE, um gráfico, um mapa.
867    pub(crate) keep_left_to_right: bool,
868    /// As cores próprias (vazio = as do tema).
869    pub(crate) colors: ColorOverride,
870    /// A fonte própria (o `Font` do `TControl`); o que ficar sem valor vem do pai.
871    pub(crate) font: FontOverride,
872    /// Quanto o conteúdo está rolado (como o `ViewportPosition` do FMX).
873    scroll_offset: PointF,
874    /// A rolagem com que o último layout pôs os filhos: a posição de um filho no conteúdo é a
875    /// dele mais esta, mesmo antes do próximo layout.
876    pub(crate) laid_out_scroll: PointF,
877    /// Faixas da tela cobertas pelo sistema (só no form; ver [`Ui::set_safe_area`](crate::Ui::set_safe_area)).
878    pub(crate) safe_area: Bounds,
879    /// Tamanho ocupado pelos filhos, calculado no layout (sem a rolagem).
880    pub(crate) content_size: SizeF,
881}
882
883impl Default for ControlBase {
884    fn default() -> Self {
885        Self::new(100.0, 100.0)
886    }
887}
888
889impl ControlBase {
890    /// Propriedades publicadas comuns a todos os controles.
891    pub const PROPS: &'static [PropInfo] = &[
892        PropInfo::new("left", PropKind::Float, "Layout"),
893        PropInfo::new("top", PropKind::Float, "Layout"),
894        PropInfo::new("width", PropKind::Float, "Layout"),
895        PropInfo::new("height", PropKind::Float, "Layout"),
896        PropInfo::new("align", PropKind::Enum(<Align as crate::prop::PropEnum>::NAMES), "Layout"),
897        PropInfo::new("anchors", PropKind::Set(&Anchors::NAMES), "Layout"),
898        PropInfo::new("margins", PropKind::Bounds, "Layout"),
899        PropInfo::new("padding", PropKind::Bounds, "Layout"),
900        PropInfo::new("visible", PropKind::Bool, "Behavior"),
901        PropInfo::new("enabled", PropKind::Bool, "Behavior"),
902        PropInfo::new("hit_test", PropKind::Bool, "Behavior"),
903        PropInfo::new("clip_children", PropKind::Bool, "Behavior"),
904        PropInfo::new("captures_wheel", PropKind::Bool, "Behavior"),
905        PropInfo::new("can_focus", PropKind::Bool, "Behavior"),
906        PropInfo::new("draggable", PropKind::Bool, "Behavior"),
907        PropInfo::new("accepts_drops", PropKind::Bool, "Behavior"),
908        PropInfo::new("drag_data", PropKind::String, "Behavior"),
909        PropInfo::new("drag_label", PropKind::String, "Behavior"),
910        PropInfo::new("drag_image", PropKind::Component, "Behavior"),
911        PropInfo::new("drop_types", PropKind::String, "Behavior"),
912        PropInfo::new("tab_stop", PropKind::Bool, "Behavior"),
913        PropInfo::new("cursor", PropKind::Enum(<CursorShape as crate::prop::PropEnum>::NAMES), "Behavior"),
914        PropInfo::new("opacity", PropKind::Float, "Appearance"),
915        PropInfo::new("cache_layer", PropKind::Bool, "Appearance"),
916        PropInfo::new("rotation", PropKind::Angle, "Layout"),
917        PropInfo::new("translate_x", PropKind::Float, "Appearance"),
918        PropInfo::new("translate_y", PropKind::Float, "Appearance"),
919        PropInfo::new("aspect_ratio", PropKind::Float, "Layout"),
920        PropInfo::new("max_width", PropKind::Float, "Layout"),
921        PropInfo::new("min_width", PropKind::Float, "Layout"),
922        PropInfo::new("min_height", PropKind::Float, "Layout"),
923        PropInfo::new("max_height", PropKind::Float, "Layout"),
924        PropInfo::new("self_align", PropKind::Enum(<SelfAlign as crate::prop::PropEnum>::NAMES), "Layout"),
925        PropInfo::new("auto_size", PropKind::Bool, "Layout"),
926        PropInfo::new("column_span", PropKind::Int, "Layout"),
927        PropInfo::new("shadow", PropKind::Shadow, "Appearance"),
928        PropInfo::new("style", PropKind::String, "Appearance"),
929        PropInfo::new("theme", PropKind::String, "Appearance"),
930        PropInfo::new("fill", PropKind::Color, "Appearance"),
931        PropInfo::new("border_color", PropKind::Color, "Appearance"),
932        PropInfo::new("text_color", PropKind::Color, "Appearance"),
933        PropInfo::new("accent_color", PropKind::Color, "Appearance"),
934        PropInfo::new("success_color", PropKind::Color, "Appearance"),
935        PropInfo::new("warning_color", PropKind::Color, "Appearance"),
936        PropInfo::new("danger_color", PropKind::Color, "Appearance"),
937        PropInfo::new("font_family", PropKind::String, "Font"),
938        PropInfo::new("font_size", PropKind::Float, "Font"),
939        PropInfo::new("font_weight", PropKind::Enum(&FONT_WEIGHTS), "Font"),
940        PropInfo::new("font_italic", PropKind::Bool, "Font"),
941        PropInfo::new("font_underline", PropKind::Bool, "Font"),
942        PropInfo::new("font_strikeout", PropKind::Bool, "Font"),
943        PropInfo::new("hint", PropKind::String, "Behavior"),
944        PropInfo::new("tag", PropKind::Int, "Misc"),
945        PropInfo::new("popup_menu", PropKind::Component, "Behavior"),
946        PropInfo::new("on_click", PropKind::Event, "Events"),
947        PropInfo::new("on_dbl_click", PropKind::Event, "Events"),
948        PropInfo::new("on_long_press", PropKind::Event, "Events"),
949        PropInfo::new("on_pointer_down", PropKind::Event, "Events"),
950        PropInfo::new("on_pointer_up", PropKind::Event, "Events"),
951        PropInfo::new("on_pointer_move", PropKind::Event, "Events"),
952        PropInfo::new("on_pointer_enter", PropKind::Event, "Events"),
953        PropInfo::new("on_pointer_leave", PropKind::Event, "Events"),
954        PropInfo::new("on_wheel", PropKind::Event, "Events"),
955        PropInfo::new("on_gesture", PropKind::Event, "Events"),
956        PropInfo::new("on_key_down", PropKind::Event, "Events"),
957        PropInfo::new("on_key_press", PropKind::Event, "Events"),
958        PropInfo::new("on_key_up", PropKind::Event, "Events"),
959        PropInfo::new("on_enter", PropKind::Event, "Events"),
960        PropInfo::new("on_exit", PropKind::Event, "Events"),
961        PropInfo::new("on_resize", PropKind::Event, "Events"),
962        PropInfo::new("on_drag_start", PropKind::Event, "Events"),
963        PropInfo::new("on_drag_over", PropKind::Event, "Events"),
964        PropInfo::new("on_drag_drop", PropKind::Event, "Events"),
965        PropInfo::new("on_drag_end", PropKind::Event, "Events"),
966    ];
967
968    pub fn new(width: f32, height: f32) -> Self {
969        Self {
970            left: 0.0,
971            top: 0.0,
972            width,
973            height,
974            margins: Bounds::ZERO,
975            padding: Bounds::ZERO,
976            align: Align::None,
977            anchors: Anchors::default(),
978            visible: true,
979            enabled: true,
980            hit_test: true,
981            clip_children: false,
982            captures_wheel: false,
983            can_focus: false,
984            draggable: false,
985            accepts_drops: false,
986            drag: None,
987            tab_stop: true,
988            pan_on_touch: true,
989            popup_menu: None,
990            cursor: CursorShape::Default,
991            opacity: 1.0,
992            rotation: 0.0,
993            translate: PointF::ZERO,
994            cache_layer: false,
995            aspect_ratio: 0.0,
996            max_width: 0.0,
997            min_width: 0.0,
998            min_height: 0.0,
999            max_height: 0.0,
1000            self_align: SelfAlign::Stretch,
1001            auto_size: false,
1002            column_span: 1,
1003            text_scale: 1.0,
1004            spacing_scale: 1.0,
1005            shadow: None,
1006            tag: 0,
1007            style: String::new(),
1008            theme: String::new(),
1009            hint: String::new(),
1010            state: ControlState::default(),
1011            bounds: RectF::new(0.0, 0.0, width, height),
1012            anchor_ref: None,
1013            follow: None,
1014            design_hidden: false,
1015            design_only: false,
1016            keep_left_to_right: false,
1017            colors: ColorOverride::default(),
1018            font: FontOverride::default(),
1019            scroll_offset: PointF::ZERO,
1020            laid_out_scroll: PointF::ZERO,
1021            content_size: SizeF::ZERO,
1022            safe_area: Bounds::default(),
1023        }
1024    }
1025
1026    // ----- leitura -----
1027
1028    pub fn left(&self) -> f32 {
1029        self.left
1030    }
1031
1032    pub fn top(&self) -> f32 {
1033        self.top
1034    }
1035
1036    pub fn width(&self) -> f32 {
1037        self.width
1038    }
1039
1040    pub fn height(&self) -> f32 {
1041        self.height
1042    }
1043
1044    pub fn position(&self) -> PointF {
1045        PointF::new(self.left, self.top)
1046    }
1047
1048    pub fn size(&self) -> SizeF {
1049        SizeF::new(self.width, self.height)
1050    }
1051
1052    /// As margens que valem no layout (com a escala de espaços da vista ativa; a propriedade
1053    /// guarda a do desenho).
1054    pub fn margins(&self) -> Bounds {
1055        if self.spacing_scale == 1.0 { self.margins } else { self.margins.scaled(self.spacing_scale) }
1056    }
1057
1058    /// O padding que vale no layout, como as [`margins`](Self::margins).
1059    pub fn padding(&self) -> Bounds {
1060        if self.spacing_scale == 1.0 { self.padding } else { self.padding.scaled(self.spacing_scale) }
1061    }
1062
1063    pub fn align(&self) -> Align {
1064        self.align
1065    }
1066
1067    pub fn anchors(&self) -> Anchors {
1068        self.anchors
1069    }
1070
1071    pub fn visible(&self) -> bool {
1072        self.visible
1073    }
1074
1075    /// Só aparece no designer (em execução não é pintado nem recebe o mouse).
1076    pub fn design_only(&self) -> bool {
1077        self.design_only
1078    }
1079
1080    /// As cores próprias.
1081    pub fn colors(&self) -> ColorOverride {
1082        self.colors
1083    }
1084
1085    pub fn set_colors(&mut self, colors: ColorOverride) -> &mut Self {
1086        self.colors = colors;
1087        self
1088    }
1089
1090    pub fn set_design_only(&mut self, on: bool) -> &mut Self {
1091        self.design_only = on;
1092        self
1093    }
1094
1095    /// Fica da esquerda para a direita (ele e os filhos) com a interface espelhada.
1096    pub fn keep_left_to_right(&self) -> bool {
1097        self.keep_left_to_right
1098    }
1099
1100    pub fn set_keep_left_to_right(&mut self, on: bool) -> &mut Self {
1101        self.keep_left_to_right = on;
1102        self
1103    }
1104
1105    pub fn enabled(&self) -> bool {
1106        self.enabled
1107    }
1108
1109    pub fn hit_test(&self) -> bool {
1110        self.hit_test
1111    }
1112
1113    pub fn clip_children(&self) -> bool {
1114        self.clip_children
1115    }
1116
1117    pub fn captures_wheel(&self) -> bool {
1118        self.captures_wheel
1119    }
1120
1121    /// Pode receber o foco do teclado (como `CanFocus`).
1122    /// Arrastável (o `DragMode = dmAutomatic` do FMX): passar de alguns pontos com o
1123    /// botão pressionado dispara `on_drag_start`, e o handler começa o arrasto com
1124    /// [`Ui::begin_drag`](crate::Ui::begin_drag).
1125    pub fn draggable(&self) -> bool {
1126        self.draggable
1127    }
1128
1129    pub fn set_draggable(&mut self, v: bool) -> &mut Self {
1130        self.draggable = v;
1131        self
1132    }
1133
1134    /// Recebe o que é arrastado: `on_drag_over` ao entrar (o handler recusa com
1135    /// [`Ui::reject_drop`](crate::Ui::reject_drop)) e `on_drag_drop` ao soltar.
1136    pub fn accepts_drops(&self) -> bool {
1137        self.accepts_drops
1138    }
1139
1140    pub fn set_accepts_drops(&mut self, v: bool) -> &mut Self {
1141        self.accepts_drops = v;
1142        self
1143    }
1144
1145    /// O que vai no arrasto declarado (vazio: só com o `on_drag_start`).
1146    pub fn drag_data(&self) -> &str {
1147        self.drag.as_ref().map_or("", |d| d.data.as_str())
1148    }
1149
1150    pub fn drag_label(&self) -> &str {
1151        self.drag.as_ref().map_or("", |d| d.label.as_str())
1152    }
1153
1154    /// O `DragImage` do arrasto (a imagem que acompanha o cursor).
1155    pub fn drag_image(&self) -> Option<ComponentId> {
1156        self.drag.as_ref().and_then(|d| d.image)
1157    }
1158
1159    /// O `DragImage` foi liberado: a referência sai.
1160    pub(crate) fn forget_drag_image(&mut self, doomed: &[ComponentId]) {
1161        if let Some(d) = self.drag.as_mut().filter(|d| d.image.is_some_and(|i| doomed.contains(&i))) {
1162            d.image = None;
1163        }
1164    }
1165
1166    /// Os tipos aceitos ao soltar (vazio: decide o `on_drag_over`).
1167    pub fn drop_types(&self) -> &str {
1168        self.drag.as_ref().map_or("", |d| d.drop_types.as_str())
1169    }
1170
1171    fn drag_decl(&mut self) -> &mut DragDecl {
1172        self.drag.get_or_insert_with(Default::default)
1173    }
1174
1175    pub fn can_focus(&self) -> bool {
1176        self.can_focus
1177    }
1178
1179    /// Participa da navegação com Tab (como `TabStop`).
1180    pub fn tab_stop(&self) -> bool {
1181        self.tab_stop
1182    }
1183
1184    /// Menu de contexto do controle.
1185    pub fn popup_menu(&self) -> Option<ComponentId> {
1186        self.popup_menu
1187    }
1188
1189    pub fn set_popup_menu(&mut self, menu: Option<ComponentId>) -> &mut Self {
1190        self.popup_menu = menu;
1191        self
1192    }
1193
1194    /// Ver [`set_pan_on_touch`](Self::set_pan_on_touch).
1195    pub fn pan_on_touch(&self) -> bool {
1196        self.pan_on_touch
1197    }
1198
1199    /// Cursor do mouse sobre o controle. `Default` herda o do pai.
1200    pub fn cursor(&self) -> CursorShape {
1201        self.cursor
1202    }
1203
1204    pub fn opacity(&self) -> f32 {
1205        self.opacity
1206    }
1207
1208    /// O desenho guardado numa imagem (veja o campo).
1209    pub fn cache_layer(&self) -> bool {
1210        self.cache_layer
1211    }
1212
1213    pub fn set_cache_layer(&mut self, on: bool) -> &mut Self {
1214        self.cache_layer = on;
1215        self
1216    }
1217
1218    /// Giro em graus, em torno do centro. Só a pintura gira; o clique usa o retângulo
1219    /// sem giro.
1220    pub fn rotation(&self) -> f32 {
1221        self.rotation
1222    }
1223
1224    pub fn shadow(&self) -> Option<crate::canvas::Shadow> {
1225        self.shadow
1226    }
1227
1228    /// Proporção fixa (largura ÷ altura); 0 = livre. No layout, a altura sai da largura
1229    /// (Top, Bottom, Horizontal, None), a largura sai da altura (Left, Right, Vertical) ou
1230    /// o controle cabe na área mantendo a proporção (Client, Center).
1231    pub fn aspect_ratio(&self) -> f32 {
1232        self.aspect_ratio
1233    }
1234
1235    pub fn set_aspect_ratio(&mut self, ratio: f32) -> &mut Self {
1236        self.aspect_ratio = if ratio.is_finite() { ratio.max(0.0) } else { 0.0 };
1237        self
1238    }
1239
1240    /// Largura máxima (0 = sem limite). O controle não passa dela; alinhado em cima, embaixo ou
1241    /// no cliente, fica no meio da área (o conteúdo de uma página que não se espalha numa tela
1242    /// larga). No form, é a largura máxima da janela.
1243    pub fn max_width(&self) -> f32 {
1244        self.max_width
1245    }
1246
1247    pub fn set_max_width(&mut self, width: f32) -> &mut Self {
1248        self.max_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1249        self
1250    }
1251
1252    /// Largura mínima (0 = sem limite). O layout não deixa o controle mais estreito que ela,
1253    /// mesmo alinhado (`top`, `client`...): o que passar da área do pai fica cortado (ou rola,
1254    /// num ScrollBox), e um texto com `wrap` para de quebrar nessa largura. No form, é a
1255    /// largura mínima da janela.
1256    pub fn min_width(&self) -> f32 {
1257        self.min_width
1258    }
1259
1260    pub fn set_min_width(&mut self, width: f32) -> &mut Self {
1261        self.min_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1262        self
1263    }
1264
1265    /// Altura mínima (0 = sem limite), como a [`min_width`](Self::min_width).
1266    pub fn min_height(&self) -> f32 {
1267        self.min_height
1268    }
1269
1270    pub fn set_min_height(&mut self, height: f32) -> &mut Self {
1271        self.min_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1272        self
1273    }
1274
1275    /// Altura máxima (0 = sem limite). No form, é a altura máxima da janela.
1276    pub fn max_height(&self) -> f32 {
1277        self.max_height
1278    }
1279
1280    pub fn set_max_height(&mut self, height: f32) -> &mut Self {
1281        self.max_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1282        self
1283    }
1284
1285    /// A largura que o controle ocupa numa faixa de `available` (com a `max_width` e a
1286    /// `min_width`; a mínima vence).
1287    pub fn clamp_width(&self, available: f32) -> f32 {
1288        let w = if self.max_width > 0.0 { available.min(self.max_width) } else { available };
1289        w.max(self.min_width)
1290    }
1291
1292    /// A altura dentro da `min_height` e da `max_height` (a mínima vence).
1293    pub fn clamp_height(&self, height: f32) -> f32 {
1294        let h = if self.max_height > 0.0 { height.min(self.max_height) } else { height };
1295        h.max(self.min_height)
1296    }
1297
1298    /// Encaixado, estica na faixa (`stretch`) ou fica com o próprio tamanho no começo, no
1299    /// meio ou no fim: veja [`SelfAlign`].
1300    pub fn self_align(&self) -> SelfAlign {
1301        self.self_align
1302    }
1303
1304    pub fn set_self_align(&mut self, align: SelfAlign) -> &mut Self {
1305        self.self_align = align;
1306        self
1307    }
1308
1309    /// A largura numa faixa horizontal de `available` (encaixado em cima ou embaixo): a faixa
1310    /// toda ou, com `self_align`, a própria `width`; com `self_align` e `max_width`, a faixa até
1311    /// a máxima (o `width: 100%; max-width` do CSS). Sempre dentro dos limites.
1312    pub fn band_width(&self, available: f32) -> f32 {
1313        match self.self_align {
1314            SelfAlign::Stretch => self.clamp_width(available),
1315            _ if self.max_width > 0.0 => self.clamp_width(available),
1316            _ => self.clamp_width(self.width),
1317        }
1318    }
1319
1320    /// A altura numa faixa vertical de `available` (encaixado à esquerda ou à direita), como a
1321    /// [`band_width`](Self::band_width).
1322    pub fn band_height(&self, available: f32) -> f32 {
1323        match self.self_align {
1324            SelfAlign::Stretch => self.clamp_height(available),
1325            _ if self.max_height > 0.0 => self.clamp_height(available),
1326            _ => self.clamp_height(self.height),
1327        }
1328    }
1329
1330    /// Onde começa um tamanho `size` numa faixa de `available`: no começo, no meio (o
1331    /// `stretch` com a largura máxima sobrando) ou no fim. Passando da faixa, no começo.
1332    pub fn band_offset(&self, available: f32, size: f32) -> f32 {
1333        let spare = (available - size).max(0.0);
1334        match self.self_align {
1335            SelfAlign::Start => 0.0,
1336            SelfAlign::End => spare,
1337            SelfAlign::Stretch | SelfAlign::Center => spare / 2.0,
1338        }
1339    }
1340
1341    /// A altura sai do conteúdo, na largura que o controle tem (como o `AutoSize` do
1342    /// Delphi): um Label com `wrap` fica da altura do texto quebrado; um contêiner, da
1343    /// altura dos filhos encaixados em cima e embaixo (mais o padding). Vale com `align`
1344    /// `top`, `bottom` ou `none`.
1345    pub fn auto_size(&self) -> bool {
1346        self.auto_size
1347    }
1348
1349    pub fn set_auto_size(&mut self, on: bool) -> &mut Self {
1350        self.auto_size = on;
1351        self
1352    }
1353
1354    /// Quantas colunas ocupa num `GridLayout` (pelo menos 1; numa grade com menos colunas,
1355    /// ocupa a linha inteira).
1356    pub fn column_span(&self) -> u32 {
1357        self.column_span.max(1)
1358    }
1359
1360    pub fn set_column_span(&mut self, span: u32) -> &mut Self {
1361        self.column_span = span.max(1);
1362        self
1363    }
1364
1365    /// A escala de fonte da vista ativa do form (1 sem vista).
1366    pub fn text_scale(&self) -> f32 {
1367        self.text_scale
1368    }
1369
1370    /// A escala de espaços da vista ativa do form (1 sem vista).
1371    pub fn spacing_scale(&self) -> f32 {
1372        self.spacing_scale
1373    }
1374
1375    pub fn tag(&self) -> i64 {
1376        self.tag
1377    }
1378
1379    /// Variante de estilo do tema ("primary", "danger", "flat"...). Vazio = estilo da classe.
1380    pub fn style(&self) -> &str {
1381        &self.style
1382    }
1383
1384    /// Tema próprio do controle (e dos filhos), pelo nome. Vazio = o do pai.
1385    pub fn theme_name(&self) -> &str {
1386        &self.theme
1387    }
1388
1389    pub fn set_theme_name(&mut self, v: impl Into<String>) -> &mut Self {
1390        self.theme = v.into();
1391        self
1392    }
1393
1394    /// Dica (balão) mostrada com o mouse parado sobre o controle. Vazio = a do pai.
1395    pub fn hint(&self) -> &str {
1396        &self.hint
1397    }
1398
1399    pub fn set_hint(&mut self, v: impl Into<String>) -> &mut Self {
1400        self.hint = v.into();
1401        self
1402    }
1403
1404    pub fn state(&self) -> ControlState {
1405        self.state
1406    }
1407
1408    /// Posição e tamanho reais, relativos ao pai, calculados pelo layout.
1409    pub fn bounds(&self) -> RectF {
1410        self.bounds
1411    }
1412
1413    /// Quanto o conteúdo está rolado: os filhos são deslocados por este valor.
1414    pub fn scroll_offset(&self) -> PointF {
1415        self.scroll_offset
1416    }
1417
1418    /// A rolagem com que o último layout pôs os filhos ([`scroll_offset`](Self::scroll_offset)
1419    /// muda na hora; esta, no layout): somada à posição de um filho, dá onde ele está no conteúdo.
1420    pub fn laid_out_scroll(&self) -> PointF {
1421        self.laid_out_scroll
1422    }
1423
1424    /// Rola o conteúdo. Chame `invalidate` (ou mude por `ui.control_mut`) para refazer o
1425    /// layout.
1426    pub fn set_scroll_offset(&mut self, offset: PointF) -> &mut Self {
1427        self.scroll_offset = offset;
1428        self
1429    }
1430
1431    /// Tamanho ocupado pelos filhos visíveis (com margens e padding), calculado no
1432    /// layout. Serve para saber até onde rolar.
1433    pub fn content_size(&self) -> SizeF {
1434        self.content_size
1435    }
1436
1437    // ----- escrita (encadeável) -----
1438
1439    pub fn set_left(&mut self, v: f32) -> &mut Self {
1440        self.left = v;
1441        self.anchor_ref = None;
1442        self
1443    }
1444
1445    pub fn set_top(&mut self, v: f32) -> &mut Self {
1446        self.top = v;
1447        self.anchor_ref = None;
1448        self
1449    }
1450
1451    pub fn set_position(&mut self, left: f32, top: f32) -> &mut Self {
1452        self.set_left(left).set_top(top)
1453    }
1454
1455    pub fn set_width(&mut self, v: f32) -> &mut Self {
1456        self.width = v.max(0.0);
1457        self.anchor_ref = None;
1458        self
1459    }
1460
1461    pub fn set_height(&mut self, v: f32) -> &mut Self {
1462        self.height = v.max(0.0);
1463        self.anchor_ref = None;
1464        self
1465    }
1466
1467    pub fn set_size(&mut self, width: f32, height: f32) -> &mut Self {
1468        self.set_width(width).set_height(height)
1469    }
1470
1471    /// Define posição e tamanho de uma vez.
1472    pub fn set_rect(&mut self, left: f32, top: f32, width: f32, height: f32) -> &mut Self {
1473        self.set_position(left, top).set_size(width, height)
1474    }
1475
1476    pub fn set_margins(&mut self, v: impl Into<Bounds>) -> &mut Self {
1477        self.margins = v.into();
1478        self
1479    }
1480
1481    pub fn set_padding(&mut self, v: impl Into<Bounds>) -> &mut Self {
1482        self.padding = v.into();
1483        self
1484    }
1485
1486    pub fn set_align(&mut self, v: Align) -> &mut Self {
1487        self.align = v;
1488        self.anchor_ref = None;
1489        self
1490    }
1491
1492    pub fn set_anchors(&mut self, v: Anchors) -> &mut Self {
1493        self.anchors = v;
1494        self.anchor_ref = None;
1495        self
1496    }
1497
1498    pub fn set_visible(&mut self, v: bool) -> &mut Self {
1499        self.visible = v;
1500        self
1501    }
1502
1503    pub fn set_enabled(&mut self, v: bool) -> &mut Self {
1504        self.enabled = v;
1505        self
1506    }
1507
1508    pub fn set_hit_test(&mut self, v: bool) -> &mut Self {
1509        self.hit_test = v;
1510        self
1511    }
1512
1513    pub fn set_clip_children(&mut self, v: bool) -> &mut Self {
1514        self.clip_children = v;
1515        self
1516    }
1517
1518    pub fn set_captures_wheel(&mut self, v: bool) -> &mut Self {
1519        self.captures_wheel = v;
1520        self
1521    }
1522
1523    pub fn set_can_focus(&mut self, v: bool) -> &mut Self {
1524        self.can_focus = v;
1525        self
1526    }
1527
1528    /// Arrastar o dedo sobre o controle rola o conteúdo (vira roda para o ScrollBox ou o
1529    /// DataGrid de baixo). Ligado por padrão; controles que precisam do arrasto em si (um
1530    /// Splitter, um designer) desligam.
1531    pub fn set_pan_on_touch(&mut self, v: bool) -> &mut Self {
1532        self.pan_on_touch = v;
1533        self
1534    }
1535
1536    pub fn set_tab_stop(&mut self, v: bool) -> &mut Self {
1537        self.tab_stop = v;
1538        self
1539    }
1540
1541    pub fn set_cursor(&mut self, v: CursorShape) -> &mut Self {
1542        self.cursor = v;
1543        self
1544    }
1545
1546    pub fn set_opacity(&mut self, v: f32) -> &mut Self {
1547        self.opacity = v.clamp(0.0, 1.0);
1548        self
1549    }
1550
1551    /// Deslocamento do desenho (sem mexer no layout).
1552    pub fn translate(&self) -> PointF {
1553        self.translate
1554    }
1555
1556    pub fn set_translate(&mut self, offset: PointF) -> &mut Self {
1557        self.translate = if offset.x.is_finite() && offset.y.is_finite() { offset } else { PointF::ZERO };
1558        self
1559    }
1560
1561    pub fn set_rotation(&mut self, degrees: f32) -> &mut Self {
1562        self.rotation = if degrees.is_finite() { degrees % 360.0 } else { 0.0 };
1563        self
1564    }
1565
1566    pub fn set_shadow(&mut self, shadow: Option<crate::canvas::Shadow>) -> &mut Self {
1567        self.shadow = shadow;
1568        self
1569    }
1570
1571    pub fn set_tag(&mut self, v: i64) -> &mut Self {
1572        self.tag = v;
1573        self
1574    }
1575
1576    pub fn set_style(&mut self, v: impl Into<String>) -> &mut Self {
1577        self.style = v.into();
1578        self
1579    }
1580
1581    /// Estado visual (hover, pressed...). Normalmente quem altera é o despacho de eventos;
1582    /// controles como CheckBox alteram `checked`.
1583    pub fn state_mut(&mut self) -> &mut ControlState {
1584        &mut self.state
1585    }
1586
1587    // ----- propriedades por nome -----
1588
1589    pub fn get_prop(&self, name: &str) -> Option<PropValue> {
1590        Some(match name {
1591            "left" => self.left.into(),
1592            "top" => self.top.into(),
1593            "width" => self.width.into(),
1594            "height" => self.height.into(),
1595            "align" => self.align.into(),
1596            "anchors" => self.anchors.into(),
1597            "margins" => self.margins.into(),
1598            "padding" => self.padding.into(),
1599            "visible" => self.visible.into(),
1600            "enabled" => self.enabled.into(),
1601            "hit_test" => self.hit_test.into(),
1602            "clip_children" => self.clip_children.into(),
1603            "captures_wheel" => self.captures_wheel.into(),
1604            "can_focus" => self.can_focus.into(),
1605            "draggable" => self.draggable.into(),
1606            "accepts_drops" => self.accepts_drops.into(),
1607            "drag_data" => self.drag_data().into(),
1608            "drag_label" => self.drag_label().into(),
1609            "drag_image" => PropValue::Component(self.drag_image()),
1610            "drop_types" => self.drop_types().into(),
1611            "tab_stop" => self.tab_stop.into(),
1612            "cursor" => PropValue::enum_value(self.cursor),
1613            "opacity" => self.opacity.into(),
1614            "cache_layer" => self.cache_layer.into(),
1615            "rotation" => self.rotation.into(),
1616            "translate_x" => self.translate.x.into(),
1617            "translate_y" => self.translate.y.into(),
1618            "aspect_ratio" => self.aspect_ratio.into(),
1619            "max_width" => self.max_width.into(),
1620            "min_width" => self.min_width.into(),
1621            "min_height" => self.min_height.into(),
1622            "max_height" => self.max_height.into(),
1623            "self_align" => PropValue::enum_value(self.self_align),
1624            "auto_size" => self.auto_size.into(),
1625            "column_span" => (self.column_span() as i64).into(),
1626            "shadow" => crate::prop::PropType::to_value(&self.shadow),
1627            "style" => self.style.clone().into(),
1628            "fill" => crate::prop::PropType::to_value(&self.colors.fill),
1629            "border_color" => crate::prop::PropType::to_value(&self.colors.border),
1630            "text_color" => crate::prop::PropType::to_value(&self.colors.text),
1631            "accent_color" => crate::prop::PropType::to_value(&self.colors.accent),
1632            "success_color" => crate::prop::PropType::to_value(&self.colors.success),
1633            "warning_color" => crate::prop::PropType::to_value(&self.colors.warning),
1634            "danger_color" => crate::prop::PropType::to_value(&self.colors.danger),
1635            "font_family" => self.font.family.clone().into(),
1636            "font_size" => crate::prop::PropType::to_value(&self.font.size),
1637            "font_weight" => PropValue::Enum(FONT_WEIGHTS[self.font.weight.map_or(0, |w| w as usize + 1)].into()),
1638            "font_italic" => self.font.italic.into(),
1639            "font_underline" => self.font.underline.into(),
1640            "font_strikeout" => self.font.strikeout.into(),
1641            "theme" => self.theme.clone().into(),
1642            "hint" => self.hint.clone().into(),
1643            "tag" => self.tag.into(),
1644            "popup_menu" => PropValue::Component(self.popup_menu),
1645            _ => return None,
1646        })
1647    }
1648
1649    pub fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
1650        match name {
1651            "left" => self.set_left(value.to_f32()?),
1652            "top" => self.set_top(value.to_f32()?),
1653            "width" => self.set_width(value.to_f32()?),
1654            "height" => self.set_height(value.to_f32()?),
1655            "align" => self.set_align(value.to_enum()?),
1656            "anchors" => self.set_anchors(value.to_anchors()?),
1657            "margins" => self.set_margins(value.to_bounds()?),
1658            "padding" => self.set_padding(value.to_bounds()?),
1659            "visible" => self.set_visible(value.to_bool()?),
1660            "enabled" => self.set_enabled(value.to_bool()?),
1661            "hit_test" => self.set_hit_test(value.to_bool()?),
1662            "clip_children" => self.set_clip_children(value.to_bool()?),
1663            "captures_wheel" => self.set_captures_wheel(value.to_bool()?),
1664            "can_focus" => self.set_can_focus(value.to_bool()?),
1665            "draggable" => self.set_draggable(value.to_bool()?),
1666            "accepts_drops" => self.set_accepts_drops(value.to_bool()?),
1667            "drag_data" => {
1668                self.drag_decl().data = value.to_str()?.to_string();
1669                self
1670            }
1671            "drag_label" => {
1672                self.drag_decl().label = value.to_str()?.to_string();
1673                self
1674            }
1675            "drag_image" => {
1676                self.drag_decl().image = value.to_component()?;
1677                self
1678            }
1679            "drop_types" => {
1680                self.drag_decl().drop_types = value.to_str()?.to_string();
1681                self
1682            }
1683            "tab_stop" => self.set_tab_stop(value.to_bool()?),
1684            "cursor" => self.set_cursor(value.to_enum()?),
1685            "opacity" => self.set_opacity(value.to_f32()?),
1686            "cache_layer" => self.set_cache_layer(value.to_bool()?),
1687            "rotation" => self.set_rotation(value.to_f32()?),
1688            "translate_x" => self.set_translate(PointF::new(value.to_f32()?, self.translate.y)),
1689            "translate_y" => self.set_translate(PointF::new(self.translate.x, value.to_f32()?)),
1690            "aspect_ratio" => self.set_aspect_ratio(value.to_f32()?),
1691            "max_width" => self.set_max_width(value.to_f32()?),
1692            "min_width" => self.set_min_width(value.to_f32()?),
1693            "min_height" => self.set_min_height(value.to_f32()?),
1694            "max_height" => self.set_max_height(value.to_f32()?),
1695            "self_align" => self.set_self_align(value.to_enum()?),
1696            "auto_size" => self.set_auto_size(value.to_bool()?),
1697            "column_span" => self.set_column_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
1698            "shadow" => self.set_shadow(crate::prop::PropType::from_value(value)?),
1699            "style" => self.set_style(value.to_str()?),
1700            "fill" => {
1701                self.colors.fill = crate::prop::PropType::from_value(value)?;
1702                self
1703            }
1704            "border_color" => {
1705                self.colors.border = crate::prop::PropType::from_value(value)?;
1706                self
1707            }
1708            "text_color" => {
1709                self.colors.text = crate::prop::PropType::from_value(value)?;
1710                self
1711            }
1712            "accent_color" => {
1713                self.colors.accent = crate::prop::PropType::from_value(value)?;
1714                self
1715            }
1716            "success_color" => {
1717                self.colors.success = crate::prop::PropType::from_value(value)?;
1718                self
1719            }
1720            "warning_color" => {
1721                self.colors.warning = crate::prop::PropType::from_value(value)?;
1722                self
1723            }
1724            "danger_color" => {
1725                self.colors.danger = crate::prop::PropType::from_value(value)?;
1726                self
1727            }
1728            "font_family" => {
1729                self.font.family = value.to_str()?.to_string();
1730                self
1731            }
1732            "font_size" => {
1733                self.font.size = crate::prop::PropType::from_value(value)?;
1734                self
1735            }
1736            "font_weight" => {
1737                self.font.weight = font_weight_named(value.to_str()?)?;
1738                self
1739            }
1740            "font_italic" => {
1741                self.font.italic = value.to_bool()?;
1742                self
1743            }
1744            "font_underline" => {
1745                self.font.underline = value.to_bool()?;
1746                self
1747            }
1748            "font_strikeout" => {
1749                self.font.strikeout = value.to_bool()?;
1750                self
1751            }
1752            "theme" => self.set_theme_name(value.to_str()?),
1753            "hint" => self.set_hint(value.to_str()?),
1754            "tag" => self.set_tag(value.to_i64()?),
1755            "popup_menu" => {
1756                self.popup_menu = value.to_component()?;
1757                self
1758            }
1759            _ => return Err(Error::UnknownProperty(name.to_string())),
1760        };
1761        Ok(())
1762    }
1763}
1764
1765/// Os pesos da propriedade `font_weight`; `default` é o do pai (ou do tema).
1766pub const FONT_WEIGHTS: [&str; 8] = ["default", "thin", "light", "normal", "medium", "semibold", "bold", "black"];
1767
1768fn font_weight_named(name: &str) -> Result<Option<crate::canvas::FontWeight>> {
1769    use crate::canvas::FontWeight::*;
1770    let all = [Thin, Light, Normal, Medium, SemiBold, Bold, Black];
1771    match FONT_WEIGHTS.iter().position(|n| n.eq_ignore_ascii_case(name)) {
1772        Some(0) => Ok(None),
1773        Some(i) => Ok(Some(all[i - 1])),
1774        None => Err(Error::invalid(format!("valor '{name}' inválido; use um de: {}", FONT_WEIGHTS.join(", ")))),
1775    }
1776}
1777
1778/// A fonte de um controle por cima da do tema, como o `Font` do Delphi: família, tamanho,
1779/// peso, itálico, sublinhado e tachado. O que não tem valor vem do pai (o `ParentFont`):
1780/// a fonte posta no form vale para tudo dentro dele.
1781#[derive(Clone, Debug, Default, PartialEq)]
1782pub struct FontOverride {
1783    /// Vazio: a do pai.
1784    pub family: String,
1785    pub size: Option<f32>,
1786    pub weight: Option<crate::canvas::FontWeight>,
1787    /// Ligados valem também para os filhos.
1788    pub italic: bool,
1789    pub underline: bool,
1790    pub strikeout: bool,
1791}
1792
1793impl FontOverride {
1794    pub fn is_empty(&self) -> bool {
1795        *self == Self::default()
1796    }
1797
1798    /// Esta fonte com o que faltar vindo de `parent`.
1799    pub fn over(&self, parent: &FontOverride) -> FontOverride {
1800        FontOverride {
1801            family: if self.family.is_empty() { parent.family.clone() } else { self.family.clone() },
1802            size: self.size.or(parent.size),
1803            weight: self.weight.or(parent.weight),
1804            italic: self.italic || parent.italic,
1805            underline: self.underline || parent.underline,
1806            strikeout: self.strikeout || parent.strikeout,
1807        }
1808    }
1809
1810    /// Aplica na fonte do estilo (a do tema).
1811    pub fn apply(&self, font: &mut crate::canvas::FontSpec) {
1812        if !self.family.is_empty() {
1813            font.family = self.family.clone();
1814        }
1815        if let Some(size) = self.size.filter(|s| *s > 0.0) {
1816            font.size = size;
1817        }
1818        if let Some(weight) = self.weight {
1819            font.weight = weight;
1820        }
1821        font.italic |= self.italic;
1822        font.underline |= self.underline;
1823        font.strikeout |= self.strikeout;
1824    }
1825}
1826
1827impl ControlBase {
1828    /// A fonte própria do controle (sem a herdada).
1829    pub fn font(&self) -> &FontOverride {
1830        &self.font
1831    }
1832
1833    pub fn set_font(&mut self, font: FontOverride) -> &mut Self {
1834        self.font = font;
1835        self
1836    }
1837}
1838
1839/// As cores próprias de um controle (vazio = as do tema), como as do `TButton` estilizado:
1840/// valem para qualquer controle (`fill`, `border_color`, `text_color`, `accent_color` e as de
1841/// sentido: `success_color`, `warning_color`, `danger_color`).
1842/// O `Ui` as põe no estilo resolvido e no tema que o controle vê (`primary` e as variações,
1843/// `text`, `border`), então até os controles que leem o tema direto as seguem.
1844#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1845pub struct ColorOverride {
1846    /// O fundo.
1847    pub fill: Option<crate::Color>,
1848    pub border: Option<crate::Color>,
1849    pub text: Option<crate::Color>,
1850    /// O destaque: a marca da caixa de seleção, a barra do progresso, o trilho preenchido,
1851    /// a seleção, o foco.
1852    pub accent: Option<crate::Color>,
1853    /// As cores de sentido: subir/positivo, atenção e cair/erro (candles, variações, avisos).
1854    pub success: Option<crate::Color>,
1855    pub warning: Option<crate::Color>,
1856    pub danger: Option<crate::Color>,
1857}
1858
1859impl ColorOverride {
1860    pub fn is_empty(&self) -> bool {
1861        *self == Self::default()
1862    }
1863
1864    /// Muda alguma cor do tema (não só o estilo).
1865    pub(crate) fn recolors_theme(&self) -> bool {
1866        !self.is_empty()
1867    }
1868
1869    /// O tema com as cores próprias por cima.
1870    pub(crate) fn apply_theme(&self, theme: &crate::Theme) -> crate::Theme {
1871        use crate::Color;
1872        let mut t = theme.clone();
1873        let mut set = |name: &str, c: Color| {
1874            t.colors.insert(name.to_string(), c);
1875        };
1876        if let Some(a) = self.accent {
1877            let dark = luminance(a) < 0.5;
1878            set("primary", a);
1879            set("primary_hover", a.lerp(if dark { Color::WHITE } else { Color::BLACK }, 0.12));
1880            set("primary_pressed", a.lerp(if dark { Color::BLACK } else { Color::BLACK }, 0.15));
1881            set("on_primary", if luminance(a) < 0.6 { Color::WHITE } else { Color::BLACK });
1882            set("focus_ring", a);
1883            set("selection", a.with_opacity(0.25));
1884            set("primary_soft", a.with_opacity(0.1));
1885            set("primary_container", a.lerp(Color::WHITE, 0.82));
1886        }
1887        if let Some(c) = self.fill {
1888            // O fundo: o da superfície e o das áreas de dentro (um pouco mais escuro ou claro).
1889            let toward = if luminance(c) < 0.5 { Color::WHITE } else { Color::BLACK };
1890            set("surface", c);
1891            set("background", c);
1892            set("surface_2", c.lerp(toward.with_opacity(c.a as f32 / 255.0), 0.06));
1893        }
1894        if let Some(c) = self.text {
1895            set("text", c);
1896            set("text_muted", c.with_opacity(0.65));
1897            for on in ["on_primary", "on_danger", "on_success", "on_primary_container"] {
1898                set(on, c);
1899            }
1900        }
1901        if let Some(c) = self.border {
1902            set("border", c);
1903            set("track", c);
1904        }
1905        for (token, color) in [("success", self.success), ("warning", self.warning), ("danger", self.danger)] {
1906            if let Some(c) = color {
1907                set(token, c);
1908                set(&format!("{token}_soft"), c.with_opacity(0.1));
1909                set(&format!("{token}_hover"), c.lerp(Color::WHITE, 0.12));
1910                set(&format!("{token}_pressed"), c.lerp(Color::BLACK, 0.15));
1911                if token == "success" {
1912                    set("meter_low", c);
1913                } else if token == "danger" {
1914                    set("meter_high", c);
1915                } else {
1916                    set("meter_mid", c);
1917                }
1918            }
1919        }
1920        t
1921    }
1922}
1923
1924/// Luminância relativa (0 escuro, 1 claro).
1925pub(crate) fn luminance(c: crate::Color) -> f32 {
1926    (0.299 * c.r as f32 + 0.587 * c.g as f32 + 0.114 * c.b as f32) / 255.0
1927}
1928
1929/// As duas pontas de um conector ([`Component::connection`]).
1930#[derive(Clone, Copy, Debug, PartialEq)]
1931pub struct Connection {
1932    pub from: ComponentId,
1933    /// O ponto de ligação em `from` (`(1, 0.5)`: o meio do lado direito).
1934    pub from_at: (f32, f32),
1935    pub to: ComponentId,
1936    pub to_at: (f32, f32),
1937}
1938
1939impl Connection {
1940    /// Quanto a ponta sai do componente antes da primeira dobra.
1941    pub const STUB: f32 = 16.0;
1942
1943    /// A direção para fora do lado onde está o ponto (`(1, 0.5)` → direita).
1944    fn normal(at: (f32, f32)) -> PointF {
1945        let (x, y) = at;
1946        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))];
1947        d.iter().min_by(|a, b| a.0.total_cmp(&b.0)).map_or(PointF::new(1.0, 0.0), |d| d.1)
1948    }
1949
1950    /// O caminho em ângulos retos entre os dois pontos (nas coordenadas do pai), dados os
1951    /// retângulos dos dois componentes.
1952    pub fn route(&self, from: RectF, to: RectF) -> Vec<PointF> {
1953        let p0 = PointF::new(from.x + from.width * self.from_at.0, from.y + from.height * self.from_at.1);
1954        let p1 = PointF::new(to.x + to.width * self.to_at.0, to.y + to.height * self.to_at.1);
1955        let (n0, n1) = (Self::normal(self.from_at), Self::normal(self.to_at));
1956        let s0 = PointF::new(p0.x + n0.x * Self::STUB, p0.y + n0.y * Self::STUB);
1957        let s1 = PointF::new(p1.x + n1.x * Self::STUB, p1.y + n1.y * Self::STUB);
1958        let mut points = vec![p0, s0];
1959        if n0.x != 0.0 {
1960            // Sai na horizontal: anda até o meio em x, desce/sobe, segue.
1961            let mx = (s0.x + s1.x) / 2.0;
1962            points.push(PointF::new(mx, s0.y));
1963            points.push(PointF::new(mx, s1.y));
1964        } else {
1965            let my = (s0.y + s1.y) / 2.0;
1966            points.push(PointF::new(s0.x, my));
1967            points.push(PointF::new(s1.x, my));
1968        }
1969        points.push(s1);
1970        points.push(p1);
1971        points.dedup_by(|a, b| (a.x - b.x).abs() < 0.01 && (a.y - b.y).abs() < 0.01);
1972        points
1973    }
1974}
1975
1976/// O arrasto declarado de um controle (fica fora do `ControlBase` comum: quase nenhum tem).
1977#[derive(Clone, Debug, Default, PartialEq)]
1978pub struct DragDecl {
1979    pub data: String,
1980    pub label: String,
1981    pub drop_types: String,
1982    /// O `DragImage` que acompanha o cursor no arrasto (a imagem e o tamanho).
1983    pub image: Option<ComponentId>,
1984}