fix(shells): paint and present Servo frames and report readiness truthfully

With servo-embed, weft-servo-shell and weft-app-shell did not compile
against the selected Servo revision: the keyboard event shape, key and
mouse action variants, frame readback, shutdown, URL type and window
handle APIs had changed. The frame path never called WebView::paint; the
software path rebuilt its softbuffer surface every frame and read pixels
without painting, and the EGL path presented nothing. weft-app-shell
printed READY right after creating its WebView, before any frame, and its
feature-disabled build printed READY and parked. Servo also disables CSS
Grid by default, which the system UI uses.

Both hosts now build against the selected API. Each frame is painted with
WebView::paint and presented: the software path reads the painted frame
back, presents the context and copies it into a persistent softbuffer
surface; the EGL path presents its window context. Nothing is presented
before Servo's first repaint request. Shutdown drops the WebView and
Servo, whose drop completes the shutdown, and exits the event loop. Both
hosts enable layout_grid_enabled.

weft-app-shell prints READY on the first frame presented after the
document has loaded and Servo reports its rendering settled: on load
completion it requests WebView::take_screenshot, which completes only once
every frame has fired load, render-blocking resources, images and web
fonts are done and the rendering is up to date. Feature-disabled builds of
both hosts exit with an error instead of reporting readiness. weft-appd
does not consume the app shell's READY yet.

tests/frame/check_frame.py runs weft-compositor nested on Xvfb with the
winit backend, starts a host showing tests/frame/reference.html and checks
the presented pixels (four colour quadrants and text). For the app host
the page must be on screen within two seconds of READY; --slow-style
delays a render-blocking stylesheet that reveals the page, so premature
readiness fails.

Validation (Ubuntu 24.04, Mesa 25.2.8 llvmpipe, software path):
- check_frame.py --host system, --host app and --host app --slow-style 3:
  5 of 5 runs pass each
- negative fixtures fail: page with red and green swapped; a fake host
  printing READY without rendering; a local build printing READY on its
  first presented frame (--slow-style 4, 3 of 3)
- cargo clippy -D warnings with and without servo-embed; cargo fmt --check
- unverified: EGL path, DRM, resize, output scale, idle wakeup, input
This commit is contained in:
Marco Allegretti 2026-10-09 01:02:26 +00:00
parent 93b67834a7
commit 64f8cff6fd
No known key found for this signature in database
12 changed files with 840 additions and 254 deletions

View file

@ -6,7 +6,7 @@ WEFT OS is a Wayland compositor and application runtime where every app is a Web
**Compositor** — `weft-compositor` is a Smithay-based Wayland compositor with DRM/KMS and winit backends. It implements the `zweft-shell-unstable-v1` protocol extension, which typed shell slots (panel, application) register against.
**System shell** — `weft-servo-shell` embeds Servo (feature-gated, `--features servo-embed`) and renders `system-ui.html` as a Wayland panel. Without `servo-embed`, the binary builds as a no-op stub. Navigation gestures from the compositor are forwarded to `weft-appd` over WebSocket.
**System shell** — `weft-servo-shell` embeds Servo (feature-gated, `--features servo-embed`) and renders `system-ui.html` as a Wayland panel. Without `servo-embed`, the binary exits with an error instead of rendering. Navigation gestures from the compositor are forwarded to `weft-appd` over WebSocket.
**App shell** — `weft-app-shell` is a per-process Servo host for application WebViews. It resolves `weft-app://<id>/ui/index.html`, injects a `weftIpc` WebSocket bridge into the page, and registers with the compositor as an application surface. Also feature-gated behind `servo-embed`.

View file

