Quellcode durchsuchen

Ability to generate desktop files

Johannes Zellner vor 7 Monaten
Ursprung
Commit
daef098985
4 geänderte Dateien mit 1256 neuen und 56 gelöschten Zeilen
  1. 818 46
      Cargo.lock
  2. 6 0
      Cargo.toml
  3. 326 0
      src/desktop_install.rs
  4. 106 10
      src/main.rs

Datei-Diff unterdrückt, da er zu groß ist
+ 818 - 46
Cargo.lock


+ 6 - 0
Cargo.toml

@@ -4,6 +4,12 @@ version = "0.1.0"
 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"
+ureq = { version = "2.12", features = ["native-certs"] }
+url = "2.5"
 webkit6 = "0.6.1"

+ 326 - 0
src/desktop_install.rs

@@ -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()
+}

+ 106 - 10
src/main.rs

@@ -1,5 +1,12 @@
+//! GTK/WebKit shell for a URL. Webapps can detect this host with `html[data-webruntime]` (CSS),
+//! `window.webruntime.version`, or `navigator.userAgent` (application details append `webruntime`
+//! and the crate version). See the `HOST_MARKER_ATTR` constant below.
+
+mod desktop_install;
+
 use std::path::PathBuf;
 
+use clap::{Parser, Subcommand};
 use libadwaita as adw;
 
 use adw::prelude::*;
@@ -24,18 +31,27 @@ const WINDOW_DRAG_MESSAGE_HANDLER: &str = "webruntimeWindowDrag";
 /// Mark draggable chrome in your HTML, e.g. `<div data-webruntime-window-drag>…</div>`.
 const WINDOW_DRAG_ATTR: &str = "data-webruntime-window-drag";
 
+/// Host detection for embedded webapps (set on `<html>` at document start).
+///
+/// **Stable API:** Pages can target webruntime with CSS, e.g. `html[data-webruntime] { … }`,
+/// read `document.documentElement.hasAttribute("data-webruntime")`, or use
+/// `window.webruntime.version`. The User-Agent also includes application details
+/// (`set_user_agent_with_application_details("webruntime", version)`), so
+/// `navigator.userAgent` contains a webruntime token for JS or server-side checks.
+const HOST_MARKER_ATTR: &str = "data-webruntime";
+
 /// Lazily created shared profile; one store for every origin (WebKit partitions internally).
 const APP_NETWORK_SESSION_KEY: &str = "webruntime-network-session";
 
-/// JS bridge: on mousedown inside a `[data-webruntime-window-drag]` region, we
-/// wait one animation frame to let the page's own handlers call preventDefault().
-/// If the event was NOT prevented and no interactive element was the direct
-/// target, we fire the native drag message. A synthetic pointerup is dispatched
-/// first so WebKit's pointer state machine stays clean after begin_move steals
-/// the grab.
-fn window_drag_bridge_source() -> String {
+/// Injected at document start: sets `html[data-webruntime]`, `window.webruntime`, and the
+/// window-drag bridge (mousedown inside `[data-webruntime-window-drag]` …).
+fn webruntime_document_start_script_source() -> String {
     format!(
         r#"(function () {{
+  try {{
+    document.documentElement.setAttribute("{host_attr}", "");
+    window.webruntime = {{ version: "{version}" }};
+  }} catch (_) {{}}
   const attr = "{attr}";
   const interactive = "A,BUTTON,INPUT,TEXTAREA,SELECT,LABEL,SUMMARY,DETAILS,AUDIO,VIDEO";
   document.addEventListener("mousedown", function (e) {{
@@ -58,6 +74,8 @@ fn window_drag_bridge_source() -> String {
     }});
   }}, false);
 }})();"#,
+        host_attr = HOST_MARKER_ATTR,
+        version = env!("CARGO_PKG_VERSION"),
         attr = WINDOW_DRAG_ATTR,
         handler = WINDOW_DRAG_MESSAGE_HANDLER,
     )
@@ -104,7 +122,7 @@ fn build_webruntime_webview(window: &ApplicationWindow, network_session: &Networ
     }
 
     let script = UserScript::new(
-        &window_drag_bridge_source(),
+        &webruntime_document_start_script_source(),
         UserContentInjectedFrames::AllFrames,
         UserScriptInjectionTime::Start,
         &[],
@@ -117,10 +135,19 @@ fn build_webruntime_webview(window: &ApplicationWindow, network_session: &Networ
         begin_move_from_pointer_on_window(&win);
     });
 
-    WebView::builder()
+    let webview = WebView::builder()
         .user_content_manager(&ucm)
         .network_session(network_session)
-        .build()
+        .build();
+
+    if let Some(settings) = WebViewExt::settings(&webview) {
+        settings.set_user_agent_with_application_details(
+            Some("webruntime"),
+            Some(env!("CARGO_PKG_VERSION")),
+        );
+    }
+
+    webview
 }
 
 /// Full-window web view with Adwaita-style CSD controls overlaid in the top corners (no title bar).
@@ -236,6 +263,35 @@ fn normalize_url(arg: &str) -> Result<String, &'static str> {
     }
 }
 
+#[derive(Parser)]
+#[command(name = "webruntime", version, about = "Minimal WebKit wrapper around a URL")]
+struct Args {
+    #[command(subcommand)]
+    cmd: Option<Cmd>,
+
+    /// URL to open (when no subcommand is used)
+    url: Option<String>,
+}
+
+#[derive(Subcommand)]
+enum Cmd {
+    /// Create a Freedesktop launcher and favicon under ~/.local/share
+    DesktopInstall {
+        /// Page URL for the launcher
+        url: String,
+        /// Display name in the app menu (default: page title or host)
+        #[arg(short = 'n', long)]
+        name: Option<String>,
+        /// Overwrite an existing launcher with the same URL
+        #[arg(long)]
+        force: bool,
+    },
+    /// Remove launcher files by URL or 12-character id (see desktop file name)
+    DesktopUninstall {
+        target: String,
+    },
+}
+
 fn persistent_profile_paths() -> Result<(PathBuf, PathBuf), std::io::Error> {
     let data_dir: PathBuf = glib::user_data_dir()
         .join("webruntime")
@@ -251,6 +307,46 @@ fn persistent_profile_paths() -> Result<(PathBuf, PathBuf), std::io::Error> {
 }
 
 fn main() -> glib::ExitCode {
+    let parsed = match Args::try_parse() {
+        Ok(a) => a,
+        Err(e) => e.exit(),
+    };
+
+    match (&parsed.cmd, &parsed.url) {
+        (Some(_), Some(_)) => {
+            eprintln!("webruntime: cannot pass a URL together with a subcommand");
+            return glib::ExitCode::from(2);
+        }
+        (None, None) => {
+            eprintln!("webruntime: expected <URL> or a subcommand (see --help)");
+            return glib::ExitCode::from(2);
+        }
+        _ => {}
+    }
+
+    if let Some(cmd) = parsed.cmd {
+        let result = match cmd {
+            Cmd::DesktopInstall { url, name, force } => {
+                desktop_install::run_install(&url, name.as_deref(), force, normalize_url)
+            }
+            Cmd::DesktopUninstall { target } => {
+                desktop_install::run_uninstall(&target, normalize_url)
+            }
+        };
+        return match result {
+            Ok(()) => glib::ExitCode::SUCCESS,
+            Err(msg) => {
+                eprintln!("webruntime: {msg}");
+                glib::ExitCode::from(1)
+            }
+        };
+    }
+
+    if let Err(msg) = normalize_url(parsed.url.as_ref().expect("validated")) {
+        eprintln!("webruntime: {msg}");
+        return glib::ExitCode::from(2);
+    }
+
     if let Err(e) = adw::init() {
         eprintln!("webruntime: failed to initialize libadwaita: {e}");
         return glib::ExitCode::from(1);

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.