main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. //! GTK/WebKit shell for a URL. Webapps can detect this host with `html[data-appiphany]` (CSS),
  2. //! `window.appiphany.version`, or `navigator.userAgent` (application details append `appiphany`
  3. //! and the crate version). See the `HOST_MARKER_ATTR` constant below.
  4. mod desktop_install;
  5. use std::path::PathBuf;
  6. use clap::{Parser, Subcommand};
  7. use libadwaita as adw;
  8. use adw::prelude::*;
  9. use adw::{Application, ApplicationWindow};
  10. use gtk4::gio::ApplicationFlags;
  11. use gtk4::gio::prelude::ApplicationExtManual;
  12. use gtk4::glib;
  13. use gtk4::glib::prelude::{Cast, IsA, ObjectExt};
  14. use gtk4::prelude::{NativeExt, WidgetExt};
  15. use gtk4::{Align, Overlay, PackType, WindowControls};
  16. use gtk4::gdk::prelude::{DeviceExt, SeatExt, ToplevelExt};
  17. use gtk4::gdk;
  18. use webkit6::prelude::*;
  19. use webkit6::{
  20. CookieAcceptPolicy, CookiePersistentStorage, NetworkSession, UserContentInjectedFrames,
  21. UserContentManager, UserScript, UserScriptInjectionTime, WebView,
  22. };
  23. /// JavaScript `window.webkit.messageHandlers.<name>` must match this identifier.
  24. const WINDOW_DRAG_MESSAGE_HANDLER: &str = "appiphanyWindowDrag";
  25. /// Mark draggable regions in HTML, e.g. `<div data-appiphany-window-drag>…</div>`.
  26. const WINDOW_DRAG_ATTR: &str = "data-appiphany-window-drag";
  27. /// Host detection for embedded webapps (set on `<html>` at document start).
  28. ///
  29. /// **Stable API:** Pages can target appiphany with CSS, e.g. `html[data-appiphany] { … }`,
  30. /// read `document.documentElement.hasAttribute("data-appiphany")`, or use
  31. /// `window.appiphany.version`. The User-Agent also includes application details
  32. /// (`set_user_agent_with_application_details("appiphany", version)`), so
  33. /// `navigator.userAgent` contains an appiphany token for JS or server-side checks.
  34. const HOST_MARKER_ATTR: &str = "data-appiphany";
  35. /// Lazily created shared profile; one store for every origin (WebKit partitions internally).
  36. const APP_NETWORK_SESSION_KEY: &str = "appiphany-network-session";
  37. /// Injected at document start: sets `html[data-appiphany]` and exposes `window.appiphany` API.
  38. /// Enables window dragging from non-interactive elements inside `[data-appiphany-window-drag]`.
  39. fn appiphany_document_start_script_source() -> String {
  40. format!(
  41. r#"(function () {{
  42. try {{
  43. document.documentElement.setAttribute("{host_attr}", "");
  44. }} catch (_) {{}}
  45. window.appiphany = {{ version: "{version}" }};
  46. var dragState = null;
  47. var dragAttr = "{drag_attr}";
  48. var interactive = "A,BUTTON,INPUT,TEXTAREA,SELECT,LABEL,SUMMARY,DETAILS,AUDIO,VIDEO";
  49. function isInteractive(el) {{
  50. if (!el || el === document.documentElement || el === document.body) return false;
  51. if (el.isContentEditable) return true;
  52. if (el.closest && el.closest(interactive)) return true;
  53. if (el.onclick || el.onmousedown || el.onmouseup) return true;
  54. return false;
  55. }}
  56. function beginNativeDrag() {{
  57. try {{
  58. window.webkit.messageHandlers.{handler}.postMessage(null);
  59. }} catch (_) {{}}
  60. }}
  61. function onMouseMove(e) {{
  62. if (!dragState) return;
  63. var dx = e.clientX - dragState.startX;
  64. var dy = e.clientY - dragState.startY;
  65. if (Math.abs(dx) > 3 || Math.abs(dy) > 3) {{
  66. cleanup();
  67. beginNativeDrag();
  68. }}
  69. }}
  70. function cleanup() {{
  71. if (dragState) {{
  72. document.removeEventListener("mousemove", onMouseMove, true);
  73. document.removeEventListener("mouseup", cleanup, true);
  74. dragState = null;
  75. }}
  76. }}
  77. document.addEventListener("mousedown", function (e) {{
  78. if (e.button !== 0) return;
  79. var el = e.target;
  80. if (!el || typeof el.closest !== "function") return;
  81. if (!el.closest("[" + dragAttr + "]")) return;
  82. if (isInteractive(el)) return;
  83. cleanup();
  84. dragState = {{
  85. startX: e.clientX,
  86. startY: e.clientY
  87. }};
  88. document.addEventListener("mousemove", onMouseMove, true);
  89. document.addEventListener("mouseup", cleanup, true);
  90. }}, false);
  91. }})();"#,
  92. host_attr = HOST_MARKER_ATTR,
  93. version = env!("CARGO_PKG_VERSION"),
  94. drag_attr = WINDOW_DRAG_ATTR,
  95. handler = WINDOW_DRAG_MESSAGE_HANDLER,
  96. )
  97. }
  98. /// Called when the web app requests window dragging via `window.appiphany.startWindowDrag()`.
  99. fn begin_move_from_pointer_on_window(window: &ApplicationWindow) {
  100. let Some(display) = gdk::Display::default() else {
  101. return;
  102. };
  103. let Some(seat) = display.default_seat() else {
  104. return;
  105. };
  106. let Some(device) = seat.pointer() else {
  107. return;
  108. };
  109. let (ptr_surface, x, y) = device.surface_at_position();
  110. let Some(ptr_surface) = ptr_surface else {
  111. return;
  112. };
  113. let Some(our_surface) = window.native().and_then(|n| n.surface()) else {
  114. return;
  115. };
  116. if ptr_surface != our_surface {
  117. return;
  118. }
  119. let Some(toplevel) = our_surface.dynamic_cast_ref::<gdk::Toplevel>() else {
  120. return;
  121. };
  122. toplevel.begin_move(
  123. &device,
  124. gdk::BUTTON_PRIMARY as i32,
  125. x,
  126. y,
  127. gdk::CURRENT_TIME,
  128. );
  129. }
  130. /// WebView with injected bridge + script handler; call after `window` exists so moves target it.
  131. fn build_appiphany_webview(window: &ApplicationWindow, network_session: &NetworkSession) -> WebView {
  132. let ucm = UserContentManager::new();
  133. if !ucm.register_script_message_handler(WINDOW_DRAG_MESSAGE_HANDLER, None) {
  134. eprintln!("appiphany: failed to register `{WINDOW_DRAG_MESSAGE_HANDLER}` message handler");
  135. }
  136. let script = UserScript::new(
  137. &appiphany_document_start_script_source(),
  138. UserContentInjectedFrames::AllFrames,
  139. UserScriptInjectionTime::Start,
  140. &[],
  141. &[],
  142. );
  143. ucm.add_script(&script);
  144. let win = window.clone();
  145. ucm.connect_script_message_received(Some(WINDOW_DRAG_MESSAGE_HANDLER), move |_ucm, _value| {
  146. begin_move_from_pointer_on_window(&win);
  147. });
  148. let webview = WebView::builder()
  149. .user_content_manager(&ucm)
  150. .network_session(network_session)
  151. .build();
  152. if let Some(settings) = WebViewExt::settings(&webview) {
  153. settings.set_user_agent_with_application_details(
  154. Some("appiphany"),
  155. Some(env!("CARGO_PKG_VERSION")),
  156. );
  157. }
  158. webview
  159. }
  160. /// Full-window web view with Adwaita-style CSD controls overlaid in the top corners (no title bar).
  161. fn build_overlay_with_webview(webview: &WebView) -> Overlay {
  162. webview.set_hexpand(true);
  163. webview.set_vexpand(true);
  164. let overlay = Overlay::new();
  165. overlay.set_child(Some(webview));
  166. let margin = 6;
  167. let start = WindowControls::new(PackType::Start);
  168. start.set_valign(Align::Start);
  169. start.set_halign(Align::Start);
  170. start.set_margin_top(margin);
  171. start.set_margin_start(margin);
  172. overlay.add_overlay(&start);
  173. let end = WindowControls::new(PackType::End);
  174. end.set_valign(Align::Start);
  175. end.set_halign(Align::End);
  176. end.set_margin_top(margin);
  177. end.set_margin_end(margin);
  178. overlay.add_overlay(&end);
  179. overlay
  180. }
  181. /// One persistent [`NetworkSession`] for the whole app: all origins share this profile directory;
  182. /// WebKit keeps cookies / storage isolated per origin inside it.
  183. fn network_session_for_app(app: &impl IsA<glib::Object>) -> NetworkSession {
  184. unsafe {
  185. let obj = app.as_ref();
  186. if let Some(p) = obj.data::<NetworkSession>(APP_NETWORK_SESSION_KEY) {
  187. return p.as_ref().clone();
  188. }
  189. let session = build_persistent_network_session();
  190. obj.set_data(APP_NETWORK_SESSION_KEY, session.clone());
  191. session
  192. }
  193. }
  194. fn build_persistent_network_session() -> NetworkSession {
  195. let session = match persistent_profile_paths() {
  196. Ok((data_dir, cache_dir)) => match (data_dir.to_str(), cache_dir.to_str()) {
  197. (Some(data), Some(cache)) => NetworkSession::new(Some(data), Some(cache)),
  198. _ => {
  199. eprintln!("appiphany: non-UTF8 storage path, using ephemeral session");
  200. NetworkSession::new_ephemeral()
  201. }
  202. },
  203. Err(e) => {
  204. eprintln!("appiphany: could not create storage dirs ({e}), using ephemeral session");
  205. NetworkSession::new_ephemeral()
  206. }
  207. };
  208. session.set_itp_enabled(false);
  209. session.set_persistent_credential_storage_enabled(true);
  210. if let Some(cm) = session.cookie_manager() {
  211. cm.set_accept_policy(CookieAcceptPolicy::Always);
  212. if let Ok((data_dir, _)) = persistent_profile_paths() {
  213. let cookies_db = data_dir.join("cookies.sqlite");
  214. if let Some(path) = cookies_db.to_str() {
  215. cm.set_persistent_storage(path, CookiePersistentStorage::Sqlite);
  216. }
  217. }
  218. }
  219. session
  220. }
  221. fn load_uri_into_overlay_webview(win: &ApplicationWindow, url: &str) {
  222. let Some(shell) = win.content() else {
  223. return;
  224. };
  225. let Some(overlay) = shell.downcast_ref::<Overlay>() else {
  226. return;
  227. };
  228. if let Some(child) = overlay.child() {
  229. if let Ok(webview) = child.downcast::<WebView>() {
  230. webview.load_uri(url);
  231. return;
  232. }
  233. }
  234. let Some(app) = win.application() else {
  235. return;
  236. };
  237. let session = network_session_for_app(&app);
  238. let webview = build_appiphany_webview(win, &session);
  239. webview.set_hexpand(true);
  240. webview.set_vexpand(true);
  241. overlay.set_child(Some(&webview));
  242. webview.load_uri(url);
  243. }
  244. fn normalize_url(arg: &str) -> Result<String, &'static str> {
  245. let t = arg.trim();
  246. if t.is_empty() {
  247. return Err("URL must not be empty");
  248. }
  249. if t.to_ascii_lowercase().starts_with("about:") {
  250. return Err("about: URLs are not supported");
  251. }
  252. if t.contains("://") {
  253. Ok(t.to_string())
  254. } else {
  255. Ok(format!("https://{t}"))
  256. }
  257. }
  258. #[derive(Parser)]
  259. #[command(name = "appiphany", version, about = "Minimal WebKit wrapper around a URL")]
  260. struct Args {
  261. #[command(subcommand)]
  262. cmd: Option<Cmd>,
  263. /// URL to open (when no subcommand is used)
  264. url: Option<String>,
  265. }
  266. #[derive(Subcommand)]
  267. enum Cmd {
  268. /// Create a Freedesktop launcher and favicon under ~/.local/share
  269. DesktopInstall {
  270. /// Page URL for the launcher
  271. url: String,
  272. /// Display name in the app menu (default: page title or host)
  273. #[arg(short = 'n', long)]
  274. name: Option<String>,
  275. /// Overwrite an existing launcher with the same URL
  276. #[arg(long)]
  277. force: bool,
  278. },
  279. /// Remove launcher files by URL or 12-character id (see desktop file name)
  280. DesktopUninstall {
  281. target: String,
  282. },
  283. }
  284. fn persistent_profile_paths() -> Result<(PathBuf, PathBuf), std::io::Error> {
  285. let data_dir: PathBuf = glib::user_data_dir()
  286. .join("appiphany")
  287. .join("profile")
  288. .join("data");
  289. let cache_dir: PathBuf = glib::user_cache_dir()
  290. .join("appiphany")
  291. .join("profile")
  292. .join("cache");
  293. std::fs::create_dir_all(&data_dir)?;
  294. std::fs::create_dir_all(&cache_dir)?;
  295. Ok((data_dir, cache_dir))
  296. }
  297. fn main() -> glib::ExitCode {
  298. let parsed = match Args::try_parse() {
  299. Ok(a) => a,
  300. Err(e) => e.exit(),
  301. };
  302. match (&parsed.cmd, &parsed.url) {
  303. (Some(_), Some(_)) => {
  304. eprintln!("appiphany: cannot pass a URL together with a subcommand");
  305. return glib::ExitCode::from(2);
  306. }
  307. (None, None) => {
  308. eprintln!("appiphany: expected <URL> or a subcommand (see --help)");
  309. return glib::ExitCode::from(2);
  310. }
  311. _ => {}
  312. }
  313. if let Some(cmd) = parsed.cmd {
  314. let result = match cmd {
  315. Cmd::DesktopInstall { url, name, force } => {
  316. desktop_install::run_install(&url, name.as_deref(), force, normalize_url)
  317. }
  318. Cmd::DesktopUninstall { target } => {
  319. desktop_install::run_uninstall(&target, normalize_url)
  320. }
  321. };
  322. return match result {
  323. Ok(()) => glib::ExitCode::SUCCESS,
  324. Err(msg) => {
  325. eprintln!("appiphany: {msg}");
  326. glib::ExitCode::from(1)
  327. }
  328. };
  329. }
  330. if let Err(msg) = normalize_url(parsed.url.as_ref().expect("validated")) {
  331. eprintln!("appiphany: {msg}");
  332. return glib::ExitCode::from(2);
  333. }
  334. if let Err(e) = adw::init() {
  335. eprintln!("appiphany: failed to initialize libadwaita: {e}");
  336. return glib::ExitCode::from(1);
  337. }
  338. let app = Application::builder()
  339. .application_id("dev.appiphany.app")
  340. .flags(ApplicationFlags::HANDLES_COMMAND_LINE)
  341. .build();
  342. app.connect_command_line(|app, cmdline| {
  343. let args: Vec<String> = match cmdline
  344. .arguments()
  345. .into_iter()
  346. .map(|s| s.into_string())
  347. .collect::<Result<Vec<_>, _>>()
  348. {
  349. Ok(a) => a,
  350. Err(_) => {
  351. eprintln!("appiphany: arguments must be valid UTF-8");
  352. return glib::ExitCode::from(2);
  353. }
  354. };
  355. if args.len() != 2 {
  356. eprintln!("Usage: appiphany <url>");
  357. return glib::ExitCode::from(2);
  358. }
  359. let url = match normalize_url(&args[1]) {
  360. Ok(u) => u,
  361. Err(msg) => {
  362. eprintln!("appiphany: {msg}");
  363. return glib::ExitCode::from(2);
  364. }
  365. };
  366. if let Some(gtk_win) = app.active_window() {
  367. if let Some(win) = gtk_win.downcast_ref::<ApplicationWindow>() {
  368. load_uri_into_overlay_webview(win, &url);
  369. }
  370. gtk_win.present();
  371. return glib::ExitCode::SUCCESS;
  372. }
  373. let window = ApplicationWindow::builder()
  374. .application(app)
  375. .title("Appiphany")
  376. .default_width(1024)
  377. .default_height(768)
  378. .build();
  379. let network_session = network_session_for_app(app);
  380. let webview = build_appiphany_webview(&window, &network_session);
  381. let shell = build_overlay_with_webview(&webview);
  382. window.set_content(Some(&shell));
  383. webview.load_uri(&url);
  384. window.present();
  385. glib::ExitCode::SUCCESS
  386. });
  387. app.run()
  388. }