Bladeren bron

Add launcher manage UI

Johannes Zellner 6 maanden geleden
bovenliggende
commit
d0e2170caa
3 gewijzigde bestanden met toevoegingen van 436 en 52 verwijderingen
  1. 1 1
      Cargo.toml
  2. 183 0
      src/desktop_install.rs
  3. 252 51
      src/main.rs

+ 1 - 1
Cargo.toml

@@ -6,7 +6,7 @@ edition = "2024"
 [dependencies]
 clap = { version = "4.5", features = ["derive"] }
 gtk4 = "0.11.1"
-libadwaita = "0.9.1"
+libadwaita = { version = "0.9.1", features = ["v1_9"] }
 scraper = "0.22"
 sha2 = "0.10"
 ureq = { version = "2.12", features = ["native-certs"] }

+ 183 - 0
src/desktop_install.rs

@@ -9,6 +9,22 @@ use url::Url;
 
 const ID_HEX_LEN: usize = 12;
 
+#[derive(Clone, Debug)]
+pub enum LauncherIcon {
+    /// Load via `gtk::Image::from_file`
+    File(PathBuf),
+    /// Load via `gtk::Image::from_icon_name`
+    Themed(String),
+}
+
+#[derive(Clone, Debug)]
+pub struct DesktopLauncher {
+    pub id: String,
+    pub name: Option<String>,
+    pub url: Option<String>,
+    pub icon: LauncherIcon,
+}
+
 pub fn run_install(
     url_arg: &str,
     display_name: Option<&str>,
@@ -128,6 +144,51 @@ pub fn run_uninstall(
     Ok(())
 }
 
+pub fn list_launchers() -> Result<Vec<DesktopLauncher>, String> {
+    let data_home = xdg_data_home();
+    let apps_dir = data_home.join("applications");
+    let mut out = Vec::new();
+    let entries = match std::fs::read_dir(&apps_dir) {
+        Ok(entries) => entries,
+        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
+        Err(e) => return Err(e.to_string()),
+    };
+
+    for ent in entries.flatten() {
+        let path = ent.path();
+        if !path.is_file() {
+            continue;
+        }
+        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
+            continue;
+        };
+        if !(name.starts_with("appiphany-") && name.ends_with(".desktop")) {
+            continue;
+        }
+
+        let id = name
+            .strip_prefix("appiphany-")
+            .and_then(|s| s.strip_suffix(".desktop"))
+            .unwrap_or_default()
+            .to_string();
+        if id.len() != ID_HEX_LEN || !id.chars().all(|c| c.is_ascii_hexdigit()) {
+            continue;
+        }
+
+        let (entry_name, entry_url, icon_line) = parse_desktop_entry(&path);
+        let icon = resolve_launcher_icon(&data_home, &id, icon_line.as_deref());
+        out.push(DesktopLauncher {
+            id,
+            name: entry_name,
+            url: entry_url,
+            icon,
+        });
+    }
+
+    out.sort_by(|a, b| a.id.cmp(&b.id));
+    Ok(out)
+}
+
 fn stable_id(url: &str) -> String {
     let mut h = Sha256::new();
     h.update(url.as_bytes());
@@ -412,6 +473,128 @@ fn pick_icon_extension(icon_url: &str, content_type: Option<&str>, bytes: &[u8])
         .unwrap_or("ico")
 }
 
