284 lines
12 KiB
Rust
284 lines
12 KiB
Rust
//! How apps are started: the command line for a web app (Chromium in kiosk or
|
|
//! app mode with its own profile) or an exec app. Shared by the launcher
|
|
//! (local testing on a desktop) and sf-core (the TV).
|
|
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::Command;
|
|
|
|
use anyhow::{Context, Result, bail};
|
|
|
|
use crate::{AppKind, AppManifest, Settings, paths, sandbox};
|
|
|
|
/// Environment variable carrying the app id into the app's processes. The
|
|
/// compositor reads it from `/proc/<pid>/environ` to tell windows apart.
|
|
pub const APP_ENV: &str = "SMARTFOX_APP";
|
|
|
|
pub struct Browser {
|
|
pub exe: PathBuf,
|
|
/// Full version, used to build a realistic user agent.
|
|
pub version: String,
|
|
}
|
|
|
|
pub fn find_browser() -> Option<Browser> {
|
|
let mut candidates: Vec<PathBuf> = Vec::new();
|
|
if let Ok(p) = std::env::var("SMARTFOX_BROWSER") {
|
|
candidates.push(p.into());
|
|
}
|
|
#[cfg(windows)]
|
|
{
|
|
for base in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] {
|
|
if let Some(b) = std::env::var_os(base) {
|
|
let b = PathBuf::from(b);
|
|
candidates.push(b.join(r"Google\Chrome\Application\chrome.exe"));
|
|
candidates.push(b.join(r"Chromium\Application\chrome.exe"));
|
|
candidates.push(b.join(r"Microsoft\Edge\Application\msedge.exe"));
|
|
}
|
|
}
|
|
}
|
|
#[cfg(not(windows))]
|
|
{
|
|
for name in ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"] {
|
|
for dir in ["/usr/bin", "/usr/local/bin", "/snap/bin"] {
|
|
candidates.push(Path::new(dir).join(name));
|
|
}
|
|
}
|
|
}
|
|
let exe = candidates.into_iter().find(|p| p.is_file())?;
|
|
let version = browser_version(&exe).unwrap_or_else(|| "141.0.0.0".into());
|
|
Some(Browser { exe, version })
|
|
}
|
|
|
|
fn browser_version(exe: &Path) -> Option<String> {
|
|
// Windows installs keep a folder named after the version next to the exe.
|
|
if cfg!(windows) {
|
|
let dir = exe.parent()?;
|
|
let mut versions: Vec<String> = std::fs::read_dir(dir)
|
|
.ok()?
|
|
.flatten()
|
|
.filter_map(|e| e.file_name().into_string().ok())
|
|
.filter(|n| n.split('.').count() == 4 && n.split('.').all(|p| p.parse::<u32>().is_ok()))
|
|
.collect();
|
|
versions.sort_by_key(|v| v.split('.').map(|p| p.parse::<u32>().unwrap_or(0)).collect::<Vec<_>>());
|
|
return versions.pop();
|
|
}
|
|
let out = Command::new(exe).arg("--version").output().ok()?;
|
|
String::from_utf8_lossy(&out.stdout)
|
|
.split_whitespace()
|
|
.find(|w| w.chars().next().is_some_and(|c| c.is_ascii_digit()) && w.contains('.'))
|
|
.map(str::to_string)
|
|
}
|
|
|
|
fn default_user_agent(version: &str) -> String {
|
|
let platform = if cfg!(windows) { "Windows NT 10.0; Win64; x64" } else { "X11; Linux x86_64" };
|
|
let major = version.split('.').next().unwrap_or("141");
|
|
format!("Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36")
|
|
}
|
|
|
|
pub struct LaunchOptions<'a> {
|
|
/// Per-app browser profiles live in `<data_dir>/profiles/<id>`.
|
|
pub data_dir: &'a Path,
|
|
pub fullscreen: bool,
|
|
/// Windowed mode: open the app exactly over the launcher (x, y, w, h).
|
|
pub bounds: Option<(i32, i32, u32, u32)>,
|
|
/// Extra query string for the start URL (DIAL launch parameters).
|
|
pub query: Option<&'a str>,
|
|
}
|
|
|
|
/// A program with its arguments and environment, before it is (maybe) put
|
|
/// into the sandbox.
|
|
struct Inner {
|
|
program: String,
|
|
args: Vec<String>,
|
|
env: Vec<(String, String)>,
|
|
}
|
|
|
|
/// The bwrap binary if `app` runs sandboxed (`sandbox` module). Store apps
|
|
/// never run without it. Official apps run unsandboxed when bwrap is missing
|
|
/// (an older image under a newer shell) or with `SMARTFOX_SANDBOX=off`
|
|
/// (debugging), with a warning.
|
|
fn sandbox_for(app: &AppManifest) -> Result<Option<PathBuf>> {
|
|
if app.origin == crate::Origin::Store {
|
|
anyhow::ensure!(cfg!(target_os = "linux"), "store apps only run on the TV (Linux)");
|
|
return sandbox::bwrap_path().context("bubblewrap (bwrap) is not installed, and store apps only run sandboxed").map(Some);
|
|
}
|
|
if !cfg!(target_os = "linux") || !app.sandboxed() {
|
|
return Ok(None);
|
|
}
|
|
if std::env::var("SMARTFOX_SANDBOX").is_ok_and(|v| v == "off") {
|
|
log::warn!("{}: SMARTFOX_SANDBOX=off, running without a sandbox", app.id);
|
|
return Ok(None);
|
|
}
|
|
let bwrap = sandbox::bwrap_path();
|
|
if bwrap.is_none() {
|
|
log::warn!("{}: bubblewrap is not installed, running without a sandbox", app.id);
|
|
}
|
|
Ok(bwrap)
|
|
}
|
|
|
|
/// The command that starts `app`. Not spawned yet, so callers can wrap it
|
|
/// (sf-core runs it inside a systemd scope).
|
|
pub fn command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result<Command> {
|
|
let bwrap = sandbox_for(app)?;
|
|
// Where the app's files are, as the app sees them.
|
|
let root = if bwrap.is_some() { PathBuf::from(sandbox::APP_DIR) } else { app.dir.clone() };
|
|
let data = paths::app_data_dir(&app.id);
|
|
let inner = match app.kind {
|
|
AppKind::Web => web_command(app, settings, opts, &root, bwrap.is_some().then_some(data.as_path()))?,
|
|
AppKind::Exec => {
|
|
let line = app.resolved_exec(&root);
|
|
let (prog, args) = line.split_first().context("empty exec command")?;
|
|
Inner { program: prog.clone(), args: args.to_vec(), env: Vec::new() }
|
|
}
|
|
AppKind::Builtin => bail!("built-in app has no process"),
|
|
};
|
|
let mut env = inner.env;
|
|
env.extend(app.env.iter().map(|(k, v)| (k.clone(), settings.expand(v))));
|
|
|
|
let mut cmd = match bwrap {
|
|
Some(bwrap) => {
|
|
std::fs::create_dir_all(&data).with_context(|| format!("creating {}", data.display()))?;
|
|
// Store apps sit behind symlinks (store/apps/<id> -> ../store-<id>/current).
|
|
let app_dir = std::fs::canonicalize(&app.dir).unwrap_or_else(|_| app.dir.clone());
|
|
let permissions = app.permissions();
|
|
let spec = sandbox::Spec {
|
|
app_id: &app.id,
|
|
app_dir: &app_dir,
|
|
data_dir: &data,
|
|
extra_rw: Vec::new(),
|
|
permissions: &permissions,
|
|
env,
|
|
program: inner.program,
|
|
args: inner.args,
|
|
};
|
|
let cmd = sandbox::command(&bwrap, &spec, &sandbox::Host::current());
|
|
log::info!("{}: sandboxed, permissions: {:?}", app.id, permissions.iter().map(|p| p.key()).collect::<Vec<_>>());
|
|
cmd
|
|
}
|
|
None => {
|
|
let mut cmd = Command::new(&inner.program);
|
|
cmd.args(&inner.args).envs(env).env("SMARTFOX_APP_DIR", &app.dir);
|
|
cmd
|
|
}
|
|
};
|
|
cmd.env(APP_ENV, &app.id);
|
|
// Own process group, so stopping the app also ends its helper processes.
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::process::CommandExt;
|
|
cmd.process_group(0);
|
|
}
|
|
Ok(cmd)
|
|
}
|
|
|
|
/// Adds `query` to `url`, before any `#fragment`.
|
|
pub fn with_query(url: &str, query: Option<&str>) -> String {
|
|
let Some(q) = query.map(|q| q.trim_start_matches(['?', '&'])).filter(|q| !q.is_empty()) else {
|
|
return url.to_string();
|
|
};
|
|
let (base, frag) = match url.find('#') {
|
|
Some(i) => (&url[..i], &url[i..]),
|
|
None => (url, ""),
|
|
};
|
|
let sep = if base.contains('?') { '&' } else { '?' };
|
|
format!("{base}{sep}{q}{frag}")
|
|
}
|
|
|
|
/// First-run preferences for an app profile: no translate prompt, Hungarian
|
|
/// content language. Existing profiles are left alone.
|
|
fn seed_profile(profile: &Path) -> Result<()> {
|
|
let prefs = profile.join("Default").join("Preferences");
|
|
if prefs.exists() {
|
|
return Ok(());
|
|
}
|
|
std::fs::create_dir_all(prefs.parent().unwrap())?;
|
|
std::fs::write(
|
|
&prefs,
|
|
r#"{"translate":{"enabled":false},"intl":{"accept_languages":"hu-HU,hu,en"},"browser":{"has_seen_welcome_page":true}}"#,
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
/// The browser command for a web app. `sandbox_home`: the app's data folder
|
|
/// when it runs sandboxed; its Chromium profile then lives in there.
|
|
fn web_command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions, root: &Path, sandbox_home: Option<&Path>) -> Result<Inner> {
|
|
let browser = find_browser().context("no Chromium/Chrome/Edge found (set SMARTFOX_BROWSER)")?;
|
|
let url = app.resolved_url(settings).filter(|u| !u.is_empty()).context("app has no URL")?;
|
|
if url.starts_with('/') {
|
|
bail!("URL is not set (check settings: {url})");
|
|
}
|
|
let url = with_query(&url, opts.query);
|
|
let old_profile = opts.data_dir.join("profiles").join(&app.id);
|
|
let profile = match sandbox_home {
|
|
Some(home) => {
|
|
let profile = home.join("chromium");
|
|
// Profiles from before the sandbox (logins, settings) move along.
|
|
if old_profile.is_dir() && !profile.exists() {
|
|
std::fs::create_dir_all(home)?;
|
|
if let Err(e) = std::fs::rename(&old_profile, &profile) {
|
|
log::warn!("{}: moving the browser profile: {e}", app.id);
|
|
}
|
|
}
|
|
profile
|
|
}
|
|
None => old_profile,
|
|
};
|
|
seed_profile(&profile)?;
|
|
|
|
let ua = match (&app.web.user_agent, &app.web.user_agent_suffix) {
|
|
(Some(ua), _) => ua.clone(),
|
|
(None, Some(suffix)) => format!("{} {suffix}", default_user_agent(&browser.version)),
|
|
(None, None) => default_user_agent(&browser.version),
|
|
};
|
|
|
|
let mut args: Vec<String> = vec![
|
|
format!("--user-data-dir={}", profile.display()),
|
|
format!("--user-agent={ua}"),
|
|
"--no-first-run".into(),
|
|
"--no-default-browser-check".into(),
|
|
"--disable-session-crashed-bubble".into(),
|
|
"--hide-crash-restore-bubble".into(),
|
|
"--disable-features=Translate,TranslateUI,MediaRouter,LocalNetworkAccessChecks".into(),
|
|
"--lang=hu".into(),
|
|
"--accept-lang=hu-HU,hu,en".into(),
|
|
// Dark first paint instead of a white flash before the page draws.
|
|
"--force-dark-mode".into(),
|
|
"--autoplay-policy=no-user-gesture-required".into(),
|
|
"--overscroll-history-navigation=0".into(),
|
|
];
|
|
if opts.fullscreen {
|
|
args.extend(["--kiosk".into(), url]);
|
|
} else {
|
|
args.push(format!("--app={url}"));
|
|
match opts.bounds {
|
|
Some((x, y, w, h)) => args.extend([format!("--window-position={x},{y}"), format!("--window-size={w},{h}")]),
|
|
None => args.push("--window-size=1600,900".into()),
|
|
}
|
|
}
|
|
let mut env = Vec::new();
|
|
if cfg!(target_os = "linux") {
|
|
// Chromium on Linux picks its UI language from the environment, not --lang.
|
|
env.push(("LANGUAGE".to_string(), "hu".to_string()));
|
|
args.push("--enable-features=VaapiVideoDecoder,VaapiIgnoreDriverChecks,PlatformHEVCDecoderSupport".into());
|
|
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
|
|
args.push("--ozone-platform=wayland".into());
|
|
}
|
|
}
|
|
for ext in &app.web.extensions {
|
|
args.push(format!("--load-extension={}", root.join(ext).display()));
|
|
}
|
|
Ok(Inner { program: browser.exe.to_string_lossy().into_owned(), args, env })
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn adds_query() {
|
|
assert_eq!(with_query("https://www.youtube.com/tv", Some("a=1&b=2")), "https://www.youtube.com/tv?a=1&b=2");
|
|
assert_eq!(with_query("https://x/tv?x=1#f", Some("?a=1")), "https://x/tv?x=1&a=1#f");
|
|
assert_eq!(with_query("https://x/", None), "https://x/");
|
|
assert_eq!(with_query("https://x/", Some("")), "https://x/");
|
|
}
|
|
}
|