| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071 |
- //! 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.<name>` must match this identifier.
- const WINDOW_DRAG_MESSAGE_HANDLER: &str = "appiphanyWindowDrag";
- /// Mark draggable regions in HTML, e.g. `<div data-appiphany-window-drag>…</div>`.
- const WINDOW_DRAG_ATTR: &str = "data-appiphany-window-drag";
- /// Host detection for embedded webapps (set on `<html>` 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::<gdk::Toplevel>() 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. `<a target="_blank">`).
- 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<String> {
- 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::<ResponsePolicyDecision>() {
- 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::<NavigationPolicyDecision>() 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::<gtk4::Widget>())
- });
- }
- /// 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<glib::Object>) -> NetworkSession {
- unsafe {
- let obj = app.as_ref();
- if let Some(p) = obj.data::<NetworkSession>(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<Mutex<Option<String>>> =
- 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::<gtk4::Window>().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<String, &'static str> {
- 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<Cmd>,
- /// URL to open (when no subcommand is used)
- url: Option<String>,
- /// GApplication ID override (used by desktop launchers for icon matching)
- #[arg(long, hide = true, global = true)]
- app_id: 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("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<String> = match cmdline
- .arguments()
- .into_iter()
- .map(|s| s.into_string())
- .collect::<Result<Vec<_>, _>>()
- {
- Ok(a) => a,
- Err(_) => {
- eprintln!("appiphany: arguments must be valid UTF-8");
- return glib::ExitCode::from(2);
- }
- };
- let args: Vec<String> = {
- 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()
- }
|