Nacre/src/util.rs
astar76 2d8323a3e0 Nacre on Servo: first complete, reviewed, not yet built version
Everything in Rust on Servo 0.7 (trimmed: no WebXR, WebGPU, multiprocess):
tabs and windows, address bar with suggestions, history, bookmarks and
reading list, downloads with resume and external download managers,
encrypted password vault with autofill, ad blocker (adblock-rust, 22 lists),
VPN through Tor or a proxy and secure DNS via a local bridge proxy,
picture in picture, Discord Rich Presence, media player and visualizer,
spell check, site apps, user scripts and styles, import from other
browsers, gamepads, Web Bluetooth, and every setting of the original Nacre
in a plain egui interface.

Not compiled yet; docs/HANDOFF.md has the first build checklist.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-11 06:08:36 -06:00

497 lines
18 KiB
Rust

//! Small helpers shared by everything: time, files, text, URLs.
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::Serialize;
use serde::de::DeserializeOwned;
use url::Url;
/// Seconds since the Unix epoch.
pub fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// Milliseconds since the Unix epoch.
pub fn now_ms() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
}
/// Fill `buf` with random bytes from the operating system.
pub fn random_bytes(buf: &mut [u8]) {
if getrandom::fill(buf).is_err() {
// The OS source failing is close to impossible; fall back to something that still
// varies between runs so tokens are never constant.
let mut seed = now_ms() ^ (std::process::id() as u64).rotate_left(32);
for b in buf.iter_mut() {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
*b = seed as u8;
}
}
}
/// A random lowercase hex string of `bytes * 2` characters.
pub fn random_hex(bytes: usize) -> String {
let mut buf = vec![0u8; bytes];
random_bytes(&mut buf);
hex(&buf)
}
pub fn hex(data: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(data.len() * 2);
for b in data {
out.push(DIGITS[(b >> 4) as usize] as char);
out.push(DIGITS[(b & 15) as usize] as char);
}
out
}
/// A random integer in `0..n` (n > 0).
pub fn random_below(n: usize) -> usize {
let mut buf = [0u8; 8];
random_bytes(&mut buf);
(u64::from_le_bytes(buf) % n.max(1) as u64) as usize
}
/// Read a JSON file; a missing or broken file gives the default.
pub fn load_json<T: DeserializeOwned + Default>(path: &Path) -> T {
match fs::read(path) {
Ok(bytes) => match serde_json::from_slice(&bytes) {
Ok(value) => value,
Err(error) => {
log::warn!("{}: unreadable ({error}); keeping a copy as .bad", path.display());
let _ = fs::copy(path, path.with_extension("bad"));
T::default()
},
},
Err(_) => T::default(),
}
}
/// Write a JSON file through a temporary file so a crash never leaves half a file.
pub fn save_json<T: Serialize>(path: &Path, value: &T) -> std::io::Result<()> {
let bytes = serde_json::to_vec_pretty(value).map_err(std::io::Error::other)?;
write_atomic(path, &bytes, false)
}
/// Like [`save_json`] but the file is readable by the owner only.
pub fn save_json_private<T: Serialize>(path: &Path, value: &T) -> std::io::Result<()> {
let bytes = serde_json::to_vec_pretty(value).map_err(std::io::Error::other)?;
write_atomic(path, &bytes, true)
}
pub fn write_atomic(path: &Path, bytes: &[u8], private: bool) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let mut tmp = path.as_os_str().to_owned();
tmp.push(".tmp");
let tmp = PathBuf::from(tmp);
{
let mut options = fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
if private {
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
#[cfg(not(unix))]
let _ = private;
let mut file = options.open(&tmp)?;
file.write_all(bytes)?;
file.sync_all().ok();
}
fs::rename(&tmp, path)
}
/// Offset of local time from UTC in seconds, for the given Unix time.
pub fn local_offset(at: u64) -> i64 {
#[cfg(unix)]
{
let t = at as libc::time_t;
let mut out: libc::tm = unsafe { std::mem::zeroed() };
// SAFETY: both pointers are valid for the call; localtime_r writes only into `out`.
let ok = unsafe { !libc::localtime_r(&t, &mut out).is_null() };
if ok { out.tm_gmtoff as i64 } else { 0 }
}
#[cfg(not(unix))]
{
let _ = at;
0
}
}
/// Broken-down local time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DateTime {
pub year: i64,
pub month: u32,
pub day: u32,
pub hour: u32,
pub minute: u32,
pub second: u32,
/// 0 = Monday
pub weekday: u32,
}
/// Convert a Unix time to local date and time (proleptic Gregorian).
pub fn local_time(at: u64) -> DateTime {
let t = at as i64 + local_offset(at);
let days = t.div_euclid(86_400);
let secs = t.rem_euclid(86_400);
// Howard Hinnant's civil_from_days.
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1_460 + 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 + if month <= 2 { 1 } else { 0 };
DateTime {
year,
month,
day,
hour: (secs / 3600) as u32,
minute: (secs % 3600 / 60) as u32,
second: (secs % 60) as u32,
weekday: (days + 3).rem_euclid(7) as u32,
}
}
const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const WEEKDAYS: [&str; 7] = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
/// "14:03"
pub fn format_clock(at: u64) -> String {
let t = local_time(at);
format!("{:02}:{:02}", t.hour, t.minute)
}
/// "10 Nov 2026"
pub fn format_date(at: u64) -> String {
let t = local_time(at);
format!("{} {} {}", t.day, MONTHS[(t.month - 1) as usize], t.year)
}
/// "Today", "Yesterday", or "Tuesday, 10 Nov 2026".
pub fn format_day_heading(at: u64) -> String {
let today = local_day(now());
let day = local_day(at);
if day == today {
"Today".to_owned()
} else if day + 1 == today {
"Yesterday".to_owned()
} else {
let t = local_time(at);
format!("{}, {}", WEEKDAYS[t.weekday as usize], format_date(at))
}
}
/// Day number in local time, for grouping entries by day.
pub fn local_day(at: u64) -> i64 {
(at as i64 + local_offset(at)).div_euclid(86_400)
}
/// "2026-11-10 14:03"
pub fn format_stamp(at: u64) -> String {
let t = local_time(at);
format!("{:04}-{:02}-{:02} {:02}:{:02}", t.year, t.month, t.day, t.hour, t.minute)
}
/// "3 min ago", "2 h ago", "5 days ago".
pub fn format_ago(at: u64) -> String {
let d = now().saturating_sub(at);
match d {
0..=59 => "just now".to_owned(),
60..=3_599 => format!("{} min ago", d / 60),
3_600..=86_399 => format!("{} h ago", d / 3_600),
86_400..=172_799 => "yesterday".to_owned(),
_ => format!("{} days ago", d / 86_400),
}
}
/// "1.4 MB"
pub fn format_bytes(n: u64) -> String {
const UNITS: [&str; 5] = ["B", "kB", "MB", "GB", "TB"];
let mut value = n as f64;
let mut unit = 0;
while value >= 1000.0 && unit < UNITS.len() - 1 {
value /= 1000.0;
unit += 1;
}
if unit == 0 { format!("{n} B") } else if value >= 100.0 { format!("{value:.0} {}", UNITS[unit]) } else { format!("{value:.1} {}", UNITS[unit]) }
}
/// "1 h 05 min", "3 min 20 s", "12 s"
pub fn format_duration(secs: u64) -> String {
if secs >= 3600 {
format!("{} h {:02} min", secs / 3600, secs % 3600 / 60)
} else if secs >= 60 {
format!("{} min {:02} s", secs / 60, secs % 60)
} else {
format!("{secs} s")
}
}
/// "3:07" or "1:02:45" for media positions.
pub fn format_media_time(secs: f64) -> String {
if !secs.is_finite() || secs < 0.0 {
return "0:00".to_owned();
}
let s = secs as u64;
if s >= 3600 { format!("{}:{:02}:{:02}", s / 3600, s % 3600 / 60, s % 60) } else { format!("{}:{:02}", s / 60, s % 60) }
}
/// Host of a URL without a leading "www.".
pub fn host_of(url: &Url) -> String {
let host = url.host_str().unwrap_or("");
host.strip_prefix("www.").unwrap_or(host).to_ascii_lowercase()
}
pub fn host_of_str(url: &str) -> String {
Url::parse(url).map(|u| host_of(&u)).unwrap_or_default()
}
/// True when `host` is `domain` or a subdomain of it.
pub fn host_matches(host: &str, domain: &str) -> bool {
let host = host.trim_start_matches("www.");
let domain = domain.trim_start_matches("www.");
!domain.is_empty() && (host == domain || (host.len() > domain.len() && host.ends_with(domain) && host.as_bytes()[host.len() - domain.len() - 1] == b'.'))
}
/// The last two labels of a host ("music.youtube.com" -> "youtube.com"). Good enough for grouping;
/// the ad blocker does the exact public-suffix work itself.
pub fn base_domain(host: &str) -> String {
if host.parse::<std::net::IpAddr>().is_ok() {
return host.to_owned();
}
let labels: Vec<&str> = host.split('.').filter(|l| !l.is_empty()).collect();
if labels.len() <= 2 {
return labels.join(".");
}
// Common two-part suffixes such as co.uk, com.au.
let last = labels[labels.len() - 1];
let second = labels[labels.len() - 2];
let two_part = last.len() == 2 && matches!(second, "co" | "com" | "net" | "org" | "gov" | "edu" | "ac");
let keep = if two_part { 3 } else { 2 };
labels[labels.len() - keep.min(labels.len())..].join(".")
}
/// Percent-encode text for use inside a query string.
pub fn encode_query(text: &str) -> String {
url::form_urlencoded::byte_serialize(text.as_bytes()).collect()
}
/// Turn what was typed in the address bar into a URL: a URL as is, a host gets https://,
/// anything else becomes a search with `search_template` (which contains `%s`).
pub fn address_to_url(input: &str, search_template: &str) -> Option<Url> {
let text = input.trim();
if text.is_empty() {
return None;
}
let lower = text.to_ascii_lowercase();
if lower.starts_with("nacre:") || lower.starts_with("about:") || lower.starts_with("data:") || lower.starts_with("file:") || lower.starts_with("view-source:") {
return Url::parse(text).ok();
}
if lower.starts_with("http://") || lower.starts_with("https://") {
return Url::parse(text).ok();
}
if text.starts_with('/') || text.starts_with("~/") {
let path = if let Some(rest) = text.strip_prefix("~/") { dirs::home_dir().map(|h| h.join(rest)) } else { Some(PathBuf::from(text)) };
if let Some(path) = path
&& path.exists()
{
return Url::from_file_path(path).ok();
}
}
let looks_like_host = !text.contains(char::is_whitespace)
&& (lower.starts_with("localhost") || text.parse::<std::net::IpAddr>().is_ok() || {
let host_part = text.split(['/', '?', '#']).next().unwrap_or("");
let host_only = host_part.rsplit_once('@').map(|(_, h)| h).unwrap_or(host_part);
let host_only = host_only.split(':').next().unwrap_or("");
host_only.contains('.') && !host_only.starts_with('.') && !host_only.ends_with('.') && host_only.rsplit('.').next().is_some_and(|tld| tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic()) || host_only.parse::<std::net::Ipv4Addr>().is_ok())
});
if looks_like_host {
// http for local names, https for everything else; HTTPS-only mode upgrades later anyway.
let local = lower.starts_with("localhost") || lower.starts_with("127.") || lower.starts_with("192.168.") || lower.starts_with("10.") || lower.starts_with("[::1]");
let scheme = if local { "http" } else { "https" };
if let Ok(url) = Url::parse(&format!("{scheme}://{text}")) {
return Some(url);
}
}
Url::parse(&search_template.replace("%s", &encode_query(text))).ok()
}
/// A file name that is safe on every platform, never empty.
pub fn safe_file_name(name: &str) -> String {
let cleaned: String = name
.chars()
.map(|c| if c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') { '_' } else { c })
.collect();
let cleaned = cleaned.trim().trim_matches('.').trim();
let cleaned: String = cleaned.chars().take(180).collect();
if cleaned.is_empty() { "download".to_owned() } else { cleaned }
}
/// File name suggested by a URL's last path segment.
pub fn file_name_from_url(url: &Url) -> String {
let segment = url.path_segments().and_then(|mut s| s.next_back().map(str::to_owned)).unwrap_or_default();
let decoded = percent_decode(&segment);
if decoded.is_empty() { safe_file_name(&host_of(url)) } else { safe_file_name(&decoded) }
}
pub fn percent_decode(text: &str) -> String {
let bytes = text.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
let hi = (bytes[i + 1] as char).to_digit(16);
let lo = (bytes[i + 2] as char).to_digit(16);
if let (Some(hi), Some(lo)) = (hi, lo) {
out.push((hi * 16 + lo) as u8);
i += 3;
continue;
}
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// Pick a path in `dir` for `name` that does not exist yet: "file.zip", "file (1).zip", ...
pub fn unused_path(dir: &Path, name: &str) -> PathBuf {
let first = dir.join(name);
if !first.exists() {
return first;
}
let (stem, ext) = match name.rsplit_once('.') {
Some((stem, ext)) if !stem.is_empty() && ext.len() <= 8 => (stem.to_owned(), format!(".{ext}")),
_ => (name.to_owned(), String::new()),
};
for n in 1..10_000 {
let candidate = dir.join(format!("{stem} ({n}){ext}"));
if !candidate.exists() {
return candidate;
}
}
dir.join(format!("{stem} ({}){ext}", random_hex(4)))
}
/// Escape text for use inside a JavaScript string literal (JSON string, with the quotes).
pub fn js_string(text: &str) -> String {
// JSON is a subset of JavaScript string syntax except for U+2028/2029, which are escaped too.
serde_json::to_string(text).unwrap_or_else(|_| "\"\"".to_owned()).replace('\u{2028}', "\\u2028").replace('\u{2029}', "\\u2029")
}
/// Escape text for HTML.
pub fn html_escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
_ => out.push(c),
}
}
out
}
/// Shorten text to `max` characters with an ellipsis.
pub fn ellipsize(text: &str, max: usize) -> String {
if text.chars().count() <= max {
text.to_owned()
} else {
let mut out: String = text.chars().take(max.saturating_sub(1)).collect();
out.push('…');
out
}
}
/// Open a file, folder or URL with the system's default program.
pub fn open_external(target: &str) -> bool {
#[cfg(target_os = "windows")]
let result = std::process::Command::new("cmd").args(["/C", "start", "", target]).spawn();
#[cfg(target_os = "macos")]
let result = std::process::Command::new("open").arg(target).spawn();
#[cfg(all(unix, not(target_os = "macos")))]
let result = std::process::Command::new("xdg-open").arg(target).spawn();
result.is_ok()
}
/// Find a program on PATH.
pub fn which(program: &str) -> Option<PathBuf> {
let direct = Path::new(program);
if direct.components().count() > 1 {
return direct.is_file().then(|| direct.to_owned());
}
let path = std::env::var_os("PATH")?;
for dir in std::env::split_paths(&path) {
let candidate = dir.join(program);
if candidate.is_file() {
return Some(candidate);
}
#[cfg(windows)]
{
let exe = dir.join(format!("{program}.exe"));
if exe.is_file() {
return Some(exe);
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
const DDG: &str = "https://duckduckgo.com/?q=%s";
#[test]
fn address_bar_input() {
assert_eq!(address_to_url("example.com", DDG).unwrap().as_str(), "https://example.com/");
assert_eq!(address_to_url("http://a.b/c", DDG).unwrap().as_str(), "http://a.b/c");
assert_eq!(address_to_url("localhost:8080", DDG).unwrap().as_str(), "http://localhost:8080/");
assert_eq!(address_to_url("rust egui", DDG).unwrap().as_str(), "https://duckduckgo.com/?q=rust+egui");
assert_eq!(address_to_url("what is 1.5", DDG).unwrap().host_str(), Some("duckduckgo.com"));
assert_eq!(address_to_url("nacre://settings", DDG).unwrap().scheme(), "nacre");
assert!(address_to_url(" ", DDG).is_none());
}
#[test]
fn domains() {
assert_eq!(base_domain("music.youtube.com"), "youtube.com");
assert_eq!(base_domain("a.b.co.uk"), "b.co.uk");
assert!(host_matches("music.youtube.com", "youtube.com"));
assert!(!host_matches("notyoutube.com", "youtube.com"));
}
#[test]
fn civil_time() {
// 2026-11-10 00:00:00 UTC is 1794268800; a Tuesday.
let t = 1_794_268_800u64;
let off = local_offset(t);
let dt = local_time((t as i64 - off) as u64);
assert_eq!((dt.year, dt.month, dt.day, dt.weekday), (2026, 11, 10, 1));
}
#[test]
fn names() {
assert_eq!(safe_file_name("a/b:c?.txt"), "a_b_c_.txt");
assert_eq!(safe_file_name("..."), "download");
assert_eq!(percent_decode("a%20b%2"), "a b%2");
assert_eq!(format_bytes(1_400_000), "1.4 MB");
}
}