BlueGit

ict rusty-teams

Files

rusty-teams / crates / browser / src / host.rs

host.rs

host.rs 2.9 KiB Download Raw
1//! Inside a Flatpak the host's browsers are neither visible nor startable from the sandbox, so
2//! lookups and processes go to the host through `flatpak-spawn --host`. The debug port and the
3//! profile under `~/.var/app` are the same on both sides.
4
5use std::collections::HashSet;
6use std::ffi::{OsStr, OsString};
7use std::path::{Path, PathBuf};
8use std::process::Command;
9use std::sync::OnceLock;
10
11const FLATPAK_INFO: &str = "/.flatpak-info";
12const LIST_DIRECTORIES: &str = r#"for directory in "$@"; do for entry in "$directory"/*; do [ -f "$entry" ] && printf '%s\n' "$entry"; done; done"#;
13
14pub(crate) fn in_flatpak() -> bool {
15 static IN_FLATPAK: OnceLock<bool> = OnceLock::new();
16 *IN_FLATPAK.get_or_init(|| Path::new(FLATPAK_INFO).exists())
17}
18
19/// `program` on the host: wrapped in `flatpak-spawn --host` inside a Flatpak.
20pub(crate) fn command(program: impl AsRef<OsStr>) -> Command {
21 if in_flatpak() {
22 let mut command = Command::new("flatpak-spawn");
23 command.arg("--host").arg(program);
24 command
25 } else {
26 Command::new(program)
27 }
28}
29
30/// The host's `PATH`, read once inside a Flatpak.
31pub(crate) fn path_variable() -> OsString {
32 if !in_flatpak() {
33 return std::env::var_os("PATH").unwrap_or_default();
34 }
35 static HOST_PATH: OnceLock<OsString> = OnceLock::new();
36 HOST_PATH
37 .get_or_init(|| {
38 command("printenv")
39 .arg("PATH")
40 .output()
41 .map(|output| String::from_utf8_lossy(&output.stdout).trim().into())
42 .unwrap_or_default()
43 })
44 .clone()
45}
46
47/// Whether `path` is a file on the host. Files in the host's `PATH` directories are listed in
48/// one call, so probing every browser name in every directory stays cheap.
49pub(crate) fn is_file(path: &Path) -> bool {
50 if !in_flatpak() {
51 return path.is_file();
52 }
53 let (directories, files) = host_path_files();
54 if path
55 .parent()
56 .is_some_and(|parent| directories.contains(parent))
57 {
58 return files.contains(path);
59 }
60 command("test")
61 .arg("-f")
62 .arg(path)
63 .status()
64 .is_ok_and(|status| status.success())
65}
66
67fn host_path_files() -> &'static (HashSet<PathBuf>, HashSet<PathBuf>) {
68 static LISTING: OnceLock<(HashSet<PathBuf>, HashSet<PathBuf>)> = OnceLock::new();
69 LISTING.get_or_init(|| {
70 let directories: HashSet<PathBuf> = std::env::split_paths(&path_variable()).collect();
71 let output = command("sh")
72 .args(["-c", LIST_DIRECTORIES, "sh"])
73 .args(&directories)
74 .output();
75 let files = output
76 .map(|output| {
77 String::from_utf8_lossy(&output.stdout)
78 .lines()
79 .map(PathBuf::from)
80 .collect()
81 })
82 .unwrap_or_default();
83 (directories, files)
84 })
85}