mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
Merge feat/app-close-policy: let an application decline a close to keep unsaved changes (#24)
This commit is contained in:
commit
400f430ced
13 changed files with 1035 additions and 115 deletions
|
|
@ -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<crate::shell_client::ShellClient>,
|
||||
/// 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<std::time::Instant>,
|
||||
}
|
||||
|
||||
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<ServoWake> 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<ServoWake> for App {
|
|||
)));
|
||||
}
|
||||
}
|
||||
WindowEvent::CloseRequested => {
|
||||
self.shut_down();
|
||||
event_loop.exit();
|
||||
}
|
||||
WindowEvent::CloseRequested => self.request_close(event_loop),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,8 +8,12 @@ pub enum Request {
|
|||
app_id: String,
|
||||
surface_id: u64,
|
||||
},
|
||||
/// Asks a running session to close as a user close would, or with
|
||||
/// `force`, terminates it without asking.
|
||||
TerminateApp {
|
||||
session_id: u64,
|
||||
#[serde(default)]
|
||||
force: bool,
|
||||
},
|
||||
/// Brings the session's window to the front with keyboard focus.
|
||||
ActivateApp {
|
||||
|
|
@ -215,10 +219,19 @@ mod tests {
|
|||
|
||||
#[test]
|
||||
fn terminate_app_request_roundtrip() {
|
||||
let req = Request::TerminateApp { session_id: 42 };
|
||||
let req = Request::TerminateApp {
|
||||
session_id: 42,
|
||||
force: false,
|
||||
};
|
||||
let bytes = rmp_serde::to_vec(&req).unwrap();
|
||||
let decoded: Request = rmp_serde::from_slice(&bytes).unwrap();
|
||||
assert!(matches!(decoded, Request::TerminateApp { session_id: 42 }));
|
||||
assert!(matches!(
|
||||
decoded,
|
||||
Request::TerminateApp {
|
||||
session_id: 42,
|
||||
force: false
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -13,7 +13,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 weft_ipc_types::trust::{
|
||||
Inventory, Owner, PublisherKey, TrustError, TrustStore, lock_owner, owner_record_path,
|
||||
|
|
@ -31,6 +31,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<String>,
|
||||
/// The image the package root is mounted from, held for as long as the
|
||||
/// session runs.
|
||||
|
|
@ -161,6 +163,7 @@ fn from_root(app_id: &str, root: PathBuf, image: Option<Mount>) -> Result<Launch
|
|||
capabilities: manifest.capabilities().to_vec(),
|
||||
module,
|
||||
ui_entry,
|
||||
close: manifest.ui.close,
|
||||
root,
|
||||
image,
|
||||
pin: None,
|
||||
|
|
@ -282,6 +285,7 @@ impl LaunchPackage {
|
|||
root: PathBuf::from("/nonexistent"),
|
||||
module: PathBuf::from("/nonexistent/app.wasm"),
|
||||
ui_entry: PathBuf::from("/nonexistent/ui/index.html"),
|
||||
close: ClosePolicy::Immediate,
|
||||
capabilities: Vec::new(),
|
||||
image: None,
|
||||
pin: None,
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ struct SessionRegistry {
|
|||
next_id: u64,
|
||||
sessions: std::collections::HashMap<u64, SessionEntry>,
|
||||
broadcast: tokio::sync::broadcast::Sender<Response>,
|
||||
abort_senders: std::collections::HashMap<u64, tokio::sync::oneshot::Sender<()>>,
|
||||
abort_senders: std::collections::HashMap<u64, runtime::StopSender>,
|
||||
compositor_tx: Option<compositor_client::CompositorSender>,
|
||||
ipc_senders: std::collections::HashMap<u64, tokio::sync::mpsc::Sender<String>>,
|
||||
}
|
||||
|
|
@ -109,26 +109,46 @@ impl SessionRegistry {
|
|||
})
|
||||
}
|
||||
|
||||
/// Asks a session to stop: a running session is closed as a user close
|
||||
/// would close it, a starting one is stopped at once. The session stays
|
||||
/// registered, Stopping, until its supervisor settles it.
|
||||
fn terminate(&mut self, session_id: u64) -> bool {
|
||||
match self.abort_senders.remove(&session_id) {
|
||||
Some(sender) => {
|
||||
let _ = sender.send(());
|
||||
self.set_state(session_id, AppStateKind::Stopping);
|
||||
true
|
||||
/// Asks a session to stop and returns the state to report, or `None`
|
||||
/// when there is no such session. A running session is asked to close
|
||||
/// as a user close would, and stays running while the application
|
||||
/// answers; a forced stop or a session still starting is stopped at
|
||||
/// once and is Stopping until its supervisor settles it.
|
||||
fn terminate(&mut self, session_id: u64, force: bool) -> Option<AppStateKind> {
|
||||
let state = self.state(session_id);
|
||||
match self.abort_senders.get(&session_id) {
|
||||
// Already ending; a forced request still ends it without waiting.
|
||||
Some(sender) if matches!(state, AppStateKind::Stopping) => {
|
||||
if force {
|
||||
let _ = sender.try_send(runtime::Stop::Force);
|
||||
}
|
||||
Some(AppStateKind::Stopping)
|
||||
}
|
||||
Some(sender) => {
|
||||
// A close is queued only into an empty queue, so a forced
|
||||
// request always finds room; one already queued says the
|
||||
// same as a repeat.
|
||||
if force {
|
||||
let _ = sender.try_send(runtime::Stop::Force);
|
||||
} else if sender.capacity() == runtime::STOP_QUEUE {
|
||||
let _ = sender.try_send(runtime::Stop::Close);
|
||||
}
|
||||
if !force && matches!(state, AppStateKind::Running) {
|
||||
return Some(AppStateKind::Running);
|
||||
}
|
||||
self.set_state(session_id, AppStateKind::Stopping);
|
||||
Some(AppStateKind::Stopping)
|
||||
}
|
||||
// A session already closing keeps closing; it stays registered
|
||||
// until its supervisor settles it.
|
||||
None if matches!(self.state(session_id), AppStateKind::Stopping) => true,
|
||||
// A session no supervisor runs has nothing to settle.
|
||||
None => self.sessions.remove(&session_id).is_some(),
|
||||
None => self
|
||||
.sessions
|
||||
.remove(&session_id)
|
||||
.map(|_| AppStateKind::Stopped),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn register_abort(&mut self, session_id: u64) -> tokio::sync::oneshot::Receiver<()> {
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
pub(crate) fn register_abort(&mut self, session_id: u64) -> runtime::StopReceiver {
|
||||
let (tx, rx) = tokio::sync::mpsc::channel(runtime::STOP_QUEUE);
|
||||
self.abort_senders.insert(session_id, tx);
|
||||
rx
|
||||
}
|
||||
|
|
@ -154,7 +174,7 @@ impl SessionRegistry {
|
|||
.collect()
|
||||
}
|
||||
|
||||
fn state(&self, session_id: u64) -> AppStateKind {
|
||||
pub(crate) fn state(&self, session_id: u64) -> AppStateKind {
|
||||
self.sessions
|
||||
.get(&session_id)
|
||||
.map(|e| e.state.clone())
|
||||
|
|
@ -566,30 +586,30 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response {
|
|||
});
|
||||
Response::LaunchAck { session_id, app_id }
|
||||
}
|
||||
Request::TerminateApp { session_id } => {
|
||||
let found = {
|
||||
Request::TerminateApp { session_id, force } => {
|
||||
let state = {
|
||||
let mut reg = registry.lock().await;
|
||||
let found = reg.terminate(session_id);
|
||||
if found && matches!(reg.state(session_id), AppStateKind::Stopping) {
|
||||
// Every client, not only the requester, shows the close.
|
||||
let before = reg.state(session_id);
|
||||
let state = reg.terminate(session_id, force);
|
||||
if matches!(state, Some(AppStateKind::Stopping))
|
||||
&& !matches!(before, AppStateKind::Stopping)
|
||||
{
|
||||
let _ = reg.broadcast().send(Response::AppState {
|
||||
session_id,
|
||||
state: AppStateKind::Stopping,
|
||||
});
|
||||
}
|
||||
found
|
||||
state
|
||||
};
|
||||
if found {
|
||||
tracing::info!(session_id, "stop requested");
|
||||
Response::AppState {
|
||||
session_id,
|
||||
state: AppStateKind::Stopping,
|
||||
match state {
|
||||
Some(state) => {
|
||||
tracing::info!(session_id, force, "stop requested");
|
||||
Response::AppState { session_id, state }
|
||||
}
|
||||
} else {
|
||||
Response::Error {
|
||||
None => Response::Error {
|
||||
code: 1,
|
||||
message: format!("session {session_id} not found"),
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
Request::ActivateApp { session_id } => {
|
||||
|
|
@ -1104,7 +1124,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_terminate_known_returns_stopping() {
|
||||
async fn dispatch_terminate_forgets_a_stopped_session() {
|
||||
let _env = env_lock().lock().await;
|
||||
let reg = make_registry();
|
||||
let ack = dispatch(
|
||||
|
|
@ -1119,22 +1139,43 @@ mod tests {
|
|||
Response::LaunchAck { session_id, .. } => session_id,
|
||||
_ => panic!("expected LaunchAck"),
|
||||
};
|
||||
// The reply says the session is stopping; Stopped is broadcast once
|
||||
// its supervisor has settled it.
|
||||
let resp = dispatch(Request::TerminateApp { session_id }, ®).await;
|
||||
// Without a configured runtime the session stopped at once; a
|
||||
// terminate forgets it.
|
||||
let resp = dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id,
|
||||
force: false,
|
||||
},
|
||||
®,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
matches!(
|
||||
resp,
|
||||
Response::AppState {
|
||||
state: AppStateKind::Stopped,
|
||||
..
|
||||
}
|
||||
),
|
||||
"{resp:?}"
|
||||
);
|
||||
assert!(matches!(
|
||||
resp,
|
||||
Response::AppState {
|
||||
state: AppStateKind::Stopping,
|
||||
..
|
||||
}
|
||||
reg.lock().await.state(session_id),
|
||||
AppStateKind::NotFound
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatch_terminate_unknown_returns_error() {
|
||||
let reg = make_registry();
|
||||
let resp = dispatch(Request::TerminateApp { session_id: 999 }, ®).await;
|
||||
let resp = dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id: 999,
|
||||
force: false,
|
||||
},
|
||||
®,
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(resp, Response::Error { .. }));
|
||||
}
|
||||
|
||||
|
|
@ -1245,14 +1286,14 @@ mod tests {
|
|||
fn registry_terminate_known_session() {
|
||||
let mut reg = SessionRegistry::default();
|
||||
let id = reg.launch("com.example.app");
|
||||
assert!(reg.terminate(id));
|
||||
assert!(reg.terminate(id, false).is_some());
|
||||
assert!(matches!(reg.state(id), AppStateKind::NotFound));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_terminate_unknown_returns_false() {
|
||||
let mut reg = SessionRegistry::default();
|
||||
assert!(!reg.terminate(999));
|
||||
assert!(reg.terminate(999, false).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1267,7 +1308,7 @@ mod tests {
|
|||
assert_eq!(sessions[0].app_id, "com.example.a");
|
||||
assert_eq!(sessions[1].session_id, id2);
|
||||
assert_eq!(sessions[1].app_id, "com.example.b");
|
||||
reg.terminate(id1);
|
||||
reg.terminate(id1, false);
|
||||
assert_eq!(reg.running_sessions().len(), 1);
|
||||
assert_eq!(reg.running_sessions()[0].session_id, id2);
|
||||
}
|
||||
|
|
@ -1540,6 +1581,168 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn an_app_that_cancels_a_close_keeps_running() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _env = env_lock().lock().await;
|
||||
use_test_runtime_dir();
|
||||
let dir = std::env::temp_dir().join(format!("weft_test_cancel_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let app = dir.join("store/org.example.cancel");
|
||||
write_test_package(&app, "org.example.cancel", "");
|
||||
let runtime = dir.join("runtime.sh");
|
||||
std::fs::write(
|
||||
&runtime,
|
||||
"#!/bin/sh\necho READY $WEFT_READY_TOKEN\nexec sleep 30\n",
|
||||
)
|
||||
.unwrap();
|
||||
// The app shell declines the close once, after a forged report.
|
||||
let shell = dir.join("shell.sh");
|
||||
std::fs::write(
|
||||
&shell,
|
||||
"#!/bin/sh\necho READY $WEFT_READY_TOKEN\nsleep 1\n\
|
||||
echo CLOSE_CANCELLED 00000000000000000000000000000000\nsleep 1\n\
|
||||
echo CLOSE_CANCELLED $WEFT_READY_TOKEN\nexec sleep 30\n",
|
||||
)
|
||||
.unwrap();
|
||||
for script in [&runtime, &shell] {
|
||||
std::fs::set_permissions(script, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let vars = [
|
||||
("WEFT_RUNTIME_BIN", runtime.clone().into_os_string()),
|
||||
("WEFT_APP_SHELL_BIN", shell.clone().into_os_string()),
|
||||
("WEFT_DISABLE_CGROUP", "1".into()),
|
||||
("WEFT_APP_STORE", dir.join("store").into_os_string()),
|
||||
];
|
||||
let prior: Vec<_> = 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, mut 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,
|
||||
force: false,
|
||||
},
|
||||
®istry,
|
||||
)
|
||||
.await;
|
||||
// Once the genuine report arrives, the declining window is brought
|
||||
// to the front, and the session never left Running.
|
||||
let resumed = tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
loop {
|
||||
match compositor.recv().await.map(|out| out.msg) {
|
||||
Some(weft_ipc_types::AppdToCompositor::AppFocusRequest { session_id: s })
|
||||
if s == session_id =>
|
||||
{
|
||||
return true;
|
||||
}
|
||||
Some(_) => {}
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
let mut broadcasts = Vec::new();
|
||||
while let Ok(message) = rx.try_recv() {
|
||||
broadcasts.push(message);
|
||||
}
|
||||
let resumed_after = started.elapsed();
|
||||
let state = registry.lock().await.state(session_id);
|
||||
// A forced stop does not ask, so nothing can decline it.
|
||||
let forced_at = std::time::Instant::now();
|
||||
let forced = dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id,
|
||||
force: true,
|
||||
},
|
||||
®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!(
|
||||
!broadcasts
|
||||
.iter()
|
||||
.any(|m| matches!(m, Response::AppState { .. })),
|
||||
"{broadcasts:?}"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
forced,
|
||||
Response::AppState {
|
||||
state: AppStateKind::Stopping,
|
||||
..
|
||||
}
|
||||
),
|
||||
"{forced:?}"
|
||||
);
|
||||
assert!(stopped.is_ok(), "a forced stop did not stop the session");
|
||||
assert!(
|
||||
forced_at.elapsed() < std::time::Duration::from_secs(3),
|
||||
"{:?}",
|
||||
forced_at.elapsed()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn an_app_that_ignores_a_close_is_terminated_after_the_timeout() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
|
@ -1595,10 +1798,24 @@ mod tests {
|
|||
})
|
||||
.await;
|
||||
let started = std::time::Instant::now();
|
||||
let reply = dispatch(Request::TerminateApp { session_id }, ®istry).await;
|
||||
// A second request while the app is closing changes nothing: the
|
||||
// session stays registered and listed until it settles.
|
||||
let again = dispatch(Request::TerminateApp { session_id }, ®istry).await;
|
||||
let reply = dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id,
|
||||
force: false,
|
||||
},
|
||||
®istry,
|
||||
)
|
||||
.await;
|
||||
// While the application is asked, the session is still running; a
|
||||
// second request changes nothing and does not ask again.
|
||||
let again = dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id,
|
||||
force: false,
|
||||
},
|
||||
®istry,
|
||||
)
|
||||
.await;
|
||||
let closing = {
|
||||
let reg = registry.lock().await;
|
||||
(
|
||||
|
|
@ -1640,7 +1857,7 @@ mod tests {
|
|||
matches!(
|
||||
reply,
|
||||
Response::AppState {
|
||||
state: AppStateKind::Stopping,
|
||||
state: AppStateKind::Running,
|
||||
..
|
||||
}
|
||||
),
|
||||
|
|
@ -1650,27 +1867,32 @@ mod tests {
|
|||
matches!(
|
||||
again,
|
||||
Response::AppState {
|
||||
state: AppStateKind::Stopping,
|
||||
state: AppStateKind::Running,
|
||||
..
|
||||
}
|
||||
),
|
||||
"{again:?}"
|
||||
);
|
||||
assert!(
|
||||
matches!(closing.0, AppStateKind::Stopping),
|
||||
matches!(closing.0, AppStateKind::Running),
|
||||
"{:?}",
|
||||
closing.0
|
||||
);
|
||||
assert!(closing.1, "a closing session is no longer listed");
|
||||
// An app the user closed is not restored at the next start.
|
||||
assert!(closing.2.is_empty(), "{:?}", closing.2);
|
||||
assert!(
|
||||
closing.1,
|
||||
"a session being asked to close is no longer listed"
|
||||
);
|
||||
assert_eq!(closing.2, ["org.example.close"]);
|
||||
assert!(stopped.is_ok(), "the session did not stop");
|
||||
// The app was asked to close, given the timeout, then terminated.
|
||||
assert!(
|
||||
sent.iter().any(|m| matches!(
|
||||
m,
|
||||
weft_ipc_types::AppdToCompositor::AppCloseRequest { session_id: s } if *s == session_id
|
||||
)),
|
||||
assert_eq!(
|
||||
sent.iter()
|
||||
.filter(|m| matches!(
|
||||
m,
|
||||
weft_ipc_types::AppdToCompositor::AppCloseRequest { session_id: s } if *s == session_id
|
||||
))
|
||||
.count(),
|
||||
1,
|
||||
"{sent:?}"
|
||||
);
|
||||
assert!(elapsed >= runtime::CLOSE_TIMEOUT, "{elapsed:?}");
|
||||
|
|
@ -1680,6 +1902,139 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn a_forced_stop_ends_a_close_in_progress() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let _env = env_lock().lock().await;
|
||||
use_test_runtime_dir();
|
||||
let dir = std::env::temp_dir().join(format!("weft_test_force_{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let app = dir.join("store/org.example.force");
|
||||
write_test_package(&app, "org.example.force", "");
|
||||
// Both children report ready and then ignore everything.
|
||||
let child = dir.join("child.sh");
|
||||
std::fs::write(
|
||||
&child,
|
||||
"#!/bin/sh\necho READY $WEFT_READY_TOKEN\nexec sleep 30\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&child, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let vars = [
|
||||
("WEFT_RUNTIME_BIN", child.clone().into_os_string()),
|
||||
("WEFT_APP_SHELL_BIN", child.clone().into_os_string()),
|
||||
("WEFT_DISABLE_CGROUP", "1".into()),
|
||||
("WEFT_APP_STORE", dir.join("store").into_os_string()),
|
||||
];
|
||||
let prior: Vec<_> = 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.force".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;
|
||||
// The close is under way: the session is running while it is asked.
|
||||
let asked = dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id,
|
||||
force: false,
|
||||
},
|
||||
®istry,
|
||||
)
|
||||
.await;
|
||||
// Repeats fill no queue a forced stop then cannot enter.
|
||||
for _ in 0..3 {
|
||||
dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id,
|
||||
force: false,
|
||||
},
|
||||
®istry,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
|
||||
let forced_at = std::time::Instant::now();
|
||||
let reply = dispatch(
|
||||
Request::TerminateApp {
|
||||
session_id,
|
||||
force: true,
|
||||
},
|
||||
®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;
|
||||
let elapsed = forced_at.elapsed();
|
||||
drop(compositor);
|
||||
|
||||
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!(
|
||||
matches!(
|
||||
reply,
|
||||
Response::AppState {
|
||||
state: AppStateKind::Stopping,
|
||||
..
|
||||
}
|
||||
),
|
||||
"{reply:?}"
|
||||
);
|
||||
assert!(
|
||||
matches!(
|
||||
asked,
|
||||
Response::AppState {
|
||||
state: AppStateKind::Running,
|
||||
..
|
||||
}
|
||||
),
|
||||
"{asked:?}"
|
||||
);
|
||||
assert!(stopped.is_ok(), "the forced stop did not stop the session");
|
||||
// The forced stop does not wait out the close timeout.
|
||||
assert!(elapsed < std::time::Duration::from_secs(3), "{elapsed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_latest_stopped_sessions_stay_registered() {
|
||||
let mut reg = SessionRegistry::default();
|
||||
|
|
@ -2036,6 +2391,11 @@ mod tests {
|
|||
Ok(Ok(Response::AppReady { session_id: sid, .. })) if sid == session_id
|
||||
));
|
||||
|
||||
let stopping = tokio::time::timeout(std::time::Duration::from_millis(200), rx.recv()).await;
|
||||
assert!(matches!(
|
||||
stopping,
|
||||
Ok(Ok(Response::AppState { session_id: sid, state: AppStateKind::Stopping })) if sid == session_id
|
||||
));
|
||||
let stopped = tokio::time::timeout(std::time::Duration::from_millis(200), rx.recv()).await;
|
||||
assert!(matches!(
|
||||
stopped,
|
||||
|
|
@ -2080,7 +2440,7 @@ mod tests {
|
|||
let session_id = registry.lock().await.launch("test.abort.startup");
|
||||
let abort_rx = registry.lock().await.register_abort(session_id);
|
||||
|
||||
registry.lock().await.terminate(session_id);
|
||||
registry.lock().await.terminate(session_id, false);
|
||||
|
||||
use_test_runtime_dir();
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
@ -260,12 +263,27 @@ fn spawn_file_portal(
|
|||
Some((socket, child))
|
||||
}
|
||||
|
||||
/// A request to end a session, from `TERMINATE_APP`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Stop {
|
||||
/// Close as a user close would; the application may decline.
|
||||
Close,
|
||||
/// Terminate without asking.
|
||||
Force,
|
||||
}
|
||||
|
||||
/// Repeated requests carry nothing new, so a few queued ones are enough.
|
||||
pub(crate) const STOP_QUEUE: usize = 2;
|
||||
pub(crate) type StopSender = tokio::sync::mpsc::Sender<Stop>;
|
||||
/// Ends when appd shuts down and drops the sender.
|
||||
pub(crate) type StopReceiver = tokio::sync::mpsc::Receiver<Stop>;
|
||||
|
||||
pub(crate) async fn supervise(
|
||||
session_id: u64,
|
||||
mut package: LaunchPackage,
|
||||
grants: crate::grants::SessionGrants,
|
||||
registry: Registry,
|
||||
abort_rx: tokio::sync::oneshot::Receiver<()>,
|
||||
abort_rx: StopReceiver,
|
||||
compositor_tx: Option<CompositorSender>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut abort_rx = abort_rx;
|
||||
|
|
@ -430,10 +448,22 @@ 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;
|
||||
// A stop requested while starting can still be queued here, or lose
|
||||
// the race with READY; the session is then stopped, not shown.
|
||||
if matches!(reg.state(session_id), AppStateKind::Stopping) || abort_rx.try_recv().is_ok() {
|
||||
drop(reg);
|
||||
return session.settle(®istry, "startup aborted").await;
|
||||
}
|
||||
reg.set_state(session_id, AppStateKind::Running);
|
||||
let _ = reg.broadcast().send(Response::AppReady {
|
||||
session_id,
|
||||
|
|
@ -442,25 +472,84 @@ 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()
|
||||
// Whether the user asked the application to close, so that a clean exit
|
||||
// afterwards, also one the application makes after declining, is a
|
||||
// close on request.
|
||||
let mut close_asked = false;
|
||||
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 match status {
|
||||
Ok(status) if close_asked && status.success() => {
|
||||
format!("closed on request; app shell exited ({status:?})")
|
||||
}
|
||||
status => format!("app shell exited ({status:?})"),
|
||||
};
|
||||
}
|
||||
stop = abort_rx.recv() => match stop {
|
||||
Some(Stop::Force) => break "terminated by force".to_owned(),
|
||||
Some(Stop::Close) => {
|
||||
close_asked = true;
|
||||
match session.close(session_id, &mut cancelled, &mut abort_rx).await {
|
||||
Close::Settle(reason) => break reason,
|
||||
// The application keeps running, as its close
|
||||
// policy allows; its window comes to the front so
|
||||
// the user sees why. A later request asks again.
|
||||
Close::Cancelled => {
|
||||
tracing::info!(session_id, "the application declined the close");
|
||||
session.focus(session_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The senders are dropped only when appd shuts down.
|
||||
None => 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<tokio::process::ChildStdout>,
|
||||
session_id: u64,
|
||||
token: String,
|
||||
cancelled: tokio::sync::mpsc::Sender<()>,
|
||||
) {
|
||||
while let Ok(Some(line)) = read_child_line(&mut reader).await {
|
||||
// Earlier output without a trailing newline can precede the
|
||||
// report, as it can precede READY; the token alone establishes it.
|
||||
if line.rsplit_once(' ').is_some_and(|(head, t)| {
|
||||
head.ends_with(CLOSE_CANCELLED) && 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 +615,18 @@ 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<()>,
|
||||
stops: &mut StopReceiver,
|
||||
) -> Close {
|
||||
// A report already read from an earlier close, for example one the
|
||||
// user started in the compositor, does not answer this one. One
|
||||
// still in the pipe can: the session then reads as declined while
|
||||
// the app shell is still asking, and the app shell's own answer
|
||||
// timeout still closes a page that does not answer.
|
||||
while cancelled.try_recv().is_ok() {}
|
||||
let asked = self.client_attached
|
||||
&& self.compositor_tx.as_ref().is_some_and(|tx| {
|
||||
tx.is_connected()
|
||||
|
|
@ -535,40 +635,77 @@ 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 {
|
||||
Ok(status) if status.success() => {
|
||||
format!("closed on request; app shell exited ({status:?})")
|
||||
loop {
|
||||
tokio::select! {
|
||||
status = app_shell.wait() => break 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() => {
|
||||
break Close::Settle(format!("runtime exited while closing ({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(),
|
||||
_ = relay.ended() => break Close::Settle(
|
||||
"component closed its IPC connection while closing".to_owned(),
|
||||
),
|
||||
Some(()) = cancelled.recv() => break Close::Cancelled,
|
||||
stop = stops.recv() => match stop {
|
||||
// Asking again while the application answers changes
|
||||
// nothing.
|
||||
Some(Stop::Close) => {}
|
||||
Some(Stop::Force) => {
|
||||
break Close::Settle("terminated by force while closing".to_owned());
|
||||
}
|
||||
None => break Close::Settle("appd is shutting down".to_owned()),
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
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()
|
||||
)
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// Brings the session's window to the front with keyboard focus.
|
||||
fn focus(&self, session_id: u64) {
|
||||
if self.client_attached
|
||||
&& let Some(tx) = &self.compositor_tx
|
||||
{
|
||||
let _ = tx.try_send(AppdToCompositor::AppFocusRequest { session_id }.into());
|
||||
}
|
||||
}
|
||||
|
||||
async fn settle(self, registry: &Registry, reason: &str) -> anyhow::Result<()> {
|
||||
let session_id = self.session_id;
|
||||
tracing::info!(session_id, reason, "stopping session");
|
||||
{
|
||||
let mut reg = registry.lock().await;
|
||||
if !matches!(reg.state(session_id), AppStateKind::Stopping) {
|
||||
reg.set_state(session_id, AppStateKind::Stopping);
|
||||
let _ = reg.broadcast().send(Response::AppState {
|
||||
session_id,
|
||||
state: AppStateKind::Stopping,
|
||||
});
|
||||
}
|
||||
}
|
||||
kill_child(self.app_shell).await;
|
||||
kill_child(self.runtime).await;
|
||||
if self.client_attached
|
||||
|
|
@ -615,7 +752,7 @@ async fn kill_child(child: Option<tokio::process::Child>) {
|
|||
async fn wait_for_child_ready(
|
||||
stdout: tokio::process::ChildStdout,
|
||||
token: &str,
|
||||
abort_rx: &mut tokio::sync::oneshot::Receiver<()>,
|
||||
abort_rx: &mut StopReceiver,
|
||||
) -> Result<BufReader<tokio::process::ChildStdout>, String> {
|
||||
tokio::select! {
|
||||
r = tokio::time::timeout(READY_TIMEOUT, wait_for_ready(stdout, token)) => match r {
|
||||
|
|
@ -623,7 +760,8 @@ async fn wait_for_child_ready(
|
|||
Ok(Err(e)) => Err(format!("did not become ready: {e}")),
|
||||
Err(_) => Err(format!("not ready after {}s", READY_TIMEOUT.as_secs())),
|
||||
},
|
||||
_ = abort_rx => Err("startup aborted".to_owned()),
|
||||
// Any stop request, or appd shutting down, ends a startup.
|
||||
_ = abort_rx.recv() => Err("startup aborted".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
@ -222,6 +247,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),
|
||||
|
|
|
|||
|
|
@ -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 <token>` 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 <token>` 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 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 session stays `running` while the application answers (appd replies with that state), and enters `stopping` only once it is ending. An application that declares the `ask` close policy may decline the close (see [Closing an application](#closing-an-application)); its window is brought to the front and the session keeps running. A repeated request while the application answers changes nothing, and a session being asked to close is still restored at the next start if appd stops meanwhile. `TERMINATE_APP` with `"force": true` terminates the session without asking; the taskbar offers it, as Force quit, for an app still running once it has had time to answer. The stop reason records what happened: a close on request with a clean exit, a failure while closing, the timeout, or a forced stop; `stopped` is broadcast once the session has settled. A session still starting is stopped at once, also when the request races its readiness, and when appd itself shuts down its sessions are terminated without a close. appd keeps the final state of at most 32 stopped sessions, forgetting those launched earliest. 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
|
||||
|
||||
|
|
@ -129,6 +129,17 @@ The revision active before an update is kept for `weft-pack rollback <id>`, whic
|
|||
|
||||
A launch is refused (500, try again) while a package operation holds the revision it would run from, rather than waiting for it. Only sessions started by this weft-appd hold their revisions: a session left from an earlier version, or processes that outlive weft-appd, do not, and a package directory from before revisions such sessions run from can be replaced under them. Package operations on one app are serialised by the owner lock in the data home of the user running them; the store itself is not locked against users with other data homes.
|
||||
|
||||
## 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 declined: the app shell reports this to weft-appd with its readiness token on standard output, so page output cannot forge it, and the session keeps 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. A clean exit after a close request, including one the page makes after declining, is recorded as a close on request. A report still unread when a new request arrives can answer that request early; the app shell still closes a page that does not answer.
|
||||
|
||||
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. An application can decline every close, so a forced stop never asks it: it is the user's way to end an application that will not close. A forced stop, the timeout, 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/<id>` (`~/.local/share/weft/app-data/<id>` 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`.
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
e8c10750b142b9df4405fd33ea0c060e63d44b5293e7f9ffa5b076989146b05e81f716e9b92aaeeb139ce1dc9b13ed26f356385d6a61a19c7f3dcaf6e95d2d03
|
||||
3c5155af4973c453e5c09b04aa0eaf71e943b6564d9aaa81a5fb023fe3ebea091a793ef493234a5a862b9752acf7cafbb0d11a2ec9c962331606ebde75c7b803
|
||||
|
|
@ -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 @@
|
|||
<button class="primary" id="save">Save</button>
|
||||
</div>
|
||||
</header>
|
||||
<div id="closing" role="alertdialog" aria-label="Unsaved changes">
|
||||
<span>These notes have unsaved changes.</span>
|
||||
<button class="primary" id="close-save">Save and close</button>
|
||||
<button id="close-discard">Close without saving</button>
|
||||
<button id="close-cancel">Cancel</button>
|
||||
</div>
|
||||
<textarea id="editor" placeholder="Start typing…" spellcheck="false"></textarea>
|
||||
<footer>
|
||||
<span id="status">connecting…</span>
|
||||
|
|
@ -121,6 +136,8 @@
|
|||
var lastSent = null;
|
||||
var loading = null; // timer of the outstanding load, if any
|
||||
var encoder = new TextEncoder();
|
||||
var closing = document.getElementById('closing');
|
||||
var closeAfterSave = false;
|
||||
|
||||
function setStatus(msg) { statusEl.textContent = msg; }
|
||||
function countChars() { charEl.textContent = editor.value.length + ' chars'; }
|
||||
|
|
@ -138,8 +155,48 @@
|
|||
setLoaded(rev !== null);
|
||||
}
|
||||
|
||||
// Close policy ("ask" in wapp.toml): when the window is asked to close
|
||||
// with unsaved changes, the close is cancelled and the user chooses to
|
||||
// save first, close without saving, or keep editing. The window closes
|
||||
// after a save only once the save is acknowledged, saving again first if
|
||||
// the text changed meanwhile; a failed save keeps it open with the error
|
||||
// shown. Text typed while the notes are not loaded cannot be saved, so it
|
||||
// does not hold the window open.
|
||||
function unsaved() {
|
||||
return pending !== null || (rev !== null && editor.value !== saved);
|
||||
}
|
||||
|
||||
function hideClosing() {
|
||||
closing.classList.remove('shown');
|
||||
closeAfterSave = false;
|
||||
}
|
||||
|
||||
window.addEventListener('weftclose', function (e) {
|
||||
if (!unsaved()) return;
|
||||
e.preventDefault();
|
||||
// Asked again while the prompt is up, keep the user's choice so far.
|
||||
closing.classList.add('shown');
|
||||
});
|
||||
|
||||
document.getElementById('close-save').addEventListener('click', function () {
|
||||
closeAfterSave = true;
|
||||
if (!pending) saveButton.click();
|
||||
// The save could not start (status says why): stay open.
|
||||
if (!pending) hideClosing();
|
||||
});
|
||||
|
||||
document.getElementById('close-discard').addEventListener('click', function () {
|
||||
window.close();
|
||||
});
|
||||
|
||||
document.getElementById('close-cancel').addEventListener('click', hideClosing);
|
||||
|
||||
saveButton.addEventListener('click', function () {
|
||||
if (!window.weftIpc || pending) return;
|
||||
if (pending) return;
|
||||
if (!window.weftIpc) {
|
||||
setStatus('not saved: not connected');
|
||||
return;
|
||||
}
|
||||
if (rev === null) {
|
||||
setStatus('the notes have not loaded; use Discard to reload them');
|
||||
return;
|
||||
|
|
@ -162,6 +219,7 @@
|
|||
text: request.text,
|
||||
timer: setTimeout(function () {
|
||||
finishSave();
|
||||
hideClosing();
|
||||
setStatus('not saved: no reply; try again');
|
||||
}, REPLY_TIMEOUT),
|
||||
};
|
||||
|
|
@ -225,8 +283,17 @@
|
|||
rev = msg.rev;
|
||||
finishSave();
|
||||
setStatus(editor.value === saved ? 'saved' : 'saved; newer changes are not saved yet');
|
||||
if (closeAfterSave) {
|
||||
if (editor.value === saved) window.close();
|
||||
// Text typed after this save began is saved before closing.
|
||||
else saveButton.click();
|
||||
if (!pending && editor.value !== saved) hideClosing();
|
||||
}
|
||||
} else if (msg.op === 'error') {
|
||||
if (pending && msg.seq === pending.seq) finishSave();
|
||||
if (pending && msg.seq === pending.seq) {
|
||||
finishSave();
|
||||
hideClosing();
|
||||
}
|
||||
if (loading && msg.seq === undefined) finishLoad();
|
||||
setStatus(msg.conflict
|
||||
? 'not saved: changed in another window. Copy your text, then Discard to reload.'
|
||||
|
|
|
|||
|
|
@ -11,3 +11,4 @@ module = "app.wasm"
|
|||
|
||||
[ui]
|
||||
entry = "ui/index.html"
|
||||
close = "ask"
|
||||
|
|
|
|||
|
|
@ -321,7 +321,7 @@
|
|||
if (msg.state === 'stopped') {
|
||||
removeTaskbarEntry(msg.session_id);
|
||||
} else if (msg.state === 'stopping') {
|
||||
markTaskbarEntryClosing(msg.session_id);
|
||||
setTaskbarEntryClosing(msg.session_id);
|
||||
}
|
||||
} else if (msg.type === 'RUNNING_APPS') {
|
||||
msg.sessions.forEach(function (s) {
|
||||
|
|
@ -379,6 +379,11 @@
|
|||
});
|
||||
}
|
||||
|
||||
// Longer than weft-appd's close timeout, so an app that neither closes
|
||||
// nor declines has already been terminated.
|
||||
var FORCE_QUIT_DELAY = 6000;
|
||||
var FORCE_QUIT_OFFER = 20000;
|
||||
|
||||
function ensureTaskbarEntry(sessionId, appId) {
|
||||
var id = 'task-' + sessionId;
|
||||
if (document.getElementById(id)) { return; }
|
||||
|
|
@ -394,17 +399,43 @@
|
|||
close.className = 'task-close';
|
||||
close.textContent = '×';
|
||||
close.title = 'Close';
|
||||
// The first click asks the app to close; it may decline, for example
|
||||
// to offer saving. An app still running once it has had time to
|
||||
// answer can then be force quit, losing what it has not saved.
|
||||
var closeTimer = null;
|
||||
close.addEventListener('click', function (e) {
|
||||
e.stopPropagation();
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'TERMINATE_APP', session_id: sessionId }));
|
||||
}
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) { return; }
|
||||
var force = close.dataset.force === '1';
|
||||
ws.send(JSON.stringify({ type: 'TERMINATE_APP', session_id: sessionId, force: force }));
|
||||
if (force || close.dataset.asked) { return; }
|
||||
close.dataset.asked = '1';
|
||||
closeTimer = setTimeout(function () {
|
||||
if (!document.getElementById(el.id) || el.dataset.closing) { return; }
|
||||
close.dataset.force = '1';
|
||||
close.textContent = 'Force quit';
|
||||
close.title = 'Force quit: changes the app has not saved are lost';
|
||||
close.style.color = '#ff6b6b';
|
||||
// Offered only for a while: an app that declined to let the user
|
||||
// keep working is closed normally next time.
|
||||
closeTimer = setTimeout(resetClose, FORCE_QUIT_OFFER);
|
||||
}, FORCE_QUIT_DELAY);
|
||||
});
|
||||
function resetClose() {
|
||||
clearTimeout(closeTimer);
|
||||
closeTimer = null;
|
||||
delete close.dataset.asked;
|
||||
delete close.dataset.force;
|
||||
close.textContent = '×';
|
||||
close.title = 'Close';
|
||||
close.style.color = '';
|
||||
}
|
||||
el.appendChild(span);
|
||||
el.appendChild(close);
|
||||
// Choosing the entry brings the app's window to the front.
|
||||
el.addEventListener('click', function () {
|
||||
if (el.dataset.closing) { return; }
|
||||
resetClose();
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify({ type: 'ACTIVATE_APP', session_id: sessionId }));
|
||||
}
|
||||
|
|
@ -414,16 +445,15 @@
|
|||
taskbar.insertBefore(el, clock);
|
||||
}
|
||||
|
||||
// The app has been asked to close and may take a few seconds, for
|
||||
// example to save; the entry stays until the session has stopped.
|
||||
function markTaskbarEntryClosing(sessionId) {
|
||||
// The session is ending; its entry stays until it has stopped.
|
||||
function setTaskbarEntryClosing(sessionId) {
|
||||
var el = document.getElementById('task-' + sessionId);
|
||||
if (!el || el.dataset.closing) { return; }
|
||||
el.dataset.closing = '1';
|
||||
el.style.opacity = '0.5';
|
||||
el.title += ' (closing)';
|
||||
var close = el.querySelector('.task-close');
|
||||
if (close) { close.remove(); }
|
||||
if (close) { close.style.display = 'none'; }
|
||||
}
|
||||
|
||||
function removeTaskbarEntry(sessionId) {
|
||||
|
|
|
|||
|
|
@ -19,6 +19,13 @@ sequence, quotes, a tab and non-ASCII characters, launches
|
|||
5. A load that fails (the stored notes are not valid UTF-8) leaves Discard
|
||||
usable: after the file is repaired, Discard loads it and it can be edited
|
||||
and saved again.
|
||||
6. Notes declares the `ask` close policy. With unsaved changes, a close
|
||||
request (TERMINATE_APP or Alt+F4) is declined and a prompt is shown: the
|
||||
session keeps running and Cancel keeps the text; "Save and close" stores
|
||||
the text before the app shell exits cleanly; "Close without saving"
|
||||
leaves the stored notes unchanged. A forced TERMINATE_APP ends a session
|
||||
whose close was declined at once, saving nothing. Without unsaved
|
||||
changes, Notes closes at once.
|
||||
|
||||
Requires Xvfb, xwd, ImageMagick's convert and xdotool.
|
||||
"""
|
||||
|
|
@ -45,6 +52,8 @@ PAGE = (15, 15, 15) # The Notes page's background, #0f0f0f.
|
|||
# The Discard button, right-aligned in the header: its offset from the
|
||||
# window's right edge, and its height on the desktop.
|
||||
DISCARD_FROM_RIGHT, DISCARD_Y = 137, 68
|
||||
# The row through the close prompt's buttons, below the header.
|
||||
PROMPT_Y = DISCARD_Y + 48
|
||||
|
||||
|
||||
def runtime_pid():
|
||||
|
|
@ -66,6 +75,145 @@ def wait_for_file(path, expected, timeout=15):
|
|||
raise AssertionError(f"stored notes {actual!r}, expected {expected!r}")
|
||||
|
||||
|
||||
def prompt_buttons(desktop, page):
|
||||
"""The close prompt's buttons, left to right, as (left, right) columns,
|
||||
or None when the prompt is not shown."""
|
||||
width, _, pixels = parse_ppm(desktop.capture())
|
||||
runs, start = [], None
|
||||
for x in range(page[0], page[2] + 2):
|
||||
i = (PROMPT_Y * width + x) * 3
|
||||
background = x > page[2] or tuple(pixels[i:i + 3]) == PAGE
|
||||
if not background and start is None:
|
||||
start = x
|
||||
elif background and start is not None:
|
||||
runs.append((start, x - 1))
|
||||
start = None
|
||||
buttons = [r for r in runs if r[1] - r[0] >= 40]
|
||||
# Shown, the row holds the prompt's text and its three buttons, with the
|
||||
# page between them; hidden, it crosses the editor from edge to edge.
|
||||
if len(buttons) < 3 or buttons[-1][1] - buttons[0][0] > (page[2] - page[0]) * 0.8:
|
||||
return None
|
||||
return buttons[-3:]
|
||||
|
||||
|
||||
def wait_for_prompt(desktop, page, shown, timeout=10):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
buttons = prompt_buttons(desktop, page)
|
||||
if (buttons is not None) == shown:
|
||||
return buttons
|
||||
time.sleep(0.3)
|
||||
raise AssertionError("the close prompt was " + ("not shown" if shown else "not dismissed"))
|
||||
|
||||
|
||||
def launch(appd):
|
||||
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||
reply = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 120)
|
||||
if reply.get("type") != "APP_READY":
|
||||
raise AssertionError(f"Notes did not start: {reply}")
|
||||
return reply["session_id"]
|
||||
|
||||
|
||||
def wait_for_state(appd, session_id, state, timeout):
|
||||
try:
|
||||
appd.wait_for(lambda m: m.get("type") == "APP_STATE" and m.get("state") == state
|
||||
and m.get("session_id") == session_id, timeout)
|
||||
except TimeoutError:
|
||||
raise AssertionError(f"session {session_id} did not become {state}")
|
||||
|
||||
|
||||
def wait_for_decline(desktop, session_id, timeout=10):
|
||||
marker = f"the application declined the close session_id={session_id}"
|
||||
deadline = time.monotonic() + timeout
|
||||
while marker not in desktop.log_text("appd"):
|
||||
if time.monotonic() > deadline:
|
||||
raise AssertionError(f"session {session_id} did not decline the close")
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def stop_reason(desktop, session_id):
|
||||
marker = f"stopping session session_id={session_id} reason=\""
|
||||
for line in desktop.log_text("appd").splitlines():
|
||||
if marker in line:
|
||||
return line.split(marker, 1)[1].rsplit('"', 1)[0]
|
||||
return None
|
||||
|
||||
|
||||
def check_close_policy(desktop, appd, page, act, notes, session_id):
|
||||
"""Step 6, from a running Notes session whose text is saved."""
|
||||
def click(column):
|
||||
act("mousemove", "--sync", str((column[0] + column[1]) // 2), str(PROMPT_Y))
|
||||
act("click", "1")
|
||||
|
||||
def type_at_end(text):
|
||||
act("mousemove", "--sync", "100", "400")
|
||||
act("click", "1")
|
||||
act("key", "ctrl+End")
|
||||
act("type", "--delay", "40", text)
|
||||
|
||||
stored = notes.read_text(encoding="utf-8")
|
||||
type_at_end(" unsaved")
|
||||
# The page declines the close; the session keeps running.
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||
wait_for_decline(desktop, session_id)
|
||||
buttons = wait_for_prompt(desktop, page, True)
|
||||
click(buttons[2]) # Cancel
|
||||
wait_for_prompt(desktop, page, False)
|
||||
# The compositor's close (Alt+F4) asks the page the same way.
|
||||
act("key", "alt+F4")
|
||||
buttons = wait_for_prompt(desktop, page, True)
|
||||
time.sleep(1)
|
||||
if stop_reason(desktop, session_id) is not None:
|
||||
raise AssertionError("the session stopped although the close was cancelled")
|
||||
click(buttons[0]) # Save and close
|
||||
wait_for_state(appd, session_id, "stopped", 20)
|
||||
if notes.read_text(encoding="utf-8") != stored + " unsaved":
|
||||
raise AssertionError("Save and close did not store the text before closing")
|
||||
reason = stop_reason(desktop, session_id)
|
||||
if reason is None or not reason.startswith("closed on request; app shell exited"):
|
||||
raise AssertionError(f"Notes did not exit cleanly after saving: {reason}")
|
||||
|
||||
# Close without saving keeps the stored notes.
|
||||
session_id = launch(appd)
|
||||
time.sleep(2)
|
||||
act("search", "--class", "weft-compositor", "windowfocus", "--sync")
|
||||
type_at_end(" dropped")
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||
wait_for_decline(desktop, session_id)
|
||||
buttons = wait_for_prompt(desktop, page, True)
|
||||
click(buttons[1]) # Close without saving
|
||||
wait_for_state(appd, session_id, "stopped", 20)
|
||||
if notes.read_text(encoding="utf-8") != stored + " unsaved":
|
||||
raise AssertionError("closing without saving changed the stored notes")
|
||||
|
||||
# A forced stop ends a session that declined its close, without asking.
|
||||
session_id = launch(appd)
|
||||
time.sleep(2)
|
||||
act("search", "--class", "weft-compositor", "windowfocus", "--sync")
|
||||
type_at_end(" forced")
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||
wait_for_decline(desktop, session_id)
|
||||
wait_for_prompt(desktop, page, True)
|
||||
forced = time.monotonic()
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id, "force": True})
|
||||
wait_for_state(appd, session_id, "stopped", 10)
|
||||
if time.monotonic() - forced > 3:
|
||||
raise AssertionError("a forced stop waited for the application")
|
||||
if stop_reason(desktop, session_id) != "terminated by force":
|
||||
raise AssertionError(f"a forced stop reported {stop_reason(desktop, session_id)!r}")
|
||||
if notes.read_text(encoding="utf-8") != stored + " unsaved":
|
||||
raise AssertionError("a forced stop changed the stored notes")
|
||||
|
||||
# Without unsaved changes, a close request closes Notes at once.
|
||||
session_id = launch(appd)
|
||||
time.sleep(2)
|
||||
appd.send({"type": "TERMINATE_APP", "session_id": session_id})
|
||||
wait_for_state(appd, session_id, "stopped", 10)
|
||||
reason = stop_reason(desktop, session_id)
|
||||
if reason is None or not reason.startswith("closed on request; app shell exited"):
|
||||
raise AssertionError(f"Notes without changes did not close on request: {reason}")
|
||||
|
||||
|
||||
def run(args, desktop, home, xdotool):
|
||||
data_home = home / "share"
|
||||
notes = data_home / "weft/app-data" / APP_ID / "notes.txt"
|
||||
|
|
@ -91,10 +239,7 @@ def run(args, desktop, home, xdotool):
|
|||
})
|
||||
port, token = read_endpoint(desktop.runtime, 30)
|
||||
appd = AppdClient(port, token)
|
||||
appd.send({"type": "LAUNCH_APP", "app_id": APP_ID, "surface_id": 0})
|
||||
reply = appd.wait_for(lambda m: m.get("type") in ("APP_READY", "ERROR"), 120)
|
||||
if reply.get("type") != "APP_READY":
|
||||
raise AssertionError(f"Notes did not start: {reply}")
|
||||
session_id = launch(appd)
|
||||
time.sleep(2)
|
||||
width, height, pixels = parse_ppm(desktop.capture())
|
||||
page = bounding_box(width, height, pixels, PAGE)
|
||||
|
|
@ -180,6 +325,8 @@ def run(args, desktop, home, xdotool):
|
|||
if leftovers:
|
||||
raise AssertionError(f"files left beside the notes: {leftovers}")
|
||||
|
||||
check_close_policy(desktop, appd, page, act, notes, session_id)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__,
|
||||
|
|
|
|||
Loading…
Reference in a new issue