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
466pub trait HttpService {
470 fn get(&mut self, url: &str, done: Box<dyn FnOnce(Result<Vec<u8>, String>) + Send>);
471}
472
473#[derive(Clone, Debug, Default, PartialEq)]
475pub struct SystemNotification {
476 pub app_id: String,
478 pub app_name: String,
480 pub title: String,
481 pub body: String,
482 pub image: String,
484 pub image_png: Vec<u8>,
486 pub big_image: bool,
488 pub id: u32,
490 pub channel: String,
492 pub channel_name: String,
493 pub priority: NotificationPriority,
494 pub actions: Vec<(String, String)>,
496 pub ongoing: bool,
498 pub progress: Option<f32>,
500 pub full_screen: bool,
503 pub component: Option<crate::ComponentId>,
505}
506
507#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
509pub enum NotificationPriority {
510 Low,
512 #[default]
513 Default,
514 High,
516}
517
518impl crate::PropEnum for NotificationPriority {
519 const NAMES: &'static [&'static str] = &["low", "default", "high"];
520 fn from_index(index: usize) -> Option<Self> {
521 [Self::Low, Self::Default, Self::High].get(index).copied()
522 }
523 fn index(self) -> usize {
524 self as usize
525 }
526}
527
528pub trait NotificationService {
530 fn notify(&mut self, notification: &SystemNotification) -> Result<(), String>;
531 fn cancel(&mut self, id: u32) -> Result<(), String> {
533 let _ = id;
534 Ok(())
535 }
536}
537
538pub trait LinkService {
541 fn open_url(&mut self, url: &str) -> Result<(), String>;
543 fn open_app(&mut self, app: &str) -> Result<(), String> {
545 Err(format!("abrir outro app não existe aqui ({app})"))
546 }
547 fn share(&mut self, text: &str, files: &[String]) -> Result<(), String> {
549 let _ = (text, files);
550 Err("compartilhar não existe aqui".into())
551 }
552 fn request(&mut self, action: &str, data: &str, done: Box<dyn FnOnce(Result<String, String>) + Send>) {
555 let _ = data;
556 done(Err(format!("pedir a outro app não existe aqui ({action})")));
557 }
558 fn can_register_schemes(&self) -> bool {
561 false
562 }
563 fn register_scheme(&mut self, scheme: &str, description: &str) -> Result<(), String> {
567 let _ = description;
568 Err(format!("registrar o prefixo {scheme}:// em execução não existe aqui (vai na publicação)"))
569 }
570 fn unregister_scheme(&mut self, scheme: &str) -> Result<(), String> {
572 Err(format!("tirar o registro do prefixo {scheme}:// não existe aqui"))
573 }
574 fn scheme_registered(&mut self, scheme: &str) -> bool {
576 let _ = scheme;
577 false
578 }
579 fn receive_links(&mut self, on_link: Box<dyn Fn(String) + Send>) {
582 let _ = on_link;
583 }
584}
585
586const RESERVED_SCHEMES: &[&str] = &[
588 "http", "https", "file", "ftp", "ftps", "mailto", "tel", "sms", "data", "javascript", "vbscript", "about", "blob", "ws", "wss", "shell", "search",
589 "search-ms", "res", "its", "mk", "hcp", "callto", "news", "nntp", "telnet", "ldap", "ssh", "sftp", "smb", "git", "magnet", "steam", "zoommtg",
590];
591
592pub fn check_scheme(scheme: &str) -> Result<String, String> {
596 let s = scheme.trim().trim_end_matches("://").trim_end_matches(':').to_ascii_lowercase();
597 let valid = s.len() >= 3
598 && s.len() <= 64
599 && s.starts_with(|c: char| c.is_ascii_lowercase())
600 && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '+' | '-' | '.'));
601 if !valid {
602 return Err(crate::messages::tf("prefixo inválido: {0} (letras, números, + - ., de 3 a 64)", &[&scheme]));
603 }
604 if RESERVED_SCHEMES.contains(&s.as_str()) || s.starts_with("ms-") || s.starts_with("microsoft") || s.starts_with("windows") {
605 return Err(crate::messages::tf("o prefixo {0} é do sistema", &[&s]));
606 }
607 Ok(s)
608}
609
610static STARTUP_LINKS: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
613
614pub fn push_startup_link(url: String) {
616 if let Ok(mut list) = STARTUP_LINKS.lock() {
617 list.push(url);
618 }
619}
620
621pub fn take_startup_links(scheme: &str) -> Vec<String> {
623 let Ok(mut list) = STARTUP_LINKS.lock() else { return Vec::new() };
624 let (mine, rest): (Vec<String>, Vec<String>) = std::mem::take(&mut *list).into_iter().partition(|url| link_scheme(url).as_deref() == Some(scheme));
625 *list = rest;
626 mine
627}
628
629pub fn link_scheme(url: &str) -> Option<String> {
631 let (scheme, _) = url.split_once(':')?;
632 (!scheme.is_empty()).then(|| scheme.to_ascii_lowercase())
633}
634
635#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
637pub enum Sensor {
638 Location,
640 Battery,
642 Network,
644 Motion,
646 Compass,
648 Proximity,
650 Light,
652}
653
654pub trait SensorService {
657 fn available(&self, sensor: Sensor) -> bool;
659 fn set_active(&mut self, sensor: Sensor, on: bool);
661 fn read(&mut self, sensor: Sensor) -> Option<Vec<f64>>;
663 fn vibrate(&mut self, ms: u32) -> bool {
665 let _ = ms;
666 false
667 }
668}
669
670pub const GAMEPAD_BUTTONS: [&str; 17] =
674 ["a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "l3", "r3", "up", "down", "left", "right", "guide"];
675
676#[derive(Clone, Debug, Default, PartialEq)]
678pub struct GamepadState {
679 pub name: String,
680 pub buttons: u32,
682 pub axes: [f32; 6],
685}
686
687impl GamepadState {
688 pub fn set_button(&mut self, name: &str, down: bool) {
690 if let Some(i) = GAMEPAD_BUTTONS.iter().position(|b| *b == name) {
691 if down {
692 self.buttons |= 1 << i;
693 } else {
694 self.buttons &= !(1 << i);
695 }
696 }
697 }
698
699 pub fn pressed(&self, name: &str) -> bool {
700 GAMEPAD_BUTTONS.iter().position(|b| *b == name).is_some_and(|i| self.buttons & (1 << i) != 0)
701 }
702}
703
704pub trait GamepadService {
706 fn pads(&mut self) -> Vec<GamepadState>;
708 fn rumble(&mut self, index: usize, strength: f32, ms: u32) -> bool {
710 let _ = (index, strength, ms);
711 false
712 }
713}
714
715pub trait PhoneService {
717 fn dial(&mut self, number: &str) -> Result<(), String>;
719 fn call(&mut self, number: &str) -> Result<(), String>;
721 fn watch(&mut self, on: bool);
723 fn state(&mut self) -> (String, String);
726 fn request_dialer(&mut self) -> Result<(), String> {
728 Err("não existe aqui".into())
729 }
730 fn answer(&mut self) -> bool {
732 false
733 }
734 fn reject(&mut self) -> bool {
735 false
736 }
737 fn hang_up(&mut self) -> bool {
738 false
739 }
740 fn history(&mut self, max: u32) -> Result<String, String> {
742 let _ = max;
743 Err("não existe aqui".into())
744 }
745 fn lock_screen(&mut self, show_when_locked: bool, turn_screen_on: bool);
747 fn dismiss_keyguard(&mut self);
749}
750
751pub trait BackgroundHost {
756 fn start(&mut self, title: &str, text: &str, kind: &str, keep_alive: bool) -> Result<(), String>;
757 fn stop(&mut self);
758}
759
760#[derive(Clone, Debug, PartialEq, Eq)]
763pub enum Incoming {
764 Link(String),
765 Shared(String),
766}
767
768static INCOMING: std::sync::Mutex<Vec<Incoming>> = std::sync::Mutex::new(Vec::new());
769
770pub fn push_incoming(item: Incoming) {
773 if let Ok(mut list) = INCOMING.lock() {
774 list.push(item);
775 }
776}
777
778pub fn take_incoming() -> Vec<Incoming> {
780 INCOMING.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
781}
782
783pub trait OffscreenService {
786 fn render_png(&self, width: u32, height: u32, scale: f32, background: crate::Color, paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>>;
788
789 fn render_rgba(&self, _width: u32, _height: u32, _scale: f32, _background: crate::Color, _paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>> {
794 None
795 }
796
797 fn render_area_rgba(
802 &self,
803 _width: u32,
804 _height: u32,
805 _background: crate::Color,
806 _over: Option<(&[u8], crate::geometry::RectF)>,
807 _paint: &mut dyn FnMut(&mut dyn crate::Canvas),
808 ) -> Option<Vec<u8>> {
809 None
810 }
811}
812
813pub trait WindowCaptureService {
816 fn capture(&mut self, form: crate::ComponentId) -> Option<(u32, u32, Vec<u8>)>;
818}
819
820#[derive(Default)]
822pub struct Services {
823 pub window_capture: Option<Box<dyn WindowCaptureService>>,
825 pub offscreen: Option<Box<dyn OffscreenService>>,
826 pub window: Option<Box<dyn WindowService>>,
827 pub timer: Option<Box<dyn TimerService>>,
828 pub clipboard: Option<Box<dyn ClipboardService>>,
829 pub clipboard_local: crate::clipboard::LocalClipboard,
831 pub cursor: Option<Box<dyn CursorService>>,
832 pub screen: Option<Box<dyn ScreenService>>,
833 pub text_input: Option<Box<dyn TextInputService>>,
834 pub locale: Option<Box<dyn LocaleService>>,
835 pub text: Option<Box<dyn TextService>>,
836 pub resources: Option<Box<dyn ResourceService>>,
837 pub forms: Option<Box<dyn FormFactory>>,
838 pub file_dialogs: Option<Box<dyn FileDialogService>>,
839 pub permissions: Option<Box<dyn PermissionService>>,
841 pub biometrics: Option<Box<dyn BiometricService>>,
843 pub http: Option<Box<dyn HttpService>>,
844 pub notifications: Option<Box<dyn NotificationService>>,
845 pub links: Option<Box<dyn LinkService>>,
847 pub sensors: Option<Box<dyn SensorService>>,
849 pub background: Option<Box<dyn BackgroundHost>>,
852 pub phone: Option<Box<dyn PhoneService>>,
854 pub gamepads: Option<Box<dyn GamepadService>>,
856 pub printer: Option<Box<dyn PrintService>>,
857 pub text_assist: Option<Box<dyn crate::textassist::TextAssist>>,
860 pub nfc: Option<Box<dyn NfcService>>,
862 pub bluetooth: Option<Box<dyn BluetoothService>>,
864 pub push: Option<Box<dyn PushService>>,
866 pub actions: Option<Box<dyn ActionService>>,
870 pub ole: Option<Box<dyn OleService>>,
872 pub wmi: Option<Box<dyn WmiService>>,
874}
875
876#[derive(Clone, Debug, Default, PartialEq, Eq)]
878pub struct NfcTag {
879 pub id: String,
881 pub tech: String,
883 pub records: Vec<crate::ndef::NdefRecord>,
885 pub writable: bool,
887}
888
889#[derive(Clone, Debug, PartialEq, Eq)]
891pub enum NfcEvent {
892 Tag(NfcTag),
893 Written,
895 Error(String),
896}
897
898pub trait NfcService {
901 fn available(&self) -> bool;
903 fn enabled(&self) -> bool {
905 self.available()
906 }
907 fn set_reading(&mut self, on: bool);
909 fn write(&mut self, message: Vec<u8>);
912 fn cancel_write(&mut self) {}
914 fn poll(&mut self) -> Vec<NfcEvent>;
916}
917
918#[derive(Clone, Debug, Default, PartialEq, Eq)]
920pub struct BleDevice {
921 pub id: String,
924 pub name: String,
925 pub rssi: i32,
927}
928
929#[derive(Clone, Debug, Default, PartialEq, Eq)]
931pub struct BleCharacteristic {
932 pub service: String,
933 pub characteristic: String,
934 pub properties: Vec<String>,
936}
937
938#[derive(Clone, Debug, PartialEq, Eq)]
940pub enum BluetoothEvent {
941 Found(BleDevice),
942 ScanStopped,
944 Connected { device: String, services: Vec<BleCharacteristic> },
946 Disconnected(String),
947 Value { device: String, characteristic: String, data: Vec<u8> },
949 Written { device: String, characteristic: String },
950 Received { device: String, data: Vec<u8> },
952 Error(String),
953}
954
955pub trait BluetoothService {
959 fn available(&self) -> bool;
960 fn enabled(&self) -> bool {
962 self.available()
963 }
964 fn scan(&mut self, on: bool, services: Vec<String>, name: String);
967 fn connect(&mut self, device: &str);
968 fn disconnect(&mut self, device: &str);
969 fn read(&mut self, device: &str, service: &str, characteristic: &str);
970 fn write(&mut self, device: &str, service: &str, characteristic: &str, data: Vec<u8>, with_response: bool);
971 fn subscribe(&mut self, device: &str, service: &str, characteristic: &str, on: bool);
973 fn paired(&mut self) -> Vec<(String, String)> {
975 Vec::new()
976 }
977 fn open_serial(&mut self, device: &str) -> Result<(), String> {
979 let _ = device;
980 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
981 }
982 fn send_serial(&mut self, device: &str, data: Vec<u8>) -> Result<(), String> {
983 let _ = (device, data);
984 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
985 }
986 fn close_serial(&mut self, device: &str) {
987 let _ = device;
988 }
989 fn poll(&mut self) -> Vec<BluetoothEvent>;
991}
992
993pub fn ble_uuid(text: &str) -> String {
996 let t = text.trim().trim_start_matches("0x").trim_start_matches("0X").to_ascii_lowercase();
997 if (t.len() == 4 || t.len() == 8) && t.chars().all(|c| c.is_ascii_hexdigit()) {
998 format!("{t:0>8}-0000-1000-8000-00805f9b34fb")
999 } else {
1000 t
1001 }
1002}
1003
1004#[derive(Clone, Debug, Default, PartialEq, Eq)]
1006pub struct PushMessage {
1007 pub id: String,
1009 pub title: String,
1011 pub body: String,
1012 pub data: String,
1014}
1015
1016#[derive(Clone, Debug, PartialEq, Eq)]
1018pub enum PushEvent {
1019 Token(String),
1023 Message(PushMessage),
1025 Opened(PushMessage),
1027 Error(String),
1028}
1029
1030#[derive(Clone, Debug, Default, PartialEq, Eq)]
1033pub struct PushConfig {
1034 pub sender_id: String,
1036 pub project_id: String,
1038 pub app_id: String,
1040 pub api_key: String,
1042 pub vapid_key: String,
1044 pub show_in_foreground: bool,
1047}
1048
1049pub trait PushService {
1053 fn available(&self) -> bool;
1056 fn provider(&self) -> &'static str;
1059 fn register(&mut self, config: &PushConfig);
1062 fn unregister(&mut self) {}
1064 fn shows_notifications(&self) -> bool {
1068 true
1069 }
1070 fn poll(&mut self) -> Vec<PushEvent> {
1072 Vec::new()
1073 }
1074}
1075
1076static PUSH_EVENTS: std::sync::Mutex<Vec<PushEvent>> = std::sync::Mutex::new(Vec::new());
1077
1078pub fn push_event(event: PushEvent) {
1081 if let Ok(mut list) = PUSH_EVENTS.lock() {
1082 list.push(event);
1083 }
1084}
1085
1086pub fn take_push_events() -> Vec<PushEvent> {
1088 PUSH_EVENTS.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
1089}
1090
1091pub fn parse_push_line(line: &str) -> Option<PushEvent> {
1095 let mut f = line.split('\t');
1096 let kind = f.next()?;
1097 let mut next = || f.next().unwrap_or_default().to_string();
1098 match kind {
1099 "token" => Some(PushEvent::Token(next())),
1100 "error" => Some(PushEvent::Error(next())),
1101 "message" | "opened" => {
1102 let mut m = PushMessage { id: next(), title: next(), body: next(), data: next() };
1103 if m.data.trim().is_empty() {
1104 m.data = "{}".into();
1105 }
1106 Some(if kind == "message" { PushEvent::Message(m) } else { PushEvent::Opened(m) })
1107 }
1108 _ => None,
1109 }
1110}
1111
1112pub fn json_field(json: &str, key: &str) -> Option<String> {
1115 let chars: Vec<char> = json.chars().collect();
1116 let mut i = 0;
1117 let skip_ws = |i: &mut usize| {
1118 while *i < chars.len() && chars[*i].is_whitespace() {
1119 *i += 1;
1120 }
1121 };
1122 let read_string = |i: &mut usize| -> Option<String> {
1124 if chars.get(*i) != Some(&'"') {
1125 return None;
1126 }
1127 *i += 1;
1128 let mut out = String::new();
1129 while *i < chars.len() {
1130 let c = chars[*i];
1131 *i += 1;
1132 match c {
1133 '"' => return Some(out),
1134 '\\' => {
1135 let e = *chars.get(*i)?;
1136 *i += 1;
1137 match e {
1138 'n' => out.push('\n'),
1139 't' => out.push('\t'),
1140 'r' => out.push('\r'),
1141 'b' => out.push('\u{8}'),
1142 'f' => out.push('\u{c}'),
1143 'u' => {
1144 let hex: String = chars.get(*i..*i + 4)?.iter().collect();
1145 *i += 4;
1146 let mut code = u32::from_str_radix(&hex, 16).ok()?;
1147 if (0xD800..0xDC00).contains(&code) && chars.get(*i) == Some(&'\\') && chars.get(*i + 1) == Some(&'u') {
1149 let low: String = chars.get(*i + 2..*i + 6)?.iter().collect();
1150 if let Ok(low) = u32::from_str_radix(&low, 16) {
1151 *i += 6;
1152 code = 0x10000 + ((code - 0xD800) << 10) + (low.wrapping_sub(0xDC00) & 0x3FF);
1153 }
1154 }
1155 out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
1156 }
1157 other => out.push(other),
1158 }
1159 }
1160 c => out.push(c),
1161 }
1162 }
1163 None
1164 };
1165 skip_ws(&mut i);
1166 if chars.get(i) != Some(&'{') {
1167 return None;
1168 }
1169 i += 1;
1170 loop {
1171 skip_ws(&mut i);
1172 if chars.get(i) == Some(&'}') || i >= chars.len() {
1173 return None;
1174 }
1175 let name = read_string(&mut i)?;
1176 skip_ws(&mut i);
1177 if chars.get(i) != Some(&':') {
1178 return None;
1179 }
1180 i += 1;
1181 skip_ws(&mut i);
1182 let value = if chars.get(i) == Some(&'"') {
1183 read_string(&mut i)?
1184 } else {
1185 let start = i;
1187 let (mut depth, mut quoted) = (0i32, false);
1188 while i < chars.len() {
1189 let c = chars[i];
1190 if quoted {
1191 if c == '\\' {
1192 i += 1;
1193 } else if c == '"' {
1194 quoted = false;
1195 }
1196 } else {
1197 match c {
1198 '"' => quoted = true,
1199 '{' | '[' => depth += 1,
1200 '}' | ']' if depth == 0 => break,
1201 '}' | ']' => depth -= 1,
1202 ',' if depth == 0 => break,
1203 _ => {}
1204 }
1205 }
1206 i += 1;
1207 }
1208 chars[start..i.min(chars.len())].iter().collect::<String>().trim().to_string()
1209 };
1210 if name == key {
1211 return Some(value);
1212 }
1213 skip_ws(&mut i);
1214 if chars.get(i) == Some(&',') {
1215 i += 1;
1216 }
1217 }
1218}
1219
1220pub fn push_message_from_payload(text: &str) -> PushMessage {
1224 let text = text.trim();
1225 if !text.starts_with('{') {
1226 return PushMessage { body: text.to_string(), data: "{}".into(), ..Default::default() };
1227 }
1228 let notification = json_field(text, "notification").unwrap_or_default();
1229 let pick = |key: &str| json_field(text, key).or_else(|| json_field(¬ification, key)).unwrap_or_default();
1230 let data = json_field(text, "data").filter(|d| d.trim_start().starts_with('{')).unwrap_or_else(|| "{}".into());
1231 PushMessage { id: pick("id"), title: pick("title"), body: pick("body"), data }
1232}
1233
1234pub fn render_template(template: &str, data: &str) -> String {
1237 let mut out = String::new();
1238 let mut rest = template;
1239 while let Some(i) = rest.find(['{', '}']) {
1240 out.push_str(&rest[..i]);
1241 let tail = &rest[i..];
1242 if tail.starts_with("{{") || tail.starts_with("}}") {
1243 out.push_str(&tail[..1]);
1244 rest = &tail[2..];
1245 } else if let (true, Some(end)) = (tail.starts_with('{'), tail.find('}')) {
1246 out.push_str(&json_field(data, tail[1..end].trim()).unwrap_or_default());
1247 rest = &tail[end + 1..];
1248 } else {
1249 out.push_str(&tail[..1]);
1250 rest = &tail[1..];
1251 }
1252 }
1253 out.push_str(rest);
1254 out
1255}
1256
1257pub fn data_matches(filter: &str, data: &str) -> bool {
1260 filter.split(';').map(str::trim).filter(|c| !c.is_empty()).all(|c| {
1261 if let Some((k, v)) = c.split_once("!=") {
1262 json_field(data, k.trim()).unwrap_or_default() != v.trim()
1263 } else if let Some((k, v)) = c.split_once('=') {
1264 json_field(data, k.trim()).unwrap_or_default() == v.trim()
1265 } else {
1266 json_field(data, c).is_some_and(|v| !v.is_empty())
1267 }
1268 })
1269}
1270
1271pub fn json_quote(text: &str) -> String {
1273 let mut out = String::with_capacity(text.len() + 2);
1274 out.push('"');
1275 for c in text.chars() {
1276 match c {
1277 '"' => out.push_str("\\\""),
1278 '\\' => out.push_str("\\\\"),
1279 '\n' => out.push_str("\\n"),
1280 '\r' => out.push_str("\\r"),
1281 '\t' => out.push_str("\\t"),
1282 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1283 c => out.push(c),
1284 }
1285 }
1286 out.push('"');
1287 out
1288}
1289
1290#[derive(Clone, Debug, PartialEq, Eq)]
1292pub struct ActionEvent {
1293 pub kind: String,
1297 pub component: String,
1299 pub detail: String,
1301 pub data: String,
1303}
1304
1305pub fn parse_action_line(line: &str) -> Option<ActionEvent> {
1307 let mut f = line.split('\t');
1308 let kind = f.next().filter(|k| !k.is_empty())?.to_string();
1309 let component = f.next()?.to_string();
1310 let detail = f.next().unwrap_or_default().to_string();
1311 let data = f.next().filter(|d| !d.trim().is_empty()).unwrap_or("{}").to_string();
1312 Some(ActionEvent { kind, component, detail, data })
1313}
1314
1315pub trait ActionService {
1319 fn execute(&mut self, spec: &str, data: &str) -> Result<(), String>;
1320 fn stop(&mut self, component: &str);
1322 fn set_push_rules(&mut self, rules: &str);
1325 fn poll(&mut self) -> Vec<ActionEvent>;
1327}
1328
1329#[derive(Clone, Debug, PartialEq)]
1331pub enum OleValue {
1332 Null,
1333 Bool(bool),
1334 Int(i64),
1335 Float(f64),
1336 String(String),
1337 Date(f64),
1340 Object(u64),
1343 Array(Vec<Vec<OleValue>>),
1346}
1347
1348pub trait OleService {
1355 fn create(&mut self, prog_id: &str, running: bool) -> Result<u64, String>;
1358 fn invoke(&mut self, object: u64, name: &str, args: Vec<OleValue>) -> Result<OleValue, String>;
1360 fn put(&mut self, object: u64, name: &str, args: Vec<OleValue>, value: OleValue) -> Result<(), String>;
1362 fn release(&mut self, object: u64);
1364 fn set_timeout(&mut self, seconds: f64) {
1366 let _ = seconds;
1367 }
1368 fn releaser(&self) -> Option<OleReleaser> {
1370 None
1371 }
1372}
1373
1374pub type OleReleaser = std::sync::Arc<dyn Fn(u64) + Send + Sync>;
1376
1377static OLE_ALLOWED: std::sync::RwLock<Vec<String>> = std::sync::RwLock::new(Vec::new());
1381
1382pub const OLE_DEFAULT: &[&str] = &["Excel.Application", "Word.Application", "Outlook.Application", "PowerPoint.Application"];
1384
1385pub fn allow_ole(prog_id: &str) {
1387 if let Ok(mut list) = OLE_ALLOWED.write() {
1388 if !list.iter().any(|p| p.eq_ignore_ascii_case(prog_id)) {
1389 list.push(prog_id.to_string());
1390 }
1391 }
1392}
1393
1394pub fn ole_allowed(prog_id: &str) -> bool {
1397 let id = prog_id.trim();
1398 let base = match id.rsplit_once('.') {
1399 Some((head, tail)) if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) => head,
1400 _ => id,
1401 };
1402 let ok = |p: &str| p.eq_ignore_ascii_case(base) || p.eq_ignore_ascii_case(id);
1403 OLE_DEFAULT.iter().any(|p| ok(p)) || OLE_ALLOWED.read().is_ok_and(|l| l.iter().any(|p| ok(p)))
1404}
1405
1406pub fn ole_date(year: i32, month: u32, day: u32, hour: u32, minute: u32, second: u32) -> f64 {
1408 let y = i64::from(year) - i64::from(month <= 2);
1410 let era = y.div_euclid(400);
1411 let yoe = y - era * 400;
1412 let m = i64::from(month);
1413 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(day) - 1;
1414 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
1415 let days = era * 146_097 + doe - 719_468 + 25_569;
1416 days as f64 + f64::from(hour * 3600 + minute * 60 + second) / 86_400.0
1417}
1418
1419pub fn ole_date_parts(date: f64) -> (i32, u32, u32, u32, u32, u32) {
1421 let mut days = date.floor() as i64;
1422 let mut secs = ((date - date.floor()) * 86_400.0).round() as i64;
1423 if secs >= 86_400 {
1424 days += 1;
1425 secs -= 86_400;
1426 }
1427 let z = days - 25_569 + 719_468;
1428 let era = z.div_euclid(146_097);
1429 let doe = z - era * 146_097;
1430 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1431 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1432 let mp = (5 * doy + 2) / 153;
1433 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
1434 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1435 let year = (yoe + era * 400 + i64::from(month <= 2)) as i32;
1436 (year, month, day, (secs / 3600) as u32, (secs % 3600 / 60) as u32, (secs % 60) as u32)
1437}
1438
1439#[derive(Clone, Debug, PartialEq)]
1441pub enum WmiValue {
1442 Null,
1443 Bool(bool),
1444 Int(i64),
1445 Float(f64),
1446 String(String),
1447 DateTime(String),
1449 Array(Vec<WmiValue>),
1451 Object(Vec<(String, WmiValue)>),
1453}
1454
1455#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1457pub enum WmiType {
1458 #[default]
1459 String,
1460 Integer,
1461 Float,
1462 Boolean,
1463 DateTime,
1464 Array,
1465 Object,
1466}
1467
1468#[derive(Clone, Debug, Default, PartialEq, Eq)]
1470pub struct WmiColumn {
1471 pub name: String,
1472 pub kind: WmiType,
1473}
1474
1475#[derive(Clone, Debug, Default, PartialEq)]
1478pub struct WmiTable {
1479 pub columns: Vec<WmiColumn>,
1480 pub rows: Vec<Vec<WmiValue>>,
1481}
1482
1483pub type WmiDone = Box<dyn FnOnce(Result<WmiTable, String>) + Send>;
1486
1487pub type WmiListener = std::sync::Arc<dyn Fn(Result<Vec<(String, WmiValue)>, String>) + Send + Sync>;
1490
1491pub struct WmiWatch(Option<Box<dyn FnOnce() + Send>>);
1493
1494impl WmiWatch {
1495 pub fn new(stop: impl FnOnce() + Send + 'static) -> Self {
1497 Self(Some(Box::new(stop)))
1498 }
1499}
1500
1501impl Drop for WmiWatch {
1502 fn drop(&mut self) {
1503 if let Some(stop) = self.0.take() {
1504 stop();
1505 }
1506 }
1507}
1508
1509pub trait WmiService {
1514 fn query(&mut self, namespace: &str, wql: &str, done: WmiDone);
1516 fn watch(&mut self, namespace: &str, wql: &str, listener: WmiListener) -> Result<WmiWatch, String>;
1520}
1521
1522pub fn wmi_namespace(namespace: &str) -> Result<String, String> {
1526 let ns = namespace.trim().replace('/', "\\");
1527 let ns = if ns.is_empty() { "root\\cimv2".to_string() } else { ns };
1528 let valid = ns.split('\\').all(|p| !p.is_empty() && p.chars().all(|c| c.is_alphanumeric() || c == '_'));
1529 if !valid || !ns.split('\\').next().is_some_and(|r| r.eq_ignore_ascii_case("root")) {
1530 return Err(crate::messages::tf("namespace do WMI inválido '{0}' (só desta máquina, como root\\cimv2)", &[&namespace]));
1531 }
1532 Ok(ns)
1533}
1534
1535pub fn wmi_datetime(text: &str) -> Option<String> {
1539 let t = text.trim();
1540 let b = t.as_bytes();
1541 if b.len() < 14 || !b[..14].iter().all(u8::is_ascii_digit) || b.get(21) == Some(&b':') {
1542 return None;
1543 }
1544 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]);
1545 let month: u32 = mo.parse().ok()?;
1546 let day: u32 = d.parse().ok()?;
1547 if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
1548 return None;
1549 }
1550 Some(format!("{y}-{mo}-{d}T{h}:{mi}:{s}"))
1551}
1552
1553pub fn wmi_select_list(wql: &str) -> Vec<String> {
1556 let t = wql.trim();
1557 let lower = t.to_ascii_lowercase();
1558 let (Some(rest), Some(from)) = (lower.strip_prefix("select"), lower.find(" from ")) else { return Vec::new() };
1559 let start = t.len() - rest.len();
1560 if from < start {
1561 return Vec::new();
1562 }
1563 t[start..from].split(',').map(str::trim).filter(|n| !n.is_empty() && *n != "*").map(str::to_string).collect()
1564}
1565
1566
1567static LOCAL_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1571
1572pub fn set_local_offset_fn(f: fn(i64) -> i64) {
1573 if let Ok(mut slot) = LOCAL_OFFSET.write() {
1574 *slot = Some(f);
1575 }
1576}
1577
1578static PROJECT_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1581
1582pub fn set_project_offset_fn(f: Option<fn(i64) -> i64>) {
1584 if let Ok(mut slot) = PROJECT_OFFSET.write() {
1585 *slot = f;
1586 }
1587}
1588
1589pub fn local_offset(utc: i64) -> i64 {
1592 let project = PROJECT_OFFSET.read().ok().and_then(|f| *f);
1593 project.or_else(|| LOCAL_OFFSET.read().ok().and_then(|f| *f)).map_or(0, |f| f(utc))
1594}