From 551df84562f0598f73689e8945bbee2a2ae4e940 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 17:00:08 +0000 Subject: [PATCH 1/4] feat: let an application decline a close to keep unsaved changes A package declares its unsaved-change policy in [ui].close. With "ask", the app shell dispatches a cancelable weftclose event before the window closes and waits up to 2 s for the page. A page that cancels the close keeps running, and the app shell reports this to weft-appd with its readiness token, which returns the session to running. The page closes itself later with window.close(). Notes declares "ask". With unsaved changes it offers Save and close, Close without saving, and Cancel. It closes after a save only once the save is acknowledged. The taskbar shows a declined close as running again. --- crates/weft-app-shell/src/embedder.rs | 114 +++++++++++++++++- crates/weft-appd/src/launch.rs | 6 +- crates/weft-appd/src/main.rs | 123 ++++++++++++++++++++ crates/weft-appd/src/runtime.rs | 122 ++++++++++++++++---- crates/weft-ipc-types/src/manifest.rs | 43 +++++++ docs/architecture.md | 13 ++- docs/building.md | 2 +- examples/org.weft.demo.notes/signature.sig | 2 +- examples/org.weft.demo.notes/ui/index.html | 61 +++++++++- examples/org.weft.demo.notes/wapp.toml | 1 + infra/shell/system-ui.html | 20 ++-- tests/frame/check_notes.py | 127 ++++++++++++++++++++- 12 files changed, 589 insertions(+), 45 deletions(-) diff --git a/crates/weft-app-shell/src/embedder.rs b/crates/weft-app-shell/src/embedder.rs index 74e72ab..987eac2 100644 --- a/crates/weft-app-shell/src/embedder.rs +++ b/crates/weft-app-shell/src/embedder.rs @@ -68,6 +68,33 @@ struct FrameSignals { content: AtomicBool, /// The document has loaded and Servo reports its rendering is up to date. settled: AtomicBool, + /// The page closed itself with `window.close()`. + page_closed: AtomicBool, + /// The page's answer to the pending close request; see `CloseAnswer`. + close_answer: std::sync::atomic::AtomicU8, +} + +/// The page's answer to a close request, as stored in `close_answer`. +#[derive(Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +enum CloseAnswer { + Pending = 0, + Close = 1, + Cancel = 2, +} + +/// How long a page with the `ask` close policy has to answer a close +/// request; a page that does not answer in time is closed. +const CLOSE_ANSWER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2); + +/// Asks the page whether it may close: dispatches a cancelable `weftclose` +/// event on the top-level window. The page cancels the close by calling +/// `preventDefault()` and closes itself later with `window.close()`. +const ASK_CLOSE_SCRIPT: &str = "window.dispatchEvent(new Event('weftclose', { cancelable: true }))"; + +/// The application's declared close policy, from `WEFT_APP_CLOSE`. +fn close_policy_asks() -> bool { + std::env::var("WEFT_APP_CLOSE").is_ok_and(|v| v == "ask") } struct WeftWebViewDelegate { @@ -87,6 +114,12 @@ impl WebViewDelegate for WeftWebViewDelegate { self.signals.redraw.store(true, Ordering::Relaxed); } + /// The application page called `window.close()`, which Servo allows for + /// a top-level document with a single history entry. + fn notify_closed(&self, _webview: servo::WebView) { + self.signals.page_closed.store(true, Ordering::Relaxed); + } + /// The webview carries the session's bridge, so it stays within the /// application's own UI files. fn request_navigation(&self, _webview: servo::WebView, request: NavigationRequest) { @@ -368,6 +401,10 @@ struct App { modifiers: ModifiersState, cursor_pos: DevicePoint, shell_client: Option, + /// Whether the page is asked before its window closes. + ask_before_close: bool, + /// When the pending close request is closed regardless of the page. + close_deadline: Option, } impl App { @@ -394,9 +431,70 @@ impl App { modifiers: ModifiersState::default(), cursor_pos: DevicePoint::origin(), shell_client: None, + ask_before_close: close_policy_asks(), + close_deadline: None, } } + /// Handles a request to close the window. Under the `ask` policy the + /// page answers first; otherwise, or without a page, the app closes. + fn request_close(&mut self, event_loop: &ActiveEventLoop) { + if self.close_deadline.is_some() { + return; + } + let Some(webview) = self.webview.as_ref().filter(|_| self.ask_before_close) else { + self.shut_down(); + event_loop.exit(); + return; + }; + self.signals + .close_answer + .store(CloseAnswer::Pending as u8, Ordering::Relaxed); + self.close_deadline = Some(std::time::Instant::now() + CLOSE_ANSWER_TIMEOUT); + let signals = Arc::clone(&self.signals); + webview.evaluate_javascript(ASK_CLOSE_SCRIPT, move |result| { + // dispatchEvent returns false when the page cancelled the event. + let answer = match result { + Ok(servo::JSValue::Boolean(false)) => CloseAnswer::Cancel, + Ok(_) => CloseAnswer::Close, + Err(e) => { + tracing::warn!(?e, "the page could not be asked to close; closing"); + CloseAnswer::Close + } + }; + signals.close_answer.store(answer as u8, Ordering::Relaxed); + }); + } + + /// Acts on the page's answer to a pending close request, or on its + /// absence once the answer is due. Returns whether the app is closing. + fn settle_close_request(&mut self) -> bool { + let Some(deadline) = self.close_deadline else { + return false; + }; + let answer = self.signals.close_answer.load(Ordering::Relaxed); + if answer == CloseAnswer::Cancel as u8 { + self.close_deadline = None; + tracing::info!("the page cancelled the close"); + // weft-appd learns that the session keeps running; the token + // keeps page output from forging this report. + if let Ok(token) = std::env::var("WEFT_READY_TOKEN") { + use std::io::Write; + println!("CLOSE_CANCELLED {token}"); + let _ = std::io::stdout().flush(); + } + return false; + } + if answer == CloseAnswer::Close as u8 { + return true; + } + if std::time::Instant::now() >= deadline { + tracing::warn!("the page did not answer the close request in time; closing"); + return true; + } + false + } + /// Paints and presents once Servo has requested its first repaint. /// /// Nothing is presented before that request; the first frames can still be @@ -546,6 +644,17 @@ impl ApplicationHandler for App { if let Some(servo) = &self.servo { servo.spin_event_loop(); } + // The page answers a close request while Servo spins. + if self.signals.page_closed.load(Ordering::Relaxed) || self.settle_close_request() { + self.shut_down(); + event_loop.exit(); + return; + } + // Wake for the close answer's deadline even when nothing else happens. + event_loop.set_control_flow(match self.close_deadline { + Some(deadline) => winit::event_loop::ControlFlow::WaitUntil(deadline), + None => winit::event_loop::ControlFlow::Wait, + }); if self.signals.redraw.swap(false, Ordering::Relaxed) && let Some(w) = &self.window { @@ -605,10 +714,7 @@ impl ApplicationHandler for App { ))); } } - WindowEvent::CloseRequested => { - self.shut_down(); - event_loop.exit(); - } + WindowEvent::CloseRequested => self.request_close(event_loop), _ => {} } } diff --git a/crates/weft-appd/src/launch.rs b/crates/weft-appd/src/launch.rs index 85b5bbc..19efb4f 100644 --- a/crates/weft-appd/src/launch.rs +++ b/crates/weft-appd/src/launch.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; -use weft_ipc_types::manifest::{MANIFEST_FILE, Manifest, ManifestError, entry_path}; +use weft_ipc_types::manifest::{ClosePolicy, MANIFEST_FILE, Manifest, ManifestError, entry_path}; use weft_ipc_types::package::{ImageFiles, is_valid_app_id}; use crate::grants::Refusal; @@ -20,6 +20,8 @@ pub(crate) struct LaunchPackage { pub(crate) module: PathBuf, /// The UI document, from `[ui].entry`. pub(crate) ui_entry: PathBuf, + /// What a user close does, from `[ui].close`. + pub(crate) close: ClosePolicy, pub(crate) capabilities: Vec, /// The image the package root is mounted from, held for as long as the /// session runs. @@ -110,6 +112,7 @@ fn from_root(app_id: &str, root: PathBuf, image: Option) -> Result = vars + .iter() + .map(|(k, _)| (*k, std::env::var_os(k))) + .collect(); + for (key, value) in &vars { + // SAFETY: env_lock is held on a current_thread runtime. + unsafe { std::env::set_var(key, value) }; + } + + let registry = make_registry(); + let (tx, _compositor) = tokio::sync::mpsc::channel(8); + registry.lock().await.compositor_tx = Some(compositor_client::CompositorSender::new( + tx, + std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)), + )); + let mut rx = registry.lock().await.subscribe(); + let ack = dispatch( + Request::LaunchApp { + app_id: "org.example.cancel".into(), + surface_id: 0, + }, + ®istry, + ) + .await; + let Response::LaunchAck { session_id, .. } = ack else { + panic!("{ack:?}"); + }; + let ready = tokio::time::timeout(std::time::Duration::from_secs(10), async { + while !matches!(rx.recv().await, Ok(Response::AppReady { .. })) {} + }) + .await; + let started = std::time::Instant::now(); + dispatch(Request::TerminateApp { session_id }, ®istry).await; + // The session is running again once the genuine report arrives. + let resumed = tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + match rx.recv().await { + Ok(Response::AppState { + state: AppStateKind::Running, + .. + }) => return true, + Ok(Response::AppState { + state: AppStateKind::Stopped, + .. + }) => return false, + _ => {} + } + } + }) + .await; + let resumed_after = started.elapsed(); + let state = registry.lock().await.state(session_id); + // A second request asks again; this time nothing declines it. + dispatch(Request::TerminateApp { session_id }, ®istry).await; + let stopped = tokio::time::timeout(std::time::Duration::from_secs(10), async { + while !matches!( + rx.recv().await, + Ok(Response::AppState { + state: AppStateKind::Stopped, + .. + }) + ) {} + }) + .await; + + for (key, value) in prior { + // SAFETY: as above. + unsafe { + match value { + Some(v) => std::env::set_var(key, v), + None => std::env::remove_var(key), + } + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(ready.is_ok(), "the session did not become ready"); + assert_eq!( + resumed, + Ok(true), + "the cancelled close did not resume the session" + ); + // The forged report one second in did not count. + assert!( + resumed_after >= std::time::Duration::from_millis(1500), + "{resumed_after:?}" + ); + assert!(matches!(state, AppStateKind::Running), "{state:?}"); + assert!(stopped.is_ok(), "the second close did not stop the session"); + } + #[tokio::test(flavor = "current_thread")] async fn an_app_that_ignores_a_close_is_terminated_after_the_timeout() { use std::os::unix::fs::PermissionsExt; diff --git a/crates/weft-appd/src/runtime.rs b/crates/weft-appd/src/runtime.rs index 8ef2dee..ed86f62 100644 --- a/crates/weft-appd/src/runtime.rs +++ b/crates/weft-appd/src/runtime.rs @@ -116,6 +116,8 @@ const READY_TIMEOUT: Duration = Duration::from_secs(30); /// runtime passes the guest only the variables it names and pages cannot read /// the host process environment. const READY_TOKEN_ENV: &str = "WEFT_READY_TOKEN"; +/// The application's close policy, `immediate` or `ask`, for the app shell. +const CLOSE_POLICY_ENV: &str = "WEFT_APP_CLOSE"; /// Environment variable carrying the session's application bridge credential /// to weft-app-shell. @@ -222,6 +224,7 @@ fn spawn_app_shell( .arg("--ui") .arg(&package.ui_entry) .env(READY_TOKEN_ENV, token) + .env(CLOSE_POLICY_ENV, package.close.as_str()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .kill_on_drop(true) @@ -430,7 +433,13 @@ pub(crate) async fn supervise( Ok(reader) => reader, Err(reason) => return session.settle(®istry, &reason).await, }; - tokio::spawn(drain_stdout(shell_stdout, session_id)); + let (cancel_tx, mut cancelled) = tokio::sync::mpsc::channel(1); + tokio::spawn(watch_app_shell_stdout( + shell_stdout, + session_id, + token.clone(), + cancel_tx, + )); { let mut reg = registry.lock().await; @@ -442,25 +451,76 @@ pub(crate) async fn supervise( } tracing::info!(session_id, %app_id, "app ready"); - let reason = tokio::select! { - status = session.runtime.as_mut().expect("runtime spawned").wait() => { - format!("runtime exited ({status:?})") - } - status = session.app_shell.as_mut().expect("app shell spawned").wait() => { - format!("app shell exited ({status:?})") - } - requested = &mut abort_rx => match requested { - Ok(()) => session.close(session_id).await, - // The sender is dropped only when appd shuts down. - Err(_) => "appd is shutting down".to_owned(), - }, - _ = session.relay.as_mut().expect("relay opened").ended() => { - "component closed its IPC connection".to_owned() + let reason = loop { + tokio::select! { + status = session.runtime.as_mut().expect("runtime spawned").wait() => { + break format!("runtime exited ({status:?})"); + } + status = session.app_shell.as_mut().expect("app shell spawned").wait() => { + break format!("app shell exited ({status:?})"); + } + requested = &mut abort_rx => match requested { + Ok(()) => match session.close(session_id, &mut cancelled).await { + Close::Settle(reason) => break reason, + // The application kept running, as its close policy + // allows; a later request asks again. + Close::Cancelled => { + let mut reg = registry.lock().await; + abort_rx = reg.register_abort(session_id); + reg.set_state(session_id, AppStateKind::Running); + let _ = reg.broadcast().send(Response::AppState { + session_id, + state: AppStateKind::Running, + }); + tracing::info!(session_id, "the application cancelled the close"); + } + }, + // The sender is dropped only when appd shuts down. + Err(_) => break "appd is shutting down".to_owned(), + }, + _ = session.relay.as_mut().expect("relay opened").ended() => { + break "component closed its IPC connection".to_owned(); + } } }; session.settle(®istry, &reason).await } +/// How a close request ended. +enum Close { + /// The session ends, for this reason. + Settle(String), + /// The application declined the close and keeps running. + Cancelled, +} + +/// The app shell's report that its page declined a close, followed by the +/// session's readiness token so page output cannot fake it. +const CLOSE_CANCELLED: &str = "CLOSE_CANCELLED"; + +/// Passes the app shell's close reports on to the supervisor and logs +/// everything else it prints. +async fn watch_app_shell_stdout( + mut reader: BufReader, + session_id: u64, + token: String, + cancelled: tokio::sync::mpsc::Sender<()>, +) { + while let Ok(Some(line)) = read_child_line(&mut reader).await { + if line + .strip_prefix(CLOSE_CANCELLED) + .and_then(|rest| rest.strip_prefix(' ')) + .is_some_and(|t| crate::ws::tokens_match(&token, t)) + { + // One pending report is enough; the supervisor drops stale ones + // before it asks again. + let _ = cancelled.try_send(()); + } else { + tracing::debug!(session_id, stdout = %line, "child stdout"); + } + } +} + /// How long an application may take to close after being asked, for /// example to save, before its processes are terminated. pub(crate) const CLOSE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); @@ -526,7 +586,14 @@ impl OwnedSession { /// its windows to close and the app shell gets `CLOSE_TIMEOUT` to exit by /// itself. Returns the terminal reason; settling terminates whatever is /// still running. - async fn close(&mut self, session_id: u64) -> String { + async fn close( + &mut self, + session_id: u64, + cancelled: &mut tokio::sync::mpsc::Receiver<()>, + ) -> Close { + // A report from an earlier close, for example one the user started + // in the compositor, does not answer this one. + while cancelled.try_recv().is_ok() {} let asked = self.client_attached && self.compositor_tx.as_ref().is_some_and(|tx| { tx.is_connected() @@ -535,34 +602,41 @@ impl OwnedSession { .is_ok() }); if !asked { - return "terminate requested; the compositor could not ask the app to close".to_owned(); + return Close::Settle( + "terminate requested; the compositor could not ask the app to close".to_owned(), + ); } let (Some(app_shell), Some(runtime), Some(relay)) = ( self.app_shell.as_mut(), self.runtime.as_mut(), self.relay.as_mut(), ) else { - return "terminate requested".to_owned(); + return Close::Settle("terminate requested".to_owned()); }; let wait = async { tokio::select! { - status = app_shell.wait() => match status { + status = app_shell.wait() => Close::Settle(match status { Ok(status) if status.success() => { format!("closed on request; app shell exited ({status:?})") } status => format!("app shell failed while closing ({status:?})"), - }, - status = runtime.wait() => format!("runtime exited while closing ({status:?})"), - _ = relay.ended() => "component closed its IPC connection while closing".to_owned(), + }), + status = runtime.wait() => { + Close::Settle(format!("runtime exited while closing ({status:?})")) + } + _ = relay.ended() => Close::Settle( + "component closed its IPC connection while closing".to_owned(), + ), + Some(()) = cancelled.recv() => Close::Cancelled, } }; tokio::time::timeout(CLOSE_TIMEOUT, wait) .await .unwrap_or_else(|_| { - format!( + Close::Settle(format!( "close requested; the app shell did not exit within {} s and was terminated", CLOSE_TIMEOUT.as_secs() - ) + )) }) } diff --git a/crates/weft-ipc-types/src/manifest.rs b/crates/weft-ipc-types/src/manifest.rs index 0115bc4..26a56dc 100644 --- a/crates/weft-ipc-types/src/manifest.rs +++ b/crates/weft-ipc-types/src/manifest.rs @@ -38,6 +38,31 @@ pub struct RuntimeMeta { pub struct UiMeta { /// The UI document, relative to the package root. pub entry: String, + /// What happens when the user asks the application's window to close. + #[serde(default)] + pub close: ClosePolicy, +} + +/// An application's declared unsaved-change policy: what a user close does. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ClosePolicy { + /// The window closes at once; the application keeps no unsaved state. + #[default] + Immediate, + /// The page is asked first and may cancel the close, for example to + /// offer saving unsaved changes; it then closes itself when done. + Ask, +} + +impl ClosePolicy { + /// The value weft-appd passes to the app shell in `WEFT_APP_CLOSE`. + pub fn as_str(self) -> &'static str { + match self { + Self::Immediate => "immediate", + Self::Ask => "ask", + } + } } /// Why a manifest could not be read. @@ -212,6 +237,24 @@ mod tests { let manifest = Manifest::read(&dir).unwrap(); assert_eq!(manifest.package.id, "org.weft.test"); assert_eq!(manifest.capabilities(), ["sys:notifications"]); + assert_eq!(manifest.ui.close, ClosePolicy::Immediate); + std::fs::write( + dir.join(MANIFEST_FILE), + "[package]\nid = \"org.weft.test\"\nname = \"T\"\nversion = \"1.0.0\"\n\ + [runtime]\nmodule = \"app.wasm\"\n[ui]\nentry = \"ui/index.html\"\nclose = \"ask\"\n", + ) + .unwrap(); + assert_eq!(Manifest::read(&dir).unwrap().ui.close, ClosePolicy::Ask); + std::fs::write( + dir.join(MANIFEST_FILE), + "[package]\nid = \"org.weft.test\"\nname = \"T\"\nversion = \"1.0.0\"\n\ + [runtime]\nmodule = \"app.wasm\"\n[ui]\nentry = \"ui/index.html\"\nclose = \"later\"\n", + ) + .unwrap(); + assert!(matches!( + Manifest::read(&dir), + Err(ManifestError::Parse(..)) + )); std::fs::write(dir.join(MANIFEST_FILE), "[package]\nid = \"x\"\n").unwrap(); assert!(matches!( Manifest::read(&dir), diff --git a/docs/architecture.md b/docs/architecture.md index d0448bc..8742547 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,7 +20,7 @@ Per-application Servo host. Spawned by `weft-appd` after the Wasm runtime signal ### weft-appd -Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). Before a session exists, appd resolves the package once (see [Package resolution](#package-resolution)) and derives its grants from that package's manifest; the runtime and the app shell receive the resolved component and UI document and do not search the stores themselves. For each session: spawns `weft-runtime` and waits for its READY, spawns `weft-app-shell` (`WEFT_APP_SHELL_BIN` is required) and waits for its READY, and only then reports the session running (`APP_READY`). A child reports readiness by printing `READY ` on stdout, where the token is a random per-session value appd passes in `WEFT_READY_TOKEN`; Wasm guests and pages share those stdout streams but cannot read the token, so their output cannot fake readiness. Each wait times out after 30 seconds. `TERMINATE_APP` on a running session closes it as a user close would: appd replies `stopping`, asks the compositor to close the session's windows, and gives the app shell 5 seconds to exit by itself, for example after saving, before terminating it; the stop reason records which happened (a clean exit, a failure while closing, or the timeout), and `stopped` is broadcast once the session has settled. A repeated `TERMINATE_APP` while the app is closing changes nothing; the timeout is the only forced termination, and a session being closed is not restored at the next start. appd keeps the final state of at most 32 stopped sessions, forgetting those launched earliest. A session still starting is stopped at once, and when appd itself shuts down its sessions are terminated without a close. If either child fails to start, fails to become ready or exits, or the session is terminated, the whole session is stopped: both children, the IPC relay (its task, socket and registered sender), the file portal, the compositor association and any image mount are released. The IPC relay is created with the session in `$XDG_RUNTIME_DIR/weft` (a session cannot start without it); its socket is accessible only to the user and accepts a single connection, which the session's runtime makes before it starts the component. If that connection closes while the session runs, the session is stopped. `IPC_FORWARD` on the Unix socket never waits: it reports an error when the session has no relay or its queue is full. appd applies cgroup resource limits to the runtime via systemd-run when available. +Session supervisor. Listens on a Unix socket (MessagePack protocol) and a WebSocket port (JSON). Before a session exists, appd resolves the package once (see [Package resolution](#package-resolution)) and derives its grants from that package's manifest; the runtime and the app shell receive the resolved component and UI document and do not search the stores themselves. For each session: spawns `weft-runtime` and waits for its READY, spawns `weft-app-shell` (`WEFT_APP_SHELL_BIN` is required) and waits for its READY, and only then reports the session running (`APP_READY`). A child reports readiness by printing `READY ` on stdout, where the token is a random per-session value appd passes in `WEFT_READY_TOKEN`; Wasm guests and pages share those stdout streams but cannot read the token, so their output cannot fake readiness. Each wait times out after 30 seconds. `TERMINATE_APP` on a running session closes it as a user close would: appd replies `stopping`, asks the compositor to close the session's windows, and gives the app shell 5 seconds to exit by itself, for example after saving, before terminating it; the stop reason records which happened (a clean exit, a failure while closing, or the timeout), and `stopped` is broadcast once the session has settled. An application that declares the `ask` close policy may decline the close (see [Closing an application](#closing-an-application)); the session is then `running` again. A repeated `TERMINATE_APP` while the app is closing changes nothing; the timeout is the only forced termination, and a session being closed is not restored at the next start. appd keeps the final state of at most 32 stopped sessions, forgetting those launched earliest. A session still starting is stopped at once, and when appd itself shuts down its sessions are terminated without a close. If either child fails to start, fails to become ready or exits, or the session is terminated, the whole session is stopped: both children, the IPC relay (its task, socket and registered sender), the file portal, the compositor association and any image mount are released. The IPC relay is created with the session in `$XDG_RUNTIME_DIR/weft` (a session cannot start without it); its socket is accessible only to the user and accepts a single connection, which the session's runtime makes before it starts the component. If that connection closes while the session runs, the session is stopped. `IPC_FORWARD` on the Unix socket never waits: it reports an error when the session has no relay or its queue is full. appd applies cgroup resource limits to the runtime via systemd-run when available. ### weft-runtime @@ -121,6 +121,17 @@ The package root must be a directory and its manifest a regular file, neither a A directory install can still be changed by its owner while a session runs, and nothing verifies its content at launch. +## Closing an application + +A user closes an application from the taskbar, which sends `TERMINATE_APP`, or with Alt+F4 in the compositor; both ask the application's window to close. What happens next is the application's declared unsaved-change policy, `[ui].close` in `wapp.toml`: + +- `immediate` (the default): the app shell exits at once. +- `ask`: the app shell dispatches a cancelable `weftclose` event on the page's top-level window and waits up to 2 seconds for it to be handled. If no listener calls `preventDefault()`, or the page does not answer in time, the app shell exits. Otherwise the close is cancelled: the app shell reports this to weft-appd with its readiness token on standard output, so page output cannot forge it, and the session stays running. The page then lets the user decide, and closes itself with `window.close()`, which Servo allows while the top-level document has a single history entry. + +Notes uses `ask`: with unsaved changes it offers "Save and close", which closes only after the save is acknowledged and stays open with the error shown when the save fails, "Close without saving", and Cancel. + +The close timeout of weft-appd still applies to a close that is not declined: an app shell that neither exits nor declines within 5 seconds is terminated, and the stop reason says so. A terminated session, a crash and appd's own shutdown are never reported as a close on request, and say nothing about whether the application saved. + ## App data Each app's private data lives in `$XDG_DATA_HOME/weft/app-data/` (`~/.local/share/weft/app-data/` by default), apart from installed packages. Installing, updating or uninstalling a package never removes it. `weft-appd` creates the directory when a session with an app-data capability starts and makes it accessible only to the user (mode 0700); a symbolic link in its place is refused rather than followed. `weft-appd` and `weft-pack` must run with the same `HOME` and `XDG_DATA_HOME` to agree on this location; the systemd unit allows `weft-appd` to write under `~/.local/share/weft`. diff --git a/docs/building.md b/docs/building.md index d13bbd9..9ca5f22 100644 --- a/docs/building.md +++ b/docs/building.md @@ -85,7 +85,7 @@ same nested desktop and drive the demo apps with real keyboard input: ```sh python3 tests/frame/check_counter.py # Counter round trip through the session bridge -python3 tests/frame/check_notes.py # Notes stores exactly what is typed, refuses stale saves +python3 tests/frame/check_notes.py # Notes stores exactly what is typed, refuses stale saves, asks before closing unsaved text python3 tests/frame/check_app_data.py # Notes data from the earlier layout is moved and kept python3 tests/frame/check_confinement.py # an app page reaches only its UI files and its session bridge python3 tests/frame/check_activation.py # apps fill the work area above the taskbar; launch and ACTIVATE_APP raise and focus diff --git a/examples/org.weft.demo.notes/signature.sig b/examples/org.weft.demo.notes/signature.sig index 637f568..2de0ba8 100644 --- a/examples/org.weft.demo.notes/signature.sig +++ b/examples/org.weft.demo.notes/signature.sig @@ -1 +1 @@ -e8c10750b142b9df4405fd33ea0c060e63d44b5293e7f9ffa5b076989146b05e81f716e9b92aaeeb139ce1dc9b13ed26f356385d6a61a19c7f3dcaf6e95d2d03 \ No newline at end of file +6bd7b2df26ef619b20c73aa42ed92438d8b0c8515e35f47fd4be346cd90875b53e83374413a3b6008b2b0a718ba1da28497532f04a54b673ebc074db94ce730c \ No newline at end of file diff --git a/examples/org.weft.demo.notes/ui/index.html b/examples/org.weft.demo.notes/ui/index.html index f99a124..114a4b3 100644 --- a/examples/org.weft.demo.notes/ui/index.html +++ b/examples/org.weft.demo.notes/ui/index.html @@ -80,6 +80,15 @@ font-size: 12px; color: #444; } + #closing { + display: none; + align-items: center; + gap: 8px; + flex-shrink: 0; + font-size: 13px; + } + #closing.shown { display: flex; } + #closing span { flex: 1; } #charcount { font-size: 12px; color: #444; @@ -95,6 +104,12 @@ +
+ These notes have unsaved changes. + + + +