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 None,
63}
64
65impl CursorShape {
66 pub const ALL: [CursorShape; 12] = [
67 CursorShape::Default,
68 CursorShape::Pointer,
69 CursorShape::Text,
70 CursorShape::Wait,
71 CursorShape::Crosshair,
72 CursorShape::Move,
73 CursorShape::NotAllowed,
74 CursorShape::ResizeHorizontal,
75 CursorShape::ResizeVertical,
76 CursorShape::ResizeNeSw,
77 CursorShape::ResizeNwSe,
78 CursorShape::None,
79 ];
80}
81
82impl crate::prop::PropEnum for CursorShape {
83 const NAMES: &'static [&'static str] = &[
84 "default",
85 "pointer",
86 "text",
87 "wait",
88 "crosshair",
89 "move",
90 "not_allowed",
91 "resize_horizontal",
92 "resize_vertical",
93 "resize_ne_sw",
94 "resize_nw_se",
95 "none",
96 ];
97
98 fn from_index(index: usize) -> Option<Self> {
99 CursorShape::ALL.get(index).copied()
100 }
101
102 fn index(self) -> usize {
103 self as usize
104 }
105}
106
107pub trait CursorService {
109 fn set_cursor(&mut self, shape: CursorShape);
110}
111
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
114pub enum Appearance {
115 #[default]
116 Light,
117 Dark,
118}
119
120pub trait ScreenService {
122 fn screen_size(&self) -> SizeF;
123 fn scale_factor(&self) -> f32;
124 fn appearance(&self) -> Appearance;
126}
127
128#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
130pub enum KeyboardKind {
131 #[default]
132 Text,
133 Number,
134 Decimal,
135 Phone,
136 Email,
137 Url,
138}
139
140pub trait TextInputService {
142 fn show_keyboard(&mut self, kind: KeyboardKind);
143 fn hide_keyboard(&mut self);
144 fn set_ime_rect(&mut self, rect: RectF);
146}
147
148#[derive(Clone, Debug, PartialEq)]
150pub struct LocaleInfo {
151 pub decimal_separator: char,
152 pub thousand_separator: char,
153 pub short_date_format: String,
154 pub long_time_format: String,
155 pub currency_symbol: String,
156 pub month_names: [&'static str; 12],
159 pub short_day_names: [&'static str; 7],
160 pub first_day_of_week: u8,
162}
163
164const MONTHS_EN: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
165const DAYS_EN: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
166
167impl Default for LocaleInfo {
168 fn default() -> Self {
169 Self {
170 decimal_separator: '.',
171 thousand_separator: ',',
172 short_date_format: "yyyy-mm-dd".into(),
173 long_time_format: "hh:nn:ss".into(),
174 currency_symbol: "$".into(),
175 month_names: MONTHS_EN,
176 short_day_names: DAYS_EN,
177 first_day_of_week: 0,
178 }
179 }
180}
181
182impl LocaleInfo {
183 pub fn pt_br() -> Self {
185 Self {
186 decimal_separator: ',',
187 thousand_separator: '.',
188 short_date_format: "dd/mm/yyyy".into(),
189 long_time_format: "hh:nn:ss".into(),
190 currency_symbol: "R$".into(),
191 month_names: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
192 short_day_names: ["dom", "seg", "ter", "qua", "qui", "sex", "sáb"],
193 first_day_of_week: 0,
194 }
195 }
196
197 pub fn es() -> Self {
199 Self {
200 decimal_separator: ',',
201 thousand_separator: '.',
202 short_date_format: "dd/mm/yyyy".into(),
203 long_time_format: "hh:nn:ss".into(),
204 currency_symbol: "€".into(),
205 month_names: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],
206 short_day_names: ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"],
207 first_day_of_week: 1,
208 }
209 }
210
211 pub fn en_us() -> Self {
213 Self {
214 decimal_separator: '.',
215 thousand_separator: ',',
216 short_date_format: "mm/dd/yyyy".into(),
217 long_time_format: "hh:nn:ss".into(),
218 currency_symbol: "$".into(),
219 month_names: MONTHS_EN,
220 short_day_names: DAYS_EN,
221 first_day_of_week: 0,
222 }
223 }
224}
225
226pub trait LocaleService {
227 fn locale(&self) -> LocaleInfo;
228}
229
230impl LocaleService for LocaleInfo {
232 fn locale(&self) -> LocaleInfo {
233 self.clone()
234 }
235}
236
237#[derive(Clone, Copy, Debug, PartialEq, Eq)]
239pub enum LifecycleEvent {
240 Resumed,
241 Suspended,
242 LowMemory,
243 SurfaceLost,
245}
246
247pub trait ResourceService {
251 fn read(&self, path: &str) -> Option<Vec<u8>>;
252}
253
254pub trait FormFactory {
257 fn create_form(&mut self, ui: &mut crate::Ui, name: &str) -> Result<crate::ComponentId, String>;
259 fn form_names(&self) -> Vec<String>;
261}
262
263#[derive(Clone, Debug, Default)]
265pub struct FileDialogOptions {
266 pub title: String,
267 pub filters: Vec<(String, Vec<String>)>,
269 pub directory: String,
270 pub file_name: String,
271 pub save: bool,
273 pub multiple: bool,
275}
276
277pub trait FileDialogService {
280 fn show(&mut self, options: FileDialogOptions, done: Box<dyn FnOnce(Vec<String>) + Send>);
281}
282
283#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
286pub enum Permission {
287 Camera,
288 Microphone,
289 Location,
291 Notifications,
292 Photos,
294 Contacts,
295 Calendar,
296 Bluetooth,
297}
298
299impl Permission {
300 pub const ALL: [Permission; 8] = [
301 Permission::Camera,
302 Permission::Microphone,
303 Permission::Location,
304 Permission::Notifications,
305 Permission::Photos,
306 Permission::Contacts,
307 Permission::Calendar,
308 Permission::Bluetooth,
309 ];
310
311 pub fn name(self) -> &'static str {
313 match self {
314 Permission::Camera => "camera",
315 Permission::Microphone => "microphone",
316 Permission::Location => "location",
317 Permission::Notifications => "notifications",
318 Permission::Photos => "photos",
319 Permission::Contacts => "contacts",
320 Permission::Calendar => "calendar",
321 Permission::Bluetooth => "bluetooth",
322 }
323 }
324
325 pub fn parse(name: &str) -> Option<Permission> {
326 let name = name.trim();
327 Permission::ALL.into_iter().find(|p| p.name().eq_ignore_ascii_case(name))
328 }
329
330 pub fn parse_list(list: &str) -> Vec<Permission> {
332 let mut out = Vec::new();
333 for p in list.split([';', ',']).filter_map(Permission::parse) {
334 if !out.contains(&p) {
335 out.push(p);
336 }
337 }
338 out
339 }
340}
341
342#[derive(Clone, Copy, Debug, PartialEq, Eq)]
344pub enum PermissionState {
345 Granted,
347 Denied,
349 Prompt,
351 Unavailable,
353}
354
355impl PermissionState {
356 pub fn name(self) -> &'static str {
357 match self {
358 PermissionState::Granted => "granted",
359 PermissionState::Denied => "denied",
360 PermissionState::Prompt => "prompt",
361 PermissionState::Unavailable => "unavailable",
362 }
363 }
364}
365
366pub trait PermissionService {
369 fn state(&self, permission: Permission) -> PermissionState;
370 fn request(&mut self, permissions: Vec<Permission>, done: Box<dyn FnOnce(Vec<(Permission, PermissionState)>) + Send>);
371}
372
373#[derive(Clone, Copy, Debug, PartialEq, Eq)]
375pub enum Biometry {
376 None,
378 Fingerprint,
379 Face,
380 Iris,
381 Any,
383}
384
385impl Biometry {
386 pub fn name(self) -> &'static str {
387 match self {
388 Biometry::None => "none",
389 Biometry::Fingerprint => "fingerprint",
390 Biometry::Face => "face",
391 Biometry::Iris => "iris",
392 Biometry::Any => "any",
393 }
394 }
395}
396
397#[derive(Clone, Debug, PartialEq, Eq)]
399pub enum BiometricResult {
400 Success,
401 Cancelled,
403 Failed(String),
405}
406
407pub trait BiometricService {
410 fn availability(&self) -> Biometry;
411 fn authenticate(&mut self, reason: &str, allow_device_credential: bool, done: Box<dyn FnOnce(BiometricResult) + Send>);
414}
415
416pub trait PrintService {
420 fn print(&mut self, title: &str, pages: crate::pages::PageSet, done: Box<dyn FnOnce(Result<bool, String>) + Send>);
421}
422
423pub trait HttpService {
427 fn get(&mut self, url: &str, done: Box<dyn FnOnce(Result<Vec<u8>, String>) + Send>);
428}
429
430#[derive(Clone, Debug, Default, PartialEq)]
432pub struct SystemNotification {
433 pub app_id: String,
435 pub app_name: String,
437 pub title: String,
438 pub body: String,
439 pub image: String,
441 pub image_png: Vec<u8>,
443 pub big_image: bool,
445 pub id: u32,
447 pub channel: String,
449 pub channel_name: String,
450 pub priority: NotificationPriority,
451 pub actions: Vec<(String, String)>,
453 pub ongoing: bool,
455 pub progress: Option<f32>,
457 pub full_screen: bool,
460 pub component: Option<crate::ComponentId>,
462}
463
464#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
466pub enum NotificationPriority {
467 Low,
469 #[default]
470 Default,
471 High,
473}
474
475impl crate::PropEnum for NotificationPriority {
476 const NAMES: &'static [&'static str] = &["low", "default", "high"];
477 fn from_index(index: usize) -> Option<Self> {
478 [Self::Low, Self::Default, Self::High].get(index).copied()
479 }
480 fn index(self) -> usize {
481 self as usize
482 }
483}
484
485pub trait NotificationService {
487 fn notify(&mut self, notification: &SystemNotification) -> Result<(), String>;
488 fn cancel(&mut self, id: u32) -> Result<(), String> {
490 let _ = id;
491 Ok(())
492 }
493}
494
495pub trait LinkService {
498 fn open_url(&mut self, url: &str) -> Result<(), String>;
500 fn open_app(&mut self, app: &str) -> Result<(), String> {
502 Err(format!("abrir outro app não existe aqui ({app})"))
503 }
504 fn share(&mut self, text: &str, files: &[String]) -> Result<(), String> {
506 let _ = (text, files);
507 Err("compartilhar não existe aqui".into())
508 }
509 fn request(&mut self, action: &str, data: &str, done: Box<dyn FnOnce(Result<String, String>) + Send>) {
512 let _ = data;
513 done(Err(format!("pedir a outro app não existe aqui ({action})")));
514 }
515}
516
517#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
519pub enum Sensor {
520 Location,
522 Battery,
524 Network,
526 Motion,
528 Compass,
530 Proximity,
532 Light,
534}
535
536pub trait SensorService {
539 fn available(&self, sensor: Sensor) -> bool;
541 fn set_active(&mut self, sensor: Sensor, on: bool);
543 fn read(&mut self, sensor: Sensor) -> Option<Vec<f64>>;
545 fn vibrate(&mut self, ms: u32) -> bool {
547 let _ = ms;
548 false
549 }
550}
551
552pub const GAMEPAD_BUTTONS: [&str; 17] =
556 ["a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "l3", "r3", "up", "down", "left", "right", "guide"];
557
558#[derive(Clone, Debug, Default, PartialEq)]
560pub struct GamepadState {
561 pub name: String,
562 pub buttons: u32,
564 pub axes: [f32; 6],
567}
568
569impl GamepadState {
570 pub fn set_button(&mut self, name: &str, down: bool) {
572 if let Some(i) = GAMEPAD_BUTTONS.iter().position(|b| *b == name) {
573 if down {
574 self.buttons |= 1 << i;
575 } else {
576 self.buttons &= !(1 << i);
577 }
578 }
579 }
580
581 pub fn pressed(&self, name: &str) -> bool {
582 GAMEPAD_BUTTONS.iter().position(|b| *b == name).is_some_and(|i| self.buttons & (1 << i) != 0)
583 }
584}
585
586pub trait GamepadService {
588 fn pads(&mut self) -> Vec<GamepadState>;
590 fn rumble(&mut self, index: usize, strength: f32, ms: u32) -> bool {
592 let _ = (index, strength, ms);
593 false
594 }
595}
596
597pub trait PhoneService {
599 fn dial(&mut self, number: &str) -> Result<(), String>;
601 fn call(&mut self, number: &str) -> Result<(), String>;
603 fn watch(&mut self, on: bool);
605 fn state(&mut self) -> (String, String);
608 fn request_dialer(&mut self) -> Result<(), String> {
610 Err("não existe aqui".into())
611 }
612 fn answer(&mut self) -> bool {
614 false
615 }
616 fn reject(&mut self) -> bool {
617 false
618 }
619 fn hang_up(&mut self) -> bool {
620 false
621 }
622 fn history(&mut self, max: u32) -> Result<String, String> {
624 let _ = max;
625 Err("não existe aqui".into())
626 }
627 fn lock_screen(&mut self, show_when_locked: bool, turn_screen_on: bool);
629 fn dismiss_keyguard(&mut self);
631}
632
633pub trait BackgroundHost {
638 fn start(&mut self, title: &str, text: &str, kind: &str, keep_alive: bool) -> Result<(), String>;
639 fn stop(&mut self);
640}
641
642#[derive(Clone, Debug, PartialEq, Eq)]
645pub enum Incoming {
646 Link(String),
647 Shared(String),
648}
649
650static INCOMING: std::sync::Mutex<Vec<Incoming>> = std::sync::Mutex::new(Vec::new());
651
652pub fn push_incoming(item: Incoming) {
655 if let Ok(mut list) = INCOMING.lock() {
656 list.push(item);
657 }
658}
659
660pub fn take_incoming() -> Vec<Incoming> {
662 INCOMING.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
663}
664
665pub trait OffscreenService {
668 fn render_png(&self, width: u32, height: u32, scale: f32, background: crate::Color, paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>>;
670}
671
672#[derive(Default)]
674pub struct Services {
675 pub offscreen: Option<Box<dyn OffscreenService>>,
676 pub window: Option<Box<dyn WindowService>>,
677 pub timer: Option<Box<dyn TimerService>>,
678 pub clipboard: Option<Box<dyn ClipboardService>>,
679 pub cursor: Option<Box<dyn CursorService>>,
680 pub screen: Option<Box<dyn ScreenService>>,
681 pub text_input: Option<Box<dyn TextInputService>>,
682 pub locale: Option<Box<dyn LocaleService>>,
683 pub text: Option<Box<dyn TextService>>,
684 pub resources: Option<Box<dyn ResourceService>>,
685 pub forms: Option<Box<dyn FormFactory>>,
686 pub file_dialogs: Option<Box<dyn FileDialogService>>,
687 pub permissions: Option<Box<dyn PermissionService>>,
689 pub biometrics: Option<Box<dyn BiometricService>>,
691 pub http: Option<Box<dyn HttpService>>,
692 pub notifications: Option<Box<dyn NotificationService>>,
693 pub links: Option<Box<dyn LinkService>>,
695 pub sensors: Option<Box<dyn SensorService>>,
697 pub background: Option<Box<dyn BackgroundHost>>,
700 pub phone: Option<Box<dyn PhoneService>>,
702 pub gamepads: Option<Box<dyn GamepadService>>,
704 pub printer: Option<Box<dyn PrintService>>,
705 pub text_assist: Option<Box<dyn crate::textassist::TextAssist>>,
708 pub nfc: Option<Box<dyn NfcService>>,
710 pub bluetooth: Option<Box<dyn BluetoothService>>,
712 pub push: Option<Box<dyn PushService>>,
714 pub actions: Option<Box<dyn ActionService>>,
718}
719
720#[derive(Clone, Debug, Default, PartialEq, Eq)]
722pub struct NfcTag {
723 pub id: String,
725 pub tech: String,
727 pub records: Vec<crate::ndef::NdefRecord>,
729 pub writable: bool,
731}
732
733#[derive(Clone, Debug, PartialEq, Eq)]
735pub enum NfcEvent {
736 Tag(NfcTag),
737 Written,
739 Error(String),
740}
741
742pub trait NfcService {
745 fn available(&self) -> bool;
747 fn enabled(&self) -> bool {
749 self.available()
750 }
751 fn set_reading(&mut self, on: bool);
753 fn write(&mut self, message: Vec<u8>);
756 fn cancel_write(&mut self) {}
758 fn poll(&mut self) -> Vec<NfcEvent>;
760}
761
762#[derive(Clone, Debug, Default, PartialEq, Eq)]
764pub struct BleDevice {
765 pub id: String,
768 pub name: String,
769 pub rssi: i32,
771}
772
773#[derive(Clone, Debug, Default, PartialEq, Eq)]
775pub struct BleCharacteristic {
776 pub service: String,
777 pub characteristic: String,
778 pub properties: Vec<String>,
780}
781
782#[derive(Clone, Debug, PartialEq, Eq)]
784pub enum BluetoothEvent {
785 Found(BleDevice),
786 ScanStopped,
788 Connected { device: String, services: Vec<BleCharacteristic> },
790 Disconnected(String),
791 Value { device: String, characteristic: String, data: Vec<u8> },
793 Written { device: String, characteristic: String },
794 Received { device: String, data: Vec<u8> },
796 Error(String),
797}
798
799pub trait BluetoothService {
803 fn available(&self) -> bool;
804 fn enabled(&self) -> bool {
806 self.available()
807 }
808 fn scan(&mut self, on: bool, services: Vec<String>, name: String);
811 fn connect(&mut self, device: &str);
812 fn disconnect(&mut self, device: &str);
813 fn read(&mut self, device: &str, service: &str, characteristic: &str);
814 fn write(&mut self, device: &str, service: &str, characteristic: &str, data: Vec<u8>, with_response: bool);
815 fn subscribe(&mut self, device: &str, service: &str, characteristic: &str, on: bool);
817 fn paired(&mut self) -> Vec<(String, String)> {
819 Vec::new()
820 }
821 fn open_serial(&mut self, device: &str) -> Result<(), String> {
823 let _ = device;
824 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
825 }
826 fn send_serial(&mut self, device: &str, data: Vec<u8>) -> Result<(), String> {
827 let _ = (device, data);
828 Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
829 }
830 fn close_serial(&mut self, device: &str) {
831 let _ = device;
832 }
833 fn poll(&mut self) -> Vec<BluetoothEvent>;
835}
836
837pub fn ble_uuid(text: &str) -> String {
840 let t = text.trim().trim_start_matches("0x").trim_start_matches("0X").to_ascii_lowercase();
841 if (t.len() == 4 || t.len() == 8) && t.chars().all(|c| c.is_ascii_hexdigit()) {
842 format!("{t:0>8}-0000-1000-8000-00805f9b34fb")
843 } else {
844 t
845 }
846}
847
848#[derive(Clone, Debug, Default, PartialEq, Eq)]
850pub struct PushMessage {
851 pub id: String,
853 pub title: String,
855 pub body: String,
856 pub data: String,
858}
859
860#[derive(Clone, Debug, PartialEq, Eq)]
862pub enum PushEvent {
863 Token(String),
867 Message(PushMessage),
869 Opened(PushMessage),
871 Error(String),
872}
873
874#[derive(Clone, Debug, Default, PartialEq, Eq)]
877pub struct PushConfig {
878 pub sender_id: String,
880 pub project_id: String,
882 pub app_id: String,
884 pub api_key: String,
886 pub vapid_key: String,
888 pub show_in_foreground: bool,
891}
892
893pub trait PushService {
897 fn available(&self) -> bool;
900 fn provider(&self) -> &'static str;
903 fn register(&mut self, config: &PushConfig);
906 fn unregister(&mut self) {}
908 fn shows_notifications(&self) -> bool {
912 true
913 }
914 fn poll(&mut self) -> Vec<PushEvent> {
916 Vec::new()
917 }
918}
919
920static PUSH_EVENTS: std::sync::Mutex<Vec<PushEvent>> = std::sync::Mutex::new(Vec::new());
921
922pub fn push_event(event: PushEvent) {
925 if let Ok(mut list) = PUSH_EVENTS.lock() {
926 list.push(event);
927 }
928}
929
930pub fn take_push_events() -> Vec<PushEvent> {
932 PUSH_EVENTS.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
933}
934
935pub fn parse_push_line(line: &str) -> Option<PushEvent> {
939 let mut f = line.split('\t');
940 let kind = f.next()?;
941 let mut next = || f.next().unwrap_or_default().to_string();
942 match kind {
943 "token" => Some(PushEvent::Token(next())),
944 "error" => Some(PushEvent::Error(next())),
945 "message" | "opened" => {
946 let mut m = PushMessage { id: next(), title: next(), body: next(), data: next() };
947 if m.data.trim().is_empty() {
948 m.data = "{}".into();
949 }
950 Some(if kind == "message" { PushEvent::Message(m) } else { PushEvent::Opened(m) })
951 }
952 _ => None,
953 }
954}
955
956pub fn json_field(json: &str, key: &str) -> Option<String> {
959 let chars: Vec<char> = json.chars().collect();
960 let mut i = 0;
961 let skip_ws = |i: &mut usize| {
962 while *i < chars.len() && chars[*i].is_whitespace() {
963 *i += 1;
964 }
965 };
966 let read_string = |i: &mut usize| -> Option<String> {
968 if chars.get(*i) != Some(&'"') {
969 return None;
970 }
971 *i += 1;
972 let mut out = String::new();
973 while *i < chars.len() {
974 let c = chars[*i];
975 *i += 1;
976 match c {
977 '"' => return Some(out),
978 '\\' => {
979 let e = *chars.get(*i)?;
980 *i += 1;
981 match e {
982 'n' => out.push('\n'),
983 't' => out.push('\t'),
984 'r' => out.push('\r'),
985 'b' => out.push('\u{8}'),
986 'f' => out.push('\u{c}'),
987 'u' => {
988 let hex: String = chars.get(*i..*i + 4)?.iter().collect();
989 *i += 4;
990 let mut code = u32::from_str_radix(&hex, 16).ok()?;
991 if (0xD800..0xDC00).contains(&code) && chars.get(*i) == Some(&'\\') && chars.get(*i + 1) == Some(&'u') {
993 let low: String = chars.get(*i + 2..*i + 6)?.iter().collect();
994 if let Ok(low) = u32::from_str_radix(&low, 16) {
995 *i += 6;
996 code = 0x10000 + ((code - 0xD800) << 10) + (low.wrapping_sub(0xDC00) & 0x3FF);
997 }
998 }
999 out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
1000 }
1001 other => out.push(other),
1002 }
1003 }
1004 c => out.push(c),
1005 }
1006 }
1007 None
1008 };
1009 skip_ws(&mut i);
1010 if chars.get(i) != Some(&'{') {
1011 return None;
1012 }
1013 i += 1;
1014 loop {
1015 skip_ws(&mut i);
1016 if chars.get(i) == Some(&'}') || i >= chars.len() {
1017 return None;
1018 }
1019 let name = read_string(&mut i)?;
1020 skip_ws(&mut i);
1021 if chars.get(i) != Some(&':') {
1022 return None;
1023 }
1024 i += 1;
1025 skip_ws(&mut i);
1026 let value = if chars.get(i) == Some(&'"') {
1027 read_string(&mut i)?
1028 } else {
1029 let start = i;
1031 let (mut depth, mut quoted) = (0i32, false);
1032 while i < chars.len() {
1033 let c = chars[i];
1034 if quoted {
1035 if c == '\\' {
1036 i += 1;
1037 } else if c == '"' {
1038 quoted = false;
1039 }
1040 } else {
1041 match c {
1042 '"' => quoted = true,
1043 '{' | '[' => depth += 1,
1044 '}' | ']' if depth == 0 => break,
1045 '}' | ']' => depth -= 1,
1046 ',' if depth == 0 => break,
1047 _ => {}
1048 }
1049 }
1050 i += 1;
1051 }
1052 chars[start..i.min(chars.len())].iter().collect::<String>().trim().to_string()
1053 };
1054 if name == key {
1055 return Some(value);
1056 }
1057 skip_ws(&mut i);
1058 if chars.get(i) == Some(&',') {
1059 i += 1;
1060 }
1061 }
1062}
1063
1064pub fn push_message_from_payload(text: &str) -> PushMessage {
1068 let text = text.trim();
1069 if !text.starts_with('{') {
1070 return PushMessage { body: text.to_string(), data: "{}".into(), ..Default::default() };
1071 }
1072 let notification = json_field(text, "notification").unwrap_or_default();
1073 let pick = |key: &str| json_field(text, key).or_else(|| json_field(¬ification, key)).unwrap_or_default();
1074 let data = json_field(text, "data").filter(|d| d.trim_start().starts_with('{')).unwrap_or_else(|| "{}".into());
1075 PushMessage { id: pick("id"), title: pick("title"), body: pick("body"), data }
1076}
1077
1078pub fn render_template(template: &str, data: &str) -> String {
1081 let mut out = String::new();
1082 let mut rest = template;
1083 while let Some(i) = rest.find(['{', '}']) {
1084 out.push_str(&rest[..i]);
1085 let tail = &rest[i..];
1086 if tail.starts_with("{{") || tail.starts_with("}}") {
1087 out.push_str(&tail[..1]);
1088 rest = &tail[2..];
1089 } else if let (true, Some(end)) = (tail.starts_with('{'), tail.find('}')) {
1090 out.push_str(&json_field(data, tail[1..end].trim()).unwrap_or_default());
1091 rest = &tail[end + 1..];
1092 } else {
1093 out.push_str(&tail[..1]);
1094 rest = &tail[1..];
1095 }
1096 }
1097 out.push_str(rest);
1098 out
1099}
1100
1101pub fn data_matches(filter: &str, data: &str) -> bool {
1104 filter.split(';').map(str::trim).filter(|c| !c.is_empty()).all(|c| {
1105 if let Some((k, v)) = c.split_once("!=") {
1106 json_field(data, k.trim()).unwrap_or_default() != v.trim()
1107 } else if let Some((k, v)) = c.split_once('=') {
1108 json_field(data, k.trim()).unwrap_or_default() == v.trim()
1109 } else {
1110 json_field(data, c).is_some_and(|v| !v.is_empty())
1111 }
1112 })
1113}
1114
1115pub fn json_quote(text: &str) -> String {
1117 let mut out = String::with_capacity(text.len() + 2);
1118 out.push('"');
1119 for c in text.chars() {
1120 match c {
1121 '"' => out.push_str("\\\""),
1122 '\\' => out.push_str("\\\\"),
1123 '\n' => out.push_str("\\n"),
1124 '\r' => out.push_str("\\r"),
1125 '\t' => out.push_str("\\t"),
1126 c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
1127 c => out.push(c),
1128 }
1129 }
1130 out.push('"');
1131 out
1132}
1133
1134#[derive(Clone, Debug, PartialEq, Eq)]
1136pub struct ActionEvent {
1137 pub kind: String,
1141 pub component: String,
1143 pub detail: String,
1145 pub data: String,
1147}
1148
1149pub fn parse_action_line(line: &str) -> Option<ActionEvent> {
1151 let mut f = line.split('\t');
1152 let kind = f.next().filter(|k| !k.is_empty())?.to_string();
1153 let component = f.next()?.to_string();
1154 let detail = f.next().unwrap_or_default().to_string();
1155 let data = f.next().filter(|d| !d.trim().is_empty()).unwrap_or("{}").to_string();
1156 Some(ActionEvent { kind, component, detail, data })
1157}
1158
1159pub trait ActionService {
1163 fn execute(&mut self, spec: &str, data: &str) -> Result<(), String>;
1164 fn stop(&mut self, component: &str);
1166 fn set_push_rules(&mut self, rules: &str);
1169 fn poll(&mut self) -> Vec<ActionEvent>;
1171}
1172
1173
1174static LOCAL_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1178
1179pub fn set_local_offset_fn(f: fn(i64) -> i64) {
1180 if let Ok(mut slot) = LOCAL_OFFSET.write() {
1181 *slot = Some(f);
1182 }
1183}
1184
1185static PROJECT_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
1188
1189pub fn set_project_offset_fn(f: Option<fn(i64) -> i64>) {
1191 if let Ok(mut slot) = PROJECT_OFFSET.write() {
1192 *slot = f;
1193 }
1194}
1195
1196pub fn local_offset(utc: i64) -> i64 {
1199 let project = PROJECT_OFFSET.read().ok().and_then(|f| *f);
1200 project.or_else(|| LOCAL_OFFSET.read().ok().and_then(|f| *f)).map_or(0, |f| f(utc))
1201}