use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use iced_core::{Event, window};
use icedwright_protocol::{
AnyRequest, CursorReading, Delivered, Done, ErrorBody, ErrorCode, FrameCount, Generation,
Guard, Input, Notification, PROTOCOL, RawNode, RawTree, RawWindowInfo, RequestId,
ScreenshotHeader, SnapshotReply, TaskChange, Welcome, WindowId, WindowList, WindowOrdinal,
WireEvent, WireRuleId, WireStatus, WireTaskId, accepts,
};
use icedwright_types::{Point, Rect, ScaleFactor, Size};
use serde::Serialize;
use serde_json::Value;
use super::collect::{Generations, Recording};
use super::keys::KeyHub;
use super::tasks::{TaskEvent, TaskHub};
use crate::wire::to_iced;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ClientId(pub u64);
#[derive(Debug)]
pub enum Effect {
Reply {
client: ClientId,
id: RequestId,
result: Result<Value, ErrorBody>,
attachment: Option<Vec<u8>>,
},
Notify(Notification),
Collect,
Screenshot {
client: ClientId,
id: RequestId,
window: window::Id,
},
Focus(window::Id),
Close(ClientId),
Size(window::Id),
Exit,
OsKeys {
client: ClientId,
id: RequestId,
window: window::Id,
ordinal: WindowOrdinal,
events: Vec<WireEvent>,
},
}
fn iced_status(status: WireStatus) -> iced_core::event::Status {
match status {
WireStatus::Captured => iced_core::event::Status::Captured,
WireStatus::Ignored => iced_core::event::Status::Ignored,
}
}
fn is_key_event(event: &WireEvent) -> bool {
matches!(
event,
WireEvent::KeyPressed { .. }
| WireEvent::KeyReleased { .. }
| WireEvent::ModifiersChanged { .. }
)
}
#[derive(Debug, Clone)]
struct WindowEntry {
id: window::Id,
info: RawWindowInfo,
sized: bool,
driver: Option<ClientId>,
exclusive: bool,
}
#[derive(Debug, Default)]
struct Feed {
events: Vec<(u64, Event)>,
next: u64,
}
#[derive(Debug)]
struct PendingInput {
client: ClientId,
id: RequestId,
window: window::Id,
ordinal: WindowOrdinal,
seqs: std::ops::RangeInclusive<u64>,
statuses: BTreeMap<u64, WireStatus>,
}
#[derive(Debug, Clone, Copy)]
pub struct FeedView<'a> {
pub events: &'a [(u64, Event)],
pub driven: bool,
pub exclusive: bool,
pub frames: &'a AtomicU64,
pub os_keyboard: bool,
pub inspect: bool,
pub record: bool,
pub highlight: Option<Rect>,
}
#[derive(Debug)]
pub struct ProbeState {
app: String,
pid: u32,
tasks: Arc<TaskHub>,
exit_on_bye: bool,
generations: Arc<Generations>,
frames: Arc<AtomicU64>,
clients: BTreeSet<ClientId>,
windows: BTreeMap<WindowOrdinal, WindowEntry>,
next_ordinal: u32,
feeds: BTreeMap<window::Id, Feed>,
inputs: Vec<PendingInput>,
guarded: Vec<(ClientId, RequestId, Input)>,
collect_waiters: Vec<(ClientId, RequestId)>,
parked: Vec<(ClientId, RequestId, Generation)>,
collecting: bool,
task_waiters: Vec<(ClientId, RequestId, String)>,
unclaimed: Vec<(String, WireTaskId)>,
rules: BTreeMap<ClientId, Vec<WireRuleId>>,
idle_waiters: Vec<(ClientId, RequestId)>,
inspecting: BTreeMap<WindowOrdinal, ClientId>,
recording: BTreeSet<ClientId>,
pointed: Option<(window::Id, Point, bool)>,
highlight: BTreeMap<window::Id, Rect>,
os_keyboard: BTreeSet<ClientId>,
os_keyboard_support: Result<(), String>,
keys: Arc<KeyHub>,
}
const EMPTY: &[(u64, Event)] = &[];
impl ProbeState {
#[must_use]
pub fn new(app: impl Into<String>, pid: u32, tasks: Arc<TaskHub>, exit_on_bye: bool) -> Self {
Self {
app: app.into(),
pid,
tasks,
exit_on_bye,
generations: Arc::default(),
frames: Arc::default(),
clients: BTreeSet::new(),
windows: BTreeMap::new(),
next_ordinal: 0,
feeds: BTreeMap::new(),
inputs: Vec::new(),
guarded: Vec::new(),
collect_waiters: Vec::new(),
parked: Vec::new(),
collecting: false,
task_waiters: Vec::new(),
unclaimed: Vec::new(),
rules: BTreeMap::new(),
idle_waiters: Vec::new(),
inspecting: BTreeMap::new(),
recording: BTreeSet::new(),
pointed: None,
highlight: BTreeMap::new(),
os_keyboard: BTreeSet::new(),
os_keyboard_support: Err(
"this app was built without the probe's os-keyboard feature".to_owned()
),
keys: KeyHub::global(),
}
}
#[must_use]
pub fn with_keys(mut self, keys: Arc<KeyHub>) -> Self {
self.keys = keys;
self
}
#[must_use]
pub fn with_os_keyboard(mut self, support: Result<(), String>) -> Self {
self.os_keyboard_support = support;
self
}
pub fn os_keys_sent(
&mut self,
client: ClientId,
id: RequestId,
ordinal: WindowOrdinal,
sent: Result<usize, String>,
) -> Vec<Effect> {
match sent {
Ok(count) => {
let reply = Delivered {
window: ordinal,
generation: self.generation(),
statuses: vec![WireStatus::Ignored; count],
cursors: Vec::new(),
};
vec![reply_with(client, id, &reply)]
}
Err(reason) => vec![error(client, id, ErrorCode::Refused, reason)],
}
}
fn is_idle(&self) -> bool {
self.tasks.running().is_empty()
&& self.inputs.is_empty()
&& self.guarded.is_empty()
&& !self.collecting
&& self.feeds.values().all(|feed| feed.events.is_empty())
}
fn answer_idle(&mut self) -> Vec<Effect> {
if self.idle_waiters.is_empty() || !self.is_idle() {
return Vec::new();
}
std::mem::take(&mut self.idle_waiters)
.into_iter()
.map(|(client, id)| reply_with(client, id, &Done))
.collect()
}
pub fn observed(
&mut self,
window: window::Id,
event: &Event,
status: WireStatus,
) -> Vec<Effect> {
if self.recording.is_empty() {
return Vec::new();
}
let Some(wire) = crate::wire::from_iced(event) else {
return Vec::new();
};
let Some(ordinal) = self.ordinal_of(window) else {
return Vec::new();
};
vec![Effect::Notify(Notification::Observed {
generation: self.generation(),
window: ordinal,
event: wire,
status,
})]
}
pub fn pointed(&mut self, window: window::Id, position: Point, pick: bool) -> Vec<Effect> {
let inspected = self
.ordinal_of(window)
.is_some_and(|ordinal| self.inspecting.contains_key(&ordinal));
if !inspected {
return Vec::new();
}
let earlier_pick = self.pointed.is_some_and(|(_, _, picked)| picked);
self.pointed = Some((window, position, pick || earlier_pick));
self.start_collect().into_iter().collect()
}
fn ordinal_of(&self, id: window::Id) -> Option<WindowOrdinal> {
self.windows
.iter()
.find(|(_, entry)| entry.id == id)
.map(|(ordinal, _)| *ordinal)
}
#[must_use]
pub fn highlight(&self, window: window::Id) -> Option<Rect> {
self.highlight.get(&window).copied()
}
#[must_use]
pub fn uses_os_keyboard(&self, client: ClientId) -> bool {
self.os_keyboard.contains(&client)
}
fn hovered(&mut self, tree: &RawTree) -> Vec<Effect> {
let Some((window, position, picked)) = self.pointed.take() else {
return Vec::new();
};
let Some(ordinal) = self.ordinal_of(window) else {
return Vec::new();
};
let Some((path, bounds)) = deepest_at(tree, ordinal, position) else {
self.highlight.remove(&window);
return Vec::new();
};
self.highlight.insert(window, bounds);
vec![Effect::Notify(Notification::Hovered {
path,
tree: tree.clone(),
picked,
})]
}
#[must_use]
pub fn generation(&self) -> Generation {
self.generations.current()
}
pub(crate) fn generations(&self) -> Arc<Generations> {
Arc::clone(&self.generations)
}
#[must_use]
pub fn frame(&self) -> FrameCount {
FrameCount(self.frames.load(Ordering::Relaxed))
}
#[must_use]
pub fn feed(&self, window: window::Id) -> FeedView<'_> {
let found = self.windows.iter().find(|(_, entry)| entry.id == window);
let entry = found.map(|(_, entry)| entry);
let inspect = found.is_some_and(|(ordinal, _)| self.inspecting.contains_key(ordinal));
FeedView {
events: self.feeds.get(&window).map_or(EMPTY, |feed| &feed.events),
driven: entry.is_some_and(|entry| entry.driver.is_some()),
exclusive: entry.is_some_and(|entry| entry.driver.is_some() && entry.exclusive),
frames: &self.frames,
os_keyboard: entry
.and_then(|entry| entry.driver)
.is_some_and(|client| self.os_keyboard.contains(&client)),
inspect,
record: !self.recording.is_empty(),
highlight: inspect.then(|| self.highlight(window)).flatten(),
}
}
pub fn window_ids(&self) -> impl Iterator<Item = window::Id> + '_ {
self.windows.values().map(|entry| entry.id)
}
fn ordinal(&mut self, id: window::Id) -> WindowOrdinal {
if let Some((ordinal, _)) = self.windows.iter().find(|(_, entry)| entry.id == id) {
return *ordinal;
}
let ordinal = WindowOrdinal(self.next_ordinal);
self.next_ordinal += 1;
self.windows.insert(
ordinal,
WindowEntry {
id,
info: RawWindowInfo {
id: WindowId(u64::from(ordinal.0)),
title: String::new(),
size: Size::new(0.0, 0.0),
scale_factor: ScaleFactor::default(),
},
sized: false,
driver: None,
exclusive: false,
},
);
ordinal
}
fn entry_mut(&mut self, id: window::Id) -> Option<&mut WindowEntry> {
self.windows.values_mut().find(|entry| entry.id == id)
}
pub fn window_opened(&mut self, id: window::Id, size: Size) -> Vec<Effect> {
let ordinal = self.ordinal(id);
let Some(entry) = self.windows.get_mut(&ordinal) else {
return Vec::new();
};
entry.info.size = size;
entry.sized = true;
vec![Effect::Notify(Notification::WindowOpened(
entry.info.clone(),
))]
}
pub fn window_resized(&mut self, id: window::Id, size: Size) {
if let Some(entry) = self.entry_mut(id) {
entry.info.size = size;
entry.sized = true;
}
}
pub fn window_rescaled(&mut self, id: window::Id, factor: f32) {
let Ok(scale) = ScaleFactor::new(factor) else {
return;
};
if let Some(entry) = self.entry_mut(id) {
entry.info.scale_factor = scale;
}
}
pub fn set_title(&mut self, id: window::Id, title: String) {
if let Some(entry) = self.entry_mut(id) {
entry.info.title = title;
}
}
pub fn window_closed(&mut self, id: window::Id) -> Vec<Effect> {
let Some(ordinal) = self
.windows
.iter()
.find(|(_, entry)| entry.id == id)
.map(|(ordinal, _)| *ordinal)
else {
return Vec::new();
};
self.windows.remove(&ordinal);
self.feeds.remove(&id);
let mut effects = Vec::new();
for input in std::mem::take(&mut self.inputs) {
if input.window != id {
self.inputs.push(input);
continue;
}
effects.push(error(
input.client,
input.id,
ErrorCode::NoSuchWindow,
format!("window {} closed during the input", ordinal.0),
));
}
effects.push(Effect::Notify(Notification::WindowClosed {
window: ordinal,
}));
effects
}
pub fn app_message(&mut self) -> Vec<Effect> {
self.bump()
}
fn bump(&mut self) -> Vec<Effect> {
let generation = self.generations.raise();
let mut effects = Vec::new();
if !self.clients.is_empty() {
effects.push(Effect::Notify(Notification::Generation {
generation,
frame: self.frame(),
}));
}
let (ready, parked): (Vec<_>, Vec<_>) = std::mem::take(&mut self.parked)
.into_iter()
.partition(|(_, _, after)| generation > *after);
self.parked = parked;
if !ready.is_empty() {
self.collect_waiters
.extend(ready.into_iter().map(|(client, id, _)| (client, id)));
effects.extend(self.start_collect());
}
effects.extend(self.answer_idle());
effects
}
fn start_collect(&mut self) -> Option<Effect> {
if self.collecting {
return None;
}
self.collecting = true;
Some(Effect::Collect)
}
pub fn delivered(
&mut self,
window: window::Id,
through: u64,
statuses: Vec<(u64, WireStatus)>,
cursors: Vec<CursorReading>,
) -> Vec<Effect> {
if let Some(feed) = self.feeds.get_mut(&window) {
for (seq, event) in feed.events.iter().filter(|(seq, _)| *seq <= through) {
let Some((_, status)) = statuses.iter().find(|(s, _)| s == seq) else {
continue;
};
self.keys.publish(window, event, iced_status(*status));
}
feed.events.retain(|(seq, _)| *seq > through);
}
let mut effects = self.bump();
let generation = self.generation();
for input in std::mem::take(&mut self.inputs) {
let mut input = input;
if input.window == window {
input.statuses.extend(
statuses
.iter()
.filter(|(seq, _)| input.seqs.contains(seq))
.copied(),
);
}
if input.window != window || *input.seqs.end() > through {
self.inputs.push(input);
continue;
}
let reply = Delivered {
window: input.ordinal,
generation,
statuses: input.statuses.into_values().collect(),
cursors: cursors.clone(),
};
effects.push(reply_with(input.client, input.id, &reply));
}
effects.extend(self.answer_idle());
effects
}
pub fn collected(&mut self, recording: Recording) -> Vec<Effect> {
self.collecting = false;
let read = self
.generations
.take_read()
.unwrap_or_else(|| self.generation());
let (mut tree, ids) = recording;
let ordinals: BTreeMap<WindowId, WindowOrdinal> = ids
.into_iter()
.map(|(window, id)| (id, self.ordinal(window)))
.collect();
for raw in &mut tree.windows {
let Some(ordinal) = raw.id.and_then(|id| ordinals.get(&id)).copied() else {
continue;
};
raw.id = Some(WindowId(u64::from(ordinal.0)));
raw.info = self
.windows
.get(&ordinal)
.filter(|entry| entry.sized)
.map(|entry| entry.info.clone());
}
tree.windows.sort_by_key(|raw| raw.id);
let reply = SnapshotReply::Tree {
generation: read,
frame: self.frame(),
tree: tree.clone(),
};
let mut effects: Vec<Effect> = self
.windows
.values()
.filter(|entry| !entry.sized)
.map(|entry| Effect::Size(entry.id))
.collect();
effects.extend(
std::mem::take(&mut self.collect_waiters)
.into_iter()
.map(|(client, id)| reply_with(client, id, &reply)),
);
for (client, id, input) in std::mem::take(&mut self.guarded) {
let found = input
.guard
.as_ref()
.is_some_and(|guard| guard_holds(&tree, input.window, guard));
if found {
effects.extend(self.queue(client, id, input));
} else {
effects.push(error(
client,
id,
ErrorCode::Stale,
"the target moved or went away since the client looked; take a new snapshot",
));
}
}
effects.extend(self.hovered(&tree));
effects.extend(self.answer_idle());
effects
}
pub fn screenshot_taken(
&mut self,
client: ClientId,
id: RequestId,
window: window::Id,
shot: Option<window::Screenshot>,
) -> Vec<Effect> {
let Some(ordinal) = self
.windows
.iter()
.find(|(_, entry)| entry.id == window)
.map(|(ordinal, _)| *ordinal)
else {
return vec![error(
client,
id,
ErrorCode::NoSuchWindow,
"the window closed",
)];
};
let Some(shot) = shot else {
return vec![error(
client,
id,
ErrorCode::NotReady,
"the window has no compositor yet",
)];
};
let Ok(scale_factor) = ScaleFactor::new(shot.scale_factor) else {
return vec![error(
client,
id,
ErrorCode::Internal,
"the screenshot has an invalid scale factor",
)];
};
let header = ScreenshotHeader {
window: ordinal,
width: shot.size.width,
height: shot.size.height,
scale_factor,
};
let mut reply = reply_with(client, id, &header);
if let Effect::Reply { attachment, .. } = &mut reply {
*attachment = Some(shot.rgba.to_vec());
}
vec![reply]
}
pub fn task_event(&mut self, event: TaskEvent) -> Vec<Effect> {
let mut effects = Vec::new();
match event.change {
TaskChange::Started => {
let waiter = self
.task_waiters
.iter()
.position(|(_, _, name)| *name == event.name);
match waiter {
Some(index) => {
let (client, id, _) = self.task_waiters.remove(index);
effects.push(reply_with(client, id, &event.task));
}
None => self.unclaimed.push((event.name.clone(), event.task)),
}
}
TaskChange::Finished | TaskChange::Resolved | TaskChange::Failed { .. } => {
self.unclaimed.retain(|(_, task)| *task != event.task);
}
TaskChange::Held | TaskChange::Released => {}
}
if !self.clients.is_empty() {
effects.push(Effect::Notify(Notification::Task {
name: event.name,
task: event.task,
change: event.change,
}));
}
effects.extend(self.answer_idle());
effects
}
pub fn client_closed(&mut self, client: ClientId) -> Vec<Effect> {
self.forget(client);
self.exit_if_done()
}
fn forget(&mut self, client: ClientId) {
self.clients.remove(&client);
for entry in self.windows.values_mut() {
if entry.driver == Some(client) {
entry.driver = None;
}
}
for rule in self.rules.remove(&client).unwrap_or_default() {
let _ = self.tasks.remove_rule(rule);
}
self.parked.retain(|(c, _, _)| *c != client);
self.collect_waiters.retain(|(c, _)| *c != client);
self.task_waiters.retain(|(c, _, _)| *c != client);
self.guarded.retain(|(c, _, _)| *c != client);
self.inputs.retain(|input| input.client != client);
self.idle_waiters.retain(|(c, _)| *c != client);
self.inspecting.retain(|_, c| *c != client);
if self.inspecting.is_empty() {
self.highlight.clear();
}
self.recording.remove(&client);
self.os_keyboard.remove(&client);
}
fn exit_if_done(&self) -> Vec<Effect> {
if self.exit_on_bye && self.clients.is_empty() {
return vec![Effect::Exit];
}
Vec::new()
}
fn infos(&self) -> Vec<RawWindowInfo> {
self.windows
.values()
.map(|entry| entry.info.clone())
.collect()
}
fn window(&self, ordinal: WindowOrdinal) -> Result<&WindowEntry, ErrorBody> {
self.windows.get(&ordinal).ok_or_else(|| {
ErrorBody::new(
ErrorCode::NoSuchWindow,
format!("no window {} is open", ordinal.0),
)
})
}
fn claim(&mut self, client: ClientId, ordinal: WindowOrdinal) -> Result<(), ErrorBody> {
let Some(entry) = self.windows.get_mut(&ordinal) else {
return Err(ErrorBody::new(
ErrorCode::NoSuchWindow,
format!("no window {} is open", ordinal.0),
));
};
match entry.driver {
Some(other) if other != client => Err(ErrorBody::new(
ErrorCode::Busy,
format!("another client is driving window {}", ordinal.0),
)),
Some(_) => Ok(()),
None => {
entry.driver = Some(client);
entry.exclusive = true;
Ok(())
}
}
}
fn queue(&mut self, client: ClientId, id: RequestId, input: Input) -> Vec<Effect> {
let Ok(entry) = self.window(input.window) else {
return vec![error(
client,
id,
ErrorCode::NoSuchWindow,
"the window closed",
)];
};
let window = entry.id;
if input.events.is_empty() {
let reply = Delivered {
window: input.window,
generation: self.generation(),
statuses: Vec::new(),
cursors: Vec::new(),
};
return vec![reply_with(client, id, &reply)];
}
let feed = self.feeds.entry(window).or_default();
let first = feed.next + 1;
for event in &input.events {
feed.next += 1;
feed.events.push((feed.next, to_iced(event)));
}
self.inputs.push(PendingInput {
client,
id,
window,
ordinal: input.window,
seqs: first..=feed.next,
statuses: BTreeMap::new(),
});
Vec::new()
}
}
fn reply_with(client: ClientId, id: RequestId, response: &impl Serialize) -> Effect {
let result = serde_json::to_value(response).map_err(|e| {
ErrorBody::new(
ErrorCode::Internal,
format!("the response could not be encoded: {e}"),
)
});
Effect::Reply {
client,
id,
result,
attachment: None,
}
}
fn error(client: ClientId, id: RequestId, code: ErrorCode, message: impl Into<String>) -> Effect {
Effect::Reply {
client,
id,
result: Err(ErrorBody::new(code, message)),
attachment: None,
}
}
fn close_enough(a: Rect, b: Rect) -> bool {
const EPSILON: f32 = 0.5;
(a.x - b.x).abs() <= EPSILON
&& (a.y - b.y).abs() <= EPSILON
&& (a.width - b.width).abs() <= EPSILON
&& (a.height - b.height).abs() <= EPSILON
}
fn guard_holds(tree: &RawTree, window: WindowOrdinal, guard: &Guard) -> bool {
fn any(node: &RawNode, bounds: Rect) -> bool {
close_enough(node.bounds, bounds) || node.children.iter().any(|child| any(child, bounds))
}
tree.windows
.iter()
.filter(|raw| raw.id == Some(WindowId(u64::from(window.0))))
.any(|raw| any(&raw.root, guard.bounds))
}
fn deepest_at(tree: &RawTree, window: WindowOrdinal, position: Point) -> Option<(String, Rect)> {
fn contains(rect: Rect, point: Point) -> bool {
point.x >= rect.x
&& point.y >= rect.y
&& point.x < rect.x + rect.width
&& point.y < rect.y + rect.height
}
fn walk(
node: &RawNode,
position: Point,
path: &mut Vec<usize>,
best: &mut Option<(Vec<usize>, Rect)>,
) {
for (index, child) in node.children.iter().enumerate() {
path.push(index);
if contains(child.bounds, position) {
*best = Some((path.clone(), child.bounds));
}
walk(child, position, path, best);
path.pop();
}
}
let (index, raw) = tree
.windows
.iter()
.enumerate()
.find(|(_, raw)| raw.id == Some(WindowId(u64::from(window.0))))?;
let mut best = None;
walk(&raw.root, position, &mut Vec::new(), &mut best);
let (path, bounds) = best?;
let mut text = index.to_string();
for step in path {
text.push('.');
text.push_str(&step.to_string());
}
Some((text, bounds))
}
pub fn dispatch(
state: &mut ProbeState,
client: ClientId,
id: RequestId,
method: &str,
params: Value,
) -> Vec<Effect> {
let request = match AnyRequest::from_params(method, params) {
Ok(Some(request)) => request,
Ok(None) => {
return vec![error(
client,
id,
ErrorCode::BadRequest,
format!("there is no method `{method}`"),
)];
}
Err(e) => {
return vec![error(
client,
id,
ErrorCode::BadRequest,
format!("{method}: {e}"),
)];
}
};
if !state.clients.contains(&client) && !matches!(request, AnyRequest::Hello(_)) {
return vec![error(
client,
id,
ErrorCode::BadRequest,
"the first request on a connection must be hello",
)];
}
let done = || reply_with(client, id, &Done);
match request {
AnyRequest::Hello(hello) => {
if let Err(mismatch) = accepts(hello.protocol) {
return vec![
error(
client,
id,
ErrorCode::ProtocolMismatch,
mismatch.to_string(),
),
Effect::Close(client),
];
}
if hello.os_keyboard {
if let Err(reason) = &state.os_keyboard_support {
return vec![error(client, id, ErrorCode::Refused, reason.clone())];
}
state.os_keyboard.insert(client);
}
state.clients.insert(client);
let welcome = Welcome {
protocol: PROTOCOL,
app: state.app.clone(),
pid: state.pid,
iced: "0.14".to_owned(),
semantics: true,
windows: state.infos(),
};
vec![reply_with(client, id, &welcome)]
}
AnyRequest::Snapshot(snapshot) => match snapshot.after {
Some(after) if state.generation() <= after => {
state.parked.push((client, id, after));
Vec::new()
}
_ => {
state.collect_waiters.push((client, id));
state.start_collect().into_iter().collect()
}
},
AnyRequest::Input(input) => {
let entry = match state.window(input.window) {
Ok(entry) => entry,
Err(body) => {
return vec![Effect::Reply {
client,
id,
result: Err(body),
attachment: None,
}];
}
};
if entry.sized && (entry.info.size.width <= 0.0 || entry.info.size.height <= 0.0) {
return vec![error(
client,
id,
ErrorCode::NotReady,
format!(
"window {} has zero size, so it draws no frames to deliver input in",
input.window.0
),
)];
}
if let Err(body) = state.claim(client, input.window) {
return vec![Effect::Reply {
client,
id,
result: Err(body),
attachment: None,
}];
}
if state.os_keyboard.contains(&client)
&& input.guard.is_none()
&& !input.events.is_empty()
&& input.events.iter().all(is_key_event)
{
let window = state.windows.get(&input.window).map(|entry| entry.id);
if let Some(window) = window {
return vec![Effect::OsKeys {
client,
id,
window,
ordinal: input.window,
events: input.events,
}];
}
}
let unchanged = input
.guard
.as_ref()
.is_none_or(|guard| guard.generation == state.generation());
if unchanged {
return state.queue(client, id, input);
}
state.guarded.push((client, id, input));
state.start_collect().into_iter().collect()
}
AnyRequest::Screenshot(screenshot) => match state.window(screenshot.window) {
Ok(entry) => vec![Effect::Screenshot {
client,
id,
window: entry.id,
}],
Err(body) => vec![Effect::Reply {
client,
id,
result: Err(body),
attachment: None,
}],
},
AnyRequest::Windows(_) => vec![reply_with(
client,
id,
&WindowList {
windows: state.infos(),
},
)],
AnyRequest::Focus(focus) => match state.window(focus.window) {
Ok(entry) => vec![Effect::Focus(entry.id), done()],
Err(body) => vec![Effect::Reply {
client,
id,
result: Err(body),
attachment: None,
}],
},
AnyRequest::Drive(drive) => {
if let Err(body) = state.claim(client, drive.window) {
return vec![Effect::Reply {
client,
id,
result: Err(body),
attachment: None,
}];
}
if let Some(entry) = state.windows.get_mut(&drive.window) {
entry.exclusive = drive.exclusive_pointer;
}
vec![done()]
}
AnyRequest::Release(release) => {
if let Some(entry) = state.windows.get_mut(&release.window)
&& entry.driver == Some(client)
{
entry.driver = None;
}
vec![done()]
}
AnyRequest::Inspect(inspect) => {
if let Err(body) = state.window(inspect.window) {
return vec![Effect::Reply {
client,
id,
result: Err(body),
attachment: None,
}];
}
if inspect.on {
state.inspecting.insert(inspect.window, client);
} else if state.inspecting.get(&inspect.window) == Some(&client) {
state.inspecting.remove(&inspect.window);
let window = state.windows.get(&inspect.window).map(|entry| entry.id);
if let Some(window) = window {
state.highlight.remove(&window);
}
}
vec![done()]
}
AnyRequest::Record(record) => {
if record.on {
state.recording.insert(client);
} else {
state.recording.remove(&client);
}
vec![done()]
}
AnyRequest::WaitIdle(_) => {
state.idle_waiters.push((client, id));
state.answer_idle()
}
AnyRequest::HoldTask(hold) => {
let rule = state.tasks.hold(hold.name);
state.rules.entry(client).or_default().push(rule);
vec![reply_with(client, id, &rule)]
}
AnyRequest::RemoveRule(remove) => {
if !state.tasks.remove_rule(remove.rule) {
return vec![error(
client,
id,
ErrorCode::BadRequest,
format!("there is no rule {}", remove.rule.0),
)];
}
if let Some(rules) = state.rules.get_mut(&client) {
rules.retain(|rule| *rule != remove.rule);
}
vec![done()]
}
AnyRequest::NextTask(next) => {
let found = state
.unclaimed
.iter()
.position(|(name, _)| *name == next.name);
match found {
Some(index) => {
let (_, task) = state.unclaimed.remove(index);
vec![reply_with(client, id, &task)]
}
None => {
state.task_waiters.push((client, id, next.name));
Vec::new()
}
}
}
AnyRequest::ReleaseTask(release) => match state.tasks.release(release.task) {
Ok(()) => vec![done()],
Err(message) => vec![error(client, id, ErrorCode::BadRequest, message)],
},
AnyRequest::ResolveTask(resolve) => {
match state.tasks.resolve(resolve.task, &resolve.output) {
Ok(()) => vec![done()],
Err(message) => vec![error(client, id, ErrorCode::BadRequest, message)],
}
}
AnyRequest::Bye(_) => {
state.forget(client);
let mut effects = vec![done()];
effects.extend(state.exit_if_done());
effects
}
_ => vec![error(
client,
id,
ErrorCode::BadRequest,
format!("`{method}` is not handled by this probe"),
)],
}
}
#[cfg(test)]
mod tests {
use icedwright_protocol::{
Bye, Drive, Hello, HoldTask, NextTask, ReleaseTask, Request, Snapshot, WireButton,
WireEvent,
};
use icedwright_types::Point;
use super::*;
fn rect(x: f32, y: f32, width: f32, height: f32) -> Rect {
Rect {
x,
y,
width,
height,
}
}
fn state() -> ProbeState {
ProbeState::new("demo", 7, Arc::new(TaskHub::new()), true)
}
fn call<R: Request>(state: &mut ProbeState, client: u64, id: u64, request: R) -> Vec<Effect> {
let params = serde_json::to_value(&request).unwrap_or(Value::Null);
dispatch(state, ClientId(client), RequestId(id), R::METHOD, params)
}
fn hello(state: &mut ProbeState, client: u64) {
let effects = call(
state,
client,
0,
Hello {
protocol: PROTOCOL,
client: "test".to_owned(),
os_keyboard: false,
},
);
assert!(matches!(effects[..], [Effect::Reply { result: Ok(_), .. }]));
}
fn code(effects: &[Effect]) -> Option<ErrorCode> {
effects.iter().find_map(|effect| match effect {
Effect::Reply {
result: Err(body), ..
} => Some(body.code),
_ => None,
})
}
fn click(window: u32, guard: Option<Guard>) -> Input {
Input {
window: WindowOrdinal(window),
events: vec![
WireEvent::CursorMoved {
position: Point::new(5.0, 5.0),
},
WireEvent::ButtonPressed {
button: WireButton::Left,
},
],
guard,
}
}
fn two_windows(state: &mut ProbeState) -> (window::Id, window::Id) {
let a = window::Id::unique();
let b = window::Id::unique();
let _ = state.window_opened(a, Size::new(100.0, 100.0));
let _ = state.window_opened(b, Size::new(50.0, 50.0));
(a, b)
}
#[test]
fn requests_before_hello_are_refused() {
let mut state = state();
let effects = call(&mut state, 1, 1, Snapshot::default());
assert_eq!(code(&effects), Some(ErrorCode::BadRequest));
}
#[test]
fn a_different_major_closes_the_connection() {
let mut state = state();
let effects = call(
&mut state,
1,
1,
Hello {
protocol: (PROTOCOL.0 + 1, 0),
client: "new".to_owned(),
os_keyboard: false,
},
);
assert_eq!(code(&effects), Some(ErrorCode::ProtocolMismatch));
assert!(matches!(effects.last(), Some(Effect::Close(ClientId(1)))));
}
#[test]
fn unknown_methods_and_bad_params_are_bad_requests() {
let mut state = state();
hello(&mut state, 1);
let unknown = dispatch(&mut state, ClientId(1), RequestId(2), "nope", Value::Null);
assert_eq!(code(&unknown), Some(ErrorCode::BadRequest));
let bad = dispatch(
&mut state,
ClientId(1),
RequestId(3),
"input",
serde_json::json!({ "window": "first" }),
);
assert_eq!(code(&bad), Some(ErrorCode::BadRequest));
}
#[test]
fn input_is_queued_for_the_right_window_and_answered_on_delivery() {
let mut state = state();
hello(&mut state, 1);
let (a, b) = two_windows(&mut state);
assert!(call(&mut state, 1, 2, click(1, None)).is_empty());
assert_eq!(state.feed(a).events.len(), 0);
assert_eq!(state.feed(b).events.len(), 2);
assert!(state.feed(b).driven);
let partial = state.delivered(b, 1, vec![(1, WireStatus::Ignored)], Vec::new());
assert!(!partial.iter().any(|e| matches!(e, Effect::Reply { .. })));
let done = state.delivered(b, 2, vec![(2, WireStatus::Captured)], Vec::new());
let reply = done.iter().find_map(|e| match e {
Effect::Reply { result: Ok(v), .. } => {
serde_json::from_value::<Delivered>(v.clone()).ok()
}
_ => None,
});
let Some(reply) = reply else {
panic!("no Delivered reply");
};
assert_eq!(reply.window, WindowOrdinal(1));
assert_eq!(
reply.statuses,
vec![WireStatus::Ignored, WireStatus::Captured]
);
assert_eq!(state.feed(b).events.len(), 0);
assert_eq!(state.generation(), Generation(2));
}
#[test]
fn a_second_client_driving_gets_busy() {
let mut state = state();
hello(&mut state, 1);
hello(&mut state, 2);
let _ = two_windows(&mut state);
let first = call(
&mut state,
1,
1,
Drive {
window: WindowOrdinal(0),
exclusive_pointer: true,
},
);
assert_eq!(code(&first), None);
let second = call(
&mut state,
2,
2,
Drive {
window: WindowOrdinal(0),
exclusive_pointer: true,
},
);
assert_eq!(code(&second), Some(ErrorCode::Busy));
assert_eq!(
code(&call(&mut state, 2, 3, click(0, None))),
Some(ErrorCode::Busy)
);
let snapshot = call(&mut state, 2, 4, Snapshot::default());
assert!(matches!(snapshot[..], [Effect::Collect]));
}
#[test]
fn zero_sized_and_missing_windows_are_refused() {
let mut state = state();
hello(&mut state, 1);
let _ = state.window_opened(window::Id::unique(), Size::new(0.0, 0.0));
assert_eq!(
code(&call(&mut state, 1, 1, click(0, None))),
Some(ErrorCode::NotReady)
);
assert_eq!(
code(&call(&mut state, 1, 2, click(5, None))),
Some(ErrorCode::NoSuchWindow)
);
}
fn recording(window: window::Id, bounds: Rect) -> Recording {
let raw = icedwright_protocol::RawWindow {
id: Some(WindowId(0)),
info: None,
root: RawNode::new(icedwright_protocol::RawCall::Group, Rect::default()).with_children(
[RawNode::new(
icedwright_protocol::RawCall::Container,
bounds,
)],
),
};
(RawTree { windows: vec![raw] }, vec![(window, WindowId(0))])
}
#[test]
fn a_guarded_input_whose_node_moved_is_stale() {
let mut state = state();
hello(&mut state, 1);
let (a, _) = two_windows(&mut state);
let _ = state.app_message();
let guard = Guard {
generation: Generation(0),
path: "/window[0]/button".to_owned(),
bounds: rect(10.0, 10.0, 20.0, 20.0),
};
let effects = call(&mut state, 1, 1, click(0, Some(guard.clone())));
assert!(matches!(effects[..], [Effect::Collect]));
let moved = state.collected(recording(a, rect(40.0, 10.0, 20.0, 20.0)));
assert_eq!(code(&moved), Some(ErrorCode::Stale));
let again = call(&mut state, 1, 2, click(0, Some(guard)));
assert!(matches!(again[..], [Effect::Collect]));
let still = state.collected(recording(a, rect(10.0, 10.0, 20.0, 20.0)));
assert_eq!(code(&still), None);
assert_eq!(state.feed(a).events.len(), 2);
}
#[test]
fn a_window_first_met_in_a_collection_is_asked_its_size() {
let mut state = state();
hello(&mut state, 1);
let window = window::Id::unique();
let effects = state.collected(recording(window, rect(0.0, 0.0, 5.0, 5.0)));
assert!(
effects
.iter()
.any(|e| matches!(e, Effect::Size(w) if *w == window))
);
assert!(call(&mut state, 1, 1, click(0, None)).is_empty());
state.window_resized(window, Size::new(0.0, 0.0));
assert_eq!(
code(&call(&mut state, 1, 2, click(0, None))),
Some(ErrorCode::NotReady)
);
}
#[test]
fn a_guard_at_the_current_generation_is_applied_at_once() {
let mut state = state();
hello(&mut state, 1);
let (a, _) = two_windows(&mut state);
let guard = Guard {
generation: state.generation(),
path: "/".to_owned(),
bounds: rect(0.0, 0.0, 1.0, 1.0),
};
assert!(call(&mut state, 1, 1, click(0, Some(guard))).is_empty());
assert_eq!(state.feed(a).events.len(), 2);
}
#[test]
fn a_long_poll_is_parked_until_the_generation_rises() {
let mut state = state();
hello(&mut state, 1);
let (a, _) = two_windows(&mut state);
let parked = call(
&mut state,
1,
1,
Snapshot {
after: Some(Generation(0)),
wait: None,
},
);
assert!(parked.is_empty());
let effects = state.app_message();
assert!(effects.iter().any(|e| matches!(e, Effect::Collect)));
assert!(
effects
.iter()
.any(|e| matches!(e, Effect::Notify(Notification::Generation { .. })))
);
let replies = state.collected(recording(a, rect(0.0, 0.0, 5.0, 5.0)));
let tree = replies.iter().find_map(|e| match e {
Effect::Reply { result: Ok(v), .. } => {
serde_json::from_value::<SnapshotReply>(v.clone()).ok()
}
_ => None,
});
let Some(SnapshotReply::Tree {
generation, tree, ..
}) = tree
else {
panic!("no tree reply");
};
assert_eq!(generation, Generation(1));
assert_eq!(
tree.windows[0].info.as_ref().map(|i| i.size),
Some(Size::new(100.0, 100.0))
);
}
fn tree_generation(effects: &[Effect]) -> Option<Generation> {
effects.iter().find_map(|e| match e {
Effect::Reply { result: Ok(v), .. } => {
match serde_json::from_value::<SnapshotReply>(v.clone()).ok()? {
SnapshotReply::Tree { generation, .. } => Some(generation),
SnapshotReply::Unchanged => None,
}
}
_ => None,
})
}
#[test]
fn a_tree_read_before_an_app_message_is_answered_with_the_generation_it_shows() {
use iced_core::widget::Operation;
use super::super::collect::Collect;
let mut state = state();
hello(&mut state, 1);
let (a, _) = two_windows(&mut state);
let _ = state.app_message();
let shown = state.generation();
let asked = call(&mut state, 1, 1, Snapshot::default());
assert!(matches!(asked[..], [Effect::Collect]));
let collect = Collect::new(Arc::default(), state.generations());
let _ = collect.finish();
let _ = state.app_message();
let replies = state.collected(recording(a, rect(0.0, 0.0, 5.0, 5.0)));
assert_eq!(tree_generation(&replies), Some(shown));
let poll = Snapshot {
after: Some(shown),
wait: None,
};
assert!(matches!(
call(&mut state, 1, 2, poll)[..],
[Effect::Collect]
));
}
#[test]
fn a_tree_with_no_noted_read_is_answered_with_the_current_generation() {
let mut state = state();
hello(&mut state, 1);
let (a, _) = two_windows(&mut state);
let _ = state.app_message();
let _ = call(&mut state, 1, 1, Snapshot::default());
let replies = state.collected(recording(a, rect(0.0, 0.0, 5.0, 5.0)));
assert_eq!(tree_generation(&replies), Some(state.generation()));
}
#[test]
fn hold_next_and_release_of_a_named_task() {
let hub = Arc::new(TaskHub::new());
let mut state = ProbeState::new("demo", 7, Arc::clone(&hub), false);
hello(&mut state, 1);
let held = call(
&mut state,
1,
1,
HoldTask {
name: "demo::Load".to_owned(),
},
);
let rule = held.iter().find_map(|e| match e {
Effect::Reply { result: Ok(v), .. } => {
serde_json::from_value::<WireRuleId>(v.clone()).ok()
}
_ => None,
});
assert!(rule.is_some());
let waiting = call(
&mut state,
1,
2,
NextTask {
name: "demo::Load".to_owned(),
wait: None,
},
);
assert!(waiting.is_empty());
let started = state.task_event(TaskEvent {
name: "demo::Load".to_owned(),
task: WireTaskId(3),
change: TaskChange::Started,
});
let task = started.iter().find_map(|e| match e {
Effect::Reply {
id: RequestId(2),
result: Ok(v),
..
} => serde_json::from_value::<WireTaskId>(v.clone()).ok(),
_ => None,
});
assert_eq!(task, Some(WireTaskId(3)));
let release = call(
&mut state,
1,
3,
ReleaseTask {
name: "demo::Load".to_owned(),
task: WireTaskId(3),
},
);
assert_eq!(code(&release), Some(ErrorCode::BadRequest));
}
#[test]
fn a_task_that_started_before_next_is_handed_out_once() {
let mut state = state();
hello(&mut state, 1);
let _ = state.task_event(TaskEvent {
name: "demo::Load".to_owned(),
task: WireTaskId(1),
change: TaskChange::Started,
});
let next = || NextTask {
name: "demo::Load".to_owned(),
wait: None,
};
assert_eq!(call(&mut state, 1, 1, next()).len(), 1);
assert!(call(&mut state, 1, 2, next()).is_empty());
}
#[test]
fn bye_frees_windows_and_exits_when_asked() {
let mut state = state();
hello(&mut state, 1);
let (a, _) = two_windows(&mut state);
let _ = call(&mut state, 1, 1, click(0, None));
assert!(state.feed(a).driven);
let effects = call(&mut state, 1, 2, Bye);
assert!(!state.feed(a).driven);
assert!(matches!(effects.last(), Some(Effect::Exit)));
}
#[test]
fn os_keyboard_is_refused_without_the_feature() {
let mut state = state();
let effects = call(
&mut state,
1,
1,
Hello {
protocol: PROTOCOL,
client: "t".to_owned(),
os_keyboard: true,
},
);
assert_eq!(code(&effects), Some(ErrorCode::Refused));
}
fn done_reply(effects: &[Effect], want: u64) -> bool {
effects
.iter()
.any(|effect| matches!(effect, Effect::Reply { id, result: Ok(_), .. } if id.0 == want))
}
#[test]
fn wait_idle_answers_at_once_when_nothing_is_outstanding() {
let mut state = state();
hello(&mut state, 1);
let effects = call(&mut state, 1, 4, icedwright_protocol::WaitIdle::default());
assert!(done_reply(&effects, 4));
}
#[test]
fn wait_idle_is_parked_until_queued_input_is_delivered() {
let mut state = state();
hello(&mut state, 1);
let (_, b) = two_windows(&mut state);
assert!(call(&mut state, 1, 2, click(1, None)).is_empty());
let parked = call(&mut state, 1, 3, icedwright_protocol::WaitIdle::default());
assert!(!done_reply(&parked, 3));
let delivered = state.delivered(
b,
2,
vec![(1, WireStatus::Ignored), (2, WireStatus::Captured)],
Vec::new(),
);
assert!(done_reply(&delivered, 2));
assert!(done_reply(&delivered, 3));
}
#[test]
fn pick_mode_reports_the_node_under_the_pointer_and_outlines_it() {
let mut state = state();
hello(&mut state, 1);
let (a, _) = two_windows(&mut state);
let inspect = icedwright_protocol::Inspect {
window: WindowOrdinal(0),
on: true,
};
assert!(done_reply(&call(&mut state, 1, 2, inspect), 2));
assert!(state.feed(a).inspect);
let effects = state.pointed(a, Point::new(15.0, 15.0), true);
assert!(matches!(effects[..], [Effect::Collect]));
let found = state.collected(recording(a, rect(10.0, 10.0, 20.0, 20.0)));
let hovered = found.iter().find_map(|effect| match effect {
Effect::Notify(Notification::Hovered { path, picked, .. }) => {
Some((path.clone(), *picked))
}
_ => None,
});
assert_eq!(hovered, Some(("0.0".to_owned(), true)));
assert_eq!(state.feed(a).highlight, Some(rect(10.0, 10.0, 20.0, 20.0)));
let off = icedwright_protocol::Inspect {
window: WindowOrdinal(0),
on: false,
};
let _ = call(&mut state, 1, 3, off);
assert!(!state.feed(a).inspect);
assert_eq!(state.feed(a).highlight, None);
assert!(state.pointed(a, Point::new(15.0, 15.0), false).is_empty());
}
#[test]
fn recording_reports_real_events_only_while_on() {
let mut state = state();
hello(&mut state, 1);
let (a, _) = two_windows(&mut state);
let event = Event::Mouse(iced_core::mouse::Event::CursorLeft);
assert!(state.observed(a, &event, WireStatus::Ignored).is_empty());
let on = icedwright_protocol::Record { on: true };
let _ = call(&mut state, 1, 2, on);
assert!(state.feed(a).record);
let seen = state.observed(a, &event, WireStatus::Ignored);
assert!(matches!(
seen[..],
[Effect::Notify(Notification::Observed {
window: WindowOrdinal(0),
event: WireEvent::CursorLeft,
..
})]
));
let _ = call(&mut state, 1, 3, Bye);
assert!(!state.feed(a).record);
}
fn key(down: bool) -> WireEvent {
let key = icedwright_protocol::WireKey::Named(icedwright_types::input::NamedKey::Enter);
let physical_key =
icedwright_protocol::WirePhysicalKey::Code(icedwright_types::input::KeyCode::Enter);
if down {
WireEvent::KeyPressed {
modified_key: key.clone(),
key,
physical_key,
location: icedwright_protocol::WireLocation::Standard,
modifiers: icedwright_protocol::WireModifiers::default(),
text: None,
repeat: false,
}
} else {
WireEvent::KeyReleased {
modified_key: key.clone(),
key,
physical_key,
location: icedwright_protocol::WireLocation::Standard,
modifiers: icedwright_protocol::WireModifiers::default(),
}
}
}
#[test]
fn an_os_keyboard_client_sends_keys_through_the_os_and_pointer_input_through_the_root() {
let mut state = state().with_os_keyboard(Ok(()));
let hello = Hello {
protocol: PROTOCOL,
client: "t".to_owned(),
os_keyboard: true,
};
assert!(done_reply(&call(&mut state, 1, 1, hello), 1));
let (a, _) = two_windows(&mut state);
let keys = Input {
window: WindowOrdinal(0),
events: vec![key(true), key(false)],
guard: None,
};
let effects = call(&mut state, 1, 2, keys);
assert!(matches!(
effects[..],
[Effect::OsKeys { window, ordinal: WindowOrdinal(0), ref events, .. }]
if window == a && events.len() == 2
));
assert!(call(&mut state, 1, 3, click(0, None)).is_empty());
assert_eq!(state.feed(a).events.len(), 2);
assert!(state.feed(a).os_keyboard);
let sent = state.os_keys_sent(ClientId(1), RequestId(2), WindowOrdinal(0), Ok(2));
assert!(done_reply(&sent, 2));
let failed = state.os_keys_sent(
ClientId(1),
RequestId(4),
WindowOrdinal(0),
Err("no X".to_owned()),
);
assert_eq!(code(&failed), Some(ErrorCode::Refused));
}
#[test]
fn a_client_without_the_os_keyboard_sends_keys_through_the_root() {
let mut state = state().with_os_keyboard(Ok(()));
hello(&mut state, 1);
let (a, _) = two_windows(&mut state);
let keys = Input {
window: WindowOrdinal(0),
events: vec![key(true)],
guard: None,
};
assert!(call(&mut state, 1, 2, keys).is_empty());
assert_eq!(state.feed(a).events.len(), 1);
assert!(!state.feed(a).os_keyboard);
}
#[test]
fn delivered_keys_reach_key_listeners_with_their_status_and_pointer_events_do_not() {
use futures::{FutureExt, StreamExt};
use iced_core::event::Status;
use iced_program::futures::subscription;
let hub = Arc::new(KeyHub::new());
let mut listener = hub.subscribe();
let mut state = state().with_keys(Arc::clone(&hub));
hello(&mut state, 1);
let (a, _) = two_windows(&mut state);
let input = Input {
window: WindowOrdinal(0),
events: vec![
WireEvent::CursorMoved {
position: Point::new(5.0, 5.0),
},
key(true),
key(false),
],
guard: None,
};
assert!(call(&mut state, 1, 2, input).is_empty());
let queued: Vec<Event> = state
.feed(a)
.events
.iter()
.map(|(_, e)| e.clone())
.collect();
let mut next = || listener.next().now_or_never().flatten();
assert_eq!(next(), None);
let _ = state.delivered(
a,
2,
vec![(1, WireStatus::Ignored), (2, WireStatus::Ignored)],
Vec::new(),
);
let heard = |event: &Event, status| subscription::Event::Interaction {
window: a,
event: event.clone(),
status,
};
assert_eq!(next(), Some(heard(&queued[1], Status::Ignored)));
assert_eq!(next(), None);
let _ = state.delivered(a, 3, vec![(3, WireStatus::Captured)], Vec::new());
assert_eq!(next(), Some(heard(&queued[2], Status::Captured)));
assert_eq!(next(), None);
}
}