Merge branch 'main' into docs/add-engineering-contract

This commit is contained in:
Marco Allegretti 2026-10-09 08:56:42 +00:00
commit 4d39ec3a8b
No known key found for this signature in database
24 changed files with 1308 additions and 423 deletions

View file

@ -7,15 +7,9 @@ on:
pull_request: pull_request:
jobs: jobs:
# Crates that must compile on every supported host platform. # Crates that build without Wayland or other Linux system libraries.
cross-platform: portable:
runs-on: ${{ matrix.os }} runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
os:
- ubuntu-latest
- windows-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable - uses: dtolnay/rust-toolchain@stable
@ -24,14 +18,14 @@ jobs:
components: rustfmt, clippy components: rustfmt, clippy
- name: cargo fmt - name: cargo fmt
run: cargo fmt --all --check run: cargo fmt --all --check
- name: cargo clippy (cross-platform crates) - name: cargo clippy (portable crates)
run: > run: >
cargo clippy --workspace cargo clippy --workspace
--exclude weft-compositor --exclude weft-compositor
--exclude weft-servo-shell --exclude weft-servo-shell
--exclude weft-app-shell --exclude weft-app-shell
--all-targets -- -D warnings --all-targets -- -D warnings
- name: cargo test (cross-platform crates) - name: cargo test (portable crates)
run: > run: >
cargo test --workspace cargo test --workspace
--exclude weft-compositor --exclude weft-compositor

132
Cargo.lock generated
View file

