Skip to main content

aylis_core/
platform.rs

1//! Serviços de plataforma (como as interfaces `IFMX*Service` do FMX).
2//!
3//! O core só conhece estes traits. Cada plataforma (Windows, Linux, web, Android, iOS)
4//! fornece as implementações num crate próprio e as entrega ao [`Ui`](crate::Ui) em
5//! [`Services`]. Sem serviços (por exemplo em testes), o `Ui` funciona normalmente,
6//! só não abre janelas.
7
8use crate::canvas::TextService;
9use crate::geometry::{RectF, SizeF};
10
11/// Identificador de uma janela nativa.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13pub struct WindowId(pub u64);
14
15/// Identificador de um timer.
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17pub struct TimerId(pub u64);
18
19/// Janelas nativas (como `IFMXWindowService`).
20pub trait WindowService {
21    fn create_window(&mut self, title: &str, size: SizeF) -> WindowId;
22    fn close_window(&mut self, window: WindowId);
23    fn set_title(&mut self, window: WindowId, title: &str);
24    fn set_size(&mut self, window: WindowId, size: SizeF);
25    /// Pede que a janela seja repintada no próximo frame.
26    fn request_redraw(&mut self, window: WindowId);
27    /// Escala de DPI da janela (1.0 = 96 dpi).
28    fn scale_factor(&self, window: WindowId) -> f32;
29}
30
31/// Timers e frames (como `IFMXTimerService`).
32pub trait TimerService {
33    fn start_timer(&mut self, interval_ms: u32, repeat: bool) -> TimerId;
34    fn stop_timer(&mut self, timer: TimerId);
35    /// Pede um frame (usado pelas animações; só enquanto houver animação ativa).
36    fn request_frame(&mut self);
37    /// Relógio monotônico em segundos.
38    fn now(&self) -> f64;
39}
40
41/// Área de transferência (como `IFMXClipboardService`).
42pub trait ClipboardService {
43    fn get_text(&mut self) -> Option<String>;
44    fn set_text(&mut self, text: &str);
45}
46
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub enum CursorShape {
49    #[default]
50    Default,
51    Pointer,
52    Text,
53    Wait,
54    Crosshair,
55    Move,
56    NotAllowed,
57    ResizeHorizontal,
58    ResizeVertical,
59    ResizeNeSw,
60    ResizeNwSe,
61    /// Sem cursor (o vídeo tocando com o mouse parado).
62    None,
63}
64
65impl CursorShape {
66    pub const ALL: [CursorShape; 12] = [
67        CursorShape::Default,
68        CursorShape::Pointer,
69        CursorShape::Text,
70        CursorShape::Wait,
71        CursorShape::Crosshair,
72        CursorShape::Move,
73        CursorShape::NotAllowed,
74        CursorShape::ResizeHorizontal,
75        CursorShape::ResizeVertical,
76        CursorShape::ResizeNeSw,
77        CursorShape::ResizeNwSe,
78        CursorShape::None,
79    ];
80}
81
82impl crate::prop::PropEnum for CursorShape {
83    const NAMES: &'static [&'static str] = &[
84        "default",
85        "pointer",
86        "text",
87        "wait",
88        "crosshair",
89        "move",
90        "not_allowed",
91        "resize_horizontal",
92        "resize_vertical",
93        "resize_ne_sw",
94        "resize_nw_se",
95        "none",
96    ];
97
98    fn from_index(index: usize) -> Option<Self> {
99        CursorShape::ALL.get(index).copied()
100    }
101
102    fn index(self) -> usize {
103        self as usize
104    }
105}
106
107/// Cursor do mouse (como `IFMXCursorService`). Plataformas sem mouse podem ignorar.
108pub trait CursorService {
109    fn set_cursor(&mut self, shape: CursorShape);
110}
111
112/// Aparência preferida pelo sistema.
113#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
114pub enum Appearance {
115    #[default]
116    Light,
117    Dark,
118}
119
120/// Tela (como `IFMXScreenService`).
121pub trait ScreenService {
122    fn screen_size(&self) -> SizeF;
123    fn scale_factor(&self) -> f32;
124    /// Tema claro/escuro do sistema operacional.
125    fn appearance(&self) -> Appearance;
126}
127
128/// Tipo de teclado virtual a mostrar no mobile.
129#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
130pub enum KeyboardKind {
131    #[default]
132    Text,
133    Number,
134    Decimal,
135    Phone,
136    Email,
137    Url,
138}
139
140/// Teclado virtual e IME (como `IFMXVirtualKeyboardService`).
141pub trait TextInputService {
142    fn show_keyboard(&mut self, kind: KeyboardKind);
143    fn hide_keyboard(&mut self);
144    /// Onde está o cursor de texto (para a janela de composição do IME).
145    fn set_ime_rect(&mut self, rect: RectF);
146}
147
148/// Formatos regionais (como o `FormatSettings`).
149#[derive(Clone, Debug, PartialEq)]
150pub struct LocaleInfo {
151    pub decimal_separator: char,
152    pub thousand_separator: char,
153    pub short_date_format: String,
154    pub long_time_format: String,
155    pub currency_symbol: String,
156    /// Nomes dos meses (janeiro a dezembro) e dos dias da semana abreviados (domingo
157    /// primeiro), para calendários.
158    pub month_names: [&'static str; 12],
159    pub short_day_names: [&'static str; 7],
160    /// Primeiro dia da semana nos calendários (0 = domingo).
161    pub first_day_of_week: u8,
162}
163
164const MONTHS_EN: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
165const DAYS_EN: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
166
167impl Default for LocaleInfo {
168    fn default() -> Self {
169        Self {
170            decimal_separator: '.',
171            thousand_separator: ',',
172            short_date_format: "yyyy-mm-dd".into(),
173            long_time_format: "hh:nn:ss".into(),
174            currency_symbol: "$".into(),
175            month_names: MONTHS_EN,
176            short_day_names: DAYS_EN,
177            first_day_of_week: 0,
178        }
179    }
180}
181
182impl LocaleInfo {
183    /// Português do Brasil: `1.234,56`, `dd/mm/yyyy`, `R$`.
184    pub fn pt_br() -> Self {
185        Self {
186            decimal_separator: ',',
187            thousand_separator: '.',
188            short_date_format: "dd/mm/yyyy".into(),
189            long_time_format: "hh:nn:ss".into(),
190            currency_symbol: "R$".into(),
191            month_names: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
192            short_day_names: ["dom", "seg", "ter", "qua", "qui", "sex", "sáb"],
193            first_day_of_week: 0,
194        }
195    }
196
197    /// Espanhol: `1.234,56`, `dd/mm/yyyy`, `€`, semana começando na segunda.
198    pub fn es() -> Self {
199        Self {
200            decimal_separator: ',',
201            thousand_separator: '.',
202            short_date_format: "dd/mm/yyyy".into(),
203            long_time_format: "hh:nn:ss".into(),
204            currency_symbol: "€".into(),
205            month_names: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],
206            short_day_names: ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"],
207            first_day_of_week: 1,
208        }
209    }
210
211    /// Inglês dos EUA: `1,234.56`, `mm/dd/yyyy`, `$`.
212    pub fn en_us() -> Self {
213        Self {
214            decimal_separator: '.',
215            thousand_separator: ',',
216            short_date_format: "mm/dd/yyyy".into(),
217            long_time_format: "hh:nn:ss".into(),
218            currency_symbol: "$".into(),
219            month_names: MONTHS_EN,
220            short_day_names: DAYS_EN,
221            first_day_of_week: 0,
222        }
223    }
224}
225
226pub trait LocaleService {
227    fn locale(&self) -> LocaleInfo;
228}
229
230/// Um `LocaleInfo` fixo também serve como serviço (útil para escolher o idioma do app).
231impl LocaleService for LocaleInfo {
232    fn locale(&self) -> LocaleInfo {
233        self.clone()
234    }
235}
236
237/// Eventos de ciclo de vida do aplicativo (importante no mobile).
238#[derive(Clone, Copy, Debug, PartialEq, Eq)]
239pub enum LifecycleEvent {
240    Resumed,
241    Suspended,
242    LowMemory,
243    /// A superfície de desenho foi perdida (GPU); é preciso recriar.
244    SurfaceLost,
245}
246
247/// Arquivos do aplicativo (imagens, áudio, vídeo, fontes) por caminho relativo à pasta
248/// do projeto, como `assets/images/logo.png`. No desktop vêm do disco; no Android podem vir
249/// de dentro do APK. O `aylis-project` instala um que lê da pasta do projeto.
250pub trait ResourceService {
251    fn read(&self, path: &str) -> Option<Vec<u8>>;
252}
253
254/// Cria forms pelo nome (como o `Application.CreateForm`). O `aylis-project` instala um que
255/// carrega os forms do projeto (`forms/*.json`).
256pub trait FormFactory {
257    /// Cria o form `name` (sem abrir) e devolve o id.
258    fn create_form(&mut self, ui: &mut crate::Ui, name: &str) -> Result<crate::ComponentId, String>;
259    /// Nomes dos forms que esta fábrica sabe criar.
260    fn form_names(&self) -> Vec<String>;
261}
262
263/// Opções de um diálogo de arquivo (Abrir/Salvar).
264#[derive(Clone, Debug, Default)]
265pub struct FileDialogOptions {
266    pub title: String,
267    /// (nome, extensões sem ponto): `("Imagens", ["png", "jpg"])`.
268    pub filters: Vec<(String, Vec<String>)>,
269    pub directory: String,
270    pub file_name: String,
271    /// Salvar em vez de abrir.
272    pub save: bool,
273    /// Abrir vários.
274    pub multiple: bool,
275}
276
277/// Diálogos de arquivo do sistema. Assíncronos: `done` recebe os caminhos escolhidos
278/// (vazio = cancelado), de qualquer thread.
279pub trait FileDialogService {
280    fn show(&mut self, options: FileDialogOptions, done: Box<dyn FnOnce(Vec<String>) + Send>);
281}
282
283/// Uma permissão que o sistema pergunta ao usuário (celular e navegador; no desktop quase
284/// tudo já vem liberado).
285#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
286pub enum Permission {
287    Camera,
288    Microphone,
289    /// A localização com o app aberto.
290    Location,
291    Notifications,
292    /// Fotos e vídeos da galeria.
293    Photos,
294    Contacts,
295    Calendar,
296    Bluetooth,
297}
298
299impl Permission {
300    pub const ALL: [Permission; 8] = [
301        Permission::Camera,
302        Permission::Microphone,
303        Permission::Location,
304        Permission::Notifications,
305        Permission::Photos,
306        Permission::Contacts,
307        Permission::Calendar,
308        Permission::Bluetooth,
309    ];
310
311    /// O nome usado nos forms e no código (`camera`, `microphone`...).
312    pub fn name(self) -> &'static str {
313        match self {
314            Permission::Camera => "camera",
315            Permission::Microphone => "microphone",
316            Permission::Location => "location",
317            Permission::Notifications => "notifications",
318            Permission::Photos => "photos",
319            Permission::Contacts => "contacts",
320            Permission::Calendar => "calendar",
321            Permission::Bluetooth => "bluetooth",
322        }
323    }
324
325    pub fn parse(name: &str) -> Option<Permission> {
326        let name = name.trim();
327        Permission::ALL.into_iter().find(|p| p.name().eq_ignore_ascii_case(name))
328    }
329
330    /// Uma lista separada por `;` (ou `,`); nomes desconhecidos ficam de fora.
331    pub fn parse_list(list: &str) -> Vec<Permission> {
332        let mut out = Vec::new();
333        for p in list.split([';', ',']).filter_map(Permission::parse) {
334            if !out.contains(&p) {
335                out.push(p);
336            }
337        }
338        out
339    }
340}
341
342/// A situação de uma permissão.
343#[derive(Clone, Copy, Debug, PartialEq, Eq)]
344pub enum PermissionState {
345    /// Liberada.
346    Granted,
347    /// Negada (no celular, às vezes só nas configurações do aparelho dá para liberar).
348    Denied,
349    /// Ainda não perguntada: pedir mostra a pergunta do sistema.
350    Prompt,
351    /// O aparelho ou o navegador não tem isso.
352    Unavailable,
353}
354
355impl PermissionState {
356    pub fn name(self) -> &'static str {
357        match self {
358            PermissionState::Granted => "granted",
359            PermissionState::Denied => "denied",
360            PermissionState::Prompt => "prompt",
361            PermissionState::Unavailable => "unavailable",
362        }
363    }
364}
365
366/// Consultar e pedir permissões ao sistema. `done` recebe cada permissão pedida com a
367/// resposta, de qualquer thread.
368pub trait PermissionService {
369    fn state(&self, permission: Permission) -> PermissionState;
370    fn request(&mut self, permissions: Vec<Permission>, done: Box<dyn FnOnce(Vec<(Permission, PermissionState)>) + Send>);
371}
372
373/// O tipo de biometria do aparelho.
374#[derive(Clone, Copy, Debug, PartialEq, Eq)]
375pub enum Biometry {
376    /// Sem biometria (ou nenhuma cadastrada).
377    None,
378    Fingerprint,
379    Face,
380    Iris,
381    /// Tem, mas o sistema não diz qual (Windows Hello, a chave do navegador, vários tipos).
382    Any,
383}
384
385impl Biometry {
386    pub fn name(self) -> &'static str {
387        match self {
388            Biometry::None => "none",
389            Biometry::Fingerprint => "fingerprint",
390            Biometry::Face => "face",
391            Biometry::Iris => "iris",
392            Biometry::Any => "any",
393        }
394    }
395}
396
397/// Como terminou a verificação biométrica.
398#[derive(Clone, Debug, PartialEq, Eq)]
399pub enum BiometricResult {
400    Success,
401    /// O usuário desistiu (ou o app foi para o fundo).
402    Cancelled,
403    /// Não reconheceu, bloqueou por tentativas, sem biometria: o motivo.
404    Failed(String),
405}
406
407/// A biometria do aparelho (digital, rosto; o Windows Hello). `done` recebe o resultado,
408/// de qualquer thread.
409pub trait BiometricService {
410    fn availability(&self) -> Biometry;
411    /// Pede a verificação mostrando `reason`. Com `allow_device_credential`, o PIN ou o
412    /// padrão do aparelho também valem.
413    fn authenticate(&mut self, reason: &str, allow_device_credential: bool, done: Box<dyn FnOnce(BiometricResult) + Send>);
414}
415
416/// Imprimir na impressora do sistema: mostra o diálogo de impressão (impressora, cópias,
417/// páginas) e imprime as páginas gravadas. `done` recebe `Ok(true)` (impresso), `Ok(false)`
418/// (cancelado) ou o erro, de qualquer thread.
419pub trait PrintService {
420    fn print(&mut self, title: &str, pages: crate::pages::PageSet, done: Box<dyn FnOnce(Result<bool, String>) + Send>);
421}
422
423/// Baixar da internet (HTTP GET) sem travar a interface (os blocos do mapa, imagens de
424/// um endereço). `done` recebe o corpo da resposta, ou o erro, de qualquer thread: use o
425/// [`Poster`](crate::Poster) para voltar à interface.
426pub trait HttpService {
427    fn get(&mut self, url: &str, done: Box<dyn FnOnce(Result<Vec<u8>, String>) + Send>);
428}
429
430/// Uma notificação do sistema (o toast do Windows, a notificação do Android).
431#[derive(Clone, Debug, Default, PartialEq)]
432pub struct SystemNotification {
433    /// Quem notifica (o AppUserModelID no Windows: `empresa.app`).
434    pub app_id: String,
435    /// O nome que aparece na notificação.
436    pub app_name: String,
437    pub title: String,
438    pub body: String,
439    /// Imagem (caminho de um PNG), opcional.
440    pub image: String,
441    /// A imagem em PNG já lida (dos assets do app, ou um form desenhado); vence `image`.
442    pub image_png: Vec<u8>,
443    /// Mostrar a imagem grande (embaixo do texto), em vez de miniatura ao lado.
444    pub big_image: bool,
445    /// Identifica a notificação: mostrar de novo com o mesmo número atualiza a anterior.
446    pub id: u32,
447    /// Canal (Android 8+): o usuário liga, desliga e escolhe o som por canal.
448    pub channel: String,
449    pub channel_name: String,
450    pub priority: NotificationPriority,
451    /// Botões da notificação: (identificador, texto).
452    pub actions: Vec<(String, String)>,
453    /// Fixa: o usuário não descarta (uma tarefa em andamento).
454    pub ongoing: bool,
455    /// Barra de progresso (0 a 1); `None`: sem barra.
456    pub progress: Option<f32>,
457    /// Tela cheia (Android): abre o app por cima de tudo, até da tela de bloqueio (uma
458    /// ligação, um alarme). Precisa da permissão `USE_FULL_SCREEN_INTENT`.
459    pub full_screen: bool,
460    /// O componente que recebe `on_click` e `on_action` quando o usuário toca.
461    pub component: Option<crate::ComponentId>,
462}
463
464/// Importância da notificação (no Android, a do canal: som, vibração, aparecer por cima).
465#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
466pub enum NotificationPriority {
467    /// Silenciosa, só na lista.
468    Low,
469    #[default]
470    Default,
471    /// Aparece por cima do app aberto (heads-up), com som.
472    High,
473}
474
475impl crate::PropEnum for NotificationPriority {
476    const NAMES: &'static [&'static str] = &["low", "default", "high"];
477    fn from_index(index: usize) -> Option<Self> {
478        [Self::Low, Self::Default, Self::High].get(index).copied()
479    }
480    fn index(self) -> usize {
481        self as usize
482    }
483}
484
485/// Notificações do sistema.
486pub trait NotificationService {
487    fn notify(&mut self, notification: &SystemNotification) -> Result<(), String>;
488    /// Tira a notificação `id` da lista.
489    fn cancel(&mut self, id: u32) -> Result<(), String> {
490        let _ = id;
491        Ok(())
492    }
493}
494
495/// Abrir endereços e outros apps, compartilhar e pedir algo a outro app (o componente
496/// `AppLink`). O que a plataforma não tem responde com o motivo.
497pub trait LinkService {
498    /// Abre o endereço no app que cuida dele (o navegador, o e-mail, o mapa, o discador).
499    fn open_url(&mut self, url: &str) -> Result<(), String>;
500    /// Abre outro app: o pacote no Android, o executável ou o nome registrado no desktop.
501    fn open_app(&mut self, app: &str) -> Result<(), String> {
502        Err(format!("abrir outro app não existe aqui ({app})"))
503    }
504    /// Compartilha texto e arquivos pela folha do sistema.
505    fn share(&mut self, text: &str, files: &[String]) -> Result<(), String> {
506        let _ = (text, files);
507        Err("compartilhar não existe aqui".into())
508    }
509    /// Pede `action` a outro app (uma `Intent` do Android com `data`): `done` recebe o que ele
510    /// devolveu, de qualquer thread.
511    fn request(&mut self, action: &str, data: &str, done: Box<dyn FnOnce(Result<String, String>) + Send>) {
512        let _ = data;
513        done(Err(format!("pedir a outro app não existe aqui ({action})")));
514    }
515}
516
517/// Os sensores do aparelho (os componentes da categoria "Dispositivo").
518#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
519pub enum Sensor {
520    /// `[latitude, longitude, precisão em metros, altitude, velocidade em m/s]`.
521    Location,
522    /// `[carga de 0 a 1, carregando 0/1]`.
523    Battery,
524    /// `[conectado 0/1, tipo: 0 nenhum, 1 Wi-Fi, 2 celular, 3 cabo, 4 outro]`.
525    Network,
526    /// A aceleração com a gravidade, em m/s²: `[x, y, z]`.
527    Motion,
528    /// `[rumo em graus, 0 = norte]`.
529    Compass,
530    /// `[distância em cm, perto 0/1]`.
531    Proximity,
532    /// `[lux]`.
533    Light,
534}
535
536/// Lê os sensores do aparelho. A plataforma guarda a última leitura de cada um (os
537/// componentes consultam num timer) e só mede os ligados (bateria e rede valem sempre).
538pub trait SensorService {
539    /// O aparelho tem esse sensor.
540    fn available(&self, sensor: Sensor) -> bool;
541    /// Começa ou para de medir (a localização pede a permissão na primeira vez).
542    fn set_active(&mut self, sensor: Sensor, on: bool);
543    /// A última leitura (`None`: ainda não mediu).
544    fn read(&mut self, sensor: Sensor) -> Option<Vec<f64>>;
545    /// Vibra por `ms` milissegundos; `false` se o aparelho não vibra.
546    fn vibrate(&mut self, ms: u32) -> bool {
547        let _ = ms;
548        false
549    }
550}
551
552/// Os botões de um controle de jogo (o componente `Gamepad`), com os nomes do Xbox; no
553/// PlayStation, `a` = ✕, `b` = ○, `x` = □ e `y` = △. O bit `i` de [`GamepadState::buttons`]
554/// é o botão `GAMEPAD_BUTTONS[i]`.
555pub const GAMEPAD_BUTTONS: [&str; 17] =
556    ["a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "l3", "r3", "up", "down", "left", "right", "guide"];
557
558/// Um controle de jogo conectado.
559#[derive(Clone, Debug, Default, PartialEq)]
560pub struct GamepadState {
561    pub name: String,
562    /// Os botões apertados (um bit por nome de [`GAMEPAD_BUTTONS`]).
563    pub buttons: u32,
564    /// `[esquerdo x, esquerdo y, direito x, direito y, gatilho esquerdo, gatilho direito]`:
565    /// os analógicos de -1 a 1 (y positivo para baixo, como na tela), os gatilhos de 0 a 1.
566    pub axes: [f32; 6],
567}
568
569impl GamepadState {
570    /// Marca o botão pelo nome (os da plataforma usam ao montar o estado).
571    pub fn set_button(&mut self, name: &str, down: bool) {
572        if let Some(i) = GAMEPAD_BUTTONS.iter().position(|b| *b == name) {
573            if down {
574                self.buttons |= 1 << i;
575            } else {
576                self.buttons &= !(1 << i);
577            }
578        }
579    }
580
581    pub fn pressed(&self, name: &str) -> bool {
582        GAMEPAD_BUTTONS.iter().position(|b| *b == name).is_some_and(|i| self.buttons & (1 << i) != 0)
583    }
584}
585
586/// Os controles de jogo (o componente `Gamepad`). O componente consulta a cada quadro.
587pub trait GamepadService {
588    /// Os controles conectados agora, na ordem em que entraram.
589    fn pads(&mut self) -> Vec<GamepadState>;
590    /// Vibra o controle `index` com a força (0 a 1) por `ms`; `false` se ele não vibra.
591    fn rumble(&mut self, index: usize, strength: f32, ms: u32) -> bool {
592        let _ = (index, strength, ms);
593        false
594    }
595}
596
597/// Ligações e a tela de bloqueio (os componentes `Phone` e `LockScreen`; hoje, o Android).
598pub trait PhoneService {
599    /// Abre o discador com o número (sem permissão).
600    fn dial(&mut self, number: &str) -> Result<(), String>;
601    /// Liga direto (a permissão `CALL_PHONE`, pedida na primeira vez).
602    fn call(&mut self, number: &str) -> Result<(), String>;
603    /// Acompanha o estado das chamadas (`READ_PHONE_STATE`).
604    fn watch(&mut self, on: bool);
605    /// O estado agora (`idle`, `ringing`, `dialing`, `active`, `holding`) e o número (quando o
606    /// sistema informa).
607    fn state(&mut self) -> (String, String);
608    /// O modo "app de telefone": pede para ser o discador padrão (o `InCallService`).
609    fn request_dialer(&mut self) -> Result<(), String> {
610        Err("não existe aqui".into())
611    }
612    /// No modo "app de telefone": atender, recusar, desligar.
613    fn answer(&mut self) -> bool {
614        false
615    }
616    fn reject(&mut self) -> bool {
617        false
618    }
619    fn hang_up(&mut self) -> bool {
620        false
621    }
622    /// As últimas `max` chamadas (`READ_CALL_LOG`): `número|tipo|quando|segundos` por linha.
623    fn history(&mut self, max: u32) -> Result<String, String> {
624        let _ = max;
625        Err("não existe aqui".into())
626    }
627    /// O form sobre a tela de bloqueio e acender a tela ao abrir.
628    fn lock_screen(&mut self, show_when_locked: bool, turn_screen_on: bool);
629    /// Pede ao sistema para destravar (o usuário confirma).
630    fn dismiss_keyguard(&mut self);
631}
632
633/// O serviço em primeiro plano do sistema (o Android: a notificação fixa que mantém o
634/// processo vivo com a tela fechada). `kind`: o tipo do Android 14+ (`dataSync`, `location`,
635/// `mediaPlayback`, `connectedDevice`...); `keep_alive`: o sistema reinicia o serviço (e no
636/// boot) e o app pede a isenção da otimização de bateria.
637pub trait BackgroundHost {
638    fn start(&mut self, title: &str, text: &str, kind: &str, keep_alive: bool) -> Result<(), String>;
639    fn stop(&mut self);
640}
641
642/// O que chega de fora para o app: um link que abriu o app (`on_link`) ou algo que outro
643/// app compartilhou com ele (`on_shared`: o texto, ou os arquivos separados por `;`).
644#[derive(Clone, Debug, PartialEq, Eq)]
645pub enum Incoming {
646    Link(String),
647    Shared(String),
648}
649
650static INCOMING: std::sync::Mutex<Vec<Incoming>> = std::sync::Mutex::new(Vec::new());
651
652/// A plataforma entrega o que chegou de fora (de qualquer thread). Fica guardado até um
653/// `AppLink` pegar: o app aberto pelo próprio link ainda nem criou o form.
654pub fn push_incoming(item: Incoming) {
655    if let Ok(mut list) = INCOMING.lock() {
656        list.push(item);
657    }
658}
659
660/// Tira da fila o que chegou de fora (o `AppLink` chama).
661pub fn take_incoming() -> Vec<Incoming> {
662    INCOMING.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
663}
664
665/// Desenho fora da tela: o `Ui` pinta um componente numa imagem (a notificação com "um
666/// form inteiro", capturas). A plataforma fornece com o renderizador dela.
667pub trait OffscreenService {
668    /// `width` x `height` em unidades lógicas, multiplicadas por `scale` em pixels.
669    fn render_png(&self, width: u32, height: u32, scale: f32, background: crate::Color, paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>>;
670}
671
672/// Conjunto de serviços fornecidos pela plataforma. Todos são opcionais.
673#[derive(Default)]
674pub struct Services {
675    pub offscreen: Option<Box<dyn OffscreenService>>,
676    pub window: Option<Box<dyn WindowService>>,
677    pub timer: Option<Box<dyn TimerService>>,
678    pub clipboard: Option<Box<dyn ClipboardService>>,
679    pub cursor: Option<Box<dyn CursorService>>,
680    pub screen: Option<Box<dyn ScreenService>>,
681    pub text_input: Option<Box<dyn TextInputService>>,
682    pub locale: Option<Box<dyn LocaleService>>,
683    pub text: Option<Box<dyn TextService>>,
684    pub resources: Option<Box<dyn ResourceService>>,
685    pub forms: Option<Box<dyn FormFactory>>,
686    pub file_dialogs: Option<Box<dyn FileDialogService>>,
687    /// Consultar e pedir permissões (câmera, localização...): o componente `Permissions`.
688    pub permissions: Option<Box<dyn PermissionService>>,
689    /// Digital, rosto, Windows Hello: o componente `Biometrics`.
690    pub biometrics: Option<Box<dyn BiometricService>>,
691    pub http: Option<Box<dyn HttpService>>,
692    pub notifications: Option<Box<dyn NotificationService>>,
693    /// Abrir endereços e apps, compartilhar: o componente `AppLink`.
694    pub links: Option<Box<dyn LinkService>>,
695    /// Localização, bateria, rede, movimento, bússola, proximidade, luz e vibração.
696    pub sensors: Option<Box<dyn SensorService>>,
697    /// O serviço em primeiro plano (o `BackgroundService`); sem ele, a lógica roda enquanto o
698    /// app roda.
699    pub background: Option<Box<dyn BackgroundHost>>,
700    /// Ligações e tela de bloqueio (`Phone`, `LockScreen`).
701    pub phone: Option<Box<dyn PhoneService>>,
702    /// Controles de jogo (`Gamepad`).
703    pub gamepads: Option<Box<dyn GamepadService>>,
704    pub printer: Option<Box<dyn PrintService>>,
705    /// Correção e sugestão de texto dos campos (`spellcheck`, `autocomplete`): o motor
706    /// nativo da plataforma, ou outro que o app ponha no lugar ([`crate::textassist`]).
707    pub text_assist: Option<Box<dyn crate::textassist::TextAssist>>,
708    /// Tags NFC (`Nfc`).
709    pub nfc: Option<Box<dyn NfcService>>,
710    /// Bluetooth BLE e clássico (`Bluetooth`).
711    pub bluetooth: Option<Box<dyn BluetoothService>>,
712    /// Notificações push (`PushNotifications`): FCM, APNs, Web Push, WNS, UnifiedPush.
713    pub push: Option<Box<dyn PushService>>,
714    /// As ações do aparelho (`WakeAppAction`, `NotifyAction`) e as regras do `PushTrigger`
715    /// executadas pela plataforma, também com o app fechado. Sem ele, os componentes fazem o
716    /// que dá com o app aberto (mostrar o form, a notificação comum).
717    pub actions: Option<Box<dyn ActionService>>,
718}
719
720/// Uma tag NFC encostada.
721#[derive(Clone, Debug, Default, PartialEq, Eq)]
722pub struct NfcTag {
723    /// O id em hexadecimal com dois pontos (`04:A2:1B:...`; [`crate::ndef::id_text`]).
724    pub id: String,
725    /// A tecnologia (`NfcA`, `MifareUltralight`, `IsoDep`...), como a plataforma informa.
726    pub tech: String,
727    /// A mensagem NDEF (vazia numa tag sem NDEF).
728    pub records: Vec<crate::ndef::NdefRecord>,
729    /// Dá para gravar nela.
730    pub writable: bool,
731}
732
733/// O que o [`NfcService`] tem para contar.
734#[derive(Clone, Debug, PartialEq, Eq)]
735pub enum NfcEvent {
736    Tag(NfcTag),
737    /// A gravação pedida terminou.
738    Written,
739    Error(String),
740}
741
742/// Ler e gravar tags NFC (o componente `Nfc`). O componente consulta [`NfcService::poll`]
743/// num timer; ler só funciona com o app na frente.
744pub trait NfcService {
745    /// Há NFC aqui (o aparelho tem, ou há um leitor USB ligado).
746    fn available(&self) -> bool;
747    /// O NFC está ligado (no Android dá para desligar nas configurações).
748    fn enabled(&self) -> bool {
749        self.available()
750    }
751    /// Começa ou para de ler as tags que encostarem.
752    fn set_reading(&mut self, on: bool);
753    /// Grava a mensagem NDEF ([`crate::ndef::encode`]) na próxima tag que encostar; o
754    /// resultado chega como [`NfcEvent::Written`] ou [`NfcEvent::Error`].
755    fn write(&mut self, message: Vec<u8>);
756    /// Desiste da gravação pendente.
757    fn cancel_write(&mut self) {}
758    /// O que aconteceu desde a última consulta.
759    fn poll(&mut self) -> Vec<NfcEvent>;
760}
761
762/// Um aparelho Bluetooth achado.
763#[derive(Clone, Debug, Default, PartialEq, Eq)]
764pub struct BleDevice {
765    /// O endereço (Android, Windows, Linux) ou o identificador que o sistema dá (macOS, iOS,
766    /// navegador).
767    pub id: String,
768    pub name: String,
769    /// A força do sinal em dBm (0: o sistema não informou).
770    pub rssi: i32,
771}
772
773/// Uma característica de um aparelho conectado.
774#[derive(Clone, Debug, Default, PartialEq, Eq)]
775pub struct BleCharacteristic {
776    pub service: String,
777    pub characteristic: String,
778    /// `read`, `write`, `write_without_response`, `notify`, `indicate`.
779    pub properties: Vec<String>,
780}
781
782/// O que o [`BluetoothService`] tem para contar.
783#[derive(Clone, Debug, PartialEq, Eq)]
784pub enum BluetoothEvent {
785    Found(BleDevice),
786    /// A procura parou (pedido, erro ou o sistema parou).
787    ScanStopped,
788    /// Conectado (BLE, com as características; o clássico, sem).
789    Connected { device: String, services: Vec<BleCharacteristic> },
790    Disconnected(String),
791    /// Uma leitura pedida ou um aviso (`notify`/`indicate`).
792    Value { device: String, characteristic: String, data: Vec<u8> },
793    Written { device: String, characteristic: String },
794    /// Bytes que chegaram pelo canal serial (clássico).
795    Received { device: String, data: Vec<u8> },
796    Error(String),
797}
798
799/// Bluetooth (o componente `Bluetooth`): BLE e o canal serial do clássico (SPP/RFCOMM). As
800/// operações respondem depois, pelo [`BluetoothService::poll`]; os uuids chegam inteiros e
801/// em minúsculas ([`ble_uuid`]).
802pub trait BluetoothService {
803    fn available(&self) -> bool;
804    /// O Bluetooth está ligado.
805    fn enabled(&self) -> bool {
806        self.available()
807    }
808    /// Começa (com os serviços que o aparelho anuncia e parte do nome; vazios, todos) ou
809    /// para de procurar.
810    fn scan(&mut self, on: bool, services: Vec<String>, name: String);
811    fn connect(&mut self, device: &str);
812    fn disconnect(&mut self, device: &str);
813    fn read(&mut self, device: &str, service: &str, characteristic: &str);
814    fn write(&mut self, device: &str, service: &str, characteristic: &str, data: Vec<u8>, with_response: bool);
815    /// Liga ou desliga os avisos de mudança (`notify` ou `indicate`).
816    fn subscribe(&mut self, device: &str, service: &str, characteristic: &str, on: bool);
817    /// Os aparelhos pareados (clássico): id e nome.
818    fn paired(&mut self) -> Vec<(String, String)> {
819        Vec::new()
820    }
821    /// Abre o canal serial (SPP) com um pareado; conecta depois ([`BluetoothEvent::Connected`]).
822    fn open_serial(&mut self, device: &str) -> Result<(), String> {
823        let _ = device;
824        Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
825    }
826    fn send_serial(&mut self, device: &str, data: Vec<u8>) -> Result<(), String> {
827        let _ = (device, data);
828        Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
829    }
830    fn close_serial(&mut self, device: &str) {
831        let _ = device;
832    }
833    /// O que aconteceu desde a última consulta.
834    fn poll(&mut self) -> Vec<BluetoothEvent>;
835}
836
837/// O uuid inteiro e em minúsculas: a forma curta do Bluetooth SIG (`180D`, `0x2A37`) vira
838/// `0000180d-0000-1000-8000-00805f9b34fb`.
839pub fn ble_uuid(text: &str) -> String {
840    let t = text.trim().trim_start_matches("0x").trim_start_matches("0X").to_ascii_lowercase();
841    if (t.len() == 4 || t.len() == 8) && t.chars().all(|c| c.is_ascii_hexdigit()) {
842        format!("{t:0>8}-0000-1000-8000-00805f9b34fb")
843    } else {
844        t
845    }
846}
847
848/// Uma notificação push que chegou.
849#[derive(Clone, Debug, Default, PartialEq, Eq)]
850pub struct PushMessage {
851    /// O id que o serviço deu (vazio se ele não deu).
852    pub id: String,
853    /// O título e o texto da parte "notification" (vazios numa mensagem só de dados).
854    pub title: String,
855    pub body: String,
856    /// Os dados do app, como um objeto JSON (`{}` sem dados).
857    pub data: String,
858}
859
860/// O que chega das notificações push.
861#[derive(Clone, Debug, PartialEq, Eq)]
862pub enum PushEvent {
863    /// O endereço deste aparelho no serviço (o token do FCM, o do APNs em hexadecimal, a
864    /// assinatura do Web Push em JSON, o canal do WNS, o endpoint do UnifiedPush): o app
865    /// manda ao servidor dele, que usa para enviar.
866    Token(String),
867    /// Uma mensagem chegou com o app aberto.
868    Message(PushMessage),
869    /// O usuário tocou na notificação (o app abriu ou voltou para a frente por ela).
870    Opened(PushMessage),
871    Error(String),
872}
873
874/// A configuração do registro. Cada serviço usa a parte dele: o FCM (Android), as quatro
875/// primeiras, que estão no `google-services.json`; o Web Push, a chave VAPID pública.
876#[derive(Clone, Debug, Default, PartialEq, Eq)]
877pub struct PushConfig {
878    /// O número do projeto do Firebase (`project_number`, o "sender id").
879    pub sender_id: String,
880    /// O id do projeto (`project_id`).
881    pub project_id: String,
882    /// O id do app no Firebase (`mobilesdk_app_id`: `1:123:android:abc`).
883    pub app_id: String,
884    /// A chave da API (`current_key`).
885    pub api_key: String,
886    /// A chave VAPID pública (base64url) do servidor que envia o Web Push.
887    pub vapid_key: String,
888    /// Com o app aberto, a mensagem com título também aparece como notificação do sistema
889    /// (sem isso, só o `on_message`).
890    pub show_in_foreground: bool,
891}
892
893/// Notificações push (o componente `PushNotifications`). O registro responde depois: o
894/// token, as mensagens e os toques chegam por [`push_event`] (de qualquer thread, quando o
895/// sistema chama) ou pelo [`PushService::poll`].
896pub trait PushService {
897    /// Há um serviço de push aqui (no Android, o Google Play Services; no navegador, a Push
898    /// API e o service worker).
899    fn available(&self) -> bool;
900    /// O serviço: `fcm`, `apns`, `webpush`, `wns` ou `unifiedpush` (o servidor precisa saber
901    /// por onde enviar).
902    fn provider(&self) -> &'static str;
903    /// Pede a permissão de notificar (onde é preciso) e registra; o token chega como
904    /// [`PushEvent::Token`].
905    fn register(&mut self, config: &PushConfig);
906    /// Deixa de receber (o token deixa de valer).
907    fn unregister(&mut self) {}
908    /// A própria plataforma mostra a notificação da mensagem (Android, iOS, macOS,
909    /// navegador). Sem isso (o WNS raw, o UnifiedPush), o componente mostra pelo
910    /// [`NotificationService`] com o `show_in_foreground`.
911    fn shows_notifications(&self) -> bool {
912        true
913    }
914    /// O que aconteceu desde a última consulta (as plataformas que guardam numa fila).
915    fn poll(&mut self) -> Vec<PushEvent> {
916        Vec::new()
917    }
918}
919
920static PUSH_EVENTS: std::sync::Mutex<Vec<PushEvent>> = std::sync::Mutex::new(Vec::new());
921
922/// A plataforma entrega um evento de push (de qualquer thread). Fica guardado até o
923/// `PushNotifications` pegar: o toque que abriu o app chega antes de o form existir.
924pub fn push_event(event: PushEvent) {
925    if let Ok(mut list) = PUSH_EVENTS.lock() {
926        list.push(event);
927    }
928}
929
930/// Tira da fila os eventos de push (o `PushNotifications` chama).
931pub fn take_push_events() -> Vec<PushEvent> {
932    PUSH_EVENTS.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
933}
934
935/// Uma linha de evento de push no formato que as plataformas com código fora do Rust usam
936/// (o Java do Android, o service worker): campos separados por tab, `token	<token>`,
937/// `message	<id>	<título>	<texto>	<dados JSON>`, `opened	...` e `error	<mensagem>`.
938pub fn parse_push_line(line: &str) -> Option<PushEvent> {
939    let mut f = line.split('\t');
940    let kind = f.next()?;
941    let mut next = || f.next().unwrap_or_default().to_string();
942    match kind {
943        "token" => Some(PushEvent::Token(next())),
944        "error" => Some(PushEvent::Error(next())),
945        "message" | "opened" => {
946            let mut m = PushMessage { id: next(), title: next(), body: next(), data: next() };
947            if m.data.trim().is_empty() {
948                m.data = "{}".into();
949            }
950            Some(if kind == "message" { PushEvent::Message(m) } else { PushEvent::Opened(m) })
951        }
952        _ => None,
953    }
954}
955
956/// O valor de `key` num objeto JSON de um nível (os dados do push são texto → texto): o
957/// texto sem as aspas, ou o valor como está (número, `true`, objeto).
958pub fn json_field(json: &str, key: &str) -> Option<String> {
959    let chars: Vec<char> = json.chars().collect();
960    let mut i = 0;
961    let skip_ws = |i: &mut usize| {
962        while *i < chars.len() && chars[*i].is_whitespace() {
963            *i += 1;
964        }
965    };
966    // Lê um texto entre aspas a partir de `i` (em cima da aspa).
967    let read_string = |i: &mut usize| -> Option<String> {
968        if chars.get(*i) != Some(&'"') {
969            return None;
970        }
971        *i += 1;
972        let mut out = String::new();
973        while *i < chars.len() {
974            let c = chars[*i];
975            *i += 1;
976            match c {
977                '"' => return Some(out),
978                '\\' => {
979                    let e = *chars.get(*i)?;
980                    *i += 1;
981                    match e {
982                        'n' => out.push('\n'),
983                        't' => out.push('\t'),
984                        'r' => out.push('\r'),
985                        'b' => out.push('\u{8}'),
986                        'f' => out.push('\u{c}'),
987                        'u' => {
988                            let hex: String = chars.get(*i..*i + 4)?.iter().collect();
989                            *i += 4;
990                            let mut code = u32::from_str_radix(&hex, 16).ok()?;
991                            // Par substituto (emoji): 😀.
992                            if (0xD800..0xDC00).contains(&code) && chars.get(*i) == Some(&'\\') && chars.get(*i + 1) == Some(&'u') {
993                                let low: String = chars.get(*i + 2..*i + 6)?.iter().collect();
994                                if let Ok(low) = u32::from_str_radix(&low, 16) {
995                                    *i += 6;
996                                    code = 0x10000 + ((code - 0xD800) << 10) + (low.wrapping_sub(0xDC00) & 0x3FF);
997                                }
998                            }
999                            out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
1000                        }
1001                        other => out.push(other),
1002                    }
1003                }
1004                c => out.push(c),
1005            }
1006        }
1007        None
1008    };
1009    skip_ws(&mut i);
1010    if chars.get(i) != Some(&'{') {
1011        return None;
1012    }
1013    i += 1;
1014    loop {
1015        skip_ws(&mut i);
1016        if chars.get(i) == Some(&'}') || i >= chars.len() {
1017            return None;
1018        }
1019        let name = read_string(&mut i)?;
1020        skip_ws(&mut i);
1021        if chars.get(i) != Some(&':') {
1022            return None;
1023        }
1024        i += 1;
1025        skip_ws(&mut i);
1026        let value = if chars.get(i) == Some(&'"') {
1027            read_string(&mut i)?
1028        } else {
1029            // Número, literal, objeto ou lista: até a vírgula ou o fecha do mesmo nível.
1030            let start = i;
1031            let (mut depth, mut quoted) = (0i32, false);
1032            while i < chars.len() {
1033                let c = chars[i];
1034                if quoted {
1035                    if c == '\\' {
1036                        i += 1;
1037                    } else if c == '"' {
1038                        quoted = false;
1039                    }
1040                } else {
1041                    match c {
1042                        '"' => quoted = true,
1043                        '{' | '[' => depth += 1,
1044                        '}' | ']' if depth == 0 => break,
1045                        '}' | ']' => depth -= 1,
1046                        ',' if depth == 0 => break,
1047                        _ => {}
1048                    }
1049                }
1050                i += 1;
1051            }
1052            chars[start..i.min(chars.len())].iter().collect::<String>().trim().to_string()
1053        };
1054        if name == key {
1055            return Some(value);
1056        }
1057        skip_ws(&mut i);
1058        if chars.get(i) == Some(&',') {
1059            i += 1;
1060        }
1061    }
1062}
1063
1064/// A mensagem de um push que chega cru (o WNS do tipo raw, o UnifiedPush, o Web Push): um
1065/// objeto JSON com `title`, `body`, `id` e `data` (objeto), ou no formato do FCM
1066/// (`{"notification": {"title", "body"}, "data": {...}}`). O que não for JSON vira o texto.
1067pub fn push_message_from_payload(text: &str) -> PushMessage {
1068    let text = text.trim();
1069    if !text.starts_with('{') {
1070        return PushMessage { body: text.to_string(), data: "{}".into(), ..Default::default() };
1071    }
1072    let notification = json_field(text, "notification").unwrap_or_default();
1073    let pick = |key: &str| json_field(text, key).or_else(|| json_field(&notification, key)).unwrap_or_default();
1074    let data = json_field(text, "data").filter(|d| d.trim_start().starts_with('{')).unwrap_or_else(|| "{}".into());
1075    PushMessage { id: pick("id"), title: pick("title"), body: pick("body"), data }
1076}
1077
1078/// Um texto de modelo com os dados de uma mensagem: `{chave}` vira o valor da chave no
1079/// objeto JSON `data` (vazio se não houver); `{{` e `}}` são as chaves literais.
1080pub fn render_template(template: &str, data: &str) -> String {
1081    let mut out = String::new();
1082    let mut rest = template;
1083    while let Some(i) = rest.find(['{', '}']) {
1084        out.push_str(&rest[..i]);
1085        let tail = &rest[i..];
1086        if tail.starts_with("{{") || tail.starts_with("}}") {
1087            out.push_str(&tail[..1]);
1088            rest = &tail[2..];
1089        } else if let (true, Some(end)) = (tail.starts_with('{'), tail.find('}')) {
1090            out.push_str(&json_field(data, tail[1..end].trim()).unwrap_or_default());
1091            rest = &tail[end + 1..];
1092        } else {
1093            out.push_str(&tail[..1]);
1094            rest = &tail[1..];
1095        }
1096    }
1097    out.push_str(rest);
1098    out
1099}
1100
1101/// Um filtro de dados (`kind=call;priority=high`): todas as condições valem (`chave=valor`,
1102/// `chave!=valor`, `chave` sozinha: existe e não é vazia). Vazio: aceita tudo.
1103pub fn data_matches(filter: &str, data: &str) -> bool {
1104    filter.split(';').map(str::trim).filter(|c| !c.is_empty()).all(|c| {
1105        if let Some((k, v)) = c.split_once("!=") {
1106            json_field(data, k.trim()).unwrap_or_default() != v.trim()
1107        } else if let Some((k, v)) = c.split_once('=') {
1108            json_field(data, k.trim()).unwrap_or_default() == v.trim()
1109        } else {
1110            json_field(data, c).is_some_and(|v| !v.is_empty())
1111        }
1112    })
1113}
1114
1115/// O texto em JSON (com as aspas), para as plataformas que montam JSON à mão.
1116pub fn json_quote(text: &str) -> String {
1117    let mut out = String::with_capacity(text.len() + 2);
1118    out.push('"');
1119    for c in text.chars() {
1120        match c {
1121            '"' => out.push_str("\\\""),
1122            '\\' => out.push_str("\\\\"),
1123            '\n' => out.push_str("\\n"),
1124            '\r' => out.push_str("\\r"),
1125            '\t' => out.push_str("\\t"),
1126            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1127            c => out.push(c),
1128        }
1129    }
1130    out.push('"');
1131    out
1132}
1133
1134/// O que volta de uma ação executada pela plataforma.
1135#[derive(Clone, Debug, PartialEq, Eq)]
1136pub struct ActionEvent {
1137    /// `open` (o app abriu pela ação), `button` (um botão da notificação), `click` (o corpo
1138    /// da notificação), `timeout` (passou o tempo sem resposta) ou `trigger` (uma regra do
1139    /// push disparou).
1140    pub kind: String,
1141    /// O caminho do componente (`frmPrincipal.wake1`; o `PushTrigger` no `trigger`).
1142    pub component: String,
1143    /// O id do botão (no `button`).
1144    pub detail: String,
1145    /// Os dados da mensagem (JSON).
1146    pub data: String,
1147}
1148
1149/// Uma linha de evento de ação (`tipo	componente	detalhe	dados`), como o Java manda.
1150pub fn parse_action_line(line: &str) -> Option<ActionEvent> {
1151    let mut f = line.split('\t');
1152    let kind = f.next().filter(|k| !k.is_empty())?.to_string();
1153    let component = f.next()?.to_string();
1154    let detail = f.next().unwrap_or_default().to_string();
1155    let data = f.next().filter(|d| !d.trim().is_empty()).unwrap_or("{}").to_string();
1156    Some(ActionEvent { kind, component, detail, data })
1157}
1158
1159/// As ações do aparelho executadas pela própria plataforma (o Android, com o app fechado e a
1160/// tela bloqueada). A ação vai como JSON (o `spec` que o componente monta: `type` `wake` ou
1161/// `notify`, os textos de modelo, os botões...); os dados, como o objeto JSON da mensagem.
1162pub trait ActionService {
1163    fn execute(&mut self, spec: &str, data: &str) -> Result<(), String>;
1164    /// Para a ação do componente (o toque, a notificação, o app por cima do bloqueio).
1165    fn stop(&mut self, component: &str);
1166    /// Grava as regras do `PushTrigger` (uma lista JSON) para valerem com o app fechado: a
1167    /// mensagem que casa executa a ação ali mesmo, antes de o app abrir.
1168    fn set_push_rules(&mut self, rules: &str);
1169    /// O que aconteceu desde a última consulta (também o que aconteceu com o app fechado).
1170    fn poll(&mut self) -> Vec<ActionEvent>;
1171}
1172
1173
1174/// Fuso horário: a plataforma liga uma função que devolve, para um instante UTC (segundos
1175/// desde 1970), quantos segundos o horário local está à frente (com horário de verão). Sem
1176/// ela (testes, servidor), o horário local é o UTC.
1177static LOCAL_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1178
1179pub fn set_local_offset_fn(f: fn(i64) -> i64) {
1180    if let Ok(mut slot) = LOCAL_OFFSET.write() {
1181        *slot = Some(f);
1182    }
1183}
1184
1185/// O fuso fixado pelo projeto (`time_zone` no `.aylisproj`): vale no lugar do fuso do
1186/// aparelho, para todos verem a hora da empresa.
1187static PROJECT_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1188
1189/// O projeto fixa o fuso (veja [`PROJECT_OFFSET`]); `None` volta ao do aparelho.
1190pub fn set_project_offset_fn(f: Option<fn(i64) -> i64>) {
1191    if let Ok(mut slot) = PROJECT_OFFSET.write() {
1192        *slot = f;
1193    }
1194}
1195
1196/// Segundos que o horário local está à frente do UTC no instante `utc`: o fuso do projeto,
1197/// se houver, senão o do aparelho.
1198pub fn local_offset(utc: i64) -> i64 {
1199    let project = PROJECT_OFFSET.read().ok().and_then(|f| *f);
1200    project.or_else(|| LOCAL_OFFSET.read().ok().and_then(|f| *f)).map_or(0, |f| f(utc))
1201}