@ -1,20 +1,22 @@
#![cfg(feature = "servo-embed")]
use std::num::NonZeroU32;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use servo::{
EventLoopWaker, InputEvent, MouseButton as ServoMouseButton, MouseButtonAction,
MouseButtonEvent, MouseMoveEvent, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager,
DeviceIntRect, DeviceIntSize, DevicePoint, EventLoopWaker, InputEvent, LoadStatus,
MouseButton as ServoMouseButton, MouseButtonAction, MouseButtonEvent, MouseMoveEvent,
RenderingContext, RgbaImage, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager,
UserScript, WebViewBuilder, WebViewDelegate,
};
use winit::{
application::ApplicationHandler,
dpi::PhysicalSize,
event::{ElementState, MouseButton, WindowEvent},
event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
keyboard::ModifiersState,
platform::wayland::{ActiveEventLoopExtWayland, WindowExtWayland},
raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle},
window::{Window, WindowAttributes, WindowId},
};
@ -48,29 +50,133 @@ impl ServoDelegate for WeftServoDelegate {
}
}
/// Frame and load progress reported by Servo, shared with the event loop.
#[derive(Default)]
struct FrameSignals {
/// A new frame is waiting to be painted.
redraw: AtomicBool,
/// Servo has requested at least one repaint.
content: AtomicBool,
/// The document has loaded and Servo reports its rendering is up to date.
settled: AtomicBool,
}
struct WeftWebViewDelegate {
redraw_requested: Arc<std::sync::atomic::AtomicBool>,
signals: Arc<FrameSignals>,
}
impl WebViewDelegate for WeftWebViewDelegate {
fn notify_new_frame_ready(&self, _webview: servo::WebView) {
self.redraw_requested
.store(true, std::sync::atomic::Ordering::Relaxed);
self.signals.content.store(true, Ordering::Relaxed);
self.signals.redraw.store(true, Ordering::Relaxed);
}
fn notify_load_status_changed(&self, webview: servo::WebView, status: LoadStatus) {
if status != LoadStatus::Complete {
return;
}
// Servo completes a screenshot request only once every frame has fired
// `load`, render-blocking resources, images and web fonts are done and
// the rendering is up to date, which is the readiness this host reports.
let signals = Arc::clone(&self.signals);
webview.take_screenshot(None, move |result| match result {
Ok(_) => {
signals.settled.store(true, Ordering::Relaxed);
signals.redraw.store(true, Ordering::Relaxed);
}
Err(e) => tracing::error!(?e, "document rendering did not settle; not ready"),
});
}
}
/// Servo preferences shared by the WEFT hosts.
fn host_preferences() -> servo::Preferences {
servo::Preferences {
// The system UI and application pages lay out with CSS Grid, which
// Servo disables by default.
layout_grid_enabled: true,
..Default::default()
}
}
// ── Rendering ───────────────────────────────────────────────────────────────
type BlitSurface = softbuffer::Surface<Arc<Window>, Arc<Window>>;
enum RenderingCtx {
Software(Rc<servo::SoftwareRenderingContext>),
/// Servo renders offscreen; each frame is read back and copied to the window.
Software {
context: Rc<servo::SoftwareRenderingContext>,
surface: BlitSurface,
},
/// Servo renders directly to the window's EGL surface.
Egl(Rc<servo::WindowRenderingContext>),
}
impl RenderingCtx {
fn as_dyn(&self) -> Rc<dyn servo::RenderingContext> {
fn as_dyn(&self) -> Rc<dyn RenderingContext> {
match self {
Self::Software(rc) => Rc::clone(rc) as Rc<dyn servo::RenderingContext>,
Self::Egl(rc) => Rc::clone(rc) as Rc<dyn servo::RenderingContext>,
Self::Software { context, .. } => Rc::clone(context) as Rc<dyn RenderingContext>,
Self::Egl(context) => Rc::clone(context) as Rc<dyn RenderingContext>,
}
}
/// Paints the webview into this context and presents the frame on the window.
fn paint_and_present(&mut self, webview: &servo::WebView) -> Result<(), String> {
match self {
Self::Software { context, surface } => {
context
.make_current()
.map_err(|e| format!("make_current: {e:?}"))?;
webview.paint();
let size = context.size();
let rect = DeviceIntRect::from_size(DeviceIntSize::new(
size.width as i32,
size.height as i32,
));
let image = context.read_to_image(rect);
context.present();
let image = image.ok_or("frame readback failed")?;
blit(surface, &image)
}
Self::Egl(context) => {
context
.make_current()
.map_err(|e| format!("make_current: {e:?}"))?;
webview.paint();
context.present();
Ok(())
}
}
}
}
/// Copies an RGBA frame into the window's software surface and presents it.
fn blit(surface: &mut BlitSurface, image: &RgbaImage) -> Result<(), String> {
let (width, height) = image.dimensions();
let (Some(w), Some(h)) = (NonZeroU32::new(width), NonZeroU32::new(height)) else {
return Ok(());
};
surface.resize(w, h).map_err(|e| format!("resize: {e}"))?;
let mut buffer = surface.buffer_mut().map_err(|e| format!("buffer: {e}"))?;
for (dst, src) in buffer.iter_mut().zip(image.as_raw().chunks_exact(4)) {
*dst = u32::from(src[0]) << 16 | u32::from(src[1]) << 8 | u32::from(src[2]);
}
buffer.present().map_err(|e| format!("present: {e}"))
}
/// Returns winit's `wl_display` and `wl_surface` pointers when running on Wayland.
fn wayland_handles(
event_loop: &ActiveEventLoop,
window: &Window,
) -> Option<(*mut std::ffi::c_void, *mut std::ffi::c_void)> {
let RawDisplayHandle::Wayland(display) = event_loop.display_handle().ok()?.as_raw() else {
return None;
};
let RawWindowHandle::Wayland(surface) = window.window_handle().ok()?.as_raw() else {
return None;
};
Some((display.display.as_ptr(), surface.surface.as_ptr()))
}
struct App {
@ -82,12 +188,12 @@ struct App {
servo: Option<servo::Servo>,
webview: Option<servo::WebView>,
rendering_context: Option<RenderingCtx>,
redraw_requested: Arc<std::sync::atomic::AtomicBool>,
signals: Arc<FrameSignals>,
waker: WeftEventLoopWaker,
shutting_down: bool,
ready_signalled: bool,
modifiers: ModifiersState,
cursor_pos: servo::euclid::default::Point2D<f32>,
cursor_pos: DevicePoint,
shell_client: Option<crate::shell_client::ShellClient>,
}
@ -108,47 +214,46 @@ impl App {
servo: None,
webview: None,
rendering_context: None,
redraw_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)),
signals: Arc::default(),
waker,
shutting_down: false,
ready_signalled: false,
modifiers: ModifiersState::default(),
cursor_pos: servo::euclid::default::Point2D::zero(),
cursor_pos: DevicePoint::origin(),
shell_client: None,
}
}
fn render_frame(window: &Arc<Window>, ctx: &RenderingCtx) {
match ctx {
RenderingCtx::Software(rc) => Self::blit_software(window, rc),
RenderingCtx::Egl(_) => {}
/// Paints and presents once Servo has requested its first repaint.
///
/// Nothing is presented before that request; the first frames can still be
/// blank or unstyled while the document loads. READY is printed after a
/// frame is presented once the document has loaded and its rendering has
/// settled.
fn render_frame(&mut self) {
if !self.signals.content.load(Ordering::Relaxed) {
return;
}
let (Some(webview), Some(context)) = (&self.webview, &mut self.rendering_context) else {
return;
};
if let Err(e) = context.paint_and_present(webview) {
tracing::warn!("frame not presented: {e}");
return;
}
if !self.ready_signalled && self.signals.settled.load(Ordering::Relaxed) {
self.ready_signalled = true;
println!("READY");
use std::io::Write;
let _ = std::io::stdout().flush();
}
}
fn blit_software(window: &Arc<Window>, rendering_context: &servo::SoftwareRenderingContext) {
let size = window.inner_size();
let Some(pixels) = rendering_context.read_pixels() else {
return;
};
let Ok(ctx) = softbuffer::Context::new(Arc::clone(window)) else {
tracing::warn!("softbuffer context creation failed; skipping frame");
return;
};
let Ok(mut surface) = softbuffer::Surface::new(&ctx, Arc::clone(window)) else {
tracing::warn!("softbuffer surface creation failed; skipping frame");
return;
};
let _ = surface.resize(
std::num::NonZeroU32::new(size.width).unwrap_or(std::num::NonZeroU32::MIN),
std::num::NonZeroU32::new(size.height).unwrap_or(std::num::NonZeroU32::MIN),
);
let Ok(mut buf) = surface.buffer_mut() else {
return;
};
for (dst, src) in buf.iter_mut().zip(pixels.chunks(4)) {
*dst = u32::from_be_bytes([0, src[0], src[1], src[2]]);
}
let _ = buf.present();
/// Drops the webview and Servo; dropping the last `Servo` handle shuts it down.
fn shut_down(&mut self) {
self.shutting_down = true;
self.webview = None;
self.servo = None;
}
}
@ -171,9 +276,8 @@ impl ApplicationHandler<ServoWake> for App {
let size = window.inner_size();
self.window = Some(Arc::clone(&window));
if self.shell_client.is_none() {
if let (Some(disp), Some(surf)) =
(event_loop.wayland_display(), window.wayland_surface())
if self.shell_client.is_none()
&& let Some((disp, surf)) = wayland_handles(event_loop, &window)
{
match crate::shell_client::ShellClient::connect_as_app_with_display(
&self.app_id,
@ -185,9 +289,9 @@ impl ApplicationHandler<ServoWake> for App {
Err(e) => tracing::warn!(error = %e, "shell protocol unavailable"),
}
}
}
let servo = ServoBuilder::default()
.preferences(host_preferences())
.event_loop_waker(Box::new(self.waker.clone()))
.build();
@ -212,22 +316,15 @@ impl ApplicationHandler<ServoWake> for App {
let webview = WebViewBuilder::new(&servo, rendering_context.as_dyn())
.delegate(Rc::new(WeftWebViewDelegate {
redraw_requested: Arc::clone(&self.redraw_requested),
signals: Arc::clone(&self.signals),
}))
.user_content_manager(ucm)
.url(self.url.clone())
.url(self.url.clone().into_url())
.build();
self.servo = Some(servo);
self.webview = Some(webview);
self.rendering_context = Some(rendering_context);
if !self.ready_signalled {
self.ready_signalled = true;
println!("READY");
use std::io::Write;
let _ = std::io::stdout().flush();
}
}
fn user_event(&mut self, _event_loop: &ActiveEventLoop, _event: ServoWake) {
@ -241,30 +338,28 @@ impl ApplicationHandler<ServoWake> for App {
event_loop.exit();
return;
}
let mut compositor_closed = false;
if let Some(sc) = &mut self.shell_client {
match sc.dispatch_pending() {
Ok(false) => {
self.shutting_down = true;
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
}
Ok(false) => compositor_closed = true,
Err(e) => tracing::warn!("shell client dispatch error: {e}"),
Ok(true) => {}
}
}
if compositor_closed {
self.shut_down();
event_loop.exit();
return;
}
if let Some(servo) = &self.servo {
servo.spin_event_loop();
}
if self
.redraw_requested
.swap(false, std::sync::atomic::Ordering::Relaxed)
if self.signals.redraw.swap(false, Ordering::Relaxed)
&& let Some(w) = &self.window
{
if let Some(w) = &self.window {
w.request_redraw();
}
}
}
fn window_event(
&mut self,
@ -273,18 +368,13 @@ impl ApplicationHandler<ServoWake> for App {
event: WindowEvent,
) {
match event {
WindowEvent::RedrawRequested => {
if let (Some(window), Some(servo)) = (&self.window, &self.servo) {
if let Some(rc) = &self.rendering_context {
Self::render_frame(window, rc);
}
servo.spin_event_loop();
}
}
WindowEvent::RedrawRequested => self.render_frame(),
WindowEvent::Resized(new_size) => {
let sz = servo::euclid::Size2D::new(new_size.width, new_size.height);
if new_size.width == 0 || new_size.height == 0 {
return;
}
if let Some(wv) = &self.webview {
wv.resize(sz);
wv.resize(new_size);
}
}
WindowEvent::ModifiersChanged(mods) => {
@ -297,10 +387,11 @@ impl ApplicationHandler<ServoWake> for App {
}
}
WindowEvent::CursorMoved { position, .. } => {
let pt = servo::euclid::default::Point2D::new(position.x as f32, position.y as f32);
let pt = DevicePoint::new(position.x as f32, position.y as f32);
self.cursor_pos = pt;
if let Some(wv) = &self.webview {
let _ = wv.notify_input_event(InputEvent::MouseMove(MouseMoveEvent::new(pt)));
let _ = wv
.notify_input_event(InputEvent::MouseMove(MouseMoveEvent::new(pt.into())));
}
}
WindowEvent::MouseInput { state, button, .. } => {
@ -311,22 +402,19 @@ impl ApplicationHandler<ServoWake> for App {
_ => return,
};
let action = match state {
ElementState::Pressed => MouseButtonAction::Click,
ElementState::Pressed => MouseButtonAction::Down,
ElementState::Released => MouseButtonAction::Up,
};
if let Some(wv) = &self.webview {
let _ = wv.notify_input_event(InputEvent::MouseButton(MouseButtonEvent::new(
action,
btn,
self.cursor_pos.cast_unit(),
self.cursor_pos.into(),
)));
}
}
WindowEvent::CloseRequested => {
self.shutting_down = true;
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
self.shut_down();
event_loop.exit();
}
_ => {}
@ -337,7 +425,7 @@ impl ApplicationHandler<ServoWake> for App {
fn build_rendering_ctx(
event_loop: &ActiveEventLoop,
window: &Arc<Window>,
size: winit::dpi::PhysicalSize<u32>,
size: PhysicalSize<u32>,
) -> Option<RenderingCtx> {
if std::env::var_os("WEFT_EGL_RENDERING").is_some() {
let display_handle = event_loop.display_handle();
@ -349,16 +437,26 @@ fn build_rendering_ctx(
return Some(RenderingCtx::Egl(Rc::new(rc)));
}
Err(e) => {
tracing::warn!("EGL rendering context failed ({e}), falling back to software");
tracing::warn!(
"EGL rendering context failed ({e:?}), falling back to software"
);
}
}
}
}
match servo::SoftwareRenderingContext::new(servo::euclid::Size2D::new(size.width, size.height))
{
Ok(rc) => Some(RenderingCtx::Software(Rc::new(rc))),
let context = match servo::SoftwareRenderingContext::new(size) {
Ok(rc) => Rc::new(rc),
Err(e) => {
tracing::error!("SoftwareRenderingContext failed: {e}");
tracing::error!("SoftwareRenderingContext failed: {e:?}");
return None;
}
};
let surface = softbuffer::Context::new(Arc::clone(window))
.and_then(|display| softbuffer::Surface::new(&display, Arc::clone(window)));
match surface {
Ok(surface) => Some(RenderingCtx::Software { context, surface }),
Err(e) => {
tracing::error!("software presentation surface failed: {e}");
None
}
}

View file

@ -1,5 +1,3 @@
#![cfg(feature = "servo-embed")]
use servo::{Code, Key, KeyState, KeyboardEvent, Location, Modifiers};
use winit::event::ElementState;
use winit::keyboard::{Key as WinitKey, KeyLocation, ModifiersState, NamedKey, PhysicalKey};
@ -14,10 +12,11 @@ pub fn keyboard_event_from_winit(
};
let key = match &event.logical_key {
WinitKey::Named(NamedKey::Space) => Key::Character(" ".to_string()),
WinitKey::Named(n) => Key::Named(named_key(*n)),
WinitKey::Character(c) => Key::Character(c.to_string().into()),
WinitKey::Unidentified(_) => Key::Unidentified,
WinitKey::Dead(c) => Key::Dead(*c),
WinitKey::Character(c) => Key::Character(c.to_string()),
WinitKey::Unidentified(_) => Key::Named(servo::NamedKey::Unidentified),
WinitKey::Dead(_) => Key::Named(servo::NamedKey::Dead),
};
let code = match event.physical_key {
@ -46,15 +45,7 @@ pub fn keyboard_event_from_winit(
mods |= Modifiers::META;
}
KeyboardEvent {
state,
key,
code,
location,
modifiers: mods,
repeat: event.repeat,
is_composing: false,
}
KeyboardEvent::new_without_event(state, key, code, location, mods, event.repeat, false)
}
fn named_key(n: NamedKey) -> servo::NamedKey {
@ -74,7 +65,6 @@ fn named_key(n: NamedKey) -> servo::NamedKey {
NamedKey::SymbolLock => S::SymbolLock,
NamedKey::Enter => S::Enter,
NamedKey::Tab => S::Tab,
NamedKey::Space => S::Space,
NamedKey::ArrowDown => S::ArrowDown,
NamedKey::ArrowLeft => S::ArrowLeft,
NamedKey::ArrowRight => S::ArrowRight,

View file

@ -57,10 +57,6 @@ fn embed_app(app_id: &str, session_id: u64, ws_port: u16) -> anyhow::Result<()>
#[cfg(not(feature = "servo-embed"))]
{
let _ = (app_id, session_id, ws_port);
println!("READY");
use std::io::Write;
let _ = std::io::stdout().flush();
std::thread::park();
Ok(())
anyhow::bail!("weft-app-shell was built without the servo-embed feature and cannot render")
}
}

View file

@ -215,8 +215,4 @@ impl ShellClient {
self.event_queue.flush().context("Wayland flush")?;
Ok(!self.data.window_state.closed)
}
pub fn window_state(&self) -> &ShellWindowState {
&self.data.window_state
}
}

View file

@ -75,32 +75,64 @@ Install with: `sudo zypper install -y libglvnd-devel libopenssl-devel dbus-1-dev
## Rendering approach
Default: `SoftwareRenderingContext` (CPU rasterisation) blitted to a
`softbuffer`-backed winit window.
Each frame is painted with `WebView::paint` and then presented:
EGL path: set `WEFT_EGL_RENDERING=1` at runtime. The embedder attempts
`WindowRenderingContext::new` using the winit display and window handles.
If construction fails it falls back to software automatically.
When the EGL path is active Servo presents directly to the EGL surface via
surfman's `eglSwapBuffers`; the softbuffer blit is skipped. Mesa handles
DMA-BUF buffer sharing with the compositor transparently.
- **Software (default):** Servo renders into a `SoftwareRenderingContext`.
The host reads the painted frame back with `read_to_image`, presents the
context and copies the pixels into a persistent `softbuffer` surface on the
winit window.
- **EGL:** with `WEFT_EGL_RENDERING=1` the host creates a
`WindowRenderingContext` from winit's display and window handles and
presents it directly. If that fails it falls back to software.
Neither host presents anything before Servo's first repaint request; the
first frames can still be blank or unstyled while the document loads. Both
enable Servo's `layout_grid_enabled` preference, because the system UI and
application pages use CSS Grid, which Servo disables by default.
`weft-app-shell` prints `READY` after it presents a frame once the document
has loaded and Servo reports its rendering settled: on load completion it
requests `WebView::take_screenshot`, whose callback runs only after `load` has
fired in every frame, render-blocking resources, images and web fonts are done
and the rendering is up to date. `weft-appd` does not read this signal yet; it
treats the runtime's `READY` as session readiness. Neither host prints `READY`
when built without `servo-embed`; both exit with an error instead.
`tests/frame/check_frame.py` checks this on a real display path: it runs
`weft-compositor` nested on Xvfb and checks the pixels each host presents for
`tests/frame/reference.html`. For the app host it requires the page on screen
within two seconds of `READY`; `--slow-style` delays a render-blocking
stylesheet that reveals the page, which makes premature readiness visible. A
build that printed `READY` on its first presented frame failed every
`--slow-style 4` run; that build was a local experiment, not part of history.
## Known limitations at this pin
Status is stated against executed evidence; code that exists but has not been
exercised is listed as unverified.
- **Embedder API**: both `weft-servo-shell` and `weft-app-shell` fail to compile
with `servo-embed` against this revision (keyboard events, mouse actions,
rendering readback, shutdown and window-handle APIs changed). Until they
build and present a frame, input forwarding, surface sharing and rendering
in the shells are unverified.
- **Verified rendering path:** both hosts present the reference page through
`weft-compositor`'s winit backend on Xvfb with Mesa 25.2.8 llvmpipe, using
the software path (Ubuntu 24.04, x86_64; `check_frame.py --host system`,
`--host app` and `--host app --slow-style 3`, five runs each). The EGL path,
DRM sessions, resize, output scale and idle wakeup are unverified.
- **Input:** keyboard and pointer events are forwarded through
`WebView::notify_input_event`; delivery through the compositor is
unverified.
- **`backdrop-filter`**: the parsing (Stylo `f1ba496`) and rendering (Servo
`8e7dc40`, `f0bb1aa`) patches are selected by the lockfile. Rendering is
unverified until a pixel check passes on the shells.
`8e7dc40`, `f0bb1aa`) patches are selected by the lockfile; rendering is
unverified.
- **Resources:** the hosts install no Servo resource reader, so Servo logs
`Resource reader not set` and uses empty resources: the public suffix list,
HSTS preload list, Bluetooth blocklist, certificate and network error pages,
crash and directory-listing pages and media controls. Servo falls back to its
built-in placeholder image.
- **Window decorations:** `weft-compositor` offers no server-side decorations,
so winit draws a client-side title bar on both hosts' windows, including the
system panel.
- **Shell surface association**: the shells pass winit's `wl_display` and
`wl_surface` to `zweft_shell_manager_v1.create_window` through a shared
connection; unverified at this revision.
connection; unverified.
- **WebGPU on Mesa**: not evaluated.
- **Process separation**: each app runs as separate `weft-app-shell` and
`weft-runtime` processes supervised by `weft-appd`. Separate processes alone

View file

@ -1,20 +1,22 @@
#![cfg(feature = "servo-embed")]
use std::num::NonZeroU32;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use servo::{
EventLoopWaker, InputEvent, MouseButton as ServoMouseButton, MouseButtonAction,
MouseButtonEvent, MouseMoveEvent, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager,
DeviceIntRect, DeviceIntSize, DevicePoint, EventLoopWaker, InputEvent,
MouseButton as ServoMouseButton, MouseButtonAction, MouseButtonEvent, MouseMoveEvent,
RenderingContext, RgbaImage, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager,
UserScript, WebViewBuilder, WebViewDelegate,
};
use winit::{
application::ApplicationHandler,
dpi::PhysicalSize,
event::{ElementState, MouseButton, WindowEvent},
event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
keyboard::ModifiersState,
platform::wayland::{ActiveEventLoopExtWayland, WindowExtWayland},
raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle},
window::{Window, WindowAttributes, WindowId},
};
@ -54,31 +56,114 @@ impl ServoDelegate for WeftServoDelegate {
// ── WebView delegate ──────────────────────────────────────────────────────────
/// Frame and load progress reported by Servo, shared with the event loop.
#[derive(Default)]
struct FrameSignals {
/// A new frame is waiting to be painted.
redraw: AtomicBool,
/// Servo has requested at least one repaint.
content: AtomicBool,
}
struct WeftWebViewDelegate {
redraw_requested: Arc<std::sync::atomic::AtomicBool>,
signals: Arc<FrameSignals>,
}
impl WebViewDelegate for WeftWebViewDelegate {
fn notify_new_frame_ready(&self, _webview: servo::WebView) {
self.redraw_requested
.store(true, std::sync::atomic::Ordering::Relaxed);
self.signals.content.store(true, Ordering::Relaxed);
self.signals.redraw.store(true, Ordering::Relaxed);
}
}
// ── Rendering context abstraction (GAP-2) ───────────────────────────────────
/// Servo preferences shared by the WEFT hosts.
fn host_preferences() -> servo::Preferences {
servo::Preferences {
// The system UI and application pages lay out with CSS Grid, which
// Servo disables by default.
layout_grid_enabled: true,
..Default::default()
}
}
// ── Rendering ───────────────────────────────────────────────────────────────
type BlitSurface = softbuffer::Surface<Arc<Window>, Arc<Window>>;
enum RenderingCtx {
Software(Rc<servo::SoftwareRenderingContext>),
/// Servo renders offscreen; each frame is read back and copied to the window.
Software {
context: Rc<servo::SoftwareRenderingContext>,
surface: BlitSurface,
},
/// Servo renders directly to the window's EGL surface.
Egl(Rc<servo::WindowRenderingContext>),
}
impl RenderingCtx {
fn as_dyn(&self) -> Rc<dyn servo::RenderingContext> {
fn as_dyn(&self) -> Rc<dyn RenderingContext> {
match self {
Self::Software(rc) => Rc::clone(rc) as Rc<dyn servo::RenderingContext>,
Self::Egl(rc) => Rc::clone(rc) as Rc<dyn servo::RenderingContext>,
Self::Software { context, .. } => Rc::clone(context) as Rc<dyn RenderingContext>,
Self::Egl(context) => Rc::clone(context) as Rc<dyn RenderingContext>,
}
}
/// Paints the webview into this context and presents the frame on the window.
fn paint_and_present(&mut self, webview: &servo::WebView) -> Result<(), String> {
match self {
Self::Software { context, surface } => {
context
.make_current()
.map_err(|e| format!("make_current: {e:?}"))?;
webview.paint();
let size = context.size();
let rect = DeviceIntRect::from_size(DeviceIntSize::new(
size.width as i32,
size.height as i32,
));
let image = context.read_to_image(rect);
context.present();
let image = image.ok_or("frame readback failed")?;
blit(surface, &image)
}
Self::Egl(context) => {
context
.make_current()
.map_err(|e| format!("make_current: {e:?}"))?;
webview.paint();
context.present();
Ok(())
}
}
}
}
/// Copies an RGBA frame into the window's software surface and presents it.
fn blit(surface: &mut BlitSurface, image: &RgbaImage) -> Result<(), String> {
let (width, height) = image.dimensions();
let (Some(w), Some(h)) = (NonZeroU32::new(width), NonZeroU32::new(height)) else {
return Ok(());
};
surface.resize(w, h).map_err(|e| format!("resize: {e}"))?;
let mut buffer = surface.buffer_mut().map_err(|e| format!("buffer: {e}"))?;
for (dst, src) in buffer.iter_mut().zip(image.as_raw().chunks_exact(4)) {
*dst = u32::from(src[0]) << 16 | u32::from(src[1]) << 8 | u32::from(src[2]);
}
buffer.present().map_err(|e| format!("present: {e}"))
}
/// Returns winit's `wl_display` and `wl_surface` pointers when running on Wayland.
fn wayland_handles(
event_loop: &ActiveEventLoop,
window: &Window,
) -> Option<(*mut std::ffi::c_void, *mut std::ffi::c_void)> {
let RawDisplayHandle::Wayland(display) = event_loop.display_handle().ok()?.as_raw() else {
return None;
};
let RawWindowHandle::Wayland(surface) = window.window_handle().ok()?.as_raw() else {
return None;
};
Some((display.display.as_ptr(), surface.surface.as_ptr()))
}
// ── Application state ─────────────────────────────────────────────────────────
@ -90,11 +175,11 @@ struct App {
servo: Option<servo::Servo>,
webview: Option<servo::WebView>,
rendering_context: Option<RenderingCtx>,
redraw_requested: Arc<std::sync::atomic::AtomicBool>,
signals: Arc<FrameSignals>,
waker: WeftEventLoopWaker,
shutting_down: bool,
modifiers: ModifiersState,
cursor_pos: servo::euclid::default::Point2D<f32>,
cursor_pos: DevicePoint,
shell_client: Option<crate::shell_client::ShellClient>,
gesture_thread: Option<std::thread::JoinHandle<()>>,
}
@ -108,47 +193,37 @@ impl App {
servo: None,
webview: None,
rendering_context: None,
redraw_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)),
signals: Arc::default(),
waker,
shutting_down: false,
modifiers: ModifiersState::default(),
cursor_pos: servo::euclid::default::Point2D::zero(),
cursor_pos: DevicePoint::origin(),
shell_client: None,
gesture_thread: None,
}
}
fn render_frame(window: &Arc<Window>, ctx: &RenderingCtx) {
match ctx {
RenderingCtx::Software(rc) => Self::blit_software(window, rc),
RenderingCtx::Egl(_) => {}
/// Paints and presents once Servo has requested its first repaint.
///
/// Nothing is presented before that request; the first frames can still be
/// blank or unstyled while the document loads.
fn render_frame(&mut self) {
if !self.signals.content.load(Ordering::Relaxed) {
return;
}
let (Some(webview), Some(context)) = (&self.webview, &mut self.rendering_context) else {
return;
};
if let Err(e) = context.paint_and_present(webview) {
tracing::warn!("frame not presented: {e}");
}
}
fn blit_software(window: &Arc<Window>, rendering_context: &servo::SoftwareRenderingContext) {
let size = window.inner_size();
let Some(pixels) = rendering_context.read_pixels() else {
return;
};
let Ok(ctx) = softbuffer::Context::new(Arc::clone(window)) else {
tracing::warn!("softbuffer context creation failed; skipping frame");
return;
};
let Ok(mut surface) = softbuffer::Surface::new(&ctx, Arc::clone(window)) else {
tracing::warn!("softbuffer surface creation failed; skipping frame");
return;
};
let _ = surface.resize(
std::num::NonZeroU32::new(size.width).unwrap_or(std::num::NonZeroU32::MIN),
std::num::NonZeroU32::new(size.height).unwrap_or(std::num::NonZeroU32::MIN),
);
let Ok(mut buf) = surface.buffer_mut() else {
return;
};
for (dst, src) in buf.iter_mut().zip(pixels.chunks(4)) {
*dst = u32::from_be_bytes([0, src[0], src[1], src[2]]);
}
let _ = buf.present();
/// Drops the webview and Servo; dropping the last `Servo` handle shuts it down.
fn shut_down(&mut self) {
self.shutting_down = true;
self.webview = None;
self.servo = None;
}
}
@ -170,18 +245,17 @@ impl ApplicationHandler<ServoWake> for App {
let size = window.inner_size();
self.window = Some(Arc::clone(&window));
if self.shell_client.is_none() {
if let (Some(disp), Some(surf)) =
(event_loop.wayland_display(), window.wayland_surface())
if self.shell_client.is_none()
&& let Some((disp, surf)) = wayland_handles(event_loop, &window)
{
match crate::shell_client::ShellClient::connect_with_display(disp, surf) {
Ok(sc) => self.shell_client = Some(sc),
Err(e) => tracing::warn!(error = %e, "shell protocol unavailable"),
}
}
}
let servo = ServoBuilder::default()
.preferences(host_preferences())
.event_loop_waker(Box::new(self.waker.clone()))
.build();
@ -205,10 +279,10 @@ impl ApplicationHandler<ServoWake> for App {
let webview = WebViewBuilder::new(&servo, rendering_context.as_dyn())
.delegate(Rc::new(WeftWebViewDelegate {
redraw_requested: Arc::clone(&self.redraw_requested),
signals: Arc::clone(&self.signals),
}))
.user_content_manager(Rc::clone(&user_content_manager))
.url(self.url.clone())
.url(self.url.clone().into_url())
.build();
self.servo = Some(servo);
@ -227,14 +301,10 @@ impl ApplicationHandler<ServoWake> for App {
event_loop.exit();
return;
}
let mut compositor_closed = false;
if let Some(sc) = &mut self.shell_client {
match sc.dispatch_pending() {
Ok(false) => {
self.shutting_down = true;
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
}
Ok(false) => compositor_closed = true,
Err(e) => tracing::warn!("shell client dispatch error: {e}"),
Ok(true) => {}
}
@ -258,18 +328,20 @@ impl ApplicationHandler<ServoWake> for App {
}
}
}
if compositor_closed {
self.shut_down();
event_loop.exit();
return;
}
if let Some(servo) = &self.servo {
servo.spin_event_loop();
}
if self
.redraw_requested
.swap(false, std::sync::atomic::Ordering::Relaxed)
if self.signals.redraw.swap(false, Ordering::Relaxed)
&& let Some(w) = &self.window
{
if let Some(w) = &self.window {
w.request_redraw();
}
}
}
fn window_event(
&mut self,
@ -278,18 +350,13 @@ impl ApplicationHandler<ServoWake> for App {
event: WindowEvent,
) {
match event {
WindowEvent::RedrawRequested => {
if let (Some(window), Some(servo)) = (&self.window, &self.servo) {
if let Some(rc) = &self.rendering_context {
Self::render_frame(window, rc);
}
servo.spin_event_loop();
}
}
WindowEvent::RedrawRequested => self.render_frame(),
WindowEvent::Resized(new_size) => {
let sz = servo::euclid::Size2D::new(new_size.width, new_size.height);
if new_size.width == 0 || new_size.height == 0 {
return;
}
if let Some(wv) = &self.webview {
wv.resize(sz);
wv.resize(new_size);
}
}
WindowEvent::ModifiersChanged(mods) => {
@ -302,10 +369,11 @@ impl ApplicationHandler<ServoWake> for App {
}
}
WindowEvent::CursorMoved { position, .. } => {
let pt = servo::euclid::default::Point2D::new(position.x as f32, position.y as f32);
let pt = DevicePoint::new(position.x as f32, position.y as f32);
self.cursor_pos = pt;
if let Some(wv) = &self.webview {
let _ = wv.notify_input_event(InputEvent::MouseMove(MouseMoveEvent::new(pt)));
let _ = wv
.notify_input_event(InputEvent::MouseMove(MouseMoveEvent::new(pt.into())));
}
}
WindowEvent::MouseInput { state, button, .. } => {
@ -316,22 +384,19 @@ impl ApplicationHandler<ServoWake> for App {
_ => return,
};
let action = match state {
ElementState::Pressed => MouseButtonAction::Click,
ElementState::Pressed => MouseButtonAction::Down,
ElementState::Released => MouseButtonAction::Up,
};
if let Some(wv) = &self.webview {
let _ = wv.notify_input_event(InputEvent::MouseButton(MouseButtonEvent::new(
action,
btn,
self.cursor_pos.cast_unit(),
self.cursor_pos.into(),
)));
}
}
WindowEvent::CloseRequested => {
self.shutting_down = true;
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
self.shut_down();
event_loop.exit();
}
_ => {}
@ -344,7 +409,7 @@ impl ApplicationHandler<ServoWake> for App {
fn build_rendering_ctx(
event_loop: &ActiveEventLoop,
window: &Arc<Window>,
size: winit::dpi::PhysicalSize<u32>,
size: PhysicalSize<u32>,
) -> Option<RenderingCtx> {
if std::env::var_os("WEFT_EGL_RENDERING").is_some() {
let display_handle = event_loop.display_handle();
@ -356,16 +421,26 @@ fn build_rendering_ctx(
return Some(RenderingCtx::Egl(Rc::new(rc)));
}
Err(e) => {
tracing::warn!("EGL rendering context failed ({e}), falling back to software");
tracing::warn!(
"EGL rendering context failed ({e:?}), falling back to software"
);
}
}
}
}
match servo::SoftwareRenderingContext::new(servo::euclid::Size2D::new(size.width, size.height))
{
Ok(rc) => Some(RenderingCtx::Software(Rc::new(rc))),
let context = match servo::SoftwareRenderingContext::new(size) {
Ok(rc) => Rc::new(rc),
Err(e) => {
tracing::error!("SoftwareRenderingContext failed: {e}");
tracing::error!("SoftwareRenderingContext failed: {e:?}");
return None;
}
};
let surface = softbuffer::Context::new(Arc::clone(window))
.and_then(|display| softbuffer::Surface::new(&display, Arc::clone(window)));
match surface {
Ok(surface) => Some(RenderingCtx::Software { context, surface }),
Err(e) => {
tracing::error!("software presentation surface failed: {e}");
None
}
}

View file

@ -1,5 +1,3 @@
#![cfg(feature = "servo-embed")]
use servo::{Code, Key, KeyState, KeyboardEvent, Location, Modifiers};
use winit::event::ElementState;
use winit::keyboard::{Key as WinitKey, KeyLocation, ModifiersState, NamedKey, PhysicalKey};
@ -14,10 +12,11 @@ pub fn keyboard_event_from_winit(
};
let key = match &event.logical_key {
WinitKey::Named(NamedKey::Space) => Key::Character(" ".to_string()),
WinitKey::Named(n) => Key::Named(named_key(*n)),
WinitKey::Character(c) => Key::Character(c.to_string().into()),
WinitKey::Unidentified(_) => Key::Unidentified,
WinitKey::Dead(c) => Key::Dead(*c),
WinitKey::Character(c) => Key::Character(c.to_string()),
WinitKey::Unidentified(_) => Key::Named(servo::NamedKey::Unidentified),
WinitKey::Dead(_) => Key::Named(servo::NamedKey::Dead),
};
let code = match event.physical_key {
@ -46,15 +45,7 @@ pub fn keyboard_event_from_winit(
mods |= Modifiers::META;
}
KeyboardEvent {
state,
key,
code,
location,
modifiers: mods,
repeat: event.repeat,
is_composing: false,
}
KeyboardEvent::new_without_event(state, key, code, location, mods, event.repeat, false)
}
fn named_key(n: NamedKey) -> servo::NamedKey {
@ -74,7 +65,6 @@ fn named_key(n: NamedKey) -> servo::NamedKey {
NamedKey::SymbolLock => S::SymbolLock,
NamedKey::Enter => S::Enter,
NamedKey::Tab => S::Tab,
NamedKey::Space => S::Space,
NamedKey::ArrowDown => S::ArrowDown,
NamedKey::ArrowLeft => S::ArrowLeft,
NamedKey::ArrowRight => S::ArrowRight,

View file

@ -239,10 +239,6 @@ impl ShellClient {
Ok(!self.data.window_state.closed)
}
pub fn window_state(&self) -> &ShellWindowState {
&self.data.window_state
}
pub fn take_pending_gestures(&mut self) -> Vec<PendingGesture> {
std::mem::take(&mut self.data.pending_gestures)
}

View file

@ -34,7 +34,7 @@ cargo build -p weft-servo-shell
cargo build -p weft-app-shell
```
Without `--features servo-embed`, the servo-shell and app-shell stubs compile and print READY without running an actual WebView. This is the default and the CI baseline.
Without `--features servo-embed`, the servo-shell and app-shell binaries compile for type and lint checks but exit with an error at startup; they never report readiness. This is the default and the CI baseline.
## Servo embedding (optional, slow)
@ -45,6 +45,28 @@ cargo build -p weft-app-shell --features servo-embed
This fetches and compiles the Servo and Stylo forks at the revisions recorded in `Cargo.lock` (see `crates/weft-servo-shell/SERVO_PIN.md`). Expect 30–60 minutes on a clean build. Servo's dependencies include SpiderMonkey (C++), which requires `clang` and `python3`.
## Frame check
`tests/frame/check_frame.py` runs `weft-compositor` nested on Xvfb with the
winit backend, starts a Servo host showing `tests/frame/reference.html`, and
checks the presented pixels. It needs `Xvfb`, `xwd`, ImageMagick's `convert`
and a Mesa OpenGL driver (llvmpipe is sufficient).
```sh
cargo build -p weft-compositor
cargo build -p weft-servo-shell -p weft-app-shell \
--features weft-servo-shell/servo-embed,weft-app-shell/servo-embed
python3 tests/frame/check_frame.py --host system
python3 tests/frame/check_frame.py --host app
python3 tests/frame/check_frame.py --host app --slow-style 3
```
`--host app` also requires the page on screen within two seconds of
`weft-app-shell` printing `READY`; `--slow-style` delays a stylesheet that
reveals the page so premature readiness becomes visible.
Logs and the last capture are written to `target/frame-check`.
## Demo apps (wasm32-wasip2)
Each demo is a standalone crate in `examples/`. Pre-built `app.wasm` binaries are committed. To rebuild:

370
tests/frame/check_frame.py Normal file
View file

@ -0,0 +1,370 @@
"""Check that a Servo host paints and presents a known page through weft-compositor.
The harness starts Xvfb, runs weft-compositor nested on it with the winit
backend, launches a Servo host as a Wayland client showing `reference.html`,
captures the X screen and checks the presented pixels: four solid quadrants
(red, green, blue, white) in the page's arrangement and dark text pixels
inside the white quadrant. It exits non-zero when the frame never appears or
does not match.
`--host system` runs weft-servo-shell with the page as its system UI.
`--host app` installs the page as a package in a temporary app store and runs
weft-app-shell for it. The host must print READY, and the page must be on
screen within a short grace period after READY, because the compositor shows
a presented frame slightly later. READY printed within that grace before the
page is presented is therefore not detected. `--slow-style SECONDS` makes
early readiness observable: the page stays hidden until a stylesheet that a
local HTTP server delivers after the delay reveals it, so a host that reports
READY before the document has loaded shows no page within the grace period.
Requires Xvfb, xwd and ImageMagick's convert. Processes are started from
argument arrays and are always terminated before the harness exits.
"""
import argparse
import http.server
import os
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
SCREEN = (1024, 768)
COLORS = {
"red": (255, 0, 0),
"green": (0, 255, 0),
"blue": (0, 0, 255),
"white": (255, 255, 255),
}
MIN_SIDE = 40
MIN_TEXT_PIXELS = 30
ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;]*m")
def parse_ppm(data):
"""Decode a binary P6 PPM into (width, height, bytes)."""
tokens = []
index = 0
while len(tokens) < 4:
while data[index:index + 1].isspace():
index += 1
if data[index:index + 1] == b"#":
index = data.index(b"\n", index) + 1
continue
end = index
while not data[end:end + 1].isspace():
end += 1
tokens.append(data[index:end])
index = end
magic, width, height, maxval = tokens
if magic != b"P6" or int(maxval) != 255:
raise ValueError("expected an 8-bit P6 image")
width, height = int(width), int(height)
pixels = data[index + 1:index + 1 + width * height * 3]
if len(pixels) != width * height * 3:
raise ValueError("truncated image")
return width, height, pixels
def bounding_box(width, height, pixels, color):
"""Return (x0, y0, x1, y1) of pixels exactly matching color, or None."""
target = bytes(color)
xs, ys = [], []
for y in range(0, height, 2):
row = pixels[y * width * 3:(y + 1) * width * 3]
start = row.find(target)
while start != -1:
if start % 3 == 0:
xs.append(start // 3)
ys.append(y)
start = row.find(target, start + 3)
else:
# A match spanning two pixels; realign on the next byte.
start = row.find(target, start + 1)
if not xs:
return None
return min(xs), min(ys), max(xs), max(ys)
def dark_pixels(width, pixels, box):
x0, y0, x1, y1 = box
count = 0
for y in range(y0, y1 + 1):
for x in range(x0, x1 + 1):
offset = (y * width + x) * 3
if max(pixels[offset:offset + 3]) < 96:
count += 1
return count
def evaluate(width, height, pixels):
"""Return a list of problems with the captured frame; empty means it matches."""
boxes = {name: bounding_box(width, height, pixels, color) for name, color in COLORS.items()}
problems = [f"no {name} region" for name, box in boxes.items() if box is None]
if problems:
return problems
for name, (x0, y0, x1, y1) in boxes.items():
if x1 - x0 < MIN_SIDE or y1 - y0 < MIN_SIDE:
problems.append(f"{name} region too small: {x1 - x0 + 1}x{y1 - y0 + 1}")
red, green, blue, white = (boxes[n] for n in ("red", "green", "blue", "white"))
if not green[0] > red[2]:
problems.append("green is not right of red")
if not blue[1] > red[3]:
problems.append("blue is not below red")
if not (white[0] > blue[2] and white[1] > green[3]):
problems.append("white is not below green and right of blue")
if abs(red[1] - green[1]) > 4 or abs(red[0] - blue[0]) > 4:
problems.append("quadrants are not aligned")
text = dark_pixels(width, pixels, white)
if text < MIN_TEXT_PIXELS:
problems.append(f"no text in white region ({text} dark pixels)")
return problems
APP_ID = "org.weft.test.frame"
COMPOSITE_GRACE = 2.0
def install_app(store, page):
"""Install `page` as the UI entry of a minimal package and return the store root."""
package = store / APP_ID
(package / "ui").mkdir(parents=True)
shutil.copyfile(page, package / "ui" / "index.html")
(package / "wapp.toml").write_text(
"[package]\n"
f'id = "{APP_ID}"\n'
'name = "Frame reference"\n'
'version = "0.0.0"\n'
"\n[runtime]\n"
'module = "app.wasm"\n'
"\n[ui]\n"
'entry = "ui/index.html"\n',
encoding="utf-8",
)
return store
def slow_style_server(delay):
"""Serve a stylesheet that reveals the page after `delay` seconds."""
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
time.sleep(delay)
body = b"body { visibility: visible; }"
self.send_response(200)
self.send_header("Content-Type", "text/css")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
def hidden_until_styled(page, destination, port):
"""Copy `page`, hiding its body until the delayed stylesheet loads."""
html = page.read_text(encoding="utf-8")
link = (f'<style>body {{ visibility: hidden; }}</style>\n'
f'<link rel="stylesheet" href="http://127.0.0.1:{port}/reveal.css">\n</head>')
if "</head>" not in html:
raise ValueError(f"{page} has no </head>")
destination.write_text(html.replace("</head>", link, 1), encoding="utf-8")
return destination
def capture(display):
xwd = subprocess.run(["xwd", "-root", "-silent", "-display", display],
capture_output=True, check=True, timeout=20)
ppm = subprocess.run(["convert", "xwd:-", "ppm:-"], input=xwd.stdout,
capture_output=True, check=True, timeout=20)
return ppm.stdout
def free_display():
for number in range(90, 140):
if not Path(f"/tmp/.X11-unix/X{number}").exists() and \
not Path(f"/tmp/.X{number}-lock").exists():
return f":{number}"
raise RuntimeError("no free X display number")
def start(command, log, env):
return subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, env=env,
start_new_session=True)
def signal_group(process, signum):
try:
os.killpg(process.pid, signum)
except ProcessLookupError:
pass
def stop(process):
"""Terminate the process and everything left in its process group."""
if process is None:
return
signal_group(process, signal.SIGTERM)
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
signal_group(process, signal.SIGKILL)
process.wait(timeout=10)
signal_group(process, signal.SIGKILL)
def wait_for(predicate, timeout, interval=0.5):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = predicate()
if result:
return result
time.sleep(interval)
return None
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("--host", choices=("system", "app"), default="system")
parser.add_argument("--shell", type=Path,
help="host binary (default: target/debug/weft-servo-shell or "
"target/debug/weft-app-shell)")
parser.add_argument("--page", type=Path, default=HERE / "reference.html")
parser.add_argument("--slow-style", type=float, metavar="SECONDS",
help="hide the page until a stylesheet delayed by SECONDS loads")
parser.add_argument("--timeout", type=float, default=120.0,
help="seconds to wait for a matching frame")
parser.add_argument("--output", type=Path, default=ROOT / "target/frame-check",
help="directory for logs and the captured screenshot")
args = parser.parse_args(argv)
if args.shell is None:
name = "weft-servo-shell" if args.host == "system" else "weft-app-shell"
args.shell = ROOT / "target/debug" / name
for tool in ("Xvfb", "xwd", "convert"):
if shutil.which(tool) is None:
print(f"missing required tool: {tool}", file=sys.stderr)
return 2
for binary in (args.compositor, args.shell):
if not binary.is_file():
print(f"missing binary: {binary}", file=sys.stderr)
return 2
args.output.mkdir(parents=True, exist_ok=True)
runtime = Path(tempfile.mkdtemp(prefix="weft-frame-"))
runtime.chmod(0o700)
display = free_display()
base_env = {key: value for key, value in os.environ.items()
if key not in ("DISPLAY", "WAYLAND_DISPLAY", "WAYLAND_SOCKET")}
base_env["XDG_RUNTIME_DIR"] = str(runtime)
base_env.setdefault("RUST_LOG", "info")
page = args.page
style_server = None
if args.slow_style:
style_server = slow_style_server(args.slow_style)
page = hidden_until_styled(args.page, runtime / "page.html",
style_server.server_address[1])
processes = []
logs = {name: open(args.output / f"{name}.log", "w", encoding="utf-8")
for name in ("xvfb", "compositor", "shell")}
try:
xvfb = start(["Xvfb", display, "-screen", "0", f"{SCREEN[0]}x{SCREEN[1]}x24",
"-nolisten", "tcp"], logs["xvfb"], base_env)
processes.append(xvfb)
if not wait_for(lambda: Path(f"/tmp/.X11-unix/X{display[1:]}").exists(), 15):
print("Xvfb did not start", file=sys.stderr)
return 1
compositor_env = dict(base_env, DISPLAY=display)
compositor = start([str(args.compositor), "--winit"], logs["compositor"],
compositor_env)
processes.append(compositor)
compositor_log = args.output / "compositor.log"
def socket_name():
if compositor.poll() is not None:
return "exited"
text = ANSI_ESCAPE.sub("", compositor_log.read_text(encoding="utf-8",
errors="replace"))
match = re.search(r'socket_name="([^"]+)"', text)
return match and match.group(1)
socket = wait_for(socket_name, 30)
if socket in (None, "exited"):
print(f"compositor did not open a Wayland socket; see {compositor_log}",
file=sys.stderr)
return 1
shell_env = dict(base_env, WAYLAND_DISPLAY=socket)
if args.host == "system":
shell_env["WEFT_SYSTEM_UI_HTML"] = str(page.resolve())
command = [str(args.shell)]
else:
shell_env["WEFT_APP_STORE"] = str(install_app(runtime / "store", page))
command = [str(args.shell), APP_ID, "1"]
shell = start(command, logs["shell"], shell_env)
processes.append(shell)
shell_log = args.output / "shell.log"
def ready_printed():
text = shell_log.read_text(encoding="utf-8", errors="replace")
return any(line.strip() == "READY" for line in text.splitlines())
problems = ["no frame captured"]
screenshot = None
ready_at = None
deadline = time.monotonic() + args.timeout
while time.monotonic() < deadline:
if shell.poll() is not None:
problems = [f"shell exited with status {shell.returncode}"]
break
if args.host == "app" and ready_at is None and ready_printed():
ready_at = time.monotonic()
ready = ready_at is not None
screenshot = capture(display)
problems = evaluate(*parse_ppm(screenshot))
if ready and problems and time.monotonic() - ready_at > COMPOSITE_GRACE:
problems = [f"page not on screen {COMPOSITE_GRACE:g} s after READY"] + problems
break
if not problems and (args.host == "system" or ready):
break
if not problems:
problems = ["frame presented but READY not printed"]
time.sleep(1)
if screenshot is not None:
(args.output / "frame.ppm").write_bytes(screenshot)
if problems:
print("frame check failed: " + "; ".join(problems), file=sys.stderr)
print(f"logs and last capture in {args.output}", file=sys.stderr)
return 1
print(f"frame check passed; capture in {args.output / 'frame.ppm'}")
return 0
finally:
for process in reversed(processes):
stop(process)
if style_server is not None:
style_server.shutdown()
for log in logs.values():
log.close()
shutil.rmtree(runtime, ignore_errors=True)
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -0,0 +1,21 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WEFT frame reference</title>
<style>
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; }
body { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; }
#red { background: rgb(255, 0, 0); }
#green { background: rgb(0, 255, 0); }
#blue { background: rgb(0, 0, 255); }
#white { background: rgb(255, 255, 255); color: rgb(0, 0, 0); font: 32px sans-serif; }
</style>
</head>
<body>
<div id="red"></div>
<div id="green"></div>
<div id="blue"></div>
<div id="white">WEFT</div>
</body>
</html>