pub use linkme;
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Support {
Native,
Emulated,
#[default]
Unsupported,
}
pub mod ffi_guard {
use std::sync::OnceLock;
static RECOVERY: OnceLock<fn()> = OnceLock::new();
pub fn set_recovery(f: fn()) {
let _ = RECOVERY.set(f);
}
pub fn contain<R>(default: R, f: impl FnOnce() -> R) -> R {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
Ok(r) => r,
Err(payload) => {
let msg = payload
.downcast_ref::<&str>()
.map(std::string::ToString::to_string)
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "<non-string panic>".into());
log::error!("panic contained at an FFI boundary: {msg}");
if let Some(recover) = RECOVERY.get() {
recover();
}
default
}
}
}
}
pub mod services {
use std::sync::Once;
pub struct Service {
pub name: &'static str,
pub initialize: fn(),
}
#[cfg(not(target_arch = "wasm32"))]
#[linkme::distributed_slice]
pub static SERVICES: [Service];
pub fn initialize() {
static ONCE: Once = Once::new();
ONCE.call_once(|| {
#[cfg(not(target_arch = "wasm32"))]
for service in SERVICES {
(service.initialize)();
}
});
}
#[derive(Clone)]
pub enum NotificationEvent {
Registered(Vec<u8>),
RegistrationFailed(String),
Received { payload: String, opened: bool },
}
impl std::fmt::Debug for NotificationEvent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Registered(_) => f.debug_tuple("Registered").finish_non_exhaustive(),
Self::RegistrationFailed(error) => {
f.debug_tuple("RegistrationFailed").field(error).finish()
}
Self::Received { opened, .. } => f
.debug_struct("Received")
.field("opened", opened)
.finish_non_exhaustive(),
}
}
}
#[cfg(not(target_arch = "wasm32"))]
#[linkme::distributed_slice]
pub static NOTIFICATION_HANDLERS: [fn(&NotificationEvent)];
#[expect(
clippy::needless_pass_by_value,
reason = "public signature; toolkits hand over the event they built"
)]
pub fn notification(event: NotificationEvent) {
#[cfg(not(target_arch = "wasm32"))]
for handler in NOTIFICATION_HANDLERS {
handler(&event);
}
#[cfg(target_arch = "wasm32")]
let _ = event;
}
}
pub mod routes {
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
static REQUESTED: Mutex<Option<String>> = Mutex::new(None);
static NOTIFIER: OnceLock<fn()> = OnceLock::new();
fn slot() -> MutexGuard<'static, Option<String>> {
REQUESTED.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn request(route: &str) {
if route.is_empty() {
return;
}
*slot() = Some(route.to_owned());
if let Some(notify) = NOTIFIER.get() {
notify();
}
}
#[must_use]
pub fn requested() -> Option<String> {
slot().clone()
}
#[must_use]
pub fn take() -> Option<String> {
slot().take()
}
pub fn set_notifier(notify: fn()) {
let _ = NOTIFIER.set(notify);
}
}
pub mod storage {
use std::path::PathBuf;
#[must_use]
pub fn app_id() -> String {
std::env::var("DAY_APP_ID")
.ok()
.filter(|id| !id.is_empty())
.or_else(|| {
option_env!("DAY_APP_ID")
.filter(|id| !id.is_empty())
.map(str::to_owned)
})
.or_else(|| {
let exe = std::env::current_exe().ok()?;
exe.file_stem()?.to_str().map(str::to_owned)
})
.map_or_else(|| "day-app".to_owned(), |id| folder_name(&id))
}
#[must_use]
pub fn data_dir() -> Option<PathBuf> {
resolve(Dir::Data, Os::HOST, &app_id(), &env_path)
}
#[must_use]
pub fn data_dir_for(app_id: &str) -> Option<PathBuf> {
resolve(Dir::Data, Os::HOST, &folder_name(app_id), &env_path)
}
#[must_use]
pub fn cache_dir() -> Option<PathBuf> {
resolve(Dir::Cache, Os::HOST, &app_id(), &env_path)
}
#[must_use]
pub fn config_dir() -> Option<PathBuf> {
resolve(Dir::Config, Os::HOST, &app_id(), &env_path)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Dir {
Data,
Cache,
Config,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Os {
Apple,
Windows,
Hosted,
Unix,
Web,
}
impl Os {
const HOST: Os = if cfg!(any(target_os = "macos", target_os = "ios")) {
Os::Apple
} else if cfg!(target_os = "windows") {
Os::Windows
} else if cfg!(any(target_os = "android", target_env = "ohos")) {
Os::Hosted
} else if cfg!(target_family = "wasm") {
Os::Web
} else {
Os::Unix
};
}
fn env_path(name: &str) -> Option<PathBuf> {
let path = PathBuf::from(std::env::var_os(name)?);
path.is_absolute().then_some(path)
}
fn folder_name(id: &str) -> String {
let name: String = id
.chars()
.map(|c| match c {
'/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_',
c if c.is_control() => '_',
c => c,
})
.collect();
match name.trim() {
"" | "." | ".." => "day-app".to_owned(),
name => name.to_owned(),
}
}
fn resolve(
dir: Dir,
os: Os,
id: &str,
var: &dyn Fn(&str) -> Option<PathBuf>,
) -> Option<PathBuf> {
if dir == Dir::Cache
&& let Some(cache) = var("DAY_CACHE_DIR")
{
return Some(cache);
}
if let Some(data) = var("DAY_DATA_DIR") {
return Some(match dir {
Dir::Data => data,
Dir::Cache => data.join("cache"),
Dir::Config => data.join("config"),
});
}
let home = || var("HOME");
match os {
Os::Apple => {
let library = home()?.join("Library");
let base = match dir {
Dir::Data | Dir::Config => library.join("Application Support"),
Dir::Cache => library.join("Caches"),
};
Some(base.join(id))
}
Os::Windows => {
let profile = |leaf: &str| Some(var("USERPROFILE")?.join("AppData").join(leaf));
let local = || var("LOCALAPPDATA").or_else(|| profile("Local"));
match dir {
Dir::Data => Some(local()?.join(id)),
Dir::Cache => Some(local()?.join(id).join("cache")),
Dir::Config => Some(var("APPDATA").or_else(|| profile("Roaming"))?.join(id)),
}
}
Os::Unix => {
let (xdg, fallback) = match dir {
Dir::Data => ("XDG_DATA_HOME", ".local/share"),
Dir::Cache => ("XDG_CACHE_HOME", ".cache"),
Dir::Config => ("XDG_CONFIG_HOME", ".config"),
};
Some(var(xdg).or_else(|| Some(home()?.join(fallback)))?.join(id))
}
Os::Hosted | Os::Web => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn at(os: Os, dir: Dir, vars: &[(&str, &str)]) -> Option<String> {
let vars: HashMap<&str, &str> = vars.iter().copied().collect();
let var = |name: &str| vars.get(name).map(PathBuf::from);
resolve(dir, os, "dev.example.notes", &var).map(|p| {
let text = p.display().to_string();
if os == Os::Windows {
text
} else {
text.replace('\\', "/")
}
})
}
#[test]
fn apple_uses_library_folders_named_for_the_app() {
let home = [("HOME", "/Users/ada"), ("XDG_DATA_HOME", "/Users/ada/.xdg")];
let support = "/Users/ada/Library/Application Support/dev.example.notes";
assert_eq!(at(Os::Apple, Dir::Data, &home).as_deref(), Some(support));
assert_eq!(at(Os::Apple, Dir::Config, &home).as_deref(), Some(support));
assert_eq!(
at(Os::Apple, Dir::Cache, &home).as_deref(),
Some("/Users/ada/Library/Caches/dev.example.notes")
);
let container = [(
"HOME",
"/Users/ada/Library/Containers/dev.example.notes/Data",
)];
assert_eq!(
at(Os::Apple, Dir::Data, &container).as_deref(),
Some(
"/Users/ada/Library/Containers/dev.example.notes/Data/Library/Application Support/dev.example.notes"
)
);
}
#[test]
fn windows_keeps_data_local_and_settings_roaming() {
let vars = [
("LOCALAPPDATA", r"C:\Users\ada\AppData\Local"),
("APPDATA", r"C:\Users\ada\AppData\Roaming"),
];
let data = at(Os::Windows, Dir::Data, &vars).unwrap_or_default();
assert!(data.starts_with(r"C:\Users\ada\AppData\Local"), "{data}");
assert!(data.ends_with("dev.example.notes"), "{data}");
let cache = at(Os::Windows, Dir::Cache, &vars).unwrap_or_default();
assert!(cache.ends_with("cache"), "{cache}");
let config = at(Os::Windows, Dir::Config, &vars).unwrap_or_default();
assert!(
config.starts_with(r"C:\Users\ada\AppData\Roaming"),
"{config}"
);
}
#[test]
fn unix_follows_xdg_then_home() {
let xdg = [
("HOME", "/home/ada"),
("XDG_DATA_HOME", "/data"),
("XDG_CACHE_HOME", "/cache"),
("XDG_CONFIG_HOME", "/config"),
];
assert_eq!(
at(Os::Unix, Dir::Data, &xdg).as_deref(),
Some("/data/dev.example.notes")
);
assert_eq!(
at(Os::Unix, Dir::Cache, &xdg).as_deref(),
Some("/cache/dev.example.notes")
);
assert_eq!(
at(Os::Unix, Dir::Config, &xdg).as_deref(),
Some("/config/dev.example.notes")
);
let home = [("HOME", "/home/ada")];
assert_eq!(
at(Os::Unix, Dir::Data, &home).as_deref(),
Some("/home/ada/.local/share/dev.example.notes")
);
assert_eq!(
at(Os::Unix, Dir::Cache, &home).as_deref(),
Some("/home/ada/.cache/dev.example.notes")
);
assert_eq!(
at(Os::Unix, Dir::Config, &home).as_deref(),
Some("/home/ada/.config/dev.example.notes")
);
}
#[test]
fn hosts_and_tests_override_every_platform() {
let host = [
("DAY_DATA_DIR", "/data/user/0/dev.example.notes/files"),
("DAY_CACHE_DIR", "/data/user/0/dev.example.notes/cache"),
];
for os in [Os::Hosted, Os::Apple, Os::Windows, Os::Unix] {
assert_eq!(
at(os, Dir::Data, &host).as_deref(),
Some("/data/user/0/dev.example.notes/files")
);
assert_eq!(
at(os, Dir::Cache, &host).as_deref(),
Some("/data/user/0/dev.example.notes/cache")
);
}
let scratch = [("HOME", "/Users/ada"), ("DAY_DATA_DIR", "/tmp/run")];
assert_eq!(
at(Os::Apple, Dir::Cache, &scratch).as_deref(),
Some("/tmp/run/cache")
);
assert_eq!(
at(Os::Apple, Dir::Config, &scratch).as_deref(),
Some("/tmp/run/config")
);
assert_eq!(at(Os::Hosted, Dir::Data, &[("HOME", "/")]), None);
assert_eq!(at(Os::Web, Dir::Data, &[("HOME", "/")]), None);
}
#[test]
fn app_ids_become_one_folder_name() {
assert_eq!(folder_name("dev.daybrite.news"), "dev.daybrite.news");
assert_eq!(folder_name("a/b\\c:d"), "a_b_c_d");
assert_eq!(folder_name(".."), "day-app");
assert_eq!(folder_name(""), "day-app");
}
}
}