main.rs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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. mod locale;
  6. use std::path::PathBuf;
  7. use std::sync::{Arc, Mutex};
  8. use desktop_install::LauncherIcon;
  9. use clap::{Parser, Subcommand};
  10. use libadwaita as adw;
  11. use adw::prelude::*;
  12. use adw::{Application, ApplicationWindow, PreferencesGroup};
  13. use gtk4::gio::ApplicationFlags;
  14. use gtk4::gio::prelude::ApplicationExtManual;
  15. use gtk4::glib;
  16. use gtk4::glib::prelude::{Cast, IsA, ObjectExt};
  17. use gtk4::prelude::{GtkWindowExt, NativeExt, WidgetExt};
  18. use gtk4::{
  19. Align, Box as GtkBox, Button, Entry, Image, ListBox, Orientation, Overlay, PackType,
  20. PolicyType, ScrolledWindow, SelectionMode, WindowControls,
  21. };
  22. use gtk4::gdk::prelude::{DeviceExt, SeatExt, ToplevelExt};
  23. use gtk4::gdk;
  24. use webkit6::prelude::*;
  25. use webkit6::{
  26. CookieAcceptPolicy, CookiePersistentStorage, NavigationAction,
  27. NavigationPolicyDecision, NavigationType, NetworkSession, PolicyDecisionType,
  28. ResponsePolicyDecision, UserContentInjectedFrames, UserContentManager, UserScript,
  29. UserScriptInjectionTime, WebView,
  30. };
  31. /// JavaScript `window.webkit.messageHandlers.<name>` must match this identifier.
  32. const WINDOW_DRAG_MESSAGE_HANDLER: &str = "appiphanyWindowDrag";
  33. /// Mark draggable regions in HTML, e.g. `<div data-appiphany-window-drag>…</div>`.
  34. const WINDOW_DRAG_ATTR: &str = "data-appiphany-window-drag";
  35. /// Host detection for embedded webapps (set on `<html>` at document start).
  36. ///
  37. /// **Stable API:** Pages can target appiphany with CSS, e.g. `html[data-appiphany] { … }`,
  38. /// read `document.documentElement.hasAttribute("data-appiphany")`, or use
  39. /// `window.appiphany.version`. The User-Agent also includes application details
  40. /// (`set_user_agent_with_application_details("appiphany", version)`), so
  41. /// `navigator.userAgent` contains an appiphany token for JS or server-side checks.
  42. const HOST_MARKER_ATTR: &str = "data-appiphany";
  43. /// Lazily created shared profile; one store for every origin (WebKit partitions internally).
  44. const APP_NETWORK_SESSION_KEY: &str = "appiphany-network-session";
  45. /// Injected at document start: sets `html[data-appiphany]` and exposes `window.appiphany` API.
  46. /// Enables window dragging from non-interactive elements inside `[data-appiphany-window-drag]`.
  47. fn appiphany_document_start_script_source() -> String {
  48. format!(
  49. r#"(function () {{
  50. try {{
  51. document.documentElement.setAttribute("{host_attr}", "");
  52. }} catch (_) {{}}
  53. window.appiphany = {{ version: "{version}" }};
  54. var dragState = null;
  55. var dragAttr = "{drag_attr}";
  56. var interactive = "A,BUTTON,INPUT,TEXTAREA,SELECT,LABEL,SUMMARY,DETAILS,AUDIO,VIDEO";
  57. function isInteractive(el) {{
  58. if (!el || el === document.documentElement || el === document.body) return false;
  59. if (el.isContentEditable) return true;
  60. if (el.closest && el.closest(interactive)) return true;
  61. if (el.onclick || el.onmousedown || el.onmouseup) return true;
  62. return false;
  63. }}
  64. function beginNativeDrag() {{
  65. try {{
  66. window.webkit.messageHandlers.{handler}.postMessage(null);
  67. }} catch (_) {{}}
  68. }}
  69. function onMouseMove(e) {{
  70. if (!dragState) return;
  71. var dx = e.clientX - dragState.startX;
  72. var dy = e.clientY - dragState.startY;
  73. if (Math.abs(dx) > 3 || Math.abs(dy) > 3) {{
  74. cleanup();
  75. beginNativeDrag();
  76. }}
  77. }}
  78. function cleanup() {{
  79. if (dragState) {{
  80. document.removeEventListener("mousemove", onMouseMove, true);
  81. document.removeEventListener("mouseup", cleanup, true);
  82. dragState = null;
  83. }}
  84. }}
  85. document.addEventListener("mousedown", function (e) {{
  86. if (e.button !== 0) return;
  87. var el = e.target;
  88. if (!el || typeof el.closest !== "function") return;
  89. if (!el.closest("[" + dragAttr + "]")) return;
  90. if (isInteractive(el)) return;
  91. cleanup();
  92. dragState = {{
  93. startX: e.clientX,
  94. startY: e.clientY
  95. }};
  96. document.addEventListener("mousemove", onMouseMove, true);
  97. document.addEventListener("mouseup", cleanup, true);
  98. }}, false);
  99. }})();"#,
  100. host_attr = HOST_MARKER_ATTR,
  101. version = env!("CARGO_PKG_VERSION"),
  102. drag_attr = WINDOW_DRAG_ATTR,
  103. handler = WINDOW_DRAG_MESSAGE_HANDLER,
  104. )
  105. }
  106. /// Called when the web app requests window dragging via `window.appiphany.startWindowDrag()`.
  107. fn begin_move_from_pointer_on_window(window: &ApplicationWindow) {
  108. let Some(display) = gdk::Display::default() else {
  109. return;
  110. };
  111. let Some(seat) = display.default_seat() else {
  112. return;
  113. };
  114. let Some(device) = seat.pointer() else {
  115. return;
  116. };
  117. let (ptr_surface, x, y) = device.surface_at_position();
  118. let Some(ptr_surface) = ptr_surface else {
  119. return;
  120. };
  121. let Some(our_surface) = window.native().and_then(|n| n.surface()) else {
  122. return;
  123. };
  124. if ptr_surface != our_surface {
  125. return;
  126. }
  127. let Some(toplevel) = our_surface.dynamic_cast_ref::<gdk::Toplevel>() else {
  128. return;
  129. };
  130. toplevel.begin_move(
  131. &device,
  132. gdk::BUTTON_PRIMARY as i32,
  133. x,
  134. y,
  135. gdk::CURRENT_TIME,
  136. );
  137. }
  138. /// True when navigation targets the `_blank` browsing context (e.g. `<a target="_blank">`).
  139. fn navigation_targets_blank_frame(action: &NavigationAction) -> bool {
  140. action
  141. .frame_name()
  142. .as_deref()
  143. .is_some_and(|n| n.eq_ignore_ascii_case("_blank"))
  144. }
  145. /// Extract the origin (scheme + host + port) from a URL.
  146. fn url_origin(url: &str) -> Option<String> {
  147. let parsed = url::Url::parse(url).ok()?;
  148. if parsed.scheme() == "blob" {
  149. let inner = url.strip_prefix("blob:")?;
  150. return url_origin(inner);
  151. }
  152. let scheme = parsed.scheme();
  153. let host = parsed.host_str()?;
  154. let port = parsed.port_or_known_default()?;
  155. Some(format!("{}://{}:{}", scheme, host, port))
  156. }
  157. /// Check if two URLs share the same origin (scheme + host + port).
  158. fn is_same_origin(url_a: &str, url_b: &str) -> bool {
  159. match (url_origin(url_a), url_origin(url_b)) {
  160. (Some(a), Some(b)) => a == b,
  161. _ => false,
  162. }
  163. }
  164. /// Open a URI in the system's default browser.
  165. fn open_in_system_browser(uri: &str) {
  166. let scheme = uri.split(':').next().unwrap_or("");
  167. if !matches!(scheme, "http" | "https" | "ftp") {
  168. return;
  169. }
  170. if let Err(e) = gtk4::gio::AppInfo::launch_default_for_uri(uri, Option::<&gtk4::gio::AppLaunchContext>::None) {
  171. eprintln!("appiphany: failed to open URI in system browser: {}", e);
  172. }
  173. }
  174. /// `window.open()` and `target="_blank"` both go through [`PolicyDecisionType::NewWindowAction`].
  175. /// Links that target `_blank` load in this view; other new-window requests get a real window via
  176. /// [`WebViewExt::connect_create`].
  177. fn wire_webview_window_policy(
  178. host_window: &ApplicationWindow,
  179. webview: &WebView,
  180. network_session: &NetworkSession,
  181. initial_url: String,
  182. ) {
  183. let network_for_create = network_session.clone();
  184. let host_window_for_create = host_window.clone();
  185. let initial_url_for_nav = initial_url.clone();
  186. let initial_url_for_create = initial_url.clone();
  187. let initial_url_for_create_2 = initial_url.clone();
  188. webview.connect_decide_policy(move |w, decision, decision_type| {
  189. if decision_type == PolicyDecisionType::Response {
  190. if let Some(rpd) = decision.dynamic_cast_ref::<ResponsePolicyDecision>() {
  191. if !rpd.is_mime_type_supported() && rpd.is_main_frame_main_resource() {
  192. decision.download();
  193. return true;
  194. }
  195. }
  196. return false;
  197. }
  198. let Some(nav_decision) = decision.dynamic_cast_ref::<NavigationPolicyDecision>() else {
  199. return false;
  200. };
  201. let Some(action) = nav_decision.navigation_action() else {
  202. return false;
  203. };
  204. let Some(uri) = action.request().and_then(|r| r.uri()) else {
  205. return false;
  206. };
  207. if decision_type == PolicyDecisionType::NavigationAction {
  208. if action.navigation_type() == NavigationType::LinkClicked
  209. && !is_same_origin(&initial_url_for_nav, &uri)
  210. {
  211. decision.ignore();
  212. open_in_system_browser(&uri);
  213. return true;
  214. }
  215. return false;
  216. }
  217. if decision_type != PolicyDecisionType::NewWindowAction {
  218. return false;
  219. }
  220. if action.navigation_type() == NavigationType::LinkClicked
  221. && action.mouse_button() != 2
  222. && navigation_targets_blank_frame(&action)
  223. {
  224. decision.ignore();
  225. if is_same_origin(&initial_url_for_create, &uri) {
  226. w.load_uri(&uri);
  227. } else {
  228. open_in_system_browser(&uri);
  229. }
  230. return true;
  231. }
  232. if !is_same_origin(&initial_url_for_create, &uri) {
  233. decision.ignore();
  234. open_in_system_browser(&uri);
  235. return true;
  236. }
  237. decision.use_();
  238. true
  239. });
  240. webview.connect_create(move |parent, _action| {
  241. let app = host_window_for_create.application()?;
  242. let window = ApplicationWindow::builder()
  243. .application(&app)
  244. .title("Appiphany")
  245. .default_width(1024)
  246. .default_height(768)
  247. .build();
  248. let popup = build_appiphany_webview(&window, &network_for_create, Some(parent), initial_url_for_create_2.clone());
  249. let shell = build_overlay_with_webview(&popup);
  250. window.set_content(Some(&shell));
  251. window.present();
  252. Some(popup.upcast::<gtk4::Widget>())
  253. });
  254. }
  255. /// WebView with injected bridge + script handler; call after `window` exists so moves target it.
  256. ///
  257. /// `related_to` should be the opener when this view is created for `window.open()` so WebKit can
  258. /// share the rendering process with the parent.
  259. /// `initial_url` is used to determine whether navigation should stay in the app or open in the
  260. /// system browser.
  261. fn build_appiphany_webview(
  262. window: &ApplicationWindow,
  263. network_session: &NetworkSession,
  264. related_to: Option<&WebView>,
  265. initial_url: String,
  266. ) -> WebView {
  267. let ucm = UserContentManager::new();
  268. if !ucm.register_script_message_handler(WINDOW_DRAG_MESSAGE_HANDLER, None) {
  269. eprintln!("appiphany: failed to register `{WINDOW_DRAG_MESSAGE_HANDLER}` message handler");
  270. }
  271. let script = UserScript::new(
  272. &appiphany_document_start_script_source(),
  273. UserContentInjectedFrames::AllFrames,
  274. UserScriptInjectionTime::Start,
  275. &[],
  276. &[],
  277. );
  278. ucm.add_script(&script);
  279. let win = window.clone();
  280. ucm.connect_script_message_received(Some(WINDOW_DRAG_MESSAGE_HANDLER), move |_ucm, _value| {
  281. begin_move_from_pointer_on_window(&win);
  282. });
  283. let webview = {
  284. let b = WebView::builder()
  285. .user_content_manager(&ucm)
  286. .network_session(network_session);
  287. let b = if let Some(rv) = related_to {
  288. b.related_view(rv)
  289. } else {
  290. b
  291. };
  292. b.build()
  293. };
  294. if let Some(settings) = WebViewExt::settings(&webview) {
  295. settings.set_user_agent_with_application_details(
  296. Some("appiphany"),
  297. Some(env!("CARGO_PKG_VERSION")),
  298. );
  299. }
  300. wire_webview_window_policy(window, &webview, network_session, initial_url);
  301. webview
  302. }
  303. /// Full-window web view with Adwaita-style CSD controls overlaid in the top corners (no title bar).
  304. fn build_overlay_with_webview(webview: &WebView) -> Overlay {
  305. webview.set_hexpand(true);
  306. webview.set_vexpand(true);
  307. let overlay = Overlay::new();
  308. overlay.set_child(Some(webview));
  309. let margin = 6;
  310. let start = WindowControls::new(PackType::Start);
  311. start.set_valign(Align::Start);
  312. start.set_halign(Align::Start);
  313. start.set_margin_top(margin);
  314. start.set_margin_start(margin);
  315. overlay.add_overlay(&start);
  316. let end = WindowControls::new(PackType::End);
  317. end.set_valign(Align::Start);
  318. end.set_halign(Align::End);
  319. end.set_margin_top(margin);
  320. end.set_margin_end(margin);
  321. overlay.add_overlay(&end);
  322. overlay
  323. }
  324. /// One persistent [`NetworkSession`] for the whole app: all origins share this profile directory;
  325. /// WebKit keeps cookies / storage isolated per origin inside it.
  326. fn network_session_for_app(app: &impl IsA<glib::Object>) -> NetworkSession {
  327. unsafe {
  328. let obj = app.as_ref();
  329. if let Some(p) = obj.data::<NetworkSession>(APP_NETWORK_SESSION_KEY) {
  330. return p.as_ref().clone();
  331. }
  332. let session = build_persistent_network_session();
  333. session.connect_download_started(|_session, download| {
  334. let ctx: Arc<
  335. Mutex<
  336. Option<(
  337. PathBuf,
  338. String,
  339. )>,
  340. >,
  341. > = Arc::new(Mutex::new(None));
  342. let ctx_dd = ctx.clone();
  343. download.connect_decide_destination(
  344. move |dl, suggested_filename| {
  345. let filename = suggested_filename.to_string();
  346. let temp_dir = std::env::temp_dir().join("appiphany-downloads");
  347. std::fs::create_dir_all(&temp_dir).ok();
  348. let dest_path = temp_dir.join(&filename);
  349. if let Some(dest) = dest_path.to_str() {
  350. dl.set_destination(dest);
  351. dl.set_allow_overwrite(true);
  352. }
  353. *ctx_dd.lock().unwrap() = Some((
  354. dest_path.clone(),
  355. filename.clone(),
  356. ));
  357. let action_arc: Arc<Mutex<Option<String>>> =
  358. Arc::new(Mutex::new(None));
  359. {
  360. let ctx_fin = ctx_dd.clone();
  361. let action_fin = action_arc.clone();
  362. dl.connect_finished(move |_| {
  363. let state = ctx_fin.lock().unwrap();
  364. if let Some((ref path, ref name)) = *state {
  365. eprintln!("appiphany: download finished \"{name}\" -> {:?}", path);
  366. let act = action_fin.lock().unwrap().clone();
  367. if act.as_deref() == Some("open") {
  368. let file = gtk4::gio::File::for_path(path);
  369. match gtk4::gio::AppInfo::launch_default_for_uri(
  370. &file.uri(),
  371. Option::<&gtk4::gio::AppLaunchContext>::None,
  372. ) {
  373. Ok(_) => eprintln!("appiphany: opened {:?}", path),
  374. Err(e) => eprintln!(
  375. "appiphany: failed to open {:?}: {}",
  376. path, e
  377. ),
  378. }
  379. } else if act.as_deref() == Some("cancel") {
  380. let _ = std::fs::remove_file(path);
  381. }
  382. }
  383. });
  384. }
  385. {
  386. let ctx_fail = ctx_dd.clone();
  387. let name = filename.clone();
  388. dl.connect_failed(move |_, err| {
  389. eprintln!(
  390. "appiphany: download \"{}\" failed: {}",
  391. name, err
  392. );
  393. if let Some((ref path, _)) = *ctx_fail.lock().unwrap() {
  394. let _ = std::fs::remove_file(path);
  395. }
  396. });
  397. }
  398. let parent_win = dl
  399. .web_view()
  400. .and_then(|wv| wv.root())
  401. .and_then(|r| r.dynamic_cast::<gtk4::Window>().ok());
  402. let ctx_dialog = ctx_dd.clone();
  403. let action_dialog = action_arc.clone();
  404. glib::idle_add_local(move || {
  405. let (dest_path_d, filename_d) = {
  406. let state = ctx_dialog.lock().unwrap();
  407. state
  408. .clone()
  409. .unwrap_or_else(|| {
  410. (
  411. PathBuf::from("/tmp/appiphany-downloads/download"),
  412. String::from("download"),
  413. )
  414. })
  415. };
  416. eprintln!(
  417. "appiphany: download dialog \"{}\"",
  418. filename_d
  419. );
  420. let dialog = adw::AlertDialog::new(
  421. Some("Download"),
  422. Some(&format!(
  423. "What would you like to do with \"{}\"?",
  424. filename_d
  425. )),
  426. );
  427. dialog.add_response("open", "Open");
  428. dialog.add_response("save", "Save As...");
  429. dialog.add_response("cancel", "Cancel");
  430. dialog.set_default_response(Some("open"));
  431. dialog.set_close_response("cancel");
  432. {
  433. let action = action_dialog.clone();
  434. let path = dest_path_d.clone();
  435. dialog.connect_response(Some("open"), move |_, _| {
  436. *action.lock().unwrap() = Some("open".into());
  437. if path.exists() {
  438. let file = gtk4::gio::File::for_path(&path);
  439. match gtk4::gio::AppInfo::launch_default_for_uri(
  440. &file.uri(),
  441. Option::<&gtk4::gio::AppLaunchContext>::None,
  442. ) {
  443. Ok(_) => eprintln!("appiphany: opened {:?}", path),
  444. Err(e) => {
  445. eprintln!(
  446. "appiphany: failed to open {:?}: {}",
  447. path, e
  448. )
  449. }
  450. }
  451. }
  452. });
  453. }
  454. {
  455. let action = action_dialog.clone();
  456. let path = dest_path_d.clone();
  457. let name = filename_d.clone();
  458. dialog.connect_response(Some("save"), move |_, _| {
  459. *action.lock().unwrap() = Some("save".into());
  460. let file_dialog = gtk4::FileDialog::builder()
  461. .title("Save File")
  462. .initial_name(&name)
  463. .build();
  464. let path2 = path.clone();
  465. let name2 = name.clone();
  466. let action2 = action.clone();
  467. file_dialog.save(
  468. None::<&gtk4::Window>,
  469. None::<&gtk4::gio::Cancellable>,
  470. move |result| match result {
  471. Ok(file) => {
  472. let uri = file.uri();
  473. eprintln!(
  474. "appiphany: save \"{name2}\" -> \"{}\"",
  475. uri
  476. );
  477. if let Some(chosen) = file.path() {
  478. let _ = std::fs::copy(&path2, &chosen);
  479. eprintln!(
  480. "appiphany: saved {:?}",
  481. chosen
  482. );
  483. }
  484. let _ = std::fs::remove_file(&path2);
  485. }
  486. Err(_) => {
  487. eprintln!("appiphany: save cancelled");
  488. *action2.lock().unwrap() = Some("cancel".into());
  489. let _ = std::fs::remove_file(&path2);
  490. }
  491. },
  492. );
  493. });
  494. }
  495. {
  496. let action = action_dialog.clone();
  497. let path = dest_path_d.clone();
  498. dialog.connect_response(Some("cancel"), move |_, _| {
  499. *action.lock().unwrap() = Some("cancel".into());
  500. eprintln!("appiphany: download cancelled");
  501. let _ = std::fs::remove_file(&path);
  502. });
  503. }
  504. dialog.present(parent_win.as_ref());
  505. glib::ControlFlow::Break
  506. });
  507. true
  508. },
  509. );
  510. });
  511. obj.set_data(APP_NETWORK_SESSION_KEY, session.clone());
  512. session
  513. }
  514. }
  515. fn build_persistent_network_session() -> NetworkSession {
  516. let session = match persistent_profile_paths() {
  517. Ok((data_dir, cache_dir)) => match (data_dir.to_str(), cache_dir.to_str()) {
  518. (Some(data), Some(cache)) => NetworkSession::new(Some(data), Some(cache)),
  519. _ => {
  520. eprintln!("appiphany: non-UTF8 storage path, using ephemeral session");
  521. NetworkSession::new_ephemeral()
  522. }
  523. },
  524. Err(e) => {
  525. eprintln!("appiphany: could not create storage dirs ({e}), using ephemeral session");
  526. NetworkSession::new_ephemeral()
  527. }
  528. };
  529. session.set_itp_enabled(false);
  530. session.set_persistent_credential_storage_enabled(true);
  531. if let Some(cm) = session.cookie_manager() {
  532. cm.set_accept_policy(CookieAcceptPolicy::Always);
  533. if let Ok((data_dir, _)) = persistent_profile_paths() {
  534. let cookies_db = data_dir.join("cookies.sqlite");
  535. if let Some(path) = cookies_db.to_str() {
  536. cm.set_persistent_storage(path, CookiePersistentStorage::Sqlite);
  537. }
  538. }
  539. }
  540. session
  541. }
  542. fn open_web_window(app: &Application, url: &str) {
  543. let (default_w, default_h, maximized) = desktop_install::load_window_state(url)
  544. .unwrap_or((1024, 768, false));
  545. let window = ApplicationWindow::builder()
  546. .application(app)
  547. .title("Appiphany")
  548. .default_width(default_w)
  549. .default_height(default_h)
  550. .build();
  551. if maximized {
  552. window.maximize();
  553. }
  554. let network_session = network_session_for_app(app);
  555. let webview = build_appiphany_webview(&window, &network_session, None, url.to_string());
  556. let shell = build_overlay_with_webview(&webview);
  557. window.set_content(Some(&shell));
  558. webview.load_uri(url);
  559. let url_owned = url.to_string();
  560. window.connect_close_request(move |win| {
  561. let maximized = win.is_maximized();
  562. let width = win.default_width();
  563. let height = win.default_height();
  564. desktop_install::save_window_state(&url_owned, width, height, maximized);
  565. glib::Propagation::Proceed
  566. });
  567. window.present();
  568. }
  569. fn launcher_icon_image(icon: &LauncherIcon) -> Image {
  570. let img = match icon {
  571. LauncherIcon::File(path) => Image::from_file(path),
  572. LauncherIcon::Themed(name) => Image::from_icon_name(name),
  573. };
  574. img.set_pixel_size(32);
  575. img.set_valign(Align::Center);
  576. img
  577. }
  578. fn clear_listbox_rows(list: &ListBox) {
  579. while let Some(row) = list.row_at_index(0) {
  580. list.remove(&row);
  581. }
  582. }
  583. fn refresh_launchers_list(
  584. list: &ListBox,
  585. app: &Application,
  586. manager_window: &ApplicationWindow,
  587. ) {
  588. clear_listbox_rows(list);
  589. match desktop_install::list_launchers() {
  590. Ok(launchers) => {
  591. if launchers.is_empty() {
  592. let row = adw::ActionRow::builder()
  593. .title("No launchers found")
  594. .activatable(false)
  595. .selectable(false)
  596. .build();
  597. row.add_prefix(&launcher_icon_image(&LauncherIcon::Themed(
  598. "applications-internet".to_string(),
  599. )));
  600. list.append(&row);
  601. } else {
  602. for launcher in launchers {
  603. let (title, subtitle) = if let Some(url) = &launcher.url {
  604. (
  605. launcher
  606. .name
  607. .as_deref()
  608. .unwrap_or("Unnamed")
  609. .to_string(),
  610. url.clone(),
  611. )
  612. } else {
  613. (
  614. launcher
  615. .name
  616. .unwrap_or_else(|| "Unnamed".to_string()),
  617. format!("ID {}", launcher.id),
  618. )
  619. };
  620. let row = adw::ActionRow::builder()
  621. .title(&title)
  622. .subtitle(&subtitle)
  623. .subtitle_lines(2)
  624. .activatable(false)
  625. .selectable(false)
  626. .build();
  627. row.add_prefix(&launcher_icon_image(&launcher.icon));
  628. let actions = GtkBox::new(Orientation::Horizontal, 6);
  629. actions.set_valign(Align::Center);
  630. let open_btn = Button::with_label("Open");
  631. open_btn.add_css_class("flat");
  632. open_btn.set_valign(Align::Center);
  633. let uninstall_btn = Button::with_label("Unregister");
  634. uninstall_btn.add_css_class("flat");
  635. uninstall_btn.set_valign(Align::Center);
  636. let id = launcher.id.clone();
  637. let url = launcher.url.clone();
  638. let app_open = app.clone();
  639. open_btn.connect_clicked(move |_| {
  640. if let Some(url) = &url {
  641. open_web_window(&app_open, url);
  642. } else {
  643. eprintln!("appiphany: launcher has no URL in Exec entry");
  644. }
  645. });
  646. let list_uninstall = list.clone();
  647. let app_uninstall = app.clone();
  648. let manager_window_uninstall = manager_window.clone();
  649. uninstall_btn.connect_clicked(move |_| {
  650. let dialog = adw::AlertDialog::new(
  651. Some("Unregister launcher?"),
  652. Some("This will remove the launcher entry and stored icons."),
  653. );
  654. dialog.add_response("cancel", "Cancel");
  655. dialog.add_response("unregister", "Unregister");
  656. dialog.set_close_response("cancel");
  657. dialog.set_default_response(Some("cancel"));
  658. dialog.set_response_appearance("unregister", adw::ResponseAppearance::Destructive);
  659. let id = id.clone();
  660. let list_uninstall = list_uninstall.clone();
  661. let app_uninstall = app_uninstall.clone();
  662. let manager_window_for_response = manager_window_uninstall.clone();
  663. dialog.connect_response(Some("unregister"), move |_, _| {
  664. match desktop_install::run_uninstall(&id, normalize_url) {
  665. Ok(()) => refresh_launchers_list(
  666. &list_uninstall,
  667. &app_uninstall,
  668. &manager_window_for_response,
  669. ),
  670. Err(e) => eprintln!("appiphany: unregister failed: {e}"),
  671. }
  672. });
  673. dialog.present(Some(&manager_window_uninstall));
  674. });
  675. actions.append(&open_btn);
  676. actions.append(&uninstall_btn);
  677. row.add_suffix(&actions);
  678. list.append(&row);
  679. }
  680. }
  681. }
  682. Err(e) => {
  683. eprintln!("appiphany: failed to list launchers: {e}");
  684. }
  685. }
  686. }
  687. fn build_manager_window(app: &Application) {
  688. let header = adw::HeaderBar::new();
  689. let window_title = adw::WindowTitle::new("Appiphany", "Run webapps as native windows");
  690. header.set_title_widget(Some(&window_title));
  691. header.set_show_end_title_buttons(true);
  692. header.set_show_start_title_buttons(false);
  693. let window = ApplicationWindow::builder()
  694. .application(app)
  695. .title("Appiphany")
  696. .default_width(900)
  697. .default_height(640)
  698. .build();
  699. window.set_resizable(true);
  700. window.set_size_request(420, 320);
  701. let root = GtkBox::new(Orientation::Vertical, 0);
  702. root.set_margin_top(12);
  703. root.set_margin_bottom(12);
  704. root.set_margin_start(12);
  705. root.set_margin_end(12);
  706. let body = GtkBox::new(Orientation::Vertical, 12);
  707. let open_row = GtkBox::new(Orientation::Horizontal, 8);
  708. let url_entry = Entry::new();
  709. url_entry.set_hexpand(true);
  710. url_entry.set_placeholder_text(Some("https://example.com"));
  711. let open_button = Button::with_label("Open");
  712. let create_button = Button::with_label("Create Launcher");
  713. open_row.append(&url_entry);
  714. open_row.append(&open_button);
  715. open_row.append(&create_button);
  716. open_row.set_margin_start(12);
  717. open_row.set_margin_end(12);
  718. let launchers_group = PreferencesGroup::builder()
  719. .title("Installed launchers")
  720. // Inset from the ScrolledWindow viewport so `.boxed-list` outlines/shadows are not clipped.
  721. .margin_start(12)
  722. .margin_end(12)
  723. .build();
  724. let list = ListBox::new();
  725. list.add_css_class("boxed-list");
  726. list.set_selection_mode(SelectionMode::None);
  727. launchers_group.add(&list);
  728. let list_scroll = ScrolledWindow::builder()
  729. .vexpand(true)
  730. .hexpand(true)
  731. .child(&launchers_group)
  732. .build();
  733. list_scroll.set_policy(PolicyType::Never, PolicyType::Automatic);
  734. let app_open = app.clone();
  735. let entry_open = url_entry.clone();
  736. open_button.connect_clicked(move |_| {
  737. let raw = entry_open.text().to_string();
  738. match normalize_url(&raw) {
  739. Ok(url) => open_web_window(&app_open, &url),
  740. Err(msg) => eprintln!("appiphany: {msg}"),
  741. }
  742. });
  743. let entry_create = url_entry.clone();
  744. let list_create = list.clone();
  745. let app_create = app.clone();
  746. let manager_window_create = window.clone();
  747. create_button.connect_clicked(move |_| {
  748. let raw = entry_create.text().to_string();
  749. match normalize_url(&raw) {
  750. Ok(url) => match desktop_install::run_install(&url, None, true, normalize_url) {
  751. Ok(()) => refresh_launchers_list(
  752. &list_create,
  753. &app_create,
  754. &manager_window_create,
  755. ),
  756. Err(e) => eprintln!("appiphany: create launcher failed: {e}"),
  757. },
  758. Err(msg) => eprintln!("appiphany: {msg}"),
  759. }
  760. });
  761. body.append(&open_row);
  762. body.append(&list_scroll);
  763. body.set_hexpand(true);
  764. body.set_vexpand(true);
  765. // Same pattern as GNOME Settings / libadwaita preferences: cap content width and center
  766. // so `.boxed-list` borders are not clipped by the scrolled viewport on wide windows.
  767. let body_clamp = adw::Clamp::builder()
  768. .child(&body)
  769. .maximum_size(600)
  770. .hexpand(true)
  771. .vexpand(true)
  772. .build();
  773. root.append(&body_clamp);
  774. root.set_hexpand(true);
  775. root.set_vexpand(true);
  776. let shell = adw::ToolbarView::new();
  777. shell.add_top_bar(&header);
  778. shell.set_content(Some(&root));
  779. window.set_content(Some(&shell));
  780. refresh_launchers_list(&list, app, &window);
  781. window.present();
  782. }
  783. fn normalize_url(arg: &str) -> Result<String, &'static str> {
  784. let t = arg.trim();
  785. if t.is_empty() {
  786. return Err("URL must not be empty");
  787. }
  788. if t.to_ascii_lowercase().starts_with("about:") {
  789. return Err("about: URLs are not supported");
  790. }
  791. if t.contains("://") {
  792. Ok(t.to_string())
  793. } else {
  794. Ok(format!("https://{t}"))
  795. }
  796. }
  797. #[derive(Parser)]
  798. #[command(name = "appiphany", version, about = "Minimal WebKit wrapper around a URL")]
  799. struct Args {
  800. #[command(subcommand)]
  801. cmd: Option<Cmd>,
  802. /// URL to open (when no subcommand is used)
  803. url: Option<String>,
  804. /// GApplication ID override (used by desktop launchers for icon matching)
  805. #[arg(long, hide = true, global = true)]
  806. app_id: Option<String>,
  807. }
  808. #[derive(Subcommand)]
  809. enum Cmd {
  810. /// Create a Freedesktop launcher and favicon under ~/.local/share
  811. DesktopInstall {
  812. /// Page URL for the launcher
  813. url: String,
  814. /// Display name in the app menu (default: page title or host)
  815. #[arg(short = 'n', long)]
  816. name: Option<String>,
  817. /// Overwrite an existing launcher with the same URL
  818. #[arg(long)]
  819. force: bool,
  820. },
  821. /// Remove launcher files by URL or 12-character id (see desktop file name)
  822. DesktopUninstall {
  823. target: String,
  824. },
  825. }
  826. fn persistent_profile_paths() -> Result<(PathBuf, PathBuf), std::io::Error> {
  827. let data_dir: PathBuf = glib::user_data_dir()
  828. .join("appiphany")
  829. .join("profile")
  830. .join("data");
  831. let cache_dir: PathBuf = glib::user_cache_dir()
  832. .join("appiphany")
  833. .join("profile")
  834. .join("cache");
  835. std::fs::create_dir_all(&data_dir)?;
  836. std::fs::create_dir_all(&cache_dir)?;
  837. Ok((data_dir, cache_dir))
  838. }
  839. fn main() -> glib::ExitCode {
  840. let parsed = match Args::try_parse() {
  841. Ok(a) => a,
  842. Err(e) => e.exit(),
  843. };
  844. match (&parsed.cmd, &parsed.url) {
  845. (Some(_), Some(_)) => {
  846. eprintln!("appiphany: cannot pass a URL together with a subcommand");
  847. return glib::ExitCode::from(2);
  848. }
  849. (None, None) => {}
  850. _ => {}
  851. }
  852. if let Some(cmd) = parsed.cmd {
  853. let result = match cmd {
  854. Cmd::DesktopInstall { url, name, force } => {
  855. desktop_install::run_install(&url, name.as_deref(), force, normalize_url)
  856. }
  857. Cmd::DesktopUninstall { target } => {
  858. desktop_install::run_uninstall(&target, normalize_url)
  859. }
  860. };
  861. return match result {
  862. Ok(()) => glib::ExitCode::SUCCESS,
  863. Err(msg) => {
  864. eprintln!("appiphany: {msg}");
  865. glib::ExitCode::from(1)
  866. }
  867. };
  868. }
  869. if let Some(url) = parsed.url.as_deref() {
  870. if let Err(msg) = normalize_url(url) {
  871. eprintln!("appiphany: {msg}");
  872. return glib::ExitCode::from(2);
  873. }
  874. }
  875. let effective_app_id = parsed
  876. .app_id
  877. .as_deref()
  878. .unwrap_or("dev.appiphany.app");
  879. // set_prgname before GTK init so both Wayland and X11 see the right identity.
  880. glib::set_prgname(Some(effective_app_id));
  881. if let Err(e) = adw::init() {
  882. eprintln!("appiphany: failed to initialize libadwaita: {e}");
  883. return glib::ExitCode::from(1);
  884. }
  885. // Before any web view/network session exists: the first entry becomes the
  886. // JavaScript `Intl` default locale (see `locale`).
  887. let languages = locale::apply_to_webkit();
  888. if !languages.is_empty() {
  889. eprintln!("appiphany: preferred languages: {}", languages.join(", "));
  890. }
  891. let app = Application::builder()
  892. .application_id(effective_app_id)
  893. .flags(ApplicationFlags::HANDLES_COMMAND_LINE)
  894. .build();
  895. locale::watch_region_changes(&app);
  896. app.connect_command_line(|app, cmdline| {
  897. let raw_args: Vec<String> = match cmdline
  898. .arguments()
  899. .into_iter()
  900. .map(|s| s.into_string())
  901. .collect::<Result<Vec<_>, _>>()
  902. {
  903. Ok(a) => a,
  904. Err(_) => {
  905. eprintln!("appiphany: arguments must be valid UTF-8");
  906. return glib::ExitCode::from(2);
  907. }
  908. };
  909. let args: Vec<String> = {
  910. let mut filtered = Vec::new();
  911. let mut skip_next = false;
  912. for arg in raw_args {
  913. if skip_next {
  914. skip_next = false;
  915. continue;
  916. }
  917. if arg == "--app-id" {
  918. skip_next = true;
  919. continue;
  920. }
  921. if arg.starts_with("--app-id=") {
  922. continue;
  923. }
  924. filtered.push(arg);
  925. }
  926. filtered
  927. };
  928. if args.len() == 1 {
  929. if app.active_window().is_none() {
  930. build_manager_window(app);
  931. } else if let Some(win) = app.active_window() {
  932. win.present();
  933. }
  934. return glib::ExitCode::SUCCESS;
  935. }
  936. if args.len() != 2 {
  937. eprintln!("Usage: appiphany [url]");
  938. return glib::ExitCode::from(2);
  939. }
  940. let url = match normalize_url(&args[1]) {
  941. Ok(u) => u,
  942. Err(msg) => {
  943. eprintln!("appiphany: {msg}");
  944. return glib::ExitCode::from(2);
  945. }
  946. };
  947. open_web_window(app, &url);
  948. glib::ExitCode::SUCCESS
  949. });
  950. app.run()
  951. }