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}
848
849impl MethodInfo {
850    pub const fn new(name: &'static str, args: &'static [PropKind], returns: Option<PropKind>) -> Self {
851        Self { name, args, returns, params: &[] }
852    }
853
854    /// Os nomes dos argumentos, na ordem de `args`:
855    /// `MethodInfo::new("save_to", &[PropKind::String], None).params(&["path"])`.
856    pub const fn params(self, names: &'static [&'static str]) -> Self {
857        Self { params: names, ..self }
858    }
859}
860
861/// Comando para uma vista nativa.
862#[derive(Clone, Debug, PartialEq)]
863pub enum NativeCommand {
864    /// Roda JavaScript na página.
865    Eval(String),
866    Back,
867    Forward,
868    Reload,
869}
870
871/// Uma vista nativa a mostrar: o controle, onde (relativo ao form) e o que é.
872#[derive(Clone, Debug, PartialEq)]
873pub struct NativeViewSlot {
874    pub id: ComponentId,
875    pub rect: crate::RectF,
876    /// A parte que aparece (os pais que recortam, como uma caixa rolada, cortam o resto),
877    /// nas mesmas coordenadas de `rect`; `None`: inteira.
878    pub clip: Option<crate::RectF>,
879    pub visible: bool,
880    pub view: NativeView,
881    pub commands: Vec<NativeCommand>,
882}
883
884/// Todas as propriedades publicadas de um componente: as da classe, as das camadas de
885/// composição e as do [`ControlBase`] (sem `name` nem os eventos ligados no `Ui`).
886///
887/// Trabalha direto no componente, sem precisar do [`Ui`](crate::Ui): serve, por exemplo,
888/// para ler os valores padrão de uma instância nova da classe.
889pub fn prop_infos_of(component: &dyn Component) -> Vec<PropInfo> {
890    let mut out: Vec<PropInfo> = Vec::new();
891    // Os nomes já vistos num conjunto: procurar na lista a cada propriedade era quadrático
892    // (~90 por controle), e isso roda para cada componente no índice de referências.
893    let mut seen = std::collections::HashSet::new();
894    let mut push = |info: &PropInfo| {
895        if seen.insert(info.name) {
896            out.push(*info);
897        }
898    };
899    let mut layer = Some(component);
900    while let Some(l) = layer {
901        l.props().iter().for_each(&mut push);
902        layer = l.inner();
903    }
904    if component.control().is_some() {
905        ControlBase::PROPS.iter().for_each(&mut push);
906    }
907    out
908}
909
910/// A descrição de uma propriedade pelo nome, na mesma ordem de [`prop_infos_of`] (a camada
911/// de fora vence), sem montar a lista inteira: todo `get_prop`/`set_prop` passa por aqui.
912pub fn prop_info_of(component: &dyn Component, name: &str) -> Option<PropInfo> {
913    let mut layer = Some(component);
914    while let Some(l) = layer {
915        if let Some(info) = l.props().iter().find(|p| p.name == name) {
916            return Some(*info);
917        }
918        layer = l.inner();
919    }
920    if component.control().is_some() {
921        return ControlBase::PROPS.iter().find(|p| p.name == name).copied();
922    }
923    None
924}
925
926/// Lê uma propriedade (que não seja evento) direto no componente, procurando em todas as
927/// camadas e no [`ControlBase`].
928/// As propriedades que são "o valor" de um controle (o que o usuário muda e o `on_change`
929/// avisa), quando publicadas em `Data` (ou `Runtime`, como o `value` da ComboBox).
930pub const VALUE_PROPERTIES: [&str; 19] = [
931    "text", "checked", "value", "item_index", "selected", "date", "end_date", "time", "color", "files", "html", "index", "page", "hotkey",
932    "angle", "pressed", "position", "low", "high",
933];
934
935/// Mudar a propriedade pelo código dispara o `on_change` do controle (se ele tiver um):
936/// as de [`VALUE_PROPERTIES`] (fora das de aparência, como o `text` de um
937/// CheckBox, que é a legenda), a aba escolhida e o aberto/fechado.
938pub fn is_value_property(info: &PropInfo) -> bool {
939    match info.name {
940        "tab_index" | "expanded" => true,
941        name => matches!(info.category, "Data" | "Runtime") && VALUE_PROPERTIES.contains(&name),
942    }
943}
944
945pub fn read_prop(component: &dyn Component, name: &str) -> Option<PropValue> {
946    let mut layer = Some(component);
947    while let Some(l) = layer {
948        if let Some(v) = l.get_prop(name) {
949            return Some(v);
950        }
951        layer = l.inner();
952    }
953    component.control().and_then(|cb| cb.get_prop(name))
954}
955
956/// Referência guardada pelas âncoras: tamanho do pai e retângulo do controle no momento
957/// em que a posição foi definida.
958#[derive(Clone, Copy, Debug, PartialEq)]
959pub(crate) struct AnchorRef {
960    pub(crate) parent: SizeF,
961    pub(crate) rect: RectF,
962}
963
964/// Dados comuns de todo controle visual.
965///
966/// `left`, `top`, `width` e `height` são os valores **pedidos**. A posição e o tamanho
967/// **reais**, calculados pelo layout (Align/Anchors), ficam em [`bounds`](Self::bounds).
968#[derive(Clone, Debug)]
969pub struct ControlBase {
970    /// Posição a partir do canto do pai; só vale com `align: none`.
971    left: f32,
972    /// Posição a partir do topo do pai; só vale com `align: none`.
973    top: f32,
974    /// Largura pedida; o `align` pode esticar (top, bottom, client).
975    width: f32,
976    /// Altura pedida; o `align` pode esticar (left, right, client).
977    height: f32,
978    /// Espaço por fora, até os vizinhos e a borda do pai: número, `[h, v]` ou `[esquerda, cima, direita, baixo]`.
979    margins: Bounds,
980    /// Espaço por dentro, até os filhos: número, `[h, v]` ou `[esquerda, cima, direita, baixo]`.
981    padding: Bounds,
982    /// Encaixe no pai: `top`/`bottom` esticam na largura, `left`/`right` na altura, `client` ocupa o resto; `none` usa `left`/`top`.
983    align: Align,
984    /// 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.
985    anchors: Anchors,
986    /// Aparece; escondido não ocupa lugar no layout.
987    visible: bool,
988    /// Aceita clique e teclado; desligado aparece apagado, e os filhos também.
989    enabled: bool,
990    /// Recebe o mouse; desligado, o clique passa para o que está embaixo.
991    hit_test: bool,
992    /// Corta o desenho dos filhos na borda dele.
993    clip_children: bool,
994    /// Pinta com o estado do pai (`hover`, `pressed`, `checked`): o rótulo da linha marcada
995    /// fica com a cor de marcado do tema sem trocar o estilo filho a filho (C25 do Tabernáculo).
996    inherit_state: bool,
997    /// Os textos dele passam pela tradução do app (o padrão). Desligado, ficam como estão e
998    /// não entram na lista do que traduzir: um nome próprio, um código, um valor de exemplo
999    /// (G19 do Tabernáculo).
1000    translatable: bool,
1001    /// A roda do mouse em cima dele fica com ele (não rola os contêineres de fora), mesmo
1002    /// sem ele rolar: uma prévia que dá zoom com a roda, um mapa, um gráfico.
1003    captures_wheel: bool,
1004    /// A pinça e o deslizar em cima dele ficam com ele: o `on_gesture`/`on_swipe` dele roda e
1005    /// os pais não recebem (a linha do tempo que amplia dentro de um palco que também amplia).
1006    captures_gesture: bool,
1007    /// Pode receber o foco do teclado (clique ou Tab).
1008    can_focus: bool,
1009    /// Pode ser arrastado (o `drag` diz o que vai junto).
1010    draggable: bool,
1011    /// Aceita o que é solto em cima dele (`on_drop`).
1012    accepts_drops: bool,
1013    /// O arrasto declarado (sem handler): o que vai (`"cliente:123"`, o tipo antes do primeiro
1014    /// `:`) e o rótulo que acompanha o mouse; os tipos que este destino aceita (`"cliente;produto"`).
1015    drag: Option<Box<DragDecl>>,
1016    /// Entra na ordem do Tab.
1017    tab_stop: bool,
1018    /// No toque, arrastar rola o contêiner de fora em vez de ir para o controle.
1019    pan_on_touch: bool,
1020    /// Menu de contexto: abre no clique direito.
1021    pub(crate) popup_menu: Option<ComponentId>,
1022    /// O cursor do mouse em cima dele.
1023    cursor: CursorShape,
1024    /// Transparência de 0 (invisível) a 1, com os filhos; continua no layout e clicável.
1025    opacity: f32,
1026    /// Como o controle (com os filhos) se junta ao que está por baixo (o `mix-blend-mode`
1027    /// do CSS): `difference` com branco é o negativo, como a marca d'água sobre um vídeo.
1028    blend_mode: crate::BlendMode,
1029    /// Giro em graus, em torno do centro.
1030    rotation: f32,
1031    /// A escala do controle e de tudo dentro dele (1 = normal): ele ocupa o
1032    /// mesmo retângulo no pai, e o desenho dele e o layout dos filhos acontecem num espaço do
1033    /// tamanho do retângulo dividido pela escala, ampliado na pintura. O clique, o foco e a
1034    /// área a repintar acompanham ([`ControlBase::inner_size`]).
1035    scale: f32,
1036    /// Deslocamento só do desenho (não muda o layout): animações e transições.
1037    translate: PointF,
1038    /// O desenho dele e dos filhos guardado numa imagem, refeita só quando algo lá dentro
1039    /// muda: um painel pesado que desliza ou some aos poucos.
1040    cache_layer: bool,
1041    /// Proporção fixa (largura ÷ altura; 0 = livre), como o `VResponsive` do Vuetify.
1042    aspect_ratio: f32,
1043    /// Largura máxima (0 = sem limite), como o `max-width` do CSS com margem automática.
1044    max_width: f32,
1045    /// Largura mínima, altura mínima e máxima (0 = sem limite).
1046    min_width: f32,
1047    /// Altura mínima: o layout e o `auto_size` não o deixam mais baixo (0 = sem limite).
1048    min_height: f32,
1049    /// Altura máxima: o layout e o `auto_size` não o deixam mais alto (0 = sem limite; a mínima vence).
1050    max_height: f32,
1051    /// Encaixado: estica na faixa ou fica com o próprio tamanho no começo, meio ou fim.
1052    self_align: SelfAlign,
1053    /// O tamanho sai do conteúdo: a altura; num Label encaixado à esquerda ou à direita, também a largura.
1054    auto_size: bool,
1055    /// Quantas colunas ocupa num `GridLayout` (o `colspan`; 1 ou 0: uma).
1056    column_span: u32,
1057    /// O lugar fixo num `GridLayout`: linha e coluna (-1: segue a ordem) e
1058    /// quantas linhas ocupa. O relatório do Tabernáculo, G12.
1059    grid_row: i16,
1060    /// A coluna fixa num `GridLayout`, contando de 0 (-1: segue a ordem); vale junto com o `grid_row`.
1061    grid_column: i16,
1062    /// Quantas linhas ocupa num `GridLayout` (1 ou 0: uma).
1063    row_span: u16,
1064    /// Quanto do espaço que sobra na linha de um `FlowLayout` ele toma (o `flex-grow`): um
1065    /// `Layout` vazio com `grow` 1 é o espaçador que empurra o resto para o fim (L04).
1066    grow: f32,
1067    /// As escalas de fonte e de espaços da vista ativa do form (postas pelo layout; veja
1068    /// `views.rs`): os getters de `margins`/`padding` e a fonte da pintura já saem escalados.
1069    pub(crate) text_scale: f32,
1070    pub(crate) spacing_scale: f32,
1071    /// Sombra do controle; quando há, vale no lugar da sombra do estilo.
1072    shadow: Option<crate::canvas::Shadow>,
1073    /// Um número livre para o código (não muda nada na tela).
1074    tag: i64,
1075    /// Os textos que quase nenhum controle usa (o `tag_string`, o `accessible_name`), numa
1076    /// caixa só, criada quando um deles tem algo: 8 bytes por controle.
1077    rare: Option<Box<RareTexts>>,
1078    /// A variante do tema (`primary`, `outline`, `flat`, `card`...): o estilo `Classe.variante`.
1079    style: String,
1080    /// Tema próprio (pelo nome), que vale também para os filhos. Vazio = o do pai.
1081    theme: String,
1082    /// Dica mostrada com o mouse parado em cima.
1083    hint: String,
1084    state: ControlState,
1085    pub(crate) bounds: RectF,
1086    pub(crate) anchor_ref: Option<AnchorRef>,
1087    /// Controle flutuante preso a outro (ver [`Ui::follow`](crate::Ui::follow)): o alvo e a
1088    /// distância do canto dele (medida no primeiro layout).
1089    pub(crate) follow: Option<(ComponentId, Option<PointF>)>,
1090    /// `visible` desligado pela propriedade no designer: o controle continua no layout e
1091    /// clicável, pintado translúcido (em execução ele some).
1092    pub(crate) design_hidden: bool,
1093    /// Só aparece no designer (o relatório: em execução, só a visualização o mostra).
1094    pub(crate) design_only: bool,
1095    /// Fica da esquerda para a direita mesmo com a interface espelhada (árabe), ele e os
1096    /// filhos: o designer da IDE, um gráfico, um mapa.
1097    pub(crate) keep_left_to_right: bool,
1098    /// As cores próprias (vazio = as do tema).
1099    pub(crate) colors: ColorOverride,
1100    /// A fonte própria; o que ficar sem valor vem do pai.
1101    pub(crate) font: FontOverride,
1102    /// Quanto o conteúdo está rolado.
1103    scroll_offset: PointF,
1104    /// A rolagem com que o último layout pôs os filhos: a posição de um filho no conteúdo é a
1105    /// dele mais esta, mesmo antes do próximo layout.
1106    pub(crate) laid_out_scroll: PointF,
1107    /// Faixas da tela cobertas pelo sistema (só no form; ver [`Ui::set_safe_area`](crate::Ui::set_safe_area)).
1108    pub(crate) safe_area: Bounds,
1109    /// Tamanho ocupado pelos filhos, calculado no layout (sem a rolagem).
1110    pub(crate) content_size: SizeF,
1111}
1112
1113impl Default for ControlBase {
1114    fn default() -> Self {
1115        Self::new(100.0, 100.0)
1116    }
1117}
1118
1119impl ControlBase {
1120    /// Propriedades publicadas comuns a todos os controles.
1121    pub const PROPS: &'static [PropInfo] = &[
1122        PropInfo::new("left", PropKind::Float, "Layout"),
1123        PropInfo::new("top", PropKind::Float, "Layout"),
1124        PropInfo::new("width", PropKind::Float, "Layout"),
1125        PropInfo::new("height", PropKind::Float, "Layout"),
1126        PropInfo::new("align", PropKind::Enum(<Align as crate::prop::PropEnum>::NAMES), "Layout"),
1127        PropInfo::new("anchors", PropKind::Set(&Anchors::NAMES), "Layout"),
1128        PropInfo::new("margins", PropKind::Bounds, "Layout"),
1129        PropInfo::new("padding", PropKind::Bounds, "Layout"),
1130        PropInfo::new("visible", PropKind::Bool, "Behavior"),
1131        PropInfo::new("enabled", PropKind::Bool, "Behavior"),
1132        PropInfo::new("hit_test", PropKind::Bool, "Behavior"),
1133        PropInfo::new("clip_children", PropKind::Bool, "Behavior"),
1134        PropInfo::new("inherit_state", PropKind::Bool, "Appearance"),
1135        PropInfo::new("translate", PropKind::Bool, "Behavior"),
1136        PropInfo::new("captures_wheel", PropKind::Bool, "Behavior"),
1137        PropInfo::new("captures_gesture", PropKind::Bool, "Behavior"),
1138        PropInfo::new("can_focus", PropKind::Bool, "Behavior"),
1139        PropInfo::new("draggable", PropKind::Bool, "Behavior"),
1140        PropInfo::new("accepts_drops", PropKind::Bool, "Behavior"),
1141        PropInfo::new("drag_data", PropKind::String, "Behavior"),
1142        PropInfo::new("drag_label", PropKind::String, "Behavior"),
1143        PropInfo::new("drag_image", PropKind::Component, "Behavior"),
1144        PropInfo::new("drop_types", PropKind::String, "Behavior"),
1145        PropInfo::new("tab_stop", PropKind::Bool, "Behavior"),
1146        PropInfo::new("cursor", PropKind::Enum(<CursorShape as crate::prop::PropEnum>::NAMES), "Behavior"),
1147        PropInfo::new("opacity", PropKind::Float, "Appearance"),
1148        PropInfo::new("blend_mode", PropKind::Enum(<crate::BlendMode as crate::prop::PropEnum>::NAMES), "Appearance"),
1149        PropInfo::new("cache_layer", PropKind::Bool, "Appearance"),
1150        PropInfo::new("rotation", PropKind::Angle, "Layout"),
1151        PropInfo::new("scale", PropKind::Float, "Layout"),
1152        PropInfo::new("translate_x", PropKind::Float, "Appearance"),
1153        PropInfo::new("translate_y", PropKind::Float, "Appearance"),
1154        PropInfo::new("aspect_ratio", PropKind::Float, "Layout"),
1155        PropInfo::new("max_width", PropKind::Float, "Layout"),
1156        PropInfo::new("min_width", PropKind::Float, "Layout"),
1157        PropInfo::new("min_height", PropKind::Float, "Layout"),
1158        PropInfo::new("max_height", PropKind::Float, "Layout"),
1159        PropInfo::new("self_align", PropKind::Enum(<SelfAlign as crate::prop::PropEnum>::NAMES), "Layout"),
1160        PropInfo::new("auto_size", PropKind::Bool, "Layout"),
1161        PropInfo::new("column_span", PropKind::Int, "Layout"),
1162        PropInfo::new("grid_row", PropKind::Int, "Layout"),
1163        PropInfo::new("grid_column", PropKind::Int, "Layout"),
1164        PropInfo::new("row_span", PropKind::Int, "Layout"),
1165        PropInfo::new("grow", PropKind::Float, "Layout"),
1166        PropInfo::new("shadow", PropKind::Shadow, "Appearance"),
1167        PropInfo::new("style", PropKind::String, "Appearance"),
1168        PropInfo::new("theme", PropKind::String, "Appearance"),
1169        PropInfo::new("fill", PropKind::Color, "Appearance"),
1170        PropInfo::new("border_color", PropKind::Color, "Appearance"),
1171        PropInfo::new("text_color", PropKind::Color, "Appearance"),
1172        PropInfo::new("accent_color", PropKind::Color, "Appearance"),
1173        PropInfo::new("success_color", PropKind::Color, "Appearance"),
1174        PropInfo::new("warning_color", PropKind::Color, "Appearance"),
1175        PropInfo::new("danger_color", PropKind::Color, "Appearance"),
1176        PropInfo::new("font_family", PropKind::String, "Font"),
1177        PropInfo::new("font_size", PropKind::Float, "Font"),
1178        PropInfo::new("font_weight", PropKind::Enum(&FONT_WEIGHTS), "Font"),
1179        PropInfo::new("font_italic", PropKind::Bool, "Font"),
1180        PropInfo::new("font_underline", PropKind::Bool, "Font"),
1181        PropInfo::new("font_strikeout", PropKind::Bool, "Font"),
1182        PropInfo::new("hint", PropKind::String, "Behavior"),
1183        PropInfo::new("tag", PropKind::Int, "Misc"),
1184        PropInfo::new("tag_string", PropKind::String, "Misc"),
1185        PropInfo::new("accessible_name", PropKind::String, "Behavior"),
1186        PropInfo::new("popup_menu", PropKind::Component, "Behavior"),
1187        PropInfo::new("on_click", PropKind::Event, "Events"),
1188        PropInfo::new("on_dbl_click", PropKind::Event, "Events"),
1189        PropInfo::new("on_long_press", PropKind::Event, "Events"),
1190        PropInfo::new("on_pointer_down", PropKind::Event, "Events"),
1191        PropInfo::new("on_pointer_up", PropKind::Event, "Events"),
1192        PropInfo::new("on_pointer_move", PropKind::Event, "Events"),
1193        PropInfo::new("on_pointer_enter", PropKind::Event, "Events"),
1194        PropInfo::new("on_pointer_leave", PropKind::Event, "Events"),
1195        PropInfo::new("on_wheel", PropKind::Event, "Events"),
1196        PropInfo::new("on_gesture", PropKind::Event, "Events"),
1197        PropInfo::new("on_swipe", PropKind::Event, "Events"),
1198        PropInfo::new("on_key_down", PropKind::Event, "Events"),
1199        PropInfo::new("on_key_press", PropKind::Event, "Events"),
1200        PropInfo::new("on_key_up", PropKind::Event, "Events"),
1201        PropInfo::new("on_enter", PropKind::Event, "Events"),
1202        PropInfo::new("on_exit", PropKind::Event, "Events"),
1203        PropInfo::new("on_resize", PropKind::Event, "Events"),
1204        PropInfo::new("on_drag_start", PropKind::Event, "Events"),
1205        PropInfo::new("on_drag_over", PropKind::Event, "Events"),
1206        PropInfo::new("on_drag_move", PropKind::Event, "Events"),
1207        PropInfo::new("on_drag_leave", PropKind::Event, "Events"),
1208        PropInfo::new("on_drag_drop", PropKind::Event, "Events"),
1209        PropInfo::new("on_drag_end", PropKind::Event, "Events"),
1210    ];
1211
1212    pub fn new(width: f32, height: f32) -> Self {
1213        Self {
1214            left: 0.0,
1215            top: 0.0,
1216            width,
1217            height,
1218            margins: Bounds::ZERO,
1219            padding: Bounds::ZERO,
1220            align: Align::None,
1221            anchors: Anchors::default(),
1222            visible: true,
1223            enabled: true,
1224            hit_test: true,
1225            clip_children: false,
1226            inherit_state: false,
1227            translatable: true,
1228            captures_wheel: false,
1229            captures_gesture: false,
1230            can_focus: false,
1231            draggable: false,
1232            accepts_drops: false,
1233            drag: None,
1234            tab_stop: true,
1235            pan_on_touch: true,
1236            popup_menu: None,
1237            cursor: CursorShape::Default,
1238            opacity: 1.0,
1239            blend_mode: crate::BlendMode::Normal,
1240            rotation: 0.0,
1241            scale: 1.0,
1242            translate: PointF::ZERO,
1243            cache_layer: false,
1244            aspect_ratio: 0.0,
1245            max_width: 0.0,
1246            min_width: 0.0,
1247            min_height: 0.0,
1248            max_height: 0.0,
1249            self_align: SelfAlign::Stretch,
1250            auto_size: false,
1251            column_span: 1,
1252            grid_row: -1,
1253            grid_column: -1,
1254            row_span: 1,
1255            grow: 0.0,
1256            text_scale: 1.0,
1257            spacing_scale: 1.0,
1258            shadow: None,
1259            tag: 0,
1260            rare: None,
1261            style: String::new(),
1262            theme: String::new(),
1263            hint: String::new(),
1264            state: ControlState::default(),
1265            bounds: RectF::new(0.0, 0.0, width, height),
1266            anchor_ref: None,
1267            follow: None,
1268            design_hidden: false,
1269            design_only: false,
1270            keep_left_to_right: false,
1271            colors: ColorOverride::default(),
1272            font: FontOverride::default(),
1273            scroll_offset: PointF::ZERO,
1274            laid_out_scroll: PointF::ZERO,
1275            content_size: SizeF::ZERO,
1276            safe_area: Bounds::default(),
1277        }
1278    }
1279
1280    // ----- leitura -----
1281
1282    pub fn left(&self) -> f32 {
1283        self.left
1284    }
1285
1286    pub fn top(&self) -> f32 {
1287        self.top
1288    }
1289
1290    pub fn width(&self) -> f32 {
1291        self.width
1292    }
1293
1294    pub fn height(&self) -> f32 {
1295        self.height
1296    }
1297
1298    pub fn position(&self) -> PointF {
1299        PointF::new(self.left, self.top)
1300    }
1301
1302    pub fn size(&self) -> SizeF {
1303        SizeF::new(self.width, self.height)
1304    }
1305
1306    /// As margens que valem no layout (com a escala de espaços da vista ativa; a propriedade
1307    /// guarda a do desenho).
1308    pub fn margins(&self) -> Bounds {
1309        if self.spacing_scale == 1.0 { self.margins } else { self.margins.scaled(self.spacing_scale) }
1310    }
1311
1312    /// O padding que vale no layout, como as [`margins`](Self::margins).
1313    pub fn padding(&self) -> Bounds {
1314        if self.spacing_scale == 1.0 { self.padding } else { self.padding.scaled(self.spacing_scale) }
1315    }
1316
1317    pub fn align(&self) -> Align {
1318        self.align
1319    }
1320
1321    pub fn anchors(&self) -> Anchors {
1322        self.anchors
1323    }
1324
1325    pub fn visible(&self) -> bool {
1326        self.visible
1327    }
1328
1329    /// Só aparece no designer (em execução não é pintado nem recebe o mouse).
1330    pub fn design_only(&self) -> bool {
1331        self.design_only
1332    }
1333
1334    /// As cores próprias.
1335    pub fn colors(&self) -> ColorOverride {
1336        self.colors
1337    }
1338
1339    pub fn set_colors(&mut self, colors: ColorOverride) -> &mut Self {
1340        self.colors = colors;
1341        self
1342    }
1343
1344    pub fn set_design_only(&mut self, on: bool) -> &mut Self {
1345        self.design_only = on;
1346        self
1347    }
1348
1349    /// Fica da esquerda para a direita (ele e os filhos) com a interface espelhada.
1350    pub fn keep_left_to_right(&self) -> bool {
1351        self.keep_left_to_right
1352    }
1353
1354    pub fn set_keep_left_to_right(&mut self, on: bool) -> &mut Self {
1355        self.keep_left_to_right = on;
1356        self
1357    }
1358
1359    pub fn enabled(&self) -> bool {
1360        self.enabled
1361    }
1362
1363    pub fn hit_test(&self) -> bool {
1364        self.hit_test
1365    }
1366
1367    pub fn translatable(&self) -> bool {
1368        self.translatable
1369    }
1370
1371    pub fn set_translatable(&mut self, v: bool) -> &mut Self {
1372        self.translatable = v;
1373        self
1374    }
1375
1376    pub fn inherit_state(&self) -> bool {
1377        self.inherit_state
1378    }
1379
1380    pub fn set_inherit_state(&mut self, v: bool) -> &mut Self {
1381        self.inherit_state = v;
1382        self
1383    }
1384
1385    pub fn clip_children(&self) -> bool {
1386        self.clip_children
1387    }
1388
1389    pub fn captures_wheel(&self) -> bool {
1390        self.captures_wheel
1391    }
1392
1393    pub fn captures_gesture(&self) -> bool {
1394        self.captures_gesture
1395    }
1396
1397    /// Pode receber o foco do teclado (como `CanFocus`).
1398    /// Arrastável: passar de alguns pontos com o
1399    /// botão pressionado dispara `on_drag_start`, e o handler começa o arrasto com
1400    /// [`Ui::begin_drag`](crate::Ui::begin_drag).
1401    pub fn draggable(&self) -> bool {
1402        self.draggable
1403    }
1404
1405    pub fn set_draggable(&mut self, v: bool) -> &mut Self {
1406        self.draggable = v;
1407        self
1408    }
1409
1410    /// Recebe o que é arrastado: `on_drag_over` ao entrar (o handler recusa com
1411    /// [`Ui::reject_drop`](crate::Ui::reject_drop)) e `on_drag_drop` ao soltar.
1412    pub fn accepts_drops(&self) -> bool {
1413        self.accepts_drops
1414    }
1415
1416    pub fn set_accepts_drops(&mut self, v: bool) -> &mut Self {
1417        self.accepts_drops = v;
1418        self
1419    }
1420
1421    /// O que vai no arrasto declarado (vazio: só com o `on_drag_start`).
1422    pub fn drag_data(&self) -> &str {
1423        self.drag.as_ref().map_or("", |d| d.data.as_str())
1424    }
1425
1426    pub fn drag_label(&self) -> &str {
1427        self.drag.as_ref().map_or("", |d| d.label.as_str())
1428    }
1429
1430    /// O `DragImage` do arrasto (a imagem que acompanha o cursor).
1431    pub fn drag_image(&self) -> Option<ComponentId> {
1432        self.drag.as_ref().and_then(|d| d.image)
1433    }
1434
1435    /// O `DragImage` foi liberado: a referência sai.
1436    pub(crate) fn forget_drag_image(&mut self, doomed: &[ComponentId]) {
1437        if let Some(d) = self.drag.as_mut().filter(|d| d.image.is_some_and(|i| doomed.contains(&i))) {
1438            d.image = None;
1439        }
1440    }
1441
1442    /// Os tipos aceitos ao soltar (vazio: decide o `on_drag_over`).
1443    pub fn drop_types(&self) -> &str {
1444        self.drag.as_ref().map_or("", |d| d.drop_types.as_str())
1445    }
1446
1447    fn drag_decl(&mut self) -> &mut DragDecl {
1448        self.drag.get_or_insert_with(Default::default)
1449    }
1450
1451    pub fn can_focus(&self) -> bool {
1452        self.can_focus
1453    }
1454
1455    /// Participa da navegação com Tab (como `TabStop`).
1456    pub fn tab_stop(&self) -> bool {
1457        self.tab_stop
1458    }
1459
1460    /// Menu de contexto do controle.
1461    pub fn popup_menu(&self) -> Option<ComponentId> {
1462        self.popup_menu
1463    }
1464
1465    pub fn set_popup_menu(&mut self, menu: Option<ComponentId>) -> &mut Self {
1466        self.popup_menu = menu;
1467        self
1468    }
1469
1470    /// Ver [`set_pan_on_touch`](Self::set_pan_on_touch).
1471    pub fn pan_on_touch(&self) -> bool {
1472        self.pan_on_touch
1473    }
1474
1475    /// Cursor do mouse sobre o controle. `Default` herda o do pai.
1476    pub fn cursor(&self) -> CursorShape {
1477        self.cursor
1478    }
1479
1480    pub fn opacity(&self) -> f32 {
1481        self.opacity
1482    }
1483
1484    /// Como o controle se junta ao que está por baixo (veja o campo).
1485    pub fn blend_mode(&self) -> crate::BlendMode {
1486        self.blend_mode
1487    }
1488
1489    pub fn set_blend_mode(&mut self, mode: crate::BlendMode) -> &mut Self {
1490        self.blend_mode = mode;
1491        self
1492    }
1493
1494    /// O desenho guardado numa imagem (veja o campo).
1495    pub fn cache_layer(&self) -> bool {
1496        self.cache_layer
1497    }
1498
1499    pub fn set_cache_layer(&mut self, on: bool) -> &mut Self {
1500        self.cache_layer = on;
1501        self
1502    }
1503
1504    /// Giro em graus, em torno do centro. Só a pintura gira; o clique usa o retângulo
1505    /// sem giro.
1506    pub fn rotation(&self) -> f32 {
1507        self.rotation
1508    }
1509
1510    /// A escala dele e de tudo dentro dele ([`set_scale`](Self::set_scale); 1 = normal).
1511    pub fn scale(&self) -> f32 {
1512        self.scale
1513    }
1514
1515    /// O tamanho do espaço de dentro: o do retângulo dividido pela escala. É nele que o
1516    /// controle se desenha (`PaintCtx::rect`) e que os filhos são arrumados.
1517    pub fn inner_size(&self) -> SizeF {
1518        let s = self.scale;
1519        if s == 1.0 { self.bounds.size() } else { SizeF::new(self.bounds.width / s, self.bounds.height / s) }
1520    }
1521
1522    pub fn shadow(&self) -> Option<crate::canvas::Shadow> {
1523        self.shadow
1524    }
1525
1526    /// Proporção fixa (largura ÷ altura); 0 = livre. No layout, a altura sai da largura
1527    /// (Top, Bottom, Horizontal, None), a largura sai da altura (Left, Right, Vertical) ou
1528    /// o controle cabe na área mantendo a proporção (Client, Center).
1529    pub fn aspect_ratio(&self) -> f32 {
1530        self.aspect_ratio
1531    }
1532
1533    pub fn set_aspect_ratio(&mut self, ratio: f32) -> &mut Self {
1534        self.aspect_ratio = if ratio.is_finite() { ratio.max(0.0) } else { 0.0 };
1535        self
1536    }
1537
1538    /// Largura máxima (0 = sem limite). O controle não passa dela; alinhado em cima, embaixo ou
1539    /// no cliente, fica no meio da área (o conteúdo de uma página que não se espalha numa tela
1540    /// larga). No form, é a largura máxima da janela.
1541    pub fn max_width(&self) -> f32 {
1542        self.max_width
1543    }
1544
1545    pub fn set_max_width(&mut self, width: f32) -> &mut Self {
1546        self.max_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1547        self
1548    }
1549
1550    /// Largura mínima (0 = sem limite). O layout não deixa o controle mais estreito que ela,
1551    /// mesmo alinhado (`top`, `client`...): o que passar da área do pai fica cortado (ou rola,
1552    /// num ScrollBox), e um texto com `wrap` para de quebrar nessa largura. No form, é a
1553    /// largura mínima da janela.
1554    pub fn min_width(&self) -> f32 {
1555        self.min_width
1556    }
1557
1558    pub fn set_min_width(&mut self, width: f32) -> &mut Self {
1559        self.min_width = if width.is_finite() { width.max(0.0) } else { 0.0 };
1560        self
1561    }
1562
1563    /// Altura mínima (0 = sem limite), como a [`min_width`](Self::min_width).
1564    pub fn min_height(&self) -> f32 {
1565        self.min_height
1566    }
1567
1568    pub fn set_min_height(&mut self, height: f32) -> &mut Self {
1569        self.min_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1570        self
1571    }
1572
1573    /// Altura máxima (0 = sem limite). No form, é a altura máxima da janela.
1574    pub fn max_height(&self) -> f32 {
1575        self.max_height
1576    }
1577
1578    pub fn set_max_height(&mut self, height: f32) -> &mut Self {
1579        self.max_height = if height.is_finite() { height.max(0.0) } else { 0.0 };
1580        self
1581    }
1582
1583    /// A largura que o controle ocupa numa faixa de `available` (com a `max_width` e a
1584    /// `min_width`; a mínima vence).
1585    pub fn clamp_width(&self, available: f32) -> f32 {
1586        let w = if self.max_width > 0.0 { available.min(self.max_width) } else { available };
1587        w.max(self.min_width)
1588    }
1589
1590    /// A altura dentro da `min_height` e da `max_height` (a mínima vence).
1591    pub fn clamp_height(&self, height: f32) -> f32 {
1592        let h = if self.max_height > 0.0 { height.min(self.max_height) } else { height };
1593        h.max(self.min_height)
1594    }
1595
1596    /// Encaixado, estica na faixa (`stretch`) ou fica com o próprio tamanho no começo, no
1597    /// meio ou no fim: veja [`SelfAlign`].
1598    pub fn self_align(&self) -> SelfAlign {
1599        self.self_align
1600    }
1601
1602    pub fn set_self_align(&mut self, align: SelfAlign) -> &mut Self {
1603        self.self_align = align;
1604        self
1605    }
1606
1607    /// A largura numa faixa horizontal de `available` (encaixado em cima ou embaixo): a faixa
1608    /// toda ou, com `self_align`, a própria `width`; com `self_align` e `max_width`, a faixa até
1609    /// a máxima (o `width: 100%; max-width` do CSS). Sempre dentro dos limites.
1610    pub fn band_width(&self, available: f32) -> f32 {
1611        match self.self_align {
1612            SelfAlign::Stretch => self.clamp_width(available),
1613            _ if self.max_width > 0.0 => self.clamp_width(available),
1614            _ => self.clamp_width(self.width),
1615        }
1616    }
1617
1618    /// A altura numa faixa vertical de `available` (encaixado à esquerda ou à direita), como a
1619    /// [`band_width`](Self::band_width).
1620    pub fn band_height(&self, available: f32) -> f32 {
1621        match self.self_align {
1622            SelfAlign::Stretch => self.clamp_height(available),
1623            _ if self.max_height > 0.0 => self.clamp_height(available),
1624            _ => self.clamp_height(self.height),
1625        }
1626    }
1627
1628    /// Onde começa um tamanho `size` numa faixa de `available`: no começo, no meio (o
1629    /// `stretch` com a largura máxima sobrando) ou no fim. Passando da faixa, no começo.
1630    pub fn band_offset(&self, available: f32, size: f32) -> f32 {
1631        let spare = (available - size).max(0.0);
1632        match self.self_align {
1633            SelfAlign::Start => 0.0,
1634            SelfAlign::End => spare,
1635            SelfAlign::Stretch | SelfAlign::Center => spare / 2.0,
1636        }
1637    }
1638
1639    /// A altura sai do conteúdo, na largura que o controle tem:
1640    /// um Label com `wrap` fica da altura do texto quebrado; um contêiner, da
1641    /// altura dos filhos encaixados em cima e embaixo (mais o padding). Vale com `align`
1642    /// `top`, `bottom` ou `none`.
1643    pub fn auto_size(&self) -> bool {
1644        self.auto_size
1645    }
1646
1647    pub fn set_auto_size(&mut self, on: bool) -> &mut Self {
1648        self.auto_size = on;
1649        self
1650    }
1651
1652    /// Quantas colunas ocupa num `GridLayout` (pelo menos 1; numa grade com menos colunas,
1653    /// ocupa a linha inteira).
1654    pub fn column_span(&self) -> u32 {
1655        self.column_span.max(1)
1656    }
1657
1658    /// O lugar fixo na grade: (linha, coluna), ou `None` (segue a ordem dos filhos).
1659    pub fn grid_cell(&self) -> Option<(u32, u32)> {
1660        (self.grid_row >= 0 && self.grid_column >= 0).then(|| (self.grid_row as u32, self.grid_column as u32))
1661    }
1662
1663    pub fn set_grid_cell(&mut self, cell: Option<(u32, u32)>) -> &mut Self {
1664        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));
1665        self.grid_row = r;
1666        self.grid_column = c;
1667        self
1668    }
1669
1670    /// Quantas linhas ocupa num `GridLayout` (o `rowspan`).
1671    pub fn row_span(&self) -> u32 {
1672        u32::from(self.row_span.max(1))
1673    }
1674
1675    pub fn set_row_span(&mut self, span: u32) -> &mut Self {
1676        self.row_span = span.clamp(1, 64) as u16;
1677        self
1678    }
1679
1680    pub fn grow(&self) -> f32 {
1681        self.grow
1682    }
1683
1684    pub fn set_grow(&mut self, grow: f32) -> &mut Self {
1685        self.grow = grow.max(0.0);
1686        self
1687    }
1688
1689    pub fn set_column_span(&mut self, span: u32) -> &mut Self {
1690        self.column_span = span.max(1);
1691        self
1692    }
1693
1694    /// A escala de fonte da vista ativa do form (1 sem vista).
1695    pub fn text_scale(&self) -> f32 {
1696        self.text_scale
1697    }
1698
1699    /// A escala de espaços da vista ativa do form (1 sem vista).
1700    pub fn spacing_scale(&self) -> f32 {
1701        self.spacing_scale
1702    }
1703
1704    pub fn tag(&self) -> i64 {
1705        self.tag
1706    }
1707
1708    /// O nome que o leitor de tela fala (o `aria-label`), no lugar do texto do controle: um
1709    /// botão só com ícone, um campo sem rótulo. O relatório do Tabernáculo, C29.
1710    pub fn accessible_name(&self) -> &str {
1711        self.rare.as_ref().map_or("", |r| &r.accessible_name)
1712    }
1713
1714    pub fn set_accessible_name(&mut self, v: &str) -> &mut Self {
1715        self.rare_mut(|r| r.accessible_name = v.into());
1716        self
1717    }
1718
1719    fn rare_mut(&mut self, change: impl FnOnce(&mut RareTexts)) {
1720        let rare = self.rare.get_or_insert_with(Default::default);
1721        change(rare);
1722        if rare.tag_string.is_empty() && rare.accessible_name.is_empty() {
1723            self.rare = None;
1724        }
1725    }
1726
1727    pub fn tag_string(&self) -> &str {
1728        self.rare.as_ref().map_or("", |r| &r.tag_string)
1729    }
1730
1731    /// Variante de estilo do tema ("primary", "danger", "flat"...). Vazio = estilo da classe.
1732    pub fn style(&self) -> &str {
1733        &self.style
1734    }
1735
1736    /// Tema próprio do controle (e dos filhos), pelo nome. Vazio = o do pai.
1737    pub fn theme_name(&self) -> &str {
1738        &self.theme
1739    }
1740
1741    pub fn set_theme_name(&mut self, v: impl Into<String>) -> &mut Self {
1742        self.theme = v.into();
1743        self
1744    }
1745
1746    /// Dica (balão) mostrada com o mouse parado sobre o controle. Vazio = a do pai.
1747    pub fn hint(&self) -> &str {
1748        &self.hint
1749    }
1750
1751    pub fn set_hint(&mut self, v: impl Into<String>) -> &mut Self {
1752        self.hint = v.into();
1753        self
1754    }
1755
1756    pub fn state(&self) -> ControlState {
1757        self.state
1758    }
1759
1760    /// Posição e tamanho reais, relativos ao pai, calculados pelo layout.
1761    pub fn bounds(&self) -> RectF {
1762        self.bounds
1763    }
1764
1765    /// Quanto o conteúdo está rolado: os filhos são deslocados por este valor.
1766    pub fn scroll_offset(&self) -> PointF {
1767        self.scroll_offset
1768    }
1769
1770    /// A rolagem com que o último layout pôs os filhos ([`scroll_offset`](Self::scroll_offset)
1771    /// muda na hora; esta, no layout): somada à posição de um filho, dá onde ele está no conteúdo.
1772    pub fn laid_out_scroll(&self) -> PointF {
1773        self.laid_out_scroll
1774    }
1775
1776    /// Rola o conteúdo. Chame `invalidate` (ou mude por `ui.control_mut`) para refazer o
1777    /// layout.
1778    pub fn set_scroll_offset(&mut self, offset: PointF) -> &mut Self {
1779        self.scroll_offset = offset;
1780        self
1781    }
1782
1783    /// Tamanho ocupado pelos filhos visíveis (com margens e padding), calculado no
1784    /// layout. Serve para saber até onde rolar.
1785    pub fn content_size(&self) -> SizeF {
1786        self.content_size
1787    }
1788
1789    // ----- escrita (encadeável) -----
1790
1791    // A posição e o tamanho pedidos mudaram: as âncoras medem de novo a partir daqui. Só quando
1792    // o valor muda de fato: regravar o mesmo valor a cada arrumação (o `auto_size`) refazia a
1793    // referência sempre, e o controle ancorado nunca acompanhava o pai (relatório do InsightDB,
1794    // 11/11: nem a célula do GridLayout, nem a janela em tela cheia).
1795    pub fn set_left(&mut self, v: f32) -> &mut Self {
1796        if self.left != v {
1797            self.left = v;
1798            self.anchor_ref = None;
1799        }
1800        self
1801    }
1802
1803    pub fn set_top(&mut self, v: f32) -> &mut Self {
1804        if self.top != v {
1805            self.top = v;
1806            self.anchor_ref = None;
1807        }
1808        self
1809    }
1810
1811    pub fn set_position(&mut self, left: f32, top: f32) -> &mut Self {
1812        self.set_left(left).set_top(top)
1813    }
1814
1815    pub fn set_width(&mut self, v: f32) -> &mut Self {
1816        if self.width != v.max(0.0) {
1817            self.width = v.max(0.0);
1818            self.anchor_ref = None;
1819        }
1820        self
1821    }
1822
1823    pub fn set_height(&mut self, v: f32) -> &mut Self {
1824        if self.height != v.max(0.0) {
1825            self.height = v.max(0.0);
1826            self.anchor_ref = None;
1827        }
1828        self
1829    }
1830
1831    /// A largura que o próprio layout mede (o `auto_size`), como [`set_measured_height`].
1832    pub(crate) fn set_measured_width(&mut self, v: f32) {
1833        self.width = v.max(0.0);
1834        if let Some(r) = self.anchor_ref.as_mut() {
1835            r.rect.width = self.width;
1836        }
1837    }
1838
1839    /// A altura que o próprio layout mede (o `auto_size`): muda o tamanho sem perder a
1840    /// referência das âncoras (a altura guardada nela acompanha).
1841    pub(crate) fn set_measured_height(&mut self, v: f32) {
1842        self.height = v.max(0.0);
1843        if let Some(r) = self.anchor_ref.as_mut() {
1844            r.rect.height = self.height;
1845        }
1846    }
1847
1848    pub fn set_size(&mut self, width: f32, height: f32) -> &mut Self {
1849        self.set_width(width).set_height(height)
1850    }
1851
1852    /// Define posição e tamanho de uma vez.
1853    pub fn set_rect(&mut self, left: f32, top: f32, width: f32, height: f32) -> &mut Self {
1854        self.set_position(left, top).set_size(width, height)
1855    }
1856
1857    pub fn set_margins(&mut self, v: impl Into<Bounds>) -> &mut Self {
1858        self.margins = v.into();
1859        self
1860    }
1861
1862    pub fn set_padding(&mut self, v: impl Into<Bounds>) -> &mut Self {
1863        self.padding = v.into();
1864        self
1865    }
1866
1867    pub fn set_align(&mut self, v: Align) -> &mut Self {
1868        self.align = v;
1869        self.anchor_ref = None;
1870        self
1871    }
1872
1873    pub fn set_anchors(&mut self, v: Anchors) -> &mut Self {
1874        self.anchors = v;
1875        self.anchor_ref = None;
1876        self
1877    }
1878
1879    pub fn set_visible(&mut self, v: bool) -> &mut Self {
1880        self.visible = v;
1881        self
1882    }
1883
1884    pub fn set_enabled(&mut self, v: bool) -> &mut Self {
1885        self.enabled = v;
1886        self
1887    }
1888
1889    pub fn set_hit_test(&mut self, v: bool) -> &mut Self {
1890        self.hit_test = v;
1891        self
1892    }
1893
1894    pub fn set_clip_children(&mut self, v: bool) -> &mut Self {
1895        self.clip_children = v;
1896        self
1897    }
1898
1899    pub fn set_captures_wheel(&mut self, v: bool) -> &mut Self {
1900        self.captures_wheel = v;
1901        self
1902    }
1903
1904    pub fn set_captures_gesture(&mut self, v: bool) -> &mut Self {
1905        self.captures_gesture = v;
1906        self
1907    }
1908
1909    pub fn set_can_focus(&mut self, v: bool) -> &mut Self {
1910        self.can_focus = v;
1911        self
1912    }
1913
1914    /// Arrastar o dedo sobre o controle rola o conteúdo (vira roda para o ScrollBox ou o
1915    /// DataGrid de baixo). Ligado por padrão; controles que precisam do arrasto em si (um
1916    /// Splitter, um designer) desligam.
1917    pub fn set_pan_on_touch(&mut self, v: bool) -> &mut Self {
1918        self.pan_on_touch = v;
1919        self
1920    }
1921
1922    pub fn set_tab_stop(&mut self, v: bool) -> &mut Self {
1923        self.tab_stop = v;
1924        self
1925    }
1926
1927    pub fn set_cursor(&mut self, v: CursorShape) -> &mut Self {
1928        self.cursor = v;
1929        self
1930    }
1931
1932    pub fn set_opacity(&mut self, v: f32) -> &mut Self {
1933        self.opacity = v.clamp(0.0, 1.0);
1934        self
1935    }
1936
1937    /// Deslocamento do desenho (sem mexer no layout).
1938    pub fn translate(&self) -> PointF {
1939        self.translate
1940    }
1941
1942    pub fn set_translate(&mut self, offset: PointF) -> &mut Self {
1943        self.translate = if offset.x.is_finite() && offset.y.is_finite() { offset } else { PointF::ZERO };
1944        self
1945    }
1946
1947    /// A escala dele e dos filhos (1 = normal; de 0,05 a 20).
1948    pub fn set_scale(&mut self, scale: f32) -> &mut Self {
1949        self.scale = if scale.is_finite() && scale > 0.0 { scale.clamp(0.05, 20.0) } else { 1.0 };
1950        self
1951    }
1952
1953    pub fn set_rotation(&mut self, degrees: f32) -> &mut Self {
1954        self.rotation = if degrees.is_finite() { degrees % 360.0 } else { 0.0 };
1955        self
1956    }
1957
1958    pub fn set_shadow(&mut self, shadow: Option<crate::canvas::Shadow>) -> &mut Self {
1959        self.shadow = shadow;
1960        self
1961    }
1962
1963    pub fn set_tag(&mut self, v: i64) -> &mut Self {
1964        self.tag = v;
1965        self
1966    }
1967
1968    pub fn set_tag_string(&mut self, v: &str) -> &mut Self {
1969        self.rare_mut(|r| r.tag_string = v.into());
1970        self
1971    }
1972
1973    pub fn set_style(&mut self, v: impl Into<String>) -> &mut Self {
1974        self.style = v.into();
1975        self
1976    }
1977
1978    /// Estado visual (hover, pressed...). Normalmente quem altera é o despacho de eventos;
1979    /// controles como CheckBox alteram `checked`.
1980    pub fn state_mut(&mut self) -> &mut ControlState {
1981        &mut self.state
1982    }
1983
1984    // ----- propriedades por nome -----
1985
1986    pub fn get_prop(&self, name: &str) -> Option<PropValue> {
1987        Some(match name {
1988            "left" => self.left.into(),
1989            "top" => self.top.into(),
1990            "width" => self.width.into(),
1991            "height" => self.height.into(),
1992            "align" => self.align.into(),
1993            "anchors" => self.anchors.into(),
1994            "margins" => self.margins.into(),
1995            "padding" => self.padding.into(),
1996            "visible" => self.visible.into(),
1997            "enabled" => self.enabled.into(),
1998            "hit_test" => self.hit_test.into(),
1999            "clip_children" => self.clip_children.into(),
2000            "inherit_state" => self.inherit_state.into(),
2001            "translate" => self.translatable.into(),
2002            "captures_wheel" => self.captures_wheel.into(),
2003            "captures_gesture" => self.captures_gesture.into(),
2004            "can_focus" => self.can_focus.into(),
2005            "draggable" => self.draggable.into(),
2006            "accepts_drops" => self.accepts_drops.into(),
2007            "drag_data" => self.drag_data().into(),
2008            "drag_label" => self.drag_label().into(),
2009            "drag_image" => PropValue::Component(self.drag_image()),
2010            "drop_types" => self.drop_types().into(),
2011            "tab_stop" => self.tab_stop.into(),
2012            "cursor" => PropValue::enum_value(self.cursor),
2013            "opacity" => self.opacity.into(),
2014            "blend_mode" => PropValue::enum_value(self.blend_mode),
2015            "cache_layer" => self.cache_layer.into(),
2016            "rotation" => self.rotation.into(),
2017            "scale" => self.scale.into(),
2018            "translate_x" => self.translate.x.into(),
2019            "translate_y" => self.translate.y.into(),
2020            "aspect_ratio" => self.aspect_ratio.into(),
2021            "max_width" => self.max_width.into(),
2022            "min_width" => self.min_width.into(),
2023            "min_height" => self.min_height.into(),
2024            "max_height" => self.max_height.into(),
2025            "self_align" => PropValue::enum_value(self.self_align),
2026            "auto_size" => self.auto_size.into(),
2027            "column_span" => (self.column_span() as i64).into(),
2028            "grid_row" => i64::from(self.grid_row).into(),
2029            "grid_column" => i64::from(self.grid_column).into(),
2030            "row_span" => (self.row_span() as i64).into(),
2031            "grow" => f64::from(self.grow).into(),
2032            "shadow" => crate::prop::PropType::to_value(&self.shadow),
2033            "style" => self.style.clone().into(),
2034            "fill" => crate::prop::PropType::to_value(&self.colors.fill),
2035            "border_color" => crate::prop::PropType::to_value(&self.colors.border),
2036            "text_color" => crate::prop::PropType::to_value(&self.colors.text),
2037            "accent_color" => crate::prop::PropType::to_value(&self.colors.accent),
2038            "success_color" => crate::prop::PropType::to_value(&self.colors.success),
2039            "warning_color" => crate::prop::PropType::to_value(&self.colors.warning),
2040            "danger_color" => crate::prop::PropType::to_value(&self.colors.danger),
2041            "font_family" => self.font.family.clone().into(),
2042            "font_size" => crate::prop::PropType::to_value(&self.font.size),
2043            "font_weight" => PropValue::Enum(FONT_WEIGHTS[self.font.weight.map_or(0, |w| w as usize + 1)].into()),
2044            "font_italic" => self.font.italic.into(),
2045            "font_underline" => self.font.underline.into(),
2046            "font_strikeout" => self.font.strikeout.into(),
2047            "theme" => self.theme.clone().into(),
2048            "hint" => self.hint.clone().into(),
2049            "tag" => self.tag.into(),
2050            "tag_string" => self.tag_string().to_string().into(),
2051            "accessible_name" => self.accessible_name().to_string().into(),
2052            "popup_menu" => PropValue::Component(self.popup_menu),
2053            _ => return None,
2054        })
2055    }
2056
2057    pub fn set_prop(&mut self, name: &str, value: PropValue) -> Result<()> {
2058        match name {
2059            "left" => self.set_left(value.to_f32()?),
2060            "top" => self.set_top(value.to_f32()?),
2061            "width" => self.set_width(value.to_f32()?),
2062            "height" => self.set_height(value.to_f32()?),
2063            "align" => self.set_align(value.to_enum()?),
2064            "anchors" => self.set_anchors(value.to_anchors()?),
2065            "margins" => self.set_margins(value.to_bounds()?),
2066            "padding" => self.set_padding(value.to_bounds()?),
2067            "visible" => self.set_visible(value.to_bool()?),
2068            "enabled" => self.set_enabled(value.to_bool()?),
2069            "hit_test" => self.set_hit_test(value.to_bool()?),
2070            "clip_children" => self.set_clip_children(value.to_bool()?),
2071            "inherit_state" => self.set_inherit_state(value.to_bool()?),
2072            "translate" => self.set_translatable(value.to_bool()?),
2073            "captures_wheel" => self.set_captures_wheel(value.to_bool()?),
2074            "captures_gesture" => self.set_captures_gesture(value.to_bool()?),
2075            "can_focus" => self.set_can_focus(value.to_bool()?),
2076            "draggable" => self.set_draggable(value.to_bool()?),
2077            "accepts_drops" => self.set_accepts_drops(value.to_bool()?),
2078            "drag_data" => {
2079                self.drag_decl().data = value.to_str()?.to_string();
2080                self
2081            }
2082            "drag_label" => {
2083                self.drag_decl().label = value.to_str()?.to_string();
2084                self
2085            }
2086            "drag_image" => {
2087                self.drag_decl().image = value.to_component()?;
2088                self
2089            }
2090            "drop_types" => {
2091                self.drag_decl().drop_types = value.to_str()?.to_string();
2092                self
2093            }
2094            "tab_stop" => self.set_tab_stop(value.to_bool()?),
2095            "cursor" => self.set_cursor(value.to_enum()?),
2096            "opacity" => self.set_opacity(value.to_f32()?),
2097            "blend_mode" => self.set_blend_mode(value.to_enum()?),
2098            "cache_layer" => self.set_cache_layer(value.to_bool()?),
2099            "rotation" => self.set_rotation(value.to_f32()?),
2100            "scale" => self.set_scale(value.to_f32()?),
2101            "translate_x" => self.set_translate(PointF::new(value.to_f32()?, self.translate.y)),
2102            "translate_y" => self.set_translate(PointF::new(self.translate.x, value.to_f32()?)),
2103            "aspect_ratio" => self.set_aspect_ratio(value.to_f32()?),
2104            "max_width" => self.set_max_width(value.to_f32()?),
2105            "min_width" => self.set_min_width(value.to_f32()?),
2106            "min_height" => self.set_min_height(value.to_f32()?),
2107            "max_height" => self.set_max_height(value.to_f32()?),
2108            "self_align" => self.set_self_align(value.to_enum()?),
2109            "auto_size" => self.set_auto_size(value.to_bool()?),
2110            "column_span" => self.set_column_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2111            "grid_row" => {
2112                self.grid_row = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2113                self
2114            }
2115            "grid_column" => {
2116                self.grid_column = value.to_f64()?.clamp(-1.0, 4096.0) as i16;
2117                self
2118            }
2119            "row_span" => self.set_row_span(value.to_f64()?.clamp(1.0, 64.0) as u32),
2120            "grow" => self.set_grow(value.to_f32()?),
2121            "shadow" => self.set_shadow(crate::prop::PropType::from_value(value)?),
2122            "style" => self.set_style(value.to_str()?),
2123            "fill" => {
2124                self.colors.fill = crate::prop::PropType::from_value(value)?;
2125                self
2126            }
2127            "border_color" => {
2128                self.colors.border = crate::prop::PropType::from_value(value)?;
2129                self
2130            }
2131            "text_color" => {
2132                self.colors.text = crate::prop::PropType::from_value(value)?;
2133                self
2134            }
2135            "accent_color" => {
2136                self.colors.accent = crate::prop::PropType::from_value(value)?;
2137                self
2138            }
2139            "success_color" => {
2140                self.colors.success = crate::prop::PropType::from_value(value)?;
2141                self
2142            }
2143            "warning_color" => {
2144                self.colors.warning = crate::prop::PropType::from_value(value)?;
2145                self
2146            }
2147            "danger_color" => {
2148                self.colors.danger = crate::prop::PropType::from_value(value)?;
2149                self
2150            }
2151            "font_family" => {
2152                self.font.family = value.to_str()?.to_string();
2153                self
2154            }
2155            "font_size" => {
2156                self.font.size = crate::prop::PropType::from_value(value)?;
2157                self
2158            }
2159            "font_weight" => {
2160                self.font.weight = font_weight_named(value.to_str()?)?;
2161                self
2162            }
2163            "font_italic" => {
2164                self.font.italic = value.to_bool()?;
2165                self
2166            }
2167            "font_underline" => {
2168                self.font.underline = value.to_bool()?;
2169                self
2170            }
2171            "font_strikeout" => {
2172                self.font.strikeout = value.to_bool()?;
2173                self
2174            }
2175            "theme" => self.set_theme_name(value.to_str()?),
2176            "hint" => self.set_hint(value.to_str()?),
2177            "tag" => self.set_tag(value.to_i64()?),
2178            "tag_string" => self.set_tag_string(value.to_str()?),
2179            "accessible_name" => self.set_accessible_name(value.to_str()?),
2180            "popup_menu" => {
2181                self.popup_menu = value.to_component()?;
2182                self
2183            }
2184            _ => return Err(Error::UnknownProperty(name.to_string())),
2185        };
2186        Ok(())
2187    }
2188}
2189
2190/// Os pesos da propriedade `font_weight`; `default` é o do pai (ou do tema).
2191pub const FONT_WEIGHTS: [&str; 8] = ["default", "thin", "light", "normal", "medium", "semibold", "bold", "black"];
2192
2193fn font_weight_named(name: &str) -> Result<Option<crate::canvas::FontWeight>> {
2194    use crate::canvas::FontWeight::*;
2195    let all = [Thin, Light, Normal, Medium, SemiBold, Bold, Black];
2196    match FONT_WEIGHTS.iter().position(|n| n.eq_ignore_ascii_case(name)) {
2197        Some(0) => Ok(None),
2198        Some(i) => Ok(Some(all[i - 1])),
2199        None => Err(Error::invalid(format!("valor '{name}' inválido; use um de: {}", FONT_WEIGHTS.join(", ")))),
2200    }
2201}
2202
2203/// A fonte de um controle por cima da do tema: família, tamanho,
2204/// peso, itálico, sublinhado e tachado. O que não tem valor vem do pai:
2205/// a fonte posta no form vale para tudo dentro dele.
2206#[derive(Clone, Debug, Default, PartialEq)]
2207pub struct FontOverride {
2208    /// A família da fonte (`"Segoe UI"`, `"monospace"`); vazio: a do pai.
2209    pub family: String,
2210    /// O tamanho da fonte, em pontos; sem valor: o do pai.
2211    pub size: Option<f32>,
2212    /// O peso da fonte (`normal`, `bold`...); sem valor: o do pai.
2213    pub weight: Option<crate::canvas::FontWeight>,
2214    /// Itálico; ligado vale também para os filhos.
2215    pub italic: bool,
2216    /// Sublinhado; ligado vale também para os filhos.
2217    pub underline: bool,
2218    /// Tachado (uma linha no meio do texto); ligado vale também para os filhos.
2219    pub strikeout: bool,
2220}
2221
2222impl FontOverride {
2223    pub fn is_empty(&self) -> bool {
2224        *self == Self::default()
2225    }
2226
2227    /// Esta fonte com o que faltar vindo de `parent`.
2228    pub fn over(&self, parent: &FontOverride) -> FontOverride {
2229        FontOverride {
2230            family: if self.family.is_empty() { parent.family.clone() } else { self.family.clone() },
2231            size: self.size.or(parent.size),
2232            weight: self.weight.or(parent.weight),
2233            italic: self.italic || parent.italic,
2234            underline: self.underline || parent.underline,
2235            strikeout: self.strikeout || parent.strikeout,
2236        }
2237    }
2238
2239    /// Aplica na fonte do estilo (a do tema).
2240    pub fn apply(&self, font: &mut crate::canvas::FontSpec) {
2241        if !self.family.is_empty() {
2242            font.family = self.family.clone();
2243        }
2244        if let Some(size) = self.size.filter(|s| *s > 0.0) {
2245            font.size = size;
2246        }
2247        if let Some(weight) = self.weight {
2248            font.weight = weight;
2249        }
2250        font.italic |= self.italic;
2251        font.underline |= self.underline;
2252        font.strikeout |= self.strikeout;
2253    }
2254}
2255
2256impl ControlBase {
2257    /// A fonte própria do controle (sem a herdada).
2258    pub fn font(&self) -> &FontOverride {
2259        &self.font
2260    }
2261
2262    pub fn set_font(&mut self, font: FontOverride) -> &mut Self {
2263        self.font = font;
2264        self
2265    }
2266}
2267
2268/// As cores próprias de um controle (vazio = as do tema):
2269/// valem para qualquer controle (`fill`, `border_color`, `text_color`, `accent_color` e as de
2270/// sentido: `success_color`, `warning_color`, `danger_color`).
2271/// O `Ui` as põe no estilo resolvido e no tema que o controle vê (`primary` e as variações,
2272/// `text`, `border`), então até os controles que leem o tema direto as seguem.
2273#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2274pub struct ColorOverride {
2275    /// A cor do fundo; vazio: a do tema.
2276    pub fill: Option<crate::Color>,
2277    /// A cor da borda; vazio: a do tema.
2278    pub border: Option<crate::Color>,
2279    /// A cor do texto; vazio: a do tema.
2280    pub text: Option<crate::Color>,
2281    /// O destaque: a marca da caixa de seleção, a barra do progresso, o trilho preenchido,
2282    /// a seleção, o foco.
2283    pub accent: Option<crate::Color>,
2284    /// As cores de sentido: subir/positivo, atenção e cair/erro (candles, variações, avisos).
2285    /// Esta é a de subir/positivo; vazio: a do tema.
2286    pub success: Option<crate::Color>,
2287    /// A cor de sentido de atenção (avisos); vazio: a do tema.
2288    pub warning: Option<crate::Color>,
2289    /// A cor de sentido de cair/erro (candles em queda, variações negativas, erros); vazio: a do tema.
2290    pub danger: Option<crate::Color>,
2291}
2292
2293impl ColorOverride {
2294    pub fn is_empty(&self) -> bool {
2295        *self == Self::default()
2296    }
2297
2298    /// Muda alguma cor do tema (não só o estilo).
2299    pub(crate) fn recolors_theme(&self) -> bool {
2300        !self.is_empty()
2301    }
2302
2303    /// O tema com as cores próprias por cima.
2304    pub(crate) fn apply_theme(&self, theme: &crate::Theme) -> crate::Theme {
2305        use crate::Color;
2306        let mut t = theme.clone();
2307        let mut set = |name: &str, c: Color| {
2308            t.colors.insert(name.to_string(), c);
2309        };
2310        if let Some(a) = self.accent {
2311            let dark = luminance(a) < 0.5;
2312            set("primary", a);
2313            set("primary_hover", a.lerp(if dark { Color::WHITE } else { Color::BLACK }, 0.12));
2314            set("primary_pressed", a.lerp(if dark { Color::BLACK } else { Color::BLACK }, 0.15));
2315            set("on_primary", if luminance(a) < 0.6 { Color::WHITE } else { Color::BLACK });
2316            set("focus_ring", a);
2317            set("selection", a.with_opacity(0.25));
2318            set("primary_soft", a.with_opacity(0.1));
2319            set("primary_container", a.lerp(Color::WHITE, 0.82));
2320        }
2321        if let Some(c) = self.fill {
2322            // O fundo: o da superfície e o das áreas de dentro (um pouco mais escuro ou claro).
2323            let toward = if luminance(c) < 0.5 { Color::WHITE } else { Color::BLACK };
2324            set("surface", c);
2325            set("background", c);
2326            set("surface_2", c.lerp(toward.with_opacity(c.a as f32 / 255.0), 0.06));
2327        }
2328        if let Some(c) = self.text {
2329            set("text", c);
2330            set("text_muted", c.with_opacity(0.65));
2331            for on in ["on_primary", "on_danger", "on_success", "on_primary_container"] {
2332                set(on, c);
2333            }
2334        }
2335        if let Some(c) = self.border {
2336            set("border", c);
2337            set("track", c);
2338        }
2339        for (token, color) in [("success", self.success), ("warning", self.warning), ("danger", self.danger)] {
2340            if let Some(c) = color {
2341                set(token, c);
2342                set(&format!("{token}_soft"), c.with_opacity(0.1));
2343                set(&format!("{token}_hover"), c.lerp(Color::WHITE, 0.12));
2344                set(&format!("{token}_pressed"), c.lerp(Color::BLACK, 0.15));
2345                if token == "success" {
2346                    set("meter_low", c);
2347                } else if token == "danger" {
2348                    set("meter_high", c);
2349                } else {
2350                    set("meter_mid", c);
2351                }
2352            }
2353        }
2354        t
2355    }
2356}
2357
2358/// Luminância relativa (0 escuro, 1 claro).
2359pub(crate) fn luminance(c: crate::Color) -> f32 {
2360    (0.299 * c.r as f32 + 0.587 * c.g as f32 + 0.114 * c.b as f32) / 255.0
2361}
2362
2363/// As duas pontas de um conector ([`Component::connection`]).
2364#[derive(Clone, Copy, Debug, PartialEq)]
2365pub struct Connection {
2366    pub from: ComponentId,
2367    /// O ponto de ligação em `from` (`(1, 0.5)`: o meio do lado direito).
2368    pub from_at: (f32, f32),
2369    pub to: ComponentId,
2370    pub to_at: (f32, f32),
2371}
2372
2373impl Connection {
2374    /// Quanto a ponta sai do componente antes da primeira dobra.
2375    pub const STUB: f32 = 16.0;
2376
2377    /// A direção para fora do lado onde está o ponto (`(1, 0.5)` → direita).
2378    fn normal(at: (f32, f32)) -> PointF {
2379        let (x, y) = at;
2380        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))];
2381        d.iter().min_by(|a, b| a.0.total_cmp(&b.0)).map_or(PointF::new(1.0, 0.0), |d| d.1)
2382    }
2383
2384    /// O caminho em ângulos retos entre os dois pontos (nas coordenadas do pai), dados os
2385    /// retângulos dos dois componentes.
2386    pub fn route(&self, from: RectF, to: RectF) -> Vec<PointF> {
2387        let p0 = PointF::new(from.x + from.width * self.from_at.0, from.y + from.height * self.from_at.1);
2388        let p1 = PointF::new(to.x + to.width * self.to_at.0, to.y + to.height * self.to_at.1);
2389        let (n0, n1) = (Self::normal(self.from_at), Self::normal(self.to_at));
2390        let s0 = PointF::new(p0.x + n0.x * Self::STUB, p0.y + n0.y * Self::STUB);
2391        let s1 = PointF::new(p1.x + n1.x * Self::STUB, p1.y + n1.y * Self::STUB);
2392        let mut points = vec![p0, s0];
2393        if n0.x != 0.0 {
2394            // Sai na horizontal: anda até o meio em x, desce/sobe, segue.
2395            let mx = (s0.x + s1.x) / 2.0;
2396            points.push(PointF::new(mx, s0.y));
2397            points.push(PointF::new(mx, s1.y));
2398        } else {
2399            let my = (s0.y + s1.y) / 2.0;
2400            points.push(PointF::new(s0.x, my));
2401            points.push(PointF::new(s1.x, my));
2402        }
2403        points.push(s1);
2404        points.push(p1);
2405        points.dedup_by(|a, b| (a.x - b.x).abs() < 0.01 && (a.y - b.y).abs() < 0.01);
2406        points
2407    }
2408}
2409
2410/// O arrasto declarado de um controle (fica fora do `ControlBase` comum: quase nenhum tem).
2411#[derive(Clone, Debug, Default, PartialEq)]
2412pub struct DragDecl {
2413    /// O que vai num arrasto que começa nele, sem handler (`"cliente:123"`: o tipo é o que vem
2414    /// antes do primeiro `:`); vazio: o arrasto declarado não leva nada.
2415    pub data: String,
2416    /// O texto que acompanha o mouse durante o arrasto; vazio: sem rótulo.
2417    pub label: String,
2418    /// Os tipos que este destino aceita, separados por `;` (`"cliente;produto"`); vazio: quem
2419    /// decide é o `on_drag_over`.
2420    pub drop_types: String,
2421    /// O `DragImage` que acompanha o cursor no arrasto (a imagem e o tamanho).
2422    pub image: Option<ComponentId>,
2423}
2424
2425/// Os textos raros do [`ControlBase`].
2426#[derive(Clone, Debug, Default)]
2427struct RareTexts {
2428    /// Um texto livre para o código (um id, um caminho, um JSON pequeno).
2429    tag_string: Box<str>,
2430    /// O nome que o leitor de tela fala, no lugar do texto do controle (um botão só com
2431    /// ícone, um campo sem rótulo); vazio: o texto do próprio controle.
2432    accessible_name: Box<str>,
2433}