spikes/gpui: the GPUI spikes' workspace, environment and meter
Plan section 6 step 1. A Cargo workspace of its own under spikes/gpui (own lock, not a member of the root workspace, so the root's lock, deny policy, notices and CI are untouched; it builds into the checkout's target/), on gpui-kit pinned to =0.8.0. No gpui-kit release builds on Rust 1.94 (every gpui-pre 0.3.x calls std::hint::cold_path, stable since 1.95), so the workspace says rust-version 1.95. - shell.sh: the toolchain (1.95.0, 1.94, stable or nightly, all from one pinned fenix), the native libraries, Mesa's lavapipe as the only Vulkan driver, Xvfb, openbox and the X tools, Noto Color Emoji and Noto Sans CJK. - headless.sh: a private Xvfb display with openbox and a private session bus, never the desktop's; headless-wayland.sh: sway's headless backend. - spike-common: CPU by thread group and memory from /proc once a second with the spike's counters (meter), proc-meter and damage-count for programs without a meter (the Slint app), Inter and the emoji/CJK fonts, the client's Lucide icons as GPUI assets, and the BGRA twin of voelin_media::convert::to_rgba. From the interrupted 2026-10-25 attempt, kept; changed here: shell.sh takes 1.94 and nightly from the pinned fenix (the store paths it named were garbage-collected), the README's headless-wayland.sh paragraph (sway, not weston), its fmt command (-p, not --all), its toolchain and nixpkgs lines, and the font docs (GPUI drops Noto Color Emoji from a fallback chain). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3930ef2945
commit
c9859bcfb4
15 files changed
+10058
No files matched your search
@@ -0,0 +1,4 @@
|
||||
# The spikes build into the worktree's target directory, next to the root
|
||||
# workspace's artifacts (one target directory per checkout).
|
||||
[build]
|
||||
target-dir = "../../target"
|
||||
Generated
+8954
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,60 @@
|
||||
# The GPUI spikes of plan section 6 step 1 (docs/design/gpui-spikes.md): a
|
||||
# workspace of its own with its own lock, not a member of the root workspace,
|
||||
# so the root's lock, deny policy, notices and CI stay as they are. It builds
|
||||
# into the checkout's target directory (.cargo/config.toml).
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["common"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.0.0"
|
||||
edition = "2024"
|
||||
# gpui-pre (every 0.3.x release) calls std::hint::cold_path, stable since 1.95.
|
||||
rust-version = "1.95"
|
||||
license = "MIT OR Apache-2.0"
|
||||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
# GPUI, gpui-component and their assets, pinned exactly (pre-1.0).
|
||||
gpui-kit = "=0.8.0"
|
||||
spike-common = { path = "common" }
|
||||
# The client's crates, read only. voelin-core brings LocalPreview (the test
|
||||
# pattern through the real encoder and decoder).
|
||||
voelin-core = { path = "../../crates/voelin-core", default-features = false, features = ["media"] }
|
||||
# The desktop codecs of `media-desktop` (libvpx, dav1d, OpenH264, FFmpeg at
|
||||
# run time) and X11 capture, without `pipewire`: it enables ashpd's `tokio`
|
||||
# feature, GPUI enables its `async-io` one, and ashpd refuses both
|
||||
# (docs/design/gpui-spikes.md, "Dependencies").
|
||||
voelin-media = { path = "../../crates/voelin-media", default-features = false, features = ["vpx", "openh264", "ffmpeg", "av1", "x11"] }
|
||||
voelin-platform = { path = "../../crates/voelin-platform", default-features = false, features = ["x11"] }
|
||||
voelin-ui-vm = { path = "../../crates/voelin-ui-vm" }
|
||||
# The revision the root workspace pins (chat messages for voelin-ui-vm).
|
||||
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" }
|
||||
# Logs of GPUI (the adapter it picked) and of the client's crates.
|
||||
env_logger = { version = "0.11", default-features = false, features = ["auto-color", "humantime"] }
|
||||
log = "0.4"
|
||||
# The same version voelin-media converts with.
|
||||
yuv = "=0.8.19"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_code = "deny"
|
||||
missing_docs = "warn"
|
||||
|
||||
[workspace.lints.clippy]
|
||||
all = { level = "warn", priority = -1 }
|
||||
|
||||
# As the root workspace: dimpl (DTLS for str0m, under voelin-stream) with its
|
||||
# patch.
|
||||
[patch.crates-io]
|
||||
dimpl = { path = "../../third_party/dimpl" }
|
||||
|
||||
[profile.release]
|
||||
debug = "line-tables-only"
|
||||
|
||||
# As the root workspace's dev profile: media code optimised in debug builds.
|
||||
[profile.dev.package.yuv]
|
||||
opt-level = 3
|
||||
[profile.dev.package.voelin-media]
|
||||
opt-level = 3
|
||||
[profile.dev.package.dav1d]
|
||||
opt-level = 3
|
||||
@@ -0,0 +1,74 @@
|
||||
# GPUI spikes
|
||||
|
||||
The three spikes of plan section 6 step 1 (Slint to GPUI), with their
|
||||
measurements and the go/no-go in [docs/design/gpui-spikes.md](../../docs/design/gpui-spikes.md):
|
||||
|
||||
| Crate | Spike | README |
|
||||
|---|---|---|
|
||||
| `video/` | decoded video as BGRA `RenderImage`s in `img()`, 1080p60 and 1440p60, against the Slint path | [video/README.md](video/README.md) |
|
||||
| `composer/` | the composer (multi-line input, emoji at the caret, paste, Ctrl+Enter, IME preedit) and chat lines as `StyledText` | [composer/README.md](composer/README.md) |
|
||||
| `windows/` | a second window sharing the root entity, focus, fullscreen, close, a global push-to-talk hotkey, a shared preview | [windows/README.md](windows/README.md) |
|
||||
| `common/` | CPU, thread and memory meter (`/proc`), `damage-count` and `proc-meter`, fonts, icons, the BGRA conversion | |
|
||||
|
||||
This is a Cargo workspace of its own (own `Cargo.lock`, not a member of the
|
||||
root workspace: the root's lock, deny policy, notices and CI are not
|
||||
involved). It builds into the checkout's `target/` (`.cargo/config.toml`).
|
||||
Nothing here is wired into `crates/voelin-ui`; the client's crates are used
|
||||
read only, by path (`voelin-core`, `voelin-media`, `voelin-platform`,
|
||||
`voelin-ui-vm`, and `voelin-model` at the root's revision).
|
||||
|
||||
## Toolchain
|
||||
|
||||
`gpui-kit` 0.8.0 is pinned exactly. No `gpui-kit` release builds with the
|
||||
repository's Rust 1.94: every `gpui-pre` 0.3.x (the GPUI snapshot under all
|
||||
of them) calls `std::hint::cold_path`, stable since 1.95.0 (E0658 on 1.94).
|
||||
The workspace says `rust-version = "1.95"`; the spikes are built and
|
||||
checked with 1.95.0 (the default of `shell.sh`) and nightly 2026-10-24
|
||||
(`TOOLCHAIN=nightly`, rustc 1.101.0-nightly of 2026-10-23), both from one
|
||||
pinned fenix. `TOOLCHAIN=1.94 spikes/gpui/shell.sh sh -c 'cd spikes/gpui &&
|
||||
cargo build --locked --ignore-rust-version'` shows the failure.
|
||||
|
||||
## Environment (NixOS)
|
||||
|
||||
`shell.sh` runs a command with everything the builds and runs need: the
|
||||
toolchain (1.95.0 from a pinned fenix), the native libraries (pkg-config
|
||||
and `LD_LIBRARY_PATH` built from nixpkgs store paths), Mesa's lavapipe as the
|
||||
only Vulkan driver (`VK_DRIVER_FILES`), the Vulkan loader, Xvfb, openbox,
|
||||
xdotool, xwd, ImageMagick, xclip, jq, and the Noto Color Emoji and Noto Sans
|
||||
CJK fonts (`SPIKE_EMOJI_FONT`, `SPIKE_EXTRA_FONTS`). `nixpkgs` is the flake
|
||||
registry's: the measurements in the report used nixpkgs 02c087f3fe67
|
||||
(Mesa 26.2.5, llvmpipe on LLVM 21.1.8); `nix registry pin` or another
|
||||
registry entry changes them.
|
||||
|
||||
```sh
|
||||
spikes/gpui/shell.sh sh -c 'cd spikes/gpui && cargo build --locked --release'
|
||||
# -p: `--all` would take in the client's crates, which are path dependencies
|
||||
spikes/gpui/shell.sh sh -c 'cd spikes/gpui && cargo fmt -p spike-common -p spike-video -p spike-composer -p spike-windows --check'
|
||||
spikes/gpui/shell.sh sh -c 'cd spikes/gpui && cargo clippy --locked --all-targets -- -D warnings'
|
||||
spikes/gpui/shell.sh sh -c 'cd spikes/gpui && cargo test --locked'
|
||||
TOOLCHAIN=nightly spikes/gpui/shell.sh sh -c 'cd spikes/gpui && cargo build --locked'
|
||||
```
|
||||
|
||||
## Headless displays
|
||||
|
||||
Every window runs on a display of its own, never on the desktop's:
|
||||
|
||||
- `headless.sh` (used for every measurement): Xvfb `:91` (3840x2160, 24 bit,
|
||||
no TCP), openbox as the window manager (fullscreen, activation and close
|
||||
requests need one), a private D-Bus session bus that starts no services,
|
||||
`WAYLAND_DISPLAY`, `XDG_SESSION_TYPE` and the desktop's bus address
|
||||
removed, the XDG directories under `.scratch/gpui-spikes-state`. GPUI
|
||||
takes its X11 backend; the renderer is wgpu on lavapipe.
|
||||
- `headless-wayland.sh`: sway on wlroots' headless backend (weston's has no
|
||||
seat, which GPUI's Wayland backend requires) on a socket in its own
|
||||
runtime directory (`.scratch/wl`), for GPUI's Wayland backend; no X
|
||||
display is set. `-r pixman` (default) keeps the compositor on the CPU;
|
||||
`-r gles2` or `-r vulkan` put it on a render node.
|
||||
|
||||
```sh
|
||||
spikes/gpui/shell.sh spikes/gpui/headless.sh -- COMMAND
|
||||
spikes/gpui/shell.sh spikes/gpui/headless-wayland.sh -- COMMAND
|
||||
```
|
||||
|
||||
Results (JSON lines, screenshots) go to `$OUT`, by default
|
||||
`.scratch/gpui-spikes-results` (git ignores `.scratch/`).
|
||||
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "spike-common"
|
||||
description = "What the GPUI spikes share: process and thread CPU, memory and frame counters, logging, fonts and icons."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
env_logger = { workspace = true }
|
||||
gpui-kit = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# Clock ticks and the page size, for /proc/self.
|
||||
rustix = { version = "1.1", features = ["param"] }
|
||||
# RenderImage holds image::Frame (the version GPUI uses).
|
||||
image = { version = "0.25", default-features = false }
|
||||
serde_json = "1"
|
||||
voelin-media = { workspace = true }
|
||||
yuv = { workspace = true }
|
||||
# The damage counter (frames a window's content changed, whatever draws it).
|
||||
x11rb = { version = "0.13", features = ["damage"] }
|
||||
|
||||
[[bin]]
|
||||
name = "damage-count"
|
||||
path = "src/bin/damage-count.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "proc-meter"
|
||||
path = "src/bin/proc-meter.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,37 @@
|
||||
//! Icons for `svg()`: the client's own Lucide SVGs
|
||||
//! (`crates/voelin-ui/ui/assets/icons`, Lucide 1.48, read from the checkout
|
||||
//! at run time) under `voelin/<name>.svg`, then gpui-kit-assets' complete
|
||||
//! Lucide 1.43 catalog under `icons/<name>.svg` (what gpui-component's
|
||||
//! `Icon` uses).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use gpui_kit::{AssetSource, Result, SharedString};
|
||||
|
||||
/// The client's icons first, then gpui-kit's catalog.
|
||||
pub struct Assets {
|
||||
client_icons: PathBuf,
|
||||
}
|
||||
|
||||
impl Default for Assets {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
client_icons: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../../crates/voelin-ui/ui/assets/icons"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AssetSource for Assets {
|
||||
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
|
||||
if let Some(name) = path.strip_prefix("voelin/") {
|
||||
return Ok(std::fs::read(self.client_icons.join(name)).ok().map(Cow::Owned));
|
||||
}
|
||||
gpui_kit::assets::AllAssets.load(path)
|
||||
}
|
||||
|
||||
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
|
||||
gpui_kit::assets::AllAssets.list(path)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
//! Frames as BGRA, the byte order GPUI's `RenderImage` holds: the BGRA twin
|
||||
//! of `voelin_media::convert::to_rgba` (the same `yuv` calls with the
|
||||
//! channels swapped, BT.601 limited range), and the picture GPUI shows.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use gpui_kit::RenderImage;
|
||||
use voelin_media::frame::{FrameRef, PixelsRef, VideoFrame};
|
||||
use yuv::{YuvBiPlanarImage, YuvConversionMode, YuvPlanarImage, YuvRange, YuvStandardMatrix};
|
||||
|
||||
const RANGE: YuvRange = YuvRange::Limited;
|
||||
const MATRIX: YuvStandardMatrix = YuvStandardMatrix::Bt601;
|
||||
|
||||
fn u32_of(n: usize) -> Result<u32, String> {
|
||||
u32::try_from(n).map_err(|_| format!("{n} does not fit a stride"))
|
||||
}
|
||||
|
||||
/// Write `frame` as BGRA (alpha 255) into `out`, `stride` bytes per row.
|
||||
pub fn to_bgra(frame: &VideoFrame, out: &mut [u8], stride: usize) -> Result<(), String> {
|
||||
to_bgra_ref(&frame.view(), out, stride)
|
||||
}
|
||||
|
||||
/// [`to_bgra`] of a borrowed frame; allocates nothing.
|
||||
pub fn to_bgra_ref(frame: &FrameRef<'_>, out: &mut [u8], stride: usize) -> Result<(), String> {
|
||||
frame.validate().map_err(|e| e.to_string())?;
|
||||
let (w, h) = (frame.width, frame.height);
|
||||
let row = w as usize * 4;
|
||||
if stride < row || out.len() < stride * (h as usize - 1) + row {
|
||||
return Err(format!("BGRA output of {} bytes is too small for {w}x{h}", out.len()));
|
||||
}
|
||||
let out_stride = u32_of(stride)?;
|
||||
match &frame.pixels {
|
||||
PixelsRef::I420 { y, u, v } => {
|
||||
let image = YuvPlanarImage {
|
||||
y_plane: y.data,
|
||||
y_stride: u32_of(y.stride)?,
|
||||
u_plane: u.data,
|
||||
u_stride: u32_of(u.stride)?,
|
||||
v_plane: v.data,
|
||||
v_stride: u32_of(v.stride)?,
|
||||
width: w,
|
||||
height: h,
|
||||
};
|
||||
yuv::yuv420_to_bgra(&image, out, out_stride, RANGE, MATRIX).map_err(|e| e.to_string())
|
||||
}
|
||||
PixelsRef::Nv12 { y, uv } => {
|
||||
let image = YuvBiPlanarImage {
|
||||
y_plane: y.data,
|
||||
y_stride: u32_of(y.stride)?,
|
||||
uv_plane: uv.data,
|
||||
uv_stride: u32_of(uv.stride)?,
|
||||
width: w,
|
||||
height: h,
|
||||
};
|
||||
yuv::yuv_nv12_to_bgra(
|
||||
&image,
|
||||
out,
|
||||
out_stride,
|
||||
RANGE,
|
||||
MATRIX,
|
||||
YuvConversionMode::Balanced,
|
||||
)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
PixelsRef::Bgra(p) => {
|
||||
for y in 0..h as usize {
|
||||
out[y * stride..y * stride + row].copy_from_slice(p.row(y, row));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
PixelsRef::Rgba(p) => {
|
||||
for y in 0..h as usize {
|
||||
let (src, dst) = (p.row(y, row), &mut out[y * stride..y * stride + row]);
|
||||
for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) {
|
||||
d.copy_from_slice(&[s[2], s[1], s[0], 255]);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels as GPUI's image: one frame, BGRA, `width * 4` bytes per row.
|
||||
pub fn render_image(width: u32, height: u32, bgra: Vec<u8>) -> Arc<RenderImage> {
|
||||
let buffer = image::RgbaImage::from_raw(width, height, bgra).expect("a buffer of the size");
|
||||
Arc::new(RenderImage::new([image::Frame::new(buffer)]))
|
||||
}
|
||||
|
||||
/// `frame` converted into a new picture.
|
||||
pub fn picture(frame: &VideoFrame) -> Result<Arc<RenderImage>, String> {
|
||||
let stride = frame.width as usize * 4;
|
||||
let mut bgra = vec![0u8; stride * frame.height as usize];
|
||||
to_bgra(frame, &mut bgra, stride)?;
|
||||
Ok(render_image(frame.width, frame.height, bgra))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use voelin_media::capture::synthetic::{Pattern, SyntheticScreen};
|
||||
use voelin_media::convert;
|
||||
|
||||
/// BGRA is RGBA with red and blue swapped, pixel for pixel, for I420 and
|
||||
/// for packed input.
|
||||
#[test]
|
||||
fn bgra_is_rgba_swapped() {
|
||||
let picture = SyntheticScreen::with_pattern(64, 36, Pattern::Desktop).frame(3, 30);
|
||||
let i420 = convert::to_i420(&picture).unwrap().into_owned();
|
||||
let rgba_in =
|
||||
VideoFrame::from_rgba(64, 36, 64 * 4, convert::to_rgba_vec(&picture).unwrap()).unwrap();
|
||||
for frame in [&picture, &i420, &rgba_in] {
|
||||
let mut rgba = vec![0; 64 * 36 * 4];
|
||||
let mut bgra = vec![0; 64 * 36 * 4];
|
||||
convert::to_rgba(frame, &mut rgba, 64 * 4).unwrap();
|
||||
to_bgra(frame, &mut bgra, 64 * 4).unwrap();
|
||||
for (r, b) in rgba.chunks_exact(4).zip(bgra.chunks_exact(4)) {
|
||||
assert_eq!([r[2], r[1], r[0], r[3]], b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_output_is_refused() {
|
||||
let picture = SyntheticScreen::new(32, 32).frame(0, 30);
|
||||
assert!(to_bgra(&picture, &mut [0; 16], 32 * 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pictures_have_the_frame_size() {
|
||||
let picture = SyntheticScreen::new(40, 20).frame(0, 30);
|
||||
let image = super::picture(&picture).unwrap();
|
||||
assert_eq!((image.size(0).width.0, image.size(0).height.0), (40, 20));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
//! Counts how often a window's content changes, whatever draws it (GPUI,
|
||||
//! Slint): XDamage events of a top-level window of the X display in
|
||||
//! `DISPLAY`, one line per second (`damage/s`) and the mean at the end.
|
||||
//!
|
||||
//! `damage-count <window name substring> <seconds> [warm-up seconds]`
|
||||
//!
|
||||
//! Every damage report is subtracted at once, so a frame drawn with one
|
||||
//! `PutImage` counts once; a frame drawn in several requests within 2 ms
|
||||
//! counts once too.
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::Event;
|
||||
use x11rb::protocol::damage::{ConnectionExt as _, ReportLevel};
|
||||
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt as _, Window};
|
||||
|
||||
fn find(conn: &impl Connection, root: Window, needle: &str) -> anyhow::Result<Option<Window>> {
|
||||
let tree = conn.query_tree(root)?.reply()?;
|
||||
for &child in &tree.children {
|
||||
let name = conn
|
||||
.get_property(false, child, AtomEnum::WM_NAME, AtomEnum::ANY, 0, 1024)?
|
||||
.reply()?
|
||||
.value;
|
||||
if String::from_utf8_lossy(&name).contains(needle) {
|
||||
return Ok(Some(child));
|
||||
}
|
||||
if let Some(found) = find(conn, child, needle)? {
|
||||
return Ok(Some(found));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let needle = args.next().ok_or_else(|| anyhow::anyhow!("no window name"))?;
|
||||
let seconds: f64 = args.next().map_or(Ok(30.0), |s| s.parse())?;
|
||||
let warmup: f64 = args.next().map_or(Ok(5.0), |s| s.parse())?;
|
||||
let (conn, screen) = x11rb::connect(None)?;
|
||||
let root = conn.setup().roots[screen].root;
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
let window = loop {
|
||||
if let Some(w) = find(&conn, root, &needle)? {
|
||||
break w;
|
||||
}
|
||||
anyhow::ensure!(Instant::now() < deadline, "no window named like {needle:?}");
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
};
|
||||
conn.damage_query_version(1, 1)?.reply()?;
|
||||
let damage = conn.generate_id()?;
|
||||
conn.damage_create(damage, window, ReportLevel::NON_EMPTY)?;
|
||||
conn.flush()?;
|
||||
let start = Instant::now();
|
||||
let (mut second, mut in_second, mut counted, mut last_event) =
|
||||
(start, 0u32, 0u64, None::<Instant>);
|
||||
let mut steady_start = None;
|
||||
loop {
|
||||
let event = conn.poll_for_event()?;
|
||||
let now = Instant::now();
|
||||
match event {
|
||||
Some(Event::DamageNotify(_)) => {
|
||||
conn.damage_subtract(damage, x11rb::NONE, x11rb::NONE)?;
|
||||
conn.flush()?;
|
||||
if last_event.is_none_or(|t| now.duration_since(t) > Duration::from_millis(2)) {
|
||||
in_second += 1;
|
||||
if steady_start.is_some() {
|
||||
counted += 1;
|
||||
}
|
||||
}
|
||||
last_event = Some(now);
|
||||
}
|
||||
Some(_) => {}
|
||||
None => std::thread::sleep(Duration::from_micros(500)),
|
||||
}
|
||||
if now.duration_since(second) >= Duration::from_secs(1) {
|
||||
println!(
|
||||
"{{\"t\": {:.1}, \"damage_per_s\": {in_second}}}",
|
||||
now.duration_since(start).as_secs_f64()
|
||||
);
|
||||
second = now;
|
||||
in_second = 0;
|
||||
if steady_start.is_none() && now.duration_since(start).as_secs_f64() >= warmup {
|
||||
steady_start = Some(now);
|
||||
}
|
||||
}
|
||||
if now.duration_since(start).as_secs_f64() >= seconds {
|
||||
let steady = steady_start.map_or(0.0, |s| now.duration_since(s).as_secs_f64());
|
||||
println!(
|
||||
"{{\"summary\": true, \"window\": {needle:?}, \"damage_per_s_mean\": {:.1}, \"steady_seconds\": {steady:.1}}}",
|
||||
counted as f64 / steady.max(1e-6)
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! CPU (process and thread groups, percent of one core) and resident memory
|
||||
//! of another process, from `/proc/<pid>`, once a second, and the means
|
||||
//! after a warm-up: the same numbers `spike_common::meter` gives for the
|
||||
//! spikes, for a program that has no meter of its own (the Slint app).
|
||||
//!
|
||||
//! `proc-meter <pid> <seconds> [warm-up seconds]`
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::json;
|
||||
use spike_common::meter::{Snapshot, cpu_between};
|
||||
|
||||
fn round(v: f64) -> f64 {
|
||||
(v * 10.0).round() / 10.0
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let pid = args.next().ok_or_else(|| anyhow::anyhow!("no pid"))?;
|
||||
let seconds: u64 = args.next().map_or(Ok(60), |s| s.parse())?;
|
||||
let warmup: u64 = args.next().map_or(Ok(10), |s| s.parse())?;
|
||||
let first = Snapshot::of(&pid);
|
||||
let mut last = first.clone();
|
||||
let mut steady = None;
|
||||
for t in 1..=seconds {
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
let now = Snapshot::of(&pid);
|
||||
let (cpu, threads) = cpu_between(&last, &now);
|
||||
println!(
|
||||
"{}",
|
||||
json!({"t": t, "cpu": round(cpu), "rss_mib": round(now.rss_mib()), "threads": threads.iter().map(|(k, v)| (k.clone(), json!(round(*v)))).collect::<serde_json::Map<_, _>>()})
|
||||
);
|
||||
if t == warmup {
|
||||
steady = Some(now.clone());
|
||||
}
|
||||
last = now;
|
||||
}
|
||||
let start = steady.unwrap_or(first);
|
||||
let (cpu, threads) = cpu_between(&start, &last);
|
||||
println!(
|
||||
"{}",
|
||||
json!({
|
||||
"summary": true,
|
||||
"pid": pid,
|
||||
"steady_seconds": seconds.saturating_sub(warmup),
|
||||
"cpu_mean": round(cpu),
|
||||
"threads_mean": threads.iter().map(|(k, v)| (k.clone(), json!(round(*v)))).collect::<serde_json::Map<_, _>>(),
|
||||
"rss_mib_steady_start": round(start.rss_mib()),
|
||||
"rss_mib_end": round(last.rss_mib()),
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//! Fonts: Inter as the client bundles it (`crates/voelin-ui/ui/assets/fonts`,
|
||||
//! read at build time, OFL), a colour emoji font (`SPIKE_EMOJI_FONT`) and
|
||||
//! further fonts (`SPIKE_EXTRA_FONTS`, colon-separated: CJK), which
|
||||
//! `shell.sh` points at Noto Color Emoji and Noto Sans CJK, added to GPUI's
|
||||
//! text system so nothing depends on what fontconfig finds.
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use gpui_kit::App;
|
||||
|
||||
/// The family name of the bundled UI font.
|
||||
pub const UI_FAMILY: &str = "Inter";
|
||||
|
||||
/// The colour emoji font's family. GPUI's Linux text system draws a glyph in
|
||||
/// colour only from a font whose PostScript name is `NotoColorEmoji`
|
||||
/// (`check_is_known_emoji_font` in gpui-pre-wgpu's `cosmic_text_system.rs`).
|
||||
pub const EMOJI_FAMILY: &str = "Noto Color Emoji";
|
||||
|
||||
const INTER: [&[u8]; 5] = [
|
||||
include_bytes!("../../../../crates/voelin-ui/ui/assets/fonts/Inter-Regular.ttf"),
|
||||
include_bytes!("../../../../crates/voelin-ui/ui/assets/fonts/Inter-Medium.ttf"),
|
||||
include_bytes!("../../../../crates/voelin-ui/ui/assets/fonts/Inter-SemiBold.ttf"),
|
||||
include_bytes!("../../../../crates/voelin-ui/ui/assets/fonts/Inter-Bold.ttf"),
|
||||
include_bytes!("../../../../crates/voelin-ui/ui/assets/fonts/Inter-Italic.ttf"),
|
||||
];
|
||||
|
||||
/// Add Inter, the emoji font and the extra fonts. Returns the emoji font's
|
||||
/// path if it was added.
|
||||
pub fn load(cx: &mut App) -> Option<String> {
|
||||
let mut fonts: Vec<Cow<'static, [u8]>> = INTER.iter().map(|b| Cow::Borrowed(*b)).collect();
|
||||
let extra = std::env::var("SPIKE_EXTRA_FONTS").unwrap_or_default();
|
||||
for path in extra.split(':').filter(|p| !p.is_empty()) {
|
||||
match std::fs::read(path) {
|
||||
Ok(bytes) => fonts.push(Cow::Owned(bytes)),
|
||||
Err(e) => log::warn!("no font at {path}: {e}"),
|
||||
}
|
||||
}
|
||||
let mut added = None;
|
||||
if let Some(path) = std::env::var("SPIKE_EMOJI_FONT").ok().filter(|p| !p.is_empty()) {
|
||||
match std::fs::read(&path) {
|
||||
Ok(bytes) => {
|
||||
fonts.push(Cow::Owned(bytes));
|
||||
added = Some(path);
|
||||
}
|
||||
Err(e) => log::warn!("no emoji font at {path}: {e}"),
|
||||
}
|
||||
}
|
||||
if let Err(e) = cx.text_system().add_fonts(fonts) {
|
||||
log::warn!("cannot add the fonts: {e:#}");
|
||||
}
|
||||
added
|
||||
}
|
||||
|
||||
/// Inter with the colour emoji font and CJK after it. GPUI 0.3.9 keeps a
|
||||
/// family in the chain only if it could be a primary font, which takes a
|
||||
/// glyph for `m`: Noto Color Emoji has none and is dropped (`load_family` in
|
||||
/// gpui-pre-wgpu's `cosmic_text_system.rs`), so colour emoji come from
|
||||
/// cosmic-text's own fallback list, where DejaVu Sans (monochrome U+1F600 to
|
||||
/// U+1F640) comes first (the composer's emoji probe).
|
||||
pub fn ui_font() -> gpui_kit::Font {
|
||||
gpui_kit::Font {
|
||||
family: UI_FAMILY.into(),
|
||||
features: gpui_kit::FontFeatures::default(),
|
||||
fallbacks: Some(gpui_kit::FontFallbacks::from_fonts(vec![
|
||||
EMOJI_FAMILY.into(),
|
||||
"Noto Sans CJK SC".into(),
|
||||
])),
|
||||
weight: gpui_kit::FontWeight::NORMAL,
|
||||
style: gpui_kit::FontStyle::Normal,
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour emoji font alone, for text known to be emoji (a chat run
|
||||
/// `voelin-ui-vm` marks as one, the picker). GPUI 0.3.9 refuses it as a
|
||||
/// run's font for the reason given at [`ui_font`] and draws such a run in
|
||||
/// its fallback font stack; docs/design/gpui-spikes.md has the patch that
|
||||
/// lets it through.
|
||||
pub fn emoji_font() -> gpui_kit::Font {
|
||||
gpui_kit::Font { family: EMOJI_FAMILY.into(), fallbacks: None, ..ui_font() }
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! What the GPUI spikes share: the process's and its threads' CPU and memory
|
||||
//! read from `/proc/self` once a second with the spike's own counters
|
||||
//! ([`meter`]), logging, the fonts the client ships ([`fonts`]) and its
|
||||
//! Lucide icons as GPUI assets ([`assets`]), and decoded frames as the BGRA
|
||||
//! pictures GPUI shows ([`bgra`]).
|
||||
|
||||
pub mod assets;
|
||||
pub mod bgra;
|
||||
pub mod fonts;
|
||||
pub mod meter;
|
||||
|
||||
/// Log to stderr: `RUST_LOG`, by default warnings and what GPUI says about
|
||||
/// the GPU adapter and the display it picked.
|
||||
pub fn init_logging() {
|
||||
env_logger::Builder::from_env(
|
||||
env_logger::Env::default().default_filter_or("warn,gpui_wgpu=info,gpui_linux=info"),
|
||||
)
|
||||
.format_timestamp_millis()
|
||||
.init();
|
||||
}
|
||||
|
||||
/// The value of `--name value` or `--name=value` among the arguments.
|
||||
pub fn arg(name: &str) -> Option<String> {
|
||||
let flag = format!("--{name}");
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
if a == flag {
|
||||
return args.next();
|
||||
}
|
||||
if let Some(v) = a.strip_prefix(&flag).and_then(|r| r.strip_prefix('=')) {
|
||||
return Some(v.to_owned());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether `--name` is among the arguments.
|
||||
pub fn flag(name: &str) -> bool {
|
||||
let flag = format!("--{name}");
|
||||
std::env::args().skip(1).any(|a| a == flag)
|
||||
}
|
||||
|
||||
/// `WIDTHxHEIGHT` as numbers.
|
||||
pub fn parse_size(text: &str) -> Option<(u32, u32)> {
|
||||
let (w, h) = text.split_once('x')?;
|
||||
Some((w.parse().ok()?, h.parse().ok()?))
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
//! CPU and memory of this process from `/proc/self`, by thread name, with
|
||||
//! the spike's own counters, sampled once a second on a thread of their own.
|
||||
//!
|
||||
//! CPU is in percent of one core (200 = two cores busy). Threads are grouped
|
||||
//! by name without a trailing number (`llvmpipe-12` → `llvmpipe`), so the
|
||||
//! software renderer's share (Mesa's `llvmpipe-*` threads, which a GPU would
|
||||
//! replace) is told apart from the decoder, the converter and GPUI's main
|
||||
//! thread.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// A number the spike counts up (frames shown) or sets (images alive); the
|
||||
/// meter reports counters per second and gauges as they are.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Counter(Arc<AtomicU64>);
|
||||
|
||||
impl Counter {
|
||||
/// Add one.
|
||||
pub fn incr(&self) {
|
||||
self.0.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Add `n`.
|
||||
pub fn add(&self, n: u64) {
|
||||
self.0.fetch_add(n, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Set (gauges).
|
||||
pub fn set(&self, value: u64) {
|
||||
self.0.store(value, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The current value.
|
||||
pub fn get(&self) -> u64 {
|
||||
self.0.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// CPU ticks of the process and of each thread group, and the resident
|
||||
/// memory, at one moment.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Snapshot {
|
||||
at: Instant,
|
||||
process: u64,
|
||||
threads: BTreeMap<String, u64>,
|
||||
rss: u64,
|
||||
}
|
||||
|
||||
/// `utime + stime` and the name of a `/proc/.../stat` line.
|
||||
fn ticks_of(stat: &str) -> Option<(String, u64)> {
|
||||
let open = stat.find('(')?;
|
||||
let close = stat.rfind(')')?;
|
||||
let name = stat.get(open + 1..close)?.to_owned();
|
||||
let fields: Vec<&str> = stat.get(close + 1..)?.split_whitespace().collect();
|
||||
// Fields 14 and 15 of proc(5); the remainder starts at field 3.
|
||||
let utime: u64 = fields.get(11)?.parse().ok()?;
|
||||
let stime: u64 = fields.get(12)?.parse().ok()?;
|
||||
Some((name, utime + stime))
|
||||
}
|
||||
|
||||
/// A thread's group: its name without a trailing number or separator.
|
||||
pub fn group_of(name: &str) -> String {
|
||||
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
|
||||
let trimmed = trimmed.trim_end_matches(['-', '_', ':', ' ', '#']);
|
||||
if trimmed.is_empty() { name.to_owned() } else { trimmed.to_owned() }
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Read `/proc/self` now.
|
||||
pub fn now() -> Self {
|
||||
Self::of("self")
|
||||
}
|
||||
|
||||
/// Read `/proc/<process>` now (`"self"` or a process id).
|
||||
pub fn of(process: &str) -> Self {
|
||||
let proc = format!("/proc/{process}");
|
||||
let process = fs::read_to_string(format!("{proc}/stat"))
|
||||
.ok()
|
||||
.and_then(|s| ticks_of(&s))
|
||||
.map_or(0, |(_, t)| t);
|
||||
let mut threads = BTreeMap::new();
|
||||
if let Ok(dir) = fs::read_dir(format!("{proc}/task")) {
|
||||
for entry in dir.flatten() {
|
||||
let Ok(stat) = fs::read_to_string(entry.path().join("stat")) else { continue };
|
||||
if let Some((name, ticks)) = ticks_of(&stat) {
|
||||
*threads.entry(group_of(&name)).or_insert(0) += ticks;
|
||||
}
|
||||
}
|
||||
}
|
||||
let rss = fs::read_to_string(format!("{proc}/statm"))
|
||||
.ok()
|
||||
.and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
|
||||
.map_or(0, |pages| pages * rustix::param::page_size() as u64);
|
||||
Self { at: Instant::now(), process, threads, rss }
|
||||
}
|
||||
|
||||
/// Resident memory in MiB.
|
||||
pub fn rss_mib(&self) -> f64 {
|
||||
self.rss as f64 / (1024.0 * 1024.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// CPU in percent of one core between two snapshots: the process's and each
|
||||
/// thread group's (groups that exited in between count from zero).
|
||||
pub fn cpu_between(a: &Snapshot, b: &Snapshot) -> (f64, BTreeMap<String, f64>) {
|
||||
let hz = rustix::param::clock_ticks_per_second() as f64;
|
||||
let secs = b.at.duration_since(a.at).as_secs_f64().max(1e-6);
|
||||
let pct = |ticks: u64| ticks as f64 / hz / secs * 100.0;
|
||||
let process = pct(b.process.saturating_sub(a.process));
|
||||
let threads = b
|
||||
.threads
|
||||
.iter()
|
||||
.map(|(name, &t)| (name.clone(), pct(t.saturating_sub(*a.threads.get(name).unwrap_or(&0)))))
|
||||
.filter(|(_, p)| *p > 0.0)
|
||||
.collect();
|
||||
(process, threads)
|
||||
}
|
||||
|
||||
/// What a run measures and how long.
|
||||
pub struct Meter {
|
||||
/// The run's settings, copied into every line.
|
||||
pub config: Value,
|
||||
/// Counted up; reported per second.
|
||||
pub counters: Vec<(&'static str, Counter)>,
|
||||
/// Set; reported as they are.
|
||||
pub gauges: Vec<(&'static str, Counter)>,
|
||||
/// Seconds not averaged at the start (start-up, the first keyframe).
|
||||
pub warmup: Duration,
|
||||
/// The whole run, warm-up included; the process exits after it.
|
||||
pub duration: Duration,
|
||||
/// JSON lines: one per second, then the summary (`"summary": true`).
|
||||
pub out: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Meter {
|
||||
/// Sample once a second on a thread; after `duration` write the summary
|
||||
/// and end the process with `exit_code`.
|
||||
pub fn start(self, exit_code: Arc<AtomicU64>) {
|
||||
std::thread::Builder::new()
|
||||
.name("spike-meter".into())
|
||||
.spawn(move || self.run(&exit_code))
|
||||
.expect("a meter thread");
|
||||
}
|
||||
|
||||
fn run(self, exit_code: &AtomicU64) {
|
||||
let mut out = self.out.as_ref().map(|p| fs::File::create(p).expect("the meter's file"));
|
||||
let mut emit = |line: &Value| {
|
||||
let text = line.to_string();
|
||||
println!("{text}");
|
||||
if let Some(f) = out.as_mut() {
|
||||
let _ = writeln!(f, "{text}");
|
||||
}
|
||||
};
|
||||
let start = Instant::now();
|
||||
let values = |list: &[(&'static str, Counter)]| -> Vec<u64> {
|
||||
list.iter().map(|(_, c)| c.get()).collect()
|
||||
};
|
||||
let mut last = Snapshot::now();
|
||||
let mut last_counts = values(&self.counters);
|
||||
let mut steady: Option<(Snapshot, Vec<u64>)> = None;
|
||||
let mut cpu_samples: Vec<f64> = Vec::new();
|
||||
let mut rss_max = last.rss_mib();
|
||||
let rss_start = last.rss_mib();
|
||||
let mut rss_steady_start = None;
|
||||
loop {
|
||||
std::thread::sleep(Duration::from_secs(1));
|
||||
let now = Snapshot::now();
|
||||
let counts = values(&self.counters);
|
||||
let (cpu, threads) = cpu_between(&last, &now);
|
||||
let secs = now.at.duration_since(last.at).as_secs_f64();
|
||||
let rates: serde_json::Map<String, Value> = self
|
||||
.counters
|
||||
.iter()
|
||||
.zip(counts.iter().zip(&last_counts))
|
||||
.map(|((name, _), (c, l))| {
|
||||
((*name).to_owned(), json!(round((c - l) as f64 / secs)))
|
||||
})
|
||||
.collect();
|
||||
let gauges: serde_json::Map<String, Value> =
|
||||
self.gauges.iter().map(|(n, g)| ((*n).to_owned(), json!(g.get()))).collect();
|
||||
let elapsed = start.elapsed();
|
||||
emit(&json!({
|
||||
"t": round(elapsed.as_secs_f64()),
|
||||
"cpu": round(cpu),
|
||||
"threads": threads.iter().map(|(k, v)| (k.clone(), json!(round(*v)))).collect::<serde_json::Map<_, _>>(),
|
||||
"rss_mib": round(now.rss_mib()),
|
||||
"rates": rates,
|
||||
"gauges": gauges,
|
||||
}));
|
||||
rss_max = rss_max.max(now.rss_mib());
|
||||
if elapsed >= self.warmup {
|
||||
if steady.is_none() {
|
||||
steady = Some((now.clone(), counts.clone()));
|
||||
rss_steady_start = Some(now.rss_mib());
|
||||
} else {
|
||||
cpu_samples.push(cpu);
|
||||
}
|
||||
}
|
||||
if elapsed >= self.duration {
|
||||
let (first, first_counts) =
|
||||
steady.unwrap_or_else(|| (last.clone(), last_counts.clone()));
|
||||
let (cpu, threads) = cpu_between(&first, &now);
|
||||
let secs = now.at.duration_since(first.at).as_secs_f64().max(1e-6);
|
||||
let rates: serde_json::Map<String, Value> = self
|
||||
.counters
|
||||
.iter()
|
||||
.zip(counts.iter().zip(&first_counts))
|
||||
.map(|((name, _), (c, f))| {
|
||||
((*name).to_owned(), json!(round((c - f) as f64 / secs)))
|
||||
})
|
||||
.collect();
|
||||
cpu_samples.sort_by(f64::total_cmp);
|
||||
let pick = |q: f64| {
|
||||
cpu_samples
|
||||
.get(((cpu_samples.len() as f64 - 1.0) * q).round() as usize)
|
||||
.copied()
|
||||
.unwrap_or(cpu)
|
||||
};
|
||||
emit(&json!({
|
||||
"summary": true,
|
||||
"config": self.config,
|
||||
"steady_seconds": round(secs),
|
||||
"cpu_mean": round(cpu),
|
||||
"cpu_p10": round(pick(0.1)),
|
||||
"cpu_p90": round(pick(0.9)),
|
||||
"threads_mean": threads.iter().map(|(k, v)| (k.clone(), json!(round(*v)))).collect::<serde_json::Map<_, _>>(),
|
||||
"rates_mean": rates,
|
||||
"gauges_end": gauges,
|
||||
"rss_mib_start": round(rss_start),
|
||||
"rss_mib_steady_start": rss_steady_start.map(round),
|
||||
"rss_mib_end": round(now.rss_mib()),
|
||||
"rss_mib_max": round(rss_max),
|
||||
"rss_growth_mib_per_min": rss_steady_start.map(|s| round((now.rss_mib() - s) / secs * 60.0)),
|
||||
}));
|
||||
std::process::exit(exit_code.load(Ordering::Relaxed) as i32);
|
||||
}
|
||||
last = now;
|
||||
last_counts = counts;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn round(v: f64) -> f64 {
|
||||
(v * 10.0).round() / 10.0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn groups_drop_trailing_numbers() {
|
||||
assert_eq!(group_of("llvmpipe-12"), "llvmpipe");
|
||||
assert_eq!(group_of("tokio-runtime-w"), "tokio-runtime-w");
|
||||
assert_eq!(group_of("spike-video"), "spike-video");
|
||||
assert_eq!(group_of("1234"), "1234");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stat_lines_parse_with_spaces_in_names() {
|
||||
let line = "42 (a b) c) S 1 2 3 4 5 6 7 8 9 10 100 23 0 0 20 0 1 0 0";
|
||||
assert_eq!(ticks_of(line), Some(("a b) c".to_owned(), 123)));
|
||||
}
|
||||
}
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/bin/sh
|
||||
# Run a command on a private headless Wayland compositor: sway on wlroots'
|
||||
# headless backend (it has a seat, which GPUI's Wayland backend requires and
|
||||
# weston's headless backend lacks), its socket in its own XDG_RUNTIME_DIR,
|
||||
# and a private D-Bus session bus, so nothing reaches the desktop the
|
||||
# command is started from. No X display is set (no XWayland).
|
||||
#
|
||||
# spikes/gpui/headless-wayland.sh [-r pixman|gles2|vulkan] [-s WIDTHxHEIGHT] -- COMMAND...
|
||||
#
|
||||
# -r: the compositor's renderer (default pixman, the CPU; gles2 or vulkan
|
||||
# use the GPU of a render node); -s: the output size (default 3840x2160).
|
||||
# Run it inside shell.sh; keys go in with wtype (virtual keyboard). State
|
||||
# lives in $SPIKE_STATE as for headless.sh.
|
||||
set -eu
|
||||
renderer=pixman size=3840x2160
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
-r) renderer=$2; shift 2 ;;
|
||||
-s) size=$2; shift 2 ;;
|
||||
--) shift; break ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
[ $# -gt 0 ] || { echo "headless-wayland.sh: no command" >&2; exit 2; }
|
||||
root=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
SPIKE_STATE=${SPIKE_STATE:-$root/.scratch/gpui-spikes-state}
|
||||
# Short: a socket path has at most 107 bytes (sway's IPC socket is
|
||||
# sway-ipc.<uid>.<pid>.sock in it).
|
||||
runtime=$root/.scratch/wl
|
||||
mkdir -p "$runtime" "$SPIKE_STATE/config" "$SPIKE_STATE/data" "$SPIKE_STATE/cache"
|
||||
chmod 700 "$runtime"
|
||||
tools=$(nix build --option substituters "https://cache.nixos.org/ https://nix-community.cachix.org" \
|
||||
--no-link --print-out-paths nixpkgs#sway nixpkgs#wtype)
|
||||
for t in $tools; do PATH="$t/bin:$PATH"; done
|
||||
unset DISPLAY WAYLAND_DISPLAY WAYLAND_SOCKET XDG_SESSION_TYPE DBUS_SESSION_BUS_ADDRESS SWAYSOCK
|
||||
export XDG_RUNTIME_DIR="$runtime" XDG_CONFIG_HOME="$SPIKE_STATE/config"
|
||||
export XDG_DATA_HOME="$SPIKE_STATE/data" XDG_CACHE_HOME="$SPIKE_STATE/cache"
|
||||
cat >"$SPIKE_STATE/sway.conf" <<CONF
|
||||
output HEADLESS-1 resolution $size position 0 0
|
||||
default_border none
|
||||
focus_follows_mouse no
|
||||
CONF
|
||||
WLR_BACKENDS=headless WLR_LIBINPUT_NO_DEVICES=1 WLR_RENDERER=$renderer \
|
||||
sway --unsupported-gpu -c "$SPIKE_STATE/sway.conf" >"$SPIKE_STATE/sway.log" 2>&1 &
|
||||
compositor=$!
|
||||
trap 'kill $compositor 2>/dev/null; wait $compositor 2>/dev/null || true' EXIT INT TERM
|
||||
i=0
|
||||
until socket=$(ls "$runtime" 2>/dev/null | grep '^wayland-[0-9]*$' | head -1) && [ -n "$socket" ]; do
|
||||
i=$((i + 1))
|
||||
[ $i -lt 100 ] || { echo "sway did not start" >&2; cat "$SPIKE_STATE/sway.log" >&2; exit 1; }
|
||||
sleep 0.1
|
||||
done
|
||||
export WAYLAND_DISPLAY=$socket
|
||||
cat >"$SPIKE_STATE/dbus-session-wayland.conf" <<CONF
|
||||
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<type>session</type>
|
||||
<listen>unix:path=$runtime/bus</listen>
|
||||
<auth>EXTERNAL</auth>
|
||||
<policy context="default">
|
||||
<allow send_destination="*" eavesdrop="true"/>
|
||||
<allow eavesdrop="true"/>
|
||||
<allow own="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
CONF
|
||||
dbus-run-session --config-file="$SPIKE_STATE/dbus-session-wayland.conf" -- "$@"
|
||||
Executable
+71
@@ -0,0 +1,71 @@
|
||||
#!/bin/sh
|
||||
# Run a command on a private headless X display: Xvfb, a window manager
|
||||
# (openbox: fullscreen, activation and close requests need one) and a
|
||||
# private D-Bus session bus, so nothing reaches the desktop the command is
|
||||
# started from (its Wayland or X display, its session bus, its portals).
|
||||
#
|
||||
# spikes/gpui/headless.sh [-d DISPLAY_NUMBER] [-s WIDTHxHEIGHT] [-n] -- COMMAND...
|
||||
#
|
||||
# -d: the display number (default 91); -s: the screen size (default
|
||||
# 3840x2160); -n: no window manager. Run it inside shell.sh (Xvfb, openbox
|
||||
# and dbus come from there). The display, the window manager's and the
|
||||
# command's state live in $SPIKE_STATE (default: .scratch/gpui-spikes-state
|
||||
# of the checkout, which git ignores).
|
||||
set -eu
|
||||
number=91 size=3840x2160 wm=1
|
||||
while [ $# -gt 0 ]; do
|
||||
case $1 in
|
||||
-d) number=$2; shift 2 ;;
|
||||
-s) size=$2; shift 2 ;;
|
||||
-n) wm=0; shift ;;
|
||||
--) shift; break ;;
|
||||
*) break ;;
|
||||
esac
|
||||
done
|
||||
[ $# -gt 0 ] || { echo "headless.sh: no command" >&2; exit 2; }
|
||||
root=$(cd "$(dirname "$0")/../.." && pwd)
|
||||
SPIKE_STATE=${SPIKE_STATE:-$root/.scratch/gpui-spikes-state}
|
||||
mkdir -p "$SPIKE_STATE/runtime" "$SPIKE_STATE/config" "$SPIKE_STATE/data" "$SPIKE_STATE/cache"
|
||||
chmod 700 "$SPIKE_STATE/runtime"
|
||||
if [ -e "/tmp/.X11-unix/X$number" ]; then
|
||||
echo "headless.sh: display :$number is taken" >&2
|
||||
exit 1
|
||||
fi
|
||||
Xvfb ":$number" -screen 0 "${size}x24" -nolisten tcp -noreset >"$SPIKE_STATE/xvfb-$number.log" 2>&1 &
|
||||
xvfb=$!
|
||||
trap 'kill $wm_pid $xvfb 2>/dev/null; wait $xvfb 2>/dev/null || true' EXIT INT TERM
|
||||
wm_pid=
|
||||
i=0
|
||||
until [ -e "/tmp/.X11-unix/X$number" ]; do
|
||||
i=$((i + 1))
|
||||
[ $i -lt 100 ] || { echo "headless.sh: Xvfb did not start" >&2; exit 1; }
|
||||
sleep 0.1
|
||||
done
|
||||
# Never the desktop's display, bus or portals.
|
||||
unset WAYLAND_DISPLAY WAYLAND_SOCKET XDG_SESSION_TYPE DBUS_SESSION_BUS_ADDRESS
|
||||
export DISPLAY=":$number"
|
||||
export XDG_RUNTIME_DIR="$SPIKE_STATE/runtime" XDG_CONFIG_HOME="$SPIKE_STATE/config"
|
||||
export XDG_DATA_HOME="$SPIKE_STATE/data" XDG_CACHE_HOME="$SPIKE_STATE/cache"
|
||||
export GPUI_X11_SCALE_FACTOR=${GPUI_X11_SCALE_FACTOR:-1}
|
||||
if [ $wm = 1 ]; then
|
||||
openbox --sm-disable >"$SPIKE_STATE/openbox-$number.log" 2>&1 &
|
||||
wm_pid=$!
|
||||
sleep 0.5
|
||||
fi
|
||||
# A session bus of its own that starts no services: the desktop's portals
|
||||
# (and their backends, which look for a compositor) stay out of the run.
|
||||
cat >"$SPIKE_STATE/dbus-session.conf" <<CONF
|
||||
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<type>session</type>
|
||||
<listen>unix:path=$SPIKE_STATE/runtime/bus</listen>
|
||||
<auth>EXTERNAL</auth>
|
||||
<policy context="default">
|
||||
<allow send_destination="*" eavesdrop="true"/>
|
||||
<allow eavesdrop="true"/>
|
||||
<allow own="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
CONF
|
||||
dbus-run-session --config-file="$SPIKE_STATE/dbus-session.conf" -- "$@"
|
||||
Executable
+74
@@ -0,0 +1,74 @@
|
||||
#!/bin/sh
|
||||
# Run a command with the spikes' build and run environment (NixOS): the
|
||||
# native libraries GPUI and voelin-media link, Mesa (lavapipe, the software
|
||||
# Vulkan device), the Vulkan loader, Xvfb, a window manager and the X tools
|
||||
# the measurements use, and a Rust toolchain on PATH.
|
||||
#
|
||||
# spikes/gpui/shell.sh cargo build --locked --release
|
||||
# TOOLCHAIN=nightly spikes/gpui/shell.sh cargo build --locked
|
||||
#
|
||||
# TOOLCHAIN: 1.95 (default: the oldest release gpui-kit builds with), 1.94
|
||||
# (rust-toolchain.toml's, which cannot build gpui-kit), stable or nightly,
|
||||
# all from one pinned fenix (stable: 2026-10-15's, nightly: 2026-10-24's);
|
||||
# RUST_BIN overrides the directory with cargo and rustc. VK_DRIVER_FILES: the
|
||||
# Vulkan drivers GPUI may use (default: lavapipe alone).
|
||||
set -eu
|
||||
substituters="https://cache.nixos.org/ https://nix-community.cachix.org"
|
||||
fenix=github:nix-community/fenix/e691190ae78c9551d1e6a0cba156555c8f7cceca
|
||||
components='[ "cargo" "rustc" "rust-std" "clippy" "rustfmt" ]'
|
||||
case "${TOOLCHAIN:-1.95}" in
|
||||
1.95) toolchain="(f.toolchainOf { channel = \"1.95.0\"; sha256 = \"sha256-gh/xTkxKHL4eiRXzWv8KP7vfjSk61Iq48x47BEDFgfk=\"; })" ;;
|
||||
1.94) toolchain="(f.toolchainOf { channel = \"1.94.0\"; sha256 = \"sha256-qqF33vNuAdU5vua96VKVIwuc43j4EFeEXbjQ6+l4mO4=\"; })" ;;
|
||||
stable) toolchain=f.stable ;;
|
||||
nightly) toolchain=f.latest ;;
|
||||
*) echo "shell.sh: TOOLCHAIN is 1.95, 1.94, stable or nightly" >&2; exit 2 ;;
|
||||
esac
|
||||
if [ -z "${RUST_BIN:-}" ]; then
|
||||
default_bin=$(nix build --option substituters "$substituters" --no-link --print-out-paths --impure \
|
||||
--expr "let f = (builtins.getFlake \"$fenix\").packages.x86_64-linux; in $toolchain.withComponents $components")/bin
|
||||
fi
|
||||
RUST_BIN=${RUST_BIN:-$default_bin}
|
||||
|
||||
# Tools (bin/ on PATH) and libraries (lib/ and pkg-config files).
|
||||
tools="gcc cmake gnumake pkg-config jq xvfb xdotool xwd imagemagick vulkan-tools
|
||||
procps xclip coreutils openbox dbus xrandr xdpyinfo xprop xwininfo"
|
||||
# Libraries with every output (lib/ and the pkg-config files are in different
|
||||
# ones).
|
||||
libs="alsa-lib openssl libvpx dav1d pipewire fontconfig freetype libxkbcommon
|
||||
expat wayland libxcb vulkan-loader libglvnd libx11 libxcursor libxrandr libxi libxext
|
||||
libxrender"
|
||||
installables="nixpkgs#libclang.lib nixpkgs#glibc.dev nixpkgs#mesa nixpkgs#noto-fonts-color-emoji
|
||||
nixpkgs#noto-fonts-cjk-sans"
|
||||
for p in $tools; do installables="$installables nixpkgs#$p"; done
|
||||
for p in $libs; do installables="$installables nixpkgs#$p^*"; done
|
||||
# shellcheck disable=SC2086
|
||||
paths=$(nix build --option substituters "$substituters" --no-link --print-out-paths $installables)
|
||||
|
||||
bin= pc= lib=
|
||||
for p in $paths; do
|
||||
[ -d "$p/bin" ] && bin="$bin:$p/bin"
|
||||
[ -d "$p/lib/pkgconfig" ] && pc="$pc:$p/lib/pkgconfig"
|
||||
[ -d "$p/share/pkgconfig" ] && pc="$pc:$p/share/pkgconfig"
|
||||
[ -d "$p/lib" ] && lib="$lib:$p/lib"
|
||||
case $p in
|
||||
*-mesa-[0-9]*) [ -e "$p/share/vulkan/icd.d/lvp_icd.x86_64.json" ] && MESA=$p ;;
|
||||
*-clang-*-lib) [ -e "$p/lib/libclang.so" ] && LIBCLANG_PATH=$p/lib ;;
|
||||
*-glibc-*-dev) GLIBC_INCLUDE=$p/include ;;
|
||||
*-noto-fonts-color-emoji-*) SPIKE_EMOJI_FONT=$p/share/fonts/noto/NotoColorEmoji.ttf ;;
|
||||
*-noto-fonts-cjk-sans-*) SPIKE_EXTRA_FONTS=$p/share/fonts/opentype/noto-cjk/NotoSansCJK-VF.otf.ttc ;;
|
||||
esac
|
||||
done
|
||||
export PATH="$RUST_BIN$bin:$PATH"
|
||||
export PKG_CONFIG_PATH="${pc#:}"
|
||||
# Run time: the Vulkan loader, libGL/EGL, Wayland and xkbcommon are opened
|
||||
# by name (dlopen); link time: -L for every library above.
|
||||
export LD_LIBRARY_PATH="${lib#:}${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
|
||||
export LIBRARY_PATH="${lib#:}"
|
||||
export LIBCLANG_PATH MESA
|
||||
# The fonts the spikes add to GPUI (common/src/fonts.rs): colour emoji, CJK.
|
||||
export SPIKE_EMOJI_FONT SPIKE_EXTRA_FONTS
|
||||
# bindgen (libclang, unwrapped) needs the C library's headers.
|
||||
export BINDGEN_EXTRA_CLANG_ARGS="-isystem $GLIBC_INCLUDE"
|
||||
export VK_DRIVER_FILES="${VK_DRIVER_FILES:-$MESA/share/vulkan/icd.d/lvp_icd.x86_64.json}"
|
||||
export __EGL_VENDOR_LIBRARY_DIRS="$MESA/share/glvnd/egl_vendor.d"
|
||||
exec "$@"
|
||||
Reference in new issue
Block a user