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);
fn set_content(&mut self, content: &crate::clipboard::ClipboardContent) {
self.set_text(content.text.as_deref().unwrap_or(""));
}
fn get_html(&mut self) -> Option<String> {
None
}
fn get_image(&mut self) -> Option<crate::Image> {
None
}
fn get_data(&mut self, _format: &str) -> Option<Vec<u8>> {
None
}
fn has(&mut self, format: &str) -> bool {
match format {
crate::clipboard::HTML => self.get_html().is_some(),
crate::clipboard::IMAGE => self.get_image().is_some(),
_ => self.get_data(format).is_some(),
}
}
fn sequence(&mut self) -> Option<u64> {
None
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CursorShape {
#[default]
Default,
Pointer,
Text,
Wait,
Crosshair,
Move,
NotAllowed,
ResizeHorizontal,
ResizeVertical,
ResizeNeSw,
ResizeNwSe,
Grab,
Grabbing,
None,
}
impl CursorShape {
pub const ALL: [CursorShape; 14] = [
CursorShape::Default,
CursorShape::Pointer,
CursorShape::Text,
CursorShape::Wait,
CursorShape::Crosshair,
CursorShape::Move,
CursorShape::NotAllowed,
CursorShape::ResizeHorizontal,
CursorShape::ResizeVertical,
CursorShape::ResizeNeSw,
CursorShape::ResizeNwSe,
CursorShape::Grab,
CursorShape::Grabbing,
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",
"grab",
"grabbing",
"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 owner: Option<crate::ComponentId>,
}
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})")));
}
fn can_register_schemes(&self) -> bool {
false
}
fn register_scheme(&mut self, scheme: &str, description: &str) -> Result<(), String> {
let _ = description;
Err(format!("registrar o prefixo {scheme}:// em execução não existe aqui (vai na publicação)"))
}
fn unregister_scheme(&mut self, scheme: &str) -> Result<(), String> {
Err(format!("tirar o registro do prefixo {scheme}:// não existe aqui"))
}
fn scheme_registered(&mut self, scheme: &str) -> bool {
let _ = scheme;
false
}
fn receive_links(&mut self, on_link: Box<dyn Fn(String) + Send>) {
let _ = on_link;
}
}
const RESERVED_SCHEMES: &[&str] = &[
"http", "https", "file", "ftp", "ftps", "mailto", "tel", "sms", "data", "javascript", "vbscript", "about", "blob", "ws", "wss", "shell", "search",
"search-ms", "res", "its", "mk", "hcp", "callto", "news", "nntp", "telnet", "ldap", "ssh", "sftp", "smb", "git", "magnet", "steam", "zoommtg",
];
pub fn check_scheme(scheme: &str) -> Result<String, String> {
let s = scheme.trim().trim_end_matches("://").trim_end_matches(':').to_ascii_lowercase();
let valid = s.len() >= 3
&& s.len() <= 64
&& s.starts_with(|c: char| c.is_ascii_lowercase())
&& s.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '+' | '-' | '.'));
if !valid {
return Err(crate::messages::tf("prefixo inválido: {0} (letras, números, + - ., de 3 a 64)", &[&scheme]));
}
if RESERVED_SCHEMES.contains(&s.as_str()) || s.starts_with("ms-") || s.starts_with("microsoft") || s.starts_with("windows") {
return Err(crate::messages::tf("o prefixo {0} é do sistema", &[&s]));
}
Ok(s)
}
static STARTUP_LINKS: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
pub fn push_startup_link(url: String) {
if let Ok(mut list) = STARTUP_LINKS.lock() {
list.push(url);
}
}
pub fn take_startup_links(scheme: &str) -> Vec<String> {
let Ok(mut list) = STARTUP_LINKS.lock() else { return Vec::new() };
let (mine, rest): (Vec<String>, Vec<String>) = std::mem::take(&mut *list).into_iter().partition(|url| link_scheme(url).as_deref() == Some(scheme));
*list = rest;
mine
}
pub fn link_scheme(url: &str) -> Option<String> {
let (scheme, _) = url.split_once(':')?;
(!scheme.is_empty()).then(|| scheme.to_ascii_lowercase())
}
#[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>>;
fn render_rgba(&self, _width: u32, _height: u32, _scale: f32, _background: crate::Color, _paint: &mut dyn FnMut(&mut dyn crate::Canvas)) -> Option<Vec<u8>> {
None
}
fn render_area_rgba(
&self,
_width: u32,
_height: u32,
_background: crate::Color,
_over: Option<(&[u8], crate::geometry::RectF)>,
_paint: &mut dyn FnMut(&mut dyn crate::Canvas),
) -> Option<Vec<u8>> {
None
}
}
pub trait WindowCaptureService {
fn capture(&mut self, form: crate::ComponentId) -> Option<(u32, u32, Vec<u8>)>;
}
#[derive(Default)]
pub struct Services {
pub window_capture: Option<Box<dyn WindowCaptureService>>,
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 clipboard_local: crate::clipboard::LocalClipboard,
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>>,
pub ole: Option<Box<dyn OleService>>,
pub wmi: Option<Box<dyn WmiService>>,
}
#[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>;
}
#[derive(Clone, Debug, PartialEq)]
pub enum OleValue {
Null,
Bool(bool),
Int(i64),
Float(f64),
String(String),
Date(f64),
Object(u64),
Array(Vec<Vec<OleValue>>),
}
pub trait OleService {
fn create(&mut self, prog_id: &str, running: bool) -> Result<u64, String>;
fn invoke(&mut self, object: u64, name: &str, args: Vec<OleValue>) -> Result<OleValue, String>;
fn put(&mut self, object: u64, name: &str, args: Vec<OleValue>, value: OleValue) -> Result<(), String>;
fn release(&mut self, object: u64);
fn set_timeout(&mut self, seconds: f64) {
let _ = seconds;
}
fn releaser(&self) -> Option<OleReleaser> {
None
}
}
pub type OleReleaser = std::sync::Arc<dyn Fn(u64) + Send + Sync>;
static OLE_ALLOWED: std::sync::RwLock<Vec<String>> = std::sync::RwLock::new(Vec::new());
pub const OLE_DEFAULT: &[&str] = &["Excel.Application", "Word.Application", "Outlook.Application", "PowerPoint.Application"];
pub fn allow_ole(prog_id: &str) {
if let Ok(mut list) = OLE_ALLOWED.write() {
if !list.iter().any(|p| p.eq_ignore_ascii_case(prog_id)) {
list.push(prog_id.to_string());
}
}
}
pub fn ole_allowed(prog_id: &str) -> bool {
let id = prog_id.trim();
let base = match id.rsplit_once('.') {
Some((head, tail)) if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) => head,
_ => id,
};
let ok = |p: &str| p.eq_ignore_ascii_case(base) || p.eq_ignore_ascii_case(id);
OLE_DEFAULT.iter().any(|p| ok(p)) || OLE_ALLOWED.read().is_ok_and(|l| l.iter().any(|p| ok(p)))
}
pub fn ole_date(year: i32, month: u32, day: u32, hour: u32, minute: u32, second: u32) -> f64 {
let y = i64::from(year) - i64::from(month <= 2);
let era = y.div_euclid(400);
let yoe = y - era * 400;
let m = i64::from(month);
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(day) - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468 + 25_569;
days as f64 + f64::from(hour * 3600 + minute * 60 + second) / 86_400.0
}
pub fn ole_date_parts(date: f64) -> (i32, u32, u32, u32, u32, u32) {
let mut days = date.floor() as i64;
let mut secs = ((date - date.floor()) * 86_400.0).round() as i64;
if secs >= 86_400 {
days += 1;
secs -= 86_400;
}
let z = days - 25_569 + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
let year = (yoe + era * 400 + i64::from(month <= 2)) as i32;
(year, month, day, (secs / 3600) as u32, (secs % 3600 / 60) as u32, (secs % 60) as u32)
}
#[derive(Clone, Debug, PartialEq)]
pub enum WmiValue {
Null,
Bool(bool),
Int(i64),
Float(f64),
String(String),
DateTime(String),
Array(Vec<WmiValue>),
Object(Vec<(String, WmiValue)>),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WmiType {
#[default]
String,
Integer,
Float,
Boolean,
DateTime,
Array,
Object,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct WmiColumn {
pub name: String,
pub kind: WmiType,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WmiTable {
pub columns: Vec<WmiColumn>,
pub rows: Vec<Vec<WmiValue>>,
}
pub type WmiDone = Box<dyn FnOnce(Result<WmiTable, String>) + Send>;
pub type WmiListener = std::sync::Arc<dyn Fn(Result<Vec<(String, WmiValue)>, String>) + Send + Sync>;
pub struct WmiWatch(Option<Box<dyn FnOnce() + Send>>);
impl WmiWatch {
pub fn new(stop: impl FnOnce() + Send + 'static) -> Self {
Self(Some(Box::new(stop)))
}
}
impl Drop for WmiWatch {
fn drop(&mut self) {
if let Some(stop) = self.0.take() {
stop();
}
}
}
pub trait WmiService {
fn query(&mut self, namespace: &str, wql: &str, done: WmiDone);
fn watch(&mut self, namespace: &str, wql: &str, listener: WmiListener) -> Result<WmiWatch, String>;
}
pub fn wmi_namespace(namespace: &str) -> Result<String, String> {
let ns = namespace.trim().replace('/', "\\");
let ns = if ns.is_empty() { "root\\cimv2".to_string() } else { ns };
let valid = ns.split('\\').all(|p| !p.is_empty() && p.chars().all(|c| c.is_alphanumeric() || c == '_'));
if !valid || !ns.split('\\').next().is_some_and(|r| r.eq_ignore_ascii_case("root")) {
return Err(crate::messages::tf("namespace do WMI inválido '{0}' (só desta máquina, como root\\cimv2)", &[&namespace]));
}
Ok(ns)
}
pub fn wmi_datetime(text: &str) -> Option<String> {
let t = text.trim();
let b = t.as_bytes();
if b.len() < 14 || !b[..14].iter().all(u8::is_ascii_digit) || b.get(21) == Some(&b':') {
return None;
}
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]);
let month: u32 = mo.parse().ok()?;
let day: u32 = d.parse().ok()?;
if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
return None;
}
Some(format!("{y}-{mo}-{d}T{h}:{mi}:{s}"))
}
pub fn wmi_select_list(wql: &str) -> Vec<String> {
let t = wql.trim();
let lower = t.to_ascii_lowercase();
let (Some(rest), Some(from)) = (lower.strip_prefix("select"), lower.find(" from ")) else { return Vec::new() };
let start = t.len() - rest.len();
if from < start {
return Vec::new();
}
t[start..from].split(',').map(str::trim).filter(|n| !n.is_empty() && *n != "*").map(str::to_string).collect()
}
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))
}