Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2e39251189 | ||
|
|
c2d04b35ba | ||
|
|
b4be8deb46 | ||
|
|
e8f86b0ac2 | ||
|
|
5d519ede78 | ||
|
|
ccb183219f | ||
|
|
d23848decc | ||
|
|
48f5510699 |
Generated
+970
-120
File diff suppressed because it is too large
Load Diff
+4
-1
@@ -34,6 +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 }
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
@@ -43,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"]
|
||||
gui = ["dep:eframe", "dep:tray-icon", "dep:notify-rust", "dep:gtk"]
|
||||
|
||||
@@ -42,8 +42,10 @@ pub enum Event<'a> {
|
||||
max_viewers: u32,
|
||||
max_viewers_source: &'a str,
|
||||
},
|
||||
/// Active viewer count changed.
|
||||
ViewerCount { active: u32, max: u32 },
|
||||
/// A new viewer joined.
|
||||
ViewerJoined { id: &'a str, active: u32, max: u32 },
|
||||
/// A viewer disconnected.
|
||||
ViewerLeft { id: &'a str, active: u32, max: u32 },
|
||||
/// Capture pipeline lifecycle (spawned on first viewer, torn down on last).
|
||||
Capture { state: CaptureState },
|
||||
/// A viewer was turned away (host full, or capture spawn failed).
|
||||
|
||||
+26
-5
@@ -35,7 +35,13 @@ pub enum ChildEvent {
|
||||
max_viewers: u32,
|
||||
max_viewers_source: String,
|
||||
},
|
||||
ViewerCount {
|
||||
ViewerJoined {
|
||||
id: String,
|
||||
active: u32,
|
||||
max: u32,
|
||||
},
|
||||
ViewerLeft {
|
||||
id: String,
|
||||
active: u32,
|
||||
max: u32,
|
||||
},
|
||||
@@ -63,6 +69,7 @@ pub struct ChildProc {
|
||||
child: Child,
|
||||
pub rx: Receiver<ChildEvent>,
|
||||
stderr_tail: Arc<Mutex<Vec<String>>>,
|
||||
stdin: std::process::ChildStdin,
|
||||
}
|
||||
|
||||
impl ChildProc {
|
||||
@@ -72,12 +79,13 @@ impl ChildProc {
|
||||
let exe = std::env::current_exe()?;
|
||||
let mut child = Command::new(exe)
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
|
||||
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);
|
||||
@@ -114,6 +122,7 @@ impl ChildProc {
|
||||
child,
|
||||
rx,
|
||||
stderr_tail,
|
||||
stdin,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -127,6 +136,14 @@ impl ChildProc {
|
||||
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.
|
||||
@@ -205,10 +222,14 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewer_count_round_trips() {
|
||||
fn viewer_events_round_trips() {
|
||||
assert!(matches!(
|
||||
parse(Event::ViewerCount { active: 2, max: 4 }),
|
||||
ChildEvent::ViewerCount { active: 2, max: 4 }
|
||||
parse(Event::ViewerJoined { id: "nodeXYZ", active: 2, max: 4 }),
|
||||
ChildEvent::ViewerJoined { id, active: 2, max: 4 } if id == "nodeXYZ"
|
||||
));
|
||||
assert!(matches!(
|
||||
parse(Event::ViewerLeft { id: "nodeXYZ", active: 1, max: 4 }),
|
||||
ChildEvent::ViewerLeft { id, active: 1, max: 4 } if id == "nodeXYZ"
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
+244
-13
@@ -43,6 +43,41 @@ fn set_clipboard(text: &str) -> bool {
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Best-effort clipboard read, backing the viewer Paste button and the
|
||||
/// View-screen prefill. `None` on a flaky/empty clipboard — callers just leave
|
||||
/// the field untouched.
|
||||
fn get_clipboard() -> Option<String> {
|
||||
arboard::Clipboard::new()
|
||||
.and_then(|mut cb| cb.get_text())
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Decode the host endpoint id from a ticket string, using the exact same
|
||||
/// parse the viewer does (`EndpointTicket::from_str`), so the GUI agrees with
|
||||
/// the child about what's a valid code. `None` means it isn't a pixelpass
|
||||
/// ticket at all. Used to surface a stale/garbage paste *before* the 15s
|
||||
/// connect timeout, and to show which host the viewer is dialing — the missing
|
||||
/// signal that let people repeatedly dial a long-dead host.
|
||||
fn ticket_endpoint_id(ticket: &str) -> Option<String> {
|
||||
ticket
|
||||
.trim()
|
||||
.parse::<iroh_tickets::endpoint::EndpointTicket>()
|
||||
.ok()
|
||||
.map(|t| t.endpoint_addr().id.to_string())
|
||||
}
|
||||
|
||||
/// Eyeball-comparable short form of an endpoint id (full ids are long). Enough
|
||||
/// to spot that two ids differ; the host and viewer screens show the same
|
||||
/// truncation so a stale ticket reads as an obvious mismatch.
|
||||
fn short_id(id: &str) -> String {
|
||||
let prefix: String = id.chars().take(12).collect();
|
||||
if prefix.len() < id.len() {
|
||||
format!("{prefix}…")
|
||||
} else {
|
||||
prefix
|
||||
}
|
||||
}
|
||||
|
||||
/// Which screen the single window is currently showing.
|
||||
#[derive(Default, PartialEq)]
|
||||
enum Screen {
|
||||
@@ -133,6 +168,8 @@ struct HostState {
|
||||
copied: bool,
|
||||
last_refusal: Option<String>,
|
||||
error: Option<String>,
|
||||
viewers: Vec<String>,
|
||||
tray_icon: Option<tray_icon::TrayIcon>,
|
||||
}
|
||||
|
||||
impl Default for HostState {
|
||||
@@ -151,6 +188,8 @@ impl Default for HostState {
|
||||
copied: false,
|
||||
last_refusal: None,
|
||||
error: None,
|
||||
viewers: Vec::new(),
|
||||
tray_icon: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -173,6 +212,12 @@ struct ViewerState {
|
||||
proc: Option<ChildProc>,
|
||||
url: Option<String>,
|
||||
launched: bool,
|
||||
/// Short endpoint id we're dialing, decoded from the ticket at Connect.
|
||||
/// Shown in the "Connecting to …" line so a dead host is identifiable.
|
||||
connecting_to: Option<String>,
|
||||
/// Set when the View screen opens so the code field grabs focus once
|
||||
/// (cleared on use, so it doesn't steal focus every frame).
|
||||
focus_ticket: bool,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
@@ -190,6 +235,11 @@ 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),
|
||||
@@ -204,6 +254,11 @@ impl PixelPassApp {
|
||||
ui.add_space(24.0);
|
||||
ui.heading("PixelPass");
|
||||
ui.label("P2P screen sharing");
|
||||
ui.label(
|
||||
egui::RichText::new(concat!("v", env!("CARGO_PKG_VERSION")))
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
ui.add_space(32.0);
|
||||
if ui
|
||||
.add_sized([260.0, 40.0], egui::Button::new("Host — share my screen"))
|
||||
@@ -220,6 +275,7 @@ impl PixelPassApp {
|
||||
.clicked()
|
||||
{
|
||||
self.screen = Screen::Viewer;
|
||||
self.prefill_viewer_ticket();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -314,6 +370,19 @@ 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}"));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(info) = &self.host.info {
|
||||
ui.label(
|
||||
@@ -342,6 +411,15 @@ impl PixelPassApp {
|
||||
|
||||
if let Some(ticket) = self.host.ticket.clone() {
|
||||
ui.label("Share this code with your viewer(s):");
|
||||
if let Some(id) = ticket_endpoint_id(&ticket) {
|
||||
// The viewer shows "Connecting to <id>…" with this same
|
||||
// truncation, so the two ends can be eyeballed for a match.
|
||||
ui.label(
|
||||
egui::RichText::new(format!("This host: endpoint {}", short_id(&id)))
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
egui::Frame::group(ui.style()).show(ui, |ui| {
|
||||
ui.add(
|
||||
@@ -416,7 +494,28 @@ impl PixelPassApp {
|
||||
}
|
||||
|
||||
match ChildProc::spawn(&args, ctx) {
|
||||
Ok(p) => self.host.proc = Some(p),
|
||||
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);
|
||||
}
|
||||
}
|
||||
Err(e) => self.host.error = Some(format!("Couldn't start host: {e}")),
|
||||
}
|
||||
}
|
||||
@@ -427,6 +526,8 @@ impl PixelPassApp {
|
||||
self.host.capturing = false;
|
||||
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
|
||||
@@ -487,9 +588,25 @@ impl PixelPassApp {
|
||||
cap_source: max_viewers_source,
|
||||
});
|
||||
}
|
||||
ChildEvent::ViewerCount { active, max } => {
|
||||
ChildEvent::ViewerJoined { id, active, max } => {
|
||||
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();
|
||||
}
|
||||
}
|
||||
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();
|
||||
}
|
||||
ChildEvent::Capture { state } => {
|
||||
self.host.capturing = matches!(state, child::CaptureState::Started);
|
||||
@@ -542,11 +659,51 @@ impl PixelPassApp {
|
||||
|
||||
ui.label("Paste the share code you received:");
|
||||
ui.add_space(4.0);
|
||||
ui.add(
|
||||
egui::TextEdit::singleline(&mut self.viewer.ticket_input)
|
||||
.desired_width(f32::INFINITY)
|
||||
.hint_text("endpoint…"),
|
||||
);
|
||||
// A Paste button (read-side mirror of the host's Copy button — one
|
||||
// click grabs the code the host just put on the clipboard) with the
|
||||
// field filling the rest of the row. A single horizontal row, so it
|
||||
// doesn't grab the panel's full height.
|
||||
let ticket_resp = ui
|
||||
.horizontal(|ui| {
|
||||
if ui.button("📋 Paste").clicked()
|
||||
&& let Some(text) = get_clipboard()
|
||||
{
|
||||
self.viewer.ticket_input = text.trim().to_string();
|
||||
}
|
||||
ui.add(
|
||||
egui::TextEdit::singleline(&mut self.viewer.ticket_input)
|
||||
.desired_width(f32::INFINITY)
|
||||
.hint_text("endpoint…"),
|
||||
)
|
||||
})
|
||||
.inner;
|
||||
// Grab focus once on screen entry so the user can paste/type straight
|
||||
// away without first clicking into the field.
|
||||
if std::mem::take(&mut self.viewer.focus_ticket) {
|
||||
ticket_resp.request_focus();
|
||||
}
|
||||
// Enter in the field connects (gated on a decodable code below).
|
||||
let enter_pressed =
|
||||
ticket_resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
|
||||
// Decode the pasted code live: confirms it's a real ticket and shows
|
||||
// which host it points at, so a stale clipboard paste is caught here
|
||||
// instead of after the 15s connect timeout.
|
||||
let trimmed = self.viewer.ticket_input.trim().to_string();
|
||||
let decoded_id = ticket_endpoint_id(&trimmed);
|
||||
if !trimmed.is_empty() {
|
||||
ui.add_space(4.0);
|
||||
match &decoded_id {
|
||||
Some(id) => ui.colored_label(
|
||||
egui::Color32::LIGHT_GREEN,
|
||||
format!("→ endpoint {}", short_id(id)),
|
||||
),
|
||||
None => ui.colored_label(
|
||||
egui::Color32::from_rgb(220, 160, 60),
|
||||
"⚠ This doesn't look like a share code.",
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
ui.add_space(10.0);
|
||||
ui.horizontal(|ui| {
|
||||
@@ -563,14 +720,16 @@ impl PixelPassApp {
|
||||
});
|
||||
|
||||
ui.add_space(16.0);
|
||||
let can_connect = !self.viewer.ticket_input.trim().is_empty();
|
||||
if ui
|
||||
// Only dial a code that actually decodes — no point spawning a child to
|
||||
// spend 15s timing out against garbage. Enter takes the same path.
|
||||
let connect_clicked = ui
|
||||
.add_enabled(
|
||||
can_connect,
|
||||
decoded_id.is_some(),
|
||||
egui::Button::new("Connect").min_size(egui::vec2(140.0, 36.0)),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
.on_disabled_hover_text("Paste a valid share code first.")
|
||||
.clicked();
|
||||
if decoded_id.is_some() && (connect_clicked || enter_pressed) {
|
||||
self.start_viewer(ui.ctx().clone());
|
||||
}
|
||||
}
|
||||
@@ -582,7 +741,11 @@ impl PixelPassApp {
|
||||
} else if self.viewer.url.is_some() {
|
||||
ui.label("Connected — launching player…");
|
||||
} else {
|
||||
ui.colored_label(egui::Color32::YELLOW, "● Connecting…");
|
||||
let msg = match &self.viewer.connecting_to {
|
||||
Some(id) => format!("● Connecting to {id}…"),
|
||||
None => "● Connecting…".to_string(),
|
||||
};
|
||||
ui.colored_label(egui::Color32::YELLOW, msg);
|
||||
}
|
||||
|
||||
ui.add_space(16.0);
|
||||
@@ -594,12 +757,30 @@ impl PixelPassApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// On entering the View screen, drop a clipboard ticket straight into the
|
||||
/// field — the host's Copy button (and our auto-copy) usually leaves the
|
||||
/// freshly-shared code right there. Guarded so it only fires when the field
|
||||
/// is empty and the clipboard holds a *decodable* ticket, so stray
|
||||
/// clipboard text never lands in the box; the live decode still shows the
|
||||
/// id for the user to verify.
|
||||
fn prefill_viewer_ticket(&mut self) {
|
||||
if self.viewer.ticket_input.trim().is_empty()
|
||||
&& self.viewer.proc.is_none()
|
||||
&& let Some(text) = get_clipboard()
|
||||
&& ticket_endpoint_id(&text).is_some()
|
||||
{
|
||||
self.viewer.ticket_input = text.trim().to_string();
|
||||
}
|
||||
self.viewer.focus_ticket = true;
|
||||
}
|
||||
|
||||
fn start_viewer(&mut self, ctx: egui::Context) {
|
||||
self.viewer.error = None;
|
||||
self.viewer.url = None;
|
||||
self.viewer.launched = false;
|
||||
|
||||
let ticket = self.viewer.ticket_input.trim().to_string();
|
||||
self.viewer.connecting_to = ticket_endpoint_id(&ticket).map(|id| short_id(&id));
|
||||
let args = vec![ticket, "--output".to_string(), "json".to_string()];
|
||||
match ChildProc::spawn(&args, ctx) {
|
||||
Ok(p) => self.viewer.proc = Some(p),
|
||||
@@ -611,6 +792,7 @@ impl PixelPassApp {
|
||||
self.viewer.proc = None;
|
||||
self.viewer.url = None;
|
||||
self.viewer.launched = false;
|
||||
self.viewer.connecting_to = None;
|
||||
}
|
||||
|
||||
fn pump_viewer_events(&mut self) {
|
||||
@@ -648,3 +830,52 @@ impl PixelPassApp {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A real, parseable ticket built the same way the host builds one
|
||||
/// (`EndpointTicket::new`), from a deterministic key so the id is stable.
|
||||
fn sample_ticket() -> (String, String) {
|
||||
let sk = iroh::SecretKey::from_bytes(&[7u8; 32]);
|
||||
let id = sk.public().to_string();
|
||||
let ticket = iroh_tickets::endpoint::EndpointTicket::new(iroh::EndpointAddr::new(
|
||||
sk.public(),
|
||||
))
|
||||
.to_string();
|
||||
(ticket, id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_endpoint_id_from_a_valid_ticket() {
|
||||
let (ticket, id) = sample_ticket();
|
||||
assert_eq!(ticket_endpoint_id(&ticket).as_deref(), Some(id.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tolerates_surrounding_whitespace() {
|
||||
let (ticket, _) = sample_ticket();
|
||||
assert!(ticket_endpoint_id(&format!(" \n{ticket}\t ")).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_ticket_input() {
|
||||
// The empty/whitespace/garbage cases that gate the Connect button off.
|
||||
assert_eq!(ticket_endpoint_id(""), None);
|
||||
assert_eq!(ticket_endpoint_id(" "), None);
|
||||
assert_eq!(ticket_endpoint_id("hello world"), None);
|
||||
assert_eq!(ticket_endpoint_id("endpointbutnotreally"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_id_truncates_long_ids() {
|
||||
assert_eq!(short_id("0123456789abcdefghij"), "0123456789ab…");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_id_leaves_short_or_exact_ids_intact() {
|
||||
assert_eq!(short_id("abc"), "abc");
|
||||
assert_eq!(short_id("0123456789ab"), "0123456789ab"); // exactly 12, no ellipsis
|
||||
}
|
||||
}
|
||||
|
||||
+43
-10
@@ -10,7 +10,9 @@ use anyhow::{Result, bail};
|
||||
use iroh::endpoint::{Connection, presets};
|
||||
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;
|
||||
|
||||
@@ -28,10 +30,16 @@ 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.
|
||||
AddViewer(oneshot::Sender<Result<u16, String>>),
|
||||
AddViewer {
|
||||
id: String,
|
||||
cancel: CancellationToken,
|
||||
reply: oneshot::Sender<Result<u16, String>>,
|
||||
},
|
||||
/// A viewer's session ended. Supervisor decrements the count and tears
|
||||
/// down capture if it just hit zero.
|
||||
RemoveViewer,
|
||||
RemoveViewer { id: String },
|
||||
/// Request to kick a specific viewer.
|
||||
KickViewer { id: String },
|
||||
}
|
||||
|
||||
pub async fn run(opts: HostOpts) -> Result<()> {
|
||||
@@ -113,6 +121,17 @@ 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;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
accept_loop(&endpoint, sup_tx.clone(), cancel.clone()).await;
|
||||
|
||||
drop(sup_tx);
|
||||
@@ -159,9 +178,11 @@ async fn handle_peer(
|
||||
cancel: CancellationToken,
|
||||
) {
|
||||
let remote = conn.remote_id();
|
||||
let id_str = remote.to_string();
|
||||
let peer_cancel = CancellationToken::new();
|
||||
|
||||
let (reply_tx, reply_rx) = oneshot::channel();
|
||||
if sup_tx.send(SupervisorMsg::AddViewer(reply_tx)).await.is_err() {
|
||||
if sup_tx.send(SupervisorMsg::AddViewer { id: id_str.clone(), cancel: peer_cancel.clone(), reply: reply_tx }).await.is_err() {
|
||||
tracing::warn!(%remote, "supervisor channel closed; dropping peer");
|
||||
return;
|
||||
}
|
||||
@@ -182,7 +203,7 @@ async fn handle_peer(
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
tracing::warn!(%remote, "accept_bi failed: {e:#}");
|
||||
let _ = sup_tx.send(SupervisorMsg::RemoveViewer).await;
|
||||
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id: id_str }).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -193,7 +214,7 @@ async fn handle_peer(
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
tracing::warn!(%remote, "connect_to_capture failed: {e:#}");
|
||||
let _ = sup_tx.send(SupervisorMsg::RemoveViewer).await;
|
||||
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id: id_str }).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -207,10 +228,13 @@ async fn handle_peer(
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!(%remote, "cancellation during stream");
|
||||
}
|
||||
_ = peer_cancel.cancelled() => {
|
||||
tracing::info!(%remote, "kicked by host");
|
||||
}
|
||||
}
|
||||
|
||||
eprintln!("[pixelpass] viewer disconnected: {remote}");
|
||||
let _ = sup_tx.send(SupervisorMsg::RemoveViewer).await;
|
||||
let _ = sup_tx.send(SupervisorMsg::RemoveViewer { id: id_str }).await;
|
||||
}
|
||||
|
||||
/// Owns the single shared CaptureHandle and the active viewer count. Spawns
|
||||
@@ -226,10 +250,11 @@ async fn supervise(
|
||||
) {
|
||||
let mut handle: Option<CaptureHandle> = None;
|
||||
let mut count: u32 = 0;
|
||||
let mut viewers: HashMap<String, CancellationToken> = HashMap::new();
|
||||
|
||||
while let Some(msg) = rx.recv().await {
|
||||
match msg {
|
||||
SupervisorMsg::AddViewer(reply) => {
|
||||
SupervisorMsg::AddViewer { id, cancel, reply } => {
|
||||
if count >= max_viewers {
|
||||
let reason =
|
||||
format!("host is full ({count} of {max_viewers} viewers connected)");
|
||||
@@ -256,13 +281,15 @@ async fn supervise(
|
||||
|
||||
let port = handle.as_ref().expect("handle was just set").local_port();
|
||||
count += 1;
|
||||
viewers.insert(id.clone(), cancel);
|
||||
let _ = reply.send(Ok(port));
|
||||
output::emit(output::Event::ViewerCount { active: count, max: max_viewers });
|
||||
output::emit(output::Event::ViewerJoined { id: &id, active: count, max: max_viewers });
|
||||
tracing::info!(active = count, cap = max_viewers, "viewer joined");
|
||||
}
|
||||
SupervisorMsg::RemoveViewer => {
|
||||
SupervisorMsg::RemoveViewer { id } => {
|
||||
viewers.remove(&id);
|
||||
count = count.saturating_sub(1);
|
||||
output::emit(output::Event::ViewerCount { active: count, max: max_viewers });
|
||||
output::emit(output::Event::ViewerLeft { id: &id, active: count, max: max_viewers });
|
||||
tracing::info!(active = count, cap = max_viewers, "viewer left");
|
||||
if count == 0
|
||||
&& let Some(h) = handle.take()
|
||||
@@ -274,6 +301,12 @@ async fn supervise(
|
||||
});
|
||||
}
|
||||
}
|
||||
SupervisorMsg::KickViewer { id } => {
|
||||
if let Some(cancel) = viewers.get(&id) {
|
||||
tracing::info!(%id, "kicking viewer");
|
||||
cancel.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user