use crate::canvas::TextService;
use crate::geometry::{RectF, SizeF};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct WindowId(pub u64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TimerId(pub u64);
pub trait WindowService {
fn create_window(&mut self, title: &str, size: SizeF) -> WindowId;
fn close_window(&mut self, window: WindowId);
fn set_title(&mut self, window: WindowId, title: &str);
fn set_size(&mut self, window: WindowId, size: SizeF);
fn request_redraw(&mut self, window: WindowId);
fn scale_factor(&self, window: WindowId) -> f32;
}
pub trait TimerService {
fn start_timer(&mut self, interval_ms: u32, repeat: bool) -> TimerId;
fn stop_timer(&mut self, timer: TimerId);
fn request_frame(&mut self);
fn now(&self) -> f64;
}
pub trait ClipboardService {
fn get_text(&mut self) -> Option<String>;
fn set_text(&mut self, text: &str);
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CursorShape {
#[default]
Default,
Pointer,
Text,
Wait,
Crosshair,
Move,
NotAllowed,
ResizeHorizontal,
ResizeVertical,
ResizeNeSw,
ResizeNwSe,
None,
}
impl CursorShape {
pub const ALL: [CursorShape; 12] = [
CursorShape::Default,
CursorShape::Pointer,
CursorShape::Text,
CursorShape::Wait,
CursorShape::Crosshair,
CursorShape::Move,
CursorShape::NotAllowed,
CursorShape::ResizeHorizontal,
CursorShape::ResizeVertical,
CursorShape::ResizeNeSw,
CursorShape::ResizeNwSe,
CursorShape::None,
];
}
impl crate::prop::PropEnum for CursorShape {
const NAMES: &'static [&'static str] = &[
"default",
"pointer",
"text",
"wait",
"crosshair",
"move",
"not_allowed",
"resize_horizontal",
"resize_vertical",
"resize_ne_sw",
"resize_nw_se",
"none",
];
fn from_index(index: usize) -> Option<Self> {
CursorShape::ALL.get(index).copied()
}
fn index(self) -> usize {
self as usize
}
}
pub trait CursorService {
fn set_cursor(&mut self, shape: CursorShape);
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Appearance {
#[default]
Light,
Dark,
}
pub trait ScreenService {
fn screen_size(&self) -> SizeF;
fn scale_factor(&self) -> f32;
fn appearance(&self) -> Appearance;
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum KeyboardKind {
#[default]
Text,
Number,
Decimal,
Phone,
Email,
Url,
}
pub trait TextInputService {
fn show_keyboard(&mut self, kind: KeyboardKind);
fn hide_keyboard(&mut self);
fn set_ime_rect(&mut self, rect: RectF);
}
#[derive(Clone, Debug, PartialEq)]
pub struct LocaleInfo {
pub decimal_separator: char,
pub thousand_separator: char,
pub short_date_format: String,
pub long_time_format: String,
pub currency_symbol: String,
pub month_names: [&'static str; 12],
pub short_day_names: [&'static str; 7],
pub first_day_of_week: u8,
}
const MONTHS_EN: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const DAYS_EN: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
impl Default for LocaleInfo {
fn default() -> Self {
Self {
decimal_separator: '.',
thousand_separator: ',',
short_date_format: "yyyy-mm-dd".into(),
long_time_format: "hh:nn:ss".into(),
currency_symbol: "$".into(),
month_names: MONTHS_EN,
short_day_names: DAYS_EN,
first_day_of_week: 0,
}
}
}
impl LocaleInfo {
pub fn pt_br() -> Self {
Self {
decimal_separator: ',',
thousand_separator: '.',
short_date_format: "dd/mm/yyyy".into(),
long_time_format: "hh:nn:ss".into(),
currency_symbol: "R$".into(),
month_names: ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"],
short_day_names: ["dom", "seg", "ter", "qua", "qui", "sex", "sáb"],
first_day_of_week: 0,
}
}
pub fn es() -> Self {
Self {
decimal_separator: ',',
thousand_separator: '.',
short_date_format: "dd/mm/yyyy".into(),
long_time_format: "hh:nn:ss".into(),
currency_symbol: "€".into(),
month_names: ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"],
short_day_names: ["dom", "lun", "mar", "mié", "jue", "vie", "sáb"],
first_day_of_week: 1,
}
}
pub fn en_us() -> Self {
Self {
decimal_separator: '.',
thousand_separator: ',',
short_date_format: "mm/dd/yyyy".into(),
long_time_format: "hh:nn:ss".into(),
currency_symbol: "$".into(),
month_names: MONTHS_EN,
short_day_names: DAYS_EN,
first_day_of_week: 0,
}
}
}
pub trait LocaleService {
fn locale(&self) -> LocaleInfo;
}
impl LocaleService for LocaleInfo {
fn locale(&self) -> LocaleInfo {
self.clone()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LifecycleEvent {
Resumed,
Suspended,
LowMemory,
SurfaceLost,
}
pub trait ResourceService {
fn read(&self, path: &str) -> Option<Vec<u8>>;
}
pub trait FormFactory {
fn create_form(&mut self, ui: &mut crate::Ui, name: &str) -> Result<crate::ComponentId, String>;
fn form_names(&self) -> Vec<String>;
}
#[derive(Clone, Debug, Default)]
pub struct FileDialogOptions {
pub title: String,
pub filters: Vec<(String, Vec<String>)>,
pub directory: String,
pub file_name: String,
pub save: bool,
pub multiple: bool,
}
pub trait FileDialogService {
fn show(&mut self, options: FileDialogOptions, done: Box<dyn FnOnce(Vec<String>) + Send>);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Permission {
Camera,
Microphone,
Location,
Notifications,
Photos,
Contacts,
Calendar,
Bluetooth,
}
impl Permission {
pub const ALL: [Permission; 8] = [
Permission::Camera,
Permission::Microphone,
Permission::Location,
Permission::Notifications,
Permission::Photos,
Permission::Contacts,
Permission::Calendar,
Permission::Bluetooth,
];
pub fn name(self) -> &'static str {
match self {
Permission::Camera => "camera",
Permission::Microphone => "microphone",
Permission::Location => "location",
Permission::Notifications => "notifications",
Permission::Photos => "photos",
Permission::Contacts => "contacts",
Permission::Calendar => "calendar",
Permission::Bluetooth => "bluetooth",
}
}
pub fn parse(name: &str) -> Option<Permission> {
let name = name.trim();
Permission::ALL.into_iter().find(|p| p.name().eq_ignore_ascii_case(name))
}
pub fn parse_list(list: &str) -> Vec<Permission> {
let mut out = Vec::new();
for p in list.split([';', ',']).filter_map(Permission::parse) {
if !out.contains(&p) {
out.push(p);
}
}
out
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PermissionState {
Granted,
Denied,
Prompt,
Unavailable,
}
impl PermissionState {
pub fn name(self) -> &'static str {
match self {
PermissionState::Granted => "granted",
PermissionState::Denied => "denied",
PermissionState::Prompt => "prompt",
PermissionState::Unavailable => "unavailable",
}
}
}
pub trait PermissionService {
fn state(&self, permission: Permission) -> PermissionState;
fn request(&mut self, permissions: Vec<Permission>, done: Box<dyn FnOnce(Vec<(Permission, PermissionState)>) + Send>);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Biometry {
None,
Fingerprint,
Face,
Iris,
Any,
}
impl Biometry {
pub fn name(self) -> &'static str {
match self {
Biometry::None => "none",
Biometry::Fingerprint => "fingerprint",
Biometry::Face => "face",
Biometry::Iris => "iris",
Biometry::Any => "any",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BiometricResult {
Success,
Cancelled,
Failed(String),
}
pub trait BiometricService {
fn availability(&self) -> Biometry;
fn authenticate(&mut self, reason: &str, allow_device_credential: bool, done: Box<dyn FnOnce(BiometricResult) + Send>);
}
pub trait PrintService {
fn print(&mut self, title: &str, pages: crate::pages::PageSet, done: Box<dyn FnOnce(Result<bool, String>) + Send>);
}
pub trait HttpService {
fn get(&mut self, url: &str, done: Box<dyn FnOnce(Result<Vec<u8>, String>) + Send>);
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SystemNotification {
pub app_id: String,
pub app_name: String,
pub title: String,
pub body: String,
pub image: String,
pub image_png: Vec<u8>,
pub big_image: bool,
pub id: u32,
pub channel: String,
pub channel_name: String,
pub priority: NotificationPriority,
pub actions: Vec<(String, String)>,
pub ongoing: bool,
pub progress: Option<f32>,
pub full_screen: bool,
pub component: Option<crate::ComponentId>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NotificationPriority {
Low,
#[default]
Default,
High,
}
impl crate::PropEnum for NotificationPriority {
const NAMES: &'static [&'static str] = &["low", "default", "high"];
fn from_index(index: usize) -> Option<Self> {
[Self::Low, Self::Default, Self::High].get(index).copied()
}
fn index(self) -> usize {
self as usize
}
}
pub trait NotificationService {
fn notify(&mut self, notification: &SystemNotification) -> Result<(), String>;
fn cancel(&mut self, id: u32) -> Result<(), String> {
let _ = id;
Ok(())
}
}
pub trait LinkService {
fn open_url(&mut self, url: &str) -> Result<(), String>;
fn open_app(&mut self, app: &str) -> Result<(), String> {
Err(format!("abrir outro app não existe aqui ({app})"))
}
fn share(&mut self, text: &str, files: &[String]) -> Result<(), String> {
let _ = (text, files);
Err("compartilhar não existe aqui".into())
}
fn request(&mut self, action: &str, data: &str, done: Box<dyn FnOnce(Result<String, String>) + Send>) {
let _ = data;
done(Err(format!("pedir a outro app não existe aqui ({action})")));
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Sensor {
Location,
Battery,
Network,
Motion,
Compass,
Proximity,
Light,
}
pub trait SensorService {
fn available(&self, sensor: Sensor) -> bool;
fn set_active(&mut self, sensor: Sensor, on: bool);
fn read(&mut self, sensor: Sensor) -> Option<Vec<f64>>;
fn vibrate(&mut self, ms: u32) -> bool {
let _ = ms;
false
}
}
pub const GAMEPAD_BUTTONS: [&str; 17] =
["a", "b", "x", "y", "lb", "rb", "lt", "rt", "back", "start", "l3", "r3", "up", "down", "left", "right", "guide"];
#[derive(Clone, Debug, Default, PartialEq)]
pub struct GamepadState {
pub name: String,
pub buttons: u32,
pub axes: [f32; 6],
}
impl GamepadState {
pub fn set_button(&mut self, name: &str, down: bool) {
if let Some(i) = GAMEPAD_BUTTONS.iter().position(|b| *b == name) {
if down {
self.buttons |= 1 << i;
} else {
self.buttons &= !(1 << i);
}
}
}
pub fn pressed(&self, name: &str) -> bool {
GAMEPAD_BUTTONS.iter().position(|b| *b == name).is_some_and(|i| self.buttons & (1 << i) != 0)
}
}
pub trait GamepadService {
fn pads(&mut self) -> Vec<GamepadState>;
fn rumble(&mut self, index: usize, strength: f32, ms: u32) -> bool {
let _ = (index, strength, ms);
false
}
}
pub trait PhoneService {
fn dial(&mut self, number: &str) -> Result<(), String>;
fn call(&mut self, number: &str) -> Result<(), String>;
fn watch(&mut self, on: bool);
fn state(&mut self) -> (String, String);
fn request_dialer(&mut self) -> Result<(), String> {
Err("não existe aqui".into())
}
fn answer(&mut self) -> bool {
false
}
fn reject(&mut self) -> bool {
false
}
fn hang_up(&mut self) -> bool {
false
}
fn history(&mut self, max: u32) -> Result<String, String> {
let _ = max;
Err("não existe aqui".into())
}
fn lock_screen(&mut self, show_when_locked: bool, turn_screen_on: bool);
fn dismiss_keyguard(&mut self);
}
pub trait BackgroundHost {
fn start(&mut self, title: &str, text: &str, kind: &str, keep_alive: bool) -> Result<(), String>;
fn stop(&mut self);
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Incoming {
Link(String),
Shared(String),
}
static INCOMING: std::sync::Mutex<Vec<Incoming>> = std::sync::Mutex::new(Vec::new());
pub fn push_incoming(item: Incoming) {
if let Ok(mut list) = INCOMING.lock() {
list.push(item);
}
}
pub fn take_incoming() -> Vec<Incoming> {
INCOMING.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
}
pub trait OffscreenService {
fn render_png(&self, width: u32, height: u32, scale: f32, background: crate::Color, paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>>;
}
#[derive(Default)]
pub struct Services {
pub offscreen: Option<Box<dyn OffscreenService>>,
pub window: Option<Box<dyn WindowService>>,
pub timer: Option<Box<dyn TimerService>>,
pub clipboard: Option<Box<dyn ClipboardService>>,
pub cursor: Option<Box<dyn CursorService>>,
pub screen: Option<Box<dyn ScreenService>>,
pub text_input: Option<Box<dyn TextInputService>>,
pub locale: Option<Box<dyn LocaleService>>,
pub text: Option<Box<dyn TextService>>,
pub resources: Option<Box<dyn ResourceService>>,
pub forms: Option<Box<dyn FormFactory>>,
pub file_dialogs: Option<Box<dyn FileDialogService>>,
pub permissions: Option<Box<dyn PermissionService>>,
pub biometrics: Option<Box<dyn BiometricService>>,
pub http: Option<Box<dyn HttpService>>,
pub notifications: Option<Box<dyn NotificationService>>,
pub links: Option<Box<dyn LinkService>>,
pub sensors: Option<Box<dyn SensorService>>,
pub background: Option<Box<dyn BackgroundHost>>,
pub phone: Option<Box<dyn PhoneService>>,
pub gamepads: Option<Box<dyn GamepadService>>,
pub printer: Option<Box<dyn PrintService>>,
pub text_assist: Option<Box<dyn crate::textassist::TextAssist>>,
pub nfc: Option<Box<dyn NfcService>>,
pub bluetooth: Option<Box<dyn BluetoothService>>,
pub push: Option<Box<dyn PushService>>,
pub actions: Option<Box<dyn ActionService>>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct NfcTag {
pub id: String,
pub tech: String,
pub records: Vec<crate::ndef::NdefRecord>,
pub writable: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NfcEvent {
Tag(NfcTag),
Written,
Error(String),
}
pub trait NfcService {
fn available(&self) -> bool;
fn enabled(&self) -> bool {
self.available()
}
fn set_reading(&mut self, on: bool);
fn write(&mut self, message: Vec<u8>);
fn cancel_write(&mut self) {}
fn poll(&mut self) -> Vec<NfcEvent>;
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BleDevice {
pub id: String,
pub name: String,
pub rssi: i32,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BleCharacteristic {
pub service: String,
pub characteristic: String,
pub properties: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BluetoothEvent {
Found(BleDevice),
ScanStopped,
Connected { device: String, services: Vec<BleCharacteristic> },
Disconnected(String),
Value { device: String, characteristic: String, data: Vec<u8> },
Written { device: String, characteristic: String },
Received { device: String, data: Vec<u8> },
Error(String),
}
pub trait BluetoothService {
fn available(&self) -> bool;
fn enabled(&self) -> bool {
self.available()
}
fn scan(&mut self, on: bool, services: Vec<String>, name: String);
fn connect(&mut self, device: &str);
fn disconnect(&mut self, device: &str);
fn read(&mut self, device: &str, service: &str, characteristic: &str);
fn write(&mut self, device: &str, service: &str, characteristic: &str, data: Vec<u8>, with_response: bool);
fn subscribe(&mut self, device: &str, service: &str, characteristic: &str, on: bool);
fn paired(&mut self) -> Vec<(String, String)> {
Vec::new()
}
fn open_serial(&mut self, device: &str) -> Result<(), String> {
let _ = device;
Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
}
fn send_serial(&mut self, device: &str, data: Vec<u8>) -> Result<(), String> {
let _ = (device, data);
Err(crate::messages::t("o Bluetooth clássico não está disponível aqui"))
}
fn close_serial(&mut self, device: &str) {
let _ = device;
}
fn poll(&mut self) -> Vec<BluetoothEvent>;
}
pub fn ble_uuid(text: &str) -> String {
let t = text.trim().trim_start_matches("0x").trim_start_matches("0X").to_ascii_lowercase();
if (t.len() == 4 || t.len() == 8) && t.chars().all(|c| c.is_ascii_hexdigit()) {
format!("{t:0>8}-0000-1000-8000-00805f9b34fb")
} else {
t
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PushMessage {
pub id: String,
pub title: String,
pub body: String,
pub data: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PushEvent {
Token(String),
Message(PushMessage),
Opened(PushMessage),
Error(String),
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PushConfig {
pub sender_id: String,
pub project_id: String,
pub app_id: String,
pub api_key: String,
pub vapid_key: String,
pub show_in_foreground: bool,
}
pub trait PushService {
fn available(&self) -> bool;
fn provider(&self) -> &'static str;
fn register(&mut self, config: &PushConfig);
fn unregister(&mut self) {}
fn shows_notifications(&self) -> bool {
true
}
fn poll(&mut self) -> Vec<PushEvent> {
Vec::new()
}
}
static PUSH_EVENTS: std::sync::Mutex<Vec<PushEvent>> = std::sync::Mutex::new(Vec::new());
pub fn push_event(event: PushEvent) {
if let Ok(mut list) = PUSH_EVENTS.lock() {
list.push(event);
}
}
pub fn take_push_events() -> Vec<PushEvent> {
PUSH_EVENTS.lock().map(|mut list| std::mem::take(&mut *list)).unwrap_or_default()
}
pub fn parse_push_line(line: &str) -> Option<PushEvent> {
let mut f = line.split('\t');
let kind = f.next()?;
let mut next = || f.next().unwrap_or_default().to_string();
match kind {
"token" => Some(PushEvent::Token(next())),
"error" => Some(PushEvent::Error(next())),
"message" | "opened" => {
let mut m = PushMessage { id: next(), title: next(), body: next(), data: next() };
if m.data.trim().is_empty() {
m.data = "{}".into();
}
Some(if kind == "message" { PushEvent::Message(m) } else { PushEvent::Opened(m) })
}
_ => None,
}
}
pub fn json_field(json: &str, key: &str) -> Option<String> {
let chars: Vec<char> = json.chars().collect();
let mut i = 0;
let skip_ws = |i: &mut usize| {
while *i < chars.len() && chars[*i].is_whitespace() {
*i += 1;
}
};
let read_string = |i: &mut usize| -> Option<String> {
if chars.get(*i) != Some(&'"') {
return None;
}
*i += 1;
let mut out = String::new();
while *i < chars.len() {
let c = chars[*i];
*i += 1;
match c {
'"' => return Some(out),
'\\' => {
let e = *chars.get(*i)?;
*i += 1;
match e {
'n' => out.push('\n'),
't' => out.push('\t'),
'r' => out.push('\r'),
'b' => out.push('\u{8}'),
'f' => out.push('\u{c}'),
'u' => {
let hex: String = chars.get(*i..*i + 4)?.iter().collect();
*i += 4;
let mut code = u32::from_str_radix(&hex, 16).ok()?;
if (0xD800..0xDC00).contains(&code) && chars.get(*i) == Some(&'\\') && chars.get(*i + 1) == Some(&'u') {
let low: String = chars.get(*i + 2..*i + 6)?.iter().collect();
if let Ok(low) = u32::from_str_radix(&low, 16) {
*i += 6;
code = 0x10000 + ((code - 0xD800) << 10) + (low.wrapping_sub(0xDC00) & 0x3FF);
}
}
out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
}
other => out.push(other),
}
}
c => out.push(c),
}
}
None
};
skip_ws(&mut i);
if chars.get(i) != Some(&'{') {
return None;
}
i += 1;
loop {
skip_ws(&mut i);
if chars.get(i) == Some(&'}') || i >= chars.len() {
return None;
}
let name = read_string(&mut i)?;
skip_ws(&mut i);
if chars.get(i) != Some(&':') {
return None;
}
i += 1;
skip_ws(&mut i);
let value = if chars.get(i) == Some(&'"') {
read_string(&mut i)?
} else {
let start = i;
let (mut depth, mut quoted) = (0i32, false);
while i < chars.len() {
let c = chars[i];
if quoted {
if c == '\\' {
i += 1;
} else if c == '"' {
quoted = false;
}
} else {
match c {
'"' => quoted = true,
'{' | '[' => depth += 1,
'}' | ']' if depth == 0 => break,
'}' | ']' => depth -= 1,
',' if depth == 0 => break,
_ => {}
}
}
i += 1;
}
chars[start..i.min(chars.len())].iter().collect::<String>().trim().to_string()
};
if name == key {
return Some(value);
}
skip_ws(&mut i);
if chars.get(i) == Some(&',') {
i += 1;
}
}
}
pub fn push_message_from_payload(text: &str) -> PushMessage {
let text = text.trim();
if !text.starts_with('{') {
return PushMessage { body: text.to_string(), data: "{}".into(), ..Default::default() };
}
let notification = json_field(text, "notification").unwrap_or_default();
let pick = |key: &str| json_field(text, key).or_else(|| json_field(¬ification, key)).unwrap_or_default();
let data = json_field(text, "data").filter(|d| d.trim_start().starts_with('{')).unwrap_or_else(|| "{}".into());
PushMessage { id: pick("id"), title: pick("title"), body: pick("body"), data }
}
pub fn render_template(template: &str, data: &str) -> String {
let mut out = String::new();
let mut rest = template;
while let Some(i) = rest.find(['{', '}']) {
out.push_str(&rest[..i]);
let tail = &rest[i..];
if tail.starts_with("{{") || tail.starts_with("}}") {
out.push_str(&tail[..1]);
rest = &tail[2..];
} else if let (true, Some(end)) = (tail.starts_with('{'), tail.find('}')) {
out.push_str(&json_field(data, tail[1..end].trim()).unwrap_or_default());
rest = &tail[end + 1..];
} else {
out.push_str(&tail[..1]);
rest = &tail[1..];
}
}
out.push_str(rest);
out
}
pub fn data_matches(filter: &str, data: &str) -> bool {
filter.split(';').map(str::trim).filter(|c| !c.is_empty()).all(|c| {
if let Some((k, v)) = c.split_once("!=") {
json_field(data, k.trim()).unwrap_or_default() != v.trim()
} else if let Some((k, v)) = c.split_once('=') {
json_field(data, k.trim()).unwrap_or_default() == v.trim()
} else {
json_field(data, c).is_some_and(|v| !v.is_empty())
}
})
}
pub fn json_quote(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 2);
out.push('"');
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ActionEvent {
pub kind: String,
pub component: String,
pub detail: String,
pub data: String,
}
pub fn parse_action_line(line: &str) -> Option<ActionEvent> {
let mut f = line.split('\t');
let kind = f.next().filter(|k| !k.is_empty())?.to_string();
let component = f.next()?.to_string();
let detail = f.next().unwrap_or_default().to_string();
let data = f.next().filter(|d| !d.trim().is_empty()).unwrap_or("{}").to_string();
Some(ActionEvent { kind, component, detail, data })
}
pub trait ActionService {
fn execute(&mut self, spec: &str, data: &str) -> Result<(), String>;
fn stop(&mut self, component: &str);
fn set_push_rules(&mut self, rules: &str);
fn poll(&mut self) -> Vec<ActionEvent>;
}
static LOCAL_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
pub fn set_local_offset_fn(f: fn(i64) -> i64) {
if let Ok(mut slot) = LOCAL_OFFSET.write() {
*slot = Some(f);
}
}
static PROJECT_OFFSET: std::sync::RwLock<Option<fn(i64) -> i64>> = std::sync::RwLock::new(None);
pub fn set_project_offset_fn(f: Option<fn(i64) -> i64>) {
if let Ok(mut slot) = PROJECT_OFFSET.write() {
*slot = f;
}
}
pub fn local_offset(utc: i64) -> i64 {
let project = PROJECT_OFFSET.read().ok().and_then(|f| *f);
project.or_else(|| LOCAL_OFFSET.read().ok().and_then(|f| *f)).map_or(0, |f| f(utc))
}