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 folder: bool,
319 pub owner: Option<crate::ComponentId>,
321}
322
323pub trait FileDialogService {
326 fn show(&mut self, options: FileDialogOptions, done: Box<dyn FnOnce(Vec<String>) + Send>);
327}
328
329#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
332pub enum Permission {
333 Camera,
334 Microphone,
335 Location,
337 Notifications,
338 Photos,
340 Contacts,
341 Calendar,
342 Bluetooth,
343}
344
345impl Permission {
346 pub const ALL: [Permission; 8] = [
347 Permission::Camera,
348 Permission::Microphone,
349 Permission::Location,
350 Permission::Notifications,
351 Permission::Photos,
352 Permission::Contacts,
353 Permission::Calendar,
354 Permission::Bluetooth,
355 ];
356
357 pub fn name(self) -> &'static str {
359 match self {
360 Permission::Camera => "camera",
361 Permission::Microphone => "microphone",
362 Permission::Location => "location",
363 Permission::Notifications => "notifications",
364 Permission::Photos => "photos",
365 Permission::Contacts => "contacts",
366 Permission::Calendar => "calendar",
367 Permission::Bluetooth => "bluetooth",
368 }
369 }
370
371 pub fn parse(name: &str) -> Option<Permission> {
372 let name = name.trim();
373 Permission::ALL.into_iter().find(|p| p.name().eq_ignore_ascii_case(name))
374 }
375
376 pub fn parse_list(list: &str) -> Vec<Permission> {
378 let mut out = Vec::new();
379 for p in list.split([';', ',']).filter_map(Permission::parse) {
380 if !out.contains(&p) {
381 out.push(p);
382 }
383 }
384 out
385 }
386}
387
388#[derive(Clone, Copy, Debug, PartialEq, Eq)]
390pub enum PermissionState {
391 Granted,
393 Denied,
395 Prompt,
397 Unavailable,
399}
400
401impl PermissionState {
402 pub fn name(self) -> &'static str {
403 match self {
404 PermissionState::Granted => "granted",
405 PermissionState::Denied => "denied",
406 PermissionState::Prompt => "prompt",
407 PermissionState::Unavailable => "unavailable",
408 }
409 }
410}
411
412impl crate::prop::PropEnum for Permission {
416 const NAMES: &'static [&'static str] = &["camera", "microphone", "location", "notifications", "photos", "contacts", "calendar", "bluetooth"];
417 fn from_index(index: usize) -> Option<Self> {
418 Permission::ALL.get(index).copied()
419 }
420 fn index(self) -> usize {
421 Permission::ALL.iter().position(|p| *p == self).unwrap_or(0)
422 }
423}
424
425impl crate::prop::PropEnum for PermissionState {
426 const NAMES: &'static [&'static str] = &["granted", "denied", "prompt", "unavailable"];
427 fn from_index(index: usize) -> Option<Self> {
428 [PermissionState::Granted, PermissionState::Denied, PermissionState::Prompt, PermissionState::Unavailable].get(index).copied()
429 }
430 fn index(self) -> usize {
431 self as usize
432 }
433}
434
435impl crate::prop::PropEnum for Biometry {
436 const NAMES: &'static [&'static str] = &["none", "fingerprint", "face", "iris", "any"];
437 fn from_index(index: usize) -> Option<Self> {
438 [Biometry::None, Biometry::Fingerprint, Biometry::Face, Biometry::Iris, Biometry::Any].get(index).copied()
439 }
440 fn index(self) -> usize {
441 self as usize
442 }
443}
444
445pub trait PermissionService {
446 fn state(&self, permission: Permission) -> PermissionState;
447 fn request(&mut self, permissions: Vec<Permission>, done: Box<dyn FnOnce(Vec<(Permission, PermissionState)>) + Send>);
448}
449
450#[derive(Clone, Copy, Debug, PartialEq, Eq)]
452pub enum Biometry {
453 None,
455 Fingerprint,
456 Face,
457 Iris,
458 Any,
460}
461
462impl Biometry {
463 pub fn name(self) -> &'static str {
464 match self {
465 Biometry::None => "none",
466 Biometry::Fingerprint => "fingerprint",
467 Biometry::Face => "face",
468 Biometry::Iris => "iris",
469 Biometry::Any => "any",
470 }
471 }
472}
473
474#[derive(Clone, Debug, PartialEq, Eq)]
476pub enum BiometricResult {
477 Success,
478 Cancelled,
480 Failed(String),
482}
483
484pub trait BiometricService {
487 fn availability(&self) -> Biometry;
488 fn authenticate(&mut self, reason: &str, allow_device_credential: bool, done: Box<dyn FnOnce(BiometricResult) + Send>);
491}
492
493pub trait PrintService {
497 fn print(&mut self, title: &str, pages: crate::pages::PageSet, done: Box<dyn FnOnce(Result<bool, String>) + Send>);
498
499 fn wants_pdf(&self) -> bool {
502 false
503 }
504
505 fn print_pdf(&mut self, title: &str, pdf: Vec<u8>, done: Box<dyn FnOnce(Result<bool, String>) + Send>) {
507 let _ = (title, pdf);
508 done(Err("esta plataforma não imprime PDF".into()));
509 }
510}
511
512pub trait HttpService {
516 fn get(&mut self, url: &str, done: Box<dyn FnOnce(Result<Vec<u8>, String>) + Send>);
517}
518
519#[derive(Clone, Debug, Default, PartialEq)]
521pub struct SystemNotification {
522 pub app_id: String,
524 pub app_name: String,
526 pub title: String,
527 pub body: String,
528 pub image: String,
530 pub image_png: Vec<u8>,
532 pub big_image: bool,
534 pub id: u32,
536 pub channel: String,
538 pub channel_name: String,
539 pub priority: NotificationPriority,
540 pub actions: Vec<(String, String)>,
542 pub ongoing: bool,
544 pub progress: Option<f32>,
546 pub full_screen: bool,
549 pub component: Option<crate::ComponentId>,
551}
552
553#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
555pub enum NotificationPriority {
556 Low,
558 #[default]
559 Default,
560 High,
562}
563
564impl crate::PropEnum for NotificationPriority {
565 const NAMES: &'static [&'static str] = &["low", "default", "high"];
566 fn from_index(index: usize) -> Option<Self> {
567 [Self::Low, Self::Default, Self::High].get(index).copied()
568 }
569 fn index(self) -> usize {
570 self as usize
571 }
572}
573
574pub trait NotificationService {
576 fn notify(&mut self, notification: &SystemNotification) -> Result<(), String>;
577 fn cancel(&mut self, id: u32) -> Result<(), String> {
579 let _ = id;
580 Ok(())
581 }
582}
583
584pub trait LinkService {
587 fn open_url(&mut self, url: &str) -> Result<(), String>;
589 fn open_app(&mut self, app: &str) -> Result<(), String> {
591 Err(format!("abrir outro app não existe aqui ({app})"))
592 }
593 fn share(&mut self, text: &str, files: &[String]) -> Result<(), String> {
595 let _ = (text, files);
596 Err("compartilhar não existe aqui".into())
597 }
598 fn request(&mut self, action: &str, data: &str, done: Box<dyn FnOnce(Result<String, String>) + Send>) {
601 let _ = data;
602 done(Err(format!("pedir a outro app não existe aqui ({action})")));
603 }
604 fn can_register_schemes(&self) -> bool {
607 false
608 }
609 fn register_scheme(&mut self, scheme: &str, description: &str) -> Result<(), String> {
613 let _ = description;
614 Err(format!("registrar o prefixo {scheme}:// em execução não existe aqui (vai na publicação)"))
615 }
616 fn unregister_scheme(&mut self, scheme: &str) -> Result<(), String> {
618 Err(format!("tirar o registro do prefixo {scheme}:// não existe aqui"))
619 }
620 fn scheme_registered(&mut self, scheme: &str) -> bool {
622 let _ = scheme;
623 false
624 }
625 fn receive_links(&mut self, on_link: Box<dyn Fn(String) + Send>) {
628 let _ = on_link;
629 }
630}
631
632const RESERVED_SCHEMES: &[&str] = &[
634 "http", "https", "file", "ftp", "ftps", "mailto", "tel", "sms", "data", "javascript", "vbscript", "about", "blob", "ws", "wss", "shell", "search",
635 "search-ms", "res", "its", "mk", "hcp", "callto", "news", "nntp", "telnet", "ldap", "ssh", "sftp", "smb", "git", "magnet", "steam", "zoommtg",
636];
637
638pub fn check_scheme(scheme: &str) -> Result<String, String> {
642 let s = scheme.trim().trim_end_matches("://").trim_end_matches(':').to_ascii_lowercase();
643 let valid = s.len() >= 3
644 && s.len() <= 64
645 && s.starts_with(|c: char| c.is_ascii_lowercase())
646 && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '+' | '-' | '.'));
647 if !valid {
648 return Err(crate::messages::tf("prefixo inválido: {0} (letras, números, + - ., de 3 a 64)", &[&scheme]));
649 }
650 if RESERVED_SCHEMES.contains(&s.as_str()) || s.starts_with("ms-") || s.starts_with("microsoft") || s.starts_with("windows") {
651 return Err(crate::messages::tf("o prefixo {0} é do sistema", &[&s]));
652 }
653 Ok(s)
654}
655
656static STARTUP_LINKS: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
659
660pub fn push_startup_link(url: String) {
662 if let Ok(mut list) = STARTUP_LINKS.lock() {
663 list.push(url);
664 }
665}
666
667pub fn take_startup_links(scheme: &str) -> Vec<String> {
669 let Ok(mut list) = STARTUP_LINKS.lock() else { return Vec::new() };
670 let (mine, rest): (Vec<String>, Vec<String>) = std::mem::take(&mut *list).into_iter().partition(|url| link_scheme(url).as_deref() == Some(scheme));
671 *list = rest;
672 mine
673}
674
675pub fn link_scheme(url: &str) -> Option<String> {
677 let (scheme, _) = url.split_once(':')?;
678 (!scheme.is_empty()).then(|| scheme.to_ascii_lowercase())
679}
680
681#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
683pub enum Sensor {
684 Location,
686 Battery,
688 Network,
690 Motion,
692 Compass,
694 Proximity,
696 Light,
698}
699
700pub trait SensorService {
703 fn available(&self, sensor: Sensor) -> bool;
705 fn set_active(&mut self, sensor: Sensor, on: bool);
707 fn read(&mut self, sensor: Sensor) -> Option<Vec<f64>>;
709 fn vibrate(&mut self, ms: u32) -> bool {
711 let _ = ms;
712 false
713 }
714}
715
716pub const GAMEPAD_BUTTONS: [&str; 17] =
720 ["a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "l3", "r3", "up", "down", "left", "right", "guide"];
721
722#[derive(Clone, Debug, Default, PartialEq)]
724pub struct GamepadState {
725 pub name: String,
726 pub buttons: u32,
728 pub axes: [f32; 6],
731}
732
733impl GamepadState {
734 pub fn set_button(&mut self, name: &str, down: bool) {
736 if let Some(i) = GAMEPAD_BUTTONS.iter().position(|b| *b == name) {
737 if down {
738 self.buttons |= 1 << i;
739 } else {
740 self.buttons &= !(1 << i);
741 }
742 }
743 }
744
745 pub fn pressed(&self, name: &str) -> bool {
746 GAMEPAD_BUTTONS.iter().position(|b| *b == name).is_some_and(|i| self.buttons & (1 << i) != 0)
747 }
748}
749
750pub trait GamepadService {
752 fn pads(&mut self) -> Vec<GamepadState>;
754 fn rumble(&mut self, index: usize, strength: f32, ms: u32) -> bool {
756 let _ = (index, strength, ms);
757 false
758 }
759}
760
761pub trait PhoneService {
763 fn dial(&mut self, number: &str) -> Result<(), String>;
765 fn call(&mut self, number: &str) -> Result<(), String>;
767 fn watch(&mut self, on: bool);
769 fn state(&mut self) -> (String, String);
772 fn request_dialer(&mut self) -> Result<(), String> {
774 Err("não existe aqui".into())
775 }
776 fn answer(&mut self) -> bool {
778 false
779 }
780 fn reject(&mut self) -> bool {
781 false
782 }
783 fn hang_up(&mut self) -> bool {
784 false
785 }
786 fn history(&mut self, max: u32) -> Result<String, String> {
788 let _ = max;
789 Err("não existe aqui".into())
790 }
791 fn lock_screen(&mut self, show_when_locked: bool, turn_screen_on: bool);
793 fn dismiss_keyguard(&mut self);
795}
796
797pub trait BackgroundHost {
802 fn start(&mut self, title: &str, text: &str, kind: &str, keep_alive: bool) -> Result<(), String>;
803 fn stop(&mut self);
804}
805
806#[derive(Clone, Debug, PartialEq, Eq)]
809pub enum Incoming {
810 Link(String),
811 Shared(String),
812}
813
814static INCOMING: std::sync::Mutex<Vec<Incoming>> = std::sync::Mutex::new(Vec::new());
815
816pub fn push_incoming(item: Incoming) {
819 if let Ok(mut list) = INCOMING.lock() {
820 list.push(item);
821 }
822}
823
824pub fn take_incoming() -> Vec<Incoming> {
826 INCOMING.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
827}
828
829pub trait OffscreenService {
832 fn render_png(&self, width: u32, height: u32, scale: f32, background: crate::Color, paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>>;
834
835 fn render_rgba(&self, _width: u32, _height: u32, _scale: f32, _background: crate::Color, _paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>> {
840 None
841 }
842
843 fn render_area_rgba(
848 &self,
849 _width: u32,
850 _height: u32,
851 _background: crate::Color,
852 _over: Option<(&[u8], crate::geometry::RectF)>,
853 _paint: &mut dyn FnMut(&mut dyn crate::Canvas),
854 ) -> Option<Vec<u8>> {
855 None
856 }
857}
858
859pub trait WindowCaptureService {
862 fn capture(&mut self, form: crate::ComponentId) -> Option<(u32, u32, Vec<u8>)>;
864}
865
866pub trait DesktopService {
871 fn cursor_position(&self) -> Option<(i32, i32)> {
873 None
874 }
875 fn form_at(&self, _x: i32, _y: i32) -> Option<crate::ComponentId> {
878 None
879 }
880 fn transparency(&self) -> Option<bool> {
882 None
883 }
884 fn capture_monitor(&mut self, _area: (i32, i32, u32, u32), _max_width: u32, done: Box<dyn FnOnce(Result<crate::Image, String>) + Send>) {
888 done(Err(crate::messages::t("A captura da tela não existe neste sistema.")));
889 }
890 fn session_state(&self) -> Option<(bool, bool)> {
893 None
894 }
895 fn start_with_login(&self) -> bool {
897 false
898 }
899 fn set_start_with_login(&mut self, _on: bool) -> Result<(), String> {
901 Err(crate::messages::t("Iniciar com o sistema não existe nesta plataforma."))
902 }
903 fn release_single_instance(&mut self) {}
905 fn lock_keys(&self) -> Option<crate::LockKeys> {
908 None
909 }
910}
911
912#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
914pub enum SingleInstance {
915 #[default]
917 Off,
918 User,
920 Machine,
923}
924
925impl crate::prop::PropEnum for SingleInstance {
926 const NAMES: &'static [&'static str] = &["off", "user", "machine"];
927 fn from_index(i: usize) -> Option<Self> {
928 [SingleInstance::Off, SingleInstance::User, SingleInstance::Machine].get(i).copied()
929 }
930 fn index(self) -> usize {
931 self as usize
932 }
933}
934
935impl SingleInstance {
936 pub fn parse(text: &str) -> Self {
938 <Self as crate::prop::PropEnum>::from_name(text.trim()).unwrap_or_default()
939 }
940}
941
942#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
945pub enum SecondInstance {
946 #[default]
948 Forward,
949 Quiet,
951}
952
953impl crate::prop::PropEnum for SecondInstance {
954 const NAMES: &'static [&'static str] = &["forward", "quiet"];
955 fn from_index(i: usize) -> Option<Self> {
956 [SecondInstance::Forward, SecondInstance::Quiet].get(i).copied()
957 }
958 fn index(self) -> usize {
959 self as usize
960 }
961}
962
963impl SecondInstance {
964 pub fn parse(text: &str) -> Self {
966 <Self as crate::prop::PropEnum>::from_name(text.trim()).unwrap_or_default()
967 }
968}
969
970impl crate::Ui {
971 pub fn fire_second_instance(&mut self, args: Vec<String>) {
976 if let Some(form) = self.active_form().or_else(|| self.main_form()).filter(|f| self.is_open(*f)) {
977 self.window_command(form, crate::WindowCommand::Show);
978 }
979 let text = args.join(";");
982 self.extension::<SecondInstanceArgs>().0 = args;
983 for app in self.components().filter(|&c| self.class_name(c) == Some("ApplicationEvents")).collect::<Vec<_>>() {
984 self.fire(app, "on_second_instance", &crate::EventArgs::Text(text.clone()));
985 }
986 self.process_events();
987 }
988}
989
990#[derive(Default)]
992struct SecondInstanceArgs(Vec<String>);
993
994impl crate::Ui {
995 pub fn second_instance_args(&self) -> &[String] {
998 self.extension_ref::<SecondInstanceArgs>().map_or(&[], |a| a.0.as_slice())
999 }
1000
1001 pub fn release_single_instance(&mut self) {
1006 if let Some(d) = self.services_mut().desktop.as_mut() {
1007 d.release_single_instance();
1008 }
1009 }
1010
1011 pub fn start_with_login(&self) -> bool {
1016 self.services().desktop.as_ref().is_some_and(|d| d.start_with_login())
1017 }
1018
1019 pub fn set_start_with_login(&mut self, on: bool) -> Result<(), String> {
1025 match self.services_mut().desktop.as_mut() {
1026 Some(d) => d.set_start_with_login(on),
1027 None => Err(crate::messages::t("Iniciar com o sistema não existe nesta plataforma.")),
1028 }
1029 }
1030}
1031
1032#[derive(Default)]
1034pub struct Services {
1035 pub desktop: Option<Box<dyn DesktopService>>,
1038 pub window_capture: Option<Box<dyn WindowCaptureService>>,
1040 pub offscreen: Option<Box<dyn OffscreenService>>,
1041 pub window: Option<Box<dyn WindowService>>,
1042 pub timer: Option<Box<dyn TimerService>>,
1043 pub clipboard: Option<Box<dyn ClipboardService>>,
1044 pub clipboard_local: crate::clipboard::LocalClipboard,
1046 pub cursor: Option<Box<dyn CursorService>>,
1047 pub screen: Option<Box<dyn ScreenService>>,
1048 pub text_input: Option<Box<dyn TextInputService>>,
1049 pub locale: Option<Box<dyn LocaleService>>,
1050 pub text: Option<Box<dyn TextService>>,
1051 pub resources: Option<Box<dyn ResourceService>>,
1052 pub forms: Option<Box<dyn FormFactory>>,
1053 pub file_dialogs: Option<Box<dyn FileDialogService>>,
1054 pub permissions: Option<Box<dyn PermissionService>>,
1056 pub biometrics: Option<Box<dyn BiometricService>>,
1058 pub http: Option<Box<dyn HttpService>>,
1059 pub notifications: Option<Box<dyn NotificationService>>,
1060 pub links: Option<Box<dyn LinkService>>,
1062 pub sensors: Option<Box<dyn SensorService>>,
1064 pub background: Option<Box<dyn BackgroundHost>>,
1067 pub phone: Option<Box<dyn PhoneService>>,
1069 pub gamepads: Option<Box<dyn GamepadService>>,
1071 pub printer: Option<Box<dyn PrintService>>,
1072 pub pdf: Option<Box<dyn crate::providers::PdfProvider>>,
1075 pub text_assist: Option<Box<dyn crate::textassist::TextAssist>>,
1078 pub nfc: Option<Box<dyn NfcService>>,
1080 pub bluetooth: Option<Box<dyn BluetoothService>>,
1082 pub push: Option<Box<dyn PushService>>,
1084 pub media_session: Option<Box<dyn MediaSessionService>>,
1087 pub actions: Option<Box<dyn ActionService>>,
1091 pub ole: Option<Box<dyn OleService>>,
1093 pub wmi: Option<Box<dyn WmiService>>,
1095}
1096
1097#[derive(Clone, Debug, Default, PartialEq, Eq)]
1099pub struct NfcTag {
1100 pub id: String,
1102 pub tech: String,
1104 pub records: Vec<crate::ndef::NdefRecord>,
1106 pub writable: bool,
1108}
1109
1110#[derive(Clone, Debug, PartialEq, Eq)]
1112pub enum NfcEvent {
1113 Tag(NfcTag),
1114 Written,
1116 Error(String),
1117}
1118
1119pub trait NfcService {
1122 fn available(&self) -> bool;
1124 fn enabled(&self) -> bool {
1126 self.available()
1127 }
1128 fn set_reading(&mut self, on: bool);
1130 fn write(&mut self, message: Vec<u8>);
1133 fn cancel_write(&mut self) {}
1135 fn poll(&mut self) -> Vec<NfcEvent>;
1137}
1138
1139#[derive(Clone, Debug, Default, PartialEq, Eq)]
1141pub struct BleDevice {
1142 pub id: String,
1145 pub name: String,
1146 pub rssi: i32,
1148}
1149
1150#[derive(Clone, Debug, Default, PartialEq, Eq)]
1152pub struct BleCharacteristic {
1153 pub service: String,
1154 pub characteristic: String,
1155 pub properties: Vec<String>,
1157}
1158
1159#[derive(Clone, Debug, PartialEq, Eq)]
1161pub enum BluetoothEvent {
1162 Found(BleDevice),
1163 ScanStopped,
1165 Connected { device: String, services: Vec<BleCharacteristic> },
1167 Disconnected(String),
1168 Value { device: String, characteristic: String, data: Vec<u8> },
1170 Written { device: String, characteristic: String },
1171 Received { device: String, data: Vec<u8> },
1173 Error(String),
1174}
1175
1176pub trait BluetoothService {
1180 fn available(&self) -> bool;
1181 fn enabled(&self) -> bool {
1183 self.available()
1184 }
1185 fn scan(&mut self, on: bool, services: Vec<String>, name: String);
1188 fn connect(&mut self, device: &str);
1189 fn disconnect(&mut self, device: &str);
1190 fn read(&mut self, device: &str, service: &str, characteristic: &str);
1191 fn write(&mut self, device: &str, service: &str, characteristic: &str, data: Vec<u8>, with_response: bool);
1192 fn subscribe(&mut self, device: &str, service: &str, characteristic: &str, on: bool);
1194 fn paired(&mut self) -> Vec<(String, String)> {
1196 Vec::new()
1197 }
1198 fn open_serial(&mut self, device: &str) -> Result<(), String> {
1200 let _ = device;
1201 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
1202 }
1203 fn send_serial(&mut self, device: &str, data: Vec<u8>) -> Result<(), String> {
1204 let _ = (device, data);
1205 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
1206 }
1207 fn close_serial(&mut self, device: &str) {
1208 let _ = device;
1209 }
1210 fn poll(&mut self) -> Vec<BluetoothEvent>;
1212}
1213
1214pub fn ble_uuid(text: &str) -> String {
1217 let t = text.trim().trim_start_matches("0x").trim_start_matches("0X").to_ascii_lowercase();
1218 if (t.len() == 4 || t.len() == 8) && t.chars().all(|c| c.is_ascii_hexdigit()) {
1219 format!("{t:0>8}-0000-1000-8000-00805f9b34fb")
1220 } else {
1221 t
1222 }
1223}
1224
1225#[derive(Clone, Debug, Default, PartialEq, Eq)]
1227pub struct PushMessage {
1228 pub id: String,
1230 pub title: String,
1232 pub body: String,
1233 pub data: String,
1235}
1236
1237#[derive(Clone, Debug, PartialEq, Eq)]
1239pub enum PushEvent {
1240 Token(String),
1244 Message(PushMessage),
1246 Opened(PushMessage),
1248 Error(String),
1249}
1250
1251#[derive(Clone, Debug, Default, PartialEq, Eq)]
1254pub struct PushConfig {
1255 pub sender_id: String,
1257 pub project_id: String,
1259 pub app_id: String,
1261 pub api_key: String,
1263 pub vapid_key: String,
1265 pub show_in_foreground: bool,
1268}
1269
1270pub trait PushService {
1274 fn available(&self) -> bool;
1277 fn provider(&self) -> &'static str;
1280 fn register(&mut self, config: &PushConfig);
1283 fn unregister(&mut self) {}
1285 fn shows_notifications(&self) -> bool {
1289 true
1290 }
1291 fn poll(&mut self) -> Vec<PushEvent> {
1293 Vec::new()
1294 }
1295}
1296
1297#[derive(Clone, Debug, Default, PartialEq)]
1300pub struct NowPlaying {
1301 pub title: String,
1302 pub artist: String,
1303 pub album: String,
1304 pub duration: f64,
1306 pub position: f64,
1308 pub playing: bool,
1309 pub cover: Option<Vec<u8>>,
1311 pub can_next: bool,
1313 pub can_previous: bool,
1314}
1315
1316#[derive(Clone, Copy, Debug, PartialEq)]
1318pub enum MediaCommand {
1319 Play,
1320 Pause,
1321 Toggle,
1323 Stop,
1324 Next,
1325 Previous,
1326 Seek(f64),
1328}
1329
1330impl MediaCommand {
1331 pub fn name(self) -> &'static str {
1333 match self {
1334 MediaCommand::Play => "play",
1335 MediaCommand::Pause => "pause",
1336 MediaCommand::Toggle => "toggle",
1337 MediaCommand::Stop => "stop",
1338 MediaCommand::Next => "next",
1339 MediaCommand::Previous => "previous",
1340 MediaCommand::Seek(_) => "seek",
1341 }
1342 }
1343}
1344
1345pub type MediaCommandSink = std::sync::Arc<dyn Fn(MediaCommand) + Send + Sync>;
1347
1348pub trait MediaSessionService {
1351 fn start(&mut self, owner: Option<crate::ComponentId>, commands: MediaCommandSink) -> Result<(), String>;
1354 fn update(&mut self, now: &NowPlaying);
1356 fn stop(&mut self);
1358}
1359
1360static PUSH_EVENTS: std::sync::Mutex<Vec<PushEvent>> = std::sync::Mutex::new(Vec::new());
1361
1362pub fn push_event(event: PushEvent) {
1365 if let Ok(mut list) = PUSH_EVENTS.lock() {
1366 list.push(event);
1367 }
1368}
1369
1370pub fn take_push_events() -> Vec<PushEvent> {
1372 PUSH_EVENTS.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
1373}
1374
1375pub fn parse_push_line(line: &str) -> Option<PushEvent> {
1379 let mut f = line.split('\t');
1380 let kind = f.next()?;
1381 let mut next = || f.next().unwrap_or_default().to_string();
1382 match kind {
1383 "token" => Some(PushEvent::Token(next())),
1384 "error" => Some(PushEvent::Error(next())),
1385 "message" | "opened" => {
1386 let mut m = PushMessage { id: next(), title: next(), body: next(), data: next() };
1387 if m.data.trim().is_empty() {
1388 m.data = "{}".into();
1389 }
1390 Some(if kind == "message" { PushEvent::Message(m) } else { PushEvent::Opened(m) })
1391 }
1392 _ => None,
1393 }
1394}
1395
1396pub fn json_field(json: &str, key: &str) -> Option<String> {
1399 let chars: Vec<char> = json.chars().collect();
1400 let mut i = 0;
1401 let skip_ws = |i: &mut usize| {
1402 while *i < chars.len() && chars[*i].is_whitespace() {
1403 *i += 1;
1404 }
1405 };
1406 let read_string = |i: &mut usize| -> Option<String> {
1408 if chars.get(*i) != Some(&'"') {
1409 return None;
1410 }
1411 *i += 1;
1412 let mut out = String::new();
1413 while *i < chars.len() {
1414 let c = chars[*i];
1415 *i += 1;
1416 match c {
1417 '"' => return Some(out),
1418 '\\' => {
1419 let e = *chars.get(*i)?;
1420 *i += 1;
1421 match e {
1422 'n' => out.push('\n'),
1423 't' => out.push('\t'),
1424 'r' => out.push('\r'),
1425 'b' => out.push('\u{8}'),
1426 'f' => out.push('\u{c}'),
1427 'u' => {
1428 let hex: String = chars.get(*i..*i + 4)?.iter().collect();
1429 *i += 4;
1430 let mut code = u32::from_str_radix(&hex, 16).ok()?;
1431 if (0xD800..0xDC00).contains(&code) && chars.get(*i) == Some(&'\\') && chars.get(*i + 1) == Some(&'u') {
1433 let low: String = chars.get(*i + 2..*i + 6)?.iter().collect();
1434 if let Ok(low) = u32::from_str_radix(&low, 16) {
1435 *i += 6;
1436 code = 0x10000 + ((code - 0xD800) << 10) + (low.wrapping_sub(0xDC00) & 0x3FF);
1437 }
1438 }
1439 out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
1440 }
1441 other => out.push(other),
1442 }
1443 }
1444 c => out.push(c),
1445 }
1446 }
1447 None
1448 };
1449 skip_ws(&mut i);
1450 if chars.get(i) != Some(&'{') {
1451 return None;
1452 }
1453 i += 1;
1454 loop {
1455 skip_ws(&mut i);
1456 if chars.get(i) == Some(&'}') || i >= chars.len() {
1457 return None;
1458 }
1459 let name = read_string(&mut i)?;
1460 skip_ws(&mut i);
1461 if chars.get(i) != Some(&':') {
1462 return None;
1463 }
1464 i += 1;
1465 skip_ws(&mut i);
1466 let value = if chars.get(i) == Some(&'"') {
1467 read_string(&mut i)?
1468 } else {
1469 let start = i;
1471 let (mut depth, mut quoted) = (0i32, false);
1472 while i < chars.len() {
1473 let c = chars[i];
1474 if quoted {
1475 if c == '\\' {
1476 i += 1;
1477 } else if c == '"' {
1478 quoted = false;
1479 }
1480 } else {
1481 match c {
1482 '"' => quoted = true,
1483 '{' | '[' => depth += 1,
1484 '}' | ']' if depth == 0 => break,
1485 '}' | ']' => depth -= 1,
1486 ',' if depth == 0 => break,
1487 _ => {}
1488 }
1489 }
1490 i += 1;
1491 }
1492 chars[start..i.min(chars.len())].iter().collect::<String>().trim().to_string()
1493 };
1494 if name == key {
1495 return Some(value);
1496 }
1497 skip_ws(&mut i);
1498 if chars.get(i) == Some(&',') {
1499 i += 1;
1500 }
1501 }
1502}
1503
1504pub fn push_message_from_payload(text: &str) -> PushMessage {
1508 let text = text.trim();
1509 if !text.starts_with('{') {
1510 return PushMessage { body: text.to_string(), data: "{}".into(), ..Default::default() };
1511 }
1512 let notification = json_field(text, "notification").unwrap_or_default();
1513 let pick = |key: &str| json_field(text, key).or_else(|| json_field(¬ification, key)).unwrap_or_default();
1514 let data = json_field(text, "data").filter(|d| d.trim_start().starts_with('{')).unwrap_or_else(|| "{}".into());
1515 PushMessage { id: pick("id"), title: pick("title"), body: pick("body"), data }
1516}
1517
1518pub fn render_template(template: &str, data: &str) -> String {
1521 let mut out = String::new();
1522 let mut rest = template;
1523 while let Some(i) = rest.find(['{', '}']) {
1524 out.push_str(&rest[..i]);
1525 let tail = &rest[i..];
1526 if tail.starts_with("{{") || tail.starts_with("}}") {
1527 out.push_str(&tail[..1]);
1528 rest = &tail[2..];
1529 } else if let (true, Some(end)) = (tail.starts_with('{'), tail.find('}')) {
1530 out.push_str(&json_field(data, tail[1..end].trim()).unwrap_or_default());
1531 rest = &tail[end + 1..];
1532 } else {
1533 out.push_str(&tail[..1]);
1534 rest = &tail[1..];
1535 }
1536 }
1537 out.push_str(rest);
1538 out
1539}
1540
1541pub fn data_matches(filter: &str, data: &str) -> bool {
1544 filter.split(';').map(str::trim).filter(|c| !c.is_empty()).all(|c| {
1545 if let Some((k, v)) = c.split_once("!=") {
1546 json_field(data, k.trim()).unwrap_or_default() != v.trim()
1547 } else if let Some((k, v)) = c.split_once('=') {
1548 json_field(data, k.trim()).unwrap_or_default() == v.trim()
1549 } else {
1550 json_field(data, c).is_some_and(|v| !v.is_empty())
1551 }
1552 })
1553}
1554
1555pub fn json_quote(text: &str) -> String {
1557 let mut out = String::with_capacity(text.len() + 2);
1558 out.push('"');
1559 for c in text.chars() {
1560 match c {
1561 '"' => out.push_str("\\\""),
1562 '\\' => out.push_str("\\\\"),
1563 '\n' => out.push_str("\\n"),
1564 '\r' => out.push_str("\\r"),
1565 '\t' => out.push_str("\\t"),
1566 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1567 c => out.push(c),
1568 }
1569 }
1570 out.push('"');
1571 out
1572}
1573
1574#[derive(Clone, Debug, PartialEq, Eq)]
1576pub struct ActionEvent {
1577 pub kind: String,
1581 pub component: String,
1583 pub detail: String,
1585 pub data: String,
1587}
1588
1589pub fn parse_action_line(line: &str) -> Option<ActionEvent> {
1591 let mut f = line.split('\t');
1592 let kind = f.next().filter(|k| !k.is_empty())?.to_string();
1593 let component = f.next()?.to_string();
1594 let detail = f.next().unwrap_or_default().to_string();
1595 let data = f.next().filter(|d| !d.trim().is_empty()).unwrap_or("{}").to_string();
1596 Some(ActionEvent { kind, component, detail, data })
1597}
1598
1599pub trait ActionService {
1603 fn execute(&mut self, spec: &str, data: &str) -> Result<(), String>;
1604 fn stop(&mut self, component: &str);
1606 fn set_push_rules(&mut self, rules: &str);
1609 fn poll(&mut self) -> Vec<ActionEvent>;
1611}
1612
1613#[derive(Clone, Debug, PartialEq)]
1615pub enum OleValue {
1616 Null,
1617 Bool(bool),
1618 Int(i64),
1619 Float(f64),
1620 String(String),
1621 Date(f64),
1624 Object(u64),
1627 Array(Vec<Vec<OleValue>>),
1630}
1631
1632pub trait OleService {
1639 fn create(&mut self, prog_id: &str, running: bool) -> Result<u64, String>;
1642 fn invoke(&mut self, object: u64, name: &str, args: Vec<OleValue>) -> Result<OleValue, String>;
1644 fn put(&mut self, object: u64, name: &str, args: Vec<OleValue>, value: OleValue) -> Result<(), String>;
1646 fn release(&mut self, object: u64);
1648 fn set_timeout(&mut self, seconds: f64) {
1650 let _ = seconds;
1651 }
1652 fn releaser(&self) -> Option<OleReleaser> {
1654 None
1655 }
1656}
1657
1658pub type OleReleaser = std::sync::Arc<dyn Fn(u64) + Send + Sync>;
1660
1661static OLE_ALLOWED: std::sync::RwLock<Vec<String>> = std::sync::RwLock::new(Vec::new());
1665
1666pub const OLE_DEFAULT: &[&str] = &["Excel.Application", "Word.Application", "Outlook.Application", "PowerPoint.Application"];
1668
1669pub fn allow_ole(prog_id: &str) {
1671 if let Ok(mut list) = OLE_ALLOWED.write() {
1672 if !list.iter().any(|p| p.eq_ignore_ascii_case(prog_id)) {
1673 list.push(prog_id.to_string());
1674 }
1675 }
1676}
1677
1678pub fn ole_allowed(prog_id: &str) -> bool {
1681 let id = prog_id.trim();
1682 let base = match id.rsplit_once('.') {
1683 Some((head, tail)) if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) => head,
1684 _ => id,
1685 };
1686 let ok = |p: &str| p.eq_ignore_ascii_case(base) || p.eq_ignore_ascii_case(id);
1687 OLE_DEFAULT.iter().any(|p| ok(p)) || OLE_ALLOWED.read().is_ok_and(|l| l.iter().any(|p| ok(p)))
1688}
1689
1690pub fn ole_date(year: i32, month: u32, day: u32, hour: u32, minute: u32, second: u32) -> f64 {
1692 let y = i64::from(year) - i64::from(month <= 2);
1694 let era = y.div_euclid(400);
1695 let yoe = y - era * 400;
1696 let m = i64::from(month);
1697 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(day) - 1;
1698 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
1699 let days = era * 146_097 + doe - 719_468 + 25_569;
1700 days as f64 + f64::from(hour * 3600 + minute * 60 + second) / 86_400.0
1701}
1702
1703pub fn ole_date_parts(date: f64) -> (i32, u32, u32, u32, u32, u32) {
1705 let mut days = date.floor() as i64;
1706 let mut secs = ((date - date.floor()) * 86_400.0).round() as i64;
1707 if secs >= 86_400 {
1708 days += 1;
1709 secs -= 86_400;
1710 }
1711 let z = days - 25_569 + 719_468;
1712 let era = z.div_euclid(146_097);
1713 let doe = z - era * 146_097;
1714 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1715 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1716 let mp = (5 * doy + 2) / 153;
1717 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
1718 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1719 let year = (yoe + era * 400 + i64::from(month <= 2)) as i32;
1720 (year, month, day, (secs / 3600) as u32, (secs % 3600 / 60) as u32, (secs % 60) as u32)
1721}
1722
1723#[derive(Clone, Debug, PartialEq)]
1725pub enum WmiValue {
1726 Null,
1727 Bool(bool),
1728 Int(i64),
1729 Float(f64),
1730 String(String),
1731 DateTime(String),
1733 Array(Vec<WmiValue>),
1735 Object(Vec<(String, WmiValue)>),
1737}
1738
1739#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1741pub enum WmiType {
1742 #[default]
1743 String,
1744 Integer,
1745 Float,
1746 Boolean,
1747 DateTime,
1748 Array,
1749 Object,
1750}
1751
1752#[derive(Clone, Debug, Default, PartialEq, Eq)]
1754pub struct WmiColumn {
1755 pub name: String,
1756 pub kind: WmiType,
1757}
1758
1759#[derive(Clone, Debug, Default, PartialEq)]
1762pub struct WmiTable {
1763 pub columns: Vec<WmiColumn>,
1764 pub rows: Vec<Vec<WmiValue>>,
1765}
1766
1767pub type WmiDone = Box<dyn FnOnce(Result<WmiTable, String>) + Send>;
1770
1771pub type WmiListener = std::sync::Arc<dyn Fn(Result<Vec<(String, WmiValue)>, String>) + Send + Sync>;
1774
1775pub struct WmiWatch(Option<Box<dyn FnOnce() + Send>>);
1777
1778impl WmiWatch {
1779 pub fn new(stop: impl FnOnce() + Send + 'static) -> Self {
1781 Self(Some(Box::new(stop)))
1782 }
1783}
1784
1785impl Drop for WmiWatch {
1786 fn drop(&mut self) {
1787 if let Some(stop) = self.0.take() {
1788 stop();
1789 }
1790 }
1791}
1792
1793pub trait WmiService {
1798 fn query(&mut self, namespace: &str, wql: &str, done: WmiDone);
1800 fn watch(&mut self, namespace: &str, wql: &str, listener: WmiListener) -> Result<WmiWatch, String>;
1804}
1805
1806pub fn wmi_namespace(namespace: &str) -> Result<String, String> {
1810 let ns = namespace.trim().replace('/', "\\");
1811 let ns = if ns.is_empty() { "root\\cimv2".to_string() } else { ns };
1812 let valid = ns.split('\\').all(|p| !p.is_empty() && p.chars().all(|c| c.is_alphanumeric() || c == '_'));
1813 if !valid || !ns.split('\\').next().is_some_and(|r| r.eq_ignore_ascii_case("root")) {
1814 return Err(crate::messages::tf("namespace do WMI inválido '{0}' (só desta máquina, como root\\cimv2)", &[&namespace]));
1815 }
1816 Ok(ns)
1817}
1818
1819pub fn wmi_datetime(text: &str) -> Option<String> {
1823 let t = text.trim();
1824 let b = t.as_bytes();
1825 if b.len() < 14 || !b[..14].iter().all(u8::is_ascii_digit) || b.get(21) == Some(&b':') {
1826 return None;
1827 }
1828 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]);
1829 let month: u32 = mo.parse().ok()?;
1830 let day: u32 = d.parse().ok()?;
1831 if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
1832 return None;
1833 }
1834 Some(format!("{y}-{mo}-{d}T{h}:{mi}:{s}"))
1835}
1836
1837pub fn wmi_select_list(wql: &str) -> Vec<String> {
1840 let t = wql.trim();
1841 let lower = t.to_ascii_lowercase();
1842 let (Some(rest), Some(from)) = (lower.strip_prefix("select"), lower.find(" from ")) else { return Vec::new() };
1843 let start = t.len() - rest.len();
1844 if from < start {
1845 return Vec::new();
1846 }
1847 t[start..from].split(',').map(str::trim).filter(|n| !n.is_empty() && *n != "*").map(str::to_string).collect()
1848}
1849
1850
1851static LOCAL_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1855
1856pub fn set_local_offset_fn(f: fn(i64) -> i64) {
1857 if let Ok(mut slot) = LOCAL_OFFSET.write() {
1858 *slot = Some(f);
1859 }
1860}
1861
1862static PROJECT_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1865
1866pub fn set_project_offset_fn(f: Option<fn(i64) -> i64>) {
1868 if let Ok(mut slot) = PROJECT_OFFSET.write() {
1869 *slot = f;
1870 }
1871}
1872
1873pub fn local_offset(utc: i64) -> i64 {
1876 let project = PROJECT_OFFSET.read().ok().and_then(|f| *f);
1877 project.or_else(|| LOCAL_OFFSET.read().ok().and_then(|f| *f)).map_or(0, |f| f(utc))
1878}