|
|
@@ -0,0 +1,326 @@
|
|
|
+//! Freedesktop launcher install: `.desktop` entry + hicolor PNG from site favicon.
|
|
|
+
|
|
|
+use std::io::{Cursor, Read};
|
|
|
+use std::path::PathBuf;
|
|
|
+
|
|
|
+use image::imageops::FilterType;
|
|
|
+use image::{DynamicImage, ImageFormat, RgbaImage};
|
|
|
+use scraper::{Html, Selector};
|
|
|
+use sha2::{Digest, Sha256};
|
|
|
+use url::Url;
|
|
|
+
|
|
|
+const ICON_SIZE: u32 = 48;
|
|
|
+const ID_HEX_LEN: usize = 12;
|
|
|
+
|
|
|
+pub fn run_install(
|
|
|
+ url_arg: &str,
|
|
|
+ display_name: Option<&str>,
|
|
|
+ force: bool,
|
|
|
+ normalize_url: fn(&str) -> Result<String, &'static str>,
|
|
|
+) -> Result<(), String> {
|
|
|
+ let url = normalize_url(url_arg)?;
|
|
|
+ let id = stable_id(&url);
|
|
|
+ let icon_name = format!("webruntime-{id}");
|
|
|
+ let data_home = xdg_data_home();
|
|
|
+ let apps_dir = data_home.join("applications");
|
|
|
+ let icon_dir = data_home
|
|
|
+ .join("icons")
|
|
|
+ .join("hicolor")
|
|
|
+ .join(format!("{ICON_SIZE}x{ICON_SIZE}"))
|
|
|
+ .join("apps");
|
|
|
+ let desktop_path = apps_dir.join(format!("webruntime-{id}.desktop"));
|
|
|
+ let icon_path = icon_dir.join(format!("{icon_name}.png"));
|
|
|
+
|
|
|
+ if desktop_path.exists() && !force {
|
|
|
+ return Err(format!(
|
|
|
+ "launcher already exists: {}\n(use --force to overwrite)",
|
|
|
+ desktop_path.display()
|
|
|
+ ));
|
|
|
+ }
|
|
|
+
|
|
|
+ std::fs::create_dir_all(&apps_dir).map_err(|e| e.to_string())?;
|
|
|
+ std::fs::create_dir_all(&icon_dir).map_err(|e| e.to_string())?;
|
|
|
+
|
|
|
+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;
|
|
|
+ let exe_str = exe.to_str().ok_or("non-UTF8 executable path")?;
|
|
|
+
|
|
|
+ let page_title = fetch_page_title(&url);
|
|
|
+ let name = display_name
|
|
|
+ .map(str::trim)
|
|
|
+ .filter(|s| !s.is_empty())
|
|
|
+ .map(String::from)
|
|
|
+ .or(page_title.filter(|s| !s.is_empty()))
|
|
|
+ .unwrap_or_else(|| host_label(&url));
|
|
|
+
|
|
|
+ let icon_written = match fetch_favicon_png(&url) {
|
|
|
+ Ok(png) => {
|
|
|
+ std::fs::write(&icon_path, png).map_err(|e| e.to_string())?;
|
|
|
+ true
|
|
|
+ }
|
|
|
+ Err(e) => {
|
|
|
+ eprintln!("webruntime: favicon: {e} (launcher will use a generic icon name)");
|
|
|
+ false
|
|
|
+ }
|
|
|
+ };
|
|
|
+
|
|
|
+ let icon_value = if icon_written {
|
|
|
+ icon_path
|
|
|
+ .to_str()
|
|
|
+ .ok_or("non-UTF8 icon path")?
|
|
|
+ .to_string()
|
|
|
+ } else {
|
|
|
+ "applications-internet".to_string()
|
|
|
+ };
|
|
|
+
|
|
|
+ let desktop_body = build_desktop_file(&name, exe_str, &url, &icon_value);
|
|
|
+ std::fs::write(&desktop_path, desktop_body).map_err(|e| e.to_string())?;
|
|
|
+
|
|
|
+ eprintln!("Wrote {}", desktop_path.display());
|
|
|
+ if icon_written {
|
|
|
+ eprintln!("Wrote {}", icon_path.display());
|
|
|
+ }
|
|
|
+ Ok(())
|
|
|
+}
|
|
|
+
|
|
|
+pub fn run_uninstall(
|
|
|
+ target: &str,
|
|
|
+ normalize_url: fn(&str) -> Result<String, &'static str>,
|
|
|
+) -> Result<(), String> {
|
|
|
+ let id = if target.chars().all(|c| c.is_ascii_hexdigit()) && target.len() == ID_HEX_LEN {
|
|
|
+ target.to_ascii_lowercase()
|
|
|
+ } else {
|
|
|
+ let url = normalize_url(target)?;
|
|
|
+ stable_id(&url)
|
|
|
+ };
|
|
|
+
|
|
|
+ let data_home = xdg_data_home();
|
|
|
+ let desktop_path = data_home
|
|
|
+ .join("applications")
|
|
|
+ .join(format!("webruntime-{id}.desktop"));
|
|
|
+ let icon_path = data_home
|
|
|
+ .join("icons")
|
|
|
+ .join("hicolor")
|
|
|
+ .join(format!("{ICON_SIZE}x{ICON_SIZE}"))
|
|
|
+ .join("apps")
|
|
|
+ .join(format!("webruntime-{id}.png"));
|
|
|
+
|
|
|
+ let mut removed = false;
|
|
|
+ if desktop_path.exists() {
|
|
|
+ std::fs::remove_file(&desktop_path).map_err(|e| e.to_string())?;
|
|
|
+ eprintln!("Removed {}", desktop_path.display());
|
|
|
+ removed = true;
|
|
|
+ }
|
|
|
+ if icon_path.exists() {
|
|
|
+ std::fs::remove_file(&icon_path).map_err(|e| e.to_string())?;
|
|
|
+ eprintln!("Removed {}", icon_path.display());
|
|
|
+ removed = true;
|
|
|
+ }
|
|
|
+
|
|
|
+ if !removed {
|
|
|
+ return Err(format!("no launcher found for `{target}` (id {id})"));
|
|
|
+ }
|
|
|
+ Ok(())
|
|
|
+}
|
|
|
+
|
|
|
+fn stable_id(url: &str) -> String {
|
|
|
+ let mut h = Sha256::new();
|
|
|
+ h.update(url.as_bytes());
|
|
|
+ let full = format!("{:x}", h.finalize());
|
|
|
+ full[..ID_HEX_LEN].to_string()
|
|
|
+}
|
|
|
+
|
|
|
+fn xdg_data_home() -> PathBuf {
|
|
|
+ std::env::var_os("XDG_DATA_HOME")
|
|
|
+ .filter(|s| !s.is_empty())
|
|
|
+ .map(PathBuf::from)
|
|
|
+ .or_else(|| {
|
|
|
+ std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share"))
|
|
|
+ })
|
|
|
+ .unwrap_or_else(|| PathBuf::from("/tmp/.local/share"))
|
|
|
+}
|
|
|
+
|
|
|
+fn host_label(url: &str) -> String {
|
|
|
+ Url::parse(url)
|
|
|
+ .ok()
|
|
|
+ .and_then(|u| u.host_str().map(String::from))
|
|
|
+ .unwrap_or_else(|| url.to_string())
|
|
|
+}
|
|
|
+
|
|
|
+fn escape_desktop_exec_component(s: &str) -> String {
|
|
|
+ let mut out = String::with_capacity(s.len() + 2);
|
|
|
+ out.push('"');
|
|
|
+ for c in s.chars() {
|
|
|
+ match c {
|
|
|
+ '"' | '\\' | '`' | '$' => {
|
|
|
+ out.push('\\');
|
|
|
+ out.push(c);
|
|
|
+ }
|
|
|
+ _ => out.push(c),
|
|
|
+ }
|
|
|
+ }
|
|
|
+ out.push('"');
|
|
|
+ out
|
|
|
+}
|
|
|
+
|
|
|
+fn build_desktop_file(name: &str, exe: &str, page_url: &str, icon: &str) -> String {
|
|
|
+ let exec_line = format!(
|
|
|
+ "{} {}",
|
|
|
+ escape_desktop_exec_component(exe),
|
|
|
+ escape_desktop_exec_component(page_url)
|
|
|
+ );
|
|
|
+
|
|
|
+ [
|
|
|
+ "[Desktop Entry]",
|
|
|
+ "Type=Application",
|
|
|
+ "Terminal=false",
|
|
|
+ "Categories=Network;WebBrowser;",
|
|
|
+ &format!("Name={}", escape_desktop_value(name)),
|
|
|
+ &format!(
|
|
|
+ "Comment=Open {} in Webruntime",
|
|
|
+ escape_desktop_value(page_url)
|
|
|
+ ),
|
|
|
+ &format!("Exec={exec_line}"),
|
|
|
+ &format!("Icon={}", escape_desktop_value(icon)),
|
|
|
+ ]
|
|
|
+ .join("\n")
|
|
|
+ + "\n"
|
|
|
+}
|
|
|
+
|
|
|
+fn escape_desktop_value(s: &str) -> String {
|
|
|
+ s.replace('\\', "\\\\")
|
|
|
+ .replace('\n', "\\n")
|
|
|
+ .replace('\r', "\\r")
|
|
|
+}
|
|
|
+
|
|
|
+fn ureq_agent() -> ureq::Agent {
|
|
|
+ ureq::Agent::new()
|
|
|
+}
|
|
|
+
|
|
|
+fn fetch_bytes(agent: &ureq::Agent, url: &str) -> Result<Vec<u8>, String> {
|
|
|
+ let resp = agent
|
|
|
+ .get(url)
|
|
|
+ .set("User-Agent", "webruntime/1.0 (desktop-install)")
|
|
|
+ .call()
|
|
|
+ .map_err(|e| e.to_string())?;
|
|
|
+ if !(200..300).contains(&resp.status()) {
|
|
|
+ return Err(format!("HTTP {} for {url}", resp.status()));
|
|
|
+ }
|
|
|
+ let mut buf = Vec::new();
|
|
|
+ resp.into_reader()
|
|
|
+ .read_to_end(&mut buf)
|
|
|
+ .map_err(|e| e.to_string())?;
|
|
|
+ Ok(buf)
|
|
|
+}
|
|
|
+
|
|
|
+fn fetch_page_title(page_url: &str) -> Option<String> {
|
|
|
+ let agent = ureq_agent();
|
|
|
+ let html = fetch_bytes(&agent, page_url).ok()?;
|
|
|
+ let doc = Html::parse_document(std::str::from_utf8(&html).ok()?);
|
|
|
+ let sel = Selector::parse("title").ok()?;
|
|
|
+ doc.select(&sel)
|
|
|
+ .next()
|
|
|
+ .map(|e| e.text().collect::<Vec<_>>().join("").trim().to_string())
|
|
|
+ .filter(|s| !s.is_empty())
|
|
|
+}
|
|
|
+
|
|
|
+fn fetch_favicon_png(page_url: &str) -> Result<Vec<u8>, String> {
|
|
|
+ let base = Url::parse(page_url).map_err(|e| e.to_string())?;
|
|
|
+ let agent = ureq_agent();
|
|
|
+
|
|
|
+ let html = fetch_bytes(&agent, page_url)?;
|
|
|
+ let html_str = std::str::from_utf8(&html).map_err(|_| "page is not valid UTF-8")?;
|
|
|
+
|
|
|
+ let icon_url = pick_icon_href(html_str, &base)
|
|
|
+ .or_else(|| base.join("/favicon.ico").ok().map(|u| u.to_string()));
|
|
|
+
|
|
|
+ let icon_url = icon_url.ok_or_else(|| "no favicon candidate URL".to_string())?;
|
|
|
+ let bytes = fetch_bytes(&agent, &icon_url)?;
|
|
|
+
|
|
|
+ decode_to_png(&bytes)
|
|
|
+}
|
|
|
+
|
|
|
+struct IconCandidate {
|
|
|
+ href: String,
|
|
|
+ score: i32,
|
|
|
+}
|
|
|
+
|
|
|
+fn pick_icon_href(html: &str, base: &Url) -> Option<String> {
|
|
|
+ let doc = Html::parse_document(html);
|
|
|
+ let sel = Selector::parse("link[rel][href]").ok()?;
|
|
|
+ let mut best: Option<IconCandidate> = None;
|
|
|
+
|
|
|
+ for el in doc.select(&sel) {
|
|
|
+ let rel = el.value().attr("rel")?.to_ascii_lowercase();
|
|
|
+ let href = el.value().attr("href")?;
|
|
|
+ if href.is_empty() {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ let tokens: Vec<&str> = rel.split_whitespace().collect();
|
|
|
+ let is_apple = tokens.iter().any(|t| {
|
|
|
+ *t == "apple-touch-icon" || *t == "apple-touch-icon-precomposed"
|
|
|
+ });
|
|
|
+ let is_icon = tokens.iter().any(|t| *t == "icon" || *t == "shortcut");
|
|
|
+
|
|
|
+ if !is_apple && !is_icon {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ let sizes = el.value().attr("sizes");
|
|
|
+ let px = sizes.and_then(parse_largest_size).unwrap_or(0);
|
|
|
+
|
|
|
+ let mut score = px;
|
|
|
+ if is_apple {
|
|
|
+ score += 10_000;
|
|
|
+ }
|
|
|
+
|
|
|
+ let resolved = base.join(href).ok()?.to_string();
|
|
|
+ let better = best
|
|
|
+ .as_ref()
|
|
|
+ .map(|b| score > b.score)
|
|
|
+ .unwrap_or(true);
|
|
|
+ if better {
|
|
|
+ best = Some(IconCandidate {
|
|
|
+ href: resolved,
|
|
|
+ score,
|
|
|
+ });
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ best.map(|b| b.href)
|
|
|
+}
|
|
|
+
|
|
|
+fn parse_largest_size(sizes: &str) -> Option<i32> {
|
|
|
+ let mut best = 0;
|
|
|
+ for part in sizes.split_whitespace() {
|
|
|
+ let mut it = part.split('x');
|
|
|
+ let w: i32 = it.next()?.parse().ok()?;
|
|
|
+ let h: i32 = it.next()?.parse().ok()?;
|
|
|
+ best = best.max(w.min(h));
|
|
|
+ }
|
|
|
+ if best > 0 {
|
|
|
+ Some(best)
|
|
|
+ } else {
|
|
|
+ None
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+fn decode_to_png(bytes: &[u8]) -> Result<Vec<u8>, String> {
|
|
|
+ let img = image::load_from_memory(bytes).map_err(|e| e.to_string())?;
|
|
|
+
|
|
|
+ let rgba = to_rgba_scaled(img);
|
|
|
+ let mut out = Vec::new();
|
|
|
+ RgbaImage::from_raw(ICON_SIZE, ICON_SIZE, rgba)
|
|
|
+ .ok_or_else(|| "icon decode produced invalid buffer".to_string())?
|
|
|
+ .write_to(&mut Cursor::new(&mut out), ImageFormat::Png)
|
|
|
+ .map_err(|e| e.to_string())?;
|
|
|
+ Ok(out)
|
|
|
+}
|
|
|
+
|
|
|
+fn to_rgba_scaled(img: DynamicImage) -> Vec<u8> {
|
|
|
+ let img = img.to_rgba8();
|
|
|
+ if img.width() == ICON_SIZE && img.height() == ICON_SIZE {
|
|
|
+ return img.into_raw();
|
|
|
+ }
|
|
|
+ image::imageops::resize(&img, ICON_SIZE, ICON_SIZE, FilterType::Lanczos3).into_raw()
|
|
|
+}
|