diff --git a/src/frontend.rs b/src/frontend.rs index b9aeb0ac..fe0b62a4 100644 --- a/src/frontend.rs +++ b/src/frontend.rs @@ -84,34 +84,39 @@ pub fn wait_for_service() -> Result { } #[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] -pub enum FrontendEvent { +pub enum FrontendRequest { /// add a new client - AddClient(Option, u16, Position), + Create(Option, u16, Position), /// activate/deactivate client - ActivateClient(ClientHandle, bool), + Activate(ClientHandle, bool), /// change the listen port (recreate udp listener) ChangePort(u16), /// remove a client - DelClient(ClientHandle), - /// request an enumertaion of all clients + Delete(ClientHandle), + /// request an enumeration of all clients Enumerate(), /// service shutdown - Shutdown(), + Terminate(), /// update a client (hostname, port, position) - UpdateClient(ClientHandle, Option, u16, Position), + Update(ClientHandle, Option, u16, Position), } #[derive(Debug, Clone, Serialize, Deserialize)] -pub enum FrontendNotify { - NotifyClientActivate(ClientHandle, bool), - NotifyClientCreate(Client), - NotifyClientUpdate(Client), - NotifyClientDelete(ClientHandle), +pub enum FrontendEvent { + /// the given client was activated + Activated(ClientHandle, bool), + /// a client was created + Created(Client), + /// a client was updated + Updated(Client), + /// the client was deleted + Deleted(ClientHandle), /// new port, reason of failure (if failed) - NotifyPortChange(u16, Option), - /// Client State, active + PortChanged(u16, Option), + /// list of all clients, used for initial state synchronization Enumerate(Vec<(Client, bool)>), - NotifyError(String), + /// an error occured + Error(String), } pub struct FrontendListener { @@ -217,7 +222,7 @@ impl FrontendListener { Ok(rx) } - pub(crate) async fn notify_all(&mut self, notify: FrontendNotify) -> Result<()> { + pub(crate) async fn broadcast_event(&mut self, notify: FrontendEvent) -> Result<()> { // encode event let json = serde_json::to_string(¬ify).unwrap(); let payload = json.as_bytes(); @@ -255,7 +260,7 @@ impl Drop for FrontendListener { } #[cfg(unix)] -pub async fn read_event(stream: &mut ReadHalf) -> Result { +pub async fn wait_for_request(stream: &mut ReadHalf) -> Result { let len = stream.read_u64().await?; assert!(len <= 256); let mut buf = [0u8; 256]; @@ -264,7 +269,7 @@ pub async fn read_event(stream: &mut ReadHalf) -> Result) -> Result { +pub async fn wait_for_request(stream: &mut ReadHalf) -> Result { let len = stream.read_u64().await?; let mut buf = [0u8; 256]; stream.read_exact(&mut buf[..len as usize]).await?; diff --git a/src/frontend/cli.rs b/src/frontend/cli.rs index a7666d2a..b3b537b0 100644 --- a/src/frontend/cli.rs +++ b/src/frontend/cli.rs @@ -8,7 +8,7 @@ use std::{ use crate::{client::Position, config::DEFAULT_PORT}; -use super::{FrontendEvent, FrontendNotify}; +use super::{FrontendEvent, FrontendRequest}; pub fn run() -> Result<()> { let Ok(mut tx) = super::wait_for_service() else { @@ -38,7 +38,7 @@ pub fn run() -> Result<()> { if let Err(e) = tx.write(bytes) { log::error!("error sending message: {e}"); }; - if *event == FrontendEvent::Shutdown() { + if *event == FrontendRequest::Terminate() { return; } } @@ -78,39 +78,39 @@ pub fn run() -> Result<()> { Err(e) => break log::error!("{e}"), }; - let notify: FrontendNotify = match serde_json::from_slice(&buf) { + let notify: FrontendEvent = match serde_json::from_slice(&buf) { Ok(n) => n, Err(e) => break log::error!("{e}"), }; match notify { - FrontendNotify::NotifyClientActivate(handle, active) => { + FrontendEvent::Activated(handle, active) => { if active { log::info!("client {handle} activated"); } else { log::info!("client {handle} deactivated"); } } - FrontendNotify::NotifyClientCreate(client) => { + FrontendEvent::Created(client) => { let handle = client.handle; let port = client.port; let pos = client.pos; let hostname = client.hostname.as_deref().unwrap_or(""); log::info!("new client ({handle}): {hostname}:{port} - {pos}"); } - FrontendNotify::NotifyClientUpdate(client) => { + FrontendEvent::Updated(client) => { let handle = client.handle; let port = client.port; let pos = client.pos; let hostname = client.hostname.as_deref().unwrap_or(""); log::info!("client ({handle}) updated: {hostname}:{port} - {pos}"); } - FrontendNotify::NotifyClientDelete(client) => { + FrontendEvent::Deleted(client) => { log::info!("client ({client}) deleted."); } - FrontendNotify::NotifyError(e) => { + FrontendEvent::Error(e) => { log::warn!("{e}"); } - FrontendNotify::Enumerate(clients) => { + FrontendEvent::Enumerate(clients) => { for (client, active) in clients.into_iter() { log::info!( "client ({}) [{}]: active: {}, associated addresses: [{}]", @@ -126,7 +126,7 @@ pub fn run() -> Result<()> { ); } } - FrontendNotify::NotifyPortChange(port, msg) => match msg { + FrontendEvent::PortChanged(port, msg) => match msg { Some(msg) => log::info!("could not change port: {msg}"), None => log::info!("port changed: {port}"), }, @@ -153,9 +153,9 @@ fn prompt() { std::io::stderr().flush().unwrap(); } -fn parse_cmd(s: String, len: usize) -> Option> { +fn parse_cmd(s: String, len: usize) -> Option> { if len == 0 { - return Some(vec![FrontendEvent::Shutdown()]); + return Some(vec![FrontendRequest::Terminate()]); } let mut l = s.split_whitespace(); let cmd = l.next()?; @@ -170,8 +170,8 @@ fn parse_cmd(s: String, len: usize) -> Option> { log::info!("setport change port"); None } - "exit" => return Some(vec![FrontendEvent::Shutdown()]), - "list" => return Some(vec![FrontendEvent::Enumerate()]), + "exit" => return Some(vec![FrontendRequest::Terminate()]), + "list" => return Some(vec![FrontendRequest::Enumerate()]), "connect" => Some(parse_connect(l)), "disconnect" => Some(parse_disconnect(l)), "activate" => Some(parse_activate(l)), @@ -192,7 +192,7 @@ fn parse_cmd(s: String, len: usize) -> Option> { } } -fn parse_connect(mut l: SplitWhitespace) -> Result> { +fn parse_connect(mut l: SplitWhitespace) -> Result> { let usage = "usage: connect left|right|top|bottom [port]"; let host = l.next().context(usage)?.to_owned(); let pos = match l.next().context(usage)? { @@ -207,36 +207,36 @@ fn parse_connect(mut l: SplitWhitespace) -> Result> { DEFAULT_PORT }; Ok(vec![ - FrontendEvent::AddClient(Some(host), port, pos), - FrontendEvent::Enumerate(), + FrontendRequest::Create(Some(host), port, pos), + FrontendRequest::Enumerate(), ]) } -fn parse_disconnect(mut l: SplitWhitespace) -> Result> { +fn parse_disconnect(mut l: SplitWhitespace) -> Result> { let client = l.next().context("usage: disconnect ")?.parse()?; Ok(vec![ - FrontendEvent::DelClient(client), - FrontendEvent::Enumerate(), + FrontendRequest::Delete(client), + FrontendRequest::Enumerate(), ]) } -fn parse_activate(mut l: SplitWhitespace) -> Result> { +fn parse_activate(mut l: SplitWhitespace) -> Result> { let client = l.next().context("usage: activate ")?.parse()?; Ok(vec![ - FrontendEvent::ActivateClient(client, true), - FrontendEvent::Enumerate(), + FrontendRequest::Activate(client, true), + FrontendRequest::Enumerate(), ]) } -fn parse_deactivate(mut l: SplitWhitespace) -> Result> { +fn parse_deactivate(mut l: SplitWhitespace) -> Result> { let client = l.next().context("usage: deactivate ")?.parse()?; Ok(vec![ - FrontendEvent::ActivateClient(client, false), - FrontendEvent::Enumerate(), + FrontendRequest::Activate(client, false), + FrontendRequest::Enumerate(), ]) } -fn parse_port(mut l: SplitWhitespace) -> Result> { +fn parse_port(mut l: SplitWhitespace) -> Result> { let port = l.next().context("usage: setport ")?.parse()?; - Ok(vec![FrontendEvent::ChangePort(port)]) + Ok(vec![FrontendRequest::ChangePort(port)]) } diff --git a/src/frontend/gtk.rs b/src/frontend/gtk.rs index a074aa4c..0ccada3e 100644 --- a/src/frontend/gtk.rs +++ b/src/frontend/gtk.rs @@ -18,7 +18,7 @@ use gtk::{gio, glib, prelude::ApplicationExt}; use self::client_object::ClientObject; -use super::FrontendNotify; +use super::FrontendEvent; pub fn run() -> glib::ExitCode { log::debug!("running gtk frontend"); @@ -119,22 +119,22 @@ fn build_ui(app: &Application) { loop { let notify = receiver.recv().await.unwrap_or_else(|_| process::exit(1)); match notify { - FrontendNotify::NotifyClientActivate(handle, active) => { + FrontendEvent::Activated(handle, active) => { window.activate_client(handle, active); } - FrontendNotify::NotifyClientCreate(client) => { + FrontendEvent::Created(client) => { window.new_client(client, false); }, - FrontendNotify::NotifyClientUpdate(client) => { + FrontendEvent::Updated(client) => { window.update_client(client); } - FrontendNotify::NotifyError(e) => { + FrontendEvent::Error(e) => { window.show_toast(e.as_str()); }, - FrontendNotify::NotifyClientDelete(client) => { + FrontendEvent::Deleted(client) => { window.delete_client(client); } - FrontendNotify::Enumerate(clients) => { + FrontendEvent::Enumerate(clients) => { for (client, active) in clients { if window.client_idx(client.handle).is_some() { window.activate_client(client.handle, active); @@ -144,7 +144,7 @@ fn build_ui(app: &Application) { } } }, - FrontendNotify::NotifyPortChange(port, msg) => { + FrontendEvent::PortChanged(port, msg) => { match msg { None => window.show_toast(format!("port changed: {port}").as_str()), Some(msg) => window.show_toast(msg.as_str()), diff --git a/src/frontend/gtk/window.rs b/src/frontend/gtk/window.rs index 72a89db7..f0aa0f6d 100644 --- a/src/frontend/gtk/window.rs +++ b/src/frontend/gtk/window.rs @@ -14,7 +14,7 @@ use gtk::{ use crate::{ client::{Client, ClientHandle, Position}, config::DEFAULT_PORT, - frontend::{gtk::client_object::ClientObject, FrontendEvent}, + frontend::{gtk::client_object::ClientObject, FrontendRequest}, }; use super::client_row::ClientRow; @@ -152,7 +152,7 @@ impl Window { } pub fn request_client_create(&self) { - let event = FrontendEvent::AddClient(None, DEFAULT_PORT, Position::default()); + let event = FrontendRequest::Create(None, DEFAULT_PORT, Position::default()); self.imp().set_port(DEFAULT_PORT); self.request(event); } @@ -160,9 +160,9 @@ impl Window { pub fn request_port_change(&self) { let port = self.imp().port_entry.get().text().to_string(); if let Ok(port) = port.as_str().parse::() { - self.request(FrontendEvent::ChangePort(port)); + self.request(FrontendRequest::ChangePort(port)); } else { - self.request(FrontendEvent::ChangePort(DEFAULT_PORT)); + self.request(FrontendRequest::ChangePort(DEFAULT_PORT)); } } @@ -178,11 +178,11 @@ impl Window { let hostname = data.hostname; let port = data.port as u16; - let event = FrontendEvent::UpdateClient(client.handle(), hostname, port, position); + let event = FrontendRequest::Update(client.handle(), hostname, port, position); log::debug!("requesting update: {event:?}"); self.request(event); - let event = FrontendEvent::ActivateClient(client.handle(), active); + let event = FrontendRequest::Activate(client.handle(), active); log::debug!("requesting activate: {event:?}"); self.request(event); } @@ -193,12 +193,12 @@ impl Window { .downcast_ref() .expect("Expected object of type `ClientObject`."); let handle = client_object.handle(); - let event = FrontendEvent::DelClient(handle); + let event = FrontendRequest::Delete(handle); self.request(event); } } - fn request(&self, event: FrontendEvent) { + fn request(&self, event: FrontendRequest) { let json = serde_json::to_string(&event).unwrap(); log::debug!("requesting {json}"); let mut stream = self.imp().stream.borrow_mut(); diff --git a/src/server.rs b/src/server.rs index 454556e9..4b2f28c1 100644 --- a/src/server.rs +++ b/src/server.rs @@ -10,7 +10,7 @@ use crate::{ client::{ClientHandle, ClientManager}, config::Config, dns, - frontend::{FrontendEvent, FrontendListener}, + frontend::{FrontendListener, FrontendRequest}, server::capture_task::CaptureEvent, }; @@ -144,7 +144,7 @@ impl Server { .collect::>(); for (handle, hostname) in active { frontend_tx - .send(FrontendEvent::ActivateClient(handle, true)) + .send(FrontendRequest::Activate(handle, true)) .await?; if let Some(hostname) = hostname { let _ = resolve_tx.send(DnsRequest { hostname, handle }).await; @@ -178,7 +178,7 @@ impl Server { let _ = emulate_channel.send(EmulationEvent::Terminate).await; let _ = capture_channel.send(CaptureEvent::Terminate).await; - let _ = frontend_tx.send(FrontendEvent::Shutdown()).await; + let _ = frontend_tx.send(FrontendRequest::Terminate()).await; if !capture_task.is_finished() { if let Err(e) = capture_task.await { diff --git a/src/server/frontend_task.rs b/src/server/frontend_task.rs index 21b606d5..3179a695 100644 --- a/src/server/frontend_task.rs +++ b/src/server/frontend_task.rs @@ -18,7 +18,7 @@ use tokio::{ use crate::{ client::{ClientEvent, ClientHandle, Position}, - frontend::{self, FrontendEvent, FrontendListener, FrontendNotify}, + frontend::{self, FrontendEvent, FrontendListener, FrontendRequest}, }; use super::{ @@ -27,13 +27,13 @@ use super::{ pub(crate) fn new( mut frontend: FrontendListener, - mut notify_rx: Receiver, + mut notify_rx: Receiver, server: Server, capture: Sender, emulate: Sender, resolve_ch: Sender, port_tx: Sender, -) -> (JoinHandle>, Sender) { +) -> (JoinHandle>, Sender) { let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(32); let event_tx_clone = event_tx.clone(); let frontend_task = tokio::task::spawn_local(async move { @@ -57,7 +57,7 @@ pub(crate) fn new( } notify = notify_rx.recv() => { let notify = notify.ok_or(anyhow!("frontend notify closed"))?; - let _ = frontend.notify_all(notify).await; + let _ = frontend.broadcast_event(notify).await; } } } @@ -67,7 +67,7 @@ pub(crate) fn new( } async fn handle_frontend_stream( - frontend_tx: &Sender, + frontend_tx: &Sender, #[cfg(unix)] mut stream: ReadHalf, #[cfg(windows)] mut stream: ReadHalf, ) { @@ -75,9 +75,9 @@ async fn handle_frontend_stream( let tx = frontend_tx.clone(); tokio::task::spawn_local(async move { - let _ = tx.send(FrontendEvent::Enumerate()).await; + let _ = tx.send(FrontendRequest::Enumerate()).await; loop { - let event = frontend::read_event(&mut stream).await; + let event = frontend::wait_for_request(&mut stream).await; match event { Ok(event) => { let _ = tx.send(event).await; @@ -103,11 +103,11 @@ async fn handle_frontend_event( resolve_tx: &Sender, frontend: &mut FrontendListener, port_tx: &Sender, - event: FrontendEvent, + event: FrontendRequest, ) -> bool { log::debug!("frontend: {event:?}"); match event { - FrontendEvent::AddClient(hostname, port, pos) => { + FrontendRequest::Create(hostname, port, pos) => { add_client( server, frontend, @@ -119,33 +119,33 @@ async fn handle_frontend_event( ) .await; } - FrontendEvent::ActivateClient(handle, active) => { + FrontendRequest::Activate(handle, active) => { if active { activate_client(server, frontend, capture_tx, emulate_tx, handle).await; } else { deactivate_client(server, frontend, capture_tx, emulate_tx, handle).await; } } - FrontendEvent::ChangePort(port) => { + FrontendRequest::ChangePort(port) => { let _ = port_tx.send(port).await; } - FrontendEvent::DelClient(handle) => { + FrontendRequest::Delete(handle) => { remove_client(server, frontend, capture_tx, emulate_tx, handle).await; } - FrontendEvent::Enumerate() => { + FrontendRequest::Enumerate() => { let clients = server .client_manager .borrow() .get_client_states() .map(|s| (s.client.clone(), s.active)) .collect(); - notify_all(frontend, FrontendNotify::Enumerate(clients)).await; + notify_all(frontend, FrontendEvent::Enumerate(clients)).await; } - FrontendEvent::Shutdown() => { + FrontendRequest::Terminate() => { log::info!("terminating gracefully..."); return true; } - FrontendEvent::UpdateClient(handle, hostname, port, pos) => { + FrontendRequest::Update(handle, hostname, port, pos) => { update_client( server, frontend, @@ -160,8 +160,8 @@ async fn handle_frontend_event( false } -async fn notify_all(frontend: &mut FrontendListener, event: FrontendNotify) { - if let Err(e) = frontend.notify_all(event).await { +async fn notify_all(frontend: &mut FrontendListener, event: FrontendEvent) { + if let Err(e) = frontend.broadcast_event(event).await { log::error!("error notifying frontend: {e}"); } } @@ -199,7 +199,7 @@ pub async fn add_client( .unwrap() .client .clone(); - notify_all(frontend, FrontendNotify::NotifyClientCreate(client)).await; + notify_all(frontend, FrontendEvent::Created(client)).await; } pub async fn deactivate_client( @@ -220,7 +220,7 @@ pub async fn deactivate_client( let event = ClientEvent::Destroy(client); let _ = capture.send(CaptureEvent::ClientEvent(event)).await; let _ = emulate.send(EmulationEvent::ClientEvent(event)).await; - let event = FrontendNotify::NotifyClientActivate(client, false); + let event = FrontendEvent::Activated(client, false); notify_all(frontend, event).await; } @@ -256,7 +256,7 @@ pub async fn activate_client( let event = ClientEvent::Create(handle, pos); let _ = capture.send(CaptureEvent::ClientEvent(event)).await; let _ = emulate.send(EmulationEvent::ClientEvent(event)).await; - let event = FrontendNotify::NotifyClientActivate(handle, true); + let event = FrontendEvent::Activated(handle, true); notify_all(frontend, event).await; } @@ -282,7 +282,7 @@ pub async fn remove_client( let _ = emulate.send(EmulationEvent::ClientEvent(destroy)).await; } - let event = FrontendNotify::NotifyClientDelete(client); + let event = FrontendEvent::Deleted(client); notify_all(frontend, event).await; } @@ -358,5 +358,5 @@ async fn update_client( .unwrap() .client .clone(); - notify_all(frontend, FrontendNotify::NotifyClientUpdate(client)).await; + notify_all(frontend, FrontendEvent::Updated(client)).await; } diff --git a/src/server/network_task.rs b/src/server/network_task.rs index f2413ba9..1b85ee66 100644 --- a/src/server/network_task.rs +++ b/src/server/network_task.rs @@ -7,13 +7,13 @@ use tokio::{ task::JoinHandle, }; -use crate::{event::Event, frontend::FrontendNotify}; +use crate::{event::Event, frontend::FrontendEvent}; use super::Server; pub async fn new( server: Server, - frontend_notify_tx: Sender, + frontend_notify_tx: Sender, ) -> Result<( JoinHandle<()>, Sender<(Event, SocketAddr)>, @@ -55,12 +55,12 @@ pub async fn new( Ok(new_socket) => { socket = new_socket; server.port.replace(port); - let _ = frontend_notify_tx.send(FrontendNotify::NotifyPortChange(port, None)).await; + let _ = frontend_notify_tx.send(FrontendEvent::PortChanged(port, None)).await; } Err(e) => { log::warn!("could not change port: {e}"); let port = socket.local_addr().unwrap().port(); - let _ = frontend_notify_tx.send(FrontendNotify::NotifyPortChange( + let _ = frontend_notify_tx.send(FrontendEvent::PortChanged( port, Some(format!("could not change port: {e}")), )).await;