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 {
43 fn get_text(&mut self) -> Option<String>;
44 fn set_text(&mut self, text: &str);
45}
46
47#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub enum CursorShape {
49 #[default]
50 Default,
51 Pointer,
52 Text,
53 Wait,
54 Crosshair,
55 Move,
56 NotAllowed,
57 ResizeHorizontal,
58 ResizeVertical,
59 ResizeNeSw,
60 ResizeNwSe,
61 Grab,
63 Grabbing,
64 None,
66}
67
68impl CursorShape {
69 pub const ALL: [CursorShape; 14] = [
70 CursorShape::Default,
71 CursorShape::Pointer,
72 CursorShape::Text,
73 CursorShape::Wait,
74 CursorShape::Crosshair,
75 CursorShape::Move,
76 CursorShape::NotAllowed,
77 CursorShape::ResizeHorizontal,
78 CursorShape::ResizeVertical,
79 CursorShape::ResizeNeSw,
80 CursorShape::ResizeNwSe,
81 CursorShape::Grab,
82 CursorShape::Grabbing,
83 CursorShape::None,
84 ];
85}
86
87impl crate::prop::PropEnum for CursorShape {
88 const NAMES: &'static [&'static str] = &[
89 "default",
90 "pointer",
91 "text",
92 "wait",
93 "crosshair",
94 "move",
95 "not_allowed",
96 "resize_horizontal",
97 "resize_vertical",
98 "resize_ne_sw",
99 "resize_nw_se",
100 "grab",
101 "grabbing",
102 "none",
103 ];
104
105 fn from_index(index: usize) -> Option<Self> {
106 CursorShape::ALL.get(index).copied()
107 }
108
109 fn index(self) -> usize {
110 self as usize
111 }
112}
113
114pub trait CursorService {
116 fn set_cursor(&mut self, shape: CursorShape);
117}
118
119#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
121pub enum Appearance {
122 #[default]
123 Light,
124 Dark,
125}
126
127pub trait ScreenService {
129 fn screen_size(&self) -> SizeF;
130 fn scale_factor(&self) -> f32;
131 fn appearance(&self) -> Appearance;
133}
134
135#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
137pub enum KeyboardKind {
138 #[default]
139 Text,
140 Number,
141 Decimal,
142 Phone,
143 Email,
144 Url,
145}
146
147pub trait TextInputService {
149 fn show_keyboard(&mut self, kind: KeyboardKind);
150 fn hide_keyboard(&mut self);
151 fn set_ime_rect(&mut self, rect: RectF);
153}
154
155#[derive(Clone, Debug, PartialEq)]
157pub struct LocaleInfo {
158 pub decimal_separator: char,
159 pub thousand_separator: char,
160 pub short_date_format: String,
161 pub long_time_format: String,
162 pub currency_symbol: String,
163 pub month_names: [&'static str; 12],
166 pub short_day_names: [&'static str; 7],
167 pub first_day_of_week: u8,
169}
170
171const MONTHS_EN: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
172const DAYS_EN: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
173
174impl Default for LocaleInfo {
175 fn default() -> Self {
176 Self {
177 decimal_separator: '.',
178 thousand_separator: ',',
179 short_date_format: "yyyy-mm-dd".into(),
180 long_time_format: "hh:nn:ss".into(),
181 currency_symbol: "$".into(),
182 month_names: MONTHS_EN,
183 short_day_names: DAYS_EN,
184 first_day_of_week: 0,
185 }
186 }
187}
188
189impl LocaleInfo {
190 pub fn pt_br() -> Self {
192 Self {
193 decimal_separator: ',',
194 thousand_separator: '.',
195 short_date_format: "dd/mm/yyyy".into(),
196 long_time_format: "hh:nn:ss".into(),
197 currency_symbol: "R$".into(),
198 month_names: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
199 short_day_names: ["dom", "seg", "ter", "qua", "qui", "sex", "sáb"],
200 first_day_of_week: 0,
201 }
202 }
203
204 pub fn es() -> Self {
206 Self {
207 decimal_separator: ',',
208 thousand_separator: '.',
209 short_date_format: "dd/mm/yyyy".into(),
210 long_time_format: "hh:nn:ss".into(),
211 currency_symbol: "€".into(),
212 month_names: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],
213 short_day_names: ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"],
214 first_day_of_week: 1,
215 }
216 }
217
218 pub fn en_us() -> Self {
220 Self {
221 decimal_separator: '.',
222 thousand_separator: ',',
223 short_date_format: "mm/dd/yyyy".into(),
224 long_time_format: "hh:nn:ss".into(),
225 currency_symbol: "$".into(),
226 month_names: MONTHS_EN,
227 short_day_names: DAYS_EN,
228 first_day_of_week: 0,
229 }
230 }
231}
232
233pub trait LocaleService {
234 fn locale(&self) -> LocaleInfo;
235}
236
237impl LocaleService for LocaleInfo {
239 fn locale(&self) -> LocaleInfo {
240 self.clone()
241 }
242}
243
244#[derive(Clone, Copy, Debug, PartialEq, Eq)]
246pub enum LifecycleEvent {
247 Resumed,
248 Suspended,
249 LowMemory,
250 SurfaceLost,
252}
253
254pub trait ResourceService {
258 fn read(&self, path: &str) -> Option<Vec<u8>>;
259}
260
261pub trait FormFactory {
264 fn create_form(&mut self, ui: &mut crate::Ui, name: &str) -> Result<crate::ComponentId, String>;
266 fn form_names(&self) -> Vec<String>;
268}
269
270#[derive(Clone, Debug, Default)]
272pub struct FileDialogOptions {
273 pub title: String,
274 pub filters: Vec<(String, Vec<String>)>,
276 pub directory: String,
277 pub file_name: String,
278 pub save: bool,
280 pub multiple: bool,
282 pub owner: Option<crate::ComponentId>,
284}
285
286pub trait FileDialogService {
289 fn show(&mut self, options: FileDialogOptions, done: Box<dyn FnOnce(Vec<String>) + Send>);
290}
291
292#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
295pub enum Permission {
296 Camera,
297 Microphone,
298 Location,
300 Notifications,
301 Photos,
303 Contacts,
304 Calendar,
305 Bluetooth,
306}
307
308impl Permission {
309 pub const ALL: [Permission; 8] = [
310 Permission::Camera,
311 Permission::Microphone,
312 Permission::Location,
313 Permission::Notifications,
314 Permission::Photos,
315 Permission::Contacts,
316 Permission::Calendar,
317 Permission::Bluetooth,
318 ];
319
320 pub fn name(self) -> &'static str {
322 match self {
323 Permission::Camera => "camera",
324 Permission::Microphone => "microphone",
325 Permission::Location => "location",
326 Permission::Notifications => "notifications",
327 Permission::Photos => "photos",
328 Permission::Contacts => "contacts",
329 Permission::Calendar => "calendar",
330 Permission::Bluetooth => "bluetooth",
331 }
332 }
333
334 pub fn parse(name: &str) -> Option<Permission> {
335 let name = name.trim();
336 Permission::ALL.into_iter().find(|p| p.name().eq_ignore_ascii_case(name))
337 }
338
339 pub fn parse_list(list: &str) -> Vec<Permission> {
341 let mut out = Vec::new();
342 for p in list.split([';', ',']).filter_map(Permission::parse) {
343 if !out.contains(&p) {
344 out.push(p);
345 }
346 }
347 out
348 }
349}
350
351#[derive(Clone, Copy, Debug, PartialEq, Eq)]
353pub enum PermissionState {
354 Granted,
356 Denied,
358 Prompt,
360 Unavailable,
362}
363
364impl PermissionState {
365 pub fn name(self) -> &'static str {
366 match self {
367 PermissionState::Granted => "granted",
368 PermissionState::Denied => "denied",
369 PermissionState::Prompt => "prompt",
370 PermissionState::Unavailable => "unavailable",
371 }
372 }
373}
374
375pub trait PermissionService {
378 fn state(&self, permission: Permission) -> PermissionState;
379 fn request(&mut self, permissions: Vec<Permission>, done: Box<dyn FnOnce(Vec<(Permission, PermissionState)>) + Send>);
380}
381
382#[derive(Clone, Copy, Debug, PartialEq, Eq)]
384pub enum Biometry {
385 None,
387 Fingerprint,
388 Face,
389 Iris,
390 Any,
392}
393
394impl Biometry {
395 pub fn name(self) -> &'static str {
396 match self {
397 Biometry::None => "none",
398 Biometry::Fingerprint => "fingerprint",
399 Biometry::Face => "face",
400 Biometry::Iris => "iris",
401 Biometry::Any => "any",
402 }
403 }
404}
405
406#[derive(Clone, Debug, PartialEq, Eq)]
408pub enum BiometricResult {
409 Success,
410 Cancelled,
412 Failed(String),
414}
415
416pub trait BiometricService {
419 fn availability(&self) -> Biometry;
420 fn authenticate(&mut self, reason: &str, allow_device_credential: bool, done: Box<dyn FnOnce(BiometricResult) + Send>);
423}
424
425pub trait PrintService {
429 fn print(&mut self, title: &str, pages: crate::pages::PageSet, done: Box<dyn FnOnce(Result<bool, String>) + Send>);
430}
431
432pub trait HttpService {
436 fn get(&mut self, url: &str, done: Box<dyn FnOnce(Result<Vec<u8>, String>) + Send>);
437}
438
439#[derive(Clone, Debug, Default, PartialEq)]
441pub struct SystemNotification {
442 pub app_id: String,
444 pub app_name: String,
446 pub title: String,
447 pub body: String,
448 pub image: String,
450 pub image_png: Vec<u8>,
452 pub big_image: bool,
454 pub id: u32,
456 pub channel: String,
458 pub channel_name: String,
459 pub priority: NotificationPriority,
460 pub actions: Vec<(String, String)>,
462 pub ongoing: bool,
464 pub progress: Option<f32>,
466 pub full_screen: bool,
469 pub component: Option<crate::ComponentId>,
471}
472
473#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
475pub enum NotificationPriority {
476 Low,
478 #[default]
479 Default,
480 High,
482}
483
484impl crate::PropEnum for NotificationPriority {
485 const NAMES: &'static [&'static str] = &["low", "default", "high"];
486 fn from_index(index: usize) -> Option<Self> {
487 [Self::Low, Self::Default, Self::High].get(index).copied()
488 }
489 fn index(self) -> usize {
490 self as usize
491 }
492}
493
494pub trait NotificationService {
496 fn notify(&mut self, notification: &SystemNotification) -> Result<(), String>;
497 fn cancel(&mut self, id: u32) -> Result<(), String> {
499 let _ = id;
500 Ok(())
501 }
502}
503
504pub trait LinkService {
507 fn open_url(&mut self, url: &str) -> Result<(), String>;
509 fn open_app(&mut self, app: &str) -> Result<(), String> {
511 Err(format!("abrir outro app não existe aqui ({app})"))
512 }
513 fn share(&mut self, text: &str, files: &[String]) -> Result<(), String> {
515 let _ = (text, files);
516 Err("compartilhar não existe aqui".into())
517 }
518 fn request(&mut self, action: &str, data: &str, done: Box<dyn FnOnce(Result<String, String>) + Send>) {
521 let _ = data;
522 done(Err(format!("pedir a outro app não existe aqui ({action})")));
523 }
524}
525
526#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
528pub enum Sensor {
529 Location,
531 Battery,
533 Network,
535 Motion,
537 Compass,
539 Proximity,
541 Light,
543}
544
545pub trait SensorService {
548 fn available(&self, sensor: Sensor) -> bool;
550 fn set_active(&mut self, sensor: Sensor, on: bool);
552 fn read(&mut self, sensor: Sensor) -> Option<Vec<f64>>;
554 fn vibrate(&mut self, ms: u32) -> bool {
556 let _ = ms;
557 false
558 }
559}
560
561pub const GAMEPAD_BUTTONS: [&str; 17] =
565 ["a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "l3", "r3", "up", "down", "left", "right", "guide"];
566
567#[derive(Clone, Debug, Default, PartialEq)]
569pub struct GamepadState {
570 pub name: String,
571 pub buttons: u32,
573 pub axes: [f32; 6],
576}
577
578impl GamepadState {
579 pub fn set_button(&mut self, name: &str, down: bool) {
581 if let Some(i) = GAMEPAD_BUTTONS.iter().position(|b| *b == name) {
582 if down {
583 self.buttons |= 1 << i;
584 } else {
585 self.buttons &= !(1 << i);
586 }
587 }
588 }
589
590 pub fn pressed(&self, name: &str) -> bool {
591 GAMEPAD_BUTTONS.iter().position(|b| *b == name).is_some_and(|i| self.buttons & (1 << i) != 0)
592 }
593}
594
595pub trait GamepadService {
597 fn pads(&mut self) -> Vec<GamepadState>;
599 fn rumble(&mut self, index: usize, strength: f32, ms: u32) -> bool {
601 let _ = (index, strength, ms);
602 false
603 }
604}
605
606pub trait PhoneService {
608 fn dial(&mut self, number: &str) -> Result<(), String>;
610 fn call(&mut self, number: &str) -> Result<(), String>;
612 fn watch(&mut self, on: bool);
614 fn state(&mut self) -> (String, String);
617 fn request_dialer(&mut self) -> Result<(), String> {
619 Err("não existe aqui".into())
620 }
621 fn answer(&mut self) -> bool {
623 false
624 }
625 fn reject(&mut self) -> bool {
626 false
627 }
628 fn hang_up(&mut self) -> bool {
629 false
630 }
631 fn history(&mut self, max: u32) -> Result<String, String> {
633 let _ = max;
634 Err("não existe aqui".into())
635 }
636 fn lock_screen(&mut self, show_when_locked: bool, turn_screen_on: bool);
638 fn dismiss_keyguard(&mut self);
640}
641
642pub trait BackgroundHost {
647 fn start(&mut self, title: &str, text: &str, kind: &str, keep_alive: bool) -> Result<(), String>;
648 fn stop(&mut self);
649}
650
651#[derive(Clone, Debug, PartialEq, Eq)]
654pub enum Incoming {
655 Link(String),
656 Shared(String),
657}
658
659static INCOMING: std::sync::Mutex<Vec<Incoming>> = std::sync::Mutex::new(Vec::new());
660
661pub fn push_incoming(item: Incoming) {
664 if let Ok(mut list) = INCOMING.lock() {
665 list.push(item);
666 }
667}
668
669pub fn take_incoming() -> Vec<Incoming> {
671 INCOMING.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
672}
673
674pub trait OffscreenService {
677 fn render_png(&self, width: u32, height: u32, scale: f32, background: crate::Color, paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>>;
679}
680
681pub trait WindowCaptureService {
684 fn capture(&mut self, form: crate::ComponentId) -> Option<(u32, u32, Vec<u8>)>;
686}
687
688#[derive(Default)]
690pub struct Services {
691 pub window_capture: Option<Box<dyn WindowCaptureService>>,
693 pub offscreen: Option<Box<dyn OffscreenService>>,
694 pub window: Option<Box<dyn WindowService>>,
695 pub timer: Option<Box<dyn TimerService>>,
696 pub clipboard: Option<Box<dyn ClipboardService>>,
697 pub cursor: Option<Box<dyn CursorService>>,
698 pub screen: Option<Box<dyn ScreenService>>,
699 pub text_input: Option<Box<dyn TextInputService>>,
700 pub locale: Option<Box<dyn LocaleService>>,
701 pub text: Option<Box<dyn TextService>>,
702 pub resources: Option<Box<dyn ResourceService>>,
703 pub forms: Option<Box<dyn FormFactory>>,
704 pub file_dialogs: Option<Box<dyn FileDialogService>>,
705 pub permissions: Option<Box<dyn PermissionService>>,
707 pub biometrics: Option<Box<dyn BiometricService>>,
709 pub http: Option<Box<dyn HttpService>>,
710 pub notifications: Option<Box<dyn NotificationService>>,
711 pub links: Option<Box<dyn LinkService>>,
713 pub sensors: Option<Box<dyn SensorService>>,
715 pub background: Option<Box<dyn BackgroundHost>>,
718 pub phone: Option<Box<dyn PhoneService>>,
720 pub gamepads: Option<Box<dyn GamepadService>>,
722 pub printer: Option<Box<dyn PrintService>>,
723 pub text_assist: Option<Box<dyn crate::textassist::TextAssist>>,
726 pub nfc: Option<Box<dyn NfcService>>,
728 pub bluetooth: Option<Box<dyn BluetoothService>>,
730 pub push: Option<Box<dyn PushService>>,
732 pub actions: Option<Box<dyn ActionService>>,
736}
737
738#[derive(Clone, Debug, Default, PartialEq, Eq)]
740pub struct NfcTag {
741 pub id: String,
743 pub tech: String,
745 pub records: Vec<crate::ndef::NdefRecord>,
747 pub writable: bool,
749}
750
751#[derive(Clone, Debug, PartialEq, Eq)]
753pub enum NfcEvent {
754 Tag(NfcTag),
755 Written,
757 Error(String),
758}
759
760pub trait NfcService {
763 fn available(&self) -> bool;
765 fn enabled(&self) -> bool {
767 self.available()
768 }
769 fn set_reading(&mut self, on: bool);
771 fn write(&mut self, message: Vec<u8>);
774 fn cancel_write(&mut self) {}
776 fn poll(&mut self) -> Vec<NfcEvent>;
778}
779
780#[derive(Clone, Debug, Default, PartialEq, Eq)]
782pub struct BleDevice {
783 pub id: String,
786 pub name: String,
787 pub rssi: i32,
789}
790
791#[derive(Clone, Debug, Default, PartialEq, Eq)]
793pub struct BleCharacteristic {
794 pub service: String,
795 pub characteristic: String,
796 pub properties: Vec<String>,
798}
799
800#[derive(Clone, Debug, PartialEq, Eq)]
802pub enum BluetoothEvent {
803 Found(BleDevice),
804 ScanStopped,
806 Connected { device: String, services: Vec<BleCharacteristic> },
808 Disconnected(String),
809 Value { device: String, characteristic: String, data: Vec<u8> },
811 Written { device: String, characteristic: String },
812 Received { device: String, data: Vec<u8> },
814 Error(String),
815}
816
817pub trait BluetoothService {
821 fn available(&self) -> bool;
822 fn enabled(&self) -> bool {
824 self.available()
825 }
826 fn scan(&mut self, on: bool, services: Vec<String>, name: String);
829 fn connect(&mut self, device: &str);
830 fn disconnect(&mut self, device: &str);
831 fn read(&mut self, device: &str, service: &str, characteristic: &str);
832 fn write(&mut self, device: &str, service: &str, characteristic: &str, data: Vec<u8>, with_response: bool);
833 fn subscribe(&mut self, device: &str, service: &str, characteristic: &str, on: bool);
835 fn paired(&mut self) -> Vec<(String, String)> {
837 Vec::new()
838 }
839 fn open_serial(&mut self, device: &str) -> Result<(), String> {
841 let _ = device;
842 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
843 }
844 fn send_serial(&mut self, device: &str, data: Vec<u8>) -> Result<(), String> {
845 let _ = (device, data);
846 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
847 }
848 fn close_serial(&mut self, device: &str) {
849 let _ = device;
850 }
851 fn poll(&mut self) -> Vec<BluetoothEvent>;
853}
854
855pub fn ble_uuid(text: &str) -> String {
858 let t = text.trim().trim_start_matches("0x").trim_start_matches("0X").to_ascii_lowercase();
859 if (t.len() == 4 || t.len() == 8) && t.chars().all(|c| c.is_ascii_hexdigit()) {
860 format!("{t:0>8}-0000-1000-8000-00805f9b34fb")
861 } else {
862 t
863 }
864}
865
866#[derive(Clone, Debug, Default, PartialEq, Eq)]
868pub struct PushMessage {
869 pub id: String,
871 pub title: String,
873 pub body: String,
874 pub data: String,
876}
877
878#[derive(Clone, Debug, PartialEq, Eq)]
880pub enum PushEvent {
881 Token(String),
885 Message(PushMessage),
887 Opened(PushMessage),
889 Error(String),
890}
891
892#[derive(Clone, Debug, Default, PartialEq, Eq)]
895pub struct PushConfig {
896 pub sender_id: String,
898 pub project_id: String,
900 pub app_id: String,
902 pub api_key: String,
904 pub vapid_key: String,
906 pub show_in_foreground: bool,
909}
910
911pub trait PushService {
915 fn available(&self) -> bool;
918 fn provider(&self) -> &'static str;
921 fn register(&mut self, config: &PushConfig);
924 fn unregister(&mut self) {}
926 fn shows_notifications(&self) -> bool {
930 true
931 }
932 fn poll(&mut self) -> Vec<PushEvent> {
934 Vec::new()
935 }
936}
937
938static PUSH_EVENTS: std::sync::Mutex<Vec<PushEvent>> = std::sync::Mutex::new(Vec::new());
939
940pub fn push_event(event: PushEvent) {
943 if let Ok(mut list) = PUSH_EVENTS.lock() {
944 list.push(event);
945 }
946}
947
948pub fn take_push_events() -> Vec<PushEvent> {
950 PUSH_EVENTS.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
951}
952
953pub fn parse_push_line(line: &str) -> Option<PushEvent> {
957 let mut f = line.split('\t');
958 let kind = f.next()?;
959 let mut next = || f.next().unwrap_or_default().to_string();
960 match kind {
961 "token" => Some(PushEvent::Token(next())),
962 "error" => Some(PushEvent::Error(next())),
963 "message" | "opened" => {
964 let mut m = PushMessage { id: next(), title: next(), body: next(), data: next() };
965 if m.data.trim().is_empty() {
966 m.data = "{}".into();
967 }
968 Some(if kind == "message" { PushEvent::Message(m) } else { PushEvent::Opened(m) })
969 }
970 _ => None,
971 }
972}
973
974pub fn json_field(json: &str, key: &str) -> Option<String> {
977 let chars: Vec<char> = json.chars().collect();
978 let mut i = 0;
979 let skip_ws = |i: &mut usize| {
980 while *i < chars.len() && chars[*i].is_whitespace() {
981 *i += 1;
982 }
983 };
984 let read_string = |i: &mut usize| -> Option<String> {
986 if chars.get(*i) != Some(&'"') {
987 return None;
988 }
989 *i += 1;
990 let mut out = String::new();
991 while *i < chars.len() {
992 let c = chars[*i];
993 *i += 1;
994 match c {
995 '"' => return Some(out),
996 '\\' => {
997 let e = *chars.get(*i)?;
998 *i += 1;
999 match e {
1000 'n' => out.push('\n'),
1001 't' => out.push('\t'),
1002 'r' => out.push('\r'),
1003 'b' => out.push('\u{8}'),
1004 'f' => out.push('\u{c}'),
1005 'u' => {
1006 let hex: String = chars.get(*i..*i + 4)?.iter().collect();
1007 *i += 4;
1008 let mut code = u32::from_str_radix(&hex, 16).ok()?;
1009 if (0xD800..0xDC00).contains(&code) && chars.get(*i) == Some(&'\\') && chars.get(*i + 1) == Some(&'u') {
1011 let low: String = chars.get(*i + 2..*i + 6)?.iter().collect();
1012 if let Ok(low) = u32::from_str_radix(&low, 16) {
1013 *i += 6;
1014 code = 0x10000 + ((code - 0xD800) << 10) + (low.wrapping_sub(0xDC00) & 0x3FF);
1015 }
1016 }
1017 out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
1018 }
1019 other => out.push(other),
1020 }
1021 }
1022 c => out.push(c),
1023 }
1024 }
1025 None
1026 };
1027 skip_ws(&mut i);
1028 if chars.get(i) != Some(&'{') {
1029 return None;
1030 }
1031 i += 1;
1032 loop {
1033 skip_ws(&mut i);
1034 if chars.get(i) == Some(&'}') || i >= chars.len() {
1035 return None;
1036 }
1037 let name = read_string(&mut i)?;
1038 skip_ws(&mut i);
1039 if chars.get(i) != Some(&':') {
1040 return None;
1041 }
1042 i += 1;
1043 skip_ws(&mut i);
1044 let value = if chars.get(i) == Some(&'"') {
1045 read_string(&mut i)?
1046 } else {
1047 let start = i;
1049 let (mut depth, mut quoted) = (0i32, false);
1050 while i < chars.len() {
1051 let c = chars[i];
1052 if quoted {
1053 if c == '\\' {
1054 i += 1;
1055 } else if c == '"' {
1056 quoted = false;
1057 }
1058 } else {
1059 match c {
1060 '"' => quoted = true,
1061 '{' | '[' => depth += 1,
1062 '}' | ']' if depth == 0 => break,
1063 '}' | ']' => depth -= 1,
1064 ',' if depth == 0 => break,
1065 _ => {}
1066 }
1067 }
1068 i += 1;
1069 }
1070 chars[start..i.min(chars.len())].iter().collect::<String>().trim().to_string()
1071 };
1072 if name == key {
1073 return Some(value);
1074 }
1075 skip_ws(&mut i);
1076 if chars.get(i) == Some(&',') {
1077 i += 1;
1078 }
1079 }
1080}
1081
1082pub fn push_message_from_payload(text: &str) -> PushMessage {
1086 let text = text.trim();
1087 if !text.starts_with('{') {
1088 return PushMessage { body: text.to_string(), data: "{}".into(), ..Default::default() };
1089 }
1090 let notification = json_field(text, "notification").unwrap_or_default();
1091 let pick = |key: &str| json_field(text, key).or_else(|| json_field(¬ification, key)).unwrap_or_default();
1092 let data = json_field(text, "data").filter(|d| d.trim_start().starts_with('{')).unwrap_or_else(|| "{}".into());
1093 PushMessage { id: pick("id"), title: pick("title"), body: pick("body"), data }
1094}
1095
1096pub fn render_template(template: &str, data: &str) -> String {
1099 let mut out = String::new();
1100 let mut rest = template;
1101 while let Some(i) = rest.find(['{', '}']) {
1102 out.push_str(&rest[..i]);
1103 let tail = &rest[i..];
1104 if tail.starts_with("{{") || tail.starts_with("}}") {
1105 out.push_str(&tail[..1]);
1106 rest = &tail[2..];
1107 } else if let (true, Some(end)) = (tail.starts_with('{'), tail.find('}')) {
1108 out.push_str(&json_field(data, tail[1..end].trim()).unwrap_or_default());
1109 rest = &tail[end + 1..];
1110 } else {
1111 out.push_str(&tail[..1]);
1112 rest = &tail[1..];
1113 }
1114 }
1115 out.push_str(rest);
1116 out
1117}
1118
1119pub fn data_matches(filter: &str, data: &str) -> bool {
1122 filter.split(';').map(str::trim).filter(|c| !c.is_empty()).all(|c| {
1123 if let Some((k, v)) = c.split_once("!=") {
1124 json_field(data, k.trim()).unwrap_or_default() != v.trim()
1125 } else if let Some((k, v)) = c.split_once('=') {
1126 json_field(data, k.trim()).unwrap_or_default() == v.trim()
1127 } else {
1128 json_field(data, c).is_some_and(|v| !v.is_empty())
1129 }
1130 })
1131}
1132
1133pub fn json_quote(text: &str) -> String {
1135 let mut out = String::with_capacity(text.len() + 2);
1136 out.push('"');
1137 for c in text.chars() {
1138 match c {
1139 '"' => out.push_str("\\\""),
1140 '\\' => out.push_str("\\\\"),
1141 '\n' => out.push_str("\\n"),
1142 '\r' => out.push_str("\\r"),
1143 '\t' => out.push_str("\\t"),
1144 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1145 c => out.push(c),
1146 }
1147 }
1148 out.push('"');
1149 out
1150}
1151
1152#[derive(Clone, Debug, PartialEq, Eq)]
1154pub struct ActionEvent {
1155 pub kind: String,
1159 pub component: String,
1161 pub detail: String,
1163 pub data: String,
1165}
1166
1167pub fn parse_action_line(line: &str) -> Option<ActionEvent> {
1169 let mut f = line.split('\t');
1170 let kind = f.next().filter(|k| !k.is_empty())?.to_string();
1171 let component = f.next()?.to_string();
1172 let detail = f.next().unwrap_or_default().to_string();
1173 let data = f.next().filter(|d| !d.trim().is_empty()).unwrap_or("{}").to_string();
1174 Some(ActionEvent { kind, component, detail, data })
1175}
1176
1177pub trait ActionService {
1181 fn execute(&mut self, spec: &str, data: &str) -> Result<(), String>;
1182 fn stop(&mut self, component: &str);
1184 fn set_push_rules(&mut self, rules: &str);
1187 fn poll(&mut self) -> Vec<ActionEvent>;
1189}
1190
1191
1192static LOCAL_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1196
1197pub fn set_local_offset_fn(f: fn(i64) -> i64) {
1198 if let Ok(mut slot) = LOCAL_OFFSET.write() {
1199 *slot = Some(f);
1200 }
1201}
1202
1203static PROJECT_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1206
1207pub fn set_project_offset_fn(f: Option<fn(i64) -> i64>) {
1209 if let Ok(mut slot) = PROJECT_OFFSET.write() {
1210 *slot = f;
1211 }
1212}
1213
1214pub fn local_offset(utc: i64) -> i64 {
1217 let project = PROJECT_OFFSET.read().ok().and_then(|f| *f);
1218 project.or_else(|| LOCAL_OFFSET.read().ok().and_then(|f| *f)).map_or(0, |f| f(utc))
1219}