Răsfoiți Sursa

Support all favicon types for desktop files

Johannes Zellner 7 luni în urmă
părinte
comite
5abd19e469
3 a modificat fișierele cu 158 adăugiri și 165 ștergeri
  1. 0 114
      Cargo.lock
  2. 0 1
      Cargo.toml
  3. 158 50
      src/desktop_install.rs

+ 0 - 114
Cargo.lock

@@ -64,7 +64,6 @@ version = "0.1.0"
 dependencies = [
  "clap",
  "gtk4",
- "image",
  "libadwaita",
  "scraper",
  "sha2",
@@ -100,24 +99,12 @@ dependencies = [
  "generic-array",
 ]
 
-[[package]]
-name = "bytemuck"
-version = "1.25.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"
-
 [[package]]
 name = "byteorder"
 version = "1.5.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
 
-[[package]]
-name = "byteorder-lite"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
-
 [[package]]
 name = "cairo-rs"
 version = "0.22.0"
@@ -207,12 +194,6 @@ version = "1.1.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
 
-[[package]]
-name = "color_quant"
-version = "1.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
-
 [[package]]
 name = "colorchoice"
 version = "1.0.5"
@@ -345,15 +326,6 @@ version = "1.0.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
 
-[[package]]
-name = "fdeflate"
-version = "0.3.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
-dependencies = [
- "simd-adler32",
-]
-
 [[package]]
 name = "field-offset"
 version = "0.3.6"
@@ -557,16 +529,6 @@ dependencies = [
  "wasi",
 ]
 
-[[package]]
-name = "gif"
-version = "0.14.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f5df2ba84018d80c213569363bdcd0c64e6933c67fe4c1d60ecf822971a3c35e"
-dependencies = [
- "color_quant",
- "weezl",
-]
-
 [[package]]
 name = "gio"
 version = "0.22.2"
@@ -884,23 +846,6 @@ dependencies = [
  "icu_properties",
 ]
 
-[[package]]
-name = "image"
-version = "0.25.10"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
-dependencies = [
- "bytemuck",
- "byteorder-lite",
- "color_quant",
- "gif",
- "moxcms",
- "num-traits",
- "png",
- "zune-core",
- "zune-jpeg",
-]
-
 [[package]]
 name = "indexmap"
 version = "2.13.1"
@@ -1060,31 +1005,12 @@ dependencies = [
  "simd-adler32",
 ]
 
-[[package]]
-name = "moxcms"
-version = "0.8.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
-dependencies = [
- "num-traits",
- "pxfm",
-]
-
 [[package]]
 name = "new_debug_unreachable"
 version = "1.0.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
 
-[[package]]
-name = "num-traits"
-version = "0.2.19"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
-dependencies = [
- "autocfg",
-]
-
 [[package]]
 name = "once_cell"
 version = "1.21.4"
@@ -1220,19 +1146,6 @@ version = "0.3.32"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
 
-[[package]]
-name = "png"
-version = "0.18.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
-dependencies = [
- "bitflags",
- "crc32fast",
- "fdeflate",
- "flate2",
- "miniz_oxide",
-]
-
 [[package]]
 name = "potential_utf"
 version = "0.1.5"
@@ -1266,12 +1179,6 @@ dependencies = [
  "unicode-ident",
 ]
 
-[[package]]
-name = "pxfm"
-version = "0.1.28"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b5a041e753da8b807c9255f28de81879c78c876392ff2469cde94799b2896b9d"
-
 [[package]]
 name = "quote"
 version = "1.0.45"
@@ -1873,12 +1780,6 @@ dependencies = [
  "rustls-pki-types",
 ]
 
-[[package]]
-name = "weezl"
-version = "0.1.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
-
 [[package]]
 name = "windows-link"
 version = "0.2.1"
@@ -2064,18 +1965,3 @@ dependencies = [
  "quote",
  "syn",
 ]
-
-[[package]]
-name = "zune-core"
-version = "0.5.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"
-
-[[package]]
-name = "zune-jpeg"
-version = "0.5.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
-dependencies = [
- "zune-core",
-]

+ 0 - 1
Cargo.toml

@@ -6,7 +6,6 @@ edition = "2024"
 [dependencies]
 clap = { version = "4.5", features = ["derive"] }
 gtk4 = "0.11.1"
-image = { version = "0.25", default-features = false, features = ["png", "ico", "jpeg", "gif"] }
 libadwaita = "0.9.1"
 scraper = "0.22"
 sha2 = "0.10"

+ 158 - 50
src/desktop_install.rs

@@ -1,15 +1,12 @@
-//! Freedesktop launcher install: `.desktop` entry + hicolor PNG from site favicon.
+//! Freedesktop launcher install: `.desktop` entry + favicon saved as fetched (e.g. SVG, PNG).
 
-use std::io::{Cursor, Read};
-use std::path::PathBuf;
+use std::io::Read;
+use std::path::{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(
@@ -20,16 +17,11 @@ pub fn run_install(
 ) -> Result<(), String> {
     let url = normalize_url(url_arg)?;
     let id = stable_id(&url);
-    let icon_name = format!("appiphany-{id}");
+    let icon_stem = format!("appiphany-{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 icon_dir = appiphany_icon_dir(&data_home);
     let desktop_path = apps_dir.join(format!("appiphany-{id}.desktop"));
-    let icon_path = icon_dir.join(format!("{icon_name}.png"));
 
     if desktop_path.exists() && !force {
         return Err(format!(
@@ -52,19 +44,22 @@ pub fn run_install(
         .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
+    let icon_written = match fetch_favicon_bytes(&url) {
+        Ok((bytes, icon_url, content_type)) => {
+            clear_stored_icons(&icon_dir, &id).map_err(|e| e.to_string())?;
+            let ext = pick_icon_extension(&icon_url, content_type.as_deref(), &bytes);
+            let icon_path = icon_dir.join(format!("{icon_stem}.{ext}"));
+            std::fs::write(&icon_path, bytes).map_err(|e| e.to_string())?;
+            Some(icon_path)
         }
         Err(e) => {
             eprintln!("appiphany: favicon: {e} (launcher will use a generic icon name)");
-            false
+            None
         }
     };
 
-    let icon_value = if icon_written {
-        icon_path
+    let icon_value = if let Some(ref path) = icon_written {
+        path
             .to_str()
             .ok_or("non-UTF8 icon path")?
             .to_string()
@@ -76,8 +71,8 @@ pub fn run_install(
     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());
+    if let Some(ref p) = icon_written {
+        eprintln!("Wrote {}", p.display());
     }
     Ok(())
 }
@@ -97,12 +92,8 @@ pub fn run_uninstall(
     let desktop_path = data_home
         .join("applications")
         .join(format!("appiphany-{id}.desktop"));
-    let icon_path = data_home
-        .join("icons")
-        .join("hicolor")
-        .join(format!("{ICON_SIZE}x{ICON_SIZE}"))
-        .join("apps")
-        .join(format!("appiphany-{id}.png"));
+    let legacy_icon_path = legacy_hicolor_icon_path(&data_home, &id);
+    let icon_dir = appiphany_icon_dir(&data_home);
 
     let mut removed = false;
     if desktop_path.exists() {
@@ -110,11 +101,26 @@ pub fn run_uninstall(
         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());
+    if legacy_icon_path.exists() {
+        std::fs::remove_file(&legacy_icon_path).map_err(|e| e.to_string())?;
+        eprintln!("Removed {}", legacy_icon_path.display());
         removed = true;
     }
+    if let Ok(entries) = std::fs::read_dir(&icon_dir) {
+        let prefix = format!("appiphany-{id}.");
+        for ent in entries.flatten() {
+            let name = ent.file_name();
+            let name = name.to_string_lossy();
+            if name.starts_with(&prefix) {
+                let p = ent.path();
+                if p.is_file() {
+                    std::fs::remove_file(&p).map_err(|e| e.to_string())?;
+                    eprintln!("Removed {}", p.display());
+                    removed = true;
+                }
+            }
+        }
+    }
 
     if !removed {
         return Err(format!("no launcher found for `{target}` (id {id})"));
@@ -139,6 +145,36 @@ fn xdg_data_home() -> PathBuf {
         .unwrap_or_else(|| PathBuf::from("/tmp/.local/share"))
 }
 
+fn appiphany_icon_dir(data_home: &Path) -> PathBuf {
+    data_home.join("icons").join("appiphany")
+}
+
+fn legacy_hicolor_icon_path(data_home: &Path, id: &str) -> PathBuf {
+    data_home
+        .join("icons")
+        .join("hicolor")
+        .join("48x48")
+        .join("apps")
+        .join(format!("appiphany-{id}.png"))
+}
+
+fn clear_stored_icons(icon_dir: &Path, id: &str) -> std::io::Result<()> {
+    if !icon_dir.exists() {
+        return Ok(());
+    }
+    let prefix = format!("appiphany-{id}.");
+    for ent in std::fs::read_dir(icon_dir)?.flatten() {
+        let name = ent.file_name();
+        if name.to_string_lossy().starts_with(&prefix) {
+            let p = ent.path();
+            if p.is_file() {
+                let _ = std::fs::remove_file(p);
+            }
+        }
+    }
+    Ok(())
+}
+
 fn host_label(url: &str) -> String {
     Url::parse(url)
         .ok()
@@ -197,6 +233,14 @@ fn ureq_agent() -> ureq::Agent {
 }
 
 fn fetch_bytes(agent: &ureq::Agent, url: &str) -> Result<Vec<u8>, String> {
+    let (bytes, _) = fetch_bytes_with_content_type(agent, url)?;
+    Ok(bytes)
+}
+
+fn fetch_bytes_with_content_type(
+    agent: &ureq::Agent,
+    url: &str,
+) -> Result<(Vec<u8>, Option<String>), String> {
     let resp = agent
         .get(url)
         .set("User-Agent", "appiphany/1.0 (desktop-install)")
@@ -205,11 +249,14 @@ fn fetch_bytes(agent: &ureq::Agent, url: &str) -> Result<Vec<u8>, String> {
     if !(200..300).contains(&resp.status()) {
         return Err(format!("HTTP {} for {url}", resp.status()));
     }
+    let content_type = resp
+        .header("Content-Type")
+        .map(|s| s.split(';').next().unwrap_or(s).trim().to_ascii_lowercase());
     let mut buf = Vec::new();
     resp.into_reader()
         .read_to_end(&mut buf)
         .map_err(|e| e.to_string())?;
-    Ok(buf)
+    Ok((buf, content_type))
 }
 
 fn fetch_page_title(page_url: &str) -> Option<String> {
@@ -223,7 +270,8 @@ fn fetch_page_title(page_url: &str) -> Option<String> {
         .filter(|s| !s.is_empty())
 }
 
-fn fetch_favicon_png(page_url: &str) -> Result<Vec<u8>, String> {
+/// Returns raw icon bytes, resolved icon URL, and optional Content-Type from the icon response.
+fn fetch_favicon_bytes(page_url: &str) -> Result<(Vec<u8>, String, Option<String>), String> {
     let base = Url::parse(page_url).map_err(|e| e.to_string())?;
     let agent = ureq_agent();
 
@@ -234,9 +282,8 @@ fn fetch_favicon_png(page_url: &str) -> Result<Vec<u8>, String> {
         .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)
+    let (bytes, content_type) = fetch_bytes_with_content_type(&agent, &icon_url)?;
+    Ok((bytes, icon_url, content_type))
 }
 
 struct IconCandidate {
@@ -305,22 +352,83 @@ fn parse_largest_size(sizes: &str) -> Option<i32> {
     }
 }
 
-fn decode_to_png(bytes: &[u8]) -> Result<Vec<u8>, String> {
-    let img = image::load_from_memory(bytes).map_err(|e| e.to_string())?;
+fn extension_from_url_path(icon_url: &str) -> Option<&'static str> {
+    let path = Url::parse(icon_url).ok()?.path().to_ascii_lowercase();
+    let (_, ext) = path.rsplit_once('.')?;
+    match ext {
+        "svg" => Some("svg"),
+        "svgz" => Some("svgz"),
+        "png" => Some("png"),
+        "ico" => Some("ico"),
+        "jpg" | "jpeg" => Some("jpg"),
+        "gif" => Some("gif"),
+        "webp" => Some("webp"),
+        _ => None,
+    }
+}
 
-    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 extension_from_mime(mime: &str) -> Option<&'static str> {
+    match mime.trim() {
+        "image/svg+xml" => Some("svg"),
+        "image/png" => Some("png"),
+        "image/x-icon" | "image/vnd.microsoft.icon" => Some("ico"),
+        "image/jpeg" => Some("jpg"),
+        "image/gif" => Some("gif"),
+        "image/webp" => Some("webp"),
+        _ => None,
+    }
 }
 
-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();
+fn extension_from_magic(bytes: &[u8]) -> Option<&'static str> {
+    if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
+        return Some("png");
+    }
+    if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") {
+        return Some("gif");
+    }
+    if bytes.len() >= 3 && bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff {
+        return Some("jpg");
+    }
+    if bytes.len() >= 4 && bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 1 && bytes[3] == 0 {
+        return Some("ico");
+    }
+    if bytes.len() >= 4 && bytes[0] == 0 && bytes[1] == 0 && bytes[2] == 2 && bytes[3] == 0 {
+        return Some("ico");
+    }
+    let head = bytes.get(..512).unwrap_or(bytes);
+    if let Ok(s) = std::str::from_utf8(head) {
+        let t = s.trim_start();
+        if t.starts_with("<?xml") || t.starts_with("<svg") {
+            return Some("svg");
+        }
+    }
+    None
+}
+
+fn pick_icon_extension(icon_url: &str, content_type: Option<&str>, bytes: &[u8]) -> &'static str {
+    extension_from_url_path(icon_url)
+        .or_else(|| content_type.and_then(extension_from_mime))
+        .or_else(|| extension_from_magic(bytes))
+        .unwrap_or("ico")
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn pick_ext_prefers_url_for_svg() {
+        let ext = pick_icon_extension(
+            "https://example.com/assets/icon.svg?v=1",
+            Some("text/html"),
+            b"<svg></svg>",
+        );
+        assert_eq!(ext, "svg");
+    }
+
+    #[test]
+    fn pick_ext_sniffs_svg_when_no_hint() {
+        let ext = pick_icon_extension("https://example.com/favicon", None, b"  <svg>");
+        assert_eq!(ext, "svg");
     }
-    image::imageops::resize(&img, ICON_SIZE, ICON_SIZE, FilterType::Lanczos3).into_raw()
 }