From aa67e7f19008e2b1147129f5b6b3cee2355fcb57 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 15:36:55 +0000 Subject: [PATCH 1/3] fix(compositor): own stacking and focus, and activate app windows on request The system shell's panel was an ordinary toplevel at winit's default size, stacked by map order with the applications, and clicking or the taskbar could never bring an application back to the front. The compositor now sizes the panel to the output and keeps it beneath every application window. A newly mapped, clicked or activated application window is raised, marked activated and given keyboard focus. weft-appd accepts ACTIVATE_APP for a running session and asks the compositor to activate that session's window (AppFocusRequest), and the system UI's taskbar entries send it when chosen. check_activation.py runs the system shell with a solid panel page and two test applications: the panel fills the output beneath them, each launch comes to the front with keyboard focus, ACTIVATE_APP switches between the sessions with focus, and activating a session that is not running is refused. --- crates/weft-appd/src/ipc.rs | 4 + crates/weft-appd/src/main.rs | 69 ++++++ crates/weft-compositor/src/appd_ipc.rs | 9 +- crates/weft-compositor/src/backend/drm.rs | 2 + crates/weft-compositor/src/backend/winit.rs | 1 + crates/weft-compositor/src/input.rs | 11 +- crates/weft-compositor/src/main.rs | 1 + crates/weft-compositor/src/state.rs | 6 +- crates/weft-compositor/src/windows.rs | 141 ++++++++++++ docs/architecture.md | 2 +- docs/building.md | 1 + docs/security.md | 2 +- infra/shell/system-ui.html | 6 + tests/frame/check_activation.py | 227 ++++++++++++++++++++ 14 files changed, 476 insertions(+), 6 deletions(-) create mode 100644 crates/weft-compositor/src/windows.rs create mode 100755 tests/frame/check_activation.py diff --git a/crates/weft-appd/src/ipc.rs b/crates/weft-appd/src/ipc.rs index 84d7e4d..d7a3d7a 100644 --- a/crates/weft-appd/src/ipc.rs +++ b/crates/weft-appd/src/ipc.rs @@ -11,6 +11,10 @@ pub enum Request { TerminateApp { session_id: u64, }, + /// Brings the session's window to the front with keyboard focus. + ActivateApp { + session_id: u64, + }, QueryRunning, QueryAppState { session_id: u64, diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index 37e706f..dda6435 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -544,6 +544,30 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response { } } } + Request::ActivateApp { session_id } => { + let reg = registry.lock().await; + let state = reg.state(session_id); + if !matches!(state, AppStateKind::Running) { + return Response::Error { + code: 404, + message: format!("session {session_id} is not running"), + }; + } + // The compositor owns stacking and focus; appd asks it to act + // for a session it supervises. + let sent = reg.compositor_tx.as_ref().is_some_and(|tx| { + tx.try_send(weft_ipc_types::AppdToCompositor::AppFocusRequest { session_id }.into()) + .is_ok() + }); + if sent { + Response::AppState { session_id, state } + } else { + Response::Error { + code: 503, + message: "weft-compositor is not connected".to_owned(), + } + } + } Request::QueryRunning => { let sessions = registry.lock().await.running_sessions(); Response::RunningApps { sessions } @@ -1276,6 +1300,51 @@ mod tests { assert!(!session_ipc_socket_path(session_id).unwrap().exists()); } + #[tokio::test(flavor = "current_thread")] + async fn activation_reaches_the_compositor_only_for_running_sessions() { + let registry = make_registry(); + let (tx, mut compositor) = tokio::sync::mpsc::channel(8); + let connected = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true)); + registry.lock().await.compositor_tx = Some(compositor_client::CompositorSender::new( + tx, + connected.clone(), + )); + let session_id = registry.lock().await.launch("org.example.active"); + + // Starting, then not found: refused, nothing sent. + let starting = dispatch(Request::ActivateApp { session_id }, ®istry).await; + let absent = dispatch(Request::ActivateApp { session_id: 999 }, ®istry).await; + for refused in [&starting, &absent] { + assert!( + matches!(refused, Response::Error { code: 404, .. }), + "{refused:?}" + ); + } + assert!(compositor.try_recv().is_err()); + + registry + .lock() + .await + .set_state(session_id, AppStateKind::Running); + let activated = dispatch(Request::ActivateApp { session_id }, ®istry).await; + assert!( + matches!(activated, Response::AppState { session_id: s, state: AppStateKind::Running } if s == session_id), + "{activated:?}" + ); + assert!(matches!( + compositor.try_recv().map(|out| out.msg), + Ok(weft_ipc_types::AppdToCompositor::AppFocusRequest { session_id: s }) if s == session_id + )); + + // Without the compositor connection the request is refused. + drop(compositor); + let unsent = dispatch(Request::ActivateApp { session_id }, ®istry).await; + assert!( + matches!(unsent, Response::Error { code: 503, .. }), + "{unsent:?}" + ); + } + #[tokio::test(flavor = "current_thread")] async fn without_a_connected_compositor_nothing_is_started() { use std::os::unix::fs::PermissionsExt; diff --git a/crates/weft-compositor/src/appd_ipc.rs b/crates/weft-compositor/src/appd_ipc.rs index 95f37dc..715d794 100644 --- a/crates/weft-compositor/src/appd_ipc.rs +++ b/crates/weft-compositor/src/appd_ipc.rs @@ -274,7 +274,14 @@ fn handle_message(state: &mut WeftCompositorState, msg: AppdToCompositor) { } } AppdToCompositor::AppFocusRequest { session_id } => { - tracing::debug!(session_id, "AppFocusRequest"); + if state.activate_session(session_id) { + tracing::info!(session_id, "session activated"); + } else { + tracing::info!( + session_id, + "activation requested for a session with no window" + ); + } } } } diff --git a/crates/weft-compositor/src/backend/drm.rs b/crates/weft-compositor/src/backend/drm.rs index 93bb258..71e93fb 100644 --- a/crates/weft-compositor/src/backend/drm.rs +++ b/crates/weft-compositor/src/backend/drm.rs @@ -550,6 +550,7 @@ fn connector_connected( tracing::info!(?name, "output connected"); let (pw, ph) = (wl_mode.size.w, wl_mode.size.h); state.weft_shell_state.reconfigure_panels(0, 0, pw, ph); + state.fit_panels(); state.weft_shell_state.retain_alive_panels(); render_output(state, node, crtc); } @@ -578,6 +579,7 @@ fn connector_disconnected( .map(|g| (g.size.w, g.size.h)) .unwrap_or((0, 0)); state.weft_shell_state.reconfigure_panels(0, 0, pw, ph); + state.fit_panels(); state.weft_shell_state.retain_alive_panels(); } diff --git a/crates/weft-compositor/src/backend/winit.rs b/crates/weft-compositor/src/backend/winit.rs index 7575211..ede398e 100644 --- a/crates/weft-compositor/src/backend/winit.rs +++ b/crates/weft-compositor/src/backend/winit.rs @@ -124,6 +124,7 @@ pub fn run() -> anyhow::Result<()> { state .weft_shell_state .reconfigure_panels(0, 0, size.w, size.h); + state.fit_panels(); state.weft_shell_state.retain_alive_panels(); } WinitEvent::Input(input_event) => { diff --git a/crates/weft-compositor/src/input.rs b/crates/weft-compositor/src/input.rs index 7f2ac6e..ef7d72d 100644 --- a/crates/weft-compositor/src/input.rs +++ b/crates/weft-compositor/src/input.rs @@ -122,10 +122,17 @@ fn handle_pointer_button( let button = event.button_code(); let button_state = event.state(); - // On press: focus the surface under the pointer. + // On press: activate the window under the pointer, which raises an + // application window and focuses it. if button_state == ButtonState::Pressed { let pointer_location = state.pointer_location; - if let Some((surface, _loc)) = surface_under(state, pointer_location) { + let window = state + .space + .element_under(pointer_location) + .map(|(window, _)| window.clone()); + if let Some(window) = window { + state.activate_window(&window); + } else if let Some((surface, _loc)) = surface_under(state, pointer_location) { if let Some(keyboard) = state.seat.get_keyboard() { keyboard.set_focus(state, Some(surface), serial); } diff --git a/crates/weft-compositor/src/main.rs b/crates/weft-compositor/src/main.rs index 84334c4..850116f 100644 --- a/crates/weft-compositor/src/main.rs +++ b/crates/weft-compositor/src/main.rs @@ -5,6 +5,7 @@ mod backend; mod input; mod protocols; mod state; +mod windows; fn main() -> anyhow::Result<()> { tracing_subscriber::fmt() diff --git a/crates/weft-compositor/src/state.rs b/crates/weft-compositor/src/state.rs index 8c6a303..4308bfa 100644 --- a/crates/weft-compositor/src/state.rs +++ b/crates/weft-compositor/src/state.rs @@ -274,7 +274,10 @@ impl XdgShellHandler for WeftCompositorState { .and_then(|data| data.session.as_ref().map(|s| s.session_id)) }); let window = Window::new_wayland_window(surface); - self.space.map_element(window, (0, 0), false); + self.space.map_element(window.clone(), (0, 0), false); + // A new window comes to the front with focus; the shell's panel is + // recognised when it registers and is then kept beneath. + self.activate_window(&window); if let (Some(session_id), Some(ipc)) = (session, self.appd_ipc.as_mut()) { ipc.surface_created(session_id); } @@ -570,6 +573,7 @@ impl Dispatch for WeftCompositorState { ), ); state.weft_shell_state.add_panel(window); + state.fit_panels(); } else { window.configure(x, y, width, height, 0); } diff --git a/crates/weft-compositor/src/windows.rs b/crates/weft-compositor/src/windows.rs new file mode 100644 index 0000000..f99708d --- /dev/null +++ b/crates/weft-compositor/src/windows.rs @@ -0,0 +1,141 @@ +//! Stacking, focus and activation of toplevel windows. +//! +//! The compositor decides the order: the trusted shell's panel, which +//! fills the output, stays beneath every application window; a newly mapped +//! application window, a clicked one and one appd asks to activate is raised +//! to the top, marked activated and given keyboard focus. + +use smithay::desktop::Window; +use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel; +use smithay::reexports::wayland_server::Resource; +use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface; +use smithay::utils::SERIAL_COUNTER; +use smithay::wayland::seat::WaylandFocus; + +use crate::protocols::WeftShellWindowData; +use crate::state::{WeftClientState, WeftCompositorState}; + +impl WeftCompositorState { + /// Whether `surface` backs a window the trusted shell registered as its + /// panel. + pub fn is_panel_surface(&self, surface: &WlSurface) -> bool { + self.weft_shell_state.panels().any(|panel| { + panel + .data::() + .and_then(|data| data.surface.as_ref()) + .is_some_and(|s| s == surface) + }) + } + + fn is_panel(&self, window: &Window) -> bool { + window + .wl_surface() + .is_some_and(|surface| self.is_panel_surface(&surface)) + } + + /// Raises `window` above the other application windows, marks it + /// activated and gives it keyboard focus. A panel is focused but stays + /// beneath the applications. + pub fn activate_window(&mut self, window: &Window) { + let panel = self.is_panel(window); + if !panel { + self.space.raise_element(window, true); + } + self.send_pending_configures(); + if let (Some(keyboard), Some(surface)) = (self.seat.get_keyboard(), window.wl_surface()) { + keyboard.set_focus( + self, + Some(surface.into_owned()), + SERIAL_COUNTER.next_serial(), + ); + } + } + + /// Activates the topmost window of `session_id`; returns whether the + /// session has one. + pub fn activate_session(&mut self, session_id: u64) -> bool { + let window = self + .space + .elements() + .rev() + .find(|window| window_session(window) == Some(session_id)) + .cloned(); + match window { + Some(window) => { + self.activate_window(&window); + true + } + None => false, + } + } + + /// Sizes the panels to the output, places them at its origin and keeps + /// them beneath every application window. + pub fn fit_panels(&mut self) { + let Some(geometry) = self + .space + .outputs() + .next() + .and_then(|output| self.space.output_geometry(output)) + else { + return; + }; + let panels: Vec = self + .space + .elements() + .filter(|window| self.is_panel(window)) + .cloned() + .collect(); + if panels.is_empty() { + return; + } + for panel in &panels { + if let Some(toplevel) = panel.toplevel() { + toplevel.with_pending_state(|state| { + state.size = Some(geometry.size); + state.states.set(xdg_toplevel::State::Maximized); + }); + toplevel.send_pending_configure(); + tracing::debug!( + width = geometry.size.w, + height = geometry.size.h, + "panel fitted to the output" + ); + } + self.space.map_element(panel.clone(), geometry.loc, false); + } + // Raising every other window, in its current order, leaves the + // panels at the bottom. + let others: Vec = self + .space + .elements() + .filter(|window| !self.is_panel(window)) + .cloned() + .collect(); + for window in &others { + self.space.raise_element(window, false); + } + } + + /// Sends the configure for every toplevel whose pending state changed, + /// such as its activated state. + fn send_pending_configures(&self) { + for window in self.space.elements() { + if let Some(toplevel) = window.toplevel() { + toplevel.send_pending_configure(); + } + } + } +} + +/// The appd session `window`'s client is bound to, if any. +pub fn window_session(window: &Window) -> Option { + window + .toplevel()? + .wl_surface() + .client()? + .get_data::()? + .session + .as_ref() + .map(|binding| binding.session_id) +} diff --git a/docs/architecture.md b/docs/architecture.md index 33f0f8a..0dc33cd 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -8,7 +8,7 @@ WEFT OS is a Wayland compositor and application runtime where every app is a Web ### weft-compositor -Smithay-based Wayland compositor. Implements the `zweft-shell-unstable-v1` protocol extension, which allows shell clients (servo-shell, app-shell) to register their surfaces as typed shell slots. Each application session's Wayland connection is handed to the compositor by weft-appd, which binds the client to that session (see `security.md`). Supports DRM/KMS and winit (software/dev) backends. +Smithay-based Wayland compositor. Implements the `zweft-shell-unstable-v1` protocol extension, which allows shell clients (servo-shell, app-shell) to register their surfaces as typed shell slots. Each application session's Wayland connection is handed to the compositor by weft-appd, which binds the client to that session (see `security.md`). The compositor owns stacking and focus: the system shell's panel is sized to the output and kept beneath application windows; a newly mapped, clicked or activated application window is raised, marked activated and given keyboard focus. weft-appd's `ACTIVATE_APP` request, which the taskbar sends, asks the compositor to activate a running session's window. Supports DRM/KMS and winit (software/dev) backends. ### weft-servo-shell diff --git a/docs/building.md b/docs/building.md index fca337a..fc6fed2 100644 --- a/docs/building.md +++ b/docs/building.md @@ -88,6 +88,7 @@ python3 tests/frame/check_counter.py # Counter round trip through the session python3 tests/frame/check_notes.py # Notes stores exactly what is typed, refuses stale saves 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 # panel beneath two apps; launch and ACTIVATE_APP raise and focus ``` ## Demo apps (wasm32-wasip2) diff --git a/docs/security.md b/docs/security.md index 81fd57e..7002382 100644 --- a/docs/security.md +++ b/docs/security.md @@ -32,7 +32,7 @@ For verified read-only package storage, `weft-pack build-image` produces an EROF Each app shell is given exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error; layer-shell surfaces and the input-method interface are not offered to session clients at all. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd; when appd's connection ends, the compositor closes every session client appd attached. The compositor accepts one appd connection at a time. A launch is refused (503) while appd is not connected to the compositor, rather than starting an app that could never show a window; if the compositor connection is lost before the session's connection is handed over, the session is stopped before the app shell starts. Frames for appd that its socket cannot take at once are queued and retried; a backlog beyond 4 MiB, from an appd that stopped reading, ends the connection and with it the sessions' clients. -Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement, stacking, focus and close are not yet decided by the compositor per session (all toplevels start at the origin); and the trusted system shell is identified only by connecting through the display socket, which any process of the user, including an app shell, can open. +Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement and close are not yet decided by the compositor per session (all toplevels start at the origin, and no work area is reserved for the taskbar); and the trusted system shell is identified only by connecting through the display socket, which any process of the user, including an app shell, can open. ## JavaScript Engine (SpiderMonkey) diff --git a/infra/shell/system-ui.html b/infra/shell/system-ui.html index 9653a41..1b98e2f 100644 --- a/infra/shell/system-ui.html +++ b/infra/shell/system-ui.html @@ -399,6 +399,12 @@ }); el.appendChild(span); el.appendChild(close); + // Choosing the entry brings the app's window to the front. + el.addEventListener('click', function () { + if (ws && ws.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify({ type: 'ACTIVATE_APP', session_id: sessionId })); + } + }); var taskbar = document.querySelector('weft-taskbar'); var clock = document.getElementById('clock'); taskbar.insertBefore(el, clock); diff --git a/tests/frame/check_activation.py b/tests/frame/check_activation.py new file mode 100755 index 0000000..a4bb1e3 --- /dev/null +++ b/tests/frame/check_activation.py @@ -0,0 +1,227 @@ +#!/usr/bin/env python3 +"""Check that the compositor stacks, focuses and activates windows. + +The harness runs weft-servo-shell with a solid green page as the system +panel, and weft-appd with two test applications, one red and one blue, on a +nested desktop (see session.py). Each application page turns a lighter shade +of its colour when it receives a key press. In the presented pixels: + +- the panel fills the compositor output and stays beneath the applications; +- each newly launched application is shown on top and receives keys; +- ACTIVATE_APP, the request the taskbar sends, brings the other session's + window back to the front with keyboard focus; +- ACTIVATE_APP for a session that is not running is refused. + +The applications are unsigned test packages, recorded as development content +in a private data home, using the Counter demo's component. +""" + +import argparse +import shutil +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from check_counter import AppdClient, free_port, read_endpoint # noqa: E402 +from session import ROOT, Desktop, SessionError, bounding_box, missing_tools, parse_ppm # noqa: E402 + +GREEN = (0, 160, 0) +APPS = { + "org.weft.test.red": ((200, 0, 0), (255, 120, 120)), + "org.weft.test.blue": ((0, 0, 200), (120, 120, 255)), +} +STARTUP_TIMEOUT = 120.0 + +PANEL_PAGE = ('') + + +def app_page(color, pressed): + return ('') + + +def make_store(store, home): + for app_id, (color, pressed) in APPS.items(): + package = store / app_id + (package / "ui").mkdir(parents=True) + (package / "wapp.toml").write_text( + f'[package]\nid = "{app_id}"\nname = "Test"\nversion = "0.1.0"\n' + '[runtime]\nmodule = "app.wasm"\n[ui]\nentry = "ui/index.html"\n') + shutil.copy(ROOT / "examples/org.weft.demo.counter/app.wasm", package / "app.wasm") + (package / "ui/index.html").write_text(app_page(color, pressed)) + record = home / "share/weft/owners" / app_id + record.parent.mkdir(parents=True, exist_ok=True) + record.write_text("development\n") + + +def area(screenshot, color): + width, height, pixels = parse_ppm(screenshot) + box = bounding_box(width, height, pixels, color) + return box, width, height + + +def wait_for_color(desktop, color, timeout=20): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + shot = desktop.capture() + box, _, _ = area(shot, color) + if box is not None: + return shot, box + time.sleep(0.3) + return desktop.capture(), None + + +def wait_until_gone(desktop, color, timeout=10): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + box, _, _ = area(desktop.capture(), color) + if box is None: + return True + time.sleep(0.3) + return False + + +def run(args, desktop, store, home): + panel_page = desktop.runtime / "panel.html" + panel_page.write_text(PANEL_PAGE) + desktop.launch_client("shell", [args.shell], {"WEFT_SYSTEM_UI_HTML": str(panel_page)}) + shot, panel = wait_for_color(desktop, GREEN, 60) + if panel is None: + raise AssertionError("the panel was not shown") + width, height, _ = parse_ppm(shot) + # The compositor sizes the panel to its whole output, which reaches the + # right and bottom edges of the nested desktop. + if panel[2] != width - 1 or panel[3] < height - 3: + raise AssertionError(f"the panel does not fill the output: {panel}") + + t = Path(args.target) + desktop.launch_client("appd", [t / "weft-appd"], { + "WEFT_RUNTIME_BIN": str(t / "weft-runtime"), + "WEFT_APP_SHELL_BIN": str(t / "weft-app-shell"), + "WEFT_APP_STORE": str(store), + "WEFT_DISABLE_CGROUP": "1", + "WEFT_APPD_WS_PORT": str(free_port()), + "HOME": str(home), + "XDG_DATA_HOME": str(home / "share"), + }) + port, token = read_endpoint(desktop.runtime, 30) + appd = AppdClient(port, token) + + def key(name): + subprocess.run([args.xdotool, "search", "--class", "weft-compositor", + "windowfocus", "--sync"], env={"DISPLAY": desktop.display}, + check=True, timeout=20) + subprocess.run([args.xdotool, "key", name], env={"DISPLAY": desktop.display}, + check=True, timeout=20) + + def shown(app_id, pressed=False): + """Waits until `app_id` is the visible application, alone on top.""" + color = APPS[app_id][1 if pressed else 0] + others = [c for other, cs in APPS.items() for c in cs if other != app_id] + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + shot = desktop.capture() + box, _, _ = area(shot, color) + hidden = all(area(shot, c)[0] is None for c in others) + if box is not None and hidden: + # The panel stays visible beside the application window. + if area(shot, GREEN)[0] is None: + raise AssertionError("an application covered the panel") + return + time.sleep(0.3) + state = "pressed " if pressed else "" + raise AssertionError(f"{app_id} is not shown {state}on top") + + sessions = {} + for app_id in APPS: + appd.send({"type": "LAUNCH_APP", "app_id": app_id, "surface_id": 0}) + try: + ready = appd.wait_for( + lambda m, a=app_id: m.get("type") == "APP_READY" and m.get("app_id") == a, + STARTUP_TIMEOUT) + except TimeoutError: + raise AssertionError(f"{app_id} did not start") + sessions[app_id] = ready["session_id"] + # A newly launched application comes to the front. + shown(app_id) + + red, blue = "org.weft.test.red", "org.weft.test.blue" + # The last launched application has keyboard focus. + key("a") + shown(blue, pressed=True) + + def activate(app_id): + appd.send({"type": "ACTIVATE_APP", "session_id": sessions[app_id]}) + reply = appd.wait_for(lambda m: m.get("type") in ("APP_STATE", "ERROR") + and m.get("session_id", sessions[app_id]) == sessions[app_id], + 10) + if reply.get("type") != "APP_STATE": + raise AssertionError(f"activating {app_id} was refused: {reply}") + + # Activation brings the other session back with keyboard focus. + activate(red) + shown(red) + key("a") + shown(red, pressed=True) + activate(blue) + shown(blue, pressed=True) + + appd.send({"type": "ACTIVATE_APP", "session_id": 999}) + reply = appd.wait_for(lambda m: m.get("type") == "ERROR", 10) + if reply.get("code") != 404: + raise AssertionError(f"activating a session that does not run: {reply}") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--compositor", type=Path, default=ROOT / "target/debug/weft-compositor") + parser.add_argument("--shell", type=Path, default=ROOT / "target/debug/weft-servo-shell") + parser.add_argument("--target", type=Path, default=ROOT / "target/debug", + help="directory with weft-appd, weft-runtime and weft-app-shell") + parser.add_argument("--output", type=Path, default=ROOT / "target/activation-check") + parser.add_argument("--xdotool", default=shutil.which("xdotool")) + args = parser.parse_args(argv) + if not args.xdotool: + print("missing: xdotool", file=sys.stderr) + return 2 + + missing = missing_tools() + [str(p) for p in (args.compositor, args.shell, + args.target / "weft-appd", + args.target / "weft-runtime", + args.target / "weft-app-shell") + if not p.is_file()] + if missing: + print("missing: " + ", ".join(missing), file=sys.stderr) + return 2 + store = Path(tempfile.mkdtemp(prefix="weft-store-")) + home = Path(tempfile.mkdtemp(prefix="weft-home-")) + try: + make_store(store, home) + with Desktop(args.compositor, args.output, outputs=["appd.log", "activation.ppm"]) \ + as desktop: + try: + run(args, desktop, store, home) + except AssertionError: + (args.output / "activation.ppm").write_bytes(desktop.capture()) + raise + except (AssertionError, SessionError, TimeoutError) as failure: + print(f"activation check failed: {failure}", file=sys.stderr) + print(f"logs and capture in {args.output}", file=sys.stderr) + return 1 + finally: + shutil.rmtree(store, ignore_errors=True) + shutil.rmtree(home, ignore_errors=True) + print("activation check passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 65c02231a0e384b491d755adb4427fcb1a009241 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 15:42:42 +0000 Subject: [PATCH 2/3] fix(compositor): restore focus when a window closes and keep later windows from taking it When the focused window closed, keys went to a dead surface until the next click; the topmost remaining application window, or the panel, now gets focus. Only a session's first window takes focus when it maps, so a client cannot take keystrokes meant for another application by creating windows. A panel is fitted and kept beneath however the shell orders its requests, and focusing the panel clears the applications' activated state. ACTIVATE_APP is refused while the compositor is not connected rather than queued. check_activation.py now also ends the focused application and checks that keys reach the remaining one. --- crates/weft-appd/src/main.rs | 10 ++-- crates/weft-compositor/src/state.rs | 9 ++-- crates/weft-compositor/src/windows.rs | 72 +++++++++++++++++++++++++-- docs/architecture.md | 2 +- docs/security.md | 2 +- tests/frame/check_activation.py | 16 ++++-- 6 files changed, 93 insertions(+), 18 deletions(-) diff --git a/crates/weft-appd/src/main.rs b/crates/weft-appd/src/main.rs index dda6435..2bf1e61 100644 --- a/crates/weft-appd/src/main.rs +++ b/crates/weft-appd/src/main.rs @@ -556,8 +556,12 @@ pub(crate) async fn dispatch(req: Request, registry: &Registry) -> Response { // The compositor owns stacking and focus; appd asks it to act // for a session it supervises. let sent = reg.compositor_tx.as_ref().is_some_and(|tx| { - tx.try_send(weft_ipc_types::AppdToCompositor::AppFocusRequest { session_id }.into()) - .is_ok() + tx.is_connected() + && tx + .try_send( + weft_ipc_types::AppdToCompositor::AppFocusRequest { session_id }.into(), + ) + .is_ok() }); if sent { Response::AppState { session_id, state } @@ -1337,7 +1341,7 @@ mod tests { )); // Without the compositor connection the request is refused. - drop(compositor); + connected.store(false, std::sync::atomic::Ordering::Release); let unsent = dispatch(Request::ActivateApp { session_id }, ®istry).await; assert!( matches!(unsent, Response::Error { code: 503, .. }), diff --git a/crates/weft-compositor/src/state.rs b/crates/weft-compositor/src/state.rs index 4308bfa..f612358 100644 --- a/crates/weft-compositor/src/state.rs +++ b/crates/weft-compositor/src/state.rs @@ -266,6 +266,10 @@ impl XdgShellHandler for WeftCompositorState { &mut self.xdg_shell_state } + fn toplevel_destroyed(&mut self, surface: ToplevelSurface) { + self.window_closed(surface.wl_surface()); + } + fn new_toplevel(&mut self, surface: ToplevelSurface) { surface.send_configure(); let session = surface.wl_surface().client().and_then(|client| { @@ -274,10 +278,7 @@ impl XdgShellHandler for WeftCompositorState { .and_then(|data| data.session.as_ref().map(|s| s.session_id)) }); let window = Window::new_wayland_window(surface); - self.space.map_element(window.clone(), (0, 0), false); - // A new window comes to the front with focus; the shell's panel is - // recognised when it registers and is then kept beneath. - self.activate_window(&window); + self.map_new_window(window); if let (Some(session_id), Some(ipc)) = (session, self.appd_ipc.as_mut()) { ipc.surface_created(session_id); } diff --git a/crates/weft-compositor/src/windows.rs b/crates/weft-compositor/src/windows.rs index f99708d..860a291 100644 --- a/crates/weft-compositor/src/windows.rs +++ b/crates/weft-compositor/src/windows.rs @@ -1,9 +1,10 @@ //! Stacking, focus and activation of toplevel windows. //! //! The compositor decides the order: the trusted shell's panel, which -//! fills the output, stays beneath every application window; a newly mapped -//! application window, a clicked one and one appd asks to activate is raised -//! to the top, marked activated and given keyboard focus. +//! fills the output, stays beneath every application window; a session's +//! first window, a clicked window and one appd asks to activate is raised to +//! the top, marked activated and given keyboard focus. When the focused +//! window closes, the topmost remaining application window gets focus. use smithay::desktop::Window; use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel; @@ -37,8 +38,13 @@ impl WeftCompositorState { /// activated and gives it keyboard focus. A panel is focused but stays /// beneath the applications. pub fn activate_window(&mut self, window: &Window) { - let panel = self.is_panel(window); - if !panel { + if self.is_panel(window) { + // The panel takes focus without rising; no application window + // stays marked activated. + for other in self.space.elements() { + other.set_activated(false); + } + } else { self.space.raise_element(window, true); } self.send_pending_configures(); @@ -117,6 +123,62 @@ impl WeftCompositorState { } } + /// Maps a new toplevel. A session's first window comes to the front with + /// keyboard focus; its later windows, and windows of clients outside + /// any session after the first, are shown without taking focus, so a + /// client cannot take keystrokes meant for another application by + /// creating windows. A panel is fitted and kept beneath. + pub fn map_new_window(&mut self, window: Window) { + let session = window_session(&window); + let first = !self + .space + .elements() + .any(|other| window_session(other) == session); + self.space.map_element(window.clone(), (0, 0), false); + if self.is_panel(&window) { + self.fit_panels(); + } else if first { + self.activate_window(&window); + } + } + + /// Unmaps a closed toplevel and, if it had keyboard focus, gives focus + /// to the topmost remaining application window, or the panel. + pub fn window_closed(&mut self, surface: &WlSurface) { + let Some(window) = self + .space + .elements() + .find(|window| window.wl_surface().is_some_and(|s| *s == *surface)) + .cloned() + else { + return; + }; + self.space.unmap_elem(&window); + let had_focus = self + .seat + .get_keyboard() + .and_then(|keyboard| keyboard.current_focus()) + .is_none_or(|focus| focus == *surface); + if !had_focus { + return; + } + let next = self + .space + .elements() + .rev() + .find(|window| !self.is_panel(window)) + .or_else(|| self.space.elements().next()) + .cloned(); + match next { + Some(next) => self.activate_window(&next), + None => { + if let Some(keyboard) = self.seat.get_keyboard() { + keyboard.set_focus(self, None, SERIAL_COUNTER.next_serial()); + } + } + } + } + /// Sends the configure for every toplevel whose pending state changed, /// such as its activated state. fn send_pending_configures(&self) { diff --git a/docs/architecture.md b/docs/architecture.md index 0dc33cd..dd74a4d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -8,7 +8,7 @@ WEFT OS is a Wayland compositor and application runtime where every app is a Web ### weft-compositor -Smithay-based Wayland compositor. Implements the `zweft-shell-unstable-v1` protocol extension, which allows shell clients (servo-shell, app-shell) to register their surfaces as typed shell slots. Each application session's Wayland connection is handed to the compositor by weft-appd, which binds the client to that session (see `security.md`). The compositor owns stacking and focus: the system shell's panel is sized to the output and kept beneath application windows; a newly mapped, clicked or activated application window is raised, marked activated and given keyboard focus. weft-appd's `ACTIVATE_APP` request, which the taskbar sends, asks the compositor to activate a running session's window. Supports DRM/KMS and winit (software/dev) backends. +Smithay-based Wayland compositor. Implements the `zweft-shell-unstable-v1` protocol extension, which allows shell clients (servo-shell, app-shell) to register their surfaces as typed shell slots. Each application session's Wayland connection is handed to the compositor by weft-appd, which binds the client to that session (see `security.md`). The compositor owns stacking and focus: the system shell's panel is sized to the output and kept beneath application windows; a session's first window, a clicked window and an activated one are raised, marked activated and given keyboard focus, and when the focused window closes the topmost remaining application window gets focus. A session's later windows are shown without taking focus. weft-appd's `ACTIVATE_APP` request, which the taskbar sends, asks the compositor to activate a running session's window. Supports DRM/KMS and winit (software/dev) backends. ### weft-servo-shell diff --git a/docs/security.md b/docs/security.md index 7002382..0d5bcc1 100644 --- a/docs/security.md +++ b/docs/security.md @@ -32,7 +32,7 @@ For verified read-only package storage, `weft-pack build-image` produces an EROF Each app shell is given exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error; layer-shell surfaces and the input-method interface are not offered to session clients at all. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd; when appd's connection ends, the compositor closes every session client appd attached. The compositor accepts one appd connection at a time. A launch is refused (503) while appd is not connected to the compositor, rather than starting an app that could never show a window; if the compositor connection is lost before the session's connection is handed over, the session is stopped before the app shell starts. Frames for appd that its socket cannot take at once are queued and retried; a backlog beyond 4 MiB, from an appd that stopped reading, ends the connection and with it the sessions' clients. -Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement and close are not yet decided by the compositor per session (all toplevels start at the origin, and no work area is reserved for the taskbar); and the trusted system shell is identified only by connecting through the display socket, which any process of the user, including an app shell, can open. +Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement and close are not yet decided by the compositor per session (all toplevels start at the origin, and no work area is reserved for the taskbar, so an application window as large as the output hides it); a session's first window takes keyboard focus when it maps, later ones do not; and the trusted system shell is identified only by connecting through the display socket, which any process of the user, including an app shell, can open. ## JavaScript Engine (SpiderMonkey) diff --git a/tests/frame/check_activation.py b/tests/frame/check_activation.py index a4bb1e3..3d46ee4 100755 --- a/tests/frame/check_activation.py +++ b/tests/frame/check_activation.py @@ -3,13 +3,14 @@ The harness runs weft-servo-shell with a solid green page as the system panel, and weft-appd with two test applications, one red and one blue, on a -nested desktop (see session.py). Each application page turns a lighter shade -of its colour when it receives a key press. In the presented pixels: +nested desktop (see session.py). Each application page switches between its +colour and a lighter shade on every key press. In the presented pixels: - the panel fills the compositor output and stays beneath the applications; - each newly launched application is shown on top and receives keys; - ACTIVATE_APP, the request the taskbar sends, brings the other session's window back to the front with keyboard focus; +- when the focused application ends, the remaining one gets keyboard focus; - ACTIVATE_APP for a session that is not running is refused. The applications are unsigned test packages, recorded as development content @@ -42,8 +43,9 @@ PANEL_PAGE = ('') @@ -173,6 +175,12 @@ def run(args, desktop, store, home): activate(blue) shown(blue, pressed=True) + # When the focused application ends, keyboard focus returns to the other. + appd.send({"type": "TERMINATE_APP", "session_id": sessions[blue]}) + shown(red, pressed=True) + key("a") + shown(red) + appd.send({"type": "ACTIVATE_APP", "session_id": 999}) reply = appd.wait_for(lambda m: m.get("type") == "ERROR", 10) if reply.get("code") != 404: From 16af8d2a8c03cd3ce4f04f7f453cae297dc6f232 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 15:45:52 +0000 Subject: [PATCH 3/3] fix(compositor): give a session focus on map only once in its lifetime Unmapping a closed window made a session with no mapped window count as new again, so destroying and recreating its only window took keyboard focus from the application the user had activated. The compositor now remembers which sessions already received focus on map until the session ends. --- crates/weft-compositor/src/appd_ipc.rs | 13 +++++++++++++ crates/weft-compositor/src/windows.rs | 26 +++++++++++++++++--------- docs/security.md | 2 +- 3 files changed, 31 insertions(+), 10 deletions(-) diff --git a/crates/weft-compositor/src/appd_ipc.rs b/crates/weft-compositor/src/appd_ipc.rs index 715d794..f6e85ab 100644 --- a/crates/weft-compositor/src/appd_ipc.rs +++ b/crates/weft-compositor/src/appd_ipc.rs @@ -46,6 +46,9 @@ pub struct WeftAppdIpc { sessions: HashMap, /// Sessions whose first toplevel was reported to appd. reported: HashSet, + /// Sessions that already received keyboard focus for a mapped window; + /// kept until the session ends, so recreating a window gains nothing. + focused_on_map: HashSet, /// Where clients report their session's disconnection. disconnected: Option>, /// Bytes for appd that did not fit in the socket buffer, sent before @@ -67,6 +70,7 @@ impl WeftAppdIpc { fds: VecDeque::new(), sessions: HashMap::new(), reported: HashSet::new(), + focused_on_map: HashSet::new(), disconnected: None, out_buf: Vec::new(), flush_retry: None, @@ -150,6 +154,12 @@ impl WeftAppdIpc { .ok(); } + /// Whether a window `session_id` maps now may take keyboard focus: only + /// the first one in the session's lifetime. + pub fn take_focus_on_map(&mut self, session_id: u64) -> bool { + self.sessions.contains_key(&session_id) && self.focused_on_map.insert(session_id) + } + /// Reports a session's first toplevel to appd. pub fn surface_created(&mut self, session_id: u64) { if self.sessions.contains_key(&session_id) && self.reported.insert(session_id) { @@ -250,6 +260,7 @@ impl WeftAppdIpc { self.read_buf.clear(); self.fds.clear(); self.reported.clear(); + self.focused_on_map.clear(); self.sessions.drain().map(|(_, client)| client).collect() } } @@ -265,6 +276,7 @@ fn handle_message(state: &mut WeftCompositorState, msg: AppdToCompositor) { return; }; ipc.reported.remove(&session_id); + ipc.focused_on_map.remove(&session_id); if let Some(client) = ipc.sessions.remove(&session_id) { tracing::info!(session_id, "closing the client of an ended session"); state @@ -389,6 +401,7 @@ pub fn setup(state: &mut WeftCompositorState) -> anyhow::Result<()> { { ipc.sessions.remove(&session_id); ipc.reported.remove(&session_id); + ipc.focused_on_map.remove(&session_id); tracing::info!(session_id, "session client disconnected"); ipc.send(&CompositorToAppd::ClientDisconnected { session_id }); } diff --git a/crates/weft-compositor/src/windows.rs b/crates/weft-compositor/src/windows.rs index 860a291..df39eb4 100644 --- a/crates/weft-compositor/src/windows.rs +++ b/crates/weft-compositor/src/windows.rs @@ -123,17 +123,25 @@ impl WeftCompositorState { } } - /// Maps a new toplevel. A session's first window comes to the front with - /// keyboard focus; its later windows, and windows of clients outside - /// any session after the first, are shown without taking focus, so a - /// client cannot take keystrokes meant for another application by - /// creating windows. A panel is fitted and kept beneath. + /// Maps a new toplevel. The first window a session maps in its lifetime + /// comes to the front with keyboard focus; its later windows, including + /// recreated ones, are shown without taking focus, so a session cannot + /// take keystrokes meant for another application by creating windows. + /// A client outside any session (one connected through the display + /// socket) takes focus only while no other such window is mapped. A + /// panel is fitted and kept beneath. pub fn map_new_window(&mut self, window: Window) { let session = window_session(&window); - let first = !self - .space - .elements() - .any(|other| window_session(other) == session); + let first = match session { + Some(session_id) => self + .appd_ipc + .as_mut() + .is_some_and(|ipc| ipc.take_focus_on_map(session_id)), + None => !self + .space + .elements() + .any(|other| window_session(other).is_none()), + }; self.space.map_element(window.clone(), (0, 0), false); if self.is_panel(&window) { self.fit_panels(); diff --git a/docs/security.md b/docs/security.md index 0d5bcc1..b18519a 100644 --- a/docs/security.md +++ b/docs/security.md @@ -32,7 +32,7 @@ For verified read-only package storage, `weft-pack build-image` produces an EROF Each app shell is given exactly one Wayland connection, created for its session. weft-appd creates a connected socket pair, gives one end to the app shell as its standard input with `WAYLAND_SOCKET=0` and no `WAYLAND_DISPLAY`, and sends the other end to the compositor over the compositor IPC socket (`SCM_RIGHTS`) with the session ID and app ID. The compositor adds that end as a client bound to the session; the binding comes from appd holding the connection, never from an ID or process ID the client supplies. A session's `zweft_shell` windows carry the session's app ID whatever the client requests, and the shell-only `panel` and `overlay` roles are refused with a protocol error; layer-shell surfaces and the input-method interface are not offered to session clients at all. When the session ends, the compositor closes its client; when the client disconnects, the compositor reports it to appd; when appd's connection ends, the compositor closes every session client appd attached. The compositor accepts one appd connection at a time. A launch is refused (503) while appd is not connected to the compositor, rather than starting an app that could never show a window; if the compositor connection is lost before the session's connection is handed over, the session is stopped before the app shell starts. Frames for appd that its socket cannot take at once are queued and retried; a backlog beyond 4 MiB, from an appd that stopped reading, ends the connection and with it the sessions' clients. -Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement and close are not yet decided by the compositor per session (all toplevels start at the origin, and no work area is reserved for the taskbar, so an application window as large as the output hides it); a session's first window takes keyboard focus when it maps, later ones do not; and the trusted system shell is identified only by connecting through the display socket, which any process of the user, including an app shell, can open. +Not yet covered: the compositor IPC socket accepts any process of the user while no appd is connected, so the first connection after a restart is trusted as appd; window placement and close are not yet decided by the compositor per session (all toplevels start at the origin, and no work area is reserved for the taskbar, so an application window as large as the output hides it); only the first window a session maps in its lifetime takes keyboard focus when it maps, and a client connected through the display socket takes focus on map only while no other such window is mapped; and the trusted system shell is identified only by connecting through the display socket, which any process of the user, including an app shell, can open. ## JavaScript Engine (SpiderMonkey)