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 fn denied_by_policy(&self, _permission: Permission) -> Option<bool> {
451 None
452 }
453 fn open_settings(&mut self, _permission: Permission) -> Result<(), String> {
455 Err(crate::messages::t("As configurações de permissão não existem neste sistema."))
456 }
457}
458
459#[derive(Clone, Copy, Debug, PartialEq, Eq)]
461pub enum Biometry {
462 None,
464 Fingerprint,
465 Face,
466 Iris,
467 Any,
469}
470
471impl Biometry {
472 pub fn name(self) -> &'static str {
473 match self {
474 Biometry::None => "none",
475 Biometry::Fingerprint => "fingerprint",
476 Biometry::Face => "face",
477 Biometry::Iris => "iris",
478 Biometry::Any => "any",
479 }
480 }
481}
482
483#[derive(Clone, Debug, PartialEq, Eq)]
485pub enum BiometricResult {
486 Success,
487 Cancelled,
489 Failed(String),
491}
492
493pub trait BiometricService {
496 fn availability(&self) -> Biometry;
497 fn authenticate(&mut self, reason: &str, allow_device_credential: bool, done: Box<dyn FnOnce(BiometricResult) + Send>);
500}
501
502pub trait PrintService {
506 fn print(&mut self, title: &str, pages: crate::pages::PageSet, done: Box<dyn FnOnce(Result<bool, String>) + Send>);
507
508 fn wants_pdf(&self) -> bool {
511 false
512 }
513
514 fn print_pdf(&mut self, title: &str, pdf: Vec<u8>, done: Box<dyn FnOnce(Result<bool, String>) + Send>) {
516 let _ = (title, pdf);
517 done(Err("esta plataforma não imprime PDF".into()));
518 }
519}
520
521pub trait HttpService {
525 fn get(&mut self, url: &str, done: Box<dyn FnOnce(Result<Vec<u8>, String>) + Send>);
526}
527
528#[derive(Clone, Debug, Default, PartialEq)]
530pub struct SystemNotification {
531 pub app_id: String,
533 pub app_name: String,
535 pub title: String,
536 pub body: String,
537 pub image: String,
539 pub image_png: Vec<u8>,
541 pub big_image: bool,
543 pub id: u32,
545 pub channel: String,
547 pub channel_name: String,
548 pub priority: NotificationPriority,
549 pub actions: Vec<(String, String)>,
551 pub ongoing: bool,
553 pub progress: Option<f32>,
555 pub full_screen: bool,
558 pub component: Option<crate::ComponentId>,
560 pub component_path: String,
563 pub tag: String,
565 pub inputs: Vec<NotificationInput>,
567 pub action_inputs: Vec<(String, String)>,
569 pub background_actions: Vec<String>,
572}
573
574#[derive(Clone, Debug, Default, PartialEq, Eq)]
576pub struct NotificationInput {
577 pub id: String,
578 pub hint: String,
579}
580
581#[derive(Clone, Debug, Default, PartialEq, Eq)]
585pub struct NotificationActivation {
586 pub id: u32,
587 pub tag: String,
588 pub action: String,
589 pub inputs: Vec<(String, String)>,
590 pub component: String,
591 pub component_id: u64,
594 pub background: bool,
596}
597
598impl NotificationActivation {
599 pub fn encode(&self) -> String {
602 let mut out = format!("aylis-notification?id={}", self.id);
603 for (key, value) in [("tag", &self.tag), ("action", &self.action), ("c", &self.component)] {
604 if !value.is_empty() {
605 out.push_str(&format!("&{key}={}", percent_encode(value)));
606 }
607 }
608 if self.component_id != 0 {
609 out.push_str(&format!("&cid={}", self.component_id));
610 }
611 if self.background {
612 out.push_str("&bg=1");
613 }
614 out
615 }
616
617 pub fn decode(text: &str) -> Option<Self> {
619 let query = text.strip_prefix("aylis-notification?")?;
620 let mut a = NotificationActivation::default();
621 for pair in query.split('&') {
622 let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
623 let value = percent_decode(value);
624 match key {
625 "id" => a.id = value.parse().ok()?,
626 "tag" => a.tag = value,
627 "action" => a.action = value,
628 "c" => a.component = value,
629 "cid" => a.component_id = value.parse().unwrap_or(0),
630 "bg" => a.background = value == "1",
631 _ => {}
632 }
633 }
634 Some(a)
635 }
636
637 pub fn event_json(&self) -> String {
639 let inputs: Vec<String> = self.inputs.iter().map(|(id, value)| format!("{{\"id\":{},\"value\":{}}}", json_quote(id), json_quote(value))).collect();
640 format!(
641 "{{\"id\":{},\"tag\":{},\"action\":{},\"component\":{},\"inputs\":[{}]}}",
642 self.id,
643 json_quote(&self.tag),
644 json_quote(&self.action),
645 json_quote(&self.component),
646 inputs.join(",")
647 )
648 }
649}
650
651fn percent_encode(text: &str) -> String {
653 text.bytes().map(|b| if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') { (b as char).to_string() } else { format!("%{b:02X}") }).collect()
654}
655
656fn percent_decode(text: &str) -> String {
657 let bytes = text.as_bytes();
658 let hex = |b: u8| (b as char).to_digit(16);
659 let mut out = Vec::with_capacity(bytes.len());
660 let mut i = 0;
661 while i < bytes.len() {
662 if bytes[i] == b'%' && i + 2 < bytes.len() {
663 if let (Some(h), Some(l)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
664 out.push((h * 16 + l) as u8);
665 i += 3;
666 continue;
667 }
668 }
669 out.push(bytes[i]);
670 i += 1;
671 }
672 String::from_utf8_lossy(&out).into_owned()
673}
674
675pub fn notification_app_id(explicit: &str, app_name: &str) -> String {
678 let explicit = explicit.trim();
679 if !explicit.is_empty() {
680 return explicit.to_string();
681 }
682 if let Some(id) = crate::providers::app_user_model_id() {
683 return id;
684 }
685 format!("aylis.{}", app_name.to_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>())
686}
687
688pub fn toast_activator_clsid(app_id: &str) -> u128 {
692 let fnv = |seed: u64| app_id.trim().to_lowercase().bytes().fold(seed, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));
693 let (high, low) = (fnv(0xcbf2_9ce4_8422_2325), fnv(0x6c62_272e_07bb_0142 ^ 0x4159_4C49_53));
694 let mut value = (u128::from(high) << 64) | u128::from(low);
695 value = (value & !(0xF_u128 << 76)) | (0x5_u128 << 76);
697 value = (value & !(0x3_u128 << 62)) | (0x2_u128 << 62);
698 value
699}
700
701pub fn clsid_text(clsid: u128) -> String {
703 let h = format!("{clsid:032X}");
704 format!("{{{}-{}-{}-{}-{}}}", &h[0..8], &h[8..12], &h[12..16], &h[16..20], &h[20..32])
705}
706
707pub const TOAST_ACTIVATED_ARG: &str = "--aylis-toast-activated";
710
711#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
713pub enum NotificationPriority {
714 Low,
716 #[default]
717 Default,
718 High,
720}
721
722impl crate::PropEnum for NotificationPriority {
723 const NAMES: &'static [&'static str] = &["low", "default", "high"];
724 fn from_index(index: usize) -> Option<Self> {
725 [Self::Low, Self::Default, Self::High].get(index).copied()
726 }
727 fn index(self) -> usize {
728 self as usize
729 }
730}
731
732pub trait NotificationService {
734 fn notify(&mut self, notification: &SystemNotification) -> Result<(), String>;
735 fn cancel(&mut self, id: u32) -> Result<(), String> {
737 let _ = id;
738 Ok(())
739 }
740 fn cancel_all(&mut self) -> Result<(), String> {
742 Ok(())
743 }
744}
745
746impl crate::Ui {
747 pub fn fire_notification(&mut self, a: &NotificationActivation, starting: bool) -> bool {
755 let args = crate::EventArgs::Text(a.event_json());
756 let by_id = (!starting && a.component_id != 0).then(|| crate::ComponentId::from_u64(a.component_id)).filter(|&c| self.contains(c));
759 let component = Some(a.component.as_str()).filter(|p| !p.is_empty()).and_then(|p| self.find_path(p)).or(by_id);
760 if let Some(c) = component {
761 if a.action.is_empty() {
762 self.fire(c, "on_click", &args);
763 } else if !self.fire(c, "on_action", &args) {
764 self.fire(c, "on_button", &crate::EventArgs::Text(a.action.clone()));
765 }
766 }
767 let mut open = !a.background;
768 if component.is_none() || starting {
769 for app in self.components().filter(|&c| self.class_name(c) == Some("ApplicationEvents")).collect::<Vec<_>>() {
770 match self.ask(app, "on_notification", &args) {
771 crate::question::Asked::Answered(answer) => open = !answer.is_refused() && answer.flag("open_window", open),
772 crate::question::Asked::Deferred(_) => {}
774 }
775 }
776 }
777 self.process_events();
778 open
779 }
780}
781
782pub trait LinkService {
785 fn open_url(&mut self, url: &str) -> Result<(), String>;
787 fn open_app(&mut self, app: &str) -> Result<(), String> {
789 Err(format!("abrir outro app não existe aqui ({app})"))
790 }
791 fn share(&mut self, text: &str, files: &[String]) -> Result<(), String> {
793 let _ = (text, files);
794 Err("compartilhar não existe aqui".into())
795 }
796 fn request(&mut self, action: &str, data: &str, done: Box<dyn FnOnce(Result<String, String>) + Send>) {
799 let _ = data;
800 done(Err(format!("pedir a outro app não existe aqui ({action})")));
801 }
802 fn can_register_schemes(&self) -> bool {
805 false
806 }
807 fn register_scheme(&mut self, scheme: &str, description: &str) -> Result<(), String> {
811 let _ = description;
812 Err(format!("registrar o prefixo {scheme}:// em execução não existe aqui (vai na publicação)"))
813 }
814 fn unregister_scheme(&mut self, scheme: &str) -> Result<(), String> {
816 Err(format!("tirar o registro do prefixo {scheme}:// não existe aqui"))
817 }
818 fn scheme_registered(&mut self, scheme: &str) -> bool {
820 let _ = scheme;
821 false
822 }
823 fn scheme_taken(&mut self, scheme: &str) -> bool {
826 let _ = scheme;
827 false
828 }
829 fn receive_links(&mut self, on_link: Box<dyn Fn(String) + Send>) {
832 let _ = on_link;
833 }
834}
835
836const RESERVED_SCHEMES: &[&str] = &[
838 "http", "https", "file", "ftp", "ftps", "mailto", "tel", "sms", "data", "javascript", "vbscript", "about", "blob", "ws", "wss", "shell", "search",
839 "search-ms", "res", "its", "mk", "hcp", "callto", "news", "nntp", "telnet", "ldap", "ssh", "sftp", "smb", "git", "magnet", "steam", "zoommtg",
840];
841
842pub fn check_scheme(scheme: &str) -> Result<String, String> {
846 let s = scheme.trim().trim_end_matches("://").trim_end_matches(':').to_ascii_lowercase();
847 let valid = s.len() >= 3
848 && s.len() <= 64
849 && s.starts_with(|c: char| c.is_ascii_lowercase())
850 && s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '+' | '-' | '.'));
851 if !valid {
852 return Err(crate::messages::tf("prefixo inválido: {0} (letras, números, + - ., de 3 a 64)", &[&scheme]));
853 }
854 if RESERVED_SCHEMES.contains(&s.as_str()) || s.starts_with("ms-") || s.starts_with("microsoft") || s.starts_with("windows") {
855 return Err(crate::messages::tf("o prefixo {0} é do sistema", &[&s]));
856 }
857 Ok(s)
858}
859
860static STARTUP_LINKS: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
863
864pub fn push_startup_link(url: String) {
866 if let Ok(mut list) = STARTUP_LINKS.lock() {
867 list.push(url);
868 }
869}
870
871pub fn take_startup_links(scheme: &str) -> Vec<String> {
873 let Ok(mut list) = STARTUP_LINKS.lock() else { return Vec::new() };
874 let (mine, rest): (Vec<String>, Vec<String>) = std::mem::take(&mut *list).into_iter().partition(|url| link_scheme(url).as_deref() == Some(scheme));
875 *list = rest;
876 mine
877}
878
879pub fn link_scheme(url: &str) -> Option<String> {
881 let (scheme, _) = url.split_once(':')?;
882 (!scheme.is_empty()).then(|| scheme.to_ascii_lowercase())
883}
884
885#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
887pub enum Sensor {
888 Location,
890 Battery,
892 Network,
894 Motion,
896 Compass,
898 Proximity,
900 Light,
902}
903
904pub trait SensorService {
907 fn available(&self, sensor: Sensor) -> bool;
909 fn set_active(&mut self, sensor: Sensor, on: bool);
911 fn read(&mut self, sensor: Sensor) -> Option<Vec<f64>>;
913 fn vibrate(&mut self, ms: u32) -> bool {
915 let _ = ms;
916 false
917 }
918}
919
920pub const GAMEPAD_BUTTONS: [&str; 17] =
924 ["a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "l3", "r3", "up", "down", "left", "right", "guide"];
925
926#[derive(Clone, Debug, Default, PartialEq)]
928pub struct GamepadState {
929 pub name: String,
930 pub buttons: u32,
932 pub axes: [f32; 6],
935}
936
937impl GamepadState {
938 pub fn set_button(&mut self, name: &str, down: bool) {
940 if let Some(i) = GAMEPAD_BUTTONS.iter().position(|b| *b == name) {
941 if down {
942 self.buttons |= 1 << i;
943 } else {
944 self.buttons &= !(1 << i);
945 }
946 }
947 }
948
949 pub fn pressed(&self, name: &str) -> bool {
950 GAMEPAD_BUTTONS.iter().position(|b| *b == name).is_some_and(|i| self.buttons & (1 << i) != 0)
951 }
952}
953
954pub trait GamepadService {
956 fn pads(&mut self) -> Vec<GamepadState>;
958 fn rumble(&mut self, index: usize, strength: f32, ms: u32) -> bool {
960 let _ = (index, strength, ms);
961 false
962 }
963}
964
965pub trait PhoneService {
967 fn dial(&mut self, number: &str) -> Result<(), String>;
969 fn call(&mut self, number: &str) -> Result<(), String>;
971 fn watch(&mut self, on: bool);
973 fn state(&mut self) -> (String, String);
976 fn request_dialer(&mut self) -> Result<(), String> {
978 Err("não existe aqui".into())
979 }
980 fn answer(&mut self) -> bool {
982 false
983 }
984 fn reject(&mut self) -> bool {
985 false
986 }
987 fn hang_up(&mut self) -> bool {
988 false
989 }
990 fn history(&mut self, max: u32) -> Result<String, String> {
992 let _ = max;
993 Err("não existe aqui".into())
994 }
995 fn lock_screen(&mut self, show_when_locked: bool, turn_screen_on: bool);
997 fn dismiss_keyguard(&mut self);
999}
1000
1001pub trait BackgroundHost {
1006 fn start(&mut self, title: &str, text: &str, kind: &str, keep_alive: bool) -> Result<(), String>;
1007 fn stop(&mut self);
1008}
1009
1010#[derive(Clone, Debug, PartialEq, Eq)]
1013pub enum Incoming {
1014 Link(String),
1015 Shared(String),
1016}
1017
1018static INCOMING: std::sync::Mutex<Vec<Incoming>> = std::sync::Mutex::new(Vec::new());
1019
1020pub fn push_incoming(item: Incoming) {
1023 if let Ok(mut list) = INCOMING.lock() {
1024 list.push(item);
1025 }
1026}
1027
1028pub fn take_incoming() -> Vec<Incoming> {
1030 INCOMING.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
1031}
1032
1033pub trait OffscreenService {
1036 fn render_png(&self, width: u32, height: u32, scale: f32, background: crate::Color, paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>>;
1038
1039 fn render_rgba(&self, _width: u32, _height: u32, _scale: f32, _background: crate::Color, _paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>> {
1044 None
1045 }
1046
1047 fn render_area_rgba(
1052 &self,
1053 _width: u32,
1054 _height: u32,
1055 _background: crate::Color,
1056 _over: Option<(&[u8], crate::geometry::RectF)>,
1057 _paint: &mut dyn FnMut(&mut dyn crate::Canvas),
1058 ) -> Option<Vec<u8>> {
1059 None
1060 }
1061}
1062
1063pub trait WindowCaptureService {
1066 fn capture(&mut self, form: crate::ComponentId) -> Option<(u32, u32, Vec<u8>)>;
1068}
1069
1070pub trait DesktopService {
1075 fn cursor_position(&self) -> Option<(i32, i32)> {
1077 None
1078 }
1079 fn form_at(&self, _x: i32, _y: i32) -> Option<crate::ComponentId> {
1082 None
1083 }
1084 fn transparency(&self) -> Option<bool> {
1086 None
1087 }
1088 fn capture_monitor(&mut self, _area: (i32, i32, u32, u32), _max_width: u32, done: Box<dyn FnOnce(Result<crate::Image, String>) + Send>) {
1092 done(Err(crate::messages::t("A captura da tela não existe neste sistema.")));
1093 }
1094 fn session_state(&self) -> Option<(bool, bool)> {
1097 None
1098 }
1099 fn start_with_login(&self) -> bool {
1101 false
1102 }
1103 fn set_start_with_login(&mut self, _on: bool) -> Result<(), String> {
1105 Err(crate::messages::t("Iniciar com o sistema não existe nesta plataforma."))
1106 }
1107 fn set_start_with_login_args(&mut self, on: bool, args: &[String]) -> Result<(), String> {
1110 if args.is_empty() { self.set_start_with_login(on) } else { Err(crate::messages::t("Iniciar com o sistema não existe nesta plataforma.")) }
1111 }
1112 fn release_single_instance(&mut self) {}
1114 fn lock_keys(&self) -> Option<crate::LockKeys> {
1117 None
1118 }
1119 fn idle_seconds(&self) -> Option<f64> {
1122 None
1123 }
1124 fn do_not_disturb(&self) -> Option<bool> {
1126 None
1127 }
1128 fn drag_files(&mut self, _form: crate::ComponentId, _paths: &[String]) -> Result<bool, String> {
1132 Err(crate::messages::t("Arrastar arquivos para fora não existe neste sistema."))
1133 }
1134}
1135
1136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1138pub enum SingleInstance {
1139 #[default]
1141 Off,
1142 User,
1144 Machine,
1147}
1148
1149impl crate::prop::PropEnum for SingleInstance {
1150 const NAMES: &'static [&'static str] = &["off", "user", "machine"];
1151 fn from_index(i: usize) -> Option<Self> {
1152 [SingleInstance::Off, SingleInstance::User, SingleInstance::Machine].get(i).copied()
1153 }
1154 fn index(self) -> usize {
1155 self as usize
1156 }
1157}
1158
1159impl SingleInstance {
1160 pub fn parse(text: &str) -> Self {
1162 <Self as crate::prop::PropEnum>::from_name(text.trim()).unwrap_or_default()
1163 }
1164}
1165
1166#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1169pub enum SecondInstance {
1170 #[default]
1172 Forward,
1173 Quiet,
1175}
1176
1177impl crate::prop::PropEnum for SecondInstance {
1178 const NAMES: &'static [&'static str] = &["forward", "quiet"];
1179 fn from_index(i: usize) -> Option<Self> {
1180 [SecondInstance::Forward, SecondInstance::Quiet].get(i).copied()
1181 }
1182 fn index(self) -> usize {
1183 self as usize
1184 }
1185}
1186
1187impl SecondInstance {
1188 pub fn parse(text: &str) -> Self {
1190 <Self as crate::prop::PropEnum>::from_name(text.trim()).unwrap_or_default()
1191 }
1192}
1193
1194impl crate::Ui {
1195 pub fn fire_second_instance(&mut self, args: Vec<String>) {
1203 self.extension::<SecondInstanceArgs>().0 = args.clone();
1204 let list = crate::EventArgs::List(args);
1205 let mut show = true;
1206 for app in self.components().filter(|&c| self.class_name(c) == Some("ApplicationEvents")).collect::<Vec<_>>() {
1207 if let crate::question::Asked::Answered(answer) = self.ask(app, "on_second_instance", &list) {
1208 show &= !answer.is_refused();
1209 }
1210 }
1211 if show {
1212 if let Some(form) = self.active_form().or_else(|| self.main_form()).filter(|f| self.is_open(*f)) {
1213 self.window_command(form, crate::WindowCommand::Show);
1214 }
1215 }
1216 self.process_events();
1217 }
1218
1219 pub fn send_to_first_instance(&mut self, args: Vec<String>) {
1222 send_to_first_instance(args);
1223 }
1224}
1225
1226static FIRST_INSTANCE_ARGS: std::sync::Mutex<Option<Vec<String>>> = std::sync::Mutex::new(None);
1228
1229pub fn send_to_first_instance(args: Vec<String>) {
1234 if let Ok(mut a) = FIRST_INSTANCE_ARGS.lock() {
1235 *a = Some(args);
1236 }
1237}
1238
1239pub fn first_instance_args() -> Option<Vec<String>> {
1241 FIRST_INSTANCE_ARGS.lock().ok().and_then(|a| a.clone())
1242}
1243
1244#[derive(Default)]
1246struct SecondInstanceArgs(Vec<String>);
1247
1248impl crate::Ui {
1249 pub fn second_instance_args(&self) -> &[String] {
1252 self.extension_ref::<SecondInstanceArgs>().map_or(&[], |a| a.0.as_slice())
1253 }
1254
1255 pub fn release_single_instance(&mut self) {
1260 if let Some(d) = self.services_mut().desktop.as_mut() {
1261 d.release_single_instance();
1262 }
1263 }
1264
1265 pub fn start_with_login(&self) -> bool {
1270 self.services().desktop.as_ref().is_some_and(|d| d.start_with_login())
1271 }
1272
1273 pub fn set_start_with_login(&mut self, on: bool) -> Result<(), String> {
1279 match self.services_mut().desktop.as_mut() {
1280 Some(d) => d.set_start_with_login(on),
1281 None => Err(crate::messages::t("Iniciar com o sistema não existe nesta plataforma.")),
1282 }
1283 }
1284
1285 pub fn set_start_with_login_args(&mut self, on: bool, args: &[String]) -> Result<(), String> {
1290 match self.services_mut().desktop.as_mut() {
1291 Some(d) => d.set_start_with_login_args(on, args),
1292 None => Err(crate::messages::t("Iniciar com o sistema não existe nesta plataforma.")),
1293 }
1294 }
1295}
1296
1297#[derive(Default)]
1299pub struct Services {
1300 pub desktop: Option<Box<dyn DesktopService>>,
1303 pub window_capture: Option<Box<dyn WindowCaptureService>>,
1305 pub offscreen: Option<Box<dyn OffscreenService>>,
1306 pub window: Option<Box<dyn WindowService>>,
1307 pub timer: Option<Box<dyn TimerService>>,
1308 pub clipboard: Option<Box<dyn ClipboardService>>,
1309 pub clipboard_local: crate::clipboard::LocalClipboard,
1311 pub cursor: Option<Box<dyn CursorService>>,
1312 pub screen: Option<Box<dyn ScreenService>>,
1313 pub text_input: Option<Box<dyn TextInputService>>,
1314 pub locale: Option<Box<dyn LocaleService>>,
1315 pub text: Option<Box<dyn TextService>>,
1316 pub resources: Option<Box<dyn ResourceService>>,
1317 pub forms: Option<Box<dyn FormFactory>>,
1318 pub file_dialogs: Option<Box<dyn FileDialogService>>,
1319 pub permissions: Option<Box<dyn PermissionService>>,
1321 pub biometrics: Option<Box<dyn BiometricService>>,
1323 pub http: Option<Box<dyn HttpService>>,
1324 pub notifications: Option<Box<dyn NotificationService>>,
1325 pub links: Option<Box<dyn LinkService>>,
1327 pub sensors: Option<Box<dyn SensorService>>,
1329 pub background: Option<Box<dyn BackgroundHost>>,
1332 pub phone: Option<Box<dyn PhoneService>>,
1334 pub gamepads: Option<Box<dyn GamepadService>>,
1336 pub printer: Option<Box<dyn PrintService>>,
1337 pub pdf: Option<Box<dyn crate::providers::PdfProvider>>,
1340 pub text_assist: Option<Box<dyn crate::textassist::TextAssist>>,
1343 pub nfc: Option<Box<dyn NfcService>>,
1345 pub bluetooth: Option<Box<dyn BluetoothService>>,
1347 pub push: Option<Box<dyn PushService>>,
1349 pub media_session: Option<Box<dyn MediaSessionService>>,
1352 pub actions: Option<Box<dyn ActionService>>,
1356 pub ole: Option<Box<dyn OleService>>,
1358 pub wmi: Option<Box<dyn WmiService>>,
1360}
1361
1362#[derive(Clone, Debug, Default, PartialEq, Eq)]
1364pub struct NfcTag {
1365 pub id: String,
1367 pub tech: String,
1369 pub records: Vec<crate::ndef::NdefRecord>,
1371 pub writable: bool,
1373}
1374
1375#[derive(Clone, Debug, PartialEq, Eq)]
1377pub enum NfcEvent {
1378 Tag(NfcTag),
1379 Written,
1381 Error(String),
1382}
1383
1384pub trait NfcService {
1387 fn available(&self) -> bool;
1389 fn enabled(&self) -> bool {
1391 self.available()
1392 }
1393 fn set_reading(&mut self, on: bool);
1395 fn write(&mut self, message: Vec<u8>);
1398 fn cancel_write(&mut self) {}
1400 fn poll(&mut self) -> Vec<NfcEvent>;
1402}
1403
1404#[derive(Clone, Debug, Default, PartialEq, Eq)]
1406pub struct BleDevice {
1407 pub id: String,
1410 pub name: String,
1411 pub rssi: i32,
1413}
1414
1415#[derive(Clone, Debug, Default, PartialEq, Eq)]
1417pub struct BleCharacteristic {
1418 pub service: String,
1419 pub characteristic: String,
1420 pub properties: Vec<String>,
1422}
1423
1424#[derive(Clone, Debug, PartialEq, Eq)]
1426pub enum BluetoothEvent {
1427 Found(BleDevice),
1428 ScanStopped,
1430 Connected { device: String, services: Vec<BleCharacteristic> },
1432 Disconnected(String),
1433 Value { device: String, characteristic: String, data: Vec<u8> },
1435 Written { device: String, characteristic: String },
1436 Received { device: String, data: Vec<u8> },
1438 Error(String),
1439}
1440
1441pub trait BluetoothService {
1445 fn available(&self) -> bool;
1446 fn enabled(&self) -> bool {
1448 self.available()
1449 }
1450 fn scan(&mut self, on: bool, services: Vec<String>, name: String);
1453 fn connect(&mut self, device: &str);
1454 fn disconnect(&mut self, device: &str);
1455 fn read(&mut self, device: &str, service: &str, characteristic: &str);
1456 fn write(&mut self, device: &str, service: &str, characteristic: &str, data: Vec<u8>, with_response: bool);
1457 fn subscribe(&mut self, device: &str, service: &str, characteristic: &str, on: bool);
1459 fn paired(&mut self) -> Vec<(String, String)> {
1461 Vec::new()
1462 }
1463 fn open_serial(&mut self, device: &str) -> Result<(), String> {
1465 let _ = device;
1466 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
1467 }
1468 fn send_serial(&mut self, device: &str, data: Vec<u8>) -> Result<(), String> {
1469 let _ = (device, data);
1470 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
1471 }
1472 fn close_serial(&mut self, device: &str) {
1473 let _ = device;
1474 }
1475 fn poll(&mut self) -> Vec<BluetoothEvent>;
1477}
1478
1479pub fn ble_uuid(text: &str) -> String {
1482 let t = text.trim().trim_start_matches("0x").trim_start_matches("0X").to_ascii_lowercase();
1483 if (t.len() == 4 || t.len() == 8) && t.chars().all(|c| c.is_ascii_hexdigit()) {
1484 format!("{t:0>8}-0000-1000-8000-00805f9b34fb")
1485 } else {
1486 t
1487 }
1488}
1489
1490#[derive(Clone, Debug, Default, PartialEq, Eq)]
1492pub struct PushMessage {
1493 pub id: String,
1495 pub title: String,
1497 pub body: String,
1498 pub data: String,
1500}
1501
1502#[derive(Clone, Debug, PartialEq, Eq)]
1504pub enum PushEvent {
1505 Token(String),
1509 Message(PushMessage),
1511 Opened(PushMessage),
1513 Error(String),
1514}
1515
1516#[derive(Clone, Debug, Default, PartialEq, Eq)]
1519pub struct PushConfig {
1520 pub sender_id: String,
1522 pub project_id: String,
1524 pub app_id: String,
1526 pub api_key: String,
1528 pub vapid_key: String,
1530 pub show_in_foreground: bool,
1533}
1534
1535pub trait PushService {
1539 fn available(&self) -> bool;
1542 fn provider(&self) -> &'static str;
1545 fn register(&mut self, config: &PushConfig);
1548 fn unregister(&mut self) {}
1550 fn shows_notifications(&self) -> bool {
1554 true
1555 }
1556 fn poll(&mut self) -> Vec<PushEvent> {
1558 Vec::new()
1559 }
1560}
1561
1562#[derive(Clone, Debug, Default, PartialEq)]
1565pub struct NowPlaying {
1566 pub title: String,
1567 pub artist: String,
1568 pub album: String,
1569 pub duration: f64,
1571 pub position: f64,
1573 pub playing: bool,
1574 pub cover: Option<Vec<u8>>,
1576 pub can_next: bool,
1578 pub can_previous: bool,
1579}
1580
1581#[derive(Clone, Copy, Debug, PartialEq)]
1583pub enum MediaCommand {
1584 Play,
1585 Pause,
1586 Toggle,
1588 Stop,
1589 Next,
1590 Previous,
1591 Seek(f64),
1593}
1594
1595impl MediaCommand {
1596 pub fn name(self) -> &'static str {
1598 match self {
1599 MediaCommand::Play => "play",
1600 MediaCommand::Pause => "pause",
1601 MediaCommand::Toggle => "toggle",
1602 MediaCommand::Stop => "stop",
1603 MediaCommand::Next => "next",
1604 MediaCommand::Previous => "previous",
1605 MediaCommand::Seek(_) => "seek",
1606 }
1607 }
1608}
1609
1610pub type MediaCommandSink = std::sync::Arc<dyn Fn(MediaCommand) + Send + Sync>;
1612
1613pub trait MediaSessionService {
1616 fn start(&mut self, owner: Option<crate::ComponentId>, commands: MediaCommandSink) -> Result<(), String>;
1619 fn update(&mut self, now: &NowPlaying);
1621 fn stop(&mut self);
1623}
1624
1625static PUSH_EVENTS: std::sync::Mutex<Vec<PushEvent>> = std::sync::Mutex::new(Vec::new());
1626
1627pub fn push_event(event: PushEvent) {
1630 if let Ok(mut list) = PUSH_EVENTS.lock() {
1631 list.push(event);
1632 }
1633}
1634
1635pub fn take_push_events() -> Vec<PushEvent> {
1637 PUSH_EVENTS.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
1638}
1639
1640pub fn parse_push_line(line: &str) -> Option<PushEvent> {
1644 let mut f = line.split('\t');
1645 let kind = f.next()?;
1646 let mut next = || f.next().unwrap_or_default().to_string();
1647 match kind {
1648 "token" => Some(PushEvent::Token(next())),
1649 "error" => Some(PushEvent::Error(next())),
1650 "message" | "opened" => {
1651 let mut m = PushMessage { id: next(), title: next(), body: next(), data: next() };
1652 if m.data.trim().is_empty() {
1653 m.data = "{}".into();
1654 }
1655 Some(if kind == "message" { PushEvent::Message(m) } else { PushEvent::Opened(m) })
1656 }
1657 _ => None,
1658 }
1659}
1660
1661pub fn json_field(json: &str, key: &str) -> Option<String> {
1664 let chars: Vec<char> = json.chars().collect();
1665 let mut i = 0;
1666 let skip_ws = |i: &mut usize| {
1667 while *i < chars.len() && chars[*i].is_whitespace() {
1668 *i += 1;
1669 }
1670 };
1671 let read_string = |i: &mut usize| -> Option<String> {
1673 if chars.get(*i) != Some(&'"') {
1674 return None;
1675 }
1676 *i += 1;
1677 let mut out = String::new();
1678 while *i < chars.len() {
1679 let c = chars[*i];
1680 *i += 1;
1681 match c {
1682 '"' => return Some(out),
1683 '\\' => {
1684 let e = *chars.get(*i)?;
1685 *i += 1;
1686 match e {
1687 'n' => out.push('\n'),
1688 't' => out.push('\t'),
1689 'r' => out.push('\r'),
1690 'b' => out.push('\u{8}'),
1691 'f' => out.push('\u{c}'),
1692 'u' => {
1693 let hex: String = chars.get(*i..*i + 4)?.iter().collect();
1694 *i += 4;
1695 let mut code = u32::from_str_radix(&hex, 16).ok()?;
1696 if (0xD800..0xDC00).contains(&code) && chars.get(*i) == Some(&'\\') && chars.get(*i + 1) == Some(&'u') {
1698 let low: String = chars.get(*i + 2..*i + 6)?.iter().collect();
1699 if let Ok(low) = u32::from_str_radix(&low, 16) {
1700 *i += 6;
1701 code = 0x10000 + ((code - 0xD800) << 10) + (low.wrapping_sub(0xDC00) & 0x3FF);
1702 }
1703 }
1704 out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
1705 }
1706 other => out.push(other),
1707 }
1708 }
1709 c => out.push(c),
1710 }
1711 }
1712 None
1713 };
1714 skip_ws(&mut i);
1715 if chars.get(i) != Some(&'{') {
1716 return None;
1717 }
1718 i += 1;
1719 loop {
1720 skip_ws(&mut i);
1721 if chars.get(i) == Some(&'}') || i >= chars.len() {
1722 return None;
1723 }
1724 let name = read_string(&mut i)?;
1725 skip_ws(&mut i);
1726 if chars.get(i) != Some(&':') {
1727 return None;
1728 }
1729 i += 1;
1730 skip_ws(&mut i);
1731 let value = if chars.get(i) == Some(&'"') {
1732 read_string(&mut i)?
1733 } else {
1734 let start = i;
1736 let (mut depth, mut quoted) = (0i32, false);
1737 while i < chars.len() {
1738 let c = chars[i];
1739 if quoted {
1740 if c == '\\' {
1741 i += 1;
1742 } else if c == '"' {
1743 quoted = false;
1744 }
1745 } else {
1746 match c {
1747 '"' => quoted = true,
1748 '{' | '[' => depth += 1,
1749 '}' | ']' if depth == 0 => break,
1750 '}' | ']' => depth -= 1,
1751 ',' if depth == 0 => break,
1752 _ => {}
1753 }
1754 }
1755 i += 1;
1756 }
1757 chars[start..i.min(chars.len())].iter().collect::<String>().trim().to_string()
1758 };
1759 if name == key {
1760 return Some(value);
1761 }
1762 skip_ws(&mut i);
1763 if chars.get(i) == Some(&',') {
1764 i += 1;
1765 }
1766 }
1767}
1768
1769pub fn push_message_from_payload(text: &str) -> PushMessage {
1773 let text = text.trim();
1774 if !text.starts_with('{') {
1775 return PushMessage { body: text.to_string(), data: "{}".into(), ..Default::default() };
1776 }
1777 let notification = json_field(text, "notification").unwrap_or_default();
1778 let pick = |key: &str| json_field(text, key).or_else(|| json_field(¬ification, key)).unwrap_or_default();
1779 let data = json_field(text, "data").filter(|d| d.trim_start().starts_with('{')).unwrap_or_else(|| "{}".into());
1780 PushMessage { id: pick("id"), title: pick("title"), body: pick("body"), data }
1781}
1782
1783pub fn render_template(template: &str, data: &str) -> String {
1786 let mut out = String::new();
1787 let mut rest = template;
1788 while let Some(i) = rest.find(['{', '}']) {
1789 out.push_str(&rest[..i]);
1790 let tail = &rest[i..];
1791 if tail.starts_with("{{") || tail.starts_with("}}") {
1792 out.push_str(&tail[..1]);
1793 rest = &tail[2..];
1794 } else if let (true, Some(end)) = (tail.starts_with('{'), tail.find('}')) {
1795 out.push_str(&json_field(data, tail[1..end].trim()).unwrap_or_default());
1796 rest = &tail[end + 1..];
1797 } else {
1798 out.push_str(&tail[..1]);
1799 rest = &tail[1..];
1800 }
1801 }
1802 out.push_str(rest);
1803 out
1804}
1805
1806pub fn data_matches(filter: &str, data: &str) -> bool {
1809 filter.split(';').map(str::trim).filter(|c| !c.is_empty()).all(|c| {
1810 if let Some((k, v)) = c.split_once("!=") {
1811 json_field(data, k.trim()).unwrap_or_default() != v.trim()
1812 } else if let Some((k, v)) = c.split_once('=') {
1813 json_field(data, k.trim()).unwrap_or_default() == v.trim()
1814 } else {
1815 json_field(data, c).is_some_and(|v| !v.is_empty())
1816 }
1817 })
1818}
1819
1820pub fn json_quote(text: &str) -> String {
1822 let mut out = String::with_capacity(text.len() + 2);
1823 out.push('"');
1824 for c in text.chars() {
1825 match c {
1826 '"' => out.push_str("\\\""),
1827 '\\' => out.push_str("\\\\"),
1828 '\n' => out.push_str("\\n"),
1829 '\r' => out.push_str("\\r"),
1830 '\t' => out.push_str("\\t"),
1831 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1832 c => out.push(c),
1833 }
1834 }
1835 out.push('"');
1836 out
1837}
1838
1839#[derive(Clone, Debug, PartialEq, Eq)]
1841pub struct ActionEvent {
1842 pub kind: String,
1846 pub component: String,
1848 pub detail: String,
1850 pub data: String,
1852}
1853
1854pub fn parse_action_line(line: &str) -> Option<ActionEvent> {
1856 let mut f = line.split('\t');
1857 let kind = f.next().filter(|k| !k.is_empty())?.to_string();
1858 let component = f.next()?.to_string();
1859 let detail = f.next().unwrap_or_default().to_string();
1860 let data = f.next().filter(|d| !d.trim().is_empty()).unwrap_or("{}").to_string();
1861 Some(ActionEvent { kind, component, detail, data })
1862}
1863
1864pub trait ActionService {
1868 fn execute(&mut self, spec: &str, data: &str) -> Result<(), String>;
1869 fn stop(&mut self, component: &str);
1871 fn set_push_rules(&mut self, rules: &str);
1874 fn poll(&mut self) -> Vec<ActionEvent>;
1876}
1877
1878#[derive(Clone, Debug, PartialEq)]
1880pub enum OleValue {
1881 Null,
1882 Bool(bool),
1883 Int(i64),
1884 Float(f64),
1885 String(String),
1886 Date(f64),
1889 Object(u64),
1892 Array(Vec<Vec<OleValue>>),
1895}
1896
1897pub trait OleService {
1904 fn create(&mut self, prog_id: &str, running: bool) -> Result<u64, String>;
1907 fn invoke(&mut self, object: u64, name: &str, args: Vec<OleValue>) -> Result<OleValue, String>;
1909 fn put(&mut self, object: u64, name: &str, args: Vec<OleValue>, value: OleValue) -> Result<(), String>;
1911 fn release(&mut self, object: u64);
1913 fn set_timeout(&mut self, seconds: f64) {
1915 let _ = seconds;
1916 }
1917 fn releaser(&self) -> Option<OleReleaser> {
1919 None
1920 }
1921}
1922
1923pub type OleReleaser = std::sync::Arc<dyn Fn(u64) + Send + Sync>;
1925
1926static OLE_ALLOWED: std::sync::RwLock<Vec<String>> = std::sync::RwLock::new(Vec::new());
1930
1931pub const OLE_DEFAULT: &[&str] = &["Excel.Application", "Word.Application", "Outlook.Application", "PowerPoint.Application"];
1933
1934pub fn allow_ole(prog_id: &str) {
1936 if let Ok(mut list) = OLE_ALLOWED.write() {
1937 if !list.iter().any(|p| p.eq_ignore_ascii_case(prog_id)) {
1938 list.push(prog_id.to_string());
1939 }
1940 }
1941}
1942
1943pub fn ole_allowed(prog_id: &str) -> bool {
1946 let id = prog_id.trim();
1947 let base = match id.rsplit_once('.') {
1948 Some((head, tail)) if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) => head,
1949 _ => id,
1950 };
1951 let ok = |p: &str| p.eq_ignore_ascii_case(base) || p.eq_ignore_ascii_case(id);
1952 OLE_DEFAULT.iter().any(|p| ok(p)) || OLE_ALLOWED.read().is_ok_and(|l| l.iter().any(|p| ok(p)))
1953}
1954
1955pub fn ole_date(year: i32, month: u32, day: u32, hour: u32, minute: u32, second: u32) -> f64 {
1957 let y = i64::from(year) - i64::from(month <= 2);
1959 let era = y.div_euclid(400);
1960 let yoe = y - era * 400;
1961 let m = i64::from(month);
1962 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(day) - 1;
1963 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
1964 let days = era * 146_097 + doe - 719_468 + 25_569;
1965 days as f64 + f64::from(hour * 3600 + minute * 60 + second) / 86_400.0
1966}
1967
1968pub fn ole_date_parts(date: f64) -> (i32, u32, u32, u32, u32, u32) {
1970 let mut days = date.floor() as i64;
1971 let mut secs = ((date - date.floor()) * 86_400.0).round() as i64;
1972 if secs >= 86_400 {
1973 days += 1;
1974 secs -= 86_400;
1975 }
1976 let z = days - 25_569 + 719_468;
1977 let era = z.div_euclid(146_097);
1978 let doe = z - era * 146_097;
1979 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
1980 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1981 let mp = (5 * doy + 2) / 153;
1982 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
1983 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
1984 let year = (yoe + era * 400 + i64::from(month <= 2)) as i32;
1985 (year, month, day, (secs / 3600) as u32, (secs % 3600 / 60) as u32, (secs % 60) as u32)
1986}
1987
1988#[derive(Clone, Debug, PartialEq)]
1990pub enum WmiValue {
1991 Null,
1992 Bool(bool),
1993 Int(i64),
1994 Float(f64),
1995 String(String),
1996 DateTime(String),
1998 Array(Vec<WmiValue>),
2000 Object(Vec<(String, WmiValue)>),
2002}
2003
2004#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2006pub enum WmiType {
2007 #[default]
2008 String,
2009 Integer,
2010 Float,
2011 Boolean,
2012 DateTime,
2013 Array,
2014 Object,
2015}
2016
2017#[derive(Clone, Debug, Default, PartialEq, Eq)]
2019pub struct WmiColumn {
2020 pub name: String,
2021 pub kind: WmiType,
2022}
2023
2024#[derive(Clone, Debug, Default, PartialEq)]
2027pub struct WmiTable {
2028 pub columns: Vec<WmiColumn>,
2029 pub rows: Vec<Vec<WmiValue>>,
2030}
2031
2032pub type WmiDone = Box<dyn FnOnce(Result<WmiTable, String>) + Send>;
2035
2036pub type WmiListener = std::sync::Arc<dyn Fn(Result<Vec<(String, WmiValue)>, String>) + Send + Sync>;
2039
2040pub struct WmiWatch(Option<Box<dyn FnOnce() + Send>>);
2042
2043impl WmiWatch {
2044 pub fn new(stop: impl FnOnce() + Send + 'static) -> Self {
2046 Self(Some(Box::new(stop)))
2047 }
2048}
2049
2050impl Drop for WmiWatch {
2051 fn drop(&mut self) {
2052 if let Some(stop) = self.0.take() {
2053 stop();
2054 }
2055 }
2056}
2057
2058pub trait WmiService {
2063 fn query(&mut self, namespace: &str, wql: &str, done: WmiDone);
2065 fn watch(&mut self, namespace: &str, wql: &str, listener: WmiListener) -> Result<WmiWatch, String>;
2069}
2070
2071pub fn wmi_namespace(namespace: &str) -> Result<String, String> {
2075 let ns = namespace.trim().replace('/', "\\");
2076 let ns = if ns.is_empty() { "root\\cimv2".to_string() } else { ns };
2077 let valid = ns.split('\\').all(|p| !p.is_empty() && p.chars().all(|c| c.is_alphanumeric() || c == '_'));
2078 if !valid || !ns.split('\\').next().is_some_and(|r| r.eq_ignore_ascii_case("root")) {
2079 return Err(crate::messages::tf("namespace do WMI inválido '{0}' (só desta máquina, como root\\cimv2)", &[&namespace]));
2080 }
2081 Ok(ns)
2082}
2083
2084pub fn wmi_datetime(text: &str) -> Option<String> {
2088 let t = text.trim();
2089 let b = t.as_bytes();
2090 if b.len() < 14 || !b[..14].iter().all(u8::is_ascii_digit) || b.get(21) == Some(&b':') {
2091 return None;
2092 }
2093 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]);
2094 let month: u32 = mo.parse().ok()?;
2095 let day: u32 = d.parse().ok()?;
2096 if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
2097 return None;
2098 }
2099 Some(format!("{y}-{mo}-{d}T{h}:{mi}:{s}"))
2100}
2101
2102pub fn wmi_select_list(wql: &str) -> Vec<String> {
2105 let t = wql.trim();
2106 let lower = t.to_ascii_lowercase();
2107 let (Some(rest), Some(from)) = (lower.strip_prefix("select"), lower.find(" from ")) else { return Vec::new() };
2108 let start = t.len() - rest.len();
2109 if from < start {
2110 return Vec::new();
2111 }
2112 t[start..from].split(',').map(str::trim).filter(|n| !n.is_empty() && *n != "*").map(str::to_string).collect()
2113}
2114
2115
2116static LOCAL_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
2120
2121pub fn set_local_offset_fn(f: fn(i64) -> i64) {
2122 if let Ok(mut slot) = LOCAL_OFFSET.write() {
2123 *slot = Some(f);
2124 }
2125}
2126
2127static PROJECT_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
2130
2131pub fn set_project_offset_fn(f: Option<fn(i64) -> i64>) {
2133 if let Ok(mut slot) = PROJECT_OFFSET.write() {
2134 *slot = f;
2135 }
2136}
2137
2138pub fn local_offset(utc: i64) -> i64 {
2141 let project = PROJECT_OFFSET.read().ok().and_then(|f| *f);
2142 project.or_else(|| LOCAL_OFFSET.read().ok().and_then(|f| *f)).map_or(0, |f| f(utc))
2143}