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