Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
663956deaa | ||
|
|
abc8531cfa | ||
|
|
f0961a2049 | ||
|
|
32ee00178e | ||
|
|
7d9ffbd3a4 | ||
|
|
01150ff249 | ||
|
|
a6d9a8cbd4 | ||
|
|
a4bb6ce0be | ||
|
|
ebfc39de46 | ||
|
|
e3ff778d5b | ||
|
|
9a059e1bb8 | ||
|
|
4dc1bcd546 | ||
|
|
067997f9ba | ||
|
|
660eb27a84 | ||
|
|
913b0b6b20 | ||
|
|
36fb8bfa9a | ||
|
|
2e9164745f | ||
|
|
3b640726d7 | ||
|
|
381e00bc0e | ||
|
|
1a3c481f4c | ||
|
|
f927567105 | ||
|
|
5c11947bd7 | ||
|
|
7349744d16 |
@@ -0,0 +1,27 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to PeerSpeak are documented here.
|
||||
|
||||
## [0.5.0] — 2026-06-27
|
||||
|
||||
### Added
|
||||
- **Right-click context menu** (Cut / Copy / Paste / Select All) on every text-entry field. (A9)
|
||||
- **Selectable, copyable text** for values that used to be read-only: your full node ID and the room ticket can now be click-selected and copied, and **chat messages are drag-selectable** (highlight + Ctrl+C / Ctrl+A) while clickable links keep working. (W21 Phase 1 + 2)
|
||||
- **Clock-skew warning**: when a peer can't be seen because the two systems' clocks differ by more than the replay-protection window, PeerSpeak now shows a "your clocks are out of sync" banner instead of failing silently. (A25)
|
||||
- **Per-application audio capture for screen-share**, removing the call-audio loopback echo when sharing a window, plus surfacing of pixelpass startup errors. (A23)
|
||||
|
||||
### Changed / Fixed
|
||||
- **Critical commands are now delivered reliably under load** — muting, releasing push-to-talk, and leaving a room can no longer be silently dropped while a slider is being dragged (prevents a hot-mic state mismatch). (A15)
|
||||
- Screen-share now passes `--strict-audio` and surfaces app-audio drop warnings; the source picker state machine and pactl handling were hardened. (A23)
|
||||
- Per-peer volume control path verified and covered by regression tests. (A24)
|
||||
|
||||
### Security
|
||||
- Hardened against insider resource-exhaustion: bounded + author-keyed chat attachment cache, capped recovery-identity state, and other Tier-C caps (F-01 / F-02 / F-03 / F-12).
|
||||
|
||||
### Packaging
|
||||
- Added Debian/Ubuntu `.deb` packaging (cargo-deb metadata); the official `.deb` is now built on **Debian 12 (bookworm)** for wide compatibility.
|
||||
- Arch `PKGBUILD` clones over anonymous HTTPS.
|
||||
|
||||
[0.5.0]: https://gitbutter.xyz/mollusk/peerspeak/releases/tag/v0.5.0
|
||||
|
||||
Earlier releases: see git tags `v0.4.0`, `v0.3.0`, `v0.2.0`.
|
||||
Generated
+1
-1
@@ -4871,7 +4871,7 @@ checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
|
||||
|
||||
[[package]]
|
||||
name = "peerspeak"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
|
||||
+31
-2
@@ -1,11 +1,40 @@
|
||||
[package]
|
||||
name = "peerspeak"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
edition = "2024"
|
||||
description = "Decentralized peer-to-peer voice chat (Rust/iroh/PipeWire/Opus/iced)"
|
||||
# Application crate, not a crates.io library — refuse `cargo publish` and let
|
||||
# cargo-deny's [licenses.private] skip the missing-license check.
|
||||
publish = false
|
||||
|
||||
# Debian/Ubuntu packaging (cargo-deb). Mirrors packaging/PKGBUILD: only the main
|
||||
# `peerspeak` binary ships (not test_net/specview), plus the desktop entry and the
|
||||
# hicolor icon set. Runtime shared-lib deps (libpipewire, libopus, libc, …) are
|
||||
# resolved by dpkg-shlibdeps via `depends = "$auto"`. Build inside a Debian/Ubuntu
|
||||
# distrobox so the binary links that distro's glibc, then `cargo deb --no-build`.
|
||||
[package.metadata.deb]
|
||||
maintainer = "mollusk <jitty+lc1iz0dc@protonmail.com>"
|
||||
copyright = "2026, mollusk. Private build — not for redistribution."
|
||||
section = "net"
|
||||
priority = "optional"
|
||||
depends = "$auto"
|
||||
# pixelpass = in-room screen sharing; mpv = the screen-share viewer (vlc fallback).
|
||||
recommends = "pixelpass, mpv"
|
||||
extended-description = "Decentralized peer-to-peer voice chat over iroh (QUIC) with PipeWire audio, the Opus codec, and an iced GUI. Full-mesh, no central server."
|
||||
assets = [
|
||||
["target/release/peerspeak", "usr/bin/", "755"],
|
||||
["packaging/peerspeak.desktop", "usr/share/applications/", "644"],
|
||||
["assets/icons/peerspeak.svg", "usr/share/icons/hicolor/scalable/apps/peerspeak.svg", "644"],
|
||||
["assets/icons/peerspeak-16.png", "usr/share/icons/hicolor/16x16/apps/peerspeak.png", "644"],
|
||||
["assets/icons/peerspeak-24.png", "usr/share/icons/hicolor/24x24/apps/peerspeak.png", "644"],
|
||||
["assets/icons/peerspeak-32.png", "usr/share/icons/hicolor/32x32/apps/peerspeak.png", "644"],
|
||||
["assets/icons/peerspeak-48.png", "usr/share/icons/hicolor/48x48/apps/peerspeak.png", "644"],
|
||||
["assets/icons/peerspeak-64.png", "usr/share/icons/hicolor/64x64/apps/peerspeak.png", "644"],
|
||||
["assets/icons/peerspeak-128.png", "usr/share/icons/hicolor/128x128/apps/peerspeak.png", "644"],
|
||||
["assets/icons/peerspeak-256.png", "usr/share/icons/hicolor/256x256/apps/peerspeak.png", "644"],
|
||||
["assets/icons/peerspeak-512.png", "usr/share/icons/hicolor/512x512/apps/peerspeak.png", "644"],
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "peerspeak"
|
||||
path = "src/lib.rs"
|
||||
@@ -28,7 +57,7 @@ async-trait = "0.1.89"
|
||||
base64 = "0.22.1"
|
||||
bytes = "1.11.1"
|
||||
dirs = "6.0.0"
|
||||
iced = { version = "0.14.0", features = ["canvas", "image", "tokio"] }
|
||||
iced = { version = "0.14.0", features = ["advanced", "canvas", "image", "tokio"] }
|
||||
# W4 custom avatars: decode/resize an arbitrary user image (png/jpeg only to keep
|
||||
# the codec surface small). The matching native file picker (`rfd`) is platform-
|
||||
# gated below — its backend differs per OS (xdg-portal on Linux, Win32 on Windows).
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
# Maintainer: mollusk <jitty+lc1iz0dc@protonmail.com>
|
||||
pkgname=peerspeak-git
|
||||
_pkgname=peerspeak
|
||||
pkgver=0.3.0.r229.g7fb1c96
|
||||
pkgver=0.5.0.r0.g0000000
|
||||
pkgrel=1
|
||||
pkgdesc="Decentralized peer-to-peer voice chat (Rust/iroh/PipeWire/Opus/iced)"
|
||||
arch=('x86_64')
|
||||
@@ -14,7 +14,7 @@ optdepends=('pixelpass: screen sharing inside a room'
|
||||
provides=('peerspeak')
|
||||
conflicts=('peerspeak')
|
||||
options=('!lto' '!debug')
|
||||
source=("$_pkgname::git+ssh://git@gitbutter.xyz/mollusk/peerspeak.git")
|
||||
source=("$_pkgname::git+https://gitbutter.xyz/mollusk/peerspeak.git")
|
||||
sha256sums=('SKIP')
|
||||
|
||||
pkgver() {
|
||||
|
||||
@@ -8,7 +8,7 @@ it once, then you and I connect directly to each other.
|
||||
|
||||
## 1. Install it
|
||||
|
||||
1. Double-click **`peerspeak-0.3.0-setup.exe`** (the file I sent you).
|
||||
1. Double-click **`peerspeak-0.4.0-setup.exe`** (the file I sent you).
|
||||
|
||||
2. **Windows will probably show a blue "Windows protected your PC" warning.**
|
||||
This is normal — it shows up for any app that isn't from a big company with a
|
||||
|
||||
@@ -12,7 +12,7 @@ runtime, so there are no extra DLLs to bundle. The installer payload is just the
|
||||
## Version compatibility
|
||||
|
||||
The installer version tracks the crate version in `Cargo.toml` (currently
|
||||
**0.3.0**) — keep `MyAppVersion` in `peerspeak.iss` in sync when it changes.
|
||||
**0.4.0**) — keep `MyAppVersion` in `peerspeak.iss` in sync when it changes.
|
||||
|
||||
Per `VERSIONING.md`, a **MINOR** bump in `0.x` is a **breaking wire change**:
|
||||
peers on different MINOR versions can't connect (they fail fast at the
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
; (x86_64-pc-windows-gnu, statically linked -- no extra DLLs needed).
|
||||
|
||||
#define MyAppName "PeerSpeak"
|
||||
#define MyAppVersion "0.3.0"
|
||||
#define MyAppVersion "0.5.0"
|
||||
#define MyAppPublisher "mollusk"
|
||||
#define MyAppExeName "peerspeak.exe"
|
||||
|
||||
|
||||
+1076
-154
File diff suppressed because it is too large
Load Diff
+119
@@ -185,10 +185,129 @@ pub fn initials(name: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// A small content-addressed LRU cache mapping image bytes to a built value
|
||||
/// (e.g. an `iced` image handle), so the SAME value is reused across redraws
|
||||
/// instead of rebuilt every frame. Two Tier C F-03 properties beyond a plain
|
||||
/// hash map:
|
||||
///
|
||||
/// 1. **Bounded** — at most `cap` entries, evicting the least-recently-used on
|
||||
/// overflow, so a peer can't grow the cache without limit by publishing an
|
||||
/// endless stream of distinct valid avatars.
|
||||
/// 2. **Collision-safe** — a hit requires full byte equality, not just a matching
|
||||
/// 64-bit hash, so a hash collision can never return a different image's value.
|
||||
///
|
||||
/// Linear scan; intended for small `cap` (tens of entries).
|
||||
pub struct ByteLru<V> {
|
||||
cap: usize,
|
||||
/// `(content hash, content bytes, value)`; back = most recently used.
|
||||
entries: Vec<(u64, Vec<u8>, V)>,
|
||||
}
|
||||
|
||||
impl<V: Clone> ByteLru<V> {
|
||||
/// Create an LRU holding at most `cap` entries (`cap` is clamped to >= 1).
|
||||
pub fn new(cap: usize) -> Self {
|
||||
Self { cap: cap.max(1), entries: Vec::new() }
|
||||
}
|
||||
|
||||
/// Return the cached value for these exact `bytes`, building and inserting it
|
||||
/// on a miss (evicting the least-recently-used entry once over `cap`). A hit
|
||||
/// verifies full byte equality, so a 64-bit hash collision never returns the
|
||||
/// wrong value. A hit also refreshes the entry's recency.
|
||||
pub fn get_or_insert(&mut self, bytes: &[u8], build: impl FnOnce() -> V) -> V {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
bytes.hash(&mut hasher);
|
||||
self.get_or_insert_hashed(hasher.finish(), bytes, build)
|
||||
}
|
||||
|
||||
/// Inner seam with the content `hash` supplied explicitly. Production callers
|
||||
/// use [`get_or_insert`]; tests use this to force a hash collision (different
|
||||
/// bytes, same hash) and exercise the byte-equality guard.
|
||||
fn get_or_insert_hashed(&mut self, hash: u64, bytes: &[u8], build: impl FnOnce() -> V) -> V {
|
||||
if let Some(idx) = self
|
||||
.entries
|
||||
.iter()
|
||||
.position(|(h, b, _)| *h == hash && b.as_slice() == bytes)
|
||||
{
|
||||
// LRU touch: move the hit entry to the back (most recent).
|
||||
let entry = self.entries.remove(idx);
|
||||
let val = entry.2.clone();
|
||||
self.entries.push(entry);
|
||||
return val;
|
||||
}
|
||||
|
||||
let val = build();
|
||||
if self.entries.len() >= self.cap {
|
||||
self.entries.remove(0); // evict least-recently-used
|
||||
}
|
||||
self.entries.push((hash, bytes.to_vec(), val.clone()));
|
||||
val
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn byte_lru_reuses_value_for_identical_bytes() {
|
||||
let mut lru: ByteLru<u32> = ByteLru::new(4);
|
||||
let mut next = 0u32;
|
||||
let mut build = |lru: &mut ByteLru<u32>, b: &[u8]| {
|
||||
lru.get_or_insert(b, || {
|
||||
next += 1;
|
||||
next
|
||||
})
|
||||
};
|
||||
// Same bytes → same value, built only once.
|
||||
assert_eq!(build(&mut lru, b"alice"), 1);
|
||||
assert_eq!(build(&mut lru, b"alice"), 1);
|
||||
// Different bytes → a freshly built value.
|
||||
assert_eq!(build(&mut lru, b"bob"), 2);
|
||||
assert_eq!(lru.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn byte_lru_evicts_least_recently_used() {
|
||||
let mut lru: ByteLru<u32> = ByteLru::new(2);
|
||||
let mut n = 0u32;
|
||||
let mut ins = |lru: &mut ByteLru<u32>, b: &[u8]| {
|
||||
lru.get_or_insert(b, || {
|
||||
n += 1;
|
||||
n
|
||||
})
|
||||
};
|
||||
ins(&mut lru, b"a"); // -> 1
|
||||
ins(&mut lru, b"b"); // -> 2, cache = [a, b]
|
||||
ins(&mut lru, b"a"); // touch a, cache = [b, a]
|
||||
ins(&mut lru, b"c"); // evicts LRU (b), cache = [a, c]
|
||||
assert_eq!(lru.len(), 2);
|
||||
// `a` survived (recently touched) → still value 1, not rebuilt.
|
||||
assert_eq!(ins(&mut lru, b"a"), 1);
|
||||
// `b` was evicted → rebuilt with a new value.
|
||||
assert_eq!(ins(&mut lru, b"b"), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn byte_lru_byte_equality_survives_a_hash_collision() {
|
||||
// Force the SAME 64-bit hash for two DIFFERENT byte strings (the case a
|
||||
// bare-hash cache would alias — Tier C F-03 collision bug).
|
||||
let mut lru: ByteLru<u32> = ByteLru::new(4);
|
||||
assert_eq!(lru.get_or_insert_hashed(42, b"alice", || 1), 1);
|
||||
// `bob` collides on the hash but differs in bytes → a MISS, built fresh,
|
||||
// NOT aliased to alice's value.
|
||||
assert_eq!(lru.get_or_insert_hashed(42, b"bob", || 2), 2);
|
||||
// Both coexist; each re-lookup returns its own value (build closure unused).
|
||||
assert_eq!(lru.get_or_insert_hashed(42, b"alice", || 99), 1);
|
||||
assert_eq!(lru.get_or_insert_hashed(42, b"bob", || 99), 2);
|
||||
assert_eq!(lru.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initials_takes_first_two_words() {
|
||||
assert_eq!(initials("Alice"), "A");
|
||||
|
||||
+161
-5
@@ -64,9 +64,16 @@ pub enum CoreCommand {
|
||||
/// Set the pixelpass binary location (config override, empty = use `$PATH`).
|
||||
/// Sent at startup so screen-share can resolve the binary.
|
||||
SetPixelpassPath(Option<String>),
|
||||
/// Enumerate apps currently producing audio (for the screen-share audio
|
||||
/// picker, A23). Replies with [`UiEvent::AudioAppsListed`]. Cheap shell-out;
|
||||
/// safe to call each time the picker opens.
|
||||
ListAudioApps,
|
||||
/// Start sharing our screen: spawn a pixelpass host and announce its ticket
|
||||
/// on our presence so the room can watch. No-op when not in a call.
|
||||
StartScreenShare,
|
||||
/// `audio_app` selects which app's audio to capture: `Some(name)` captures
|
||||
/// only that app (avoiding the call-loopback echo, A23); `None` shares the
|
||||
/// whole desktop audio (the legacy behavior).
|
||||
StartScreenShare { audio_app: Option<String> },
|
||||
/// Stop sharing our screen: kill the pixelpass host and clear the presence
|
||||
/// ticket. No-op when not sharing.
|
||||
StopScreenShare,
|
||||
@@ -102,6 +109,80 @@ pub enum CoreCommand {
|
||||
SetGameProcessMap(std::collections::BTreeMap<String, String>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DeliveryClass {
|
||||
Reliable,
|
||||
BestEffort,
|
||||
}
|
||||
|
||||
/// Route a command by how bad it is to drop it. Discrete, human-paced user
|
||||
/// actions are Reliable (must land). The only high-frequency commands are the
|
||||
/// continuous audio sliders, where dropping intermediate values is harmless;
|
||||
/// those are BestEffort.
|
||||
pub fn delivery_class(cmd: &CoreCommand) -> DeliveryClass {
|
||||
match cmd {
|
||||
CoreCommand::SetPeerVolume(_, _)
|
||||
| CoreCommand::SetPeerPan(_, _)
|
||||
| CoreCommand::SetPeerGate(_, _)
|
||||
| CoreCommand::SetPeerEq(_, _)
|
||||
| CoreCommand::SetInputVolume(_)
|
||||
| CoreCommand::SetOutputVolume(_)
|
||||
| CoreCommand::SetNoiseGateThreshold(_) => DeliveryClass::BestEffort,
|
||||
|
||||
CoreCommand::Join {
|
||||
name: _,
|
||||
ticket: _,
|
||||
room_name: _,
|
||||
input_device: _,
|
||||
output_device: _,
|
||||
echo_cancellation: _,
|
||||
avatar: _,
|
||||
}
|
||||
| CoreCommand::Leave
|
||||
| CoreCommand::Shutdown
|
||||
| CoreCommand::ToggleMute
|
||||
| CoreCommand::SetAvatar(_)
|
||||
| CoreCommand::ToggleDeafen
|
||||
| CoreCommand::SetPttMode(_)
|
||||
| CoreCommand::SetPttActive(_)
|
||||
| CoreCommand::SetPeerMuted(_, _)
|
||||
| CoreCommand::SetMicMonitor {
|
||||
enabled: _,
|
||||
input_device: _,
|
||||
}
|
||||
| CoreCommand::SetNetworkMode(_)
|
||||
| CoreCommand::SetRecording(_)
|
||||
| CoreCommand::SetRecordingMode(_)
|
||||
| CoreCommand::SendChat(_)
|
||||
| CoreCommand::SendChatFile {
|
||||
text: _,
|
||||
attachment: _,
|
||||
data: _,
|
||||
}
|
||||
| CoreCommand::FetchAttachment {
|
||||
from: _,
|
||||
attachment: _,
|
||||
}
|
||||
| CoreCommand::SetPixelpassPath(_)
|
||||
| CoreCommand::ListAudioApps
|
||||
| CoreCommand::StartScreenShare { audio_app: _ }
|
||||
| CoreCommand::StopScreenShare
|
||||
| CoreCommand::ViewShare(_)
|
||||
| CoreCommand::RegenerateIdentity
|
||||
| CoreCommand::AddFriend {
|
||||
id: _,
|
||||
name: _,
|
||||
addr: _,
|
||||
}
|
||||
| CoreCommand::RemoveFriend(_)
|
||||
| CoreCommand::RenameFriend(_, _)
|
||||
| CoreCommand::SetPresenceMode(_)
|
||||
| CoreCommand::SetGamePresenceEnabled(_)
|
||||
| CoreCommand::SetGameOverride(_)
|
||||
| CoreCommand::SetGameProcessMap(_) => DeliveryClass::Reliable,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum UiEvent {
|
||||
RoomJoined { ticket: String, self_id: String },
|
||||
@@ -133,15 +214,33 @@ pub enum UiEvent {
|
||||
/// string, used to key their avatar (W4).
|
||||
ChatMessage { from: String, name: String, text: String, attachment: Option<crate::files::ChatAttachment> },
|
||||
/// An attachment's bytes are now available (auto-fetched for images, or
|
||||
/// fetched on demand for files). Keyed by attachment id so the UI can match
|
||||
/// it to the chat entry.
|
||||
AttachmentReady { id: crate::files::AttachmentId, data: Vec<u8> },
|
||||
/// fetched on demand for files). Keyed by `(from, id)`: the id is
|
||||
/// attacker-chosen, so a malicious peer can reuse a victim's id — the author
|
||||
/// disambiguates whose bytes these are and stops content aliasing (Tier C
|
||||
/// F-12).
|
||||
AttachmentReady { from: EndpointId, id: crate::files::AttachmentId, data: Vec<u8> },
|
||||
/// An attachment fetch failed (sender gone, too large, decode error, etc.).
|
||||
AttachmentFailed { id: crate::files::AttachmentId, error: String },
|
||||
AttachmentFailed { from: EndpointId, id: crate::files::AttachmentId, error: String },
|
||||
/// The apps currently producing audio, for the screen-share audio picker
|
||||
/// (A23). Sorted, deduplicated `application.name`s; empty when nothing is
|
||||
/// playing or enumeration isn't available. `app_audio_supported` reports
|
||||
/// whether the resolved pixelpass understands `--strict-audio`: when `false`
|
||||
/// (an older pixelpass) the picker must offer whole-desktop audio only, since
|
||||
/// a per-app share would pass a flag that older binary rejects (audit P2).
|
||||
AudioAppsListed { apps: Vec<String>, app_audio_supported: bool },
|
||||
/// Our own screen share started; the UI flips the Share button to "Stop".
|
||||
ScreenShareStarted,
|
||||
/// Our own screen share stopped (or failed to start).
|
||||
ScreenShareStopped,
|
||||
/// Per-app screen-share audio routing state (A23). `true` = the app we chose
|
||||
/// is now reaching viewers; `false` = its audio stopped, so under our strict
|
||||
/// run viewers currently hear silence. The UI shows a transient warning while
|
||||
/// `false`. Only meaningful while sharing a specific app (not whole-desktop).
|
||||
ShareAudioActive(bool),
|
||||
/// A validly signed peer cannot be admitted because its gossip timestamp is
|
||||
/// outside the replay freshness window. `peer_ahead` describes the peer's
|
||||
/// sender-stamped timestamp relative to this machine's clock.
|
||||
ClockSkewWarning { skew_secs: u64, peer_ahead: bool },
|
||||
/// Our node identity (W7): the current node id string, and whether it is
|
||||
/// PERSISTED to disk. Sent once at startup and again after a regenerate.
|
||||
/// `persisted = false` means the key file couldn't be read/written and we're
|
||||
@@ -174,3 +273,60 @@ pub enum UiEvent {
|
||||
ShutdownComplete,
|
||||
Error(String),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{delivery_class, CoreCommand, DeliveryClass};
|
||||
use crate::audio::eq::EqSettings;
|
||||
use crate::presence::PresenceMode;
|
||||
use iroh::{EndpointId, SecretKey};
|
||||
|
||||
fn endpoint_id() -> EndpointId {
|
||||
SecretKey::generate().public()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuous_audio_controls_are_best_effort() {
|
||||
let peer = endpoint_id();
|
||||
let commands = [
|
||||
CoreCommand::SetPeerVolume(peer, 0.7),
|
||||
CoreCommand::SetPeerPan(peer, -0.2),
|
||||
CoreCommand::SetPeerGate(peer, 0.1),
|
||||
CoreCommand::SetPeerEq(peer, EqSettings::default()),
|
||||
CoreCommand::SetInputVolume(0.8),
|
||||
CoreCommand::SetOutputVolume(0.9),
|
||||
CoreCommand::SetNoiseGateThreshold(0.02),
|
||||
];
|
||||
|
||||
for cmd in commands {
|
||||
assert_eq!(delivery_class(&cmd), DeliveryClass::BestEffort);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discrete_user_actions_are_reliable() {
|
||||
let peer = endpoint_id();
|
||||
let commands = [
|
||||
CoreCommand::ToggleMute,
|
||||
CoreCommand::SetPttActive(false),
|
||||
CoreCommand::Leave,
|
||||
CoreCommand::RegenerateIdentity,
|
||||
CoreCommand::Join {
|
||||
name: "Peer".to_string(),
|
||||
ticket: "create".to_string(),
|
||||
room_name: "Room".to_string(),
|
||||
input_device: None,
|
||||
output_device: None,
|
||||
echo_cancellation: true,
|
||||
avatar: crate::avatar::Avatar::default(),
|
||||
},
|
||||
CoreCommand::SetPeerMuted(peer, true),
|
||||
CoreCommand::SetPresenceMode(PresenceMode::Normal),
|
||||
CoreCommand::SendChat("hello".to_string()),
|
||||
];
|
||||
|
||||
for cmd in commands {
|
||||
assert_eq!(delivery_class(&cmd), DeliveryClass::Reliable);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+337
-49
@@ -11,7 +11,7 @@ use crate::network::{
|
||||
iroh_impl::{IrohTransport, AudioRouter, FileRouter},
|
||||
gossip::IrohGossipState,
|
||||
};
|
||||
use crate::core::messages::{CoreCommand, UiEvent};
|
||||
use crate::core::messages::{CoreCommand, DeliveryClass, UiEvent, delivery_class};
|
||||
use crate::core::recovery::RecoveryCoordinator;
|
||||
|
||||
use crate::config::{NetworkMode, RecordingMode};
|
||||
@@ -26,38 +26,44 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
pub struct CoreController {
|
||||
cmd_tx: mpsc::Sender<CoreCommand>,
|
||||
reliable_tx: mpsc::UnboundedSender<CoreCommand>,
|
||||
besteffort_tx: mpsc::Sender<CoreCommand>,
|
||||
}
|
||||
|
||||
impl CoreController {
|
||||
pub fn new(ui_tx: mpsc::Sender<UiEvent>) -> Self {
|
||||
let (cmd_tx, cmd_rx) = mpsc::channel(100);
|
||||
let (reliable_tx, reliable_rx) = mpsc::unbounded_channel();
|
||||
let (besteffort_tx, besteffort_rx) = mpsc::channel(100);
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let rt = tokio::runtime::Runtime::new().expect("Failed to create Tokio runtime");
|
||||
rt.block_on(async move {
|
||||
crate::log_msg("Starting core network loop in dedicated Tokio runtime");
|
||||
if let Err(e) = run_core_loop(cmd_rx, ui_tx).await {
|
||||
if let Err(e) = run_core_loop(reliable_rx, besteffort_rx, ui_tx).await {
|
||||
crate::log_msg(&format!("App core loop failed: {:?}", e));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Self { cmd_tx }
|
||||
Self { reliable_tx, besteffort_tx }
|
||||
}
|
||||
|
||||
/// Queue a command for the core loop, best-effort. Returns `true` if it was
|
||||
/// accepted, `false` if the channel is full or closed. (We return a plain
|
||||
/// bool rather than the channel's `Result` so the bulky `CoreCommand` isn't
|
||||
/// carried back by value in every caller's error type.)
|
||||
/// Queue a command for the core loop. Reliable commands only fail when the
|
||||
/// core loop is dead; best-effort slider commands keep today's bounded
|
||||
/// try-send behavior. (We return a plain bool rather than the channel's
|
||||
/// `Result` so the bulky `CoreCommand` isn't carried back by value in every
|
||||
/// caller's error type.)
|
||||
pub fn send(&self, cmd: CoreCommand) -> bool {
|
||||
self.cmd_tx.try_send(cmd).is_ok()
|
||||
match delivery_class(&cmd) {
|
||||
DeliveryClass::Reliable => self.reliable_tx.send(cmd).is_ok(),
|
||||
DeliveryClass::BestEffort => self.besteffort_tx.try_send(cmd).is_ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Clone the command sender for asynchronous one-shot sends that should wait
|
||||
/// for channel capacity instead of failing immediately on a full queue.
|
||||
pub fn command_sender(&self) -> mpsc::Sender<CoreCommand> {
|
||||
self.cmd_tx.clone()
|
||||
self.besteffort_tx.clone()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,6 +140,25 @@ type SeenConnected = Arc<std::sync::Mutex<HashSet<EndpointId>>>;
|
||||
type KnownPeers =
|
||||
Arc<std::sync::Mutex<HashMap<[u8; 32], HashMap<EndpointId, EndpointAddr>>>>;
|
||||
|
||||
/// Per-topic cap on the retained rejoin-bootstrap / recovery target table
|
||||
/// (Tier C recovery-identity cap). Set comfortably above the live-roster cap
|
||||
/// (`gossip::MAX_ACTIVE_PEERS`, 32) so a legitimate room — even one where every
|
||||
/// member drops at once during a relay outage — never hits it, while an insider
|
||||
/// who grace-cycles distinct identities (join, drop without a signed Leave,
|
||||
/// repeat) cannot grow the table without bound. Combined with the recovery
|
||||
/// terminal budget (which forgets a retained address when it gives up), abandoned
|
||||
/// identities drain on their own, so this cap is a deterministic ceiling rather
|
||||
/// than a pinnable slot pool.
|
||||
const MAX_RETAINED_PEERS: usize = 64;
|
||||
|
||||
/// Whether a peer may be inserted into a retained-target table at `len` entries.
|
||||
/// An update to an id already present is always allowed (it only refreshes an
|
||||
/// address); a brand-new id is admitted only while below the cap. Mirrors the
|
||||
/// gossip roster's `admit_into_roster` reject-when-full admission.
|
||||
fn admit_retained(len: usize, is_new_id: bool, cap: usize) -> bool {
|
||||
!is_new_id || len < cap
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct RecoveryContext {
|
||||
coordinator: RecoveryCoordinator,
|
||||
@@ -275,6 +300,17 @@ fn apply_volume(frame: &mut [i16], vol: f32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply the listener's per-peer volume for the audio sender id currently being
|
||||
/// mixed. The map key must be the same `EndpointId` used for the jitter buffer.
|
||||
fn apply_peer_volume(
|
||||
frame: &mut [i16],
|
||||
peer_id: EndpointId,
|
||||
volumes: &HashMap<EndpointId, f32>,
|
||||
) {
|
||||
let vol = volumes.get(&peer_id).copied().unwrap_or(1.0);
|
||||
apply_volume(frame, vol);
|
||||
}
|
||||
|
||||
/// Normalized RMS level of a frame in `[0.0, 1.0]` (32768 = full scale), for the
|
||||
/// UI level meter. An empty frame reads as 0.0.
|
||||
fn frame_level(frame: &[i16]) -> f32 {
|
||||
@@ -522,6 +558,7 @@ struct ActiveSession {
|
||||
event_task: tokio::task::JoinHandle<()>,
|
||||
conn_event_task: tokio::task::JoinHandle<()>,
|
||||
recovery_task: tokio::task::JoinHandle<()>,
|
||||
recovery_terminal_task: tokio::task::JoinHandle<()>,
|
||||
grace_timers: GraceTimers,
|
||||
transport: Arc<IrohTransport>,
|
||||
/// Loaded PipeWire echo-cancel module (if enabled); unloads on drop.
|
||||
@@ -557,6 +594,7 @@ impl ActiveSession {
|
||||
handle.abort();
|
||||
}
|
||||
self.recovery_task.abort();
|
||||
self.recovery_terminal_task.abort();
|
||||
crate::log_msg("Aborted tasks");
|
||||
|
||||
let audio_backend_clone = audio_backend.clone();
|
||||
@@ -744,25 +782,70 @@ async fn build_net_stack(
|
||||
})
|
||||
}
|
||||
|
||||
/// Maximum number of *automatic* chat-attachment fetches in flight at once.
|
||||
///
|
||||
/// Auto-fetch (inline image preview) is triggered by an untrusted peer's chat
|
||||
/// message, and each fetch is a detached task that can spend up to ~60s dialing
|
||||
/// and reading. Without a bound, a room insider could spam attachment-carrying
|
||||
/// chat to accumulate arbitrary pending tasks/dials (Tier C F-02). When the bound
|
||||
/// is reached we simply skip the auto-fetch; the descriptor still renders and the
|
||||
/// user can fetch it on demand (which is not rate-limited here).
|
||||
const MAX_INFLIGHT_ATTACHMENT_FETCHES: usize = 4;
|
||||
|
||||
/// In-flight `(author, attachment_id)` markers for bounded, deduplicated auto-
|
||||
/// fetches (Tier C F-02). Bounded by [`MAX_INFLIGHT_ATTACHMENT_FETCHES`].
|
||||
type InflightAttachments =
|
||||
Arc<std::sync::Mutex<HashSet<(EndpointId, crate::files::AttachmentId)>>>;
|
||||
|
||||
/// RAII bookkeeping for one bounded auto-fetch: holds the concurrency permit for
|
||||
/// the task's lifetime and clears the in-flight `(author, id)` marker when the
|
||||
/// fetch finishes (success OR failure), so the same image can be retried later.
|
||||
struct AutoFetchGuard {
|
||||
_permit: tokio::sync::OwnedSemaphorePermit,
|
||||
inflight: InflightAttachments,
|
||||
key: (EndpointId, crate::files::AttachmentId),
|
||||
}
|
||||
|
||||
impl Drop for AutoFetchGuard {
|
||||
fn drop(&mut self) {
|
||||
self.inflight.lock().unwrap().remove(&self.key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether to AUTO-fetch a chat image attachment. Only authenticated roster
|
||||
/// authors qualify (closing the non-roster injection vector), and a `(author,
|
||||
/// id)` already being fetched is skipped (dedup). The concurrency bound itself is
|
||||
/// enforced separately by the permit. Pure → unit-testable (Tier C F-02).
|
||||
fn should_auto_fetch(is_image: bool, author_in_roster: bool, already_inflight: bool) -> bool {
|
||||
is_image && author_in_roster && !already_inflight
|
||||
}
|
||||
|
||||
/// Fetch a chat attachment's bytes from `from` over the file plane in a detached
|
||||
/// task, then report the result to the UI via [`UiEvent::AttachmentReady`] /
|
||||
/// [`UiEvent::AttachmentFailed`] keyed by the attachment id. For images
|
||||
/// [`UiEvent::AttachmentFailed`], tagged with `from` so the UI keys the bytes by
|
||||
/// `(author, id)` and can't alias a same-id attachment from another sender. For images
|
||||
/// (`is_image`) the bytes are defensively re-validated (decodable + within pixel
|
||||
/// limits) before being handed to the renderer; an "Image" that doesn't decode is
|
||||
/// reported as a failure rather than rendered.
|
||||
/// reported as a failure rather than rendered. `guard` is `Some` for bounded
|
||||
/// auto-fetches and `None` for user-initiated fetches; it is dropped when the
|
||||
/// task ends, releasing the concurrency permit and the dedup marker.
|
||||
fn spawn_attachment_fetch(
|
||||
transport: Arc<IrohTransport>,
|
||||
ui_tx: mpsc::Sender<UiEvent>,
|
||||
from: EndpointId,
|
||||
att: crate::files::ChatAttachment,
|
||||
is_image: bool,
|
||||
guard: Option<AutoFetchGuard>,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
// Held for the whole fetch; dropped here on completion (Tier C F-02).
|
||||
let _guard = guard;
|
||||
match transport.fetch_attachment(from, &att).await {
|
||||
Ok(data) => {
|
||||
if is_image && crate::files::validate_image_bytes(&data).is_none() {
|
||||
let _ = ui_tx
|
||||
.send(UiEvent::AttachmentFailed {
|
||||
from,
|
||||
id: att.id,
|
||||
error: "received image failed to decode".to_string(),
|
||||
})
|
||||
@@ -770,12 +853,12 @@ fn spawn_attachment_fetch(
|
||||
return;
|
||||
}
|
||||
let _ = ui_tx
|
||||
.send(UiEvent::AttachmentReady { id: att.id, data })
|
||||
.send(UiEvent::AttachmentReady { from, id: att.id, data })
|
||||
.await;
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = ui_tx
|
||||
.send(UiEvent::AttachmentFailed { id: att.id, error: e.to_string() })
|
||||
.send(UiEvent::AttachmentFailed { from, id: att.id, error: e.to_string() })
|
||||
.await;
|
||||
}
|
||||
}
|
||||
@@ -875,7 +958,8 @@ async fn probe_friends_once(
|
||||
}
|
||||
|
||||
async fn run_core_loop(
|
||||
mut cmd_rx: mpsc::Receiver<CoreCommand>,
|
||||
mut reliable_rx: mpsc::UnboundedReceiver<CoreCommand>,
|
||||
mut besteffort_rx: mpsc::Receiver<CoreCommand>,
|
||||
ui_tx: mpsc::Sender<UiEvent>,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let memory_lookup = iroh::address_lookup::memory::MemoryLookup::new();
|
||||
@@ -1078,7 +1162,12 @@ async fn run_core_loop(
|
||||
ping_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
let cmd = tokio::select! {
|
||||
maybe_cmd = cmd_rx.recv() => match maybe_cmd {
|
||||
biased;
|
||||
maybe_cmd = reliable_rx.recv() => match maybe_cmd {
|
||||
Some(cmd) => cmd,
|
||||
None => break,
|
||||
},
|
||||
maybe_cmd = besteffort_rx.recv() => match maybe_cmd {
|
||||
Some(cmd) => cmd,
|
||||
None => break,
|
||||
},
|
||||
@@ -1641,8 +1730,7 @@ async fn run_core_loop(
|
||||
peer_noise_gates.remove(&peer_id);
|
||||
}
|
||||
|
||||
let vol = current_volumes.get(&peer_id).copied().unwrap_or(1.0);
|
||||
apply_volume(&mut frame, vol);
|
||||
apply_peer_volume(&mut frame, peer_id, ¤t_volumes);
|
||||
|
||||
let eq_settings = current_eq
|
||||
.get(&peer_id)
|
||||
@@ -1799,7 +1887,7 @@ async fn run_core_loop(
|
||||
// The topic of the room this event loop serves, so peer add/remove
|
||||
// updates the right per-topic bucket in `known_peers` (A8 archive).
|
||||
let room_topic = topic_id;
|
||||
let (recovery_coordinator, recovery_task) =
|
||||
let (recovery_coordinator, recovery_task, recovery_terminal_rx) =
|
||||
RecoveryCoordinator::spawn(room_state.clone());
|
||||
let recovery_context = RecoveryContext {
|
||||
coordinator: recovery_coordinator,
|
||||
@@ -1808,17 +1896,51 @@ async fn run_core_loop(
|
||||
topic_id,
|
||||
};
|
||||
let recovery_events = recovery_context.clone();
|
||||
// Drain the recovery coordinator's terminal-eviction signals (Tier C
|
||||
// recovery-identity cap). When background recovery exhausts its budget
|
||||
// for a peer, forget its retained dial target so the per-topic retain
|
||||
// table drains, scrub residual seen-connected state, and surface the
|
||||
// failure. A peer that later returns can still rejoin via a gossip
|
||||
// announce, so giving up never blocks a legitimate reconnect.
|
||||
let recovery_terminal_ctx = recovery_context.clone();
|
||||
let seen_connected_terminal = seen_connected.clone();
|
||||
let ui_tx_terminal = ui_tx.clone();
|
||||
let recovery_terminal_task = tokio::spawn(async move {
|
||||
let mut terminal_rx = recovery_terminal_rx;
|
||||
while let Some(peer_id) = terminal_rx.recv().await {
|
||||
crate::log_msg(&format!(
|
||||
"Background recovery gave up on peer {peer_id:?}; forgetting retained target"
|
||||
));
|
||||
recovery_terminal_ctx.forget(peer_id);
|
||||
seen_connected_terminal.lock().unwrap().remove(&peer_id);
|
||||
let _ = ui_tx_terminal
|
||||
.send(UiEvent::PeerConnectionFailed { id: peer_id })
|
||||
.await;
|
||||
}
|
||||
});
|
||||
// Friends store + ui sender, so a connected peer who is a friend has
|
||||
// their saved address auto-healed (W7) — populates `last_addr` so the
|
||||
// presence scheduler can reach them later.
|
||||
let friends_events = friends.clone();
|
||||
let friends_read_only_events = friends_read_only;
|
||||
// Bounded, deduplicated auto-fetch of chat image attachments (Tier C
|
||||
// F-02): the permit pool caps concurrent fetch tasks; the in-flight
|
||||
// set dedups identical (author, id) pairs.
|
||||
let attachment_limiter =
|
||||
Arc::new(tokio::sync::Semaphore::new(MAX_INFLIGHT_ATTACHMENT_FETCHES));
|
||||
let inflight_attachments: InflightAttachments =
|
||||
Arc::new(std::sync::Mutex::new(HashSet::new()));
|
||||
let event_task = tokio::spawn(async move {
|
||||
// The authenticated roster for this room, maintained from the
|
||||
// same sequential event stream. Only its members may trigger an
|
||||
// automatic attachment fetch (Tier C F-02).
|
||||
let mut roster: HashSet<EndpointId> = HashSet::new();
|
||||
while let Some(event) = room_events.recv().await {
|
||||
match event {
|
||||
RoomEvent::PeerJoined(peer_id, state) => {
|
||||
// A (re)join means the peer is back — cancel any
|
||||
// pending reconnect grace timer before re-adding it.
|
||||
roster.insert(peer_id);
|
||||
cancel_grace_timer(&grace_timers_events, &peer_id);
|
||||
recovery_events.cancel(peer_id);
|
||||
transport_events.admit_audio_sender(peer_id);
|
||||
@@ -1843,13 +1965,22 @@ async fn run_core_loop(
|
||||
.await;
|
||||
}
|
||||
// Retain this peer under this room's topic as a
|
||||
// future rejoin bootstrap target (A8).
|
||||
known_peers_events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.entry(room_topic)
|
||||
.or_default()
|
||||
.insert(peer_id, state.addr.clone());
|
||||
// future rejoin bootstrap target (A8), bounded by the
|
||||
// per-topic retain cap (Tier C recovery-identity cap):
|
||||
// refreshing a peer we already track is always allowed,
|
||||
// a brand-new identity only while below the cap.
|
||||
{
|
||||
let mut kp = known_peers_events.lock().unwrap();
|
||||
let bucket = kp.entry(room_topic).or_default();
|
||||
let is_new_id = !bucket.contains_key(&peer_id);
|
||||
if admit_retained(bucket.len(), is_new_id, MAX_RETAINED_PEERS) {
|
||||
bucket.insert(peer_id, state.addr.clone());
|
||||
} else {
|
||||
crate::log_msg(&format!(
|
||||
"Retain table full ({MAX_RETAINED_PEERS}); not retaining new peer {peer_id:?} for rejoin"
|
||||
));
|
||||
}
|
||||
}
|
||||
// If a multitrack recording is live, give this peer
|
||||
// its own stem track (silence-padded back to t=0).
|
||||
if is_multitrack_events.load(Ordering::Relaxed)
|
||||
@@ -1862,6 +1993,7 @@ async fn run_core_loop(
|
||||
}
|
||||
RoomEvent::PeerLeft(peer_id) => {
|
||||
// Graceful leave — evict immediately.
|
||||
roster.remove(&peer_id);
|
||||
cancel_grace_timer(&grace_timers_events, &peer_id);
|
||||
seen_connected_events.lock().unwrap().remove(&peer_id);
|
||||
// A signed Leave cancels background recovery and
|
||||
@@ -1899,13 +2031,21 @@ async fn run_core_loop(
|
||||
.await;
|
||||
}
|
||||
// Refresh this room's retained rejoin target with the
|
||||
// fresh addr (A8).
|
||||
known_peers_events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.entry(room_topic)
|
||||
.or_default()
|
||||
.insert(peer_id, state.addr.clone());
|
||||
// fresh addr (A8), under the per-topic retain cap. A
|
||||
// re-announce from a peer we already track always
|
||||
// refreshes; a new identity is bounded by the cap.
|
||||
{
|
||||
let mut kp = known_peers_events.lock().unwrap();
|
||||
let bucket = kp.entry(room_topic).or_default();
|
||||
let is_new_id = !bucket.contains_key(&peer_id);
|
||||
if admit_retained(bucket.len(), is_new_id, MAX_RETAINED_PEERS) {
|
||||
bucket.insert(peer_id, state.addr.clone());
|
||||
} else {
|
||||
crate::log_msg(&format!(
|
||||
"Retain table full ({MAX_RETAINED_PEERS}); not retaining new peer {peer_id:?} for rejoin"
|
||||
));
|
||||
}
|
||||
}
|
||||
let _ = ui_tx_events.send(UiEvent::PeerUpdated { id: peer_id, state }).await;
|
||||
}
|
||||
RoomEvent::ChatMessage { from, name, text, ts: _, attachment } => {
|
||||
@@ -1913,16 +2053,47 @@ async fn run_core_loop(
|
||||
// without a click; non-image files wait for an explicit
|
||||
// FetchAttachment (the "Save" chip). The descriptor was
|
||||
// already filename-sanitized + size-capped on ingest.
|
||||
if let Some(att) = attachment.clone()
|
||||
&& att.kind == crate::files::AttachmentKind::Image
|
||||
{
|
||||
spawn_attachment_fetch(
|
||||
transport_events.clone(),
|
||||
ui_tx_events.clone(),
|
||||
from,
|
||||
att,
|
||||
true,
|
||||
);
|
||||
//
|
||||
// The auto path is an untrusted-peer-triggered detached
|
||||
// task, so it is gated (Tier C F-02): only roster authors
|
||||
// qualify, identical (author,id) pairs are deduped, and a
|
||||
// permit pool caps concurrent fetch tasks. The chat TEXT
|
||||
// is always forwarded (it's sanitized at the UI edge);
|
||||
// only the fetch is bounded.
|
||||
if let Some(att) = attachment.clone() {
|
||||
let is_image = att.kind == crate::files::AttachmentKind::Image;
|
||||
let key = (from, att.id);
|
||||
let already_inflight =
|
||||
inflight_attachments.lock().unwrap().contains(&key);
|
||||
if should_auto_fetch(is_image, roster.contains(&from), already_inflight) {
|
||||
// Reserve the dedup slot, then a permit. If the
|
||||
// pool is exhausted, drop the auto-fetch (and the
|
||||
// dedup marker) — the descriptor still shows and
|
||||
// the user can fetch on demand.
|
||||
inflight_attachments.lock().unwrap().insert(key);
|
||||
match attachment_limiter.clone().try_acquire_owned() {
|
||||
Ok(permit) => {
|
||||
spawn_attachment_fetch(
|
||||
transport_events.clone(),
|
||||
ui_tx_events.clone(),
|
||||
from,
|
||||
att,
|
||||
true,
|
||||
Some(AutoFetchGuard {
|
||||
_permit: permit,
|
||||
inflight: inflight_attachments.clone(),
|
||||
key,
|
||||
}),
|
||||
);
|
||||
}
|
||||
Err(_) => {
|
||||
inflight_attachments.lock().unwrap().remove(&key);
|
||||
crate::log_msg(
|
||||
"Chat attachment auto-fetch limit reached; skipping (fetch on demand)",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = ui_tx_events.send(UiEvent::ChatMessage {
|
||||
from: from.to_string(),
|
||||
@@ -1931,6 +2102,19 @@ async fn run_core_loop(
|
||||
attachment,
|
||||
}).await;
|
||||
}
|
||||
RoomEvent::ClockSkewSuspected { author, skew_ms } => {
|
||||
crate::log_msg(&format!(
|
||||
"Clock skew suspected for authenticated gossip author={} skew_ms={skew_ms}",
|
||||
crate::short_id(&author.to_string())
|
||||
));
|
||||
let skew_secs = skew_ms.unsigned_abs().saturating_add(999) / 1000;
|
||||
let _ = ui_tx_events
|
||||
.send(UiEvent::ClockSkewWarning {
|
||||
skew_secs,
|
||||
peer_ahead: skew_ms > 0,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
RoomEvent::PeerConnectionLost(peer_id) => {
|
||||
// Transient drop: do NOT tear down the peer. Its audio
|
||||
// supervisor stays alive and keeps redialing the
|
||||
@@ -1992,6 +2176,7 @@ async fn run_core_loop(
|
||||
event_task,
|
||||
conn_event_task,
|
||||
recovery_task,
|
||||
recovery_terminal_task,
|
||||
grace_timers,
|
||||
transport: transport.clone(),
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -2467,12 +2652,15 @@ async fn run_core_loop(
|
||||
CoreCommand::FetchAttachment { from, attachment } => {
|
||||
if let Some(session) = &active_session {
|
||||
let is_image = attachment.kind == crate::files::AttachmentKind::Image;
|
||||
// User-initiated (the "Save" chip): not bounded here — a human
|
||||
// click rate-limits it. The auto path (F-02) passes a guard.
|
||||
spawn_attachment_fetch(
|
||||
session.transport.clone(),
|
||||
ui_tx.clone(),
|
||||
from,
|
||||
attachment,
|
||||
is_image,
|
||||
None,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2481,7 +2669,29 @@ async fn run_core_loop(
|
||||
pixelpass_override = path.filter(|p| !p.trim().is_empty());
|
||||
}
|
||||
|
||||
CoreCommand::StartScreenShare => {
|
||||
CoreCommand::ListAudioApps => {
|
||||
// Probe whether this pixelpass supports `--strict-audio` before
|
||||
// offering per-app capture: an older binary would reject the flag
|
||||
// and hard-fail the share (audit P2). When unsupported (or
|
||||
// pixelpass is missing), skip enumeration and let the picker show
|
||||
// whole-desktop audio only — never a best-effort `--app` that
|
||||
// would reopen the A23 echo.
|
||||
let app_audio_supported =
|
||||
match crate::screenshare::pixelpass_path(pixelpass_override.as_deref()) {
|
||||
Some(bin) => crate::screenshare::supports_strict_audio(&bin).await,
|
||||
None => false,
|
||||
};
|
||||
let apps = if app_audio_supported {
|
||||
crate::screenshare::list_audio_apps().await
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let _ = ui_tx
|
||||
.send(UiEvent::AudioAppsListed { apps, app_audio_supported })
|
||||
.await;
|
||||
}
|
||||
|
||||
CoreCommand::StartScreenShare { audio_app } => {
|
||||
let Some(session) = &mut active_session else {
|
||||
let _ = ui_tx
|
||||
.send(UiEvent::Error("Join a call before sharing your screen".into()))
|
||||
@@ -2502,7 +2712,33 @@ async fn run_core_loop(
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match crate::screenshare::spawn_host(&bin).await {
|
||||
// Forward pixelpass `app_audio` events (only emitted when an app
|
||||
// is selected) to the UI so it can warn when the chosen app's
|
||||
// audio drops. The channel closes when the host dies (drain hits
|
||||
// EOF), ending the forwarder task on its own.
|
||||
let notices = audio_app.as_deref().map(|_| {
|
||||
let (tx, mut rx) =
|
||||
tokio::sync::mpsc::unbounded_channel::<crate::screenshare::PixelpassEvent>();
|
||||
let ui_tx_notices = ui_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Some(ev) = rx.recv().await {
|
||||
let active = match ev {
|
||||
crate::screenshare::PixelpassEvent::AppAudioRouted => true,
|
||||
crate::screenshare::PixelpassEvent::AppAudioLost => false,
|
||||
_ => continue,
|
||||
};
|
||||
if ui_tx_notices
|
||||
.send(UiEvent::ShareAudioActive(active))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
tx
|
||||
});
|
||||
match crate::screenshare::spawn_host(&bin, audio_app.as_deref(), notices).await {
|
||||
Ok((child, ticket)) => {
|
||||
crate::log_msg("Screen share host started");
|
||||
session.screenshare_host = Some(child);
|
||||
@@ -2575,11 +2811,39 @@ async fn run_core_loop(
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
apply_volume, audio_datagram_len_ok, frame_level, mix_frames, mix_stereo_frames,
|
||||
next_game_change, stereo_to_mono, KnownPeers, MicLevelMeter, PeerSpeakTicket,
|
||||
MAX_OPUS_PAYLOAD, MIC_LEVEL_REPORT_SAMPLES,
|
||||
admit_retained, apply_peer_volume, apply_volume, audio_datagram_len_ok, frame_level,
|
||||
mix_frames, mix_stereo_frames, next_game_change, should_auto_fetch, stereo_to_mono,
|
||||
KnownPeers, MicLevelMeter, PeerSpeakTicket, MAX_OPUS_PAYLOAD, MAX_RETAINED_PEERS,
|
||||
MIC_LEVEL_REPORT_SAMPLES,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn admit_retained_rejects_only_new_ids_at_the_cap() {
|
||||
// Below the cap, a brand-new identity is retained.
|
||||
assert!(admit_retained(0, true, MAX_RETAINED_PEERS));
|
||||
assert!(admit_retained(MAX_RETAINED_PEERS - 1, true, MAX_RETAINED_PEERS));
|
||||
// At the cap, a brand-new identity is refused — this is the bound that stops
|
||||
// an insider grace-cycling distinct identities from growing the retain table.
|
||||
assert!(!admit_retained(MAX_RETAINED_PEERS, true, MAX_RETAINED_PEERS));
|
||||
// A peer already tracked always refreshes, even at (or past) the cap: it only
|
||||
// updates an existing address and never adds a slot.
|
||||
assert!(admit_retained(MAX_RETAINED_PEERS, false, MAX_RETAINED_PEERS));
|
||||
assert!(admit_retained(MAX_RETAINED_PEERS + 5, false, MAX_RETAINED_PEERS));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_fetch_only_for_roster_images_not_already_inflight() {
|
||||
// The happy path: a roster author's brand-new image attachment.
|
||||
assert!(should_auto_fetch(true, true, false));
|
||||
// A non-image (generic file) never auto-fetches — it waits for "Save".
|
||||
assert!(!should_auto_fetch(false, true, false));
|
||||
// A non-roster author (e.g. a sock puppet that never announced) is rejected,
|
||||
// closing the F-02 unbounded-task vector.
|
||||
assert!(!should_auto_fetch(true, false, false));
|
||||
// An identical (author,id) already being fetched is deduped.
|
||||
assert!(!should_auto_fetch(true, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retained_peers_are_shared_by_topic_across_restamped_tickets() {
|
||||
let topic_id = [23u8; 32];
|
||||
@@ -2809,6 +3073,30 @@ mod tests {
|
||||
assert_eq!(frame, vec![2000, -2000]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_volume_map_scales_the_matching_audio_peer_frame() {
|
||||
let peer = iroh::SecretKey::generate().public();
|
||||
let other_peer = iroh::SecretKey::generate().public();
|
||||
let volumes = std::collections::HashMap::from([(peer, 0.5), (other_peer, 2.0)]);
|
||||
let mut frame = vec![100, -200, 300, -400];
|
||||
|
||||
apply_peer_volume(&mut frame, peer, &volumes);
|
||||
|
||||
assert_eq!(frame, vec![50, -100, 150, -200]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_volume_map_defaults_to_unity_when_audio_peer_key_is_unmatched() {
|
||||
let ui_peer = iroh::SecretKey::generate().public();
|
||||
let audio_peer = iroh::SecretKey::generate().public();
|
||||
let volumes = std::collections::HashMap::from([(ui_peer, 0.5)]);
|
||||
let mut frame = vec![100, -200, 300, -400];
|
||||
|
||||
apply_peer_volume(&mut frame, audio_peer, &volumes);
|
||||
|
||||
assert_eq!(frame, vec![100, -200, 300, -400]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_peers_sum_without_saturation() {
|
||||
let a = vec![10, 20];
|
||||
|
||||
+68
-8
@@ -22,6 +22,27 @@ fn recovery_delay(attempt: usize) -> Duration {
|
||||
RECOVERY_DELAYS[attempt.min(RECOVERY_DELAYS.len() - 1)]
|
||||
}
|
||||
|
||||
/// Terminal retry budget for background recovery. After this many failed attempts
|
||||
/// the coordinator gives up: it drops the entry, frees the active slot, and signals
|
||||
/// the event task to forget the retained address (Tier C recovery-identity cap).
|
||||
///
|
||||
/// With the [`RECOVERY_DELAYS`] backoff this is roughly seven minutes of dialing
|
||||
/// (1+2+4+8+15+30+60s, then 60s steps), far beyond any normal transient outage. A
|
||||
/// genuine peer returning after a longer outage still rejoins on its own via a
|
||||
/// gossip announce, so giving up only stops us from dialing a peer that is not
|
||||
/// coming back — it does not break legitimate reconnect-after-outage.
|
||||
const RECOVERY_TERMINAL_ATTEMPTS: usize = 12;
|
||||
|
||||
/// Capacity of the terminal-eviction notification channel. Bounded; on the rare
|
||||
/// event of saturation the entry is still removed (the dial work stops) and only
|
||||
/// the retained-address forget is skipped, which the per-topic retain cap bounds.
|
||||
const RECOVERY_TERMINAL_CAPACITY: usize = 64;
|
||||
|
||||
/// Whether `attempt` completed recoveries have exhausted the terminal budget.
|
||||
fn recovery_is_terminal(attempt: usize, max_attempts: usize) -> bool {
|
||||
attempt >= max_attempts
|
||||
}
|
||||
|
||||
enum RecoveryCommand {
|
||||
Start {
|
||||
peer_id: EndpointId,
|
||||
@@ -60,19 +81,24 @@ pub(super) struct RecoveryCoordinator {
|
||||
}
|
||||
|
||||
impl RecoveryCoordinator {
|
||||
pub(super) fn spawn(room_state: Arc<IrohGossipState>) -> (Self, JoinHandle<()>) {
|
||||
pub(super) fn spawn(
|
||||
room_state: Arc<IrohGossipState>,
|
||||
) -> (Self, JoinHandle<()>, mpsc::Receiver<EndpointId>) {
|
||||
Self::spawn_inner(room_state)
|
||||
}
|
||||
|
||||
fn spawn_inner(room_state: Arc<dyn RecoveryRoom>) -> (Self, JoinHandle<()>) {
|
||||
fn spawn_inner(
|
||||
room_state: Arc<dyn RecoveryRoom>,
|
||||
) -> (Self, JoinHandle<()>, mpsc::Receiver<EndpointId>) {
|
||||
let (tx, rx) = mpsc::channel(RECOVERY_COMMAND_CAPACITY);
|
||||
let (terminal_tx, terminal_rx) = mpsc::channel(RECOVERY_TERMINAL_CAPACITY);
|
||||
let active = Arc::new(Mutex::new(HashSet::new()));
|
||||
let handle = Self {
|
||||
tx,
|
||||
active: active.clone(),
|
||||
};
|
||||
let task = tokio::spawn(run_coordinator(room_state, active, rx));
|
||||
(handle, task)
|
||||
let task = tokio::spawn(run_coordinator(room_state, active, rx, terminal_tx));
|
||||
(handle, task, terminal_rx)
|
||||
}
|
||||
|
||||
/// Reserve one recovery slot before grace-expiry teardown begins. Returns
|
||||
@@ -116,6 +142,7 @@ async fn run_coordinator(
|
||||
room_state: Arc<dyn RecoveryRoom>,
|
||||
active: Arc<Mutex<HashSet<EndpointId>>>,
|
||||
mut rx: mpsc::Receiver<RecoveryCommand>,
|
||||
terminal_tx: mpsc::Sender<EndpointId>,
|
||||
) {
|
||||
let mut entries: HashMap<EndpointId, RecoveryEntry> = HashMap::new();
|
||||
|
||||
@@ -155,9 +182,24 @@ async fn run_coordinator(
|
||||
entries.remove(&peer_id);
|
||||
continue;
|
||||
}
|
||||
if let Some(entry) = entries.get_mut(&peer_id) {
|
||||
// Advance the backoff, then check the terminal budget.
|
||||
// `attempt` counts completed attempts, so the delay
|
||||
// uses the current value before it is incremented.
|
||||
let terminal = if let Some(entry) = entries.get_mut(&peer_id) {
|
||||
entry.next_attempt = scheduled_at + recovery_delay(entry.attempt);
|
||||
entry.attempt = entry.attempt.saturating_add(1);
|
||||
recovery_is_terminal(entry.attempt, RECOVERY_TERMINAL_ATTEMPTS)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if terminal {
|
||||
// Give up on a peer that has not returned within the
|
||||
// budget: drop its entry, free the active slot, and
|
||||
// signal the event task to forget its retained
|
||||
// address so the per-topic retain table drains.
|
||||
entries.remove(&peer_id);
|
||||
active.lock().unwrap().remove(&peer_id);
|
||||
let _ = terminal_tx.try_send(peer_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -210,6 +252,23 @@ mod tests {
|
||||
assert_eq!(actual, vec![1, 2, 4, 8, 15, 30, 60, 60, 60, 60]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_budget_is_terminal_only_at_or_past_the_cap() {
|
||||
assert!(!recovery_is_terminal(0, RECOVERY_TERMINAL_ATTEMPTS));
|
||||
assert!(!recovery_is_terminal(
|
||||
RECOVERY_TERMINAL_ATTEMPTS - 1,
|
||||
RECOVERY_TERMINAL_ATTEMPTS
|
||||
));
|
||||
assert!(recovery_is_terminal(
|
||||
RECOVERY_TERMINAL_ATTEMPTS,
|
||||
RECOVERY_TERMINAL_ATTEMPTS
|
||||
));
|
||||
assert!(recovery_is_terminal(
|
||||
RECOVERY_TERMINAL_ATTEMPTS + 5,
|
||||
RECOVERY_TERMINAL_ATTEMPTS
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_slots_are_deduplicated_and_cancel_immediately() {
|
||||
let (tx, mut rx) = mpsc::channel(4);
|
||||
@@ -244,9 +303,10 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn coordinator_attempts_rebootstrap_immediately() {
|
||||
let (attempts_tx, mut attempts_rx) = mpsc::unbounded_channel();
|
||||
let (coordinator, task) = RecoveryCoordinator::spawn_inner(Arc::new(RecordingRoom {
|
||||
attempts: attempts_tx,
|
||||
}));
|
||||
let (coordinator, task, _terminal_rx) =
|
||||
RecoveryCoordinator::spawn_inner(Arc::new(RecordingRoom {
|
||||
attempts: attempts_tx,
|
||||
}));
|
||||
let peer_id = SecretKey::generate().public();
|
||||
let addr = EndpointAddr::from(peer_id);
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ pub mod discovery;
|
||||
pub mod hotkeys;
|
||||
pub mod files;
|
||||
pub mod game;
|
||||
pub mod widget;
|
||||
|
||||
use std::fs::File;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
+429
-12
@@ -1,11 +1,11 @@
|
||||
use crate::network::{RoomState, NetError, PeerState, RoomEvent, PeerSpeakTicket};
|
||||
use iroh::{Endpoint, EndpointAddr, EndpointId, SecretKey, Signature};
|
||||
use iroh::{Endpoint, EndpointAddr, EndpointId, SecretKey, Signature, TransportAddr};
|
||||
use iroh_gossip::net::Gossip;
|
||||
use iroh_gossip::proto::TopicId;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::mpsc::Receiver;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use async_trait::async_trait;
|
||||
use tokio_stream::StreamExt;
|
||||
use serde::{Serialize, Deserialize};
|
||||
@@ -131,6 +131,183 @@ fn admit_state_mutation(
|
||||
true
|
||||
}
|
||||
|
||||
/// Size at which we prune stale entries from the replay-tracking map (Tier C
|
||||
/// F-01 audit). `admit_state_mutation` records `(author, kind)` for every signed
|
||||
/// mutation, so an insider sending validly signed `Leave`s from unlimited
|
||||
/// generated keys would otherwise grow it for the room's lifetime. A mutation
|
||||
/// older than the freshness window can never be the deciding `last_ts` for an
|
||||
/// in-window message — `verify_gossip`'s timestamp check rejects such a replay
|
||||
/// first — so dropping those entries cannot weaken replay protection; it bounds
|
||||
/// the map to roughly the authors seen within one freshness window.
|
||||
const STATE_MUTATIONS_SOFT_CAP: usize = 256;
|
||||
|
||||
/// Drop replay-tracking entries whose timestamp is older than `window_ms` before
|
||||
/// `now_ms` (see [`STATE_MUTATIONS_SOFT_CAP`]). Pure → unit-testable.
|
||||
fn prune_stale_mutations(
|
||||
seen: &mut HashMap<(EndpointId, StateMutationKind), u64>,
|
||||
now_ms: u64,
|
||||
window_ms: u64,
|
||||
) {
|
||||
let floor = now_ms.saturating_sub(window_ms);
|
||||
seen.retain(|_, last_ts| *last_ts >= floor);
|
||||
}
|
||||
|
||||
/// Three signed, out-of-window payloads inside one minute is enough to distinguish
|
||||
/// a persistently skewed clock from a single delayed gossip frame without making
|
||||
/// the user wait long. Repeats are suppressed for five minutes per author.
|
||||
const CLOCK_SKEW_OBSERVATION_WINDOW_MS: u64 = 60_000;
|
||||
const CLOCK_SKEW_WARNING_THRESHOLD: usize = 3;
|
||||
const CLOCK_SKEW_COOLDOWN_MS: u64 = 5 * 60_000;
|
||||
const CLOCK_SKEW_AUTHORS_SOFT_CAP: usize = 256;
|
||||
const CLOCK_SKEW_AUTHORS_HARD_CAP: usize = 512;
|
||||
const CLOCK_SKEW_AUTHOR_TTL_MS: u64 = CLOCK_SKEW_COOLDOWN_MS;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct ClockSkewWarning {
|
||||
author: EndpointId,
|
||||
/// Positive means the peer's sender-stamped clock is ahead of ours.
|
||||
skew_ms: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ClockSkewMonitor {
|
||||
authors: HashMap<EndpointId, ClockSkewAuthorState>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ClockSkewAuthorState {
|
||||
observed_at: Vec<u64>,
|
||||
last_seen_ms: u64,
|
||||
last_warned_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl ClockSkewMonitor {
|
||||
fn observe(
|
||||
&mut self,
|
||||
author: EndpointId,
|
||||
skew_ms: i64,
|
||||
now_ms: u64,
|
||||
) -> Option<ClockSkewWarning> {
|
||||
if self.authors.len() > CLOCK_SKEW_AUTHORS_SOFT_CAP {
|
||||
self.prune_stale_authors(now_ms);
|
||||
}
|
||||
|
||||
let warning = {
|
||||
let state = self.authors.entry(author).or_default();
|
||||
state.last_seen_ms = now_ms;
|
||||
let floor = now_ms.saturating_sub(CLOCK_SKEW_OBSERVATION_WINDOW_MS);
|
||||
state.observed_at.retain(|ts| *ts >= floor);
|
||||
state.observed_at.push(now_ms);
|
||||
if state.observed_at.len() > CLOCK_SKEW_WARNING_THRESHOLD {
|
||||
let excess = state.observed_at.len() - CLOCK_SKEW_WARNING_THRESHOLD;
|
||||
state.observed_at.drain(0..excess);
|
||||
}
|
||||
|
||||
let threshold_met = state.observed_at.len() >= CLOCK_SKEW_WARNING_THRESHOLD;
|
||||
let in_cooldown = state
|
||||
.last_warned_ms
|
||||
.is_some_and(|last| now_ms.saturating_sub(last) < CLOCK_SKEW_COOLDOWN_MS);
|
||||
if threshold_met && !in_cooldown {
|
||||
state.last_warned_ms = Some(now_ms);
|
||||
Some(ClockSkewWarning { author, skew_ms })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
if self.authors.len() > CLOCK_SKEW_AUTHORS_HARD_CAP {
|
||||
self.drop_oldest_authors();
|
||||
}
|
||||
|
||||
warning
|
||||
}
|
||||
|
||||
fn prune_stale_authors(&mut self, now_ms: u64) {
|
||||
let stale_before = now_ms.saturating_sub(CLOCK_SKEW_AUTHOR_TTL_MS);
|
||||
self.authors.retain(|_, state| {
|
||||
let last_warning_live = state
|
||||
.last_warned_ms
|
||||
.is_some_and(|last| now_ms.saturating_sub(last) < CLOCK_SKEW_COOLDOWN_MS);
|
||||
last_warning_live || state.last_seen_ms >= stale_before
|
||||
});
|
||||
}
|
||||
|
||||
fn drop_oldest_authors(&mut self) {
|
||||
let remove_count = self.authors.len().saturating_sub(CLOCK_SKEW_AUTHORS_SOFT_CAP);
|
||||
let mut by_age: Vec<_> = self
|
||||
.authors
|
||||
.iter()
|
||||
.map(|(author, state)| (*author, state.last_seen_ms))
|
||||
.collect();
|
||||
by_age.sort_by_key(|(_, last_seen_ms)| *last_seen_ms);
|
||||
for (author, _) in by_age.into_iter().take(remove_count) {
|
||||
self.authors.remove(&author);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Maximum number of distinct peers we hold in a room roster at once.
|
||||
///
|
||||
/// Everyone with the room ticket is an authenticated *insider*: a signature only
|
||||
/// proves ownership of the generated keypair it was made with, not that the
|
||||
/// author is a distinct human. A malicious member can therefore mint many valid
|
||||
/// signed identities. Voice is full-mesh (each peer dials every other), so a real
|
||||
/// room is realistically well under this bound; the cap exists purely so a flood
|
||||
/// of sock-puppet `Announce`s can't grow our peer map / audio supervisors / dials
|
||||
/// without limit (Tier C F-01).
|
||||
const MAX_ACTIVE_PEERS: usize = 32;
|
||||
|
||||
/// Maximum transport addresses we retain from a single peer announce. iroh
|
||||
/// normally advertises a handful (a few LAN/WAN IP candidates plus one home
|
||||
/// relay); the cap stops an insider stuffing a large unique address set into each
|
||||
/// announce to inflate the address lookup and the dialer's candidate list.
|
||||
const MAX_PEER_ADDRS: usize = 8;
|
||||
|
||||
/// Maximum byte length of a relay URL we accept inside a peer address. A relay
|
||||
/// URL is normal-length; anything longer is dropped rather than retained.
|
||||
const MAX_RELAY_URL_LEN: usize = 256;
|
||||
|
||||
/// Bound an untrusted peer's advertised address set before we retain it / hand it
|
||||
/// to the address lookup and dialer (Tier C F-01). Drops transport kinds we never
|
||||
/// use (`Custom`) and over-long relay URLs, then truncates to at most
|
||||
/// [`MAX_PEER_ADDRS`] addresses. `BTreeSet` iteration is deterministic, so the
|
||||
/// kept subset is stable. Pure → unit-testable.
|
||||
fn sanitize_endpoint_addr(addr: &EndpointAddr) -> EndpointAddr {
|
||||
let addrs: BTreeSet<TransportAddr> = addr
|
||||
.addrs
|
||||
.iter()
|
||||
.filter(|a| match a {
|
||||
TransportAddr::Relay(url) => url.as_str().len() <= MAX_RELAY_URL_LEN,
|
||||
TransportAddr::Ip(_) => true,
|
||||
// `TransportAddr` is #[non_exhaustive]; we only speak IP + relay, so
|
||||
// anything else (Custom / future kinds) is dropped, not retained.
|
||||
_ => false,
|
||||
})
|
||||
.take(MAX_PEER_ADDRS)
|
||||
.cloned()
|
||||
.collect();
|
||||
EndpointAddr { id: addr.id, addrs }
|
||||
}
|
||||
|
||||
/// Whether an `Announce` may enter the roster. Only a brand-new author
|
||||
/// (`subject_to_cap`) is gated by [`MAX_ACTIVE_PEERS`]; updates to an
|
||||
/// already-present peer AND re-announces from a peer mid-reconnect (which
|
||||
/// already held a slot) always pass — exempting reconnects keeps a full room
|
||||
/// from rejecting a legitimately reconnecting member and orphaning its recovery
|
||||
/// state (Tier C F-01 audit). Pure → unit-testable.
|
||||
fn admit_into_roster(roster_len: usize, subject_to_cap: bool, max_peers: usize) -> bool {
|
||||
!subject_to_cap || roster_len < max_peers
|
||||
}
|
||||
|
||||
/// Whether a received `Announce`'s author is gated by the roster cap. A peer
|
||||
/// already in the roster (`is_new == false`, an ordinary update) or one
|
||||
/// mid-reconnect (`is_reconnecting`, it already held a slot) is exempt; only a
|
||||
/// brand-new author counts against [`MAX_ACTIVE_PEERS`] (Tier C F-01 audit).
|
||||
/// Pure → unit-testable.
|
||||
fn announce_subject_to_cap(is_new: bool, is_reconnecting: bool) -> bool {
|
||||
is_new && !is_reconnecting
|
||||
}
|
||||
|
||||
fn peer_state_for_log(state: &PeerState) -> String {
|
||||
format!(
|
||||
"name={:?}, muted={}, addr_id={}, addrs={}, sharing={}, game={:?}",
|
||||
@@ -330,6 +507,7 @@ impl RoomState for IrohGossipState {
|
||||
let handle = tokio::spawn(async move {
|
||||
crate::log_msg(&format!("Spawned gossip topic loop for self_id={:?}", self_id));
|
||||
let mut state_mutations_seen = HashMap::new();
|
||||
let mut clock_skew_monitor = ClockSkewMonitor::default();
|
||||
|
||||
// Broadcast initial state
|
||||
let initial_payload = {
|
||||
@@ -370,9 +548,28 @@ impl RoomState for IrohGossipState {
|
||||
// action: a forged/stale payload is dropped here
|
||||
// so it can't impersonate, evict, or poison
|
||||
// presence/address-book (security S2).
|
||||
if let Err(reason) =
|
||||
verify_gossip(&payload, &topic_bytes, now_millis(), GOSSIP_FRESHNESS_MS)
|
||||
{
|
||||
let received_now_ms = now_millis();
|
||||
if let Err(reason) = verify_gossip(
|
||||
&payload,
|
||||
&topic_bytes,
|
||||
received_now_ms,
|
||||
GOSSIP_FRESHNESS_MS,
|
||||
) {
|
||||
if reason == GossipReject::OutOfWindow {
|
||||
let skew_ms = payload.ts as i64 - received_now_ms as i64;
|
||||
if let Some(warning) = clock_skew_monitor.observe(
|
||||
payload.author,
|
||||
skew_ms,
|
||||
received_now_ms,
|
||||
) {
|
||||
let _ = event_tx
|
||||
.send(RoomEvent::ClockSkewSuspected {
|
||||
author: warning.author,
|
||||
skew_ms: warning.skew_ms,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
crate::log_msg(&format!(
|
||||
"Gossip dropped unauthenticated/stale payload claiming author={:?}: {:?}",
|
||||
payload.author, reason
|
||||
@@ -390,6 +587,18 @@ impl RoomState for IrohGossipState {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Keep the replay-tracking map bounded: prune entries
|
||||
// older than the freshness window once it grows past the
|
||||
// soft cap (Tier C F-01 audit). Stale entries can't gate
|
||||
// an in-window message, so this never weakens replay
|
||||
// protection.
|
||||
if state_mutations_seen.len() > STATE_MUTATIONS_SOFT_CAP {
|
||||
prune_stale_mutations(
|
||||
&mut state_mutations_seen,
|
||||
now_millis(),
|
||||
GOSSIP_FRESHNESS_MS,
|
||||
);
|
||||
}
|
||||
if !admit_state_mutation(
|
||||
&mut state_mutations_seen,
|
||||
payload.author,
|
||||
@@ -436,16 +645,49 @@ impl RoomState for IrohGossipState {
|
||||
let cleaned = crate::sanitize::sanitize_game_label(&g);
|
||||
(!cleaned.is_empty()).then_some(cleaned)
|
||||
});
|
||||
disconnected_peers.lock().unwrap().remove(&payload.author);
|
||||
let (is_new, state_changed) = {
|
||||
// Bound an insider's advertised address set
|
||||
// before we retain it / hand it to the dialer
|
||||
// (Tier C F-01).
|
||||
state.addr = sanitize_endpoint_addr(&state.addr);
|
||||
// A peer reconnecting from a transient drop sits
|
||||
// in `disconnected_peers` (not the live roster);
|
||||
// it already held a slot, so it must be re-admitted
|
||||
// regardless of the cap, and its disconnect marker
|
||||
// cleared ONLY once re-admitted — clearing it before
|
||||
// a possible reject would orphan its recovery state
|
||||
// (Tier C F-01 audit).
|
||||
let is_reconnecting =
|
||||
disconnected_peers.lock().unwrap().contains(&payload.author);
|
||||
let admitted = {
|
||||
let mut peer_map = peers.lock().unwrap();
|
||||
let is_new = !peer_map.contains_key(&payload.author);
|
||||
let state_changed = peer_map.get(&payload.author) != Some(&state);
|
||||
if is_new || state_changed {
|
||||
peer_map.insert(payload.author, state.clone());
|
||||
// Cap the roster so a flood of signed
|
||||
// sock-puppet identities can't grow our
|
||||
// memory/tasks/dials without bound (Tier C
|
||||
// F-01). Existing-peer updates and reconnects
|
||||
// are exempt; only brand-new authors are gated.
|
||||
let subject_to_cap = announce_subject_to_cap(is_new, is_reconnecting);
|
||||
if !admit_into_roster(peer_map.len(), subject_to_cap, MAX_ACTIVE_PEERS) {
|
||||
None
|
||||
} else {
|
||||
let state_changed = peer_map.get(&payload.author) != Some(&state);
|
||||
if is_new || state_changed {
|
||||
peer_map.insert(payload.author, state.clone());
|
||||
}
|
||||
Some((is_new, state_changed))
|
||||
}
|
||||
(is_new, state_changed)
|
||||
};
|
||||
let Some((is_new, state_changed)) = admitted else {
|
||||
crate::log_msg(&format!(
|
||||
"Gossip roster full ({MAX_ACTIVE_PEERS}); rejecting new peer {}",
|
||||
crate::short_id(&payload.author.to_string())
|
||||
));
|
||||
continue;
|
||||
};
|
||||
// Admitted — now it is safe to clear any reconnect
|
||||
// marker (a rejected announce above leaves it intact
|
||||
// so a later signed Leave still cleans up).
|
||||
disconnected_peers.lock().unwrap().remove(&payload.author);
|
||||
|
||||
if is_new {
|
||||
crate::log_msg(&format!(
|
||||
@@ -453,7 +695,12 @@ impl RoomState for IrohGossipState {
|
||||
crate::short_id(&payload.author.to_string()),
|
||||
peer_state_for_log(&state)
|
||||
));
|
||||
address_lookup.add_endpoint_info(state.addr.clone());
|
||||
// Replace (not union) the lookup's record for
|
||||
// this id with the authenticated, sanitized
|
||||
// address set, so leave/re-announce cycles
|
||||
// can't accumulate attacker-supplied history
|
||||
// (Tier C F-01).
|
||||
let _ = address_lookup.set_endpoint_info(state.addr.clone());
|
||||
let _ = event_tx.send(RoomEvent::PeerJoined(payload.author, state)).await;
|
||||
} else if state_changed {
|
||||
crate::log_msg(&format!(
|
||||
@@ -466,6 +713,11 @@ impl RoomState for IrohGossipState {
|
||||
}
|
||||
GossipMessage::Leave => {
|
||||
crate::log_msg(&format!("Gossip peer leave request from author={:?}", payload.author));
|
||||
// Drop this id's address-lookup entry so cycling
|
||||
// distinct identities through Announce→Leave can't
|
||||
// grow the lookup for the room's lifetime (Tier C
|
||||
// F-01 audit). Re-announce re-populates it.
|
||||
let _ = address_lookup.remove_endpoint_info(payload.author);
|
||||
let removed = peers.lock().unwrap().remove(&payload.author).is_some();
|
||||
let was_disconnected = disconnected_peers
|
||||
.lock()
|
||||
@@ -768,6 +1020,171 @@ mod tests {
|
||||
assert!(!bootstrap.contains(&me));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admit_into_roster_caps_new_authors_but_not_updates() {
|
||||
// New authors are admitted while there's room...
|
||||
assert!(admit_into_roster(0, true, 3));
|
||||
assert!(admit_into_roster(2, true, 3));
|
||||
// ...rejected once the roster is full...
|
||||
assert!(!admit_into_roster(3, true, 3));
|
||||
assert!(!admit_into_roster(10, true, 3));
|
||||
// ...but an existing peer's update always passes, even at/over the cap.
|
||||
assert!(admit_into_roster(3, false, 3));
|
||||
assert!(admit_into_roster(99, false, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconnecting_and_existing_peers_are_exempt_from_the_cap() {
|
||||
// A brand-new author counts against the cap...
|
||||
assert!(announce_subject_to_cap(/* is_new */ true, /* is_reconnecting */ false));
|
||||
// ...but an ordinary update from an in-roster peer does not...
|
||||
assert!(!announce_subject_to_cap(false, false));
|
||||
// ...and neither does a re-announce from a peer mid-reconnect, even
|
||||
// though it was removed from the live roster (the F-01-audit fix: a full
|
||||
// room must not reject a legitimately reconnecting member).
|
||||
assert!(!announce_subject_to_cap(true, true));
|
||||
// Combined with admit_into_roster: a reconnecting author passes at a full
|
||||
// roster, a brand-new one does not.
|
||||
assert!(admit_into_roster(3, announce_subject_to_cap(true, true), 3));
|
||||
assert!(!admit_into_roster(3, announce_subject_to_cap(true, false), 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_stale_mutations_drops_only_out_of_window_entries() {
|
||||
let a = fresh_id();
|
||||
let b = fresh_id();
|
||||
let mut seen = HashMap::new();
|
||||
seen.insert((a, StateMutationKind::Announce), 10_000u64);
|
||||
seen.insert((b, StateMutationKind::Leave), 250_000u64);
|
||||
// now = 300_000, window = 120_000 → floor 180_000. The 10_000 entry is
|
||||
// stale (and could never gate an in-window message), the 250_000 is live.
|
||||
prune_stale_mutations(&mut seen, 300_000, GOSSIP_FRESHNESS_MS);
|
||||
assert_eq!(seen.len(), 1);
|
||||
assert!(seen.contains_key(&(b, StateMutationKind::Leave)));
|
||||
assert!(!seen.contains_key(&(a, StateMutationKind::Announce)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_skew_monitor_single_drop_does_not_warn() {
|
||||
let author = fresh_id();
|
||||
let mut monitor = ClockSkewMonitor::default();
|
||||
|
||||
assert_eq!(monitor.observe(author, -121_000, 10_000), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_skew_monitor_three_drops_in_window_warn_once() {
|
||||
let author = fresh_id();
|
||||
let mut monitor = ClockSkewMonitor::default();
|
||||
|
||||
assert_eq!(monitor.observe(author, -121_000, 10_000), None);
|
||||
assert_eq!(monitor.observe(author, -122_000, 40_000), None);
|
||||
assert_eq!(
|
||||
monitor.observe(author, -123_000, 69_999),
|
||||
Some(ClockSkewWarning { author, skew_ms: -123_000 })
|
||||
);
|
||||
assert_eq!(monitor.observe(author, -124_000, 70_000), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_skew_monitor_cooldown_suppresses_repeats() {
|
||||
let author = fresh_id();
|
||||
let mut monitor = ClockSkewMonitor::default();
|
||||
|
||||
assert_eq!(monitor.observe(author, 121_000, 0), None);
|
||||
assert_eq!(monitor.observe(author, 122_000, 10_000), None);
|
||||
assert!(monitor.observe(author, 123_000, 20_000).is_some());
|
||||
|
||||
assert_eq!(monitor.observe(author, 124_000, 30_000), None);
|
||||
assert_eq!(monitor.observe(author, 125_000, 310_000), None);
|
||||
assert_eq!(monitor.observe(author, 126_000, 319_000), None);
|
||||
assert_eq!(monitor.observe(author, 127_000, 319_999), None);
|
||||
assert_eq!(
|
||||
monitor.observe(author, 128_000, 320_000),
|
||||
Some(ClockSkewWarning { author, skew_ms: 128_000 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_skew_monitor_tracks_distinct_authors_independently() {
|
||||
let a = fresh_id();
|
||||
let b = fresh_id();
|
||||
let mut monitor = ClockSkewMonitor::default();
|
||||
|
||||
assert_eq!(monitor.observe(a, -121_000, 0), None);
|
||||
assert_eq!(monitor.observe(a, -121_000, 1_000), None);
|
||||
assert_eq!(monitor.observe(b, 121_000, 0), None);
|
||||
assert_eq!(monitor.observe(b, 121_000, 1_000), None);
|
||||
assert_eq!(
|
||||
monitor.observe(b, 121_000, 2_000),
|
||||
Some(ClockSkewWarning { author: b, skew_ms: 121_000 })
|
||||
);
|
||||
assert_eq!(
|
||||
monitor.observe(a, -121_000, 2_000),
|
||||
Some(ClockSkewWarning { author: a, skew_ms: -121_000 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_skew_monitor_prunes_stale_authors_when_over_cap() {
|
||||
let mut monitor = ClockSkewMonitor::default();
|
||||
for _ in 0..=CLOCK_SKEW_AUTHORS_SOFT_CAP {
|
||||
assert_eq!(monitor.observe(fresh_id(), -121_000, 1), None);
|
||||
}
|
||||
assert!(monitor.authors.len() > CLOCK_SKEW_AUTHORS_SOFT_CAP);
|
||||
|
||||
let current = fresh_id();
|
||||
assert_eq!(
|
||||
monitor.observe(current, -121_000, CLOCK_SKEW_AUTHOR_TTL_MS + 2),
|
||||
None
|
||||
);
|
||||
assert_eq!(monitor.authors.len(), 1);
|
||||
assert!(monitor.authors.contains_key(¤t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clock_skew_monitor_hard_cap_bounds_fresh_author_growth() {
|
||||
let mut monitor = ClockSkewMonitor::default();
|
||||
for now_ms in 0..(CLOCK_SKEW_AUTHORS_HARD_CAP as u64 + 10) {
|
||||
let _ = monitor.observe(fresh_id(), -121_000, now_ms);
|
||||
assert!(monitor.authors.len() <= CLOCK_SKEW_AUTHORS_HARD_CAP);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_endpoint_addr_caps_address_count() {
|
||||
use std::net::SocketAddr;
|
||||
let id = fresh_id();
|
||||
// An insider stuffs far more addresses than MAX_PEER_ADDRS into one announce.
|
||||
let many: Vec<TransportAddr> = (0..(MAX_PEER_ADDRS as u16 + 50))
|
||||
.map(|i| TransportAddr::Ip(SocketAddr::from(([127, 0, 0, 1], 1000 + i))))
|
||||
.collect();
|
||||
let addr = EndpointAddr::from_parts(id, many);
|
||||
let out = sanitize_endpoint_addr(&addr);
|
||||
assert_eq!(out.id, id);
|
||||
assert_eq!(out.addrs.len(), MAX_PEER_ADDRS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_endpoint_addr_drops_overlong_relay_url() {
|
||||
use std::str::FromStr;
|
||||
let id = fresh_id();
|
||||
let short = iroh::RelayUrl::from_str("https://relay.example/").unwrap();
|
||||
let long = iroh::RelayUrl::from_str(&format!(
|
||||
"https://relay.example/{}",
|
||||
"a".repeat(MAX_RELAY_URL_LEN)
|
||||
))
|
||||
.unwrap();
|
||||
assert!(long.as_str().len() > MAX_RELAY_URL_LEN);
|
||||
let addr = EndpointAddr::from_parts(
|
||||
id,
|
||||
[TransportAddr::Relay(short.clone()), TransportAddr::Relay(long)],
|
||||
);
|
||||
let out = sanitize_endpoint_addr(&addr);
|
||||
let relays: Vec<_> = out.relay_urls().cloned().collect();
|
||||
assert_eq!(relays, vec![short], "over-long relay URL must be dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_gossip_message_leave_round_trip() {
|
||||
let original = GossipMessage::Leave;
|
||||
|
||||
@@ -106,6 +106,10 @@ pub enum RoomEvent {
|
||||
/// from `PeerLeft` precisely so a momentary `NeighborDown` can't tear down the
|
||||
/// reconnect path the way it used to.
|
||||
PeerConnectionLost(EndpointId),
|
||||
/// A validly signed gossip payload was rejected only because its timestamp is
|
||||
/// outside the replay-protection window. The peer is not in the roster yet,
|
||||
/// so this surfaces as a room-level warning instead of a peer-card state.
|
||||
ClockSkewSuspected { author: EndpointId, skew_ms: i64 },
|
||||
/// A peer sent a room text-chat message. Carries the sender's id, their
|
||||
/// display name (embedded so it shows even without a presence entry), the
|
||||
/// text, and a sender-stamped millisecond timestamp.
|
||||
|
||||
+405
-15
@@ -39,6 +39,10 @@ fn pixelpass_path_candidates(dir: &Path) -> [PathBuf; 1] {
|
||||
/// growth, but reject unbounded gossip payloads before the UI offers "Watch".
|
||||
const MAX_TICKET_LEN: usize = 512;
|
||||
|
||||
/// Upper bound on a PipeWire `application.name` we'll pass to `--app`. Real names
|
||||
/// are short ("Firefox", "mpv"); this only guards against a pathological value.
|
||||
const MAX_APP_NAME_LEN: usize = 256;
|
||||
|
||||
/// How long to wait for the host to emit its ticket / the viewer to connect
|
||||
/// before giving up and killing the child. Startup is normally sub-second; this
|
||||
/// is only a safety net so a hung pixelpass can't wedge the caller forever.
|
||||
@@ -64,6 +68,12 @@ pub enum PixelpassEvent {
|
||||
CaptureStarted,
|
||||
/// Host: capture pipeline torn down (on last viewer).
|
||||
CaptureStopped,
|
||||
/// Host (per-app audio): the chosen app's audio is now reaching viewers.
|
||||
AppAudioRouted,
|
||||
/// Host (per-app audio): the chosen app's last audio stream went away. Under
|
||||
/// our `--strict-audio` run this means viewers now hear silence (not the call
|
||||
/// echo) until the app produces audio again — we surface it as a warning.
|
||||
AppAudioLost,
|
||||
/// A recognized event we don't act on (e.g. `host_info`).
|
||||
Other,
|
||||
}
|
||||
@@ -98,6 +108,11 @@ pub fn parse_pixelpass_event(line: &str) -> Option<PixelpassEvent> {
|
||||
Some("stopped") => PixelpassEvent::CaptureStopped,
|
||||
_ => PixelpassEvent::Other,
|
||||
},
|
||||
"app_audio" => match v.get("state").and_then(|s| s.as_str()) {
|
||||
Some("routed") => PixelpassEvent::AppAudioRouted,
|
||||
Some("lost") => PixelpassEvent::AppAudioLost,
|
||||
_ => PixelpassEvent::Other,
|
||||
},
|
||||
_ => PixelpassEvent::Other,
|
||||
};
|
||||
Some(ev)
|
||||
@@ -107,6 +122,144 @@ fn json_u32(v: &serde_json::Value, key: &str) -> u32 {
|
||||
v.get(key).and_then(|x| x.as_u64()).unwrap_or(0) as u32
|
||||
}
|
||||
|
||||
/// Build the argv for a pixelpass *host*. Always `--host --output json`; when
|
||||
/// `audio_app` is `Some`, append `--app=<name> --strict-audio` so pixelpass
|
||||
/// captures only that app's audio instead of the whole desktop sink monitor
|
||||
/// (which contains our own call playout → the viewer would hear themselves
|
||||
/// echoed back, backlog A23).
|
||||
///
|
||||
/// `--strict-audio` is what makes the fix a guarantee rather than best-effort:
|
||||
/// without it, pixelpass falls back to the whole-desktop loopback before the
|
||||
/// app's first stream routes and again if the app's audio later stops — both of
|
||||
/// which reintroduce the echo. With it, the viewer hears only the chosen app (or
|
||||
/// silence), and pixelpass emits `app_audio` events we surface as a warning.
|
||||
///
|
||||
/// The name is passed in the single-token `--app=<name>` form so a value that
|
||||
/// happens to begin with `-` can never be reparsed as a pixelpass flag (clap
|
||||
/// otherwise rejects hyphen-leading option values). The name is locally chosen
|
||||
/// (our own enumeration / the user's pick), not peer-supplied, but is still
|
||||
/// sanitized via [`sanitize_app_name`] before reaching here. Pure: no I/O.
|
||||
pub fn host_args(audio_app: Option<&str>) -> Vec<String> {
|
||||
let mut args = vec![
|
||||
"--host".to_string(),
|
||||
"--output".to_string(),
|
||||
"json".to_string(),
|
||||
];
|
||||
if let Some(name) = audio_app.and_then(sanitize_app_name) {
|
||||
args.push(format!("--app={name}"));
|
||||
args.push("--strict-audio".to_string());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
/// Validate a locally-chosen audio app name before it becomes a `--app` value:
|
||||
/// trim, reject empty / overlong, and reject names carrying control characters
|
||||
/// (newlines etc.) that have no place in a real `application.name`. `None` means
|
||||
/// "no valid app selected" — the caller then shares the whole desktop audio.
|
||||
pub fn sanitize_app_name(name: &str) -> Option<String> {
|
||||
let name = name.trim();
|
||||
let ok = !name.is_empty()
|
||||
&& name.len() <= MAX_APP_NAME_LEN
|
||||
&& !name.chars().any(|c| c.is_control());
|
||||
ok.then(|| name.to_string())
|
||||
}
|
||||
|
||||
/// Hard cap on how long enumeration waits for `pactl`. It runs inline on the core
|
||||
/// command loop (the picker awaits it before opening), so a wedged/slow `pactl`
|
||||
/// must not stall mute/deafen/leave/stop. On timeout we treat it like any other
|
||||
/// failure: empty list → "All system audio" only.
|
||||
const LIST_APPS_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Enumerate the apps currently sending audio to a sink, deduplicated by
|
||||
/// `application.name`. Mirrors how pixelpass itself builds its interactive
|
||||
/// picker (`pactl -f json list sink-inputs`), so the names we return are exactly
|
||||
/// the ones `--app` matches against. Returns an empty list on any error (pactl
|
||||
/// missing, non-PipeWire host, nothing playing, or [`LIST_APPS_TIMEOUT`] elapsed)
|
||||
/// — a normal, handled state that leaves the picker showing only "All system
|
||||
/// audio".
|
||||
pub async fn list_audio_apps() -> Vec<String> {
|
||||
let run = Command::new("pactl")
|
||||
.args(["-f", "json", "list", "sink-inputs"])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
// On [`LIST_APPS_TIMEOUT`] the `output()` future is dropped, which drops
|
||||
// the child — `kill_on_drop(true)` then SIGKILLs and reaps it so a wedged
|
||||
// `pactl` can't linger/accumulate across picker opens (audit P3).
|
||||
.kill_on_drop(true)
|
||||
.output();
|
||||
match tokio::time::timeout(LIST_APPS_TIMEOUT, run).await {
|
||||
Ok(Ok(o)) if o.status.success() => parse_audio_apps(&o.stdout),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Hard cap on the capability probe (`pixelpass --help`). Conservative: a slow or
|
||||
/// hung pixelpass degrades to "strict audio unsupported" → whole-desktop-only
|
||||
/// picker (safe), never a stalled core loop.
|
||||
const HELP_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Whether the resolved pixelpass understands `--strict-audio` (added in pixelpass
|
||||
/// `85fdebe`). peerspeak only offers per-app audio capture when it does: a per-app
|
||||
/// share always appends `--strict-audio`, and an **older** pixelpass would have
|
||||
/// clap reject the unknown flag → the host spawn hard-fails and the share is
|
||||
/// broken (audit P2, version skew). When unsupported the picker degrades to
|
||||
/// whole-desktop audio only — we never silently drop to best-effort `--app`, which
|
||||
/// would reintroduce the call echo (A23).
|
||||
///
|
||||
/// Any probe failure/timeout returns `false` (degrade to the safe path). The
|
||||
/// `--help` child is `kill_on_drop` so a hung pixelpass can't linger.
|
||||
pub async fn supports_strict_audio(bin: &Path) -> bool {
|
||||
let run = Command::new(bin)
|
||||
.arg("--help")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output();
|
||||
match tokio::time::timeout(HELP_PROBE_TIMEOUT, run).await {
|
||||
Ok(Ok(o)) => help_mentions_strict_audio(&o.stdout),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pure check: does `pixelpass --help` advertise `--strict-audio`? Matches the
|
||||
/// flag token rather than a whole line, since clap may wrap/realign help text.
|
||||
pub fn help_mentions_strict_audio(help_stdout: &[u8]) -> bool {
|
||||
String::from_utf8_lossy(help_stdout).contains("--strict-audio")
|
||||
}
|
||||
|
||||
/// Parse `pactl -f json list sink-inputs` stdout into a sorted, deduplicated list
|
||||
/// of `application.name`s. Pure: no I/O. Unparseable input yields an empty list.
|
||||
/// Each name is passed through [`sanitize_app_name`] so the picker only ever
|
||||
/// offers names that will actually survive [`host_args`]; otherwise a name that
|
||||
/// parses here but fails sanitization later would be selectable yet silently
|
||||
/// drop the `--app` flag and revert the share to whole-desktop audio (A23 echo).
|
||||
pub fn parse_audio_apps(stdout: &[u8]) -> Vec<String> {
|
||||
let Ok(entries) = serde_json::from_slice::<Vec<SinkInput>>(stdout) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut names: Vec<String> = entries
|
||||
.into_iter()
|
||||
.filter_map(|e| e.properties.application_name)
|
||||
.filter_map(|n| sanitize_app_name(&n))
|
||||
.collect();
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
names
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct SinkInput {
|
||||
properties: SinkInputProperties,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct SinkInputProperties {
|
||||
#[serde(rename = "application.name")]
|
||||
application_name: Option<String>,
|
||||
}
|
||||
|
||||
/// Build the argv for a pixelpass *viewer*. The `ticket` is peer-supplied (it
|
||||
/// rides gossip presence, which is untrusted and spoofable), so flags come first
|
||||
/// and the ticket is passed as a positional **after a `--` end-of-options
|
||||
@@ -162,20 +315,30 @@ pub fn is_available(config_override: Option<&str>) -> bool {
|
||||
pixelpass_path(config_override).is_some()
|
||||
}
|
||||
|
||||
/// Spawn a pixelpass host (`pixelpass --host --output json`), wait for its
|
||||
/// startup ticket, and return the live child plus the ticket. The child keeps
|
||||
/// Spawn a pixelpass host (`pixelpass --host --output json [--app=<name>]`), wait
|
||||
/// for its startup ticket, and return the live child plus the ticket. When
|
||||
/// `audio_app` is `Some`, pixelpass captures only that app's audio instead of the
|
||||
/// whole desktop sink, which avoids the call-loopback echo (A23). The child keeps
|
||||
/// running (streaming to viewers) until killed or dropped; remaining stdout is
|
||||
/// drained in a background task so a full pipe can't stall the host. We do
|
||||
/// **not** pass `--max-viewers`: pixelpass bandwidth-measures its own safe cap,
|
||||
/// protecting the sharer's uplink, and refuses extras with `viewer_refused`.
|
||||
pub async fn spawn_host(bin: &Path) -> std::io::Result<(Child, String)> {
|
||||
pub async fn spawn_host(
|
||||
bin: &Path,
|
||||
audio_app: Option<&str>,
|
||||
notices: Option<tokio::sync::mpsc::UnboundedSender<PixelpassEvent>>,
|
||||
) -> std::io::Result<(Child, String)> {
|
||||
let mut child = Command::new(bin)
|
||||
.arg("--host")
|
||||
.arg("--output")
|
||||
.arg("json")
|
||||
.args(host_args(audio_app))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
// Capture stderr (not null): pixelpass prints its startup precondition
|
||||
// failures there — a missing GStreamer plugin / `pactl`, each with an
|
||||
// actionable "Install hint: sudo apt install ..." line. If the host dies
|
||||
// before its ticket we fold that tail into our error so the user sees
|
||||
// *what to install* instead of a dead-end "exited before a ticket". On
|
||||
// the success path we drain it in the background so the pipe can't fill.
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()?;
|
||||
|
||||
@@ -183,6 +346,7 @@ pub async fn spawn_host(bin: &Path) -> std::io::Result<(Child, String)> {
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| std::io::Error::other("pixelpass host stdout missing"))?;
|
||||
let stderr = child.stderr.take();
|
||||
let mut lines = BufReader::new(stdout).lines();
|
||||
|
||||
let ticket = match read_until(&mut lines, |e| match e {
|
||||
@@ -194,9 +358,10 @@ pub async fn spawn_host(bin: &Path) -> std::io::Result<(Child, String)> {
|
||||
Ok(Some(t)) => t,
|
||||
Ok(None) => {
|
||||
let _ = child.kill().await;
|
||||
return Err(std::io::Error::other(
|
||||
"pixelpass host exited before emitting a ticket",
|
||||
));
|
||||
let detail = read_stderr_tail(stderr).await;
|
||||
return Err(std::io::Error::other(format!(
|
||||
"pixelpass host exited before emitting a ticket{detail}"
|
||||
)));
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = child.kill().await;
|
||||
@@ -204,10 +369,65 @@ pub async fn spawn_host(bin: &Path) -> std::io::Result<(Child, String)> {
|
||||
}
|
||||
};
|
||||
|
||||
drain_in_background(lines, "host");
|
||||
if let Some(stderr) = stderr {
|
||||
drain_stderr_in_background(stderr);
|
||||
}
|
||||
drain_in_background(lines, "host", notices);
|
||||
Ok((child, ticket))
|
||||
}
|
||||
|
||||
/// Read a killed pixelpass child's stderr to EOF and reduce it to a short,
|
||||
/// user-facing diagnostic tail via [`pixelpass_failure_detail`]. Bounded: the
|
||||
/// caller kills the child first, so the pipe EOFs promptly. Returns an empty
|
||||
/// string when stderr was already taken or carried nothing useful.
|
||||
async fn read_stderr_tail(stderr: Option<tokio::process::ChildStderr>) -> String {
|
||||
use tokio::io::AsyncReadExt;
|
||||
let Some(mut stderr) = stderr else {
|
||||
return String::new();
|
||||
};
|
||||
let mut buf = Vec::new();
|
||||
let _ = stderr.read_to_end(&mut buf).await;
|
||||
pixelpass_failure_detail(&String::from_utf8_lossy(&buf))
|
||||
}
|
||||
|
||||
/// Discard a running pixelpass child's stderr in the background so its pipe
|
||||
/// can't fill and stall the host (mirrors [`drain_in_background`] for stdout).
|
||||
fn drain_stderr_in_background(mut stderr: tokio::process::ChildStderr) {
|
||||
use tokio::io::AsyncReadExt;
|
||||
tokio::spawn(async move {
|
||||
let mut buf = [0u8; 4096];
|
||||
while let Ok(n) = stderr.read(&mut buf).await {
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Extract a human-useful tail from a failed pixelpass child's stderr to append
|
||||
/// to our error. pixelpass writes actionable startup errors there (a missing
|
||||
/// GStreamer element / `pactl` plus an `Install hint: sudo apt install ...`
|
||||
/// line), which is exactly what a freshly-installed host needs to see. The
|
||||
/// decorative host banner (box-drawing) is dropped — it only prints on the
|
||||
/// success path, but we filter it defensively. Pure: no I/O. Returns an empty
|
||||
/// string when there's nothing worth surfacing (so callers can append blindly).
|
||||
pub fn pixelpass_failure_detail(stderr: &str) -> String {
|
||||
let useful: Vec<&str> = stderr
|
||||
.lines()
|
||||
.map(str::trim_end)
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.filter(|l| !l.trim_start().starts_with(['│', '┌', '└', '├']))
|
||||
.collect();
|
||||
if useful.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
// The anyhow error and its install hint are the *last* lines printed, so
|
||||
// keep the tail rather than the head.
|
||||
const MAX_LINES: usize = 12;
|
||||
let start = useful.len().saturating_sub(MAX_LINES);
|
||||
format!("\n\npixelpass reported:\n{}", useful[start..].join("\n"))
|
||||
}
|
||||
|
||||
/// Spawn a pixelpass viewer for `ticket`, wait for it to connect, and open the
|
||||
/// stream in a local player (mpv, falling back to vlc). Returns the live viewer
|
||||
/// child so the caller can kill it on room-leave; it also self-exits when the
|
||||
@@ -251,7 +471,7 @@ pub async fn spawn_viewer(bin: &Path, ticket: &str) -> std::io::Result<Child> {
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
drain_in_background(lines, "viewer");
|
||||
drain_in_background(lines, "viewer", None);
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
@@ -286,15 +506,24 @@ where
|
||||
}
|
||||
|
||||
/// Keep reading the child's stdout to EOF in the background so a full pipe can't
|
||||
/// stall it; log notable events for diagnostics.
|
||||
fn drain_in_background<R>(mut lines: tokio::io::Lines<BufReader<R>>, role: &'static str)
|
||||
where
|
||||
/// stall it; log notable events for diagnostics. When `notices` is `Some`, each
|
||||
/// parsed event is also forwarded to the caller (the core, which translates the
|
||||
/// `app_audio` ones into a UI warning); a send failure (receiver dropped) just
|
||||
/// stops forwarding, draining continues. The task ends on EOF (child exited).
|
||||
fn drain_in_background<R>(
|
||||
mut lines: tokio::io::Lines<BufReader<R>>,
|
||||
role: &'static str,
|
||||
notices: Option<tokio::sync::mpsc::UnboundedSender<PixelpassEvent>>,
|
||||
) where
|
||||
R: tokio::io::AsyncRead + Unpin + Send + 'static,
|
||||
{
|
||||
tokio::spawn(async move {
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
if let Some(ev) = parse_pixelpass_event(&line) {
|
||||
crate::log_msg(&format!("pixelpass {role}: {}", event_for_log(&ev)));
|
||||
if let Some(tx) = ¬ices {
|
||||
let _ = tx.send(ev);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -313,6 +542,8 @@ fn event_for_log(ev: &PixelpassEvent) -> String {
|
||||
PixelpassEvent::Refused(reason) => format!("viewer_refused reason={reason:?}"),
|
||||
PixelpassEvent::CaptureStarted => "capture_started".to_string(),
|
||||
PixelpassEvent::CaptureStopped => "capture_stopped".to_string(),
|
||||
PixelpassEvent::AppAudioRouted => "app_audio_routed".to_string(),
|
||||
PixelpassEvent::AppAudioLost => "app_audio_lost".to_string(),
|
||||
PixelpassEvent::Other => "other".to_string(),
|
||||
}
|
||||
}
|
||||
@@ -384,6 +615,142 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_args_without_app_shares_whole_desktop() {
|
||||
// No app selected → no --app flag → pixelpass keeps its default
|
||||
// (whole-desktop) audio capture.
|
||||
assert_eq!(host_args(None), vec!["--host", "--output", "json"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_args_with_app_appends_single_token_flag() {
|
||||
// The chosen app rides in the `--app=<name>` single-token form so a
|
||||
// name beginning with `-` can never be reparsed as a flag (A23), plus
|
||||
// `--strict-audio` so pixelpass never falls back to whole-desktop audio.
|
||||
assert_eq!(
|
||||
host_args(Some("Firefox")),
|
||||
vec!["--host", "--output", "json", "--app=Firefox", "--strict-audio"]
|
||||
);
|
||||
// The hyphen-leading name is still bound to --app as a single token;
|
||||
// --strict-audio is the trailing flag.
|
||||
let args = host_args(Some("-rm -rf"));
|
||||
assert_eq!(args[3], "--app=-rm -rf");
|
||||
assert_eq!(args[4], "--strict-audio");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_args_blank_or_control_app_is_dropped() {
|
||||
// An empty / whitespace / control-laden selection is sanitized away,
|
||||
// falling back to whole-desktop capture rather than a broken flag.
|
||||
assert_eq!(host_args(Some(" ")), vec!["--host", "--output", "json"]);
|
||||
assert_eq!(host_args(Some("bad\nname")), vec!["--host", "--output", "json"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_app_name_trims_and_rejects_garbage() {
|
||||
assert_eq!(sanitize_app_name(" Firefox \n"), Some("Firefox".to_string()));
|
||||
assert_eq!(sanitize_app_name(""), None);
|
||||
assert_eq!(sanitize_app_name(" "), None);
|
||||
assert_eq!(sanitize_app_name("a\tb"), None);
|
||||
assert_eq!(sanitize_app_name(&"x".repeat(MAX_APP_NAME_LEN + 1)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_audio_apps_dedups_and_sorts_by_application_name() {
|
||||
let stdout = br#"[
|
||||
{"index":1,"properties":{"application.name":"Firefox"}},
|
||||
{"index":2,"properties":{"application.name":"mpv"}},
|
||||
{"index":3,"properties":{"application.name":"Firefox"}},
|
||||
{"index":4,"properties":{"application.name":" Spotify "}},
|
||||
{"index":5,"properties":{"application.name":""}},
|
||||
{"index":6,"properties":{"other":"no name here"}}
|
||||
]"#;
|
||||
assert_eq!(
|
||||
parse_audio_apps(stdout),
|
||||
vec!["Firefox".to_string(), "Spotify".to_string(), "mpv".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_audio_apps_empty_or_garbage_is_empty() {
|
||||
assert_eq!(parse_audio_apps(b""), Vec::<String>::new());
|
||||
assert_eq!(parse_audio_apps(b"not json"), Vec::<String>::new());
|
||||
assert_eq!(parse_audio_apps(b"[]"), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_audio_apps_drops_names_host_args_would_reject() {
|
||||
// Names that parse from pactl but fail `sanitize_app_name` (control chars,
|
||||
// overlong) must NOT be offered in the picker — otherwise the user could
|
||||
// pick one, `host_args` would silently drop `--app`, and the share would
|
||||
// revert to whole-desktop audio (A23 echo) with no signal. The valid name
|
||||
// survives; the control-char and overlong ones are filtered out.
|
||||
let overlong = "x".repeat(MAX_APP_NAME_LEN + 1);
|
||||
let stdout = format!(
|
||||
r#"[
|
||||
{{"index":1,"properties":{{"application.name":"mpv"}}}},
|
||||
{{"index":2,"properties":{{"application.name":"bad\nname"}}}},
|
||||
{{"index":3,"properties":{{"application.name":"{overlong}"}}}}
|
||||
]"#
|
||||
);
|
||||
assert_eq!(parse_audio_apps(stdout.as_bytes()), vec!["mpv".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_detail_surfaces_install_hint_and_drops_banner() {
|
||||
// The real shape of a fresh-host failure: anyhow error + install hint on
|
||||
// stderr. We must keep those (so the user knows what to apt install) and
|
||||
// drop the decorative banner box-drawing lines.
|
||||
let stderr = "\
|
||||
┌─ PixelPass · host ─────────────────────────────────────────
|
||||
│ display server : Wayland
|
||||
└────────────────────────────────────────────────────────────
|
||||
Error: GStreamer element `vah264enc` not available.
|
||||
Install hint: sudo apt install gstreamer1.0-plugins-bad
|
||||
";
|
||||
let detail = pixelpass_failure_detail(stderr);
|
||||
assert!(detail.starts_with("\n\npixelpass reported:\n"));
|
||||
assert!(detail.contains("vah264enc` not available"));
|
||||
assert!(detail.contains("sudo apt install gstreamer1.0-plugins-bad"));
|
||||
assert!(!detail.contains('│'), "banner box-drawing must be dropped");
|
||||
assert!(!detail.contains('┌'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_detail_empty_when_nothing_useful() {
|
||||
// Blank / banner-only stderr yields an empty string so the caller can
|
||||
// append it to the base message unconditionally without trailing noise.
|
||||
assert_eq!(pixelpass_failure_detail(""), "");
|
||||
assert_eq!(pixelpass_failure_detail(" \n \n"), "");
|
||||
assert_eq!(
|
||||
pixelpass_failure_detail("│ display server : Wayland\n│ capture : x\n"),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_detail_keeps_only_the_tail() {
|
||||
// A long stderr is truncated to its last lines (where the real error
|
||||
// and hint live), not its head.
|
||||
let body: String = (0..30).map(|i| format!("line {i}\n")).collect();
|
||||
let detail = pixelpass_failure_detail(&body);
|
||||
assert!(detail.contains("line 29"));
|
||||
assert!(!detail.contains("line 0\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_probe_detects_strict_audio_flag() {
|
||||
// A new pixelpass advertises the flag; an old one doesn't. The probe must
|
||||
// match the token even when clap wraps the option onto its own line.
|
||||
let new_help = b"Options:\n --app <APP>\n --strict-audio\n With --app, never fall back...";
|
||||
assert!(help_mentions_strict_audio(new_help));
|
||||
let old_help = b"Options:\n --app <APP>\n --output <OUTPUT>\n -h, --help";
|
||||
assert!(!help_mentions_strict_audio(old_help));
|
||||
// Garbage / empty output degrades to "unsupported" (safe path).
|
||||
assert!(!help_mentions_strict_audio(b""));
|
||||
assert!(!help_mentions_strict_audio(&[0xff, 0xfe, 0x00]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_ticket_accepts_pixelpass_endpoint_ticket_shape() {
|
||||
let ticket = "endpointaabwxjexzensznfvuudiapn5tyzws3angd2merarm";
|
||||
@@ -470,6 +837,29 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_app_audio_states() {
|
||||
// The wire contract from pixelpass's --strict-audio run (A23): routed =
|
||||
// the chosen app's audio is live; lost = it stopped (viewers now silent).
|
||||
assert_eq!(
|
||||
parse_pixelpass_event(r#"{"event":"app_audio","state":"routed"}"#),
|
||||
Some(PixelpassEvent::AppAudioRouted)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_pixelpass_event(r#"{"event":"app_audio","state":"lost"}"#),
|
||||
Some(PixelpassEvent::AppAudioLost)
|
||||
);
|
||||
// Unknown / missing state is recognized-but-unused, not a parse failure.
|
||||
assert_eq!(
|
||||
parse_pixelpass_event(r#"{"event":"app_audio","state":"weird"}"#),
|
||||
Some(PixelpassEvent::Other)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_pixelpass_event(r#"{"event":"app_audio"}"#),
|
||||
Some(PixelpassEvent::Other)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recognized_but_unused_event_is_other() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -0,0 +1,943 @@
|
||||
use iced::advanced::clipboard::{self, Clipboard};
|
||||
use iced::advanced::layout;
|
||||
use iced::advanced::mouse;
|
||||
use iced::advanced::overlay;
|
||||
use iced::advanced::renderer;
|
||||
use iced::advanced::text;
|
||||
use iced::advanced::widget::tree::{self, Tree};
|
||||
use iced::advanced::widget::{self, Widget};
|
||||
use iced::advanced::{Layout, Shell};
|
||||
use iced::widget::text_input;
|
||||
use iced::{
|
||||
alignment, Background, Border, Color, Element, Event, Length, Padding,
|
||||
Pixels, Point, Rectangle, Shadow, Size, Vector,
|
||||
};
|
||||
use std::rc::Rc;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Edit {
|
||||
pub value: String,
|
||||
pub cursor: usize,
|
||||
}
|
||||
|
||||
pub fn copy_selection(value: &str, start: usize, end: usize) -> Option<String> {
|
||||
let value = text_input::Value::new(value);
|
||||
let (start, end) = normalized_range(&value, start, end);
|
||||
|
||||
(start != end).then(|| value.select(start, end).to_string())
|
||||
}
|
||||
|
||||
pub fn cut_selection(
|
||||
value: &str,
|
||||
start: usize,
|
||||
end: usize,
|
||||
) -> (Edit, Option<String>) {
|
||||
let mut value = text_input::Value::new(value);
|
||||
let (start, end) = normalized_range(&value, start, end);
|
||||
|
||||
if start == end {
|
||||
return (
|
||||
Edit {
|
||||
value: value.to_string(),
|
||||
cursor: start,
|
||||
},
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
let selected = value.select(start, end).to_string();
|
||||
value.remove_many(start, end);
|
||||
|
||||
(
|
||||
Edit {
|
||||
value: value.to_string(),
|
||||
cursor: start,
|
||||
},
|
||||
Some(selected),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn paste(value: &str, start: usize, end: usize, clip: &str) -> Edit {
|
||||
let mut value = text_input::Value::new(value);
|
||||
let (start, end) = normalized_range(&value, start, end);
|
||||
let clip = text_input::Value::new(clip);
|
||||
let cursor = start + clip.len();
|
||||
|
||||
if start != end {
|
||||
value.remove_many(start, end);
|
||||
}
|
||||
value.insert_many(start, clip);
|
||||
|
||||
Edit {
|
||||
value: value.to_string(),
|
||||
cursor,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn select_all_range(value: &str) -> (usize, usize) {
|
||||
let value = text_input::Value::new(value);
|
||||
|
||||
(0, value.len())
|
||||
}
|
||||
|
||||
fn normalized_range(
|
||||
value: &text_input::Value,
|
||||
start: usize,
|
||||
end: usize,
|
||||
) -> (usize, usize) {
|
||||
let len = value.len();
|
||||
|
||||
(start.min(end).min(len), start.max(end).min(len))
|
||||
}
|
||||
|
||||
type InputStyleFn<'a, Theme> =
|
||||
Rc<dyn Fn(&Theme, text_input::Status) -> text_input::Style + 'a>;
|
||||
|
||||
pub fn context_input<'a, Message, Theme, Renderer>(
|
||||
placeholder: &str,
|
||||
value: &str,
|
||||
) -> ContextInput<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: Clone + 'a,
|
||||
Theme: text_input::Catalog + 'a,
|
||||
Renderer: text::Renderer,
|
||||
{
|
||||
ContextInput::new(placeholder, value)
|
||||
}
|
||||
|
||||
pub fn locked_value<'a, Message, Theme, Renderer>(
|
||||
value: &str,
|
||||
noop: Message,
|
||||
) -> ContextInput<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: Clone + 'a,
|
||||
Theme: text_input::Catalog + 'a,
|
||||
Renderer: text::Renderer,
|
||||
{
|
||||
ContextInput::new("", value)
|
||||
.on_input(move |_| noop.clone())
|
||||
.locked(true)
|
||||
}
|
||||
|
||||
pub struct ContextInput<
|
||||
'a,
|
||||
Message,
|
||||
Theme = iced::Theme,
|
||||
Renderer = iced::Renderer,
|
||||
> where
|
||||
Theme: text_input::Catalog,
|
||||
Renderer: text::Renderer,
|
||||
{
|
||||
input: text_input::TextInput<'a, Message, Theme, Renderer>,
|
||||
value: String,
|
||||
is_secure: bool,
|
||||
locked: bool,
|
||||
on_input: Option<Rc<dyn Fn(String) -> Message + 'a>>,
|
||||
on_paste: Option<Rc<dyn Fn(String) -> Message + 'a>>,
|
||||
style: Option<InputStyleFn<'a, Theme>>,
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer>
|
||||
ContextInput<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: Clone + 'a,
|
||||
Theme: text_input::Catalog + 'a,
|
||||
Renderer: text::Renderer,
|
||||
{
|
||||
pub fn new(placeholder: &str, value: &str) -> Self {
|
||||
Self {
|
||||
input: text_input::TextInput::new(placeholder, value),
|
||||
value: value.to_owned(),
|
||||
is_secure: false,
|
||||
locked: false,
|
||||
on_input: None,
|
||||
on_paste: None,
|
||||
style: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn id(mut self, id: impl Into<widget::Id>) -> Self {
|
||||
self.input = self.input.id(id);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn secure(mut self, is_secure: bool) -> Self {
|
||||
self.is_secure = is_secure;
|
||||
self.input = self.input.secure(is_secure);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn locked(mut self, yes: bool) -> Self {
|
||||
self.locked = yes;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_input(
|
||||
mut self,
|
||||
on_input: impl Fn(String) -> Message + 'a,
|
||||
) -> Self {
|
||||
let on_input: Rc<dyn Fn(String) -> Message + 'a> =
|
||||
Rc::new(on_input);
|
||||
let input_callback = Rc::clone(&on_input);
|
||||
|
||||
self.input =
|
||||
self.input.on_input(move |value| input_callback.as_ref()(value));
|
||||
self.on_input = Some(on_input);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_submit(mut self, message: Message) -> Self {
|
||||
self.input = self.input.on_submit(message);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_submit_maybe(mut self, message: Option<Message>) -> Self {
|
||||
self.input = self.input.on_submit_maybe(message);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_paste(
|
||||
mut self,
|
||||
on_paste: impl Fn(String) -> Message + 'a,
|
||||
) -> Self {
|
||||
let on_paste: Rc<dyn Fn(String) -> Message + 'a> =
|
||||
Rc::new(on_paste);
|
||||
let paste_callback = Rc::clone(&on_paste);
|
||||
|
||||
self.input =
|
||||
self.input.on_paste(move |value| paste_callback.as_ref()(value));
|
||||
self.on_paste = Some(on_paste);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn font(mut self, font: Renderer::Font) -> Self {
|
||||
self.input = self.input.font(font);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn icon(mut self, icon: text_input::Icon<Renderer::Font>) -> Self {
|
||||
self.input = self.input.icon(icon);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.input = self.input.width(width);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
|
||||
self.input = self.input.padding(padding);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn size(mut self, size: impl Into<Pixels>) -> Self {
|
||||
self.input = self.input.size(size);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn line_height(
|
||||
mut self,
|
||||
line_height: impl Into<text::LineHeight>,
|
||||
) -> Self {
|
||||
self.input = self.input.line_height(line_height);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn align_x(
|
||||
mut self,
|
||||
alignment: impl Into<alignment::Horizontal>,
|
||||
) -> Self {
|
||||
self.input = self.input.align_x(alignment);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn style(
|
||||
mut self,
|
||||
style: impl Fn(&Theme, text_input::Status) -> text_input::Style + 'a,
|
||||
) -> Self
|
||||
where
|
||||
Theme::Class<'a>: From<text_input::StyleFn<'a, Theme>>,
|
||||
{
|
||||
let style: InputStyleFn<'a, Theme> = Rc::new(style);
|
||||
let input_style = Rc::clone(&style);
|
||||
|
||||
self.input = self
|
||||
.input
|
||||
.style(move |theme, status| input_style.as_ref()(theme, status));
|
||||
self.style = Some(style);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
|
||||
self.input = self.input.class(class);
|
||||
self.style = None;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ContextInputState {
|
||||
menu: Option<MenuState>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct MenuState {
|
||||
anchor: Point,
|
||||
selection: (usize, usize),
|
||||
}
|
||||
|
||||
impl<Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for ContextInput<'_, Message, Theme, Renderer>
|
||||
where
|
||||
Message: Clone,
|
||||
Theme: text_input::Catalog,
|
||||
Renderer: text::Renderer,
|
||||
{
|
||||
fn tag(&self) -> tree::Tag {
|
||||
tree::Tag::of::<ContextInputState>()
|
||||
}
|
||||
|
||||
fn state(&self) -> tree::State {
|
||||
tree::State::new(ContextInputState::default())
|
||||
}
|
||||
|
||||
fn children(&self) -> Vec<Tree> {
|
||||
vec![Tree::new(&self.input as &dyn Widget<_, _, _>)]
|
||||
}
|
||||
|
||||
fn diff(&self, tree: &mut Tree) {
|
||||
if tree.children.is_empty() {
|
||||
tree.children
|
||||
.push(Tree::new(&self.input as &dyn Widget<_, _, _>));
|
||||
} else {
|
||||
tree.children[0].diff(&self.input as &dyn Widget<_, _, _>);
|
||||
tree.children.truncate(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
Widget::size(&self.input)
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> Size<Length> {
|
||||
Widget::size_hint(&self.input)
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
renderer: &Renderer,
|
||||
limits: &layout::Limits,
|
||||
) -> layout::Node {
|
||||
Widget::layout(&mut self.input, &mut tree.children[0], renderer, limits)
|
||||
}
|
||||
|
||||
fn operate(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
layout: Layout<'_>,
|
||||
renderer: &Renderer,
|
||||
operation: &mut dyn widget::Operation,
|
||||
) {
|
||||
Widget::operate(
|
||||
&mut self.input,
|
||||
&mut tree.children[0],
|
||||
layout,
|
||||
renderer,
|
||||
operation,
|
||||
);
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
let right_click_on_input = matches!(
|
||||
event,
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Right))
|
||||
) && cursor.is_over(layout.bounds());
|
||||
|
||||
if right_click_on_input {
|
||||
let value = text_input::Value::new(&self.value);
|
||||
let input_state = tree.children[0]
|
||||
.state
|
||||
.downcast_ref::<text_input::State<Renderer::Paragraph>>();
|
||||
let selection = match input_state.cursor().state(&value) {
|
||||
text_input::cursor::State::Index(index) => {
|
||||
let index = index.min(value.len());
|
||||
(index, index)
|
||||
}
|
||||
text_input::cursor::State::Selection { start, end } => {
|
||||
normalized_range(&value, start, end)
|
||||
}
|
||||
};
|
||||
|
||||
tree.state.downcast_mut::<ContextInputState>().menu =
|
||||
cursor.position().map(|anchor| MenuState {
|
||||
anchor,
|
||||
selection,
|
||||
});
|
||||
|
||||
shell.capture_event();
|
||||
shell.request_redraw();
|
||||
return;
|
||||
}
|
||||
|
||||
Widget::update(
|
||||
&mut self.input,
|
||||
&mut tree.children[0],
|
||||
event,
|
||||
layout,
|
||||
cursor,
|
||||
renderer,
|
||||
clipboard,
|
||||
shell,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
Widget::draw(
|
||||
&self.input,
|
||||
&tree.children[0],
|
||||
renderer,
|
||||
theme,
|
||||
style,
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
Widget::mouse_interaction(
|
||||
&self.input,
|
||||
&tree.children[0],
|
||||
layout,
|
||||
cursor,
|
||||
viewport,
|
||||
renderer,
|
||||
)
|
||||
}
|
||||
|
||||
fn overlay<'a>(
|
||||
&'a mut self,
|
||||
tree: &'a mut Tree,
|
||||
_layout: Layout<'a>,
|
||||
_renderer: &Renderer,
|
||||
_viewport: &Rectangle,
|
||||
_translation: Vector,
|
||||
) -> Option<overlay::Element<'a, Message, Theme, Renderer>> {
|
||||
let Tree {
|
||||
state, children, ..
|
||||
} = tree;
|
||||
let menu = &mut state.downcast_mut::<ContextInputState>().menu;
|
||||
|
||||
if menu.is_none() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let input_state = children[0]
|
||||
.state
|
||||
.downcast_mut::<text_input::State<Renderer::Paragraph>>();
|
||||
|
||||
Some(overlay::Element::new(Box::new(ContextMenuOverlay {
|
||||
menu,
|
||||
input_state,
|
||||
value: &self.value,
|
||||
is_secure: self.is_secure,
|
||||
locked: self.locked,
|
||||
on_input: self.on_input.clone(),
|
||||
on_paste: self.on_paste.clone(),
|
||||
style: self.style.clone(),
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Message, Theme, Renderer>
|
||||
From<ContextInput<'a, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: Clone + 'a,
|
||||
Theme: text_input::Catalog + 'a,
|
||||
Renderer: text::Renderer + 'a,
|
||||
{
|
||||
fn from(
|
||||
input: ContextInput<'a, Message, Theme, Renderer>,
|
||||
) -> Element<'a, Message, Theme, Renderer> {
|
||||
Element::new(input)
|
||||
}
|
||||
}
|
||||
|
||||
struct ContextMenuOverlay<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: text_input::Catalog,
|
||||
Renderer: text::Renderer,
|
||||
{
|
||||
menu: &'a mut Option<MenuState>,
|
||||
input_state: &'a mut text_input::State<Renderer::Paragraph>,
|
||||
value: &'a str,
|
||||
is_secure: bool,
|
||||
locked: bool,
|
||||
on_input: Option<Rc<dyn Fn(String) -> Message + 'a>>,
|
||||
on_paste: Option<Rc<dyn Fn(String) -> Message + 'a>>,
|
||||
style: Option<InputStyleFn<'a, Theme>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum MenuAction {
|
||||
Cut,
|
||||
Copy,
|
||||
Paste,
|
||||
SelectAll,
|
||||
}
|
||||
|
||||
impl MenuAction {
|
||||
const ALL: [Self; 4] = [
|
||||
Self::Cut,
|
||||
Self::Copy,
|
||||
Self::Paste,
|
||||
Self::SelectAll,
|
||||
];
|
||||
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Cut => "Cut",
|
||||
Self::Copy => "Copy",
|
||||
Self::Paste => "Paste",
|
||||
Self::SelectAll => "Select All",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const MENU_WIDTH: f32 = 136.0;
|
||||
const ITEM_HEIGHT: f32 = 28.0;
|
||||
const TEXT_SIZE: f32 = 13.0;
|
||||
const MENU_PADDING_X: f32 = 10.0;
|
||||
|
||||
impl<Message, Theme, Renderer> overlay::Overlay<Message, Theme, Renderer>
|
||||
for ContextMenuOverlay<'_, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: text_input::Catalog,
|
||||
Renderer: text::Renderer,
|
||||
{
|
||||
fn layout(&mut self, _renderer: &Renderer, bounds: Size) -> layout::Node {
|
||||
let size = Size::new(MENU_WIDTH, ITEM_HEIGHT * MenuAction::ALL.len() as f32);
|
||||
let Some(menu) = self.menu.as_ref() else {
|
||||
return layout::Node::new(Size::ZERO);
|
||||
};
|
||||
let x = menu.anchor.x.min((bounds.width - size.width).max(0.0));
|
||||
let y = menu.anchor.y.min((bounds.height - size.height).max(0.0));
|
||||
|
||||
layout::Node::new(size).move_to(Point::new(x.max(0.0), y.max(0.0)))
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
_style: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
) {
|
||||
let active_style = input_style(theme, self.style.as_ref(), text_input::Status::Active);
|
||||
let hovered_style =
|
||||
input_style(theme, self.style.as_ref(), text_input::Status::Hovered);
|
||||
let bounds = layout.bounds();
|
||||
let viewport = Rectangle::INFINITE;
|
||||
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds,
|
||||
border: Border {
|
||||
radius: 5.0.into(),
|
||||
width: 1.0,
|
||||
color: active_style.border.color,
|
||||
},
|
||||
shadow: Shadow {
|
||||
color: Color::from_rgba(0.0, 0.0, 0.0, 0.22),
|
||||
offset: Vector::new(0.0, 4.0),
|
||||
blur_radius: 10.0,
|
||||
},
|
||||
..renderer::Quad::default()
|
||||
},
|
||||
active_style.background,
|
||||
);
|
||||
|
||||
for (index, action) in MenuAction::ALL.iter().copied().enumerate() {
|
||||
let item_bounds = item_bounds(bounds, index);
|
||||
let enabled = self.enabled(action);
|
||||
let hovered = enabled && cursor.is_over(item_bounds);
|
||||
|
||||
if hovered {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: item_bounds,
|
||||
border: Border {
|
||||
radius: 3.0.into(),
|
||||
..Border::default()
|
||||
},
|
||||
..renderer::Quad::default()
|
||||
},
|
||||
Background::Color(hovered_style.selection),
|
||||
);
|
||||
}
|
||||
|
||||
renderer.fill_text(
|
||||
text::Text {
|
||||
content: action.label().to_owned(),
|
||||
bounds: Size::new(item_bounds.width - MENU_PADDING_X * 2.0, item_bounds.height),
|
||||
size: Pixels(TEXT_SIZE),
|
||||
line_height: text::LineHeight::default(),
|
||||
font: renderer.default_font(),
|
||||
align_x: text::Alignment::Default,
|
||||
align_y: alignment::Vertical::Center,
|
||||
shaping: text::Shaping::Advanced,
|
||||
wrapping: text::Wrapping::default(),
|
||||
},
|
||||
Point::new(item_bounds.x + MENU_PADDING_X, item_bounds.center_y()),
|
||||
if enabled {
|
||||
active_style.value
|
||||
} else {
|
||||
disabled_color(active_style.value)
|
||||
},
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
_renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
) {
|
||||
match event {
|
||||
Event::Keyboard(iced::keyboard::Event::KeyPressed {
|
||||
key: iced::keyboard::Key::Named(
|
||||
iced::keyboard::key::Named::Escape,
|
||||
),
|
||||
..
|
||||
}) => {
|
||||
self.close(shell);
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
|
||||
let Some(position) = cursor.position() else {
|
||||
self.close(shell);
|
||||
return;
|
||||
};
|
||||
let bounds = layout.bounds();
|
||||
|
||||
if !bounds.contains(position) {
|
||||
self.close(shell);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(action) = self.hit_action(bounds, position) {
|
||||
if self.enabled(action) {
|
||||
self.perform(action, clipboard, shell);
|
||||
}
|
||||
self.close(shell);
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonPressed(_)) => {
|
||||
let should_close = cursor
|
||||
.position()
|
||||
.is_none_or(|position| !layout.bounds().contains(position));
|
||||
|
||||
if should_close {
|
||||
self.close(shell);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
_renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
let Some(position) = cursor.position() else {
|
||||
return mouse::Interaction::default();
|
||||
};
|
||||
|
||||
if self.hit_action(layout.bounds(), position).is_some() {
|
||||
mouse::Interaction::Pointer
|
||||
} else {
|
||||
mouse::Interaction::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Message, Theme, Renderer> ContextMenuOverlay<'_, Message, Theme, Renderer>
|
||||
where
|
||||
Theme: text_input::Catalog,
|
||||
Renderer: text::Renderer,
|
||||
{
|
||||
fn enabled(&self, action: MenuAction) -> bool {
|
||||
let Some(menu) = self.menu.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
let has_selection = menu.selection.0 != menu.selection.1;
|
||||
let has_value = !text_input::Value::new(self.value).is_empty();
|
||||
|
||||
menu_action_enabled(
|
||||
action,
|
||||
has_selection,
|
||||
has_value,
|
||||
self.is_secure,
|
||||
self.locked,
|
||||
)
|
||||
}
|
||||
|
||||
fn hit_action(
|
||||
&self,
|
||||
bounds: Rectangle,
|
||||
position: Point,
|
||||
) -> Option<MenuAction> {
|
||||
if !bounds.contains(position) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let index = ((position.y - bounds.y) / ITEM_HEIGHT).floor() as usize;
|
||||
|
||||
MenuAction::ALL.get(index).copied()
|
||||
}
|
||||
|
||||
fn perform(
|
||||
&mut self,
|
||||
action: MenuAction,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
) {
|
||||
let Some(menu) = self.menu.as_ref().copied() else {
|
||||
return;
|
||||
};
|
||||
let (start, end) = menu.selection;
|
||||
|
||||
match action {
|
||||
MenuAction::Cut => {
|
||||
let (edit, selected) = cut_selection(self.value, start, end);
|
||||
|
||||
if let Some(selected) = selected {
|
||||
clipboard.write(clipboard::Kind::Standard, selected);
|
||||
self.publish_edit(edit, shell);
|
||||
}
|
||||
}
|
||||
MenuAction::Copy => {
|
||||
if let Some(selected) = copy_selection(self.value, start, end) {
|
||||
clipboard.write(clipboard::Kind::Standard, selected);
|
||||
}
|
||||
}
|
||||
MenuAction::Paste => {
|
||||
let clip = clipboard
|
||||
.read(clipboard::Kind::Standard)
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.filter(|c| !c.is_control())
|
||||
.collect::<String>();
|
||||
let edit = paste(self.value, start, end, &clip);
|
||||
|
||||
self.publish_paste(edit, shell);
|
||||
}
|
||||
MenuAction::SelectAll => {
|
||||
let (start, end) = select_all_range(self.value);
|
||||
|
||||
self.input_state.select_range(start, end);
|
||||
shell.request_redraw();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_edit(&mut self, edit: Edit, shell: &mut Shell<'_, Message>) {
|
||||
if let Some(on_input) = &self.on_input {
|
||||
self.input_state.move_cursor_to(edit.cursor);
|
||||
shell.publish(on_input.as_ref()(edit.value));
|
||||
shell.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
fn publish_paste(&mut self, edit: Edit, shell: &mut Shell<'_, Message>) {
|
||||
self.input_state.move_cursor_to(edit.cursor);
|
||||
|
||||
if let Some(on_paste) = &self.on_paste {
|
||||
shell.publish(on_paste.as_ref()(edit.value));
|
||||
} else if let Some(on_input) = &self.on_input {
|
||||
shell.publish(on_input.as_ref()(edit.value));
|
||||
}
|
||||
|
||||
shell.request_redraw();
|
||||
}
|
||||
|
||||
fn close(&mut self, shell: &mut Shell<'_, Message>) {
|
||||
*self.menu = None;
|
||||
shell.capture_event();
|
||||
shell.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
fn item_bounds(menu_bounds: Rectangle, index: usize) -> Rectangle {
|
||||
Rectangle {
|
||||
x: menu_bounds.x + 3.0,
|
||||
y: menu_bounds.y + 3.0 + ITEM_HEIGHT * index as f32,
|
||||
width: menu_bounds.width - 6.0,
|
||||
height: ITEM_HEIGHT,
|
||||
}
|
||||
}
|
||||
|
||||
fn input_style<Theme: text_input::Catalog>(
|
||||
theme: &Theme,
|
||||
style: Option<&InputStyleFn<'_, Theme>>,
|
||||
status: text_input::Status,
|
||||
) -> text_input::Style {
|
||||
if let Some(style) = style {
|
||||
style.as_ref()(theme, status)
|
||||
} else {
|
||||
let class = <Theme as text_input::Catalog>::default();
|
||||
|
||||
theme.style(&class, status)
|
||||
}
|
||||
}
|
||||
|
||||
fn disabled_color(color: Color) -> Color {
|
||||
Color {
|
||||
a: color.a * 0.45,
|
||||
..color
|
||||
}
|
||||
}
|
||||
|
||||
fn menu_action_enabled(
|
||||
action: MenuAction,
|
||||
has_selection: bool,
|
||||
has_value: bool,
|
||||
is_secure: bool,
|
||||
locked: bool,
|
||||
) -> bool {
|
||||
match action {
|
||||
MenuAction::Cut => has_selection && !is_secure && !locked,
|
||||
MenuAction::Copy => has_selection && !is_secure,
|
||||
MenuAction::Paste => !locked,
|
||||
MenuAction::SelectAll => has_value,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn copy_selection_returns_middle_substring_and_empty_none() {
|
||||
assert_eq!(copy_selection("abcdef", 2, 5), Some("cde".to_owned()));
|
||||
assert_eq!(copy_selection("abcdef", 3, 3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cut_selection_removes_range_and_copies_selection() {
|
||||
let (edit, clip) = cut_selection("abcdef", 2, 5);
|
||||
|
||||
assert_eq!(
|
||||
edit,
|
||||
Edit {
|
||||
value: "abf".to_owned(),
|
||||
cursor: 2,
|
||||
}
|
||||
);
|
||||
assert_eq!(clip, Some("cde".to_owned()));
|
||||
|
||||
let (edit, clip) = cut_selection("abcdef", 3, 3);
|
||||
assert_eq!(
|
||||
edit,
|
||||
Edit {
|
||||
value: "abcdef".to_owned(),
|
||||
cursor: 3,
|
||||
}
|
||||
);
|
||||
assert_eq!(clip, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paste_replaces_selection_or_inserts_at_cursor() {
|
||||
assert_eq!(
|
||||
paste("abcdef", 2, 5, "XY"),
|
||||
Edit {
|
||||
value: "abXYf".to_owned(),
|
||||
cursor: 4,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
paste("abcdef", 3, 3, "XY"),
|
||||
Edit {
|
||||
value: "abcXYdef".to_owned(),
|
||||
cursor: 5,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_all_range_uses_grapheme_length() {
|
||||
assert_eq!(select_all_range(""), (0, 0));
|
||||
assert_eq!(select_all_range("abé🦀"), (0, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_selection_boundaries_are_grapheme_correct() {
|
||||
assert_eq!(copy_selection("aé🦀z", 1, 3), Some("é🦀".to_owned()));
|
||||
|
||||
let (edit, clip) = cut_selection("aé🦀z", 2, 3);
|
||||
assert_eq!(clip, Some("🦀".to_owned()));
|
||||
assert_eq!(
|
||||
edit,
|
||||
Edit {
|
||||
value: "aéz".to_owned(),
|
||||
cursor: 2,
|
||||
}
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
paste("aéz", 2, 2, "🦀"),
|
||||
Edit {
|
||||
value: "aé🦀z".to_owned(),
|
||||
cursor: 3,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_menu_allows_copy_and_select_all_only() {
|
||||
assert!(!menu_action_enabled(MenuAction::Cut, true, true, false, true));
|
||||
assert!(menu_action_enabled(MenuAction::Copy, true, true, false, true));
|
||||
assert!(!menu_action_enabled(MenuAction::Paste, true, true, false, true));
|
||||
assert!(menu_action_enabled(MenuAction::SelectAll, true, true, false, true));
|
||||
|
||||
assert!(!menu_action_enabled(MenuAction::Copy, false, true, false, true));
|
||||
assert!(!menu_action_enabled(MenuAction::SelectAll, false, false, false, true));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod context_input;
|
||||
pub mod selectable_text;
|
||||
@@ -0,0 +1,890 @@
|
||||
use iced::advanced::clipboard::{self, Clipboard};
|
||||
use iced::advanced::layout;
|
||||
use iced::advanced::mouse;
|
||||
use iced::advanced::renderer;
|
||||
use iced::advanced::text::{self as advanced_text, Paragraph, Span};
|
||||
use iced::advanced::widget::tree::{self, Tree};
|
||||
use iced::advanced::widget::Widget;
|
||||
use iced::advanced::{Layout, Shell};
|
||||
use iced::widget::text::{
|
||||
self as widget_text, Alignment, Catalog, LineHeight, Shaping, Style, StyleFn,
|
||||
Wrapping,
|
||||
};
|
||||
use iced::{
|
||||
alignment, Background, Border, Color, Element, Event, Length, Pixels, Point,
|
||||
Rectangle, Size, Vector, keyboard,
|
||||
};
|
||||
|
||||
const DRAG_THRESHOLD: f32 = 3.0;
|
||||
const HIT_SEARCH_STEPS: usize = 24;
|
||||
|
||||
// Offsets here are paragraph-global BYTE offsets. `Paragraph::hit_test` returns
|
||||
// `Hit::CharOffset(cursor.index)`, and cosmic-text's `cursor.index` is a byte
|
||||
// offset WITHIN its buffer line — it discards the line number. That equals the
|
||||
// global byte offset only when the text is a single logical line. Chat bodies
|
||||
// satisfy this because `app::sanitize_chat` turns every control char (incl. `\n`
|
||||
// and `\r`) into a space and collapses whitespace, so a stored message can never
|
||||
// contain a newline. If that sanitizer ever starts preserving newlines, this
|
||||
// widget's per-line offsets would stop being global and selection/copy across
|
||||
// lines would break — revisit then.
|
||||
|
||||
pub fn selected_substring(
|
||||
text: &str,
|
||||
anchor: usize,
|
||||
cursor: usize,
|
||||
) -> Option<String> {
|
||||
let (start, end) = normalized_byte_range(text, anchor, cursor);
|
||||
|
||||
(start != end).then(|| text[start..end].to_owned())
|
||||
}
|
||||
|
||||
pub fn select_all(text: &str) -> (usize, usize) {
|
||||
(0, text.len())
|
||||
}
|
||||
|
||||
fn normalized_byte_range(
|
||||
text: &str,
|
||||
anchor: usize,
|
||||
cursor: usize,
|
||||
) -> (usize, usize) {
|
||||
let start = clamp_to_char_boundary(text, anchor.min(cursor));
|
||||
let end = clamp_to_char_boundary(text, anchor.max(cursor));
|
||||
|
||||
(start.min(end), start.max(end))
|
||||
}
|
||||
|
||||
fn clamp_to_char_boundary(text: &str, offset: usize) -> usize {
|
||||
let mut offset = offset.min(text.len());
|
||||
|
||||
while offset > 0 && !text.is_char_boundary(offset) {
|
||||
offset -= 1;
|
||||
}
|
||||
|
||||
offset
|
||||
}
|
||||
|
||||
pub fn selectable_rich_text<'a, Link, Message, Theme, Renderer>(
|
||||
spans: impl AsRef<[Span<'a, Link, Renderer::Font>]> + 'a,
|
||||
) -> SelectableRichText<'a, Link, Message, Theme, Renderer>
|
||||
where
|
||||
Link: Clone + 'static,
|
||||
Theme: Catalog + 'a,
|
||||
Renderer: advanced_text::Renderer,
|
||||
Renderer::Font: 'a,
|
||||
{
|
||||
SelectableRichText::with_spans(spans)
|
||||
}
|
||||
|
||||
pub struct SelectableRichText<
|
||||
'a,
|
||||
Link,
|
||||
Message,
|
||||
Theme = iced::Theme,
|
||||
Renderer = iced::Renderer,
|
||||
> where
|
||||
Link: Clone + 'static,
|
||||
Theme: Catalog,
|
||||
Renderer: advanced_text::Renderer,
|
||||
{
|
||||
spans: Box<dyn AsRef<[Span<'a, Link, Renderer::Font>]> + 'a>,
|
||||
size: Option<Pixels>,
|
||||
line_height: LineHeight,
|
||||
width: Length,
|
||||
height: Length,
|
||||
font: Option<Renderer::Font>,
|
||||
align_x: Alignment,
|
||||
align_y: alignment::Vertical,
|
||||
wrapping: Wrapping,
|
||||
class: Theme::Class<'a>,
|
||||
hovered_link: Option<usize>,
|
||||
on_link_click: Option<Box<dyn Fn(Link) -> Message + 'a>>,
|
||||
selection_color: Color,
|
||||
}
|
||||
|
||||
impl<'a, Link, Message, Theme, Renderer>
|
||||
SelectableRichText<'a, Link, Message, Theme, Renderer>
|
||||
where
|
||||
Link: Clone + 'static,
|
||||
Theme: Catalog,
|
||||
Renderer: advanced_text::Renderer,
|
||||
Renderer::Font: 'a,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
spans: Box::new([]),
|
||||
size: None,
|
||||
line_height: LineHeight::default(),
|
||||
width: Length::Shrink,
|
||||
height: Length::Shrink,
|
||||
font: None,
|
||||
align_x: Alignment::Default,
|
||||
align_y: alignment::Vertical::Top,
|
||||
wrapping: Wrapping::default(),
|
||||
class: Theme::default(),
|
||||
hovered_link: None,
|
||||
on_link_click: None,
|
||||
selection_color: Color::from_rgba(0.35, 0.55, 0.95, 0.35),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_spans(
|
||||
spans: impl AsRef<[Span<'a, Link, Renderer::Font>]> + 'a,
|
||||
) -> Self {
|
||||
Self {
|
||||
spans: Box::new(spans),
|
||||
..Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn size(mut self, size: impl Into<Pixels>) -> Self {
|
||||
self.size = Some(size.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn line_height(mut self, line_height: impl Into<LineHeight>) -> Self {
|
||||
self.line_height = line_height.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn font(mut self, font: impl Into<Renderer::Font>) -> Self {
|
||||
self.font = Some(font.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn width(mut self, width: impl Into<Length>) -> Self {
|
||||
self.width = width.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn height(mut self, height: impl Into<Length>) -> Self {
|
||||
self.height = height.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn align_x(mut self, alignment: impl Into<Alignment>) -> Self {
|
||||
self.align_x = alignment.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn align_y(
|
||||
mut self,
|
||||
alignment: impl Into<alignment::Vertical>,
|
||||
) -> Self {
|
||||
self.align_y = alignment.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn wrapping(mut self, wrapping: Wrapping) -> Self {
|
||||
self.wrapping = wrapping;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn on_link_click(
|
||||
mut self,
|
||||
on_link_click: impl Fn(Link) -> Message + 'a,
|
||||
) -> Self {
|
||||
self.on_link_click = Some(Box::new(on_link_click));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn selection_color(mut self, color: Color) -> Self {
|
||||
self.selection_color = Color {
|
||||
a: color.a.min(0.35),
|
||||
..color
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn style(mut self, style: impl Fn(&Theme) -> Style + 'a) -> Self
|
||||
where
|
||||
Theme::Class<'a>: From<StyleFn<'a, Theme>>,
|
||||
{
|
||||
self.class = (Box::new(style) as StyleFn<'a, Theme>).into();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn color(self, color: impl Into<Color>) -> Self
|
||||
where
|
||||
Theme::Class<'a>: From<StyleFn<'a, Theme>>,
|
||||
{
|
||||
self.color_maybe(Some(color))
|
||||
}
|
||||
|
||||
pub fn color_maybe(self, color: Option<impl Into<Color>>) -> Self
|
||||
where
|
||||
Theme::Class<'a>: From<StyleFn<'a, Theme>>,
|
||||
{
|
||||
let color = color.map(Into::into);
|
||||
|
||||
self.style(move |_theme| Style { color })
|
||||
}
|
||||
|
||||
pub fn class(mut self, class: impl Into<Theme::Class<'a>>) -> Self {
|
||||
self.class = class.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, Link, Message, Theme, Renderer> Default
|
||||
for SelectableRichText<'a, Link, Message, Theme, Renderer>
|
||||
where
|
||||
Link: Clone + 'static,
|
||||
Theme: Catalog,
|
||||
Renderer: advanced_text::Renderer,
|
||||
Renderer::Font: 'a,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
struct SelectableTextState<Link, P: Paragraph> {
|
||||
spans: Vec<Span<'static, Link, P::Font>>,
|
||||
span_pressed: Option<usize>,
|
||||
paragraph: P,
|
||||
selection: Option<(usize, usize)>,
|
||||
dragging: bool,
|
||||
active: bool,
|
||||
press_position: Option<Point>,
|
||||
}
|
||||
|
||||
impl<Link, P: Paragraph> SelectableTextState<Link, P> {
|
||||
fn selection_range(&self, text: &str) -> Option<(usize, usize)> {
|
||||
let (anchor, cursor) = self.selection?;
|
||||
let (start, end) = normalized_byte_range(text, anchor, cursor);
|
||||
|
||||
(start != end).then_some((start, end))
|
||||
}
|
||||
}
|
||||
|
||||
impl<Link, Message, Theme, Renderer> Widget<Message, Theme, Renderer>
|
||||
for SelectableRichText<'_, Link, Message, Theme, Renderer>
|
||||
where
|
||||
Link: Clone + 'static,
|
||||
Theme: Catalog,
|
||||
Renderer: advanced_text::Renderer,
|
||||
{
|
||||
fn tag(&self) -> tree::Tag {
|
||||
tree::Tag::of::<SelectableTextState<Link, Renderer::Paragraph>>()
|
||||
}
|
||||
|
||||
fn state(&self) -> tree::State {
|
||||
tree::State::new(SelectableTextState::<Link, _> {
|
||||
spans: Vec::new(),
|
||||
span_pressed: None,
|
||||
paragraph: Renderer::Paragraph::default(),
|
||||
selection: None,
|
||||
dragging: false,
|
||||
active: false,
|
||||
press_position: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn size(&self) -> Size<Length> {
|
||||
Size {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
}
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
renderer: &Renderer,
|
||||
limits: &layout::Limits,
|
||||
) -> layout::Node {
|
||||
layout_text(
|
||||
tree.state
|
||||
.downcast_mut::<SelectableTextState<Link, Renderer::Paragraph>>(),
|
||||
renderer,
|
||||
limits,
|
||||
TextLayout {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
spans: self.spans.as_ref().as_ref(),
|
||||
line_height: self.line_height,
|
||||
size: self.size,
|
||||
font: self.font,
|
||||
align_x: self.align_x,
|
||||
align_y: self.align_y,
|
||||
wrapping: self.wrapping,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn draw(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
renderer: &mut Renderer,
|
||||
theme: &Theme,
|
||||
defaults: &renderer::Style,
|
||||
layout: Layout<'_>,
|
||||
_cursor: mouse::Cursor,
|
||||
viewport: &Rectangle,
|
||||
) {
|
||||
if !layout.bounds().intersects(viewport) {
|
||||
return;
|
||||
}
|
||||
|
||||
let state = tree
|
||||
.state
|
||||
.downcast_ref::<SelectableTextState<Link, Renderer::Paragraph>>();
|
||||
let spans = self.spans.as_ref().as_ref();
|
||||
let flat_text = flatten_spans(spans);
|
||||
let style = theme.style(&self.class);
|
||||
let translation = layout.position() - Point::ORIGIN;
|
||||
|
||||
if let Some((start, end)) = state.selection_range(&flat_text) {
|
||||
let mut rects = selection_rects(&state.paragraph, spans.len(), start, end);
|
||||
if rects.is_empty() {
|
||||
rects = visual_lines(&state.paragraph, spans.len());
|
||||
}
|
||||
|
||||
for bounds in rects {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: bounds + translation,
|
||||
border: Border {
|
||||
radius: 2.0.into(),
|
||||
..Border::default()
|
||||
},
|
||||
..renderer::Quad::default()
|
||||
},
|
||||
Background::Color(self.selection_color),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (index, span) in spans.iter().enumerate() {
|
||||
let is_hovered_link = self.on_link_click.is_some()
|
||||
&& Some(index) == self.hovered_link;
|
||||
|
||||
if span.highlight.is_some()
|
||||
|| span.underline
|
||||
|| span.strikethrough
|
||||
|| is_hovered_link
|
||||
{
|
||||
let regions = state.paragraph.span_bounds(index);
|
||||
|
||||
if let Some(highlight) = span.highlight {
|
||||
for bounds in ®ions {
|
||||
let bounds = Rectangle::new(
|
||||
bounds.position()
|
||||
- Vector::new(
|
||||
span.padding.left,
|
||||
span.padding.top,
|
||||
),
|
||||
bounds.size()
|
||||
+ Size::new(span.padding.x(), span.padding.y()),
|
||||
);
|
||||
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: bounds + translation,
|
||||
border: highlight.border,
|
||||
..Default::default()
|
||||
},
|
||||
highlight.background,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if span.underline || span.strikethrough || is_hovered_link {
|
||||
let size = span
|
||||
.size
|
||||
.or(self.size)
|
||||
.unwrap_or(renderer.default_size());
|
||||
|
||||
let line_height = span
|
||||
.line_height
|
||||
.unwrap_or(self.line_height)
|
||||
.to_absolute(size);
|
||||
|
||||
let color = span
|
||||
.color
|
||||
.or(style.color)
|
||||
.unwrap_or(defaults.text_color);
|
||||
|
||||
let baseline = translation
|
||||
+ Vector::new(
|
||||
0.0,
|
||||
size.0 + (line_height.0 - size.0) / 2.0,
|
||||
);
|
||||
|
||||
if span.underline || is_hovered_link {
|
||||
for bounds in ®ions {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: Rectangle::new(
|
||||
bounds.position() + baseline
|
||||
- Vector::new(0.0, size.0 * 0.08),
|
||||
Size::new(bounds.width, 1.0),
|
||||
),
|
||||
..Default::default()
|
||||
},
|
||||
color,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if span.strikethrough {
|
||||
for bounds in ®ions {
|
||||
renderer.fill_quad(
|
||||
renderer::Quad {
|
||||
bounds: Rectangle::new(
|
||||
bounds.position() + baseline
|
||||
- Vector::new(0.0, size.0 / 2.0),
|
||||
Size::new(bounds.width, 1.0),
|
||||
),
|
||||
..Default::default()
|
||||
},
|
||||
color,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
widget_text::draw(
|
||||
renderer,
|
||||
defaults,
|
||||
layout.bounds(),
|
||||
&state.paragraph,
|
||||
style,
|
||||
viewport,
|
||||
);
|
||||
}
|
||||
|
||||
fn update(
|
||||
&mut self,
|
||||
tree: &mut Tree,
|
||||
event: &Event,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
_renderer: &Renderer,
|
||||
clipboard: &mut dyn Clipboard,
|
||||
shell: &mut Shell<'_, Message>,
|
||||
_viewport: &Rectangle,
|
||||
) {
|
||||
let bounds = layout.bounds();
|
||||
let local_position = cursor.position_in(bounds);
|
||||
let state = tree
|
||||
.state
|
||||
.downcast_mut::<SelectableTextState<Link, Renderer::Paragraph>>();
|
||||
let spans = self.spans.as_ref().as_ref();
|
||||
let flat_text = flatten_spans(spans);
|
||||
|
||||
let was_hovered = self.hovered_link.is_some();
|
||||
self.hovered_link = local_position.and_then(|position| {
|
||||
state.paragraph.hit_span(position).and_then(|span| {
|
||||
if spans.get(span)?.link.is_some() {
|
||||
Some(span)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
if was_hovered != self.hovered_link.is_some() {
|
||||
shell.request_redraw();
|
||||
}
|
||||
|
||||
match event {
|
||||
Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
|
||||
if let Some(position) = local_position {
|
||||
state.active = true;
|
||||
state.dragging = true;
|
||||
state.press_position = Some(position);
|
||||
state.span_pressed = self.hovered_link;
|
||||
state.selection = state
|
||||
.paragraph
|
||||
.hit_test(position)
|
||||
.map(|hit| {
|
||||
let offset = hit.cursor().min(flat_text.len());
|
||||
(offset, offset)
|
||||
});
|
||||
shell.capture_event();
|
||||
shell.request_redraw();
|
||||
} else if state.active || state.selection.is_some() {
|
||||
state.active = false;
|
||||
state.dragging = false;
|
||||
state.press_position = None;
|
||||
state.span_pressed = None;
|
||||
state.selection = None;
|
||||
shell.request_redraw();
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::CursorMoved { .. }) => {
|
||||
if state.dragging
|
||||
&& let Some(position) = clamped_position(cursor, bounds)
|
||||
&& let Some(hit) = state.paragraph.hit_test(position)
|
||||
&& let Some((anchor, _)) = state.selection
|
||||
{
|
||||
state.selection =
|
||||
Some((anchor, hit.cursor().min(flat_text.len())));
|
||||
shell.request_redraw();
|
||||
}
|
||||
}
|
||||
Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) => {
|
||||
if state.dragging {
|
||||
let release_position = clamped_position(cursor, bounds)
|
||||
.or(local_position)
|
||||
.or(state.press_position);
|
||||
let dragged = state
|
||||
.press_position
|
||||
.zip(release_position)
|
||||
.is_some_and(|(start, end)| point_distance(start, end) > DRAG_THRESHOLD);
|
||||
|
||||
if let Some(position) = release_position
|
||||
&& let Some(hit) = state.paragraph.hit_test(position)
|
||||
&& let Some((anchor, _)) = state.selection
|
||||
{
|
||||
state.selection =
|
||||
Some((anchor, hit.cursor().min(flat_text.len())));
|
||||
}
|
||||
|
||||
if !dragged {
|
||||
if let (Some(on_link_clicked), Some(span)) =
|
||||
(&self.on_link_click, state.span_pressed)
|
||||
&& Some(span) == self.hovered_link
|
||||
&& let Some(link) =
|
||||
spans.get(span).and_then(|span| span.link.clone())
|
||||
{
|
||||
shell.publish(on_link_clicked(link));
|
||||
}
|
||||
state.selection = None;
|
||||
} else if state.selection_range(&flat_text).is_none() {
|
||||
state.selection = None;
|
||||
}
|
||||
|
||||
state.dragging = false;
|
||||
state.span_pressed = None;
|
||||
state.press_position = None;
|
||||
shell.capture_event();
|
||||
shell.request_redraw();
|
||||
}
|
||||
}
|
||||
Event::Keyboard(keyboard::Event::KeyPressed {
|
||||
key,
|
||||
physical_key,
|
||||
modifiers,
|
||||
..
|
||||
}) if state.active && modifiers.command() => {
|
||||
match key.to_latin(*physical_key) {
|
||||
Some('c') | Some('C') => {
|
||||
if let Some((anchor, cursor)) = state.selection
|
||||
&& let Some(selected) =
|
||||
selected_substring(&flat_text, anchor, cursor)
|
||||
{
|
||||
clipboard.write(clipboard::Kind::Standard, selected);
|
||||
shell.capture_event();
|
||||
}
|
||||
}
|
||||
Some('a') | Some('A') => {
|
||||
state.selection = Some(select_all(&flat_text));
|
||||
shell.capture_event();
|
||||
shell.request_redraw();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn mouse_interaction(
|
||||
&self,
|
||||
tree: &Tree,
|
||||
layout: Layout<'_>,
|
||||
cursor: mouse::Cursor,
|
||||
_viewport: &Rectangle,
|
||||
_renderer: &Renderer,
|
||||
) -> mouse::Interaction {
|
||||
let state = tree
|
||||
.state
|
||||
.downcast_ref::<SelectableTextState<Link, Renderer::Paragraph>>();
|
||||
|
||||
if state.dragging {
|
||||
mouse::Interaction::Text
|
||||
} else if self.hovered_link.is_some() {
|
||||
mouse::Interaction::Pointer
|
||||
} else if cursor.is_over(layout.bounds()) {
|
||||
mouse::Interaction::Text
|
||||
} else {
|
||||
mouse::Interaction::None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct TextLayout<'a, 'span, Link, Font> {
|
||||
width: Length,
|
||||
height: Length,
|
||||
spans: &'a [Span<'span, Link, Font>],
|
||||
line_height: LineHeight,
|
||||
size: Option<Pixels>,
|
||||
font: Option<Font>,
|
||||
align_x: Alignment,
|
||||
align_y: alignment::Vertical,
|
||||
wrapping: Wrapping,
|
||||
}
|
||||
|
||||
fn layout_text<Link, Renderer>(
|
||||
state: &mut SelectableTextState<Link, Renderer::Paragraph>,
|
||||
renderer: &Renderer,
|
||||
limits: &layout::Limits,
|
||||
config: TextLayout<'_, '_, Link, Renderer::Font>,
|
||||
) -> layout::Node
|
||||
where
|
||||
Link: Clone,
|
||||
Renderer: advanced_text::Renderer,
|
||||
{
|
||||
layout::sized(limits, config.width, config.height, |limits| {
|
||||
let bounds = limits.max();
|
||||
let size = config.size.unwrap_or_else(|| renderer.default_size());
|
||||
let font = config.font.unwrap_or_else(|| renderer.default_font());
|
||||
|
||||
let text_with_spans = || advanced_text::Text {
|
||||
content: config.spans,
|
||||
bounds,
|
||||
size,
|
||||
line_height: config.line_height,
|
||||
font,
|
||||
align_x: config.align_x,
|
||||
align_y: config.align_y,
|
||||
shaping: Shaping::Advanced,
|
||||
wrapping: config.wrapping,
|
||||
};
|
||||
|
||||
if state.spans != config.spans {
|
||||
state.paragraph =
|
||||
Renderer::Paragraph::with_spans(text_with_spans());
|
||||
state.spans = config
|
||||
.spans
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(Span::to_static)
|
||||
.collect();
|
||||
} else {
|
||||
match state.paragraph.compare(advanced_text::Text {
|
||||
content: (),
|
||||
bounds,
|
||||
size,
|
||||
line_height: config.line_height,
|
||||
font,
|
||||
align_x: config.align_x,
|
||||
align_y: config.align_y,
|
||||
shaping: Shaping::Advanced,
|
||||
wrapping: config.wrapping,
|
||||
}) {
|
||||
advanced_text::Difference::None => {}
|
||||
advanced_text::Difference::Bounds => {
|
||||
state.paragraph.resize(bounds);
|
||||
}
|
||||
advanced_text::Difference::Shape => {
|
||||
state.paragraph =
|
||||
Renderer::Paragraph::with_spans(text_with_spans());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
state.paragraph.min_bounds()
|
||||
})
|
||||
}
|
||||
|
||||
fn flatten_spans<Link, Font>(spans: &[Span<'_, Link, Font>]) -> String {
|
||||
spans
|
||||
.iter()
|
||||
.map(|span| span.text.as_ref())
|
||||
.collect::<String>()
|
||||
}
|
||||
|
||||
fn selection_rects<P: Paragraph>(
|
||||
paragraph: &P,
|
||||
span_count: usize,
|
||||
start: usize,
|
||||
end: usize,
|
||||
) -> Vec<Rectangle> {
|
||||
visual_lines(paragraph, span_count)
|
||||
.into_iter()
|
||||
.filter_map(|line| selection_rect_for_line(paragraph, line, start, end))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn selection_rect_for_line<P: Paragraph>(
|
||||
paragraph: &P,
|
||||
line: Rectangle,
|
||||
start: usize,
|
||||
end: usize,
|
||||
) -> Option<Rectangle> {
|
||||
let y = line.center_y();
|
||||
let paragraph_width = paragraph.bounds().width.max(line.x + line.width + 1.0);
|
||||
let left_probe = line.x.max(0.0);
|
||||
let right_probe = (line.x + line.width + 1.0).min(paragraph_width.max(1.0));
|
||||
let line_start = paragraph
|
||||
.hit_test(Point::new(left_probe, y))
|
||||
.map(advanced_text::Hit::cursor)?;
|
||||
let line_end = paragraph
|
||||
.hit_test(Point::new(right_probe, y))
|
||||
.map(advanced_text::Hit::cursor)
|
||||
.unwrap_or(line_start);
|
||||
let (line_start, line_end) = if line_start <= line_end {
|
||||
(line_start, line_end)
|
||||
} else {
|
||||
(line_end, line_start)
|
||||
};
|
||||
let overlap_start = start.max(line_start);
|
||||
let overlap_end = end.min(line_end);
|
||||
|
||||
if overlap_start >= overlap_end {
|
||||
return None;
|
||||
}
|
||||
|
||||
let x_start = if overlap_start <= line_start {
|
||||
line.x
|
||||
} else {
|
||||
x_for_offset(paragraph, y, overlap_start, line.x, line.x + line.width)
|
||||
};
|
||||
let x_end = if overlap_end >= line_end {
|
||||
line.x + line.width
|
||||
} else {
|
||||
x_for_offset(paragraph, y, overlap_end, line.x, line.x + line.width)
|
||||
};
|
||||
let left = x_start.min(x_end);
|
||||
let right = x_start.max(x_end);
|
||||
|
||||
(right > left).then(|| {
|
||||
Rectangle::new(
|
||||
Point::new(left, line.y),
|
||||
Size::new(right - left, line.height),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn x_for_offset<P: Paragraph>(
|
||||
paragraph: &P,
|
||||
y: f32,
|
||||
offset: usize,
|
||||
left: f32,
|
||||
right: f32,
|
||||
) -> f32 {
|
||||
let mut low = left;
|
||||
let mut high = right.max(left);
|
||||
|
||||
for _ in 0..HIT_SEARCH_STEPS {
|
||||
let mid = (low + high) / 2.0;
|
||||
let hit = paragraph
|
||||
.hit_test(Point::new(mid, y))
|
||||
.map(advanced_text::Hit::cursor);
|
||||
|
||||
match hit {
|
||||
Some(hit) if hit < offset => low = mid,
|
||||
Some(_) => high = mid,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
|
||||
high
|
||||
}
|
||||
|
||||
fn visual_lines<P: Paragraph>(
|
||||
paragraph: &P,
|
||||
span_count: usize,
|
||||
) -> Vec<Rectangle> {
|
||||
let mut lines: Vec<Rectangle> = Vec::new();
|
||||
|
||||
for span in 0..span_count {
|
||||
for bounds in paragraph.span_bounds(span) {
|
||||
if bounds.width <= 0.0 || bounds.height <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(line) = lines
|
||||
.iter_mut()
|
||||
.find(|line| (line.center_y() - bounds.center_y()).abs() < 1.0)
|
||||
{
|
||||
*line = union(*line, bounds);
|
||||
} else {
|
||||
lines.push(bounds);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lines.sort_by(|a, b| a.y.total_cmp(&b.y));
|
||||
lines
|
||||
}
|
||||
|
||||
fn union(a: Rectangle, b: Rectangle) -> Rectangle {
|
||||
let left = a.x.min(b.x);
|
||||
let top = a.y.min(b.y);
|
||||
let right = (a.x + a.width).max(b.x + b.width);
|
||||
let bottom = (a.y + a.height).max(b.y + b.height);
|
||||
|
||||
Rectangle::new(
|
||||
Point::new(left, top),
|
||||
Size::new(right - left, bottom - top),
|
||||
)
|
||||
}
|
||||
|
||||
fn clamped_position(cursor: mouse::Cursor, bounds: Rectangle) -> Option<Point> {
|
||||
cursor.position_from(bounds.position()).map(|position| {
|
||||
Point::new(
|
||||
position.x.clamp(0.0, bounds.width.max(1.0) - 1.0),
|
||||
position.y.clamp(0.0, bounds.height.max(1.0) - 1.0),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn point_distance(a: Point, b: Point) -> f32 {
|
||||
let dx = a.x - b.x;
|
||||
let dy = a.y - b.y;
|
||||
|
||||
(dx * dx + dy * dy).sqrt()
|
||||
}
|
||||
|
||||
impl<'a, Link, Message, Theme, Renderer>
|
||||
From<SelectableRichText<'a, Link, Message, Theme, Renderer>>
|
||||
for Element<'a, Message, Theme, Renderer>
|
||||
where
|
||||
Message: 'a,
|
||||
Link: Clone + 'a,
|
||||
Theme: Catalog + 'a,
|
||||
Renderer: advanced_text::Renderer + 'a,
|
||||
{
|
||||
fn from(
|
||||
text: SelectableRichText<'a, Link, Message, Theme, Renderer>,
|
||||
) -> Element<'a, Message, Theme, Renderer> {
|
||||
Element::new(text)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn selected_substring_returns_middle_and_none_for_collapsed() {
|
||||
assert_eq!(selected_substring("abcdef", 2, 5), Some("cde".to_owned()));
|
||||
assert_eq!(selected_substring("abcdef", 3, 3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_substring_handles_reversed_range() {
|
||||
assert_eq!(selected_substring("abcdef", 5, 2), Some("cde".to_owned()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_all_uses_byte_length() {
|
||||
assert_eq!(select_all(""), (0, 0));
|
||||
assert_eq!(select_all("aé👍z"), (0, "aé👍z".len()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_selection_uses_byte_offsets_without_panicking() {
|
||||
let text = "aé👍z";
|
||||
|
||||
assert_eq!(selected_substring(text, 1, 7), Some("é👍".to_owned()));
|
||||
assert_eq!(selected_substring(text, 3, 7), Some("👍".to_owned()));
|
||||
assert_eq!(selected_substring(text, 2, 7), Some("é👍".to_owned()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user