diff --git a/spikes/gpui/Cargo.lock b/spikes/gpui/Cargo.lock index f411bb1..58fa484 100644 --- a/spikes/gpui/Cargo.lock +++ b/spikes/gpui/Cargo.lock @@ -8313,6 +8313,21 @@ dependencies = [ "yuv", ] +[[package]] +name = "spike-windows" +version = "0.0.0" +dependencies = [ + "anyhow", + "futures", + "gpui-kit", + "log", + "serde_json", + "spike-common", + "tokio", + "voelin-media", + "voelin-platform", +] + [[package]] name = "spin" version = "0.9.9" @@ -9803,6 +9818,7 @@ dependencies = [ "tokio", "tracing", "windows 0.62.2", + "x11rb", ] [[package]] diff --git a/spikes/gpui/Cargo.toml b/spikes/gpui/Cargo.toml index 5bcf6a7..20a90ac 100644 --- a/spikes/gpui/Cargo.toml +++ b/spikes/gpui/Cargo.toml @@ -4,7 +4,7 @@ # into the checkout's target directory (.cargo/config.toml). [workspace] resolver = "3" -members = ["common", "video", "composer"] +members = ["common", "video", "composer", "windows"] [workspace.package] version = "0.0.0" diff --git a/spikes/gpui/windows/Cargo.toml b/spikes/gpui/windows/Cargo.toml new file mode 100644 index 0000000..db814ef --- /dev/null +++ b/spikes/gpui/windows/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "spike-windows" +description = "Spike 3: a second window sharing the root entity, focus, fullscreen, close, a global push-to-talk hotkey and a shared preview." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +anyhow = "1" +gpui-kit = { workspace = true } +log = { workspace = true } +spike-common = { workspace = true } +futures = "0.3" +serde_json = "1" +tokio = { version = "1", features = ["rt-multi-thread", "time"] } +voelin-media = { workspace = true } +voelin-platform = { workspace = true } + +[lints] +workspace = true diff --git a/spikes/gpui/windows/README.md b/spikes/gpui/windows/README.md new file mode 100644 index 0000000..d4667f9 --- /dev/null +++ b/spikes/gpui/windows/README.md @@ -0,0 +1,47 @@ +# Spike 3: the second window + +`spike-windows` opens a main window and, on Ctrl+O (or the Open Studio +button), a Studio-like window with `cx.open_window` (`gpui_kit::open_window`, +which wraps the view in gpui-component's `Root`). Both windows render one +root entity, `Shared`: a counter both change (Ctrl+K or +1 in either), the +push-to-talk state, which window is active, and the studio's preview. + +- **Preview.** GPUI cannot read a window's pixels (no `take_snapshot`), so + the studio's preview comes from where the client gets it today: the + engine's compositor (`voelin_media::studio::Studio` with one scene of the + test pattern, 1920x1080 at 30 fps) and its preview tap at the studio's + default 960x540, 15 fps (RGBA). A thread converts each preview frame to + one BGRA `RenderImage`; the shared entity holds it and both windows show + the same `Arc` (`img()`), the replaced one leaves every window's atlas + (`cx.drop_image(old, None)`). +- **Global push-to-talk.** `voelin_platform::hotkey::HotkeyManager::x11` + on the display (XInput2 raw events on the root window: whichever window + has focus, nothing grabbed), F8 by default (`--hotkey`). Its events (a + tokio `UnboundedReceiver`) are read by a GPUI foreground task, which needs + no tokio reactor, and set the shared model. +- **Close and fullscreen.** Closing the studio window (`on_window_should_close`) + docks the studio back into the main window and the app goes on; closing + the main window quits. F11 toggles fullscreen in either window; Ctrl+Tab + activates the other window (`Window::activate_window`). + +Every change is a JSON line on stdout (`{"event": …}`); with `--seconds` the +meter adds its once-a-second CPU and memory lines. + +## Reproducing + +```sh +spikes/gpui/shell.sh sh -c 'cd spikes/gpui && cargo build --locked --release' +# the scenario and its eleven checks (PASS/FAIL), screenshots in $OUT: +spikes/gpui/shell.sh spikes/gpui/headless.sh -- spikes/gpui/windows/drive.sh +# the cost of the shared preview: CPU and memory with the main window +# alone, with both windows showing it, and without the compositor (45 s +# each, 10 s of warm-up; .jsonl and .load in $OUT): +spikes/gpui/shell.sh spikes/gpui/headless.sh -- spikes/gpui/windows/measure.sh +``` + +`drive.sh` (xdotool on the headless display, keys through XTEST so the +hotkey's raw events see them): Ctrl+O in the main window; Ctrl+K twice in +the studio window; F8 held while the studio window has focus; F11 twice; +Ctrl+Tab; Ctrl+K in the main window; Alt+F4 on the studio window (openbox +asks it to close); F8 with the main window active; Alt+F4 on the main +window. Results: [docs/design/gpui-spikes.md](../../../docs/design/gpui-spikes.md#spike-3-the-second-window). diff --git a/spikes/gpui/windows/drive.sh b/spikes/gpui/windows/drive.sh new file mode 100755 index 0000000..9ef8c66 --- /dev/null +++ b/spikes/gpui/windows/drive.sh @@ -0,0 +1,118 @@ +#!/bin/sh +# Spike 3's scenario on the headless display: opens the studio window from +# the main one, changes the shared counter from both, holds the global +# push-to-talk key while the studio window has focus, toggles fullscreen, +# moves focus with GPUI and with the window manager, closes the studio +# window (it docks) and then the main one (the app ends); then checks the +# events the spike printed. Screenshots and the event log go to $OUT. +# +# spikes/gpui/shell.sh spikes/gpui/headless.sh -- spikes/gpui/windows/drive.sh +set -eu +root=$(cd "$(dirname "$0")/../../.." && pwd) +out=${OUT:-$root/.scratch/gpui-spikes-results} +mkdir -p "$out" +out=$(cd "$out" && pwd) +events=$out/windows-events.jsonl +"$root/target/release/spike-windows" --seconds 120 --warmup 3 >"$events" 2>"$out/windows.log" & +pid=$! +shot() { xwd -root -silent | magick xwd:- -resize 50% "png:$out/$1"; } +find_window() { + i=0 + until w=$(xdotool search --name "$1" 2>/dev/null | head -1) && [ -n "$w" ]; do + i=$((i + 1)) + [ $i -lt 150 ] || { echo "no window $1" >&2; return 1; } + sleep 0.1 + done + echo "$w" +} +step() { echo "== $*" >&2; } + +main=$(find_window 'Voelin \(spike\)') +sleep 2 +step "Ctrl+O in the main window opens the studio window" +xdotool windowactivate --sync "$main" +sleep 0.3 +xdotool key ctrl+o +studio=$(find_window 'Stream Studio \(spike\)') +sleep 2 +step "Ctrl+K twice in the studio window: the shared counter" +xdotool windowactivate --sync "$studio" +sleep 0.3 +xdotool key ctrl+k +sleep 0.2 +xdotool key ctrl+k +sleep 0.5 +step "the global push-to-talk key held while the studio window has focus" +xdotool keydown F8 +sleep 0.6 +shot windows-talking.png +xdotool keyup F8 +sleep 0.5 +step "F11: the studio window fullscreen, then windowed" +xdotool key F11 +sleep 1.5 +shot windows-studio-fullscreen.png +xdotool key F11 +sleep 1.5 +step "Ctrl+Tab in the studio: GPUI activates the main window" +xdotool key ctrl+Tab +sleep 1 +step "Ctrl+K in the main window" +xdotool key ctrl+k +sleep 0.5 +shot windows-both.png +step "the window manager activates the studio window, Alt+F4 closes it" +xdotool windowactivate --sync "$studio" +sleep 0.5 +xdotool key alt+F4 +sleep 1 +step "push-to-talk with the main window and no studio window" +xdotool windowactivate --sync "$main" +sleep 0.3 +xdotool keydown F8 +sleep 0.3 +xdotool keyup F8 +sleep 0.5 +shot windows-docked.png +step "Alt+F4 on the main window ends the app" +xdotool key alt+F4 +ended=true +i=0 +while kill -0 "$pid" 2>/dev/null; do + i=$((i + 1)) + if [ $i -ge 100 ]; then + ended=false + kill "$pid" + break + fi + sleep 0.1 +done +wait "$pid" || true + +fail=0 +check() { + if jq -e -s "$2" "$events" >/dev/null; then + echo "PASS $1" + else + echo "FAIL $1" + fail=1 + fi +} +ev='[.[] | select(.event)]' +check "the studio window opens from the main one" "$ev | any(.event == \"studio window opened\")" +check "a key in the studio window reaches the shared model" "$ev | map(select(.event == \"studio: increment\")) | length == 2 and (last.counter == 2)" +check "the global hotkey reaches the shared model with the studio window active" "$ev | any(.event == \"hotkey Pressed with the studio window active\" and .talking)" +check "the hotkey's release too" "$ev | any(.event | startswith(\"hotkey Released\"))" +check "fullscreen and back" "$ev | (any(.event | startswith(\"studio window fullscreen\")) and any(.event | startswith(\"studio window windowed\")))" +check "the studio window gets its own size back (1000x900)" "$ev | any(.event == \"studio window now 1000x900\")" +check "GPUI moves focus to the other window (Ctrl+Tab)" "$ev | (map(select(.event | startswith(\"studio window windowed\"))) | last.t) as \$a | (map(select(.event == \"main: increment\")) | first.t) as \$b | any(.event == \"main window active\" and .t >= \$a and .t <= \$b)" +check "the main window changes the same counter" "$ev | any(.event == \"main: increment\" and .counter == 3)" +check "closing the studio window docks it, the app goes on" "$ev | any(.event == \"studio window closed, docked in the main window\")" +check "the hotkey with the main window active" "$ev | any(.event == \"hotkey Pressed with the main window active\")" +if $ended; then + echo "PASS closing the main window ends the app (after $((i / 10)).$((i % 10)) s)" +else + echo "FAIL closing the main window ends the app (killed after 10 s)" + fail=1 +fi +exit $fail diff --git a/spikes/gpui/windows/measure.sh b/spikes/gpui/windows/measure.sh new file mode 100755 index 0000000..70f61ec --- /dev/null +++ b/spikes/gpui/windows/measure.sh @@ -0,0 +1,33 @@ +#!/bin/sh +# The cost of spike 3's shared preview on the headless display: CPU and +# memory with the main window alone (the preview in it), with the studio's +# window open too (one picture in both), and with both windows but no +# compositor. Every case writes .jsonl (one line a second, then the +# summary) and .load (load average before and after) to $OUT. +# +# spikes/gpui/shell.sh spikes/gpui/headless.sh -- spikes/gpui/windows/measure.sh [CASE...] +# +# Cases (default: all): windows-main windows-both windows-none. +# SECONDS_RUN (default 45) and WARMUP (default 10) set their length. +set -eu +root=$(cd "$(dirname "$0")/../../.." && pwd) +out=${OUT:-$root/.scratch/gpui-spikes-results} +mkdir -p "$out" +out=$(cd "$out" && pwd) +seconds=${SECONDS_RUN:-45} +warmup=${WARMUP:-10} +for c in ${*:-windows-main windows-both windows-none}; do + case $c in + windows-main) args= ;; + windows-both) args=--open-studio ;; + windows-none) args="--open-studio --no-preview" ;; + *) echo "unknown case $c" >&2; exit 2 ;; + esac + echo "== $c: spike-windows $args" >&2 + echo "load before: $(cat /proc/loadavg)" >"$out/$c.load" + # shellcheck disable=SC2086 + "$root/target/release/spike-windows" $args --seconds "$seconds" --warmup "$warmup" \ + --out "$out/$c.jsonl" >/dev/null 2>"$out/$c.log" + echo "load after: $(cat /proc/loadavg)" >>"$out/$c.load" + tail -1 "$out/$c.jsonl" +done diff --git a/spikes/gpui/windows/src/main.rs b/spikes/gpui/windows/src/main.rs new file mode 100644 index 0000000..d3e4265 --- /dev/null +++ b/spikes/gpui/windows/src/main.rs @@ -0,0 +1,528 @@ +//! 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>, + preview_frames: u64, + main: Option, + studio: Option, + /// Which window has focus ("main", "studio", "none"). + active: &'static str, + events: Vec, +} + +impl Shared { + /// Note `what` (a JSON line on stdout and the windows' event list). + fn event(&mut self, what: impl Into) { + 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, + 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, + window: &mut Window, + cx: &mut Context, + ) -> 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) -> 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, 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>>>, + 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>>> = 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(()) +}