//! GTK/WebKit shell for a URL. Webapps can detect this host with `html[data-appiphany]` (CSS), //! `window.appiphany.version`, or `navigator.userAgent` (application details append `appiphany` //! and the crate version). See the `HOST_MARKER_ATTR` constant below. mod desktop_install; mod locale; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use desktop_install::LauncherIcon; use clap::{Parser, Subcommand}; use libadwaita as adw; use adw::prelude::*; 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::{GtkWindowExt, NativeExt, WidgetExt}; use gtk4::{ Align, Box as GtkBox, Button, Entry, Image, ListBox, Orientation, Overlay, PackType, PolicyType, ScrolledWindow, SelectionMode, WindowControls, }; use gtk4::gdk::prelude::{DeviceExt, SeatExt, ToplevelExt}; use gtk4::gdk; use webkit6::prelude::*; use webkit6::{ CookieAcceptPolicy, CookiePersistentStorage, NavigationAction, NavigationPolicyDecision, NavigationType, NetworkSession, PolicyDecisionType, ResponsePolicyDecision, UserContentInjectedFrames, UserContentManager, UserScript, UserScriptInjectionTime, WebView, }; /// JavaScript `window.webkit.messageHandlers.` must match this identifier. const WINDOW_DRAG_MESSAGE_HANDLER: &str = "appiphanyWindowDrag"; /// Mark draggable regions in HTML, e.g. `
…
`. const WINDOW_DRAG_ATTR: &str = "data-appiphany-window-drag"; /// Host detection for embedded webapps (set on `` at document start). /// /// **Stable API:** Pages can target appiphany with CSS, e.g. `html[data-appiphany] { … }`, /// read `document.documentElement.hasAttribute("data-appiphany")`, or use /// `window.appiphany.version`. The User-Agent also includes application details /// (`set_user_agent_with_application_details("appiphany", version)`), so /// `navigator.userAgent` contains an appiphany token for JS or server-side checks. const HOST_MARKER_ATTR: &str = "data-appiphany"; /// Lazily created shared profile; one store for every origin (WebKit partitions internally). const APP_NETWORK_SESSION_KEY: &str = "appiphany-network-session"; /// Injected at document start: sets `html[data-appiphany]` and exposes `window.appiphany` API. /// Enables window dragging from non-interactive elements inside `[data-appiphany-window-drag]`. fn appiphany_document_start_script_source() -> String { format!( r#"(function () {{ try {{ document.documentElement.setAttribute("{host_attr}", ""); }} catch (_) {{}} window.appiphany = {{ version: "{version}" }}; var dragState = null; var dragAttr = "{drag_attr}"; var interactive = "A,BUTTON,INPUT,TEXTAREA,SELECT,LABEL,SUMMARY,DETAILS,AUDIO,VIDEO"; function isInteractive(el) {{ if (!el || el === document.documentElement || el === document.body) return false; if (el.isContentEditable) return true; if (el.closest && el.closest(interactive)) return true; if (el.onclick || el.onmousedown || el.onmouseup) return true; return false; }} function beginNativeDrag() {{ try {{ window.webkit.messageHandlers.{handler}.postMessage(null); }} catch (_) {{}} }} function onMouseMove(e) {{ if (!dragState) return; var dx = e.clientX - dragState.startX; var dy = e.clientY - dragState.startY; if (Math.abs(dx) > 3 || Math.abs(dy) > 3) {{ cleanup(); beginNativeDrag(); }} }} function cleanup() {{ if (dragState) {{ document.removeEventListener("mousemove", onMouseMove, true); document.removeEventListener("mouseup", cleanup, true); dragState = null; }} }} document.addEventListener("mousedown", function (e) {{ if (e.button !== 0) return; var el = e.target; if (!el || typeof el.closest !== "function") return; if (!el.closest("[" + dragAttr + "]")) return; if (isInteractive(el)) return; cleanup(); dragState = {{ startX: e.clientX, startY: e.clientY }}; document.addEventListener("mousemove", onMouseMove, true); document.addEventListener("mouseup", cleanup, true); }}, false); }})();"#, host_attr = HOST_MARKER_ATTR, version = env!("CARGO_PKG_VERSION"), drag_attr = WINDOW_DRAG_ATTR, handler = WINDOW_DRAG_MESSAGE_HANDLER, ) } /// Called when the web app requests window dragging via `window.appiphany.startWindowDrag()`. fn begin_move_from_pointer_on_window(window: &ApplicationWindow) { let Some(display) = gdk::Display::default() else { return; }; let Some(seat) = display.default_seat() else { return; }; let Some(device) = seat.pointer() else { return; }; let (ptr_surface, x, y) = device.surface_at_position(); let Some(ptr_surface) = ptr_surface else { return; }; let Some(our_surface) = window.native().and_then(|n| n.surface()) else { return; }; if ptr_surface != our_surface { return; } let Some(toplevel) = our_surface.dynamic_cast_ref::() else { return; }; toplevel.begin_move( &device, gdk::BUTTON_PRIMARY as i32, x, y, gdk::CURRENT_TIME, ); } /// True when navigation targets the `_blank` browsing context (e.g. ``). fn navigation_targets_blank_frame(action: &NavigationAction) -> bool { action .frame_name() .as_deref() .is_some_and(|n| n.eq_ignore_ascii_case("_blank")) } /// Extract the origin (scheme + host + port) from a URL. fn url_origin(url: &str) -> Option { let parsed = url::Url::parse(url).ok()?; if parsed.scheme() == "blob" { let inner = url.strip_prefix("blob:")?; return url_origin(inner); } let scheme = parsed.scheme(); let host = parsed.host_str()?; let port = parsed.port_or_known_default()?; Some(format!("{}://{}:{}", scheme, host, port)) } /// Check if two URLs share the same origin (scheme + host + port). fn is_same_origin(url_a: &str, url_b: &str) -> bool { match (url_origin(url_a), url_origin(url_b)) { (Some(a), Some(b)) => a == b, _ => false, } } /// Open a URI in the system's default browser. fn open_in_system_browser(uri: &str) { let scheme = uri.split(':').next().unwrap_or(""); if !matches!(scheme, "http" | "https" | "ftp") { return; } if let Err(e) = gtk4::gio::AppInfo::launch_default_for_uri(uri, Option::<>k4::gio::AppLaunchContext>::None) { eprintln!("appiphany: failed to open URI in system browser: {}", e); } } /// `window.open()` and `target="_blank"` both go through [`PolicyDecisionType::NewWindowAction`]. /// Links that target `_blank` load in this view; other new-window requests get a real window via /// [`WebViewExt::connect_create`]. fn wire_webview_window_policy( host_window: &ApplicationWindow, webview: &WebView, network_session: &NetworkSession, initial_url: String, ) { let network_for_create = network_session.clone(); let host_window_for_create = host_window.clone(); let initial_url_for_nav = initial_url.clone(); let initial_url_for_create = initial_url.clone(); let initial_url_for_create_2 = initial_url.clone(); webview.connect_decide_policy(move |w, decision, decision_type| { if decision_type == PolicyDecisionType::Response { if let Some(rpd) = decision.dynamic_cast_ref::() { if !rpd.is_mime_type_supported() && rpd.is_main_frame_main_resource() { decision.download(); return true; } } return false; } let Some(nav_decision) = decision.dynamic_cast_ref::() else { return false; }; let Some(action) = nav_decision.navigation_action() else { return false; }; let Some(uri) = action.request().and_then(|r| r.uri()) else { return false; }; if decision_type == PolicyDecisionType::NavigationAction { if action.navigation_type() == NavigationType::LinkClicked && !is_same_origin(&initial_url_for_nav, &uri) { decision.ignore(); open_in_system_browser(&uri); return true; } return false; } if decision_type != PolicyDecisionType::NewWindowAction { return false; } if action.navigation_type() == NavigationType::LinkClicked && action.mouse_button() != 2 && navigation_targets_blank_frame(&action) { decision.ignore(); if is_same_origin(&initial_url_for_create, &uri) { w.load_uri(&uri); } else { open_in_system_browser(&uri); } return true; } if !is_same_origin(&initial_url_for_create, &uri) { decision.ignore(); open_in_system_browser(&uri); return true; } decision.use_(); true }); webview.connect_create(move |parent, _action| { let app = host_window_for_create.application()?; let window = ApplicationWindow::builder() .application(&app) .title("Appiphany") .default_width(1024) .default_height(768) .build(); let popup = build_appiphany_webview(&window, &network_for_create, Some(parent), initial_url_for_create_2.clone()); let shell = build_overlay_with_webview(&popup); window.set_content(Some(&shell)); window.present(); Some(popup.upcast::()) }); } /// WebView with injected bridge + script handler; call after `window` exists so moves target it. /// /// `related_to` should be the opener when this view is created for `window.open()` so WebKit can /// share the rendering process with the parent. /// `initial_url` is used to determine whether navigation should stay in the app or open in the /// system browser. fn build_appiphany_webview( window: &ApplicationWindow, network_session: &NetworkSession, related_to: Option<&WebView>, initial_url: String, ) -> WebView { let ucm = UserContentManager::new(); if !ucm.register_script_message_handler(WINDOW_DRAG_MESSAGE_HANDLER, None) { eprintln!("appiphany: failed to register `{WINDOW_DRAG_MESSAGE_HANDLER}` message handler"); } let script = UserScript::new( &appiphany_document_start_script_source(), UserContentInjectedFrames::AllFrames, UserScriptInjectionTime::Start, &[], &[], ); ucm.add_script(&script); let win = window.clone(); ucm.connect_script_message_received(Some(WINDOW_DRAG_MESSAGE_HANDLER), move |_ucm, _value| { begin_move_from_pointer_on_window(&win); }); let webview = { let b = WebView::builder() .user_content_manager(&ucm) .network_session(network_session); let b = if let Some(rv) = related_to { b.related_view(rv) } else { b }; b.build() }; if let Some(settings) = WebViewExt::settings(&webview) { settings.set_user_agent_with_application_details( Some("appiphany"), Some(env!("CARGO_PKG_VERSION")), ); } wire_webview_window_policy(window, &webview, network_session, initial_url); webview } /// Full-window web view with Adwaita-style CSD controls overlaid in the top corners (no title bar). fn build_overlay_with_webview(webview: &WebView) -> Overlay { webview.set_hexpand(true); webview.set_vexpand(true); let overlay = Overlay::new(); overlay.set_child(Some(webview)); let margin = 6; let start = WindowControls::new(PackType::Start); start.set_valign(Align::Start); start.set_halign(Align::Start); start.set_margin_top(margin); start.set_margin_start(margin); overlay.add_overlay(&start); let end = WindowControls::new(PackType::End); end.set_valign(Align::Start); end.set_halign(Align::End); end.set_margin_top(margin); end.set_margin_end(margin); overlay.add_overlay(&end); overlay } /// One persistent [`NetworkSession`] for the whole app: all origins share this profile directory; /// WebKit keeps cookies / storage isolated per origin inside it. fn network_session_for_app(app: &impl IsA) -> NetworkSession { unsafe { let obj = app.as_ref(); if let Some(p) = obj.data::(APP_NETWORK_SESSION_KEY) { return p.as_ref().clone(); } let session = build_persistent_network_session(); session.connect_download_started(|_session, download| { let ctx: Arc< Mutex< Option<( PathBuf, String, )>, >, > = Arc::new(Mutex::new(None)); let ctx_dd = ctx.clone(); download.connect_decide_destination( move |dl, suggested_filename| { let filename = suggested_filename.to_string(); let temp_dir = std::env::temp_dir().join("appiphany-downloads"); std::fs::create_dir_all(&temp_dir).ok(); let dest_path = temp_dir.join(&filename); if let Some(dest) = dest_path.to_str() { dl.set_destination(dest); dl.set_allow_overwrite(true); } *ctx_dd.lock().unwrap() = Some(( dest_path.clone(), filename.clone(), )); let action_arc: Arc>> = Arc::new(Mutex::new(None)); { let ctx_fin = ctx_dd.clone(); let action_fin = action_arc.clone(); dl.connect_finished(move |_| { let state = ctx_fin.lock().unwrap(); if let Some((ref path, ref name)) = *state { eprintln!("appiphany: download finished \"{name}\" -> {:?}", path); let act = action_fin.lock().unwrap().clone(); if act.as_deref() == Some("open") { let file = gtk4::gio::File::for_path(path); match gtk4::gio::AppInfo::launch_default_for_uri( &file.uri(), Option::<>k4::gio::AppLaunchContext>::None, ) { Ok(_) => eprintln!("appiphany: opened {:?}", path), Err(e) => eprintln!( "appiphany: failed to open {:?}: {}", path, e ), } } else if act.as_deref() == Some("cancel") { let _ = std::fs::remove_file(path); } } }); } { let ctx_fail = ctx_dd.clone(); let name = filename.clone(); dl.connect_failed(move |_, err| { eprintln!( "appiphany: download \"{}\" failed: {}", name, err ); if let Some((ref path, _)) = *ctx_fail.lock().unwrap() { let _ = std::fs::remove_file(path); } }); } let parent_win = dl .web_view() .and_then(|wv| wv.root()) .and_then(|r| r.dynamic_cast::().ok()); let ctx_dialog = ctx_dd.clone(); let action_dialog = action_arc.clone(); glib::idle_add_local(move || { let (dest_path_d, filename_d) = { let state = ctx_dialog.lock().unwrap(); state .clone() .unwrap_or_else(|| { ( PathBuf::from("/tmp/appiphany-downloads/download"), String::from("download"), ) }) }; eprintln!( "appiphany: download dialog \"{}\"", filename_d ); let dialog = adw::AlertDialog::new( Some("Download"), Some(&format!( "What would you like to do with \"{}\"?", filename_d )), ); dialog.add_response("open", "Open"); dialog.add_response("save", "Save As..."); dialog.add_response("cancel", "Cancel"); dialog.set_default_response(Some("open")); dialog.set_close_response("cancel"); { let action = action_dialog.clone(); let path = dest_path_d.clone(); dialog.connect_response(Some("open"), move |_, _| { *action.lock().unwrap() = Some("open".into()); if path.exists() { let file = gtk4::gio::File::for_path(&path); match gtk4::gio::AppInfo::launch_default_for_uri( &file.uri(), Option::<>k4::gio::AppLaunchContext>::None, ) { Ok(_) => eprintln!("appiphany: opened {:?}", path), Err(e) => { eprintln!( "appiphany: failed to open {:?}: {}", path, e ) } } } }); } { let action = action_dialog.clone(); let path = dest_path_d.clone(); let name = filename_d.clone(); dialog.connect_response(Some("save"), move |_, _| { *action.lock().unwrap() = Some("save".into()); let file_dialog = gtk4::FileDialog::builder() .title("Save File") .initial_name(&name) .build(); let path2 = path.clone(); let name2 = name.clone(); let action2 = action.clone(); file_dialog.save( None::<>k4::Window>, None::<>k4::gio::Cancellable>, move |result| match result { Ok(file) => { let uri = file.uri(); eprintln!( "appiphany: save \"{name2}\" -> \"{}\"", uri ); if let Some(chosen) = file.path() { let _ = std::fs::copy(&path2, &chosen); eprintln!( "appiphany: saved {:?}", chosen ); } let _ = std::fs::remove_file(&path2); } Err(_) => { eprintln!("appiphany: save cancelled"); *action2.lock().unwrap() = Some("cancel".into()); let _ = std::fs::remove_file(&path2); } }, ); }); } { let action = action_dialog.clone(); let path = dest_path_d.clone(); dialog.connect_response(Some("cancel"), move |_, _| { *action.lock().unwrap() = Some("cancel".into()); eprintln!("appiphany: download cancelled"); let _ = std::fs::remove_file(&path); }); } dialog.present(parent_win.as_ref()); glib::ControlFlow::Break }); true }, ); }); obj.set_data(APP_NETWORK_SESSION_KEY, session.clone()); session } } fn build_persistent_network_session() -> NetworkSession { let session = match persistent_profile_paths() { Ok((data_dir, cache_dir)) => match (data_dir.to_str(), cache_dir.to_str()) { (Some(data), Some(cache)) => NetworkSession::new(Some(data), Some(cache)), _ => { eprintln!("appiphany: non-UTF8 storage path, using ephemeral session"); NetworkSession::new_ephemeral() } }, Err(e) => { eprintln!("appiphany: could not create storage dirs ({e}), using ephemeral session"); NetworkSession::new_ephemeral() } }; session.set_itp_enabled(false); session.set_persistent_credential_storage_enabled(true); if let Some(cm) = session.cookie_manager() { cm.set_accept_policy(CookieAcceptPolicy::Always); if let Ok((data_dir, _)) = persistent_profile_paths() { let cookies_db = data_dir.join("cookies.sqlite"); if let Some(path) = cookies_db.to_str() { cm.set_persistent_storage(path, CookiePersistentStorage::Sqlite); } } } session } fn open_web_window(app: &Application, url: &str) { let (default_w, default_h, maximized) = desktop_install::load_window_state(url) .unwrap_or((1024, 768, false)); let window = ApplicationWindow::builder() .application(app) .title("Appiphany") .default_width(default_w) .default_height(default_h) .build(); if maximized { window.maximize(); } let network_session = network_session_for_app(app); let webview = build_appiphany_webview(&window, &network_session, None, url.to_string()); let shell = build_overlay_with_webview(&webview); window.set_content(Some(&shell)); webview.load_uri(url); let url_owned = url.to_string(); window.connect_close_request(move |win| { let maximized = win.is_maximized(); let width = win.default_width(); let height = win.default_height(); desktop_install::save_window_state(&url_owned, width, height, maximized); glib::Propagation::Proceed }); 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); } } 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}"); } } } 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, 0); root.set_margin_top(12); root.set_margin_bottom(12); root.set_margin_start(12); root.set_margin_end(12); let body = GtkBox::new(Orientation::Vertical, 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); open_row.set_margin_start(12); open_row.set_margin_end(12); let launchers_group = PreferencesGroup::builder() .title("Installed launchers") // Inset from the ScrolledWindow viewport so `.boxed-list` outlines/shadows are not clipped. .margin_start(12) .margin_end(12) .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(); list_scroll.set_policy(PolicyType::Never, PolicyType::Automatic); 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}"), } }); body.append(&open_row); body.append(&list_scroll); body.set_hexpand(true); body.set_vexpand(true); // Same pattern as GNOME Settings / libadwaita preferences: cap content width and center // so `.boxed-list` borders are not clipped by the scrolled viewport on wide windows. let body_clamp = adw::Clamp::builder() .child(&body) .maximum_size(600) .hexpand(true) .vexpand(true) .build(); root.append(&body_clamp); 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 { let t = arg.trim(); if t.is_empty() { return Err("URL must not be empty"); } if t.to_ascii_lowercase().starts_with("about:") { return Err("about: URLs are not supported"); } if t.contains("://") { Ok(t.to_string()) } else { Ok(format!("https://{t}")) } } #[derive(Parser)] #[command(name = "appiphany", version, about = "Minimal WebKit wrapper around a URL")] struct Args { #[command(subcommand)] cmd: Option, /// URL to open (when no subcommand is used) url: Option, /// GApplication ID override (used by desktop launchers for icon matching) #[arg(long, hide = true, global = true)] app_id: Option, } #[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, /// 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("appiphany") .join("profile") .join("data"); let cache_dir: PathBuf = glib::user_cache_dir() .join("appiphany") .join("profile") .join("cache"); std::fs::create_dir_all(&data_dir)?; std::fs::create_dir_all(&cache_dir)?; Ok((data_dir, cache_dir)) } 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!("appiphany: cannot pass a URL together with a subcommand"); return glib::ExitCode::from(2); } (None, None) => {} _ => {} } 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!("appiphany: {msg}"); glib::ExitCode::from(1) } }; } if let Some(url) = parsed.url.as_deref() { if let Err(msg) = normalize_url(url) { eprintln!("appiphany: {msg}"); return glib::ExitCode::from(2); } } let effective_app_id = parsed .app_id .as_deref() .unwrap_or("dev.appiphany.app"); // set_prgname before GTK init so both Wayland and X11 see the right identity. glib::set_prgname(Some(effective_app_id)); if let Err(e) = adw::init() { eprintln!("appiphany: failed to initialize libadwaita: {e}"); return glib::ExitCode::from(1); } // Before any web view/network session exists: the first entry becomes the // JavaScript `Intl` default locale (see `locale`). let languages = locale::apply_to_webkit(); if !languages.is_empty() { eprintln!("appiphany: preferred languages: {}", languages.join(", ")); } let app = Application::builder() .application_id(effective_app_id) .flags(ApplicationFlags::HANDLES_COMMAND_LINE) .build(); locale::watch_region_changes(&app); app.connect_command_line(|app, cmdline| { let raw_args: Vec = match cmdline .arguments() .into_iter() .map(|s| s.into_string()) .collect::, _>>() { Ok(a) => a, Err(_) => { eprintln!("appiphany: arguments must be valid UTF-8"); return glib::ExitCode::from(2); } }; let args: Vec = { let mut filtered = Vec::new(); let mut skip_next = false; for arg in raw_args { if skip_next { skip_next = false; continue; } if arg == "--app-id" { skip_next = true; continue; } if arg.starts_with("--app-id=") { continue; } filtered.push(arg); } filtered }; 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]"); return glib::ExitCode::from(2); } let url = match normalize_url(&args[1]) { Ok(u) => u, Err(msg) => { eprintln!("appiphany: {msg}"); return glib::ExitCode::from(2); } }; open_web_window(app, &url); glib::ExitCode::SUCCESS }); app.run() }