Skip to main content

aylis_core/
component.rs

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