use std::fs;
use std::io;
use std::os::windows::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Browser {
pub exe: PathBuf,
pub data: &'static str,
}
const BROWSERS: &[(&str, &str, &str)] = &[
("Zen Browser", "zen.exe", "zen"),
("Mozilla Firefox", "firefox.exe", r"Mozilla\Firefox"),
("Floorp", "floorp.exe", "Floorp"),
("LibreWolf", "librewolf.exe", "librewolf"),
("Waterfox", "waterfox.exe", "Waterfox"),
];
pub fn find() -> Option<Browser> {
if let Some(exe) = std::env::var_os("RUSTIMAL_BROWSER").map(PathBuf::from).filter(|p| p.is_file()) {
let stem = exe.file_stem().map(|s| s.to_string_lossy().to_lowercase()).unwrap_or_default();
let data = BROWSERS.iter().find(|b| b.1.trim_end_matches(".exe") == stem).map_or("", |b| b.2);
return Some(Browser { exe, data });
}
let roots: Vec<PathBuf> = ["LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"]
.iter()
.filter_map(std::env::var_os)
.flat_map(|base| {
let base = PathBuf::from(base);
let programs = base.join("Programs");
[base, programs]
})
.collect();
BROWSERS.iter().find_map(|&(folder, exe, data)| {
roots.iter().map(|r| r.join(folder).join(exe)).find(|p| p.is_file()).map(|exe| Browser { exe, data })
})
}
pub fn default_profile(data: &Path) -> Option<PathBuf> {
let text = fs::read_to_string(data.join("profiles.ini")).ok()?;
let mut sections: Vec<(String, Vec<(String, String)>)> = Vec::new();
for line in text.lines().map(str::trim) {
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
sections.push((name.to_string(), Vec::new()));
} else if let (Some((key, value)), Some(section)) = (line.split_once('='), sections.last_mut()) {
section.1.push((key.trim().to_string(), value.trim().to_string()));
}
}
let get = |section: &[(String, String)], key: &str| {
section.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.clone())
};
let resolve = |path: &str, relative: bool| {
let path = path.replace('/', "\\");
if relative { data.join(path) } else { PathBuf::from(path) }
};
let installed = sections
.iter()
.filter(|(name, _)| name.starts_with("Install"))
.find_map(|(_, items)| get(items, "Default"))
.map(|path| resolve(&path, true))
.filter(|p| p.is_dir());
let profiles = || sections.iter().filter(|(name, _)| name.starts_with("Profile"));
let listed = |items: &[(String, String)]| {
let relative = get(items, "IsRelative").is_none_or(|v| v != "0");
get(items, "Path").map(|path| resolve(&path, relative)).filter(|p| p.is_dir())
};
installed
.or_else(|| {
profiles().find(|(_, items)| get(items, "Default").is_some_and(|v| v == "1")).and_then(|(_, i)| listed(i))
})
.or_else(|| profiles().find_map(|(_, items)| listed(items)))
}
pub fn in_use(profile: &Path) -> bool {
let lock = profile.join("parent.lock");
if !lock.exists() {
return false;
}
fs::OpenOptions::new().read(true).write(true).share_mode(0).open(lock).is_err()
}
const LEFT_OUT_FOLDERS: &[&str] = &[
"cache2",
"startupcache",
"shader-cache",
"crashes",
"minidumps",
"datareporting",
"saved-telemetry-pings",
"safebrowsing",
"thumbnails",
"offlinecache",
"gmp",
"gmp-gmpopenh264",
"gmp-widevinecdm",
"sessionstore-backups",
"zen-sessions-backup",
];
const LEFT_OUT_FILES: &[&str] =
&["parent.lock", "lock", ".parentlock", "sessionstore.jsonlz4", "sessioncheckpoints.json", "zen-sessions.jsonlz4"];
fn left_out(name: &str, is_dir: bool) -> bool {
let name = name.to_lowercase();
if is_dir { LEFT_OUT_FOLDERS.contains(&name.as_str()) } else { LEFT_OUT_FILES.contains(&name.as_str()) }
}
pub fn copy_profile(from: &Path, to: &Path) -> io::Result<usize> {
fs::create_dir_all(to)?;
let mut copied = 0;
for entry in fs::read_dir(from)?.flatten() {
let (name, path) = (entry.file_name().to_string_lossy().into_owned(), entry.path());
let is_dir = entry.file_type().is_ok_and(|t| t.is_dir());
if left_out(&name, is_dir) {
continue;
}
if is_dir {
copied += copy_profile(&path, &to.join(&name)).unwrap_or(0);
} else if fs::copy(&path, to.join(&name)).is_ok() {
copied += 1;
}
}
Ok(copied)
}
pub fn own_profile() -> Option<PathBuf> {
dirs::data_local_dir().map(|d| d.join("rustimal").join("browser-profile"))
}
const SOURCE_MARK: &str = "rustimal-copied-from.txt";
const FRESH_PREFS: &str = r#"// Written once by rustimal.
user_pref("browser.shell.checkDefaultBrowser", false);
user_pref("browser.aboutwelcome.enabled", false);
user_pref("browser.startup.homepage_override.mstone", "ignore");
user_pref("browser.tabs.warnOnClose", false);
user_pref("datareporting.policy.dataSubmissionPolicyBypassNotification", true);
user_pref("toolkit.telemetry.reportingpolicy.firstRun", false);
user_pref("trailhead.firstrun.didSeeAboutWelcome", true);
"#;
fn write_once(file: &Path, text: &str) -> io::Result<()> {
match fs::OpenOptions::new().write(true).create_new(true).open(file) {
Ok(mut f) => io::Write::write_all(&mut f, text.as_bytes()),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
Err(e) => Err(e),
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum Launch {
Own,
Separate(PathBuf),
}
pub fn plan(browser: &Browser, appdata: &Path, own: &Path, say: &dyn Fn(&str)) -> io::Result<Launch> {
let source = default_profile(&appdata.join(browser.data));
let Some(source) = source else {
fs::create_dir_all(own)?;
write_once(&own.join("user.js"), FRESH_PREFS)?;
return Ok(Launch::Separate(own.to_path_buf()));
};
if !in_use(&source) {
return Ok(Launch::Own);
}
let mark = own.join(SOURCE_MARK);
let wanted = source.to_string_lossy().into_owned();
if fs::read_to_string(&mark).is_ok_and(|m| m == wanted) {
return Ok(Launch::Separate(own.to_path_buf()));
}
say(&format!("Copying {} (once, as it is open on the desktop)...", source.display()));
if own.exists() {
fs::remove_dir_all(own)?;
}
let files = copy_profile(&source, own)?;
fs::write(&mark, &wanted)?;
say(&format!("Copied {files} files."));
Ok(Launch::Separate(own.to_path_buf()))
}
pub fn what_to_show(given: &[String]) -> Vec<String> {
let search = |terms: &[String]| {
let terms = terms.join(" ");
if terms.trim().is_empty() { Vec::new() } else { vec!["-search".to_string(), terms] }
};
match given {
[flag, terms @ ..] if flag == "--search" => search(terms),
[page] if looks_like_a_page(page) => vec![page_address(page)],
words => search(words),
}
}
pub fn looks_like_a_page(word: &str) -> bool {
let word = word.trim();
if word.is_empty() || word.contains(char::is_whitespace) {
return false;
}
let host = word.split(['/', '?', '#']).next().unwrap_or(word);
let (name, port) = host.rsplit_once(':').map_or((host, None), |(n, p)| (n, Some(p)));
word.contains("://")
|| word.starts_with("about:")
|| Path::new(word).exists()
|| name.eq_ignore_ascii_case("localhost")
|| (port.is_some_and(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) && !name.is_empty())
|| (name.contains('.') && !name.starts_with('.') && !name.ends_with('.'))
}
pub fn args(launch: &Launch, show: &[String]) -> Vec<String> {
let mut args = Vec::new();
if let Launch::Separate(profile) = launch {
args.extend(["-no-remote".to_string(), "-profile".into(), profile.to_string_lossy().into_owned()]);
}
args.extend(show.iter().cloned());
args
}
pub fn page_address(given: &str) -> String {
let given = given.trim();
if given.is_empty() || given.contains("://") || given.starts_with("about:") || Path::new(given).exists() {
given.to_string()
} else {
format!("http://{given}")
}
}
fn state_file() -> Option<PathBuf> {
let pane = std::env::var("RUSTIMAL_PANE").ok().filter(|p| !p.is_empty())?;
crate::config::state_dir().map(|d| d.join(format!("browser-{pane}.txt")))
}
fn remember(launch: &Launch) {
let Some(file) = state_file() else { return };
let text = match launch {
Launch::Own => "own".to_string(),
Launch::Separate(profile) => format!("separate\n{}", profile.display()),
};
if let Some(dir) = file.parent() {
let _ = fs::create_dir_all(dir);
}
let _ = fs::write(file, text);
}
fn remembered() -> Option<Launch> {
let text = fs::read_to_string(state_file()?).ok()?;
let mut lines = text.lines();
match lines.next()? {
"own" => Some(Launch::Own),
"separate" => lines.next().map(|p| Launch::Separate(PathBuf::from(p))),
_ => None,
}
}
pub fn search_address(terms: &str) -> String {
let encoded: String = terms
.bytes()
.map(|b| {
if b.is_ascii_alphanumeric() || b"-_.~".contains(&b) {
(b as char).to_string()
} else if b == b' ' {
"+".to_string()
} else {
format!("%{b:02X}")
}
})
.collect();
format!("https://www.google.com/search?q={encoded}")
}
pub fn forward_args(launch: &Launch, show: &[String]) -> Vec<String> {
let mut args = Vec::new();
if let Launch::Separate(profile) = launch {
args.extend(["-profile".to_string(), profile.to_string_lossy().into_owned()]);
}
match show {
[flag, terms] if flag == "-search" => args.extend(["-new-tab".to_string(), search_address(terms)]),
[page] => args.extend(["-new-tab".to_string(), page.clone()]),
_ => {}
}
args
}
pub fn run(args_given: &[String]) -> i32 {
let (reuse, args_given) = match args_given.split_first() {
Some((flag, rest)) if flag == "--reuse" => (true, rest),
_ => (false, args_given),
};
let show = what_to_show(args_given);
let Some(browser) = find() else {
eprintln!("embed: no Firefox-based browser found (Zen, Firefox, Floorp, LibreWolf, Waterfox).");
eprintln!(" Install one, or set RUSTIMAL_BROWSER to its exe.");
return 1;
};
let (Some(appdata), Some(own)) = (dirs::config_dir(), own_profile()) else {
eprintln!("embed: could not find the browser's profile");
return 1;
};
if reuse && let Some(launch) = remembered() {
if show.is_empty() {
return 0;
}
return match Command::new(&browser.exe).args(forward_args(&launch, &show)).status() {
Ok(status) => status.code().unwrap_or(1),
Err(e) => {
eprintln!("embed: could not start {}: {e}", browser.exe.display());
1
}
};
}
let launch = match plan(&browser, &appdata, &own, &|text| eprintln!("{text}")) {
Ok(launch) => launch,
Err(e) => {
eprintln!("embed: could not get the browser's profile ready: {e}");
return 1;
}
};
remember(&launch);
match Command::new(&browser.exe).args(args(&launch, &show)).status() {
Ok(status) => status.code().unwrap_or(1),
Err(e) => {
eprintln!("embed: could not start {}: {e}", browser.exe.display());
1
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("rustimal-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn the_profile_an_installation_uses_is_the_default() {
let data = temp("ini");
for p in ["Profiles/a.default", "Profiles/b.Default (release)"] {
fs::create_dir_all(data.join(p)).unwrap();
}
let ini = "[Profile1]\nName=default\nIsRelative=1\nPath=Profiles/a.default\nDefault=1\n\n\
[Profile0]\nName=Default (release)\nIsRelative=1\nPath=Profiles/b.Default (release)\n\n\
[General]\nVersion=2\n\n[Install99]\nDefault=Profiles/b.Default (release)\nLocked=1\n";
fs::write(data.join("profiles.ini"), ini).unwrap();
assert_eq!(default_profile(&data), Some(data.join(r"Profiles\b.Default (release)")));
let plain = ini.split("[Install99]").next().unwrap();
fs::write(data.join("profiles.ini"), plain).unwrap();
assert_eq!(default_profile(&data), Some(data.join(r"Profiles\a.default")));
fs::remove_dir_all(data.join("Profiles")).unwrap();
assert_eq!(default_profile(&data), None);
assert_eq!(default_profile(&data.join("nothing")), None);
fs::remove_dir_all(data).unwrap();
}
#[test]
fn a_profile_is_in_use_while_its_lock_is_held() {
let profile = temp("lock");
assert!(!in_use(&profile), "no lock file, nobody");
let lock = profile.join("parent.lock");
fs::write(&lock, "").unwrap();
assert!(!in_use(&profile), "a lock file nobody holds");
let held = fs::OpenOptions::new().read(true).write(true).share_mode(0).open(&lock).unwrap();
assert!(in_use(&profile));
drop(held);
assert!(!in_use(&profile));
fs::remove_dir_all(profile).unwrap();
}
#[test]
fn a_copy_takes_the_persons_data_and_leaves_out_what_is_rebuilt() {
let from = temp("from");
let to = temp("to");
fs::remove_dir_all(&to).unwrap();
for dir in ["storage/default", "cache2/entries", "gmp-widevinecdm", "sessionstore-backups", "extensions"] {
fs::create_dir_all(from.join(dir)).unwrap();
}
for file in [
"places.sqlite",
"logins.json",
"prefs.js",
"storage/default/site.sqlite",
"extensions/a@b.xpi",
"cache2/entries/x",
"gmp-widevinecdm/w.dll",
"sessionstore-backups/recovery.jsonlz4",
"parent.lock",
"zen-sessions.jsonlz4",
] {
fs::write(from.join(file), "x").unwrap();
}
let copied = copy_profile(&from, &to).unwrap();
assert_eq!(copied, 5);
for kept in ["places.sqlite", "logins.json", "prefs.js", "storage/default/site.sqlite", "extensions/a@b.xpi"] {
assert!(to.join(kept).is_file(), "{kept}");
}
for left in ["cache2", "gmp-widevinecdm", "sessionstore-backups", "parent.lock", "zen-sessions.jsonlz4"] {
assert!(!to.join(left).exists(), "{left}");
}
fs::remove_dir_all(from).unwrap();
fs::remove_dir_all(to).unwrap();
}
#[test]
fn an_open_browser_is_copied_once_and_a_closed_one_is_used_as_it_is() {
let appdata = temp("appdata");
let own = temp("own");
fs::remove_dir_all(&own).unwrap();
let browser = Browser { exe: "zen.exe".into(), data: "zen" };
let nothing = |_: &str| {};
assert_eq!(plan(&browser, &appdata, &own, ¬hing).unwrap(), Launch::Separate(own.clone()));
assert!(own.join("user.js").is_file());
fs::remove_dir_all(&own).unwrap();
let profile = appdata.join(r"zen\Profiles\p.default");
fs::create_dir_all(&profile).unwrap();
fs::write(profile.join("places.sqlite"), "bookmarks").unwrap();
fs::write(appdata.join(r"zen\profiles.ini"), "[Profile0]\nIsRelative=1\nPath=Profiles/p.default\nDefault=1\n")
.unwrap();
assert_eq!(plan(&browser, &appdata, &own, ¬hing).unwrap(), Launch::Own, "nothing uses it");
let held = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(false)
.share_mode(0)
.open(profile.join("parent.lock"))
.unwrap();
let said = std::cell::RefCell::new(Vec::new());
let say = |t: &str| said.borrow_mut().push(t.to_string());
assert_eq!(plan(&browser, &appdata, &own, &say).unwrap(), Launch::Separate(own.clone()));
assert_eq!(fs::read_to_string(own.join("places.sqlite")).unwrap(), "bookmarks", "the data came along");
assert_eq!(said.borrow().len(), 2, "it said it was copying");
fs::write(own.join("places.sqlite"), "changed here").unwrap();
assert_eq!(plan(&browser, &appdata, &own, &say).unwrap(), Launch::Separate(own.clone()));
assert_eq!(fs::read_to_string(own.join("places.sqlite")).unwrap(), "changed here", "not copied again");
assert_eq!(said.borrow().len(), 2);
drop(held);
fs::remove_dir_all(appdata).unwrap();
fs::remove_dir_all(own).unwrap();
}
#[test]
fn the_command_line_depends_on_the_profile() {
let separate = Launch::Separate(PathBuf::from(r"C:\p"));
let page = ["http://a".to_string()];
assert_eq!(args(&separate, &page), ["-no-remote", "-profile", r"C:\p", "http://a"]);
assert_eq!(args(&separate, &[]).len(), 3);
assert_eq!(args(&Launch::Own, &page), ["http://a"]);
assert!(args(&Launch::Own, &[]).is_empty());
}
#[test]
fn a_page_or_a_search_is_what_to_show() {
let words = |text: &str| text.split(' ').map(str::to_string).collect::<Vec<_>>();
assert_eq!(what_to_show(&words("localhost:3000")), ["http://localhost:3000"]);
assert_eq!(what_to_show(&words("example.com")), ["http://example.com"]);
assert_eq!(what_to_show(&words("https://example.com/a?b=c d")), ["-search", "https://example.com/a?b=c d"]);
assert_eq!(what_to_show(&words("asd")), ["-search", "asd"], "one plain word is a search");
assert_eq!(what_to_show(&words("rust window embedding")), ["-search", "rust window embedding"]);
assert_eq!(what_to_show(&words("http://x/y")), ["http://x/y"]);
assert_eq!(what_to_show(&words("--search rust window embedding")), ["-search", "rust window embedding"]);
assert!(what_to_show(&words("--search")).is_empty());
assert!(what_to_show(&[]).is_empty());
assert!(what_to_show(&[String::new()]).is_empty());
}
#[test]
fn a_second_page_goes_to_the_running_browser() {
let separate = Launch::Separate(PathBuf::from(r"C:\p"));
let show = ["-search".to_string(), "asd & more".to_string()];
let url = "https://www.google.com/search?q=asd+%26+more";
assert_eq!(forward_args(&separate, &show), ["-profile", r"C:\p", "-new-tab", url]);
assert_eq!(forward_args(&Launch::Own, &show), ["-new-tab", url]);
assert_eq!(forward_args(&Launch::Own, &["http://a".to_string()]), ["-new-tab", "http://a"]);
assert!(forward_args(&Launch::Own, &[]).is_empty(), "nothing to show: just the running browser");
assert!(!forward_args(&separate, &show).contains(&"-no-remote".to_string()), "it must find the running one");
}
#[test]
fn a_page_is_an_address() {
assert_eq!(page_address("localhost:3000"), "http://localhost:3000");
assert_eq!(page_address("https://example.com/a"), "https://example.com/a");
assert_eq!(page_address("about:blank"), "about:blank");
assert_eq!(page_address(""), "");
assert_eq!(page_address(" 127.0.0.1:8080/x "), "http://127.0.0.1:8080/x");
}
}