use std::collections::BTreeMap;
use std::fmt;
use std::path::Path;
use std::sync::{Arc, Mutex, PoisonError};
use futures::channel::mpsc;
use futures::stream::{self, BoxStream, StreamExt};
use iced_core::window;
use iced_core::{Element, Settings, theme};
use iced_program::Program;
use iced_program::futures::Subscription;
use iced_program::runtime::{Task, task};
use icedwright_protocol::{
Attachment, CursorReading, ErrorBody, Notification, RequestId, WireFrame,
};
use icedwright_types::Size;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use super::collect::{Collect, Generations, Recording, Slot, take};
use super::dispatch::{ClientId, Effect, ProbeState, dispatch};
use super::endpoint::{Inbound, Outbox, spawn_acceptor};
use super::policy::{Decision, ENV, Startup, decide};
use super::root::Root;
use super::tasks::{RemoteExecutor, TaskHub, install_global, resolver};
use super::transport::UnixEndpoint;
use crate::TaskName;
const EXIT_ON_BYE: &str = "ICEDWRIGHT_REMOTE_EXIT_ON_BYE";
#[derive(Debug)]
pub enum ProbeMessage {
Inbound(Vec<Inbound>),
Delivered {
window: window::Id,
through: u64,
statuses: Vec<(u64, icedwright_protocol::WireStatus)>,
cursors: Vec<CursorReading>,
},
Collected(Option<Recording>),
Shot {
client: ClientId,
id: RequestId,
window: window::Id,
shot: Option<window::Screenshot>,
},
Window(window::Id, window::Event),
OsKeysSent {
client: ClientId,
id: RequestId,
window: icedwright_protocol::WindowOrdinal,
sent: Result<usize, String>,
},
Observed {
window: window::Id,
event: iced_core::Event,
status: icedwright_protocol::WireStatus,
},
Pointed {
window: window::Id,
position: iced_core::Point,
pick: bool,
},
}
#[derive(Debug)]
pub enum Wrapped<M> {
App(M),
Probe(ProbeMessage),
}
pub struct RemoteState<S> {
app: S,
core: Core,
}
impl<S> fmt::Debug for RemoteState<S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RemoteState")
.field("probe", &self.core.probe)
.field("clients", &self.core.outboxes.len())
.finish_non_exhaustive()
}
}
impl<S> RemoteState<S> {
#[must_use]
pub fn app(&self) -> &S {
&self.app
}
}
pub struct Remote<P> {
program: P,
hub: Arc<TaskHub>,
live: bool,
exit_on_bye: bool,
}
impl<P> fmt::Debug for Remote<P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Remote")
.field("live", &self.live)
.finish_non_exhaustive()
}
}
pub fn attach<P: Program>(program: P) -> Remote<P> {
Remote {
program,
hub: Arc::new(TaskHub::new()),
live: false,
exit_on_bye: false,
}
}
pub fn run<P>(program: P) -> Result<(), iced_winit::Error>
where
P: Program + 'static,
P::Theme: theme::Base + 'static,
P::Renderer: 'static,
{
attach(program).run()
}
static INBOX: Mutex<Option<mpsc::UnboundedReceiver<Inbound>>> = Mutex::new(None);
fn inbox() -> BoxStream<'static, ProbeMessage> {
let receiver = INBOX.lock().unwrap_or_else(PoisonError::into_inner).take();
match receiver {
Some(receiver) => receiver.ready_chunks(64).map(ProbeMessage::Inbound).boxed(),
None => stream::pending().boxed(),
}
}
impl<P: Program> Remote<P> {
#[must_use]
pub fn resolvable<N: TaskName>(self) -> Self
where
N::Output: DeserializeOwned,
{
self.hub.register(N::NAME, resolver::<N>());
self
}
pub fn run(self) -> Result<(), iced_winit::Error>
where
P: 'static,
P::Theme: theme::Base + 'static,
P::Renderer: 'static,
{
iced_winit::run(self.open())
}
fn open(mut self) -> Self {
if let Some(opened) = open_endpoint(P::name(), &self.hub) {
self.hub = opened.hub;
self.live = true;
self.exit_on_bye = opened.exit_on_bye;
}
self
}
}
struct Opened {
hub: Arc<TaskHub>,
exit_on_bye: bool,
}
fn open_endpoint(app: &str, hub: &Arc<TaskHub>) -> Option<Opened> {
let env = std::env::var_os(ENV);
let runtime = std::env::var_os("XDG_RUNTIME_DIR");
let startup = Startup {
debug_assertions: cfg!(debug_assertions),
allow_in_release: cfg!(feature = "remote-in-release"),
remote_env: env.as_deref(),
runtime_dir: runtime.as_deref().map(Path::new),
app,
pid: std::process::id(),
};
let plan = match decide(&startup) {
Ok(Decision::Off) => return None,
Ok(Decision::Listen(plan)) => plan,
Err(refusal) => {
eprintln!("icedwright-remote: refused: {refusal}");
return None;
}
};
let endpoint = match UnixEndpoint::bind(&plan) {
Ok(endpoint) => endpoint,
Err(refusal) => {
eprintln!("icedwright-remote: refused: {refusal}");
return None;
}
};
let path = endpoint.path().display().to_string();
let (sender, receiver) = mpsc::unbounded();
let hub = install_global(Arc::clone(hub));
let tasks = sender.clone();
hub.listen(move |event| {
let _ = tasks.unbounded_send(Inbound::Task(event));
});
let sink = move |inbound| sender.unbounded_send(inbound).is_ok();
if let Err(error) = spawn_acceptor(Box::new(endpoint), sink) {
eprintln!("icedwright-remote: refused: the socket thread did not start: {error}");
return None;
}
*INBOX.lock().unwrap_or_else(PoisonError::into_inner) = Some(receiver);
if cfg!(not(debug_assertions)) {
eprintln!("icedwright-remote: warning: the endpoint is open in a release build");
}
eprintln!("icedwright-remote: listening on {path}");
Some(Opened {
hub,
exit_on_bye: std::env::var_os(EXIT_ON_BYE).is_some_and(|v| v == "1"),
})
}
#[derive(Debug)]
struct Core {
probe: ProbeState,
outboxes: BTreeMap<ClientId, Outbox>,
}
impl Core {
fn new(app: &str, hub: &Arc<TaskHub>, exit_on_bye: bool) -> Self {
Self {
probe: ProbeState::new(app, std::process::id(), Arc::clone(hub), exit_on_bye)
.with_os_keyboard(super::oskeys::support()),
outboxes: BTreeMap::new(),
}
}
fn set_titles(&mut self, titles: Vec<(window::Id, String)>) {
for (id, title) in titles {
self.probe.set_title(id, title);
}
}
fn handle(
&mut self,
message: ProbeMessage,
titles: &dyn Fn(&ProbeState) -> Vec<(window::Id, String)>,
) -> Vec<Effect> {
match message {
ProbeMessage::Inbound(batch) => {
self.set_titles(titles(&self.probe));
let mut effects = Vec::new();
for inbound in batch {
effects.extend(self.inbound(inbound));
}
effects
}
ProbeMessage::Delivered {
window,
through,
statuses,
cursors,
} => self.probe.delivered(window, through, statuses, cursors),
ProbeMessage::Collected(recording) => {
self.set_titles(titles(&self.probe));
self.probe.collected(recording.unwrap_or_default())
}
ProbeMessage::Shot {
client,
id,
window,
shot,
} => self.probe.screenshot_taken(client, id, window, shot),
ProbeMessage::Window(id, event) => match event {
window::Event::Opened { size, .. } => {
let effects = self
.probe
.window_opened(id, Size::new(size.width, size.height));
self.set_titles(titles(&self.probe));
effects
}
window::Event::Resized(size) => {
self.probe
.window_resized(id, Size::new(size.width, size.height));
Vec::new()
}
window::Event::Rescaled(factor) => {
self.probe.window_rescaled(id, factor);
Vec::new()
}
window::Event::Closed => self.probe.window_closed(id),
_ => Vec::new(),
},
ProbeMessage::OsKeysSent {
client,
id,
window,
sent,
} => self.probe.os_keys_sent(client, id, window, sent),
ProbeMessage::Observed {
window,
event,
status,
} => self.probe.observed(window, &event, status),
ProbeMessage::Pointed {
window,
position,
pick,
} => self.probe.pointed(
window,
icedwright_types::Point::new(position.x, position.y),
pick,
),
}
}
fn inbound(&mut self, inbound: Inbound) -> Vec<Effect> {
match inbound {
Inbound::Opened { client, outbox } => {
self.outboxes.insert(client, outbox);
Vec::new()
}
Inbound::Call {
client,
id,
method,
params,
} => dispatch(&mut self.probe, client, id, &method, params),
Inbound::Malformed {
client,
id: Some(id),
message,
} => vec![Effect::Reply {
client,
id,
result: Err(ErrorBody::new(
icedwright_protocol::ErrorCode::BadRequest,
message,
)),
attachment: None,
}],
Inbound::Malformed { id: None, .. } => Vec::new(),
Inbound::Closed { client } => {
self.outboxes.remove(&client);
self.probe.client_closed(client)
}
Inbound::Task(event) => self.probe.task_event(event),
}
}
fn subscription() -> Subscription<ProbeMessage> {
Subscription::batch([
Subscription::run(inbox),
iced_program::runtime::window::events()
.map(|(id, event)| ProbeMessage::Window(id, event)),
])
}
}
pub struct Probe {
core: Core,
titles: BTreeMap<window::Id, String>,
}
impl fmt::Debug for Probe {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Probe")
.field("probe", &self.core.probe)
.field("clients", &self.core.outboxes.len())
.finish_non_exhaustive()
}
}
impl Probe {
#[must_use]
pub fn from_env() -> Option<Self> {
let exe = std::env::current_exe().ok();
let app = exe
.as_deref()
.and_then(Path::file_stem)
.and_then(|stem| stem.to_str())
.unwrap_or("app")
.to_owned();
Self::open(&app, Arc::new(TaskHub::new()))
}
fn open(app: &str, hub: Arc<TaskHub>) -> Option<Self> {
let opened = open_endpoint(app, &hub)?;
Some(Self::with_hub(app, &opened.hub, opened.exit_on_bye))
}
fn with_hub(app: &str, hub: &Arc<TaskHub>, exit_on_bye: bool) -> Self {
Self {
core: Core::new(app, hub, exit_on_bye),
titles: BTreeMap::new(),
}
}
pub fn subscription(&self) -> Subscription<ProbeMessage> {
Core::subscription()
}
pub fn update(&mut self, message: ProbeMessage) -> Task<ProbeMessage> {
let titles = &self.titles;
let effects = self.core.handle(message, &|probe| {
probe
.window_ids()
.filter_map(|id| titles.get(&id).map(|title| (id, title.clone())))
.collect()
});
carry_out(&mut self.core, effects, std::convert::identity)
}
pub fn observe(&mut self) -> Task<ProbeMessage> {
let effects = self.core.probe.app_message();
carry_out(&mut self.core, effects, std::convert::identity)
}
pub fn set_title(&mut self, window: window::Id, title: impl Into<String>) {
let title = title.into();
self.core.probe.set_title(window, title.clone());
self.titles.insert(window, title);
}
pub fn root<'a, M: 'a, Theme: 'a, R: iced_core::Renderer + 'a>(
&'a self,
window: window::Id,
content: impl Into<Element<'a, M, Theme, R>>,
on_probe: fn(ProbeMessage) -> M,
) -> Element<'a, M, Theme, R> {
Root::new(window, self.core.probe.feed(window), content, on_probe).into()
}
}
fn frames_for(
id: RequestId,
result: Result<Value, ErrorBody>,
attachment: Option<Vec<u8>>,
) -> Vec<WireFrame> {
let mut reply = match result {
Ok(value) => json!({ "id": id, "result": value }),
Err(body) => json!({ "id": id, "error": body }),
};
let mut frames = Vec::new();
if let Some(bytes) = &attachment
&& let Some(object) = reply.as_object_mut()
{
let announce = Attachment {
bytes: u64::try_from(bytes.len()).unwrap_or(u64::MAX),
media: "image/x-rgba".into(),
};
object.insert(
"attachment".to_owned(),
serde_json::to_value(announce).unwrap_or(Value::Null),
);
}
let Ok(payload) = serde_json::to_vec(&reply) else {
return frames;
};
frames.push(WireFrame::json(payload));
if let Some(bytes) = attachment {
frames.push(WireFrame::binary(bytes));
}
frames
}
fn notification_frame(notification: &Notification) -> Option<WireFrame> {
serde_json::to_vec(notification).ok().map(WireFrame::json)
}
fn collect_task<T: Send + 'static>(
wrap: fn(ProbeMessage) -> T,
generations: Arc<Generations>,
) -> Task<T> {
let slot: Slot = Arc::default();
let read = Arc::clone(&slot);
task::widget(Collect::new(slot, generations))
.map(move |()| wrap(ProbeMessage::Collected(take(&read))))
}
fn carry_out<T: Send + 'static>(
core: &mut Core,
effects: Vec<Effect>,
wrap: fn(ProbeMessage) -> T,
) -> Task<T> {
let mut tasks = Vec::new();
for effect in effects {
match effect {
Effect::Reply {
client,
id,
result,
attachment,
} => {
let Some(outbox) = core.outboxes.get(&client) else {
continue;
};
if !outbox.send(frames_for(id, result, attachment)) {
core.outboxes.remove(&client);
}
}
Effect::Notify(notification) => {
let Some(frame) = notification_frame(¬ification) else {
continue;
};
core.outboxes
.retain(|_, outbox| outbox.send(vec![frame.clone()]));
}
Effect::Collect => tasks.push(collect_task(wrap, core.probe.generations())),
Effect::Screenshot { client, id, window } => tasks.push(
iced_program::runtime::window::screenshot(window)
.collect()
.map(move |shots| {
wrap(ProbeMessage::Shot {
client,
id,
window,
shot: shots.into_iter().next(),
})
}),
),
Effect::Focus(window) => tasks.push(iced_program::runtime::window::gain_focus(window)),
Effect::Close(client) => {
core.outboxes.remove(&client);
}
Effect::Size(window) => tasks.push(
iced_program::runtime::window::size(window).map(move |size| {
wrap(ProbeMessage::Window(window, window::Event::Resized(size)))
}),
),
Effect::Exit => tasks.push(iced_program::runtime::exit()),
Effect::OsKeys {
client,
id,
window,
ordinal,
events,
} => {
let send = iced_program::runtime::window::run(window, super::oskeys::x11_window)
.then(move |xid| {
let events = events.clone();
Task::perform(async move { send_os_keys(xid, &events) }, move |sent| {
wrap(ProbeMessage::OsKeysSent {
client,
id,
window: ordinal,
sent,
})
})
});
tasks.push(iced_program::runtime::window::gain_focus(window).chain(send));
}
}
}
Task::batch(tasks)
}
#[cfg(feature = "os-keyboard")]
fn send_os_keys(
window: Option<u32>,
events: &[icedwright_protocol::WireEvent],
) -> Result<usize, String> {
use super::oskeys::{KeyInjector, connect, inject};
static KEYBOARD: Mutex<Option<Box<dyn KeyInjector>>> = Mutex::new(None);
let mut keyboard = KEYBOARD.lock().unwrap_or_else(PoisonError::into_inner);
if keyboard.is_none() {
*keyboard = Some(connect()?);
}
let Some(injector) = keyboard.as_mut() else {
return Err("the OS keyboard is not connected".to_owned());
};
inject(injector.as_mut(), window, events)
}
#[cfg(not(feature = "os-keyboard"))]
fn send_os_keys(
_window: Option<u32>,
_events: &[icedwright_protocol::WireEvent],
) -> Result<usize, String> {
Err("this app was built without the probe's os-keyboard feature".to_owned())
}
fn wrap_probe<M>(message: ProbeMessage) -> Wrapped<M> {
Wrapped::Probe(message)
}
impl<P> Program for Remote<P>
where
P: Program,
P::Theme: 'static,
P::Renderer: 'static,
{
type State = RemoteState<P::State>;
type Message = Wrapped<P::Message>;
type Theme = P::Theme;
type Renderer = P::Renderer;
type Executor = RemoteExecutor<P::Executor>;
fn name() -> &'static str {
P::name()
}
fn settings(&self) -> Settings {
self.program.settings()
}
fn window(&self) -> Option<window::Settings> {
self.program.window()
}
fn boot(&self) -> (Self::State, Task<Self::Message>) {
let (app, task) = self.program.boot();
let state = RemoteState {
app,
core: Core::new(P::name(), &self.hub, self.exit_on_bye),
};
(state, task.map(Wrapped::App))
}
fn update(&self, state: &mut Self::State, message: Self::Message) -> Task<Self::Message> {
match message {
Wrapped::App(message) => {
let app = self
.program
.update(&mut state.app, message)
.map(Wrapped::App);
if !self.live {
return app;
}
let effects = state.core.probe.app_message();
Task::batch([app, carry_out(&mut state.core, effects, wrap_probe)])
}
Wrapped::Probe(message) => {
let (app, program) = (&state.app, &self.program);
let titles = |probe: &ProbeState| {
probe
.window_ids()
.map(|id| (id, program.title(app, id)))
.collect()
};
let effects = state.core.handle(message, &titles);
carry_out(&mut state.core, effects, wrap_probe)
}
}
}
fn view<'a>(
&self,
state: &'a Self::State,
window: window::Id,
) -> Element<'a, Self::Message, Self::Theme, Self::Renderer> {
let content = self.program.view(&state.app, window).map(Wrapped::App);
Root::new(
window,
state.core.probe.feed(window),
content,
Wrapped::Probe,
)
.into()
}
fn title(&self, state: &Self::State, window: window::Id) -> String {
self.program.title(&state.app, window)
}
fn subscription(&self, state: &Self::State) -> Subscription<Self::Message> {
let app = self.program.subscription(&state.app).map(Wrapped::App);
if !self.live {
return app;
}
Subscription::batch([app, Core::subscription().map(Wrapped::Probe)])
}
fn theme(&self, state: &Self::State, window: window::Id) -> Option<Self::Theme> {
self.program.theme(&state.app, window)
}
fn style(&self, state: &Self::State, theme: &Self::Theme) -> theme::Style {
self.program.style(&state.app, theme)
}
fn scale_factor(&self, state: &Self::State, window: window::Id) -> f32 {
self.program.scale_factor(&state.app, window)
}
}
#[cfg(test)]
mod tests {
use icedwright_protocol::{ErrorCode, Generation};
use super::*;
#[test]
fn a_reply_with_an_attachment_announces_it_before_the_bytes() -> Result<(), serde_json::Error> {
let frames = frames_for(RequestId(4), Ok(json!({ "w": 1 })), Some(vec![1, 2, 3, 4]));
assert_eq!(frames.len(), 2);
let first: Value = serde_json::from_slice(&frames[0].payload)?;
assert_eq!(first["id"], 4);
assert_eq!(first["attachment"]["bytes"], 4);
assert_eq!(first["attachment"]["media"], "image/x-rgba");
assert_eq!(frames[1], WireFrame::binary(vec![1, 2, 3, 4]));
Ok(())
}
fn hello_from(client: u64) -> Inbound {
Inbound::Call {
client: ClientId(client),
id: RequestId(1),
method: "hello".to_owned(),
params: json!({ "protocol": icedwright_protocol::PROTOCOL, "client": "test" }),
}
}
fn replies(frames: &std::sync::mpsc::Receiver<WireFrame>) -> Vec<Value> {
frames
.try_iter()
.filter_map(|frame| serde_json::from_slice(&frame.payload).ok())
.collect()
}
#[test]
fn the_three_call_probe_answers_hello_and_names_titled_windows() {
let mut probe = Probe::with_hub("demo", &Arc::new(TaskHub::new()), false);
let window = window::Id::unique();
let opened = window::Event::Opened {
position: None,
size: iced_core::Size::new(100.0, 50.0),
};
let _ = probe.update(ProbeMessage::Window(window, opened));
probe.set_title(window, "Main");
let (outbox, frames) = Outbox::channel();
let client = ClientId(3);
let _ = probe.update(ProbeMessage::Inbound(vec![
Inbound::Opened { client, outbox },
hello_from(3),
]));
let answers = replies(&frames);
assert_eq!(answers.len(), 1, "{answers:?}");
assert_eq!(answers[0]["result"]["app"], "demo");
assert_eq!(answers[0]["result"]["windows"][0]["title"], "Main");
}
#[test]
fn observing_an_app_message_notifies_clients_of_the_new_generation() {
let mut probe = Probe::with_hub("demo", &Arc::new(TaskHub::new()), false);
let (outbox, frames) = Outbox::channel();
let _ = probe.update(ProbeMessage::Inbound(vec![
Inbound::Opened {
client: ClientId(1),
outbox,
},
hello_from(1),
]));
let _ = replies(&frames);
assert_eq!(probe.core.probe.generation(), Generation(0));
let _ = probe.observe();
assert_eq!(probe.core.probe.generation(), Generation(1));
let pushed = replies(&frames);
assert_eq!(pushed.len(), 1, "{pushed:?}");
assert_eq!(pushed[0]["event"], "generation");
}
#[test]
fn an_error_reply_carries_its_code() -> Result<(), serde_json::Error> {
let frames = frames_for(
RequestId(1),
Err(ErrorBody::new(ErrorCode::Stale, "moved")),
None,
);
let reply: Value = serde_json::from_slice(&frames[0].payload)?;
assert_eq!(reply["error"]["code"], "stale");
assert!(reply.get("result").is_none());
Ok(())
}
}