Author SHA1 Message Date
molluskandClaude Opus 4.7 675f25f266 chore: clear clippy warnings and refresh the GUI README
`cargo clippy --fix`: drop needless borrows in interactive.rs, remove an
unneeded `return`, and derive `Default` for `HostState` / the config struct
instead of hand-writing it. No behaviour change.

README: the GUI host screen now lists connected viewers with a Kick button
and notifies on join/leave — update the description, which still mentioned
only a "live viewer count".

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 16:42:35 -04:00
molluskandClaude Opus 4.7 e54d625f2a fix(gui): close the window on the first click while hosting
Closing the window while a host/viewer child was running took two clicks:
the first only dropped the stream, the second actually closed the window.

eframe drops the app synchronously while it destroys the window, which ran
`ChildProc`'s teardown — SIGINT plus a up-to-2s grace-period wait — on the
event-loop thread. That wait froze the window mid-close, so the first click
looked like it only killed the stream and the window lingered until a second
close event. (The teardown runs from `Drop`, not from an `on_exit` /
`close_requested` hook, so it fires on every backend and close path; those
hooks don't fire at all under some winit backends.)

Make the teardown non-blocking: hold the child in an `Option`, and on drop
SIGINT it synchronously (so the host still runs its ctrl-c teardown even if
we exit immediately after) then reap it on a detached thread instead of
waiting inline. The app drops instantly, so the window closes on the first
click; the kicked-off SIGINT still tears the stream down cleanly.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 16:34:23 -04:00
molluskandClaude Opus 4.7 f926dbea4e feat(gui): desktop notification when a viewer joins or leaves
The host screen pops a desktop notification on each viewer join/leave,
so you know someone connected while the window is in the background.

Fired on a detached thread (the D-Bus call never touches the egui
frame) and gated on the same viewer-list transitions, so stopping the
host — which drops the child and stops pumping events — doesn't spray a
notification per remaining viewer.

notify-rust's default features give the pure-Rust zbus backend, so this
adds no system libdbus dependency and no GTK event loop (gui feature
only; the headless build is untouched).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 15:31:48 -04:00
molluskandClaude Opus 4.7 24e0d0e799 feat(gui): list connected viewers and let the host kick them
Track viewers by endpoint id instead of a bare count. The JSON event
stream gains viewer_joined / viewer_left (each carrying the id),
replacing viewer_count; active/max still ride along so the count
display is unchanged.

The host screen now renders one row per connected viewer with a Kick
button. Clicking it sends `kick <id>` to the headless child over a new
stdin command channel, which the host turns into a per-viewer
CancellationToken cancel; the existing teardown path then emits the
leave, so a kick and a self-disconnect look identical downstream.

The stdin channel only runs under --output json (the GUI shell-out) and
on a detached OS thread, so a read parked on stdin can't hold up the
host's Ctrl+C shutdown.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 15:27:49 -04:00
9 changed files with 289 additions and 837 deletions
Generated
+86 -674
View File
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -34,9 +34,9 @@ ureq = { version = "3", default-features = false, features = ["rustls"] }
toml = "1"
chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] }
eframe = { version = "0.34.2", default-features = false, features = ["glow", "default_fonts", "wayland", "x11"], optional = true }
tray-icon = { version = "0.24.0", optional = true }
notify-rust = { version = "4.17.0", optional = true }
gtk = { version = "0.18.2", optional = true }
# Desktop notifications on viewer join/leave. Default features give the
# pure-Rust zbus backend (no system libdbus, no image crate).
notify-rust = { version = "4", optional = true }
[profile.release]
lto = "thin"
@@ -46,4 +46,4 @@ strip = "symbols"
[features]
# Opt-in graphical front-end (pixelpass --gui). Default-off so the headless
# build never pulls the GUI toolkit tree.
gui = ["dep:eframe", "dep:tray-icon", "dep:notify-rust", "dep:gtk"]
gui = ["dep:eframe", "dep:notify-rust"]
+3 -2
View File
@@ -83,8 +83,9 @@ pixelpass --gui
```
Host: pick quality / max-viewers / options, click **Start hosting**, and the
share code appears with a copy button alongside a live viewer count. View:
paste a code, pick mpv or VLC, click **Connect** and the player launches.
share code appears with a copy button. Connected viewers are listed with a
**Kick** button each, and a desktop notification fires as they join or leave.
View: paste a code, pick mpv or VLC, click **Connect** and the player launches.
The window is a thin driver — it runs the same headless `pixelpass` as a
child process and reads its event stream, so the GUI is purely additive and
+2 -5
View File
@@ -37,18 +37,15 @@ pub struct BandwidthEntry {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum BandwidthStatus {
#[default]
Unmeasured,
Measured,
Skipped,
Failed,
}
impl Default for BandwidthStatus {
fn default() -> Self {
Self::Unmeasured
}
}
fn default_status() -> BandwidthStatus {
BandwidthStatus::Unmeasured
+9 -3
View File
@@ -22,7 +22,11 @@ pub fn set_json(enabled: bool) {
JSON_ENABLED.store(enabled, Ordering::Relaxed);
}
fn json_enabled() -> bool {
/// Whether the JSON event stream is on — i.e. we're being driven by a
/// machine front-end (the `--gui` shell-out) rather than a human terminal.
/// Gates features that only make sense under that front-end, like the
/// stdin command channel the host reads `kick` requests from.
pub fn json_enabled() -> bool {
JSON_ENABLED.load(Ordering::Relaxed)
}
@@ -42,9 +46,11 @@ pub enum Event<'a> {
max_viewers: u32,
max_viewers_source: &'a str,
},
/// A new viewer joined.
/// A viewer joined. `id` is the viewer's endpoint id; `active` is the new
/// total after the join.
ViewerJoined { id: &'a str, active: u32, max: u32 },
/// A viewer disconnected.
/// A viewer left — disconnected on their own or kicked by the host. `id`
/// is the viewer's endpoint id; `active` is the new total after.
ViewerLeft { id: &'a str, active: u32, max: u32 },
/// Capture pipeline lifecycle (spawned on first viewer, torn down on last).
Capture { state: CaptureState },
+52 -37
View File
@@ -6,8 +6,8 @@
//! egui app drains each frame. stderr is captured into a small ring so a
//! failed launch (e.g. a missing gst plugin) can be surfaced in the window.
use std::io::{BufRead, BufReader};
use std::process::{Child, Command, Stdio};
use std::io::{BufRead, BufReader, Write};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::Receiver;
use std::sync::{Arc, Mutex};
use std::time::Duration;
@@ -66,10 +66,14 @@ pub enum CaptureState {
const STDERR_TAIL_MAX: usize = 60;
pub struct ChildProc {
child: Child,
/// `Some` while the child is owned here; `Drop` takes it to hand off to a
/// detached reaper thread (see the `Drop` impl).
child: Option<Child>,
pub rx: Receiver<ChildEvent>,
stderr_tail: Arc<Mutex<Vec<String>>>,
stdin: std::process::ChildStdin,
/// Write end of the child's stdin, for the line-based command channel
/// (see [`ChildProc::send_command`]). `None` once it's been closed.
stdin: Option<ChildStdin>,
}
impl ChildProc {
@@ -79,13 +83,15 @@ impl ChildProc {
let exe = std::env::current_exe()?;
let mut child = Command::new(exe)
.args(args)
// Piped so we can send line commands (e.g. `kick <id>`); the host
// only reads it when driven this way (`--output json`).
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let stdin = child.stdin.take();
let (tx, rx) = std::sync::mpsc::channel();
let stdin = child.stdin.take().expect("stdin piped");
let stdout = child.stdout.take().expect("stdout piped");
std::thread::spawn(move || {
let reader = BufReader::new(stdout);
@@ -119,55 +125,64 @@ impl ChildProc {
});
Ok(Self {
child,
child: Some(child),
rx,
stderr_tail,
stdin,
})
}
/// Send one newline-terminated command to the child over its stdin (the
/// host parses these as `kick <endpoint-id>`). Best-effort: a closed pipe
/// (child already gone) just drops the command.
pub fn send_command(&mut self, cmd: &str) {
let Some(stdin) = self.stdin.as_mut() else {
return;
};
if let Err(e) = writeln!(stdin, "{cmd}") {
tracing::warn!("failed to send command to host child: {e}");
self.stdin = None; // pipe is dead; stop trying
}
}
/// Whether the child is still running.
pub fn is_alive(&mut self) -> bool {
matches!(self.child.try_wait(), Ok(None))
matches!(self.child.as_mut().map(Child::try_wait), Some(Ok(None)))
}
/// The last captured stderr lines, joined — for error display.
pub fn stderr_tail(&self) -> String {
self.stderr_tail.lock().unwrap().join("\n")
}
/// Send a newline-terminated command to the child.
pub fn send_command(&mut self, cmd: &str) {
use std::io::Write;
if let Err(e) = writeln!(self.stdin, "{cmd}") {
tracing::warn!("failed to send command to child: {e}");
}
}
/// Gracefully stop the child: SIGINT (so the host runs its ctrl-c teardown
/// — tears down capture, closes the endpoint), with a ~2 s grace period
/// before a hard kill. Idempotent.
pub fn stop(&mut self) {
if matches!(self.child.try_wait(), Ok(Some(_))) {
return; // already exited
}
let _ = kill(Pid::from_raw(self.child.id() as i32), Signal::SIGINT);
for _ in 0..40 {
if matches!(self.child.try_wait(), Ok(Some(_))) {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
let _ = self.child.kill();
let _ = self.child.wait();
}
}
impl Drop for ChildProc {
fn drop(&mut self) {
// Closing the window (dropping the app, hence the session) must not
// orphan a live host child streaming to viewers.
self.stop();
// Leaving a host/viewer screen, or closing the window, must not orphan
// a live child — but it must also not *block*. eframe runs this drop
// synchronously while it destroys the window, so a grace-period wait
// here freezes the window mid-close: the first click looks like it did
// nothing (the stream just drops) and the window only goes away on a
// second click. So SIGINT now — synchronously, so the host always gets
// its ctrl-c teardown (capture down, endpoint closed) even if we exit
// right after — then reap on a detached thread instead of waiting.
let Some(mut child) = self.child.take() else {
return;
};
if matches!(child.try_wait(), Ok(Some(_))) {
return; // already exited; nothing to signal or reap
}
let _ = kill(Pid::from_raw(child.id() as i32), Signal::SIGINT);
std::thread::spawn(move || {
for _ in 0..40 {
if matches!(child.try_wait(), Ok(Some(_))) {
return;
}
std::thread::sleep(Duration::from_millis(50));
}
let _ = child.kill();
let _ = child.wait();
});
}
}
@@ -222,7 +237,7 @@ mod tests {
}
#[test]
fn viewer_events_round_trips() {
fn viewer_join_leave_round_trip() {
assert!(matches!(
parse(Event::ViewerJoined { id: "nodeXYZ", active: 2, max: 4 }),
ChildEvent::ViewerJoined { id, active: 2, max: 4 } if id == "nodeXYZ"
+50 -73
View File
@@ -78,6 +78,23 @@ fn short_id(id: &str) -> String {
}
}
/// Fire a desktop notification, on a detached thread so the D-Bus round-trip
/// can't stall the egui frame. Best-effort: with no notification daemon it
/// just does nothing. (notify-rust talks D-Bus via pure-Rust zbus, so this
/// needs no system libdbus and no GTK event loop.)
fn notify(summary: &'static str, body: String) {
std::thread::spawn(move || {
if let Err(e) = notify_rust::Notification::new()
.appname("PixelPass")
.summary(summary)
.body(&body)
.show()
{
tracing::warn!("desktop notification failed: {e}");
}
});
}
/// Which screen the single window is currently showing.
#[derive(Default, PartialEq)]
enum Screen {
@@ -148,6 +165,7 @@ impl PlayerSel {
/// Host-screen state: the config form fields plus, once started, the running
/// child and the latest values parsed from its event stream.
#[derive(Default)]
struct HostState {
// form
quality: QualitySel,
@@ -168,30 +186,9 @@ struct HostState {
copied: bool,
last_refusal: Option<String>,
error: Option<String>,
/// Endpoint ids of the currently-connected viewers, in arrival order.
/// Drives the per-viewer list and its Kick buttons.
viewers: Vec<String>,
tray_icon: Option<tray_icon::TrayIcon>,
}
impl Default for HostState {
fn default() -> Self {
Self {
quality: QualitySel::default(),
max_viewers: 0,
no_hwencode: false,
window: false,
proc: None,
ticket: None,
info: None,
active: 0,
max: 0,
capturing: false,
copied: false,
last_refusal: None,
error: None,
viewers: Vec::new(),
tray_icon: None,
}
}
}
/// The host config summary echoed back by the child's `host_info` event.
@@ -235,11 +232,6 @@ impl eframe::App for PixelPassApp {
self.pump_host_events();
self.pump_viewer_events();
if let Ok(_event) = tray_icon::menu::MenuEvent::receiver().try_recv() {
// Only one menu item right now: "Stop Hosting"
self.stop_host();
}
match self.screen {
Screen::Menu => self.menu(ui),
Screen::Host => self.host(ui),
@@ -370,18 +362,22 @@ impl PixelPassApp {
ui.add_space(6.0);
ui.label(format!("Viewers: {} / {}", self.host.active, self.host.max));
if !self.host.viewers.is_empty() {
ui.add_space(4.0);
for id in &self.host.viewers.clone() {
ui.horizontal(|ui| {
ui.label(format!("{}", short_id(id)));
if ui.button("Kick").clicked() {
if let Some(p) = &mut self.host.proc {
p.send_command(&format!("kick {id}"));
}
}
});
}
// Per-viewer list with a Kick button each. Collect the click first so
// we're not borrowing self.host.viewers while we reach for the child.
let mut kick: Option<String> = None;
for id in &self.host.viewers {
ui.horizontal(|ui| {
ui.label(format!("• endpoint {}", short_id(id)));
if ui.small_button("Kick").clicked() {
kick = Some(id.clone());
}
});
}
if let Some(id) = kick
&& let Some(p) = &mut self.host.proc
{
p.send_command(&format!("kick {id}"));
}
if let Some(info) = &self.host.info {
@@ -474,6 +470,7 @@ impl PixelPassApp {
self.host.max = 0;
self.host.capturing = false;
self.host.copied = false;
self.host.viewers.clear();
let mut args = vec![
"--host".to_string(),
@@ -494,28 +491,7 @@ impl PixelPassApp {
}
match ChildProc::spawn(&args, ctx) {
Ok(p) => {
self.host.proc = Some(p);
#[cfg(target_os = "linux")]
if let Err(e) = gtk::init() {
tracing::warn!("Failed to initialize GTK for system tray: {e}");
}
use tray_icon::{TrayIconBuilder, menu::{Menu, MenuItem}};
let menu = Menu::new();
let _ = menu.append(&MenuItem::new("Stop Hosting", true, None));
let icon = tray_icon::Icon::from_rgba(vec![255, 0, 0, 255], 1, 1).unwrap();
if let Ok(tray) = TrayIconBuilder::new()
.with_title("PixelPass")
.with_tooltip("PixelPass Screen Sharing")
.with_icon(icon)
.with_menu(Box::new(menu))
.build()
{
self.host.tray_icon = Some(tray);
}
}
Ok(p) => self.host.proc = Some(p),
Err(e) => self.host.error = Some(format!("Couldn't start host: {e}")),
}
}
@@ -527,7 +503,6 @@ impl PixelPassApp {
self.host.ticket = None;
self.host.copied = false;
self.host.viewers.clear();
self.host.tray_icon = None;
}
/// Drain the host child's event channel into state, and detect an
@@ -592,21 +567,23 @@ impl PixelPassApp {
self.host.active = active;
self.host.max = max;
if !self.host.viewers.contains(&id) {
self.host.viewers.push(id.clone());
let _ = notify_rust::Notification::new()
.summary("PixelPass Viewer Connected")
.body(&format!("Viewer {} joined the stream.", short_id(&id)))
.show();
notify(
"PixelPass — viewer connected",
format!("endpoint {} is now watching ({active}/{max})", short_id(&id)),
);
self.host.viewers.push(id);
}
}
ChildEvent::ViewerLeft { id, active, max } => {
self.host.active = active;
self.host.max = max;
self.host.viewers.retain(|v| v != &id);
let _ = notify_rust::Notification::new()
.summary("PixelPass Viewer Disconnected")
.body(&format!("Viewer {} left the stream.", short_id(&id)))
.show();
if self.host.viewers.iter().any(|v| v == &id) {
notify(
"PixelPass — viewer disconnected",
format!("endpoint {} left ({active}/{max})", short_id(&id)),
);
self.host.viewers.retain(|v| v != &id);
}
}
ChildEvent::Capture { state } => {
self.host.capturing = matches!(state, child::CaptureState::Started);
+77 -33
View File
@@ -12,7 +12,6 @@ use iroh::{Endpoint, EndpointAddr};
use iroh_tickets::endpoint::EndpointTicket;
use std::collections::HashMap;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;
@@ -25,11 +24,16 @@ use crate::common::{
use self::pipeline::CaptureHandle;
use self::quality::EffectiveQuality;
/// Messages from per-viewer tasks to the capture supervisor.
/// Messages from per-viewer tasks (and the GUI command channel) to the
/// capture supervisor.
// The shared `Viewer` suffix is the point — these are all viewer lifecycle
// messages — so keep the descriptive names.
#[allow(clippy::enum_variant_names)]
enum SupervisorMsg {
/// A new viewer wants in. Supervisor replies with the local capture
/// HTTP port to connect to, or an error string if the host is full or
/// capture spawn failed.
/// A new viewer wants in. Supervisor replies with the local capture HTTP
/// port to connect to, or an error string if the host is full or capture
/// spawn failed. `cancel` is the viewer's own token — the supervisor keeps
/// it so a later `KickViewer` can tear this viewer's stream down.
AddViewer {
id: String,
cancel: CancellationToken,
@@ -38,7 +42,9 @@ enum SupervisorMsg {
/// A viewer's session ended. Supervisor decrements the count and tears
/// down capture if it just hit zero.
RemoveViewer { id: String },
/// Request to kick a specific viewer.
/// Host asked (via the GUI command channel) to disconnect a viewer by
/// endpoint id. Cancels that viewer's token; the normal teardown path then
/// emits the `ViewerLeft`.
KickViewer { id: String },
}
@@ -121,16 +127,14 @@ pub async fn run(opts: HostOpts) -> Result<()> {
sup_rx,
));
// Stdin listener for "kick <id>"
let stdin_sup_tx = sup_tx.clone();
tokio::spawn(async move {
let mut lines = BufReader::new(tokio::io::stdin()).lines();
while let Ok(Some(line)) = lines.next_line().await {
if let Some(id) = line.strip_prefix("kick ") {
let _ = stdin_sup_tx.send(SupervisorMsg::KickViewer { id: id.trim().to_string() }).await;
}
}
});
// Command channel for the GUI front-end: read `kick <endpoint-id>` lines
// off stdin. Only when machine-driven (`--output json`) — a human host has
// nothing to type here, and we don't want to swallow terminal input. Runs
// on a plain OS thread (not a tokio task) so a read parked on stdin can't
// hold up runtime shutdown on Ctrl+C; the thread dies with the process.
if output::json_enabled() {
spawn_kick_listener(sup_tx.clone());
}
accept_loop(&endpoint, sup_tx.clone(), cancel.clone()).await;
@@ -178,11 +182,18 @@ async fn handle_peer(
cancel: CancellationToken,
) {
let remote = conn.remote_id();
let id_str = remote.to_string();
let id = remote.to_string();
// This viewer's own kill switch: the supervisor holds a clone so a `kick`
// can cancel it, and the stream select! below watches it.
let peer_cancel = CancellationToken::new();
let (reply_tx, reply_rx) = oneshot::channel();
if sup_tx.send(SupervisorMsg::AddViewer { id: id_str.clone(), cancel: peer_cancel.clone(), reply: reply_tx }).await.is_err() {
let add = SupervisorMsg::AddViewer {
id: id.clone(),
cancel: peer_cancel.clone(),
reply: reply_tx,
};
if sup_tx.send(add).await.is_err() {
tracing::warn!(%remote, "supervisor channel closed; dropping peer");
return;
}
@@ -203,7 +214,7 @@ async fn handle_peer(
Ok(s) => s,
Err(e) => {
tracing::warn!(%remote, "accept_bi failed: {e:#}");
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id: id_str }).await;
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
return;
}
};
@@ -214,7 +225,7 @@ async fn handle_peer(
Ok(t) => t,
Err(e) => {
tracing::warn!(%remote, "connect_to_capture failed: {e:#}");
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id: id_str }).await;
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
return;
}
};
@@ -234,7 +245,28 @@ async fn handle_peer(
}
eprintln!("[pixelpass] viewer disconnected: {remote}");
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id: id_str }).await;
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id }).await;
}
/// Read `kick <endpoint-id>` lines off stdin and forward them to the
/// supervisor. Runs on a detached OS thread (see the call site for why). Ends
/// when stdin hits EOF (the GUI closed the pipe) or the supervisor is gone.
fn spawn_kick_listener(sup_tx: mpsc::Sender<SupervisorMsg>) {
use std::io::BufRead;
std::thread::spawn(move || {
let stdin = std::io::stdin();
for line in stdin.lock().lines().map_while(Result::ok) {
let Some(id) = line.trim().strip_prefix("kick ") else {
continue;
};
let msg = SupervisorMsg::KickViewer { id: id.trim().to_string() };
// blocking_send is valid here: this is a plain thread, not inside
// the tokio runtime. An Err means the supervisor closed — stop.
if sup_tx.blocking_send(msg).is_err() {
break;
}
}
});
}
/// Owns the single shared CaptureHandle and the active viewer count. Spawns
@@ -249,12 +281,15 @@ async fn supervise(
mut rx: mpsc::Receiver<SupervisorMsg>,
) {
let mut handle: Option<CaptureHandle> = None;
let mut count: u32 = 0;
// Active viewers, keyed by endpoint id, holding each one's kill switch.
// The count is just `viewers.len()`. (A given endpoint connecting twice is
// a non-case here: each viewer process uses a fresh ephemeral identity.)
let mut viewers: HashMap<String, CancellationToken> = HashMap::new();
while let Some(msg) = rx.recv().await {
match msg {
SupervisorMsg::AddViewer { id, cancel, reply } => {
let count = viewers.len() as u32;
if count >= max_viewers {
let reason =
format!("host is full ({count} of {max_viewers} viewers connected)");
@@ -280,18 +315,22 @@ async fn supervise(
}
let port = handle.as_ref().expect("handle was just set").local_port();
count += 1;
viewers.insert(id.clone(), cancel);
let active = viewers.len() as u32;
let _ = reply.send(Ok(port));
output::emit(output::Event::ViewerJoined { id: &id, active: count, max: max_viewers });
tracing::info!(active = count, cap = max_viewers, "viewer joined");
output::emit(output::Event::ViewerJoined { id: &id, active, max: max_viewers });
tracing::info!(active, cap = max_viewers, "viewer joined");
}
SupervisorMsg::RemoveViewer { id } => {
viewers.remove(&id);
count = count.saturating_sub(1);
output::emit(output::Event::ViewerLeft { id: &id, active: count, max: max_viewers });
tracing::info!(active = count, cap = max_viewers, "viewer left");
if count == 0
// A given viewer task only ever sends RemoveViewer once, but the
// map remove is the source of truth either way.
if viewers.remove(&id).is_none() {
continue;
}
let active = viewers.len() as u32;
output::emit(output::Event::ViewerLeft { id: &id, active, max: max_viewers });
tracing::info!(active, cap = max_viewers, "viewer left");
if active == 0
&& let Some(h) = handle.take()
{
tracing::info!("last viewer left — tearing down capture");
@@ -302,9 +341,14 @@ async fn supervise(
}
}
SupervisorMsg::KickViewer { id } => {
if let Some(cancel) = viewers.get(&id) {
tracing::info!(%id, "kicking viewer");
cancel.cancel();
match viewers.get(&id) {
// Cancel the viewer's token; its handle_peer select! wakes,
// sends RemoveViewer, and the leave is emitted there.
Some(cancel) => {
tracing::info!(%id, "kicking viewer");
cancel.cancel();
}
None => tracing::debug!(%id, "kick for unknown/already-gone viewer"),
}
}
}
+6 -6
View File
@@ -13,7 +13,7 @@ pub async fn run(cli: Cli) -> Result<()> {
let theme = ColorfulTheme::default();
let choice = Select::with_theme(&theme)
.with_prompt("What do you want to do?")
.items(&[
.items([
"Host (share my screen)",
"View (watch someone else's screen)",
])
@@ -112,7 +112,7 @@ fn pick_quality(theme: &ColorfulTheme) -> Result<Quality> {
let choice = Select::with_theme(theme)
.with_prompt("What quality should the viewer(s) get?")
.items(&items)
.items(items)
.default(0)
.interact()?;
@@ -138,7 +138,7 @@ pub async fn run_reconfigure() -> Result<()> {
async fn preflight_if_needed(theme: &ColorfulTheme) {
let mut cfg = config::load().unwrap_or_default();
match cfg.bandwidth.status {
config::BandwidthStatus::Measured | config::BandwidthStatus::Skipped => return,
config::BandwidthStatus::Measured | config::BandwidthStatus::Skipped => (),
config::BandwidthStatus::Unmeasured => {
eprintln!();
eprintln!("First-time setup");
@@ -154,7 +154,7 @@ async fn preflight_if_needed(theme: &ColorfulTheme) {
let Ok(choice) = Select::with_theme(theme)
.with_prompt("What would you like to do?")
.items(&[
.items([
"Run the bandwidth test (recommended)",
"Skip — use the conservative default",
])
@@ -180,7 +180,7 @@ async fn preflight_if_needed(theme: &ColorfulTheme) {
eprintln!();
let Ok(choice) = Select::with_theme(theme)
.with_prompt("Last bandwidth test failed. Try again?")
.items(&[
.items([
"Yes — retry now",
"No — use the conservative default",
])
@@ -341,7 +341,7 @@ pub fn prompt_player() -> Result<Player> {
let theme = ColorfulTheme::default();
let choice = Select::with_theme(&theme)
.with_prompt("Connected. Pick a player to launch")
.items(&["mpv", "VLC"])
.items(["mpv", "VLC"])
.default(0)
.interact()?;
Ok(if choice == 0 { Player::Mpv } else { Player::Vlc })