1use crate::canvas::TextService;
9use crate::geometry::{RectF, SizeF};
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13pub struct WindowId(pub u64);
14
15#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17pub struct TimerId(pub u64);
18
19pub 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 fn request_redraw(&mut self, window: WindowId);
27 fn scale_factor(&self, window: WindowId) -> f32;
29}
30
31pub trait TimerService {
33 fn start_timer(&mut self, interval_ms: u32, repeat: bool) -> TimerId;
34 fn stop_timer(&mut self, timer: TimerId);
35 fn request_frame(&mut self);
37 fn now(&self) -> f64;
39}
40
41pub trait ClipboardService {
44 fn get_text(&mut self) -> Option<String>;
45 fn set_text(&mut self, text: &str);
46
47 fn set_content(&mut self, content: &crate::clipboard::ClipboardContent) {
49 self.set_text(content.text.as_deref().unwrap_or(""));
50 }
51
52 fn get_html(&mut self) -> Option<String> {
53 None
54 }
55
56 fn get_image(&mut self) -> Option<crate::Image> {
57 None
58 }
59
60 fn get_data(&mut self, _format: &str) -> Option<Vec<u8>> {
62 None
63 }
64
65 fn has(&mut self, format: &str) -> bool {
67 match format {
68 crate::clipboard::HTML => self.get_html().is_some(),
69 crate::clipboard::IMAGE => self.get_image().is_some(),
70 _ => self.get_data(format).is_some(),
71 }
72 }
73
74 fn sequence(&mut self) -> Option<u64> {
77 None
78 }
79}
80
81#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
82pub enum CursorShape {
83 #[default]
84 Default,
85 Pointer,
86 Text,
87 Wait,
88 Crosshair,
89 Move,
90 NotAllowed,
91 ResizeHorizontal,
92 ResizeVertical,
93 ResizeNeSw,
94 ResizeNwSe,
95 Grab,
97 Grabbing,
98 None,
100}
101
102impl CursorShape {
103 pub const ALL: [CursorShape; 14] = [
104 CursorShape::Default,
105 CursorShape::Pointer,
106 CursorShape::Text,
107 CursorShape::Wait,
108 CursorShape::Crosshair,
109 CursorShape::Move,
110 CursorShape::NotAllowed,
111 CursorShape::ResizeHorizontal,
112 CursorShape::ResizeVertical,
113 CursorShape::ResizeNeSw,
114 CursorShape::ResizeNwSe,
115 CursorShape::Grab,
116 CursorShape::Grabbing,
117 CursorShape::None,
118 ];
119}
120
121impl crate::prop::PropEnum for CursorShape {
122 const NAMES: &'static [&'static str] = &[
123 "default",
124 "pointer",
125 "text",
126 "wait",
127 "crosshair",
128 "move",
129 "not_allowed",
130 "resize_horizontal",
131 "resize_vertical",
132 "resize_ne_sw",
133 "resize_nw_se",
134 "grab",
135 "grabbing",
136 "none",
137 ];
138
139 fn from_index(index: usize) -> Option<Self> {
140 CursorShape::ALL.get(index).copied()
141 }
142
143 fn index(self) -> usize {
144 self as usize
145 }
146}
147
148pub trait CursorService {
150 fn set_cursor(&mut self, shape: CursorShape);
151}
152
153#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
155pub enum Appearance {
156 #[default]
157 Light,
158 Dark,
159}
160
161pub trait ScreenService {
163 fn screen_size(&self) -> SizeF;
164 fn scale_factor(&self) -> f32;
165 fn appearance(&self) -> Appearance;
167}
168
169#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
171pub enum KeyboardKind {
172 #[default]
173 Text,
174 Number,
175 Decimal,
176 Phone,
177 Email,
178 Url,
179}
180
181pub trait TextInputService {
183 fn show_keyboard(&mut self, kind: KeyboardKind);
184 fn hide_keyboard(&mut self);
185 fn set_ime_rect(&mut self, rect: RectF);
187}
188
189#[derive(Clone, Debug, PartialEq)]
191pub struct LocaleInfo {
192 pub decimal_separator: char,
193 pub thousand_separator: char,
194 pub short_date_format: String,
195 pub long_time_format: String,
196 pub currency_symbol: String,
197 pub month_names: [&'static str; 12],
200 pub short_day_names: [&'static str; 7],
201 pub first_day_of_week: u8,
203}
204
205const MONTHS_EN: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
206const DAYS_EN: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
207
208impl Default for LocaleInfo {
209 fn default() -> Self {
210 Self {
211 decimal_separator: '.',
212 thousand_separator: ',',
213 short_date_format: "yyyy-mm-dd".into(),
214 long_time_format: "hh:nn:ss".into(),
215 currency_symbol: "$".into(),
216 month_names: MONTHS_EN,
217 short_day_names: DAYS_EN,
218 first_day_of_week: 0,
219 }
220 }
221}
222
223impl LocaleInfo {
224 pub fn pt_br() -> Self {
226 Self {
227 decimal_separator: ',',
228 thousand_separator: '.',
229 short_date_format: "dd/mm/yyyy".into(),
230 long_time_format: "hh:nn:ss".into(),
231 currency_symbol: "R$".into(),
232 month_names: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
233 short_day_names: ["dom", "seg", "ter", "qua", "qui", "sex", "sáb"],
234 first_day_of_week: 0,
235 }
236 }
237
238 pub fn es() -> Self {
240 Self {
241 decimal_separator: ',',
242 thousand_separator: '.',
243 short_date_format: "dd/mm/yyyy".into(),
244 long_time_format: "hh:nn:ss".into(),
245 currency_symbol: "€".into(),
246 month_names: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],
247 short_day_names: ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"],
248 first_day_of_week: 1,
249 }
250 }
251
252 pub fn en_us() -> Self {
254 Self {
255 decimal_separator: '.',
256 thousand_separator: ',',
257 short_date_format: "mm/dd/yyyy".into(),
258 long_time_format: "hh:nn:ss".into(),
259 currency_symbol: "$".into(),
260 month_names: MONTHS_EN,
261 short_day_names: DAYS_EN,
262 first_day_of_week: 0,
263 }
264 }
265}
266
267pub trait LocaleService {
268 fn locale(&self) -> LocaleInfo;
269}
270
271impl LocaleService for LocaleInfo {
273 fn locale(&self) -> LocaleInfo {
274 self.clone()
275 }
276}
277
278#[derive(Clone, Copy, Debug, PartialEq, Eq)]
280pub enum LifecycleEvent {
281 Resumed,
282 Suspended,
283 LowMemory,
284 SurfaceLost,
286}
287
288pub trait ResourceService {
292 fn read(&self, path: &str) -> Option<Vec<u8>>;
293}
294
295pub trait FormFactory {
298 fn create_form(&mut self, ui: &mut crate::Ui, name: &str) -> Result<crate::ComponentId, String>;
300 fn form_names(&self) -> Vec<String>;
302}
303
304#[derive(Clone, Debug, Default)]
306pub struct FileDialogOptions {
307 pub title: String,
308 pub filters: Vec<(String, Vec<String>)>,
310 pub directory: String,
311 pub file_name: String,
312 pub save: bool,
314 pub multiple: bool,
316 pub owner: Option<crate::ComponentId>,
318}
319
320pub trait FileDialogService {
323 fn show(&mut self, options: FileDialogOptions, done: Box<dyn FnOnce(Vec<String>) + Send>);
324}
325
326#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
329pub enum Permission {
330 Camera,
331 Microphone,
332 Location,
334 Notifications,
335 Photos,
337 Contacts,
338 Calendar,
339 Bluetooth,
340}
341
342impl Permission {
343 pub const ALL: [Permission; 8] = [
344 Permission::Camera,
345 Permission::Microphone,
346 Permission::Location,
347 Permission::Notifications,
348 Permission::Photos,
349 Permission::Contacts,
350 Permission::Calendar,
351 Permission::Bluetooth,
352 ];
353
354 pub fn name(self) -> &'static str {
356 match self {
357 Permission::Camera => "camera",
358 Permission::Microphone => "microphone",
359 Permission::Location => "location",
360 Permission::Notifications => "notifications",
361 Permission::Photos => "photos",
362 Permission::Contacts => "contacts",
363 Permission::Calendar => "calendar",
364 Permission::Bluetooth => "bluetooth",
365 }
366 }
367
368 pub fn parse(name: &str) -> Option<Permission> {
369 let name = name.trim();
370 Permission::ALL.into_iter().find(|p| p.name().eq_ignore_ascii_case(name))
371 }
372
373 pub fn parse_list(list: &str) -> Vec<Permission> {
375 let mut out = Vec::new();
376 for p in list.split([';', ',']).filter_map(Permission::parse) {
377 if !out.contains(&p) {
378 out.push(p);
379 }
380 }
381 out
382 }
383}
384
385#[derive(Clone, Copy, Debug, PartialEq, Eq)]
387pub enum PermissionState {
388 Granted,
390 Denied,
392 Prompt,
394 Unavailable,
396}
397
398impl PermissionState {
399 pub fn name(self) -> &'static str {
400 match self {
401 PermissionState::Granted => "granted",
402 PermissionState::Denied => "denied",
403 PermissionState::Prompt => "prompt",
404 PermissionState::Unavailable => "unavailable",
405 }
406 }
407}
408
409pub trait PermissionService {
412 fn state(&self, permission: Permission) -> PermissionState;
413 fn request(&mut self, permissions: Vec<Permission>, done: Box<dyn FnOnce(Vec<(Permission, PermissionState)>) + Send>);
414}
415
416#[derive(Clone, Copy, Debug, PartialEq, Eq)]
418pub enum Biometry {
419 None,
421 Fingerprint,
422 Face,
423 Iris,
424 Any,
426}
427
428impl Biometry {
429 pub fn name(self) -> &'static str {
430 match self {
431 Biometry::None => "none",
432 Biometry::Fingerprint => "fingerprint",
433 Biometry::Face => "face",
434 Biometry::Iris => "iris",
435 Biometry::Any => "any",
436 }
437 }
438}
439
440#[derive(Clone, Debug, PartialEq, Eq)]
442pub enum BiometricResult {
443 Success,
444 Cancelled,
446 Failed(String),
448}
449
450pub trait BiometricService {
453 fn availability(&self) -> Biometry;
454 fn authenticate(&mut self, reason: &str, allow_device_credential: bool, done: Box<dyn FnOnce(BiometricResult) + Send>);
457}
458
459pub trait PrintService {
463 fn print(&mut self, title: &str, pages: crate::pages::PageSet, done: Box<dyn FnOnce(Result<bool, String>) + Send>);
464
465 fn wants_pdf(&self) -> bool {
468 false
469 }
470
471 fn print_pdf(&mut self, title: &str, pdf: Vec<u8>, done: Box<dyn FnOnce(Result<bool, String>) + Send>) {
473 let _ = (title, pdf);
474 done(Err("esta plataforma não imprime PDF".into()));
475 }
476}
477
478pub trait HttpService {
482 fn get(&mut self, url: &str, done: Box<dyn FnOnce(Result<Vec<u8>, String>) + Send>);
483}
484
485#[derive(Clone, Debug, Default, PartialEq)]
487pub struct SystemNotification {
488 pub app_id: String,
490 pub app_name: String,
492 pub title: String,
493 pub body: String,
494 pub image: String,
496 pub image_png: Vec<u8>,
498 pub big_image: bool,
500 pub id: u32,
502 pub channel: String,
504 pub channel_name: String,
505 pub priority: NotificationPriority,
506 pub actions: Vec<(String, String)>,
508 pub ongoing: bool,
510 pub progress: Option<f32>,
512 pub full_screen: bool,
515 pub component: Option<crate::ComponentId>,
517}
518
519#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
521pub enum NotificationPriority {
522 Low,
524 #[default]
525 Default,
526 High,
528}
529
530impl crate::PropEnum for NotificationPriority {
531 const NAMES: &'static [&'static str] = &["low", "default", "high"];
532 fn from_index(index: usize) -> Option<Self> {
533 [Self::Low, Self::Default, Self::High].get(index).copied()
534 }
535 fn index(self) -> usize {
536 self as usize
537 }
538}
539
540pub trait NotificationService {
542 fn notify(&mut self, notification: &SystemNotification) -> Result<(), String>;
543 fn cancel(&mut self, id: u32) -> Result<(), String> {
545 let _ = id;
546 Ok(())
547 }
548}
549
550pub trait LinkService {
553 fn open_url(&mut self, url: &str) -> Result<(), String>;
555 fn open_app(&mut self, app: &str) -> Result<(), String> {
557 Err(format!("abrir outro app não existe aqui ({app})"))
558 }
559 fn share(&mut self, text: &str, files: &[String]) -> Result<(), String> {
561 let _ = (text, files);
562 Err("compartilhar não existe aqui".into())
563 }
564 fn request(&mut self, action: &str, data: &str, done: Box<dyn FnOnce(Result<String, String>) + Send>) {
567 let _ = data;
568 done(Err(format!("pedir a outro app não existe aqui ({action})")));
569 }
570 fn can_register_schemes(&self) -> bool {
573 false
574 }
575 fn register_scheme(&mut self, scheme: &str, description: &str) -> Result<(), String> {
579 let _ = description;
580 Err(format!("registrar o prefixo {scheme}:// em execução não existe aqui (vai na publicação)"))
581 }
582 fn unregister_scheme(&mut self, scheme: &str) -> Result<(), String> {
584 Err(format!("tirar o registro do prefixo {scheme}:// não existe aqui"))
585 }
586 fn scheme_registered(&mut self, scheme: &str) -> bool {
588 let _ = scheme;
589 false
590 }
591 fn receive_links(&mut self, on_link: Box<dyn Fn(String) + Send>) {
594 let _ = on_link;
595 }
596}
597
598const RESERVED_SCHEMES: &[&str] = &[
600 "http", "https", "file", "ftp", "ftps", "mailto", "tel", "sms", "data", "javascript", "vbscript", "about", "blob", "ws", "wss", "shell", "search",
601 "search-ms", "res", "its", "mk", "hcp", "callto", "news", "nntp", "telnet", "ldap", "ssh", "sftp", "smb", "git", "magnet", "steam", "zoommtg",
602];
603
604pub fn check_scheme(scheme: &str) -> Result<String, String> {
608 let s = scheme.trim().trim_end_matches("://").trim_end_matches(':').to_ascii_lowercase();
609 let valid = s.len() >= 3
610 && s.len() <= 64
611 && s.starts_with(|c: char| c.is_ascii_lowercase())
612 && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '+' | '-' | '.'));
613 if !valid {
614 return Err(crate::messages::tf("prefixo inválido: {0} (letras, números, + - ., de 3 a 64)", &[&scheme]));
615 }
616 if RESERVED_SCHEMES.contains(&s.as_str()) || s.starts_with("ms-") || s.starts_with("microsoft") || s.starts_with("windows") {
617 return Err(crate::messages::tf("o prefixo {0} é do sistema", &[&s]));
618 }
619 Ok(s)
620}
621
622static STARTUP_LINKS: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
625
626pub fn push_startup_link(url: String) {
628 if let Ok(mut list) = STARTUP_LINKS.lock() {
629 list.push(url);
630 }
631}
632
633pub fn take_startup_links(scheme: &str) -> Vec<String> {
635 let Ok(mut list) = STARTUP_LINKS.lock() else { return Vec::new() };
636 let (mine, rest): (Vec<String>, Vec<String>) = std::mem::take(&mut *list).into_iter().partition(|url| link_scheme(url).as_deref() == Some(scheme));
637 *list = rest;
638 mine
639}
640
641pub fn link_scheme(url: &str) -> Option<String> {
643 let (scheme, _) = url.split_once(':')?;
644 (!scheme.is_empty()).then(|| scheme.to_ascii_lowercase())
645}
646
647#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
649pub enum Sensor {
650 Location,
652 Battery,
654 Network,
656 Motion,
658 Compass,
660 Proximity,
662 Light,
664}
665
666pub trait SensorService {
669 fn available(&self, sensor: Sensor) -> bool;
671 fn set_active(&mut self, sensor: Sensor, on: bool);
673 fn read(&mut self, sensor: Sensor) -> Option<Vec<f64>>;
675 fn vibrate(&mut self, ms: u32) -> bool {
677 let _ = ms;
678 false
679 }
680}
681
682pub const GAMEPAD_BUTTONS: [&str; 17] =
686 ["a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "l3", "r3", "up", "down", "left", "right", "guide"];
687
688#[derive(Clone, Debug, Default, PartialEq)]
690pub struct GamepadState {
691 pub name: String,
692 pub buttons: u32,
694 pub axes: [f32; 6],
697}
698
699impl GamepadState {
700 pub fn set_button(&mut self, name: &str, down: bool) {
702 if let Some(i) = GAMEPAD_BUTTONS.iter().position(|b| *b == name) {
703 if down {
704 self.buttons |= 1 << i;
705 } else {
706 self.buttons &= !(1 << i);
707 }
708 }
709 }
710
711 pub fn pressed(&self, name: &str) -> bool {
712 GAMEPAD_BUTTONS.iter().position(|b| *b == name).is_some_and(|i| self.buttons & (1 << i) != 0)
713 }
714}
715
716pub trait GamepadService {
718 fn pads(&mut self) -> Vec<GamepadState>;
720 fn rumble(&mut self, index: usize, strength: f32, ms: u32) -> bool {
722 let _ = (index, strength, ms);
723 false
724 }
725}
726
727pub trait PhoneService {
729 fn dial(&mut self, number: &str) -> Result<(), String>;
731 fn call(&mut self, number: &str) -> Result<(), String>;
733 fn watch(&mut self, on: bool);
735 fn state(&mut self) -> (String, String);
738 fn request_dialer(&mut self) -> Result<(), String> {
740 Err("não existe aqui".into())
741 }
742 fn answer(&mut self) -> bool {
744 false
745 }
746 fn reject(&mut self) -> bool {
747 false
748 }
749 fn hang_up(&mut self) -> bool {
750 false
751 }
752 fn history(&mut self, max: u32) -> Result<String, String> {
754 let _ = max;
755 Err("não existe aqui".into())
756 }
757 fn lock_screen(&mut self, show_when_locked: bool, turn_screen_on: bool);
759 fn dismiss_keyguard(&mut self);
761}
762
763pub trait BackgroundHost {
768 fn start(&mut self, title: &str, text: &str, kind: &str, keep_alive: bool) -> Result<(), String>;
769 fn stop(&mut self);
770}
771
772#[derive(Clone, Debug, PartialEq, Eq)]
775pub enum Incoming {
776 Link(String),
777 Shared(String),
778}
779
780static INCOMING: std::sync::Mutex<Vec<Incoming>> = std::sync::Mutex::new(Vec::new());
781
782pub fn push_incoming(item: Incoming) {
785 if let Ok(mut list) = INCOMING.lock() {
786 list.push(item);
787 }
788}
789
790pub fn take_incoming() -> Vec<Incoming> {
792 INCOMING.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
793}
794
795pub trait OffscreenService {
798 fn render_png(&self, width: u32, height: u32, scale: f32, background: crate::Color, paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>>;
800
801 fn render_rgba(&self, _width: u32, _height: u32, _scale: f32, _background: crate::Color, _paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>> {
806 None
807 }
808
809 fn render_area_rgba(
814 &self,
815 _width: u32,
816 _height: u32,
817 _background: crate::Color,
818 _over: Option<(&[u8], crate::geometry::RectF)>,
819 _paint: &mut dyn FnMut(&mut dyn crate::Canvas),
820 ) -> Option<Vec<u8>> {
821 None
822 }
823}
824
825pub trait WindowCaptureService {
828 fn capture(&mut self, form: crate::ComponentId) -> Option<(u32, u32, Vec<u8>)>;
830}
831
832#[derive(Default)]
834pub struct Services {
835 pub window_capture: Option<Box<dyn WindowCaptureService>>,
837 pub offscreen: Option<Box<dyn OffscreenService>>,
838 pub window: Option<Box<dyn WindowService>>,
839 pub timer: Option<Box<dyn TimerService>>,
840 pub clipboard: Option<Box<dyn ClipboardService>>,
841 pub clipboard_local: crate::clipboard::LocalClipboard,
843 pub cursor: Option<Box<dyn CursorService>>,
844 pub screen: Option<Box<dyn ScreenService>>,
845 pub text_input: Option<Box<dyn TextInputService>>,
846 pub locale: Option<Box<dyn LocaleService>>,
847 pub text: Option<Box<dyn TextService>>,
848 pub resources: Option<Box<dyn ResourceService>>,
849 pub forms: Option<Box<dyn FormFactory>>,
850 pub file_dialogs: Option<Box<dyn FileDialogService>>,
851 pub permissions: Option<Box<dyn PermissionService>>,
853 pub biometrics: Option<Box<dyn BiometricService>>,
855 pub http: Option<Box<dyn HttpService>>,
856 pub notifications: Option<Box<dyn NotificationService>>,
857 pub links: Option<Box<dyn LinkService>>,
859 pub sensors: Option<Box<dyn SensorService>>,
861 pub background: Option<Box<dyn BackgroundHost>>,
864 pub phone: Option<Box<dyn PhoneService>>,
866 pub gamepads: Option<Box<dyn GamepadService>>,
868 pub printer: Option<Box<dyn PrintService>>,
869 pub pdf: Option<Box<dyn crate::providers::PdfProvider>>,
872 pub text_assist: Option<Box<dyn crate::textassist::TextAssist>>,
875 pub nfc: Option<Box<dyn NfcService>>,
877 pub bluetooth: Option<Box<dyn BluetoothService>>,
879 pub push: Option<Box<dyn PushService>>,
881 pub actions: Option<Box<dyn ActionService>>,
885 pub ole: Option<Box<dyn OleService>>,
887 pub wmi: Option<Box<dyn WmiService>>,
889}
890
891#[derive(Clone, Debug, Default, PartialEq, Eq)]
893pub struct NfcTag {
894 pub id: String,
896 pub tech: String,
898 pub records: Vec<crate::ndef::NdefRecord>,
900 pub writable: bool,
902}
903
904#[derive(Clone, Debug, PartialEq, Eq)]
906pub enum NfcEvent {
907 Tag(NfcTag),
908 Written,
910 Error(String),
911}
912
913pub trait NfcService {
916 fn available(&self) -> bool;
918 fn enabled(&self) -> bool {
920 self.available()
921 }
922 fn set_reading(&mut self, on: bool);
924 fn write(&mut self, message: Vec<u8>);
927 fn cancel_write(&mut self) {}
929 fn poll(&mut self) -> Vec<NfcEvent>;
931}
932
933#[derive(Clone, Debug, Default, PartialEq, Eq)]
935pub struct BleDevice {
936 pub id: String,
939 pub name: String,
940 pub rssi: i32,
942}
943
944#[derive(Clone, Debug, Default, PartialEq, Eq)]
946pub struct BleCharacteristic {
947 pub service: String,
948 pub characteristic: String,
949 pub properties: Vec<String>,
951}
952
953#[derive(Clone, Debug, PartialEq, Eq)]
955pub enum BluetoothEvent {
956 Found(BleDevice),
957 ScanStopped,
959 Connected { device: String, services: Vec<BleCharacteristic> },
961 Disconnected(String),
962 Value { device: String, characteristic: String, data: Vec<u8> },
964 Written { device: String, characteristic: String },
965 Received { device: String, data: Vec<u8> },
967 Error(String),
968}
969
970pub trait BluetoothService {
974 fn available(&self) -> bool;
975 fn enabled(&self) -> bool {
977 self.available()
978 }
979 fn scan(&mut self, on: bool, services: Vec<String>, name: String);
982 fn connect(&mut self, device: &str);
983 fn disconnect(&mut self, device: &str);
984 fn read(&mut self, device: &str, service: &str, characteristic: &str);
985 fn write(&mut self, device: &str, service: &str, characteristic: &str, data: Vec<u8>, with_response: bool);
986 fn subscribe(&mut self, device: &str, service: &str, characteristic: &str, on: bool);
988 fn paired(&mut self) -> Vec<(String, String)> {
990 Vec::new()
991 }
992 fn open_serial(&mut self, device: &str) -> Result<(), String> {
994 let _ = device;
995 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
996 }
997 fn send_serial(&mut self, device: &str, data: Vec<u8>) -> Result<(), String> {
998 let _ = (device, data);
999 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
1000 }
1001 fn close_serial(&mut self, device: &str) {
1002 let _ = device;
1003 }
1004 fn poll(&mut self) -> Vec<BluetoothEvent>;
1006}
1007
1008pub fn ble_uuid(text: &str) -> String {
1011 let t = text.trim().trim_start_matches("0x").trim_start_matches("0X").to_ascii_lowercase();
1012 if (t.len() == 4 || t.len() == 8) && t.chars().all(|c| c.is_ascii_hexdigit()) {
1013 format!("{t:0>8}-0000-1000-8000-00805f9b34fb")
1014 } else {
1015 t
1016 }
1017}
1018
1019#[derive(Clone, Debug, Default, PartialEq, Eq)]
1021pub struct PushMessage {
1022 pub id: String,
1024 pub title: String,
1026 pub body: String,
1027 pub data: String,
1029}
1030
1031#[derive(Clone, Debug, PartialEq, Eq)]
1033pub enum PushEvent {
1034 Token(String),
1038 Message(PushMessage),
1040 Opened(PushMessage),
1042 Error(String),
1043}
1044
1045#[derive(Clone, Debug, Default, PartialEq, Eq)]
1048pub struct PushConfig {
1049 pub sender_id: String,
1051 pub project_id: String,
1053 pub app_id: String,
1055 pub api_key: String,
1057 pub vapid_key: String,
1059 pub show_in_foreground: bool,
1062}
1063
1064pub trait PushService {
1068 fn available(&self) -> bool;
1071 fn provider(&self) -> &'static str;
1074 fn register(&mut self, config: &PushConfig);
1077 fn unregister(&mut self) {}
1079 fn shows_notifications(&self) -> bool {
1083 true
1084 }
1085 fn poll(&mut self) -> Vec<PushEvent> {
1087 Vec::new()
1088 }
1089}
1090
1091static PUSH_EVENTS: std::sync::Mutex<Vec<PushEvent>> = std::sync::Mutex::new(Vec::new());
1092
1093pub fn push_event(event: PushEvent) {
1096 if let Ok(mut list) = PUSH_EVENTS.lock() {
1097 list.push(event);
1098 }
1099}
1100
1101pub fn take_push_events() -> Vec<PushEvent> {
1103 PUSH_EVENTS.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
1104}
1105
1106pub fn parse_push_line(line: &str) -> Option<PushEvent> {
1110 let mut f = line.split('\t');
1111 let kind = f.next()?;
1112 let mut next = || f.next().unwrap_or_default().to_string();
1113 match kind {
1114 "token" => Some(PushEvent::Token(next())),
1115 "error" => Some(PushEvent::Error(next())),
1116 "message" | "opened" => {
1117 let mut m = PushMessage { id: next(), title: next(), body: next(), data: next() };
1118 if m.data.trim().is_empty() {
1119 m.data = "{}".into();
1120 }
1121 Some(if kind == "message" { PushEvent::Message(m) } else { PushEvent::Opened(m) })
1122 }
1123 _ => None,
1124 }
1125}
1126
1127pub fn json_field(json: &str, key: &str) -> Option<String> {
1130 let chars: Vec<char> = json.chars().collect();
1131 let mut i = 0;
1132 let skip_ws = |i: &mut usize| {
1133 while *i < chars.len() && chars[*i].is_whitespace() {
1134 *i += 1;
1135 }
1136 };
1137 let read_string = |i: &mut usize| -> Option<String> {
1139 if chars.get(*i) != Some(&'"') {
1140 return None;
1141 }
1142 *i += 1;
1143 let mut out = String::new();
1144 while *i < chars.len() {
1145 let c = chars[*i];
1146 *i += 1;
1147 match c {
1148 '"' => return Some(out),
1149 '\\' => {
1150 let e = *chars.get(*i)?;
1151 *i += 1;
1152 match e {
1153 'n' => out.push('\n'),
1154 't' => out.push('\t'),
1155 'r' => out.push('\r'),
1156 'b' => out.push('\u{8}'),
1157 'f' => out.push('\u{c}'),
1158 'u' => {
1159 let hex: String = chars.get(*i..*i + 4)?.iter().collect();
1160 *i += 4;
1161 let mut code = u32::from_str_radix(&hex, 16).ok()?;
1162 if (0xD800..0xDC00).contains(&code) && chars.get(*i) == Some(&'\\') && chars.get(*i + 1) == Some(&'u') {
1164 let low: String = chars.get(*i + 2..*i + 6)?.iter().collect();
1165 if let Ok(low) = u32::from_str_radix(&low, 16) {
1166 *i += 6;
1167 code = 0x10000 + ((code - 0xD800) << 10) + (low.wrapping_sub(0xDC00) & 0x3FF);
1168 }
1169 }
1170 out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
1171 }
1172 other => out.push(other),
1173 }
1174 }
1175 c => out.push(c),
1176 }
1177 }
1178 None
1179 };
1180 skip_ws(&mut i);
1181 if chars.get(i) != Some(&'{') {
1182 return None;
1183 }
1184 i += 1;
1185 loop {
1186 skip_ws(&mut i);
1187 if chars.get(i) == Some(&'}') || i >= chars.len() {
1188 return None;
1189 }
1190 let name = read_string(&mut i)?;
1191 skip_ws(&mut i);
1192 if chars.get(i) != Some(&':') {
1193 return None;
1194 }
1195 i += 1;
1196 skip_ws(&mut i);
1197 let value = if chars.get(i) == Some(&'"') {
1198 read_string(&mut i)?
1199 } else {
1200 let start = i;
1202 let (mut depth, mut quoted) = (0i32, false);
1203 while i < chars.len() {
1204 let c = chars[i];
1205 if quoted {
1206 if c == '\\' {
1207 i += 1;
1208 } else if c == '"' {
1209 quoted = false;
1210 }
1211 } else {
1212 match c {
1213 '"' => quoted = true,
1214 '{' | '[' => depth += 1,
1215 '}' | ']' if depth == 0 => break,
1216 '}' | ']' => depth -= 1,
1217 ',' if depth == 0 => break,
1218 _ => {}
1219 }
1220 }
1221 i += 1;
1222 }
1223 chars[start..i.min(chars.len())].iter().collect::<String>().trim().to_string()
1224 };
1225 if name == key {
1226 return Some(value);
1227 }
1228 skip_ws(&mut i);
1229 if chars.get(i) == Some(&',') {
1230 i += 1;
1231 }
1232 }
1233}
1234
1235pub fn push_message_from_payload(text: &str) -> PushMessage {
1239 let text = text.trim();
1240 if !text.starts_with('{') {
1241 return PushMessage { body: text.to_string(), data: "{}".into(), ..Default::default() };
1242 }
1243 let notification = json_field(text, "notification").unwrap_or_default();
1244 let pick = |key: &str| json_field(text, key).or_else(|| json_field(¬ification, key)).unwrap_or_default();
1245 let data = json_field(text, "data").filter(|d| d.trim_start().starts_with('{')).unwrap_or_else(|| "{}".into());
1246 PushMessage { id: pick("id"), title: pick("title"), body: pick("body"), data }
1247}
1248
1249pub fn render_template(template: &str, data: &str) -> String {
1252 let mut out = String::new();
1253 let mut rest = template;
1254 while let Some(i) = rest.find(['{', '}']) {
1255 out.push_str(&rest[..i]);
1256 let tail = &rest[i..];
1257 if tail.starts_with("{{") || tail.starts_with("}}") {
1258 out.push_str(&tail[..1]);
1259 rest = &tail[2..];
1260 } else if let (true, Some(end)) = (tail.starts_with('{'), tail.find('}')) {
1261 out.push_str(&json_field(data, tail[1..end].trim()).unwrap_or_default());
1262 rest = &tail[end + 1..];
1263 } else {
1264 out.push_str(&tail[..1]);
1265 rest = &tail[1..];
1266 }
1267 }
1268 out.push_str(rest);
1269 out
1270}
1271
1272pub fn data_matches(filter: &str, data: &str) -> bool {
1275 filter.split(';').map(str::trim).filter(|c| !c.is_empty()).all(|c| {
1276 if let Some((k, v)) = c.split_once("!=") {
1277 json_field(data, k.trim()).unwrap_or_default() != v.trim()
1278 } else if let Some((k, v)) = c.split_once('=') {
1279 json_field(data, k.trim()).unwrap_or_default() == v.trim()
1280 } else {
1281 json_field(data, c).is_some_and(|v| !v.is_empty())
1282 }
1283 })
1284}
1285
1286pub fn json_quote(text: &str) -> String {
1288 let mut out = String::with_capacity(text.len() + 2);
1289 out.push('"');
1290 for c in text.chars() {
1291 match c {
1292 '"' => out.push_str("\\\""),
1293 '\\' => out.push_str("\\\\"),
1294 '\n' => out.push_str("\\n"),
1295 '\r' => out.push_str("\\r"),
1296 '\t' => out.push_str("\\t"),
1297 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1298 c => out.push(c),
1299 }
1300 }
1301 out.push('"');
1302 out
1303}
1304
1305#[derive(Clone, Debug, PartialEq, Eq)]
1307pub struct ActionEvent {
1308 pub kind: String,
1312 pub component: String,
1314 pub detail: String,
1316 pub data: String,
1318}
1319
1320pub fn parse_action_line(line: &str) -> Option<ActionEvent> {
1322 let mut f = line.split('\t');
1323 let kind = f.next().filter(|k| !k.is_empty())?.to_string();
1324 let component = f.next()?.to_string();
1325 let detail = f.next().unwrap_or_default().to_string();
1326 let data = f.next().filter(|d| !d.trim().is_empty()).unwrap_or("{}").to_string();
1327 Some(ActionEvent { kind, component, detail, data })
1328}
1329
1330pub trait ActionService {
1334 fn execute(&mut self, spec: &str, data: &str) -> Result<(), String>;
1335 fn stop(&mut self, component: &str);
1337 fn set_push_rules(&mut self, rules: &str);
1340 fn poll(&mut self) -> Vec<ActionEvent>;
1342}
1343
1344#[derive(Clone, Debug, PartialEq)]
1346pub enum OleValue {
1347 Null,
1348 Bool(bool),
1349 Int(i64),
1350 Float(f64),
1351 String(String),
1352 Date(f64),
1355 Object(u64),
1358 Array(Vec<Vec<OleValue>>),
1361}
1362
1363pub trait OleService {
1370 fn create(&mut self, prog_id: &str, running: bool) -> Result<u64, String>;
1373 fn invoke(&mut self, object: u64, name: &str, args: Vec<OleValue>) -> Result<OleValue, String>;
1375 fn put(&mut self, object: u64, name: &str, args: Vec<OleValue>, value: OleValue) -> Result<(), String>;
1377 fn release(&mut self, object: u64);
1379 fn set_timeout(&mut self, seconds: f64) {
1381 let _ = seconds;
1382 }
1383 fn releaser(&self) -> Option<OleReleaser> {
1385 None
1386 }
1387}
1388
1389pub type OleReleaser = std::sync::Arc<dyn Fn(u64) + Send + Sync>;
1391
1392static OLE_ALLOWED: std::sync::RwLock<Vec<String>> = std::sync::RwLock::new(Vec::new());
1396
1397pub const OLE_DEFAULT: &[&str] = &["Excel.Application", "Word.Application", "Outlook.Application", "PowerPoint.Application"];
1399
1400pub fn allow_ole(prog_id: &str) {
1402 if let Ok(mut list) = OLE_ALLOWED.write() {
1403 if !list.iter().any(|p| p.eq_ignore_ascii_case(prog_id)) {
1404 list.push(prog_id.to_string());
1405 }
1406 }
1407}
1408
1409pub fn ole_allowed(prog_id: &str) -> bool {
1412 let id = prog_id.trim();
1413 let base = match id.rsplit_once('.') {
1414 Some((head, tail)) if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) => head,
1415 _ => id,
1416 };
1417 let ok = |p: &str| p.eq_ignore_ascii_case(base) || p.eq_ignore_ascii_case(id);
1418 OLE_DEFAULT.iter().any(|p| ok(p)) || OLE_ALLOWED.read().is_ok_and(|l| l.iter().any(|p| ok(p)))
1419}
1420
1421pub fn ole_date(year: i32, month: u32, day: u32, hour: u32, minute: u32, second: u32) -> f64 {
1423 let y = i64::from(year) - i64::from(month <= 2);
1425 let era = y.div_euclid(400);
1426 let yoe = y - era * 400;
1427 let m = i64::from(month);
1428 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(day) - 1;
1429 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
1430 let days = era * 146_097 + doe - 719_468 + 25_569;
1431 days as f64 + f64::from(hour * 3600 + minute * 60 + second) / 86_400.0
1432}
1433
1434pub fn ole_date_parts(date: f64) -> (i32, u32, u32, u32, u32, u32) {
1436 let mut days = date.floor() as i64;
1437 let mut secs = ((date - date.floor()) * 86_400.0).round() as i64;
1438 if secs >= 86_400 {
1439 days += 1;
1440 secs -= 86_400;
1441 }
1442 let z = days - 25_569 + 719_468;
1443 let era = z.div_euclid(146_097);
1444 let doe = z - era * 146_097;
1445 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1446 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1447 let mp = (5 * doy + 2) / 153;
1448 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
1449 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1450 let year = (yoe + era * 400 + i64::from(month <= 2)) as i32;
1451 (year, month, day, (secs / 3600) as u32, (secs % 3600 / 60) as u32, (secs % 60) as u32)
1452}
1453
1454#[derive(Clone, Debug, PartialEq)]
1456pub enum WmiValue {
1457 Null,
1458 Bool(bool),
1459 Int(i64),
1460 Float(f64),
1461 String(String),
1462 DateTime(String),
1464 Array(Vec<WmiValue>),
1466 Object(Vec<(String, WmiValue)>),
1468}
1469
1470#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1472pub enum WmiType {
1473 #[default]
1474 String,
1475 Integer,
1476 Float,
1477 Boolean,
1478 DateTime,
1479 Array,
1480 Object,
1481}
1482
1483#[derive(Clone, Debug, Default, PartialEq, Eq)]
1485pub struct WmiColumn {
1486 pub name: String,
1487 pub kind: WmiType,
1488}
1489
1490#[derive(Clone, Debug, Default, PartialEq)]
1493pub struct WmiTable {
1494 pub columns: Vec<WmiColumn>,
1495 pub rows: Vec<Vec<WmiValue>>,
1496}
1497
1498pub type WmiDone = Box<dyn FnOnce(Result<WmiTable, String>) + Send>;
1501
1502pub type WmiListener = std::sync::Arc<dyn Fn(Result<Vec<(String, WmiValue)>, String>) + Send + Sync>;
1505
1506pub struct WmiWatch(Option<Box<dyn FnOnce() + Send>>);
1508
1509impl WmiWatch {
1510 pub fn new(stop: impl FnOnce() + Send + 'static) -> Self {
1512 Self(Some(Box::new(stop)))
1513 }
1514}
1515
1516impl Drop for WmiWatch {
1517 fn drop(&mut self) {
1518 if let Some(stop) = self.0.take() {
1519 stop();
1520 }
1521 }
1522}
1523
1524pub trait WmiService {
1529 fn query(&mut self, namespace: &str, wql: &str, done: WmiDone);
1531 fn watch(&mut self, namespace: &str, wql: &str, listener: WmiListener) -> Result<WmiWatch, String>;
1535}
1536
1537pub fn wmi_namespace(namespace: &str) -> Result<String, String> {
1541 let ns = namespace.trim().replace('/', "\\");
1542 let ns = if ns.is_empty() { "root\\cimv2".to_string() } else { ns };
1543 let valid = ns.split('\\').all(|p| !p.is_empty() && p.chars().all(|c| c.is_alphanumeric() || c == '_'));
1544 if !valid || !ns.split('\\').next().is_some_and(|r| r.eq_ignore_ascii_case("root")) {
1545 return Err(crate::messages::tf("namespace do WMI inválido '{0}' (só desta máquina, como root\\cimv2)", &[&namespace]));
1546 }
1547 Ok(ns)
1548}
1549
1550pub fn wmi_datetime(text: &str) -> Option<String> {
1554 let t = text.trim();
1555 let b = t.as_bytes();
1556 if b.len() < 14 || !b[..14].iter().all(u8::is_ascii_digit) || b.get(21) == Some(&b':') {
1557 return None;
1558 }
1559 let (y, mo, d, h, mi, s) = (&t[0..4], &t[4..6], &t[6..8], &t[8..10], &t[10..12], &t[12..14]);
1560 let month: u32 = mo.parse().ok()?;
1561 let day: u32 = d.parse().ok()?;
1562 if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
1563 return None;
1564 }
1565 Some(format!("{y}-{mo}-{d}T{h}:{mi}:{s}"))
1566}
1567
1568pub fn wmi_select_list(wql: &str) -> Vec<String> {
1571 let t = wql.trim();
1572 let lower = t.to_ascii_lowercase();
1573 let (Some(rest), Some(from)) = (lower.strip_prefix("select"), lower.find(" from ")) else { return Vec::new() };
1574 let start = t.len() - rest.len();
1575 if from < start {
1576 return Vec::new();
1577 }
1578 t[start..from].split(',').map(str::trim).filter(|n| !n.is_empty() && *n != "*").map(str::to_string).collect()
1579}
1580
1581
1582static LOCAL_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1586
1587pub fn set_local_offset_fn(f: fn(i64) -> i64) {
1588 if let Ok(mut slot) = LOCAL_OFFSET.write() {
1589 *slot = Some(f);
1590 }
1591}
1592
1593static PROJECT_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1596
1597pub fn set_project_offset_fn(f: Option<fn(i64) -> i64>) {
1599 if let Ok(mut slot) = PROJECT_OFFSET.write() {
1600 *slot = f;
1601 }
1602}
1603
1604pub fn local_offset(utc: i64) -> i64 {
1607 let project = PROJECT_OFFSET.read().ok().and_then(|f| *f);
1608 project.or_else(|| LOCAL_OFFSET.read().ok().and_then(|f| *f)).map_or(0, |f| f(utc))
1609}