Files
VoelinClient/spikes/gpui/windows/src/main.rs
T
faumarayandClaude Opus 5.5 1ffcf690cc spikes/gpui/windows: spike 3, a second window on the shared model
A main window and a Studio-like window (cx.open_window through
gpui_kit::open_window) both render views that observe one root entity: a
counter both change, the push-to-talk state, which window is active, and
the studio's preview. Closing the studio window docks it
(on_window_should_close), closing the main window ends the app, F11
toggles fullscreen, Ctrl+Tab activates the other window. The global
push-to-talk key is voelin-platform's X11 hotkey (XInput2 raw events),
read by a GPUI foreground task. The preview comes from voelin-media's
studio compositor and its preview tap, one BGRA RenderImage shown by both
windows, the replaced one dropped from every atlas. drive.sh runs the
scenario and its checks on the headless display.

From the interrupted attempt, changed here: the window's size after a
fullscreen toggle is logged once the window manager has set it (the
toggle's own bounds are the old ones) and checked (1000x900 back);
drive.sh says how long the app took to end; measure.sh (new) runs the
three cost cases into $OUT instead of the README's commands, which wrote
into the current directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:43 +03:00

529 lines
16 KiB
Rust

//! Spike 3, the second window (plan section 6 step 1): a main window and a
//! Studio-like window opened with `cx.open_window`, both rendering one
//! shared model entity (a counter both change, the push-to-talk state, the
//! studio's preview); close, fullscreen and focus handling; a global
//! push-to-talk hotkey (`voelin-platform`'s X11 backend) that reaches the
//! shared model while the second window has focus; and the studio
//! compositor's preview shown in both windows as one shared `RenderImage`.
//!
//! ```text
//! spike-windows [--open-studio] [--no-preview] [--hotkey F8]
//! [--seconds 600] [--warmup 5] [--out FILE.jsonl]
//! ```
//!
//! Keys: Ctrl+K adds one (in either window), Ctrl+O opens the studio
//! window, Ctrl+Tab activates the other window, F11 toggles fullscreen,
//! closing the studio window docks it back. Every event is a JSON line on
//! stdout (`{"event": ...}`), which `drive.sh` checks.
use std::sync::atomic::AtomicU64;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use futures::StreamExt as _;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::{
AnyWindowHandle, App, AppContext as _, AsyncApp, Bounds, Context, Entity, FocusHandle,
ImageSource, InteractiveElement as _, IntoElement, KeyBinding, ObjectFit, ParentElement as _,
Render, RenderImage, SharedString, Styled as _, StyledImage as _, TitlebarOptions, Window,
WindowBounds, WindowOptions, actions, div, img, point, px, rgb, size,
};
use serde_json::json;
use spike_common::meter::{Counter, Meter};
use voelin_media::studio::scene::{Scene, Scenes, Source, SourceKind};
use voelin_media::studio::{Command, Studio};
use voelin_platform::hotkey::{HotkeyEvent, HotkeyManager};
actions!(
spike_windows,
[
/// Add one to the shared counter.
Increment,
/// Open (or activate) the studio's own window.
OpenStudio,
/// Toggle this window's fullscreen.
ToggleFullscreen,
/// Activate the other window.
ActivateOther,
/// End the app.
Quit,
]
);
/// The root model both windows render.
struct Shared {
start: Instant,
counter: i64,
talking: bool,
hotkey_presses: u64,
/// The studio compositor's newest preview, shown by both windows.
preview: Option<Arc<RenderImage>>,
preview_frames: u64,
main: Option<AnyWindowHandle>,
studio: Option<AnyWindowHandle>,
/// Which window has focus ("main", "studio", "none").
active: &'static str,
events: Vec<SharedString>,
}
impl Shared {
/// Note `what` (a JSON line on stdout and the windows' event list).
fn event(&mut self, what: impl Into<String>) {
let what = what.into();
println!(
"{}",
json!({"t": (self.start.elapsed().as_secs_f64() * 10.0).round() / 10.0, "event": what, "counter": self.counter, "talking": self.talking, "active": self.active})
);
self.events.push(what.into());
if self.events.len() > 8 {
self.events.remove(0);
}
}
}
/// Which window a view is.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Role {
Main,
Studio,
}
impl Role {
fn name(self) -> &'static str {
match self {
Self::Main => "main",
Self::Studio => "studio",
}
}
}
/// One window's view of the shared model.
struct Pane {
role: Role,
shared: Entity<Shared>,
focus: FocusHandle,
fullscreen: bool,
/// The size when fullscreen last changed: the bounds the window manager
/// sets afterwards are logged once they differ (they may come later).
resize_after_toggle: Option<(f32, f32)>,
}
impl Pane {
fn new(
role: Role,
shared: Entity<Shared>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
cx.observe(&shared, |_, _, cx| cx.notify()).detach();
cx.observe_window_activation(window, move |this: &mut Self, window, cx| {
let active = window.is_window_active();
this.shared.update(cx, |s, cx| {
if active {
s.active = role.name();
} else if s.active == role.name() {
s.active = "none";
}
s.event(format!(
"{} window {}",
role.name(),
if active { "active" } else { "inactive" }
));
cx.notify();
});
})
.detach();
cx.observe_window_bounds(window, move |this: &mut Self, window, cx| {
let fullscreen = window.is_fullscreen();
let bounds = window.bounds();
let size = (bounds.size.width.as_f32(), bounds.size.height.as_f32());
if fullscreen != this.fullscreen {
this.fullscreen = fullscreen;
this.resize_after_toggle = Some(size);
this.shared.update(cx, |s, _| {
s.event(format!(
"{} window {} ({}x{})",
role.name(),
if fullscreen { "fullscreen" } else { "windowed" },
size.0,
size.1
))
});
} else if this.resize_after_toggle.is_some_and(|before| before != size) {
this.resize_after_toggle = None;
this.shared.update(cx, |s, _| {
s.event(format!("{} window now {}x{}", role.name(), size.0, size.1))
});
}
})
.detach();
let focus = cx.focus_handle();
window.focus(&focus, cx);
Self { role, shared, focus, fullscreen: false, resize_after_toggle: None }
}
}
impl Render for Pane {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let role = self.role;
let s = self.shared.read(cx);
let (preview_w, preview_h) = match role {
Role::Main => (480.0, 270.0),
Role::Studio => (960.0, 540.0),
};
let preview = match &s.preview {
Some(picture) => img(ImageSource::Render(picture.clone()))
.w(px(preview_w))
.h(px(preview_h))
.object_fit(ObjectFit::Contain)
.into_any_element(),
None => div().w(px(preview_w)).h(px(preview_h)).bg(rgb(0x101828)).into_any_element(),
};
let title = match role {
Role::Main => "Main window",
Role::Studio => "Stream Studio (its own window)",
};
let studio_line = match (role, s.studio.is_some()) {
(Role::Main, true) => "The studio is in its own window",
(Role::Main, false) => "The studio is docked (Ctrl+O opens its window)",
(Role::Studio, _) => "Closing this window docks the studio",
};
div()
.id(role.name())
.key_context(match role {
Role::Main => "Main",
Role::Studio => "Studio",
})
.track_focus(&self.focus)
.on_action(cx.listener(move |this, _: &Increment, _, cx| {
this.shared.update(cx, |s, cx| {
s.counter += 1;
s.event(format!("{}: increment", role.name()));
cx.notify();
});
}))
.on_action(
cx.listener(|this, _: &OpenStudio, _, cx| open_studio(this.shared.clone(), cx)),
)
.on_action(cx.listener(|_, _: &ToggleFullscreen, window, _| window.toggle_fullscreen()))
.on_action(cx.listener(move |this, _: &ActivateOther, _, cx| {
let other = {
let s = this.shared.read(cx);
match role {
Role::Main => s.studio,
Role::Studio => s.main,
}
};
if let Some(other) = other {
let _ = other.update(cx, |_, window, _| window.activate_window());
}
}))
.size_full()
.flex()
.flex_col()
.gap_3()
.p_4()
.bg(rgb(0x0b1220))
.text_color(rgb(0xe6edf7))
.font(spike_common::fonts::ui_font())
.child(div().text_xl().child(title))
.child(format!("Counter (shared): {}", s.counter))
.child(format!(
"Push-to-talk (global hotkey): {}, {} presses",
if s.talking { "TALKING" } else { "silent" },
s.hotkey_presses
))
.child(format!("Active window: {}; preview frames: {}", s.active, s.preview_frames))
.child(studio_line)
.child(preview)
.child(
div()
.flex()
.gap_2()
.child(
Button::new(SharedString::from(format!("{}-plus", role.name())))
.primary()
.label("+1")
.on_click(cx.listener(move |this, _, _, cx| {
this.shared.update(cx, |s, cx| {
s.counter += 1;
s.event(format!("{}: +1 clicked", role.name()));
cx.notify();
})
})),
)
.when_main(role, |d| {
d.child(Button::new("open-studio").label("Open Studio").on_click(
cx.listener(|this, _, _, cx| open_studio(this.shared.clone(), cx)),
))
}),
)
.children(
s.events
.iter()
.rev()
.map(|e| div().text_sm().text_color(rgb(0x8b9bb4)).child(e.clone())),
)
}
}
/// `when` for the main window only.
trait WhenMain: Sized {
fn when_main(self, role: Role, f: impl FnOnce(Self) -> Self) -> Self {
if role == Role::Main { f(self) } else { self }
}
}
impl WhenMain for gpui_kit::Div {}
fn window_options(title: &str, size_px: (f32, f32), origin: (f32, f32)) -> WindowOptions {
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds {
origin: point(px(origin.0), px(origin.1)),
size: size(px(size_px.0), px(size_px.1)),
})),
titlebar: Some(TitlebarOptions {
title: Some(title.to_owned().into()),
..Default::default()
}),
// The preview plays on in the window without focus.
inactive_frame_interval: None,
..Default::default()
}
}
/// Open the studio's own window (once), sharing the root entity.
fn open_studio(shared: Entity<Shared>, cx: &mut App) {
if let Some(existing) = shared.read(cx).studio {
let _ = existing.update(cx, |_, window, _| window.activate_window());
return;
}
let opened = gpui_kit::open_window(
window_options("Stream Studio (spike)", (1000.0, 900.0), (1240.0, 40.0)),
cx,
{
let shared = shared.clone();
move |window, cx| {
let handle = window.window_handle();
// Closing the studio's window docks the studio again; the app
// goes on.
window.on_window_should_close(cx, {
let shared = shared.clone();
move |_, cx| {
shared.update(cx, |s, cx| {
s.studio = None;
if s.active == "studio" {
s.active = "none";
}
s.event("studio window closed, docked in the main window");
cx.notify();
});
true
}
});
shared.update(cx, |s, _| s.studio = Some(handle));
cx.new(|cx| Pane::new(Role::Studio, shared, window, cx))
}
},
);
match opened {
Ok(_) => shared.update(cx, |s, cx| {
s.event("studio window opened");
cx.notify();
}),
Err(e) => log::error!("cannot open the studio window: {e:#}"),
}
}
/// The studio compositor (voelin-media's `Studio`: one scene with the test
/// pattern, 1920x1080 at 30 fps) and its preview tap at 960x540, 15 fps,
/// the studio's default rate: every preview becomes one BGRA picture on a
/// thread of its own; `wake` runs when one is waiting.
fn start_compositor(
runtime: &tokio::runtime::Runtime,
latest: Arc<Mutex<Option<Arc<RenderImage>>>>,
converted: Counter,
wake: impl Fn() + Send + 'static,
) {
runtime.spawn(async move {
let mut scene = Scene::new(1, "Scene");
scene.sources.push(Source::new(1, SourceKind::Pattern { size: (1920, 1080) }));
let scenes = Scenes { scenes: vec![scene], active: 1, width: 1920, height: 1080, fps: 30 };
let studio = match Studio::start(scenes).await {
Ok(s) => s,
Err(e) => {
log::error!("no studio: {e}");
return;
}
};
if let Err(e) = studio.apply(Command::SetPreview { width: 960, height: 540, fps: 15 }).await
{
log::error!("no preview: {e}");
}
let tap = studio.preview();
std::thread::Builder::new()
.name("spike-preview".into())
.spawn(move || {
// The studio lives as long as its preview is read.
let _studio = studio;
loop {
let Some(frame) = tap.wait_timeout(Duration::from_secs(1)) else { continue };
match spike_common::bgra::picture(&frame) {
Ok(picture) => {
converted.incr();
let was_empty = latest
.lock()
.unwrap_or_else(PoisonError::into_inner)
.replace(picture)
.is_none();
if was_empty {
wake();
}
}
Err(e) => log::warn!("cannot show the preview: {e}"),
}
}
})
.expect("a preview thread");
});
}
fn main() -> anyhow::Result<()> {
spike_common::init_logging();
use spike_common::{arg, flag};
let seconds: u64 = arg("seconds").map_or(Ok(600), |v| v.parse())?;
let warmup: u64 = arg("warmup").map_or(Ok(5), |v| v.parse())?;
let preview_on = !flag("no-preview");
let open_studio_at_start = flag("open-studio");
let hotkey_name = arg("hotkey").unwrap_or_else(|| "F8".into());
let runtime =
tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build()?;
// The global hotkey: XInput2 raw events on the root window of this
// display, whichever window has focus (voelin-platform, X11 backend).
let display = std::env::var("DISPLAY").unwrap_or_else(|_| ":0".into());
let mut hotkeys = HotkeyManager::x11(&display)?;
let hotkey_events =
futures::executor::block_on(hotkeys.register("ptt", "Push to talk", hotkey_name.parse()?))?;
let latest: Arc<Mutex<Option<Arc<RenderImage>>>> = Arc::default();
let (converted, shown) = (Counter::default(), Counter::default());
let (wake_tx, mut wakes) = futures::channel::mpsc::unbounded::<()>();
if preview_on {
start_compositor(&runtime, latest.clone(), converted.clone(), move || {
let _ = wake_tx.unbounded_send(());
});
}
Meter {
config: json!({
"spike": "windows",
"preview": preview_on,
"open_studio": open_studio_at_start,
"hotkey": hotkey_name,
"display": display,
"vk_driver_files": std::env::var("VK_DRIVER_FILES").ok(),
}),
counters: vec![("preview_converted", converted), ("preview_shown", shown.clone())],
gauges: vec![],
warmup: Duration::from_secs(warmup),
duration: Duration::from_secs(seconds),
out: arg("out").map(Into::into),
}
.start(Arc::new(AtomicU64::new(0)));
gpui_kit::application().with_assets(spike_common::assets::Assets::default()).run(move |cx| {
gpui_kit::init(cx);
spike_common::fonts::load(cx);
gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, cx);
cx.bind_keys([
KeyBinding::new("ctrl-k", Increment, None),
KeyBinding::new("ctrl-o", OpenStudio, None),
KeyBinding::new("ctrl-tab", ActivateOther, None),
KeyBinding::new("f11", ToggleFullscreen, None),
KeyBinding::new("ctrl-q", Quit, None),
]);
cx.on_action(|_: &Quit, cx| cx.quit());
let shared = cx.new(|_| Shared {
start: Instant::now(),
counter: 0,
talking: false,
hotkey_presses: 0,
preview: None,
preview_frames: 0,
main: None,
studio: None,
active: "none",
events: Vec::new(),
});
let main = gpui_kit::open_window(
window_options("Voelin (spike)", (1200.0, 900.0), (20.0, 40.0)),
cx,
{
let shared = shared.clone();
move |window, cx| {
// The main window's close ends the app.
window.on_window_should_close(cx, |_, cx| {
cx.quit();
true
});
cx.new(|cx| Pane::new(Role::Main, shared, window, cx))
}
},
)
.expect("the main window");
shared.update(cx, |s, _| {
s.main = Some(main.0);
s.event("main window opened");
});
// The hotkey's events, on the UI thread: the tokio receiver needs no
// reactor.
let ptt = shared.clone();
let mut hotkey_events = hotkey_events;
cx.spawn(async move |cx: &mut AsyncApp| {
while let Some(event) = hotkey_events.recv().await {
ptt.update(cx, |s, cx| {
s.talking = event == HotkeyEvent::Pressed;
if s.talking {
s.hotkey_presses += 1;
}
s.event(format!("hotkey {event:?} with the {} window active", s.active));
cx.notify();
});
}
})
.detach();
// The preview: one picture for both windows; the one it replaces
// leaves every window's atlas.
let preview = shared.clone();
cx.spawn(async move |cx: &mut AsyncApp| {
while wakes.next().await.is_some() {
let Some(picture) = latest.lock().unwrap_or_else(PoisonError::into_inner).take()
else {
continue;
};
shown.incr();
cx.update(|cx| {
let old = preview.update(cx, |s, cx| {
s.preview_frames += 1;
cx.notify();
s.preview.replace(picture)
});
if let Some(old) = old {
cx.drop_image(old, None);
}
});
}
})
.detach();
if open_studio_at_start {
open_studio(shared, cx);
}
});
drop(hotkeys);
drop(runtime);
Ok(())
}