mirror of
https://github.com/marcoallegretti/WEFT_OS.git
synced 2026-11-22 08:13:59 +00:00
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.
This commit is contained in:
parent
db042fcb5c
commit
aa67e7f190
14 changed files with 476 additions and 6 deletions
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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) => {
|
||||
|
|
|
|||
|
|
@ -122,10 +122,17 @@ fn handle_pointer_button<B: InputBackend>(
|
|||
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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ mod backend;
|
|||
mod input;
|
||||
mod protocols;
|
||||
mod state;
|
||||
mod windows;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
|
|
|
|||
|
|
@ -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<ZweftShellManagerV1, ()> for WeftCompositorState {
|
|||
),
|
||||
);
|
||||
state.weft_shell_state.add_panel(window);
|
||||
state.fit_panels();
|
||||
} else {
|
||||
window.configure(x, y, width, height, 0);
|
||||
}
|
||||
|
|
|
|||
141
crates/weft-compositor/src/windows.rs
Normal file
141
crates/weft-compositor/src/windows.rs
Normal file
|
|
@ -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::<WeftShellWindowData>()
|
||||
.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<Window> = 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<Window> = 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<u64> {
|
||||
window
|
||||
.toplevel()?
|
||||
.wl_surface()
|
||||
.client()?
|
||||
.get_data::<WeftClientState>()?
|
||||
.session
|
||||
.as_ref()
|
||||
.map(|binding| binding.session_id)
|
||||
}
|
||||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
227
tests/frame/check_activation.py
Executable file
227
tests/frame/check_activation.py
Executable file
|
|
@ -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 = ('<!DOCTYPE html><html><body style="margin:0;background:rgb(0,160,0);'
|
||||
'width:100vw;height:100vh"></body></html>')
|
||||
|
||||
|
||||
def app_page(color, pressed):
|
||||
return ('<!DOCTYPE html><html><body style="margin:0;width:100vw;height:100vh;'
|
||||
f'background:rgb{color}"><script>'
|
||||
'addEventListener("keydown", function () {'
|
||||
f'document.body.style.background = "rgb{pressed}"; }});'
|
||||
'</script></body></html>')
|
||||
|
||||
|
||||
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())
|
||||
Loading…
Reference in a new issue