@ -6476,7 +6476,7 @@ dependencies = [
[[package]] [[package]]
name = "selectors" name = "selectors"
version = "0.36.0" version = "0.36.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a" source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [ dependencies = [
"bitflags 2.11.0", "bitflags 2.11.0",
"cssparser", "cssparser",
@ -6590,7 +6590,7 @@ dependencies = [
[[package]] [[package]]
name = "servo" name = "servo"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"accesskit", "accesskit",
"bitflags 2.11.0", "bitflags 2.11.0",
@ -6651,7 +6651,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-allocator" name = "servo-allocator"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"libc", "libc",
"tikv-jemalloc-sys", "tikv-jemalloc-sys",
@ -6662,7 +6662,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-background-hang-monitor" name = "servo-background-hang-monitor"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"backtrace", "backtrace",
"crossbeam-channel", "crossbeam-channel",
@ -6677,7 +6677,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-background-hang-monitor-api" name = "servo-background-hang-monitor-api"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"serde", "serde",
"servo-base", "servo-base",
@ -6686,7 +6686,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-base" name = "servo-base"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"accesskit", "accesskit",
"crossbeam-channel", "crossbeam-channel",
@ -6711,7 +6711,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-canvas" name = "servo-canvas"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"crossbeam-channel", "crossbeam-channel",
@ -6736,7 +6736,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-canvas-traits" name = "servo-canvas-traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"crossbeam-channel", "crossbeam-channel",
"euclid", "euclid",
@ -6758,7 +6758,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-config" name = "servo-config"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
@ -6770,7 +6770,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-config-macro" name = "servo-config-macro"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -6781,7 +6781,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-constellation" name = "servo-constellation"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"backtrace", "backtrace",
"content-security-policy", "content-security-policy",
@ -6828,7 +6828,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-constellation-traits" name = "servo-constellation-traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"content-security-policy", "content-security-policy",
"encoding_rs", "encoding_rs",
@ -6863,7 +6863,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-deny-public-fields" name = "servo-deny-public-fields"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"syn", "syn",
"synstructure", "synstructure",
@ -6872,7 +6872,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-devtools" name = "servo-devtools"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"atomic_refcell", "atomic_refcell",
"base64 0.22.1", "base64 0.22.1",
@ -6901,7 +6901,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-devtools-traits" name = "servo-devtools-traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"bitflags 2.11.0", "bitflags 2.11.0",
"http 1.4.0", "http 1.4.0",
@ -6920,7 +6920,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-dom-struct" name = "servo-dom-struct"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -6930,7 +6930,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-embedder-traits" name = "servo-embedder-traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"accesskit", "accesskit",
"bitflags 2.11.0", "bitflags 2.11.0",
@ -6963,7 +6963,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-fonts" name = "servo-fonts"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"app_units", "app_units",
"bitflags 2.11.0", "bitflags 2.11.0",
@ -7016,7 +7016,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-fonts-traits" name = "servo-fonts-traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"atomic_refcell", "atomic_refcell",
"dwrote", "dwrote",
@ -7039,7 +7039,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-geometry" name = "servo-geometry"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"app_units", "app_units",
"euclid", "euclid",
@ -7052,7 +7052,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-hyper-serde" name = "servo-hyper-serde"
version = "0.13.2" version = "0.13.2"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"cookie 0.18.1", "cookie 0.18.1",
"headers 0.4.1", "headers 0.4.1",
@ -7066,7 +7066,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-jstraceable-derive" name = "servo-jstraceable-derive"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"syn", "syn",
@ -7076,7 +7076,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-layout" name = "servo-layout"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"accesskit", "accesskit",
"app_units", "app_units",
@ -7130,7 +7130,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-layout-api" name = "servo-layout-api"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"app_units", "app_units",
"atomic_refcell", "atomic_refcell",
@ -7164,7 +7164,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-malloc-size-of" name = "servo-malloc-size-of"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"accountable-refcell", "accountable-refcell",
"app_units", "app_units",
@ -7204,7 +7204,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-media" name = "servo-media"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"once_cell", "once_cell",
"servo-media-audio", "servo-media-audio",
@ -7217,7 +7217,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-media-audio" name = "servo-media-audio"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"byte-slice-cast", "byte-slice-cast",
"euclid", "euclid",
@ -7240,7 +7240,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-media-derive" name = "servo-media-derive"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -7250,7 +7250,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-media-dummy" name = "servo-media-dummy"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"ipc-channel", "ipc-channel",
"servo-media", "servo-media",
@ -7264,7 +7264,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-media-player" name = "servo-media-player"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"ipc-channel", "ipc-channel",
"malloc_size_of_derive", "malloc_size_of_derive",
@ -7278,7 +7278,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-media-streams" name = "servo-media-streams"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"malloc_size_of_derive", "malloc_size_of_derive",
"servo-malloc-size-of", "servo-malloc-size-of",
@ -7288,7 +7288,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-media-thread" name = "servo-media-thread"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"euclid", "euclid",
"ipc-channel", "ipc-channel",
@ -7306,7 +7306,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-media-traits" name = "servo-media-traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"malloc_size_of_derive", "malloc_size_of_derive",
"servo-malloc-size-of", "servo-malloc-size-of",
@ -7315,7 +7315,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-media-webrtc" name = "servo-media-webrtc"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"log", "log",
"servo-media-streams", "servo-media-streams",
@ -7325,7 +7325,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-metrics" name = "servo-metrics"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"malloc_size_of_derive", "malloc_size_of_derive",
"servo-base", "servo-base",
@ -7340,7 +7340,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-net" name = "servo-net"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"async-compression", "async-compression",
"async-recursion", "async-recursion",
@ -7409,7 +7409,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-net-traits" name = "servo-net-traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"content-security-policy", "content-security-policy",
"cookie 0.18.1", "cookie 0.18.1",
@ -7449,7 +7449,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-paint" name = "servo-paint"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"bitflags 2.11.0", "bitflags 2.11.0",
"crossbeam-channel", "crossbeam-channel",
@ -7486,7 +7486,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-paint-api" name = "servo-paint-api"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"bitflags 2.11.0", "bitflags 2.11.0",
"crossbeam-channel", "crossbeam-channel",
@ -7522,7 +7522,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-pixels" name = "servo-pixels"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"euclid", "euclid",
"image", "image",
@ -7537,7 +7537,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-profile" name = "servo-profile"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"libc", "libc",
"log", "log",
@ -7556,7 +7556,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-profile-traits" name = "servo-profile-traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"crossbeam-channel", "crossbeam-channel",
"ipc-channel", "ipc-channel",
@ -7573,7 +7573,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-script" name = "servo-script"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"aes", "aes",
"aes-gcm", "aes-gcm",
@ -7712,7 +7712,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-script-bindings" name = "servo-script-bindings"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"bitflags 2.11.0", "bitflags 2.11.0",
"crossbeam-channel", "crossbeam-channel",
@ -7750,7 +7750,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-script-traits" name = "servo-script-traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"accesskit", "accesskit",
"content-security-policy", "content-security-policy",
@ -7787,7 +7787,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-storage" name = "servo-storage"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"libc", "libc",
"log", "log",
@ -7817,7 +7817,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-storage-traits" name = "servo-storage-traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"malloc_size_of_derive", "malloc_size_of_derive",
"serde", "serde",
@ -7831,7 +7831,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-timers" name = "servo-timers"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"crossbeam-channel", "crossbeam-channel",
"malloc_size_of_derive", "malloc_size_of_derive",
@ -7841,7 +7841,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-tracing" name = "servo-tracing"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -7851,7 +7851,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-url" name = "servo-url"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"encoding_rs", "encoding_rs",
"malloc_size_of_derive", "malloc_size_of_derive",
@ -7865,7 +7865,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-webgl" name = "servo-webgl"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"bitflags 2.11.0", "bitflags 2.11.0",
"byteorder", "byteorder",
@ -7889,7 +7889,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-webgpu" name = "servo-webgpu"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"arrayvec", "arrayvec",
"euclid", "euclid",
@ -7908,7 +7908,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-webgpu-traits" name = "servo-webgpu-traits"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"arrayvec", "arrayvec",
"malloc_size_of_derive", "malloc_size_of_derive",
@ -7924,7 +7924,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-webxr" name = "servo-webxr"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"crossbeam-channel", "crossbeam-channel",
"euclid", "euclid",
@ -7943,7 +7943,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-webxr-api" name = "servo-webxr-api"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"euclid", "euclid",
"ipc-channel", "ipc-channel",
@ -7959,7 +7959,7 @@ dependencies = [
[[package]] [[package]]
name = "servo-xpath" name = "servo-xpath"
version = "0.0.1" version = "0.0.1"
source = "git+https://github.com/marcoallegretti/servo?branch=servo-weft#8e7dc40bff42448980b7249798f17e3131547138" source = "git+https://github.com/marcoallegretti/servo?rev=f0bb1aaf981b65c8dddc848bb647045d4c777d11#f0bb1aaf981b65c8dddc848bb647045d4c777d11"
dependencies = [ dependencies = [
"log", "log",
"malloc_size_of_derive", "malloc_size_of_derive",
@ -7970,7 +7970,7 @@ dependencies = [
[[package]] [[package]]
name = "servo_arc" name = "servo_arc"
version = "0.4.3" version = "0.4.3"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a" source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [ dependencies = [
"serde", "serde",
"stable_deref_trait", "stable_deref_trait",
@ -8396,7 +8396,7 @@ dependencies = [
[[package]] [[package]]
name = "stylo" name = "stylo"
version = "0.13.0" version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a" source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [ dependencies = [
"app_units", "app_units",
"arrayvec", "arrayvec",
@ -8452,7 +8452,7 @@ dependencies = [
[[package]] [[package]]
name = "stylo_atoms" name = "stylo_atoms"
version = "0.13.0" version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a" source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [ dependencies = [
"string_cache", "string_cache",
"string_cache_codegen", "string_cache_codegen",
@ -8461,7 +8461,7 @@ dependencies = [
[[package]] [[package]]
name = "stylo_derive" name = "stylo_derive"
version = "0.13.0" version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a" source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [ dependencies = [
"darling", "darling",
"proc-macro2", "proc-macro2",
@ -8473,7 +8473,7 @@ dependencies = [
[[package]] [[package]]
name = "stylo_dom" name = "stylo_dom"
version = "0.13.0" version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a" source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [ dependencies = [
"bitflags 2.11.0", "bitflags 2.11.0",
"stylo_malloc_size_of", "stylo_malloc_size_of",
@ -8482,7 +8482,7 @@ dependencies = [
[[package]] [[package]]
name = "stylo_malloc_size_of" name = "stylo_malloc_size_of"
version = "0.13.0" version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a" source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [ dependencies = [
"app_units", "app_units",
"cssparser", "cssparser",
@ -8499,12 +8499,12 @@ dependencies = [
[[package]] [[package]]
name = "stylo_static_prefs" name = "stylo_static_prefs"
version = "0.13.0" version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a" source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
[[package]] [[package]]
name = "stylo_traits" name = "stylo_traits"
version = "0.13.0" version = "0.13.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a" source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [ dependencies = [
"app_units", "app_units",
"bitflags 2.11.0", "bitflags 2.11.0",
@ -8904,7 +8904,7 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]] [[package]]
name = "to_shmem" name = "to_shmem"
version = "0.3.0" version = "0.3.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a" source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [ dependencies = [
"cssparser", "cssparser",
"servo_arc", "servo_arc",
@ -8917,7 +8917,7 @@ dependencies = [
[[package]] [[package]]
name = "to_shmem_derive" name = "to_shmem_derive"
version = "0.1.0" version = "0.1.0"
source = "git+https://github.com/servo/stylo?rev=dca3934667dae76c49bb579b268c5eb142d09c6a#dca3934667dae76c49bb579b268c5eb142d09c6a" source = "git+https://github.com/marcoallegretti/stylo?rev=f1ba4969536d63f2e319a561e466c03e78b4a076#f1ba4969536d63f2e319a561e466c03e78b4a076"
dependencies = [ dependencies = [
"darling", "darling",
"proc-macro2", "proc-macro2",

View file

@ -24,3 +24,17 @@ rust-version = "1.93"
[workspace.lints.rust] [workspace.lints.rust]
unsafe_code = "forbid" unsafe_code = "forbid"
# Servo's own [patch] tables do not apply to dependents. The servo fork's
# backdrop-filter support needs the stylo fork that removes the property's
# `layout.unimplemented` gate, so the override lives here. Remove it once the
# change is available from upstream stylo at the revision Servo selects.
[patch."https://github.com/servo/stylo"]
selectors = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
servo_arc = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo_atoms = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo_dom = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo_malloc_size_of = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo_static_prefs = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }
stylo_traits = { git = "https://github.com/marcoallegretti/stylo", rev = "f1ba4969536d63f2e319a561e466c03e78b4a076" }

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. **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`. **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`.
@ -77,7 +77,7 @@ See `docs/building.md` for full instructions including Wasm component builds, Ni
Four jobs on every push to `main` and on pull requests: Four jobs on every push to `main` and on pull requests:
- `cross-platform` — fmt, clippy, tests on Ubuntu and Windows - `portable` — fmt, clippy and tests for the crates that need no Linux system libraries
- `linux-only` — clippy and tests for compositor and shell crates - `linux-only` — clippy and tests for compositor and shell crates
- `servo-embed-linux` — `cargo check --features servo-embed` for both servo crates - `servo-embed-linux` — `cargo check --features servo-embed` for both servo crates
- `contributor-toolkit` — links, metadata and catalog of the contributor toolkit, and runner tests - `contributor-toolkit` — links, metadata and catalog of the contributor toolkit, and runner tests
@ -95,9 +95,9 @@ See `docs/security.md`. Key points:
## Servo fork ## Servo fork
- Repository: `https://github.com/marcoallegretti/servo`, branch `servo-weft` - Servo: `https://github.com/marcoallegretti/servo` at `f0bb1aaf`, pinned by revision
- Base revision: `04ca254f` - Stylo: `https://github.com/marcoallegretti/stylo` at `f1ba4969`, through the root `[patch]`
- Patches: keyboard input, backdrop-filter in stylo - Patches: `backdrop-filter` parsing (Stylo) and rendering (Servo)
- See `crates/weft-servo-shell/SERVO_PIN.md` for Servo integration status and known limitations - See `crates/weft-servo-shell/SERVO_PIN.md` for Servo integration status and known limitations
## Contributing ## Contributing

View file

@ -27,7 +27,7 @@ toml = { version = "0.8", optional = true }
[dependencies.servo] [dependencies.servo]
git = "https://github.com/marcoallegretti/servo" git = "https://github.com/marcoallegretti/servo"
branch = "servo-weft" rev = "f0bb1aaf981b65c8dddc848bb647045d4c777d11"
optional = true optional = true
default-features = false default-features = false

View file

@ -1,20 +1,22 @@
#![cfg(feature = "servo-embed")] use std::num::NonZeroU32;
use std::path::PathBuf; use std::path::PathBuf;
use std::rc::Rc; use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use servo::{ use servo::{
EventLoopWaker, InputEvent, MouseButton as ServoMouseButton, MouseButtonAction, DeviceIntRect, DeviceIntSize, DevicePoint, EventLoopWaker, InputEvent, LoadStatus,
MouseButtonEvent, MouseMoveEvent, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager, MouseButton as ServoMouseButton, MouseButtonAction, MouseButtonEvent, MouseMoveEvent,
RenderingContext, RgbaImage, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager,
UserScript, WebViewBuilder, WebViewDelegate, UserScript, WebViewBuilder, WebViewDelegate,
}; };
use winit::{ use winit::{
application::ApplicationHandler, application::ApplicationHandler,
dpi::PhysicalSize,
event::{ElementState, MouseButton, WindowEvent}, event::{ElementState, MouseButton, WindowEvent},
event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy}, event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
keyboard::ModifiersState, keyboard::ModifiersState,
platform::wayland::{ActiveEventLoopExtWayland, WindowExtWayland}, raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle},
window::{Window, WindowAttributes, WindowId}, 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 { struct WeftWebViewDelegate {
redraw_requested: Arc<std::sync::atomic::AtomicBool>, signals: Arc<FrameSignals>,
} }
impl WebViewDelegate for WeftWebViewDelegate { impl WebViewDelegate for WeftWebViewDelegate {
fn notify_new_frame_ready(&self, _webview: servo::WebView) { fn notify_new_frame_ready(&self, _webview: servo::WebView) {
self.redraw_requested self.signals.content.store(true, Ordering::Relaxed);
.store(true, std::sync::atomic::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 { 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>), Egl(Rc<servo::WindowRenderingContext>),
} }
impl RenderingCtx { impl RenderingCtx {
fn as_dyn(&self) -> Rc<dyn servo::RenderingContext> { fn as_dyn(&self) -> Rc<dyn RenderingContext> {
match self { match self {
Self::Software(rc) => Rc::clone(rc) as Rc<dyn servo::RenderingContext>, Self::Software { context, .. } => Rc::clone(context) as Rc<dyn RenderingContext>,
Self::Egl(rc) => Rc::clone(rc) as Rc<dyn servo::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 { struct App {
@ -82,12 +188,12 @@ struct App {
servo: Option<servo::Servo>, servo: Option<servo::Servo>,
webview: Option<servo::WebView>, webview: Option<servo::WebView>,
rendering_context: Option<RenderingCtx>, rendering_context: Option<RenderingCtx>,
redraw_requested: Arc<std::sync::atomic::AtomicBool>, signals: Arc<FrameSignals>,
waker: WeftEventLoopWaker, waker: WeftEventLoopWaker,
shutting_down: bool, shutting_down: bool,
ready_signalled: bool, ready_signalled: bool,
modifiers: ModifiersState, modifiers: ModifiersState,
cursor_pos: servo::euclid::default::Point2D<f32>, cursor_pos: DevicePoint,
shell_client: Option<crate::shell_client::ShellClient>, shell_client: Option<crate::shell_client::ShellClient>,
} }
@ -108,47 +214,46 @@ impl App {
servo: None, servo: None,
webview: None, webview: None,
rendering_context: None, rendering_context: None,
redraw_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)), signals: Arc::default(),
waker, waker,
shutting_down: false, shutting_down: false,
ready_signalled: false, ready_signalled: false,
modifiers: ModifiersState::default(), modifiers: ModifiersState::default(),
cursor_pos: servo::euclid::default::Point2D::zero(), cursor_pos: DevicePoint::origin(),
shell_client: None, shell_client: None,
} }
} }
fn render_frame(window: &Arc<Window>, ctx: &RenderingCtx) { /// Paints and presents once Servo has requested its first repaint.
match ctx { ///
RenderingCtx::Software(rc) => Self::blit_software(window, rc), /// Nothing is presented before that request; the first frames can still be
RenderingCtx::Egl(_) => {} /// 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) { /// Drops the webview and Servo; dropping the last `Servo` handle shuts it down.
let size = window.inner_size(); fn shut_down(&mut self) {
let Some(pixels) = rendering_context.read_pixels() else { self.shutting_down = true;
return; self.webview = None;
}; self.servo = None;
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();
} }
} }
@ -171,9 +276,8 @@ impl ApplicationHandler<ServoWake> for App {
let size = window.inner_size(); let size = window.inner_size();
self.window = Some(Arc::clone(&window)); self.window = Some(Arc::clone(&window));
if self.shell_client.is_none() { if self.shell_client.is_none()
if let (Some(disp), Some(surf)) = && let Some((disp, surf)) = wayland_handles(event_loop, &window)
(event_loop.wayland_display(), window.wayland_surface())
{ {
match crate::shell_client::ShellClient::connect_as_app_with_display( match crate::shell_client::ShellClient::connect_as_app_with_display(
&self.app_id, &self.app_id,
@ -185,9 +289,9 @@ impl ApplicationHandler<ServoWake> for App {
Err(e) => tracing::warn!(error = %e, "shell protocol unavailable"), Err(e) => tracing::warn!(error = %e, "shell protocol unavailable"),
} }
} }
}
let servo = ServoBuilder::default() let servo = ServoBuilder::default()
.preferences(host_preferences())
.event_loop_waker(Box::new(self.waker.clone())) .event_loop_waker(Box::new(self.waker.clone()))
.build(); .build();
@ -212,22 +316,15 @@ impl ApplicationHandler<ServoWake> for App {
let webview = WebViewBuilder::new(&servo, rendering_context.as_dyn()) let webview = WebViewBuilder::new(&servo, rendering_context.as_dyn())
.delegate(Rc::new(WeftWebViewDelegate { .delegate(Rc::new(WeftWebViewDelegate {
redraw_requested: Arc::clone(&self.redraw_requested), signals: Arc::clone(&self.signals),
})) }))
.user_content_manager(ucm) .user_content_manager(ucm)
.url(self.url.clone()) .url(self.url.clone().into_url())
.build(); .build();
self.servo = Some(servo); self.servo = Some(servo);
self.webview = Some(webview); self.webview = Some(webview);
self.rendering_context = Some(rendering_context); 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) { fn user_event(&mut self, _event_loop: &ActiveEventLoop, _event: ServoWake) {
@ -241,30 +338,28 @@ impl ApplicationHandler<ServoWake> for App {
event_loop.exit(); event_loop.exit();
return; return;
} }
let mut compositor_closed = false;
if let Some(sc) = &mut self.shell_client { if let Some(sc) = &mut self.shell_client {
match sc.dispatch_pending() { match sc.dispatch_pending() {
Ok(false) => { Ok(false) => compositor_closed = true,
self.shutting_down = true;
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
}
Err(e) => tracing::warn!("shell client dispatch error: {e}"), Err(e) => tracing::warn!("shell client dispatch error: {e}"),
Ok(true) => {} Ok(true) => {}
} }
} }
if compositor_closed {
self.shut_down();
event_loop.exit();
return;
}
if let Some(servo) = &self.servo { if let Some(servo) = &self.servo {
servo.spin_event_loop(); servo.spin_event_loop();
} }
if self if self.signals.redraw.swap(false, Ordering::Relaxed)
.redraw_requested && let Some(w) = &self.window
.swap(false, std::sync::atomic::Ordering::Relaxed)
{ {
if let Some(w) = &self.window {
w.request_redraw(); w.request_redraw();
} }
} }
}
fn window_event( fn window_event(
&mut self, &mut self,
@ -273,18 +368,13 @@ impl ApplicationHandler<ServoWake> for App {
event: WindowEvent, event: WindowEvent,
) { ) {
match event { match event {
WindowEvent::RedrawRequested => { WindowEvent::RedrawRequested => self.render_frame(),
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::Resized(new_size) => { 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 { if let Some(wv) = &self.webview {
wv.resize(sz); wv.resize(new_size);
} }
} }
WindowEvent::ModifiersChanged(mods) => { WindowEvent::ModifiersChanged(mods) => {
@ -297,10 +387,11 @@ impl ApplicationHandler<ServoWake> for App {
} }
} }
WindowEvent::CursorMoved { position, .. } => { 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; self.cursor_pos = pt;
if let Some(wv) = &self.webview { 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, .. } => { WindowEvent::MouseInput { state, button, .. } => {
@ -311,22 +402,19 @@ impl ApplicationHandler<ServoWake> for App {
_ => return, _ => return,
}; };
let action = match state { let action = match state {
ElementState::Pressed => MouseButtonAction::Click, ElementState::Pressed => MouseButtonAction::Down,
ElementState::Released => MouseButtonAction::Up, ElementState::Released => MouseButtonAction::Up,
}; };
if let Some(wv) = &self.webview { if let Some(wv) = &self.webview {
let _ = wv.notify_input_event(InputEvent::MouseButton(MouseButtonEvent::new( let _ = wv.notify_input_event(InputEvent::MouseButton(MouseButtonEvent::new(
action, action,
btn, btn,
self.cursor_pos.cast_unit(), self.cursor_pos.into(),
))); )));
} }
} }
WindowEvent::CloseRequested => { WindowEvent::CloseRequested => {
self.shutting_down = true; self.shut_down();
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
event_loop.exit(); event_loop.exit();
} }
_ => {} _ => {}
@ -337,7 +425,7 @@ impl ApplicationHandler<ServoWake> for App {
fn build_rendering_ctx( fn build_rendering_ctx(
event_loop: &ActiveEventLoop, event_loop: &ActiveEventLoop,
window: &Arc<Window>, window: &Arc<Window>,
size: winit::dpi::PhysicalSize<u32>, size: PhysicalSize<u32>,
) -> Option<RenderingCtx> { ) -> Option<RenderingCtx> {
if std::env::var_os("WEFT_EGL_RENDERING").is_some() { if std::env::var_os("WEFT_EGL_RENDERING").is_some() {
let display_handle = event_loop.display_handle(); let display_handle = event_loop.display_handle();
@ -349,16 +437,26 @@ fn build_rendering_ctx(
return Some(RenderingCtx::Egl(Rc::new(rc))); return Some(RenderingCtx::Egl(Rc::new(rc)));
} }
Err(e) => { 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)) let context = match servo::SoftwareRenderingContext::new(size) {
{ Ok(rc) => Rc::new(rc),
Ok(rc) => Some(RenderingCtx::Software(Rc::new(rc))),
Err(e) => { 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 None
} }
} }

View file

@ -1,5 +1,3 @@
#![cfg(feature = "servo-embed")]
use servo::{Code, Key, KeyState, KeyboardEvent, Location, Modifiers}; use servo::{Code, Key, KeyState, KeyboardEvent, Location, Modifiers};
use winit::event::ElementState; use winit::event::ElementState;
use winit::keyboard::{Key as WinitKey, KeyLocation, ModifiersState, NamedKey, PhysicalKey}; 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 { let key = match &event.logical_key {
WinitKey::Named(NamedKey::Space) => Key::Character(" ".to_string()),
WinitKey::Named(n) => Key::Named(named_key(*n)), WinitKey::Named(n) => Key::Named(named_key(*n)),
WinitKey::Character(c) => Key::Character(c.to_string().into()), WinitKey::Character(c) => Key::Character(c.to_string()),
WinitKey::Unidentified(_) => Key::Unidentified, WinitKey::Unidentified(_) => Key::Named(servo::NamedKey::Unidentified),
WinitKey::Dead(c) => Key::Dead(*c), WinitKey::Dead(_) => Key::Named(servo::NamedKey::Dead),
}; };
let code = match event.physical_key { let code = match event.physical_key {
@ -46,15 +45,7 @@ pub fn keyboard_event_from_winit(
mods |= Modifiers::META; mods |= Modifiers::META;
} }
KeyboardEvent { KeyboardEvent::new_without_event(state, key, code, location, mods, event.repeat, false)
state,
key,
code,
location,
modifiers: mods,
repeat: event.repeat,
is_composing: false,
}
} }
fn named_key(n: NamedKey) -> servo::NamedKey { fn named_key(n: NamedKey) -> servo::NamedKey {
@ -74,7 +65,6 @@ fn named_key(n: NamedKey) -> servo::NamedKey {
NamedKey::SymbolLock => S::SymbolLock, NamedKey::SymbolLock => S::SymbolLock,
NamedKey::Enter => S::Enter, NamedKey::Enter => S::Enter,
NamedKey::Tab => S::Tab, NamedKey::Tab => S::Tab,
NamedKey::Space => S::Space,
NamedKey::ArrowDown => S::ArrowDown, NamedKey::ArrowDown => S::ArrowDown,
NamedKey::ArrowLeft => S::ArrowLeft, NamedKey::ArrowLeft => S::ArrowLeft,
NamedKey::ArrowRight => S::ArrowRight, 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"))] #[cfg(not(feature = "servo-embed"))]
{ {
let _ = (app_id, session_id, ws_port); let _ = (app_id, session_id, ws_port);
println!("READY"); anyhow::bail!("weft-app-shell was built without the servo-embed feature and cannot render")
use std::io::Write;
let _ = std::io::stdout().flush();
std::thread::park();
Ok(())
} }
} }

View file

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

View file

@ -70,6 +70,22 @@ pub(crate) async fn spawn_ipc_relay(
const READY_TIMEOUT: Duration = Duration::from_secs(30); const READY_TIMEOUT: Duration = Duration::from_secs(30);
/// `systemd-run` options that place the runtime in a transient user scope.
///
/// A scope runs the command in the foreground as systemd-run's own process,
/// so its stdout and exit status reach appd directly. `--wait` only applies
/// to service units; systemd rejects it together with `--scope`.
const SYSTEMD_SCOPE_ARGS: &[&str] = &[
"--user",
"--scope",
"--collect",
"--slice=weft-apps.slice",
"-p",
"CPUQuota=200%",
"-p",
"MemoryMax=512M",
];
fn systemd_cgroup_available() -> bool { fn systemd_cgroup_available() -> bool {
if std::env::var("WEFT_DISABLE_CGROUP").is_ok() { if std::env::var("WEFT_DISABLE_CGROUP").is_ok() {
return false; return false;
@ -240,19 +256,7 @@ pub(crate) async fn supervise(
let mut cmd = if systemd_cgroup_available() { let mut cmd = if systemd_cgroup_available() {
let mut c = tokio::process::Command::new("systemd-run"); let mut c = tokio::process::Command::new("systemd-run");
c.args([ c.args(SYSTEMD_SCOPE_ARGS).arg("--").arg(&bin);
"--user",
"--scope",
"--wait",
"--collect",
"--slice=weft-apps.slice",
"-p",
"CPUQuota=200%",
"-p",
"MemoryMax=512M",
"--",
&bin,
]);
c c
} else { } else {
tokio::process::Command::new(&bin) tokio::process::Command::new(&bin)
@ -437,3 +441,41 @@ async fn drain_stderr(stderr: tokio::process::ChildStderr, session_id: u64) {
tracing::warn!(session_id, stderr = %line, "app stderr"); tracing::warn!(session_id, stderr = %line, "app stderr");
} }
} }
#[cfg(all(test, target_os = "linux"))]
mod tests {
use super::SYSTEMD_SCOPE_ARGS;
/// systemd-run checks its options and their combinations before it
/// connects to the service manager. Run against an empty runtime
/// directory and bus address, it must get as far as the connection
/// attempt; any option error ends earlier with a different message. This
/// does not validate the `-p` property values, which only the manager
/// checks, and never starts a real scope.
#[test]
fn systemd_run_accepts_scope_options() {
let empty = std::env::temp_dir().join(format!("weft-scope-test-{}", std::process::id()));
std::fs::create_dir_all(&empty).unwrap();
let output = std::process::Command::new("systemd-run")
.args(SYSTEMD_SCOPE_ARGS)
.args(["--", "true"])
.env_clear()
.env("PATH", std::env::var_os("PATH").unwrap_or_default())
.env("LC_ALL", "C")
.env("XDG_RUNTIME_DIR", &empty)
.env(
"DBUS_SESSION_BUS_ADDRESS",
format!("unix:path={}/bus", empty.display()),
)
.output();
std::fs::remove_dir_all(&empty).unwrap();
let output = output.expect("systemd-run is required to check the scope options");
let stderr = String::from_utf8_lossy(&output.stderr);
// systemd 255 says "Failed to connect to bus"; later releases name the
// transport, e.g. "Failed to connect to user scope bus via local transport".
assert!(
stderr.starts_with("Failed to connect to"),
"systemd-run did not reach the manager connection: {stderr}"
);
}
}

View file

@ -157,11 +157,9 @@ pub fn run() -> anyhow::Result<()> {
false false
} }
}; };
if render_ok { if render_ok && let Err(e) = backend.submit(Some(&[full_damage])) {
if let Err(e) = backend.submit(Some(&[full_damage])) {
tracing::warn!(?e, "backend submit failed"); tracing::warn!(?e, "backend submit failed");
} }
}
state.space.elements().for_each(|window| { state.space.elements().for_each(|window| {
window.send_frame( window.send_frame(

View file

@ -27,7 +27,7 @@ tungstenite = "0.24"
[dependencies.servo] [dependencies.servo]
git = "https://github.com/marcoallegretti/servo" git = "https://github.com/marcoallegretti/servo"
branch = "servo-weft" rev = "f0bb1aaf981b65c8dddc848bb647045d4c777d11"
optional = true optional = true
default-features = false default-features = false

View file

@ -2,13 +2,25 @@
## Current pin ## Current pin
| Field | Value | The selected revisions are the ones recorded in the workspace `Cargo.lock`.
|---------|------------------------------------------------------------------------------------|
| Source | <https://github.com/marcoallegretti/servo> (fork of servo/servo) | | Dependency | Source | Revision | Selected by |
| Branch | `servo-weft` | |------------|--------|----------|-------------|
| Rev | `04ca254f843ed650d3e5b14e5693ad51a60cc84b` (servo-weft tip, 2026-03-11) | | Servo (`servo` crate) | <https://github.com/marcoallegretti/servo> | `f0bb1aaf981b65c8dddc848bb647045d4c777d11` | `rev` in both shell crates' `Cargo.toml` |
| Crate | `servo` (package name as of 2026-03-11; previously `libservo`) | | Stylo (`stylo`, `selectors`, `servo_arc`, ...) | <https://github.com/marcoallegretti/stylo> | `f1ba4969536d63f2e319a561e466c03e78b4a076` | `[patch."https://github.com/servo/stylo"]` in the root `Cargo.toml` |
| Feature | `servo-embed` (optional; off by default) |
The Servo revision is `servo-weft` commit `8e7dc40` (backdrop-filter rendering)
plus `f0bb1aa`, which fixes that commit's `servo-layout` build errors. It lives
on the fork branch `fix/backdrop-filter-build-errors` until it is merged into
`servo-weft`; keep that branch until then so the revision stays fetchable.
Servo's own `[patch]` table for Stylo does not apply to WEFT, because Cargo
only honours patches in the root workspace. Without the root override, WEFT
resolves upstream Stylo `dca3934`, where `backdrop-filter` is still gated
behind `layout.unimplemented`. Remove the override once the selected Servo
revision depends on a Stylo that parses the property for Servo.
The feature is `servo-embed` (optional; off by default).
## Cargo dependencies ## Cargo dependencies
@ -25,7 +37,7 @@ servo-embed = ["dep:servo", "dep:winit", "dep:softbuffer"]
[dependencies.servo] [dependencies.servo]
git = "https://github.com/marcoallegretti/servo" git = "https://github.com/marcoallegretti/servo"
branch = "servo-weft" rev = "f0bb1aaf981b65c8dddc848bb647045d4c777d11"
optional = true optional = true
default-features = false default-features = false
@ -63,84 +75,110 @@ Install with: `sudo zypper install -y libglvnd-devel libopenssl-devel dbus-1-dev
## Rendering approach ## Rendering approach
Default: `SoftwareRenderingContext` (CPU rasterisation) blitted to a Each frame is painted with `WebView::paint` and then presented:
`softbuffer`-backed winit window.
EGL path: set `WEFT_EGL_RENDERING=1` at runtime. The embedder attempts - **Software (default):** Servo renders into a `SoftwareRenderingContext`.
`WindowRenderingContext::new` using the winit display and window handles. The host reads the painted frame back with `read_to_image`, presents the
If construction fails it falls back to software automatically. context and copies the pixels into a persistent `softbuffer` surface on the
When the EGL path is active Servo presents directly to the EGL surface via winit window.
surfman's `eglSwapBuffers`; the softbuffer blit is skipped. Mesa handles - **EGL:** with `WEFT_EGL_RENDERING=1` the host creates a
DMA-BUF buffer sharing with the compositor transparently. `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 ## Known limitations at this pin
- **Wayland input events**: ~~not forwarded to Servo~~ **Resolved** — keyboard and Status is stated against executed evidence; code that exists but has not been
mouse events forwarded via `webview.notify_input_event`; key mapping in `keyutils.rs`. exercised is listed as unverified.
- **Wayland surface sharing**: ~~`ZweftShellWindowV1` created with `surface = null`~~ **Resolved** —
`ShellClient::connect_with_display(display_ptr, surface_ptr)` uses - **Verified rendering path:** both hosts present the reference page through
`Backend::from_foreign_display` to share winit's `wl_display` connection; the winit `weft-compositor`'s winit backend on Xvfb with Mesa 25.2.8 llvmpipe, using
`wl_surface` pointer is passed directly to `create_window`, associating the compositor the software path (Ubuntu 24.04, x86_64; `check_frame.py --host system`,
shell slot with the actual rendered surface. `ShellClient` is now constructed inside `--host app` and `--host app --slow-style 3`, five runs each). The EGL path,
`resumed()` after the winit window exists, not before the event loop. EGL path and DRM sessions, resize, output scale and idle wakeup are unverified.
per-frame event dispatch are unchanged. - **Input:** `tests/frame/check_input.py` verifies, on the same nested
Protocol note: `wayland-scanner 0.31` generates `_type` (not `r#type`) for the setup, that left clicks 6 px either side of a boundary reach the element
`navigation_gesture` event arg named `type`. under the pointer, and that `a` and `Shift+a` key presses reach the page with
- **WebGPU on Mesa**: adapter may fail CTS — validation task, requires Mesa GPU hardware. the right key value and modifier, using real X input that `weft-compositor`
- **CSS layout features**: ~~CSS Grid~~ **Grid resolved** (Taffy-backed, fully wired). routes to `weft-servo-shell` (three runs). The harness gives the compositor's
~~CSS `backdrop-filter` unimplemented~~ **`backdrop-filter` resolved** (servo/servo issue X window input focus, as a window manager would; the client's keyboard focus
[#41567](https://github.com/servo/servo/issues/41567)). Implemented across two commits: comes from the compositor's click-to-focus. Unverified: key release and
- `marcoallegretti/stylo` `servo-weft` `f1ba496`: removed `servo_pref = "layout.unimplemented"` repeat, pointer motion, enter/leave and button release events, other buttons,
from `backdrop-filter` in `style/properties/longhands.toml` (enables parsing). wheel, focus loss, non-US layouts, non-ASCII text, scale changes and
- `marcoallegretti/servo` `servo-weft` `8e7dc40`: `Cargo.toml` patched to use the stylo fork; `weft-app-shell` input.
`style_ext.rs` adds `backdrop-filter` to `establishes_stacking_context` and - **`backdrop-filter`**: the parsing (Stylo `f1ba496`) and rendering (Servo
`establishes_containing_block_for_all_descendants`; `stacking_context.rs` guards the `8e7dc40`, `f0bb1aa`) patches are selected by the lockfile; rendering is
WebRender stacking-context early-return on `backdrop_filter.0.is_empty()`; `display_list/mod.rs` unverified.
adds `BuilderForBoxFragment::build_backdrop_filter` calling `push_backdrop_filter` before - **Resources:** the hosts install no Servo resource reader, so Servo logs
background paint. `Resource reader not set` and uses empty resources: the public suffix list,
- **Per-app process isolation**: ~~not implemented~~ **Resolved** — each app runs in a separate HSTS preload list, Bluetooth blocklist, certificate and network error pages,
`weft-app-shell` and `weft-runtime` OS process pair supervised by `weft-appd`. OS-level crash and directory-listing pages and media controls. Servo falls back to its
isolation does not require Servo's multi-process constellation architecture. built-in placeholder image.
- **SpiderMonkey sandbox**: SpiderMonkey is not sandbox-isolated beyond process-level isolation. - **Window decorations:** `weft-compositor` offers no server-side decorations,
JIT-compiled JS runs with the same memory permissions as the Servo process. WEFT relies on so winit draws a client-side title bar on both hosts' windows, including the
SpiderMonkey's own security properties for the JavaScript execution boundary. See system panel.
`docs/security.md` for the full bounded statement. Not addressed. - **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.
- **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
do not confine the renderer; see `docs/security.md`.
- **SpiderMonkey**: JIT-compiled JavaScript runs with the Servo process's
permissions; WEFT relies on SpiderMonkey's own security properties for the
JavaScript boundary. See `docs/security.md`.
## Update policy ## Update policy
The `servo-weft` branch is the working branch for WEFT-specific Servo patches. `servo-weft` in `marcoallegretti/servo` and `servo-weft` in
Upstream servo/servo changes are merged into it periodically. `marcoallegretti/stylo` carry WEFT-specific patches. WEFT pins exact revisions
rather than tracking a branch, so a rebuild selects the same code. A pinned
revision must stay reachable from a published branch: never force-push,
rebase or delete a branch that contains a revision a WEFT lockfile selects.
Today Servo `f0bb1aa` is reachable only from `fix/backdrop-filter-build-errors`
and Stylo `f1ba496` only from Stylo's `servo-weft`.
To rebase onto a new upstream commit: To move to new revisions:
1. In the `marcoallegretti/servo` repo: `git fetch upstream && git rebase upstream/main` on `servo-weft`. 1. Land the Servo or Stylo change on the fork and note its commit.
2. Force-push `servo-weft`. 2. Update the `rev` values in `crates/weft-servo-shell/Cargo.toml`,
3. Update `Rev` in this file to the new tip SHA. `crates/weft-app-shell/Cargo.toml` and, for Stylo, the root `[patch]`.
4. Run `cargo update -p servo` in the WEFT OS workspace. 3. Run `cargo update -p servo` (and `cargo update -p stylo` for a Stylo-only change).
5. Confirm the compositor and shell tests still pass. 4. Confirm with `grep -A2 'name = "servo"' Cargo.lock` and
`grep -A2 'name = "stylo"' Cargo.lock` that the lockfile selects them, that
`cargo metadata --locked` succeeds, and that `grep -c servo/stylo Cargo.lock`
prints `0`, which shows the override applies to every Stylo crate.
5. Recompute the `outputHashes` in `infra/nixos/weft-packages.nix` for each
changed git source.
6. Run `cargo check -p weft-servo-shell --features servo-embed --locked` and
`cargo check -p weft-app-shell --features servo-embed --locked`, plus the
rendering checks for any behavior the change claims, and update the tables
in this file.
To submit patches upstream: open a PR from `servo-weft` (or a topic branch) to `servo/servo`. Each fork patch keeps its purpose, upstream status and removal condition here.
## Stylo fork | Patch | Fork commit | Purpose | Upstream status | Remove when |
|-------|-------------|---------|-----------------|-------------|
The Stylo CSS engine is a separate repo (`servo/stylo`) pinned at rev `dca3934667dae76c49bb579b268c5eb142d09c6a` | Stylo: parse `backdrop-filter` for Servo | stylo `f1ba496` | Remove the `layout.unimplemented` gate | Not submitted | Upstream Stylo parses it for Servo |
in `Cargo.toml`. To patch it for WEFT-specific changes (e.g. enabling `backdrop-filter`): | Servo: render `backdrop-filter` | servo `8e7dc40` | Stacking context and display list support | servo/servo issue [#41567](https://github.com/servo/servo/issues/41567) | Equivalent upstream support |
| Servo: fix `build_backdrop_filter` types | servo `f0bb1aa` | Make `servo-layout` compile | Part of the patch above | Same as above |
1. Fork `servo/stylo` to `marcoallegretti/stylo`, create branch `servo-weft`.
2. Make changes on that branch.
3. Add to this fork's `Cargo.toml` workspace `[patch]` section:
```toml
[patch."https://github.com/servo/stylo"]
stylo = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
stylo_atoms = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
stylo_dom = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
stylo_malloc_size_of = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
stylo_static_prefs = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
stylo_traits = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
selectors = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
servo_arc = { git = "https://github.com/marcoallegretti/stylo", branch = "servo-weft" }
```
1. Run `cargo update` to resolve the new stylo deps.
2. Commit both the `Cargo.toml` and `Cargo.lock` changes to `servo-weft`.

View file

@ -1,20 +1,22 @@
#![cfg(feature = "servo-embed")] use std::num::NonZeroU32;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::rc::Rc; use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use servo::{ use servo::{
EventLoopWaker, InputEvent, MouseButton as ServoMouseButton, MouseButtonAction, DeviceIntRect, DeviceIntSize, DevicePoint, EventLoopWaker, InputEvent,
MouseButtonEvent, MouseMoveEvent, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager, MouseButton as ServoMouseButton, MouseButtonAction, MouseButtonEvent, MouseMoveEvent,
RenderingContext, RgbaImage, ServoBuilder, ServoDelegate, ServoUrl, UserContentManager,
UserScript, WebViewBuilder, WebViewDelegate, UserScript, WebViewBuilder, WebViewDelegate,
}; };
use winit::{ use winit::{
application::ApplicationHandler, application::ApplicationHandler,
dpi::PhysicalSize,
event::{ElementState, MouseButton, WindowEvent}, event::{ElementState, MouseButton, WindowEvent},
event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy}, event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
keyboard::ModifiersState, keyboard::ModifiersState,
platform::wayland::{ActiveEventLoopExtWayland, WindowExtWayland}, raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle},
window::{Window, WindowAttributes, WindowId}, window::{Window, WindowAttributes, WindowId},
}; };
@ -54,31 +56,114 @@ impl ServoDelegate for WeftServoDelegate {
// ── WebView delegate ────────────────────────────────────────────────────────── // ── 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 { struct WeftWebViewDelegate {
redraw_requested: Arc<std::sync::atomic::AtomicBool>, signals: Arc<FrameSignals>,
} }
impl WebViewDelegate for WeftWebViewDelegate { impl WebViewDelegate for WeftWebViewDelegate {
fn notify_new_frame_ready(&self, _webview: servo::WebView) { fn notify_new_frame_ready(&self, _webview: servo::WebView) {
self.redraw_requested self.signals.content.store(true, Ordering::Relaxed);
.store(true, std::sync::atomic::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 { 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>), Egl(Rc<servo::WindowRenderingContext>),
} }
impl RenderingCtx { impl RenderingCtx {
fn as_dyn(&self) -> Rc<dyn servo::RenderingContext> { fn as_dyn(&self) -> Rc<dyn RenderingContext> {
match self { match self {
Self::Software(rc) => Rc::clone(rc) as Rc<dyn servo::RenderingContext>, Self::Software { context, .. } => Rc::clone(context) as Rc<dyn RenderingContext>,
Self::Egl(rc) => Rc::clone(rc) as Rc<dyn servo::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 ───────────────────────────────────────────────────────── // ── Application state ─────────────────────────────────────────────────────────
@ -90,11 +175,11 @@ struct App {
servo: Option<servo::Servo>, servo: Option<servo::Servo>,
webview: Option<servo::WebView>, webview: Option<servo::WebView>,
rendering_context: Option<RenderingCtx>, rendering_context: Option<RenderingCtx>,
redraw_requested: Arc<std::sync::atomic::AtomicBool>, signals: Arc<FrameSignals>,
waker: WeftEventLoopWaker, waker: WeftEventLoopWaker,
shutting_down: bool, shutting_down: bool,
modifiers: ModifiersState, modifiers: ModifiersState,
cursor_pos: servo::euclid::default::Point2D<f32>, cursor_pos: DevicePoint,
shell_client: Option<crate::shell_client::ShellClient>, shell_client: Option<crate::shell_client::ShellClient>,
gesture_thread: Option<std::thread::JoinHandle<()>>, gesture_thread: Option<std::thread::JoinHandle<()>>,
} }
@ -108,47 +193,37 @@ impl App {
servo: None, servo: None,
webview: None, webview: None,
rendering_context: None, rendering_context: None,
redraw_requested: Arc::new(std::sync::atomic::AtomicBool::new(false)), signals: Arc::default(),
waker, waker,
shutting_down: false, shutting_down: false,
modifiers: ModifiersState::default(), modifiers: ModifiersState::default(),
cursor_pos: servo::euclid::default::Point2D::zero(), cursor_pos: DevicePoint::origin(),
shell_client: None, shell_client: None,
gesture_thread: None, gesture_thread: None,
} }
} }
fn render_frame(window: &Arc<Window>, ctx: &RenderingCtx) { /// Paints and presents once Servo has requested its first repaint.
match ctx { ///
RenderingCtx::Software(rc) => Self::blit_software(window, rc), /// Nothing is presented before that request; the first frames can still be
RenderingCtx::Egl(_) => {} /// 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) { /// Drops the webview and Servo; dropping the last `Servo` handle shuts it down.
let size = window.inner_size(); fn shut_down(&mut self) {
let Some(pixels) = rendering_context.read_pixels() else { self.shutting_down = true;
return; self.webview = None;
}; self.servo = None;
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();
} }
} }
@ -170,18 +245,17 @@ impl ApplicationHandler<ServoWake> for App {
let size = window.inner_size(); let size = window.inner_size();
self.window = Some(Arc::clone(&window)); self.window = Some(Arc::clone(&window));
if self.shell_client.is_none() { if self.shell_client.is_none()
if let (Some(disp), Some(surf)) = && let Some((disp, surf)) = wayland_handles(event_loop, &window)
(event_loop.wayland_display(), window.wayland_surface())
{ {
match crate::shell_client::ShellClient::connect_with_display(disp, surf) { match crate::shell_client::ShellClient::connect_with_display(disp, surf) {
Ok(sc) => self.shell_client = Some(sc), Ok(sc) => self.shell_client = Some(sc),
Err(e) => tracing::warn!(error = %e, "shell protocol unavailable"), Err(e) => tracing::warn!(error = %e, "shell protocol unavailable"),
} }
} }
}
let servo = ServoBuilder::default() let servo = ServoBuilder::default()
.preferences(host_preferences())
.event_loop_waker(Box::new(self.waker.clone())) .event_loop_waker(Box::new(self.waker.clone()))
.build(); .build();
@ -205,10 +279,10 @@ impl ApplicationHandler<ServoWake> for App {
let webview = WebViewBuilder::new(&servo, rendering_context.as_dyn()) let webview = WebViewBuilder::new(&servo, rendering_context.as_dyn())
.delegate(Rc::new(WeftWebViewDelegate { .delegate(Rc::new(WeftWebViewDelegate {
redraw_requested: Arc::clone(&self.redraw_requested), signals: Arc::clone(&self.signals),
})) }))
.user_content_manager(Rc::clone(&user_content_manager)) .user_content_manager(Rc::clone(&user_content_manager))
.url(self.url.clone()) .url(self.url.clone().into_url())
.build(); .build();
self.servo = Some(servo); self.servo = Some(servo);
@ -227,14 +301,10 @@ impl ApplicationHandler<ServoWake> for App {
event_loop.exit(); event_loop.exit();
return; return;
} }
let mut compositor_closed = false;
if let Some(sc) = &mut self.shell_client { if let Some(sc) = &mut self.shell_client {
match sc.dispatch_pending() { match sc.dispatch_pending() {
Ok(false) => { Ok(false) => compositor_closed = true,
self.shutting_down = true;
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
}
Err(e) => tracing::warn!("shell client dispatch error: {e}"), Err(e) => tracing::warn!("shell client dispatch error: {e}"),
Ok(true) => {} 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 { if let Some(servo) = &self.servo {
servo.spin_event_loop(); servo.spin_event_loop();
} }
if self if self.signals.redraw.swap(false, Ordering::Relaxed)
.redraw_requested && let Some(w) = &self.window
.swap(false, std::sync::atomic::Ordering::Relaxed)
{ {
if let Some(w) = &self.window {
w.request_redraw(); w.request_redraw();
} }
} }
}
fn window_event( fn window_event(
&mut self, &mut self,
@ -278,18 +350,13 @@ impl ApplicationHandler<ServoWake> for App {
event: WindowEvent, event: WindowEvent,
) { ) {
match event { match event {
WindowEvent::RedrawRequested => { WindowEvent::RedrawRequested => self.render_frame(),
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::Resized(new_size) => { 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 { if let Some(wv) = &self.webview {
wv.resize(sz); wv.resize(new_size);
} }
} }
WindowEvent::ModifiersChanged(mods) => { WindowEvent::ModifiersChanged(mods) => {
@ -302,10 +369,11 @@ impl ApplicationHandler<ServoWake> for App {
} }
} }
WindowEvent::CursorMoved { position, .. } => { 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; self.cursor_pos = pt;
if let Some(wv) = &self.webview { 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, .. } => { WindowEvent::MouseInput { state, button, .. } => {
@ -316,22 +384,19 @@ impl ApplicationHandler<ServoWake> for App {
_ => return, _ => return,
}; };
let action = match state { let action = match state {
ElementState::Pressed => MouseButtonAction::Click, ElementState::Pressed => MouseButtonAction::Down,
ElementState::Released => MouseButtonAction::Up, ElementState::Released => MouseButtonAction::Up,
}; };
if let Some(wv) = &self.webview { if let Some(wv) = &self.webview {
let _ = wv.notify_input_event(InputEvent::MouseButton(MouseButtonEvent::new( let _ = wv.notify_input_event(InputEvent::MouseButton(MouseButtonEvent::new(
action, action,
btn, btn,
self.cursor_pos.cast_unit(), self.cursor_pos.into(),
))); )));
} }
} }
WindowEvent::CloseRequested => { WindowEvent::CloseRequested => {
self.shutting_down = true; self.shut_down();
if let Some(servo) = &self.servo {
servo.start_shutting_down();
}
event_loop.exit(); event_loop.exit();
} }
_ => {} _ => {}
@ -344,7 +409,7 @@ impl ApplicationHandler<ServoWake> for App {
fn build_rendering_ctx( fn build_rendering_ctx(
event_loop: &ActiveEventLoop, event_loop: &ActiveEventLoop,
window: &Arc<Window>, window: &Arc<Window>,
size: winit::dpi::PhysicalSize<u32>, size: PhysicalSize<u32>,
) -> Option<RenderingCtx> { ) -> Option<RenderingCtx> {
if std::env::var_os("WEFT_EGL_RENDERING").is_some() { if std::env::var_os("WEFT_EGL_RENDERING").is_some() {
let display_handle = event_loop.display_handle(); let display_handle = event_loop.display_handle();
@ -356,16 +421,26 @@ fn build_rendering_ctx(
return Some(RenderingCtx::Egl(Rc::new(rc))); return Some(RenderingCtx::Egl(Rc::new(rc)));
} }
Err(e) => { 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)) let context = match servo::SoftwareRenderingContext::new(size) {
{ Ok(rc) => Rc::new(rc),
Ok(rc) => Some(RenderingCtx::Software(Rc::new(rc))),
Err(e) => { 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 None
} }
} }

View file

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

View file

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

View file

@ -2,7 +2,7 @@
## Prerequisites ## Prerequisites
Linux (x86_64 or aarch64). Building on Windows is supported for workspace validation only; runtime components require Linux kernel interfaces. Linux (x86_64 or aarch64). WEFT OS is built and validated on Linux only; runtime components require Linux kernel interfaces.
System packages (openSUSE): System packages (openSUSE):
@ -34,7 +34,7 @@ cargo build -p weft-servo-shell
cargo build -p weft-app-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) ## Servo embedding (optional, slow)
@ -43,7 +43,39 @@ cargo build -p weft-servo-shell --features servo-embed
cargo build -p weft-app-shell --features servo-embed cargo build -p weft-app-shell --features servo-embed
``` ```
This fetches and compiles the Servo fork (`github.com/marcoallegretti/servo`, branch `servo-weft`). Expect 30–60 minutes on a clean build. Servo's dependencies include SpiderMonkey (C++), which requires `clang` and `python3`. 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`.
`tests/frame/check_input.py` uses the same nested desktop to send real X
pointer and keyboard input (with `xdotool`) through `weft-compositor` to
`weft-servo-shell` showing `tests/frame/input.html`, and checks that the
page reacts to clicks on either side of a boundary and to the `a` and
`Shift+a` keys. Logs and the last capture are written to `target/input-check`.
```sh
python3 tests/frame/check_input.py
```
## Demo apps (wasm32-wasip2) ## Demo apps (wasm32-wasip2)
@ -86,13 +118,13 @@ Run with QEMU:
bash infra/vm/run.sh bash infra/vm/run.sh
``` ```
See `infra/nixos/weft-packages.nix` for the package derivations. The `outputHashes` entry for the Servo git dependency must be filled in before the `servo-embed` packages will build under Nix. See `infra/nixos/weft-packages.nix` for the package derivations. Its `outputHashes` hold one hash per git source in `Cargo.lock` (the Servo and Stylo forks); every package vendors them, so they must match the pinned revisions for any Nix package to build. The Nix shell packages do not yet enable `servo-embed`.
## CI ## CI
Four jobs run on every push to `main` and on pull requests: Four jobs run on every push to `main` and on pull requests:
- `cross-platform` — fmt, clippy, tests on Ubuntu and Windows (excludes Wayland crates) - `portable` — fmt, clippy, tests for the crates that need no Linux system libraries (excludes Wayland crates)
- `linux-only` — clippy and tests for `weft-compositor`, `weft-servo-shell`, `weft-app-shell` - `linux-only` — clippy and tests for `weft-compositor`, `weft-servo-shell`, `weft-app-shell`
- `servo-embed-linux` — `cargo check --features servo-embed` for servo-shell and app-shell - `servo-embed-linux` — `cargo check --features servo-embed` for servo-shell and app-shell
- `contributor-toolkit` — `python .agents/scripts/verify.py toolkit` - `contributor-toolkit` — `python .agents/scripts/verify.py toolkit`

View file

@ -10,9 +10,13 @@ let
cargoLock = { cargoLock = {
lockFile = ../../Cargo.lock; lockFile = ../../Cargo.lock;
# One hash per git source in Cargo.lock: the Servo fork and the Stylo fork
# (keyed by its `selectors` crate). Every package vendors both, so both must
# match the pinned revisions. Recompute them whenever a revision changes.
# The Servo hash is not yet known for f0bb1aa; a Nix build reports it.
outputHashes = { outputHashes = {
"servo-0.0.1" = "0b803qankr0rs4hi0md26dydf2cvpd6v5x2bxxypzsga0jwfdd26"; "servo-0.0.1" = pkgs.lib.fakeHash;
"selectors-0.36.0" = "1x5g61cadq700yhl1wwrjd043grlpdviqqn4n9cm5k68gbx0if81"; "selectors-0.36.0" = "13y6pa19j4w2zsxfhv6mrl03wsa0frazlsssbqkzpwci8k9gzl4i";
}; };
}; };

View file

@ -22,7 +22,7 @@ The guest is the validation target for:
## Host versus target boundary ## Host versus target boundary
The Windows host is acceptable for editing, documentation, and workspace validation. The Windows host is acceptable for editing and documentation. Builds and tests are validated on Linux only; CI does not build on Windows.
The Linux guest is authoritative for: The Linux guest is authoritative for:

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

@ -0,0 +1,221 @@
"""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; see session.py.
"""
import argparse
import http.server
import shutil
import sys
import threading
import time
from pathlib import Path
sys.dont_write_bytecode = True
from session import ROOT, Desktop, SessionError, bounding_box, missing_tools, parse_ppm # noqa: E402
HERE = Path(__file__).resolve().parent
COLORS = {
"red": (255, 0, 0),
"green": (0, 255, 0),
"blue": (0, 0, 255),
"white": (255, 255, 255),
}
MIN_SIDE = 40
MIN_TEXT_PIXELS = 30
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 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
missing = missing_tools() + [str(b) for b in (args.compositor, args.shell) if not b.is_file()]
if missing:
print("missing: " + ", ".join(missing), file=sys.stderr)
return 2
style_server = None
try:
with Desktop(args.compositor, args.output, outputs=["frame.ppm"]) as desktop:
page = args.page
if args.slow_style:
style_server = slow_style_server(args.slow_style)
page = hidden_until_styled(args.page, desktop.runtime / "page.html",
style_server.server_address[1])
if args.host == "system":
shell = desktop.launch_client(
"shell", [args.shell], {"WEFT_SYSTEM_UI_HTML": str(page.resolve())})
else:
store = install_app(desktop.runtime / "store", page)
shell = desktop.launch_client(
"shell", [args.shell, APP_ID, "1"], {"WEFT_APP_STORE": str(store)})
problems, screenshot = watch(desktop, shell, args)
except SessionError as error:
print(error, file=sys.stderr)
return 1
finally:
if style_server is not None:
style_server.shutdown()
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
def watch(desktop, shell, args):
"""Capture until the frame matches, the host exits or the time runs out."""
def ready_printed():
return any(line.strip() == "READY" for line in desktop.log_text("shell").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:
return [f"shell exited with status {shell.returncode}"], screenshot
if args.host == "app" and ready_at is None and ready_printed():
ready_at = time.monotonic()
screenshot = desktop.capture()
problems = evaluate(*parse_ppm(screenshot))
if ready_at is not None and problems and time.monotonic() - ready_at > COMPOSITE_GRACE:
return [f"page not on screen {COMPOSITE_GRACE:g} s after READY"] + problems, screenshot
if not problems and (args.host == "system" or ready_at is not None):
return [], screenshot
if not problems:
problems = ["frame presented but READY not printed"]
time.sleep(1)
return problems, screenshot
if __name__ == "__main__":
raise SystemExit(main())

140
tests/frame/check_input.py Normal file
View file

@ -0,0 +1,140 @@
"""Check that native pointer and keyboard input reaches a page through weft-compositor.
The harness runs weft-servo-shell with `input.html` on a nested desktop (see
session.py) and injects real X input into the compositor's window with
xdotool (after giving that window X input focus, since Xvfb runs without a
window manager), which weft-compositor's winit backend receives and routes to
the focused Wayland client. Each step must change the page as the page's script
defines, as seen in the presented pixels:
1. A click 6 px inside the left half's right edge turns only the left half
green; the right half must stay blue.
2. Typing `a` turns the right half yellow.
3. Typing `Shift+a` turns the right half magenta, which checks the modifier.
4. A click 6 px inside the right half's left edge turns the right half white.
The two clicks straddle the boundary between the halves, so a pointer
position that is scaled or offset by more than a few pixels fails.
Requires Xvfb, xwd, ImageMagick's convert and xdotool.
"""
import argparse
import shutil
import subprocess
import sys
import time
from pathlib import Path
sys.dont_write_bytecode = True
from session import ROOT, Desktop, SessionError, bounding_box, missing_tools, parse_ppm # noqa: E402
HERE = Path(__file__).resolve().parent
RED, GREEN, BLUE = (255, 0, 0), (0, 255, 0), (0, 0, 255)
WHITE, YELLOW, MAGENTA = (255, 255, 255), (255, 255, 0), (255, 0, 255)
MIN_SIDE = 40
def region(screenshot, color):
"""Bounding box of `color` if it covers a page half, else None."""
box = bounding_box(*parse_ppm(screenshot), color)
if box and box[2] - box[0] >= MIN_SIDE and box[3] - box[1] >= MIN_SIDE:
return box
return None
STARTUP_TIMEOUT = 120.0
EDGE_INSET = 6
class Steps:
def __init__(self, desktop, shell, timeout):
self.desktop = desktop
self.shell = shell
self.timeout = timeout
self.screenshot = None
self.xdotool_path = shutil.which("xdotool")
def expect(self, description, present, absent=(), timeout=None):
"""Wait until every colour in `present` and none in `absent` is shown."""
deadline = time.monotonic() + (self.timeout if timeout is None else timeout)
while time.monotonic() < deadline:
if self.shell.poll() is not None:
raise AssertionError(f"shell exited with status {self.shell.returncode}")
self.screenshot = self.desktop.capture()
boxes = {color: region(self.screenshot, color) for color in present}
if all(boxes.values()) and not any(region(self.screenshot, c) for c in absent):
return boxes
time.sleep(0.5)
raise AssertionError(f"{description}: expected page state not shown")
def xdotool(self, *arguments):
subprocess.run([self.xdotool_path, *arguments], env={"DISPLAY": self.desktop.display},
check=True, timeout=20)
def click(self, x, y):
self.xdotool("mousemove", "--sync", str(x), str(y))
self.xdotool("click", "1")
def run(steps):
boxes = steps.expect("initial page", [RED, BLUE], timeout=STARTUP_TIMEOUT)
# Xvfb runs without a window manager, so give the compositor's window the
# X input focus that a real session's window manager would.
steps.xdotool("search", "--class", "weft-compositor", "windowfocus", "--sync")
left, right = boxes[RED], boxes[BLUE]
middle = (left[1] + left[3]) // 2
steps.click(left[2] - EDGE_INSET, middle)
steps.expect("click near the right edge of the left half", [GREEN, BLUE],
absent=[RED, WHITE])
steps.xdotool("key", "a")
steps.expect("key a", [GREEN, YELLOW], absent=[BLUE])
steps.xdotool("key", "shift+a")
steps.expect("key Shift+a", [GREEN, MAGENTA], absent=[YELLOW])
steps.click(right[0] + EDGE_INSET, middle)
steps.expect("click near the left edge of the right half", [GREEN, WHITE],
absent=[MAGENTA, RED])
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("--page", type=Path, default=HERE / "input.html")
parser.add_argument("--timeout", type=float, default=30.0,
help="seconds to wait for each expected page state")
parser.add_argument("--output", type=Path, default=ROOT / "target/input-check",
help="directory for logs and the last capture")
args = parser.parse_args(argv)
missing = missing_tools() + [tool for tool in ("xdotool",) if shutil.which(tool) is None]
missing += [str(b) for b in (args.compositor, args.shell) if not b.is_file()]
if missing:
print("missing: " + ", ".join(missing), file=sys.stderr)
return 2
try:
with Desktop(args.compositor, args.output, outputs=["input.ppm"]) as desktop:
shell = desktop.launch_client("shell", [args.shell],
{"WEFT_SYSTEM_UI_HTML": str(args.page.resolve())})
steps = Steps(desktop, shell, args.timeout)
try:
run(steps)
except AssertionError as failure:
print(f"input check failed: {failure}", file=sys.stderr)
print(f"logs and last capture in {args.output}", file=sys.stderr)
return 1
finally:
if steps.screenshot is not None:
(args.output / "input.ppm").write_bytes(steps.screenshot)
except SessionError as error:
print(error, file=sys.stderr)
return 1
print("input check passed")
return 0
if __name__ == "__main__":
raise SystemExit(main())

31
tests/frame/input.html Normal file
View file

@ -0,0 +1,31 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WEFT input reference</title>
<style>
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; }
body { display: grid; grid-template-columns: 1fr 1fr; }
#left { background: rgb(255, 0, 0); }
#right { background: rgb(0, 0, 255); }
</style>
</head>
<body>
<div id="left"></div>
<div id="right"></div>
<script>
// Each input the harness sends changes one half to a colour it checks for.
const left = document.getElementById("left");
const right = document.getElementById("right");
left.addEventListener("click", () => { left.style.background = "rgb(0, 255, 0)"; });
right.addEventListener("click", () => { right.style.background = "rgb(255, 255, 255)"; });
document.addEventListener("keydown", (event) => {
if (event.key === "a" && !event.shiftKey) {
right.style.background = "rgb(255, 255, 0)";
} else if (event.key === "A" && event.shiftKey) {
right.style.background = "rgb(255, 0, 255)";
}
});
</script>
</body>
</html>

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>

209
tests/frame/session.py Normal file
View file

@ -0,0 +1,209 @@
"""Nested WEFT desktop for graphical tests: Xvfb, weft-compositor and Wayland clients.
`Desktop` starts Xvfb and weft-compositor with its winit backend, launches
clients on the compositor's Wayland socket, captures the X screen and
terminates every process it started when the `with` block ends. Processes are
started from argument arrays in their own process groups.
"""
import os
import re
import shutil
import signal
import subprocess
import tempfile
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SCREEN = (1024, 768)
ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;]*m")
REQUIRED_TOOLS = ("Xvfb", "xwd", "convert")
class SessionError(Exception):
"""The nested desktop could not be started."""
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 pixel(width, pixels, x, y):
offset = (y * width + x) * 3
return tuple(pixels[offset:offset + 3])
def missing_tools():
return [tool for tool in REQUIRED_TOOLS if shutil.which(tool) is None]
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 _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."""
_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)
class Desktop:
"""Xvfb plus weft-compositor; logs are written to `output/<name>.log`."""
def __init__(self, compositor, output, outputs=()):
"""`outputs` names further files in `output` that this run will write."""
self.compositor = Path(compositor)
self.output = Path(output)
self.own_outputs = ["xvfb.log", "compositor.log", "shell.log", *outputs]
self.processes = []
self.logs = {}
def __enter__(self):
self.output.mkdir(parents=True, exist_ok=True)
for name in self.own_outputs:
(self.output / name).unlink(missing_ok=True)
self.runtime = Path(tempfile.mkdtemp(prefix="weft-desktop-"))
self.runtime.chmod(0o700)
self.env = {key: value for key, value in os.environ.items()
if key not in ("DISPLAY", "WAYLAND_DISPLAY", "WAYLAND_SOCKET")}
self.env["XDG_RUNTIME_DIR"] = str(self.runtime)
self.env.setdefault("RUST_LOG", "info")
try:
self._start_display()
self._start_compositor()
except BaseException:
self.__exit__(None, None, None)
raise
return self
def __exit__(self, *exc):
for process in reversed(self.processes):
_stop(process)
for log in self.logs.values():
log.close()
shutil.rmtree(self.runtime, ignore_errors=True)
return False
def launch(self, name, command, env=None):
"""Start a process with its output in `<name>.log`."""
log = open(self.output / f"{name}.log", "w", encoding="utf-8")
self.logs[name] = log
process = subprocess.Popen([str(part) for part in command], stdout=log,
stderr=subprocess.STDOUT, env=dict(self.env, **(env or {})),
start_new_session=True)
self.processes.append(process)
return process
def launch_client(self, name, command, env=None):
"""Start a Wayland client of the compositor."""
return self.launch(name, command, dict(env or {}, WAYLAND_DISPLAY=self.socket))
def log_text(self, name):
text = (self.output / f"{name}.log").read_text(encoding="utf-8", errors="replace")
return ANSI_ESCAPE.sub("", text)
def capture(self):
"""Return the X screen as a P6 PPM."""
xwd = subprocess.run(["xwd", "-root", "-silent", "-display", self.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 _start_display(self):
# Xvfb picks a free display itself and writes its number to the pipe
# once it accepts connections, so concurrent runs cannot share one.
read_end, write_end = os.pipe()
log = open(self.output / "xvfb.log", "w", encoding="utf-8")
self.logs["xvfb"] = log
try:
xvfb = subprocess.Popen(
["Xvfb", "-displayfd", str(write_end), "-screen", "0",
f"{SCREEN[0]}x{SCREEN[1]}x24", "-nolisten", "tcp"],
stdout=log, stderr=subprocess.STDOUT, env=self.env,
start_new_session=True, pass_fds=(write_end,))
finally:
os.close(write_end)
self.processes.append(xvfb)
with os.fdopen(read_end) as reported:
number = reported.readline().strip()
if not number.isdigit() or xvfb.poll() is not None:
raise SessionError("Xvfb did not start")
self.display = f":{number}"
def _start_compositor(self):
compositor = self.launch("compositor", [self.compositor, "--winit"],
{"DISPLAY": self.display})
def socket_name():
if compositor.poll() is not None:
return "exited"
match = re.search(r'socket_name="([^"]+)"', self.log_text("compositor"))
return match and match.group(1)
socket = wait_for(socket_name, 30)
if socket in (None, "exited"):
raise SessionError("compositor did not open a Wayland socket; see "
f"{self.output / 'compositor.log'}")
self.socket = socket