//! 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; use std::path::PathBuf; use clap::{Parser, Subcommand}; use libadwaita as adw; use adw::prelude::*; use adw::{Application, ApplicationWindow}; 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::gdk::prelude::{DeviceExt, SeatExt, ToplevelExt}; use gtk4::gdk; use webkit6::prelude::*; use webkit6::{ CookieAcceptPolicy, CookiePersistentStorage, NetworkSession, 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, ); } /// WebView with injected bridge + script handler; call after `window` exists so moves target it. fn build_appiphany_webview(window: &ApplicationWindow, network_session: &NetworkSession) -> 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 = WebView::builder() .user_content_manager(&ucm) .network_session(network_session) .build(); if let Some(settings) = WebViewExt::settings(&webview) { settings.set_user_agent_with_application_details( Some("appiphany"), Some(env!("CARGO_PKG_VERSION")), ); } 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(); 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 load_uri_into_overlay_webview(win: &ApplicationWindow, url: &str) { let Some(shell) = win.content() else { return; }; let Some(overlay) = shell.downcast_ref::() else { return; }; if let Some(child) = overlay.child() { if let Ok(webview) = child.downcast::() { webview.load_uri(url); return; } } 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 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, } #[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) => { eprintln!("appiphany: expected 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!("appiphany: {msg}"); glib::ExitCode::from(1) } }; } if let Err(msg) = normalize_url(parsed.url.as_ref().expect("validated")) { eprintln!("appiphany: {msg}"); return glib::ExitCode::from(2); } if let Err(e) = adw::init() { eprintln!("appiphany: failed to initialize libadwaita: {e}"); return glib::ExitCode::from(1); } let app = Application::builder() .application_id("dev.appiphany.app") .flags(ApplicationFlags::HANDLES_COMMAND_LINE) .build(); app.connect_command_line(|app, cmdline| { let 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); } }; if args.len() != 2 { eprintln!("Usage: appiphany "); 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); } }; if let Some(gtk_win) = app.active_window() { if let Some(win) = gtk_win.downcast_ref::() { 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(); glib::ExitCode::SUCCESS }); app.run() }