+fn parse_desktop_entry(path: &Path) -> (Option<String>, Option<String>, Option<String>) {
+    let Ok(body) = std::fs::read_to_string(path) else {
+        return (None, None, None);
+    };
+    let mut name = None;
+    let mut exec = None;
+    let mut icon = None;
+
+    for line in body.lines() {
+        if let Some(rest) = line.strip_prefix("Name=") {
+            name = Some(rest.to_string());
+        } else if let Some(rest) = line.strip_prefix("Exec=") {
+            exec = Some(rest.to_string());
+        } else if let Some(rest) = line.strip_prefix("Icon=") {
+            icon = Some(rest.to_string());
+        }
+    }
+
+    let url = exec.as_deref().and_then(extract_url_from_exec);
+    (name, url, icon)
+}
+
+fn find_appiphany_icon_file(data_home: &Path, id: &str) -> Option<PathBuf> {
+    let icon_dir = appiphany_icon_dir(data_home);
+    let prefix = format!("appiphany-{id}.");
+    let mut paths: Vec<PathBuf> = std::fs::read_dir(&icon_dir)
+        .ok()?
+        .flatten()
+        .filter_map(|e| {
+            let p = e.path();
+            if !p.is_file() {
+                return None;
+            }
+            let fname = e.file_name();
+            if fname.to_string_lossy().starts_with(&prefix) {
+                Some(p)
+            } else {
+                None
+            }
+        })
+        .collect();
+    if paths.is_empty() {
+        return None;
+    }
+    let score = |p: &Path| {
+        let ext = p
+            .extension()
+            .and_then(|e| e.to_str())
+            .unwrap_or("")
+            .to_ascii_lowercase();
+        match ext.as_str() {
+            "png" => 0,
+            "svg" | "svgz" => 1,
+            "webp" => 2,
+            "ico" => 3,
+            "jpg" | "jpeg" | "gif" => 4,
+            _ => 5,
+        }
+    };
+    paths.sort_by(|a, b| {
+        score(a)
+            .cmp(&score(b))
+            .then_with(|| a.to_string_lossy().cmp(&b.to_string_lossy()))
+    });
+    paths.into_iter().next()
+}
+
+fn resolve_launcher_icon(data_home: &Path, id: &str, icon_line: Option<&str>) -> LauncherIcon {
+    if let Some(p) = find_appiphany_icon_file(data_home, id) {
+        return LauncherIcon::File(p);
+    }
+    let legacy = legacy_hicolor_icon_path(data_home, id);
+    if legacy.is_file() {
+        return LauncherIcon::File(legacy);
+    }
+    if let Some(raw) = icon_line.map(str::trim).filter(|s| !s.is_empty()) {
+        if raw.contains('/') {
+            let p = PathBuf::from(raw);
+            if p.is_file() {
+                return LauncherIcon::File(p);
+            }
+        } else {
+            return LauncherIcon::Themed(raw.to_string());
+        }
+    }
+    LauncherIcon::Themed("applications-internet".to_string())
+}
+
+fn extract_url_from_exec(exec_line: &str) -> Option<String> {
+    let quoted = extract_quoted_tokens(exec_line);
+    if let Some(last) = quoted.last() {
+        return Some(last.clone());
+    }
+    exec_line.split_whitespace().last().map(str::to_string)
+}
+
+fn extract_quoted_tokens(s: &str) -> Vec<String> {
+    let mut out = Vec::new();
+    let mut chars = s.chars().peekable();
+
+    while let Some(ch) = chars.next() {
+        if ch != '"' {
+            continue;
+        }
+        let mut token = String::new();
+        while let Some(c) = chars.next() {
+            if c == '\\' {
+                if let Some(next) = chars.next() {
+                    token.push(next);
+                }
+                continue;
+            }
+            if c == '"' {
+                break;
+            }
+            token.push(c);
+        }
+        out.push(token);
+    }
+    out
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;

+ 252 - 51
src/main.rs

@@ -6,17 +6,22 @@ mod desktop_install;
 
 use std::path::PathBuf;
 
+use desktop_install::LauncherIcon;
+
 use clap::{Parser, Subcommand};
 use libadwaita as adw;
 
 use adw::prelude::*;
-use adw::{Application, ApplicationWindow};
+use adw::{Application, ApplicationWindow, PreferencesGroup};
 use gtk4::gio::ApplicationFlags;
 use gtk4::gio::prelude::ApplicationExtManual;
 use gtk4::glib;
 use gtk4::glib::prelude::{Cast, IsA, ObjectExt};
-use gtk4::prelude::{NativeExt, WidgetExt};
-use gtk4::{Align, Overlay, PackType, WindowControls};
+use gtk4::prelude::{GtkWindowExt, NativeExt, WidgetExt};
+use gtk4::{
+    Align, Box as GtkBox, Button, Entry, Image, ListBox, Orientation, Overlay, PackType,
+    ScrolledWindow, SelectionMode, WindowControls,
+};
 use gtk4::gdk::prelude::{DeviceExt, SeatExt, ToplevelExt};
 use gtk4::gdk;
 use webkit6::prelude::*;
@@ -253,30 +258,239 @@ fn build_persistent_network_session() -> NetworkSession {
     session
 }
 
-fn load_uri_into_overlay_webview(win: &ApplicationWindow, url: &str) {
-    let Some(shell) = win.content() else {
-        return;
-    };
-    let Some(overlay) = shell.downcast_ref::<Overlay>() else {
-        return;
+fn open_web_window(app: &Application, url: &str) {
+    let window = ApplicationWindow::builder()
+        .application(app)
+        .title("Appiphany")
+        .default_width(1024)
+        .default_height(768)
+        .build();
+
+    let network_session = network_session_for_app(app);
+    let webview = build_appiphany_webview(&window, &network_session);
+    let shell = build_overlay_with_webview(&webview);
+    window.set_content(Some(&shell));
+    webview.load_uri(url);
+    window.present();
+}
+
+fn launcher_icon_image(icon: &LauncherIcon) -> Image {
+    let img = match icon {
+        LauncherIcon::File(path) => Image::from_file(path),
+        LauncherIcon::Themed(name) => Image::from_icon_name(name),
     };
+    img.set_pixel_size(32);
+    img.set_valign(Align::Center);
+    img
+}
+
+fn clear_listbox_rows(list: &ListBox) {
+    while let Some(row) = list.row_at_index(0) {
+        list.remove(&row);
+    }
+}
 
-    if let Some(child) = overlay.child() {
-        if let Ok(webview) = child.downcast::<WebView>() {
-            webview.load_uri(url);
-            return;
+fn refresh_launchers_list(
+    list: &ListBox,
+    app: &Application,
+    manager_window: &ApplicationWindow,
+) {
+    clear_listbox_rows(list);
+    match desktop_install::list_launchers() {
+        Ok(launchers) => {
+            if launchers.is_empty() {
+                let row = adw::ActionRow::builder()
+                    .title("No launchers found")
+                    .activatable(false)
+                    .selectable(false)
+                    .build();
+                row.add_prefix(&launcher_icon_image(&LauncherIcon::Themed(
+                    "applications-internet".to_string(),
+                )));
+                list.append(&row);
+            } else {
+                for launcher in launchers {
+                    let (title, subtitle) = if let Some(url) = &launcher.url {
+                        (
+                            launcher
+                                .name
+                                .as_deref()
+                                .unwrap_or("Unnamed")
+                                .to_string(),
+                            url.clone(),
+                        )
+                    } else {
+                        (
+                            launcher
+                                .name
+                                .unwrap_or_else(|| "Unnamed".to_string()),
+                            format!("ID {}", launcher.id),
+                        )
+                    };
+
+                    let row = adw::ActionRow::builder()
+                        .title(&title)
+                        .subtitle(&subtitle)
+                        .subtitle_lines(2)
+                        .activatable(false)
+                        .selectable(false)
+                        .build();
+
+                    row.add_prefix(&launcher_icon_image(&launcher.icon));
+
+                    let actions = GtkBox::new(Orientation::Horizontal, 6);
+                    actions.set_valign(Align::Center);
+
+                    let open_btn = Button::with_label("Open");
+                    open_btn.add_css_class("flat");
+                    open_btn.set_valign(Align::Center);
+                    let uninstall_btn = Button::with_label("Unregister");
+                    uninstall_btn.add_css_class("flat");
+                    uninstall_btn.set_valign(Align::Center);
+
+                    let id = launcher.id.clone();
+                    let url = launcher.url.clone();
+                    let app_open = app.clone();
+                    open_btn.connect_clicked(move |_| {
+                        if let Some(url) = &url {
+                            open_web_window(&app_open, url);
+                        } else {
+                            eprintln!("appiphany: launcher has no URL in Exec entry");
+                        }
+                    });
+
+                    let list_uninstall = list.clone();
+                    let app_uninstall = app.clone();
+                    let manager_window_uninstall = manager_window.clone();
+                    uninstall_btn.connect_clicked(move |_| {
+                        let dialog = adw::AlertDialog::new(
+                            Some("Unregister launcher?"),
+                            Some("This will remove the launcher entry and stored icons."),
+                        );
+                        dialog.add_response("cancel", "Cancel");
+                        dialog.add_response("unregister", "Unregister");
+                        dialog.set_close_response("cancel");
+                        dialog.set_default_response(Some("cancel"));
+                        dialog.set_response_appearance("unregister", adw::ResponseAppearance::Destructive);
+
+                        let id = id.clone();
+                        let list_uninstall = list_uninstall.clone();
+                        let app_uninstall = app_uninstall.clone();
+                        let manager_window_for_response = manager_window_uninstall.clone();
+                        dialog.connect_response(Some("unregister"), move |_, _| {
+                            match desktop_install::run_uninstall(&id, normalize_url) {
+                                Ok(()) => refresh_launchers_list(
+                                    &list_uninstall,
+                                    &app_uninstall,
+                                    &manager_window_for_response,
+                                ),
+                                Err(e) => eprintln!("appiphany: unregister failed: {e}"),
+                            }
+                        });
+                        dialog.present(Some(&manager_window_uninstall));
+                    });
+
+                    actions.append(&open_btn);
+                    actions.append(&uninstall_btn);
+                    row.add_suffix(&actions);
+
+                    list.append(&row);
+                }
+            }
+        }
+        Err(e) => {
+            eprintln!("appiphany: failed to list launchers: {e}");
         }
     }
+}
 
-    let Some(app) = win.application() else {
-        return;
-    };
-    let session = network_session_for_app(&app);
-    let webview = build_appiphany_webview(win, &session);
-    webview.set_hexpand(true);
-    webview.set_vexpand(true);
-    overlay.set_child(Some(&webview));
-    webview.load_uri(url);
+fn build_manager_window(app: &Application) {
+    let header = adw::HeaderBar::new();
+    let window_title = adw::WindowTitle::new("Appiphany", "Run webapps as native windows");
+    header.set_title_widget(Some(&window_title));
+    header.set_show_end_title_buttons(true);
+    header.set_show_start_title_buttons(false);
+
+    let window = ApplicationWindow::builder()
+        .application(app)
+        .title("Appiphany")
+        .default_width(900)
+        .default_height(640)
+        .build();
+
+    window.set_resizable(true);
+    window.set_size_request(420, 320);
+
+    let root = GtkBox::new(Orientation::Vertical, 12);
+    root.set_margin_top(12);
+    root.set_margin_bottom(12);
+    root.set_margin_start(12);
+    root.set_margin_end(12);
+
+    let open_row = GtkBox::new(Orientation::Horizontal, 8);
+    let url_entry = Entry::new();
+    url_entry.set_hexpand(true);
+    url_entry.set_placeholder_text(Some("https://example.com"));
+    let open_button = Button::with_label("Open");
+    let create_button = Button::with_label("Create Launcher");
+    open_row.append(&url_entry);
+    open_row.append(&open_button);
+    open_row.append(&create_button);
+
+    let launchers_group = PreferencesGroup::builder()
+        .title("Installed launchers")
+        .build();
+    let list = ListBox::new();
+    list.add_css_class("boxed-list");
+    list.set_selection_mode(SelectionMode::None);
+    launchers_group.add(&list);
+    let list_scroll = ScrolledWindow::builder()
+        .vexpand(true)
+        .hexpand(true)
+        .child(&launchers_group)
+        .build();
+    let app_open = app.clone();
+    let entry_open = url_entry.clone();
+    open_button.connect_clicked(move |_| {
+        let raw = entry_open.text().to_string();
+        match normalize_url(&raw) {
+            Ok(url) => open_web_window(&app_open, &url),
+            Err(msg) => eprintln!("appiphany: {msg}"),
+        }
+    });
+
+    let entry_create = url_entry.clone();
+    let list_create = list.clone();
+    let app_create = app.clone();
+    let manager_window_create = window.clone();
+    create_button.connect_clicked(move |_| {
+        let raw = entry_create.text().to_string();
+        match normalize_url(&raw) {
+            Ok(url) => match desktop_install::run_install(&url, None, true, normalize_url) {
+                Ok(()) => refresh_launchers_list(
+                    &list_create,
+                    &app_create,
+                    &manager_window_create,
+                ),
+                Err(e) => eprintln!("appiphany: create launcher failed: {e}"),
+            },
+            Err(msg) => eprintln!("appiphany: {msg}"),
+        }
+    });
+
+    root.append(&open_row);
+    root.append(&list_scroll);
+
+    root.set_hexpand(true);
+    root.set_vexpand(true);
+
+    let shell = adw::ToolbarView::new();
+    shell.add_top_bar(&header);
+    shell.set_content(Some(&root));
+
+    window.set_content(Some(&shell));
+    refresh_launchers_list(&list, app, &window);
+    window.present();
 }
 
 fn normalize_url(arg: &str) -> Result<String, &'static str> {
@@ -348,10 +562,7 @@ fn main() -> glib::ExitCode {
             eprintln!("appiphany: cannot pass a URL together with a subcommand");
             return glib::ExitCode::from(2);
         }
-        (None, None) => {
-            eprintln!("appiphany: expected <URL> or a subcommand (see --help)");
-            return glib::ExitCode::from(2);
-        }
+        (None, None) => {}
         _ => {}
     }
 
@@ -373,9 +584,11 @@ fn main() -> glib::ExitCode {
         };
     }
 
-    if let Err(msg) = normalize_url(parsed.url.as_ref().expect("validated")) {
-        eprintln!("appiphany: {msg}");
-        return glib::ExitCode::from(2);
+    if let Some(url) = parsed.url.as_deref() {
+        if let Err(msg) = normalize_url(url) {
+            eprintln!("appiphany: {msg}");
+            return glib::ExitCode::from(2);
+        }
     }
 
     if let Err(e) = adw::init() {
@@ -402,8 +615,16 @@ fn main() -> glib::ExitCode {
             }
         };
 
+        if args.len() == 1 {
+            if app.active_window().is_none() {
+                build_manager_window(app);
+            } else if let Some(win) = app.active_window() {
+                win.present();
+            }
+            return glib::ExitCode::SUCCESS;
+        }
         if args.len() != 2 {
-            eprintln!("Usage: appiphany <url>");
+            eprintln!("Usage: appiphany [url]");
             return glib::ExitCode::from(2);
         }
 
@@ -415,27 +636,7 @@ fn main() -> glib::ExitCode {
             }
         };
 
-        if let Some(gtk_win) = app.active_window() {
-            if let Some(win) = gtk_win.downcast_ref::<ApplicationWindow>() {
-                load_uri_into_overlay_webview(win, &url);
-            }
-            gtk_win.present();
-            return glib::ExitCode::SUCCESS;
-        }
-
-        let window = ApplicationWindow::builder()
-            .application(app)
-            .title("Appiphany")
-            .default_width(1024)
-            .default_height(768)
-            .build();
-
-        let network_session = network_session_for_app(app);
-        let webview = build_appiphany_webview(&window, &network_session);
-        let shell = build_overlay_with_webview(&webview);
-        window.set_content(Some(&shell));
-        webview.load_uri(&url);
-        window.present();
+        open_web_window(app, &url);
         glib::ExitCode::SUCCESS
     });