Rename FrontendEvent to FrontendRequest (#111)

* rename frontend event and notify
* simplify event names
This commit is contained in:
Ferdinand Schober
2024-04-25 22:18:43 +02:00
committed by GitHub
parent 9edd2f7f3b
commit 279e582698
7 changed files with 97 additions and 92 deletions

View File

@@ -84,34 +84,39 @@ pub fn wait_for_service() -> Result<std::net::TcpStream> {
} }
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)] #[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum FrontendEvent { pub enum FrontendRequest {
/// add a new client /// add a new client
AddClient(Option<String>, u16, Position), Create(Option<String>, u16, Position),
/// activate/deactivate client /// activate/deactivate client
ActivateClient(ClientHandle, bool), Activate(ClientHandle, bool),
/// change the listen port (recreate udp listener) /// change the listen port (recreate udp listener)
ChangePort(u16), ChangePort(u16),
/// remove a client /// remove a client
DelClient(ClientHandle), Delete(ClientHandle),
/// request an enumertaion of all clients /// request an enumeration of all clients
Enumerate(), Enumerate(),
/// service shutdown /// service shutdown
Shutdown(), Terminate(),
/// update a client (hostname, port, position) /// update a client (hostname, port, position)
UpdateClient(ClientHandle, Option<String>, u16, Position), Update(ClientHandle, Option<String>, u16, Position),
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FrontendNotify { pub enum FrontendEvent {
NotifyClientActivate(ClientHandle, bool), /// the given client was activated
NotifyClientCreate(Client), Activated(ClientHandle, bool),
NotifyClientUpdate(Client), /// a client was created
NotifyClientDelete(ClientHandle), Created(Client),
/// a client was updated
Updated(Client),
/// the client was deleted
Deleted(ClientHandle),
/// new port, reason of failure (if failed) /// new port, reason of failure (if failed)
NotifyPortChange(u16, Option<String>), PortChanged(u16, Option<String>),
/// Client State, active /// list of all clients, used for initial state synchronization
Enumerate(Vec<(Client, bool)>), Enumerate(Vec<(Client, bool)>),
NotifyError(String), /// an error occured
Error(String),
} }
pub struct FrontendListener { pub struct FrontendListener {
@@ -217,7 +222,7 @@ impl FrontendListener {
Ok(rx) 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 // encode event
let json = serde_json::to_string(&notify).unwrap(); let json = serde_json::to_string(&notify).unwrap();
let payload = json.as_bytes(); let payload = json.as_bytes();
@@ -255,7 +260,7 @@ impl Drop for FrontendListener {
} }
#[cfg(unix)] #[cfg(unix)]
pub async fn read_event(stream: &mut ReadHalf<UnixStream>) -> Result<FrontendEvent> { pub async fn wait_for_request(stream: &mut ReadHalf<UnixStream>) -> Result<FrontendRequest> {
let len = stream.read_u64().await?; let len = stream.read_u64().await?;
assert!(len <= 256); assert!(len <= 256);
let mut buf = [0u8; 256]; let mut buf = [0u8; 256];
@@ -264,7 +269,7 @@ pub async fn read_event(stream: &mut ReadHalf<UnixStream>) -> Result<FrontendEve
} }
#[cfg(windows)] #[cfg(windows)]
pub async fn read_event(stream: &mut ReadHalf<TcpStream>) -> Result<FrontendEvent> { pub async fn wait_for_request(stream: &mut ReadHalf<TcpStream>) -> Result<FrontendRequest> {
let len = stream.read_u64().await?; let len = stream.read_u64().await?;
let mut buf = [0u8; 256]; let mut buf = [0u8; 256];
stream.read_exact(&mut buf[..len as usize]).await?; stream.read_exact(&mut buf[..len as usize]).await?;

View File

@@ -8,7 +8,7 @@ use std::{
use crate::{client::Position, config::DEFAULT_PORT}; use crate::{client::Position, config::DEFAULT_PORT};
use super::{FrontendEvent, FrontendNotify}; use super::{FrontendEvent, FrontendRequest};
pub fn run() -> Result<()> { pub fn run() -> Result<()> {
let Ok(mut tx) = super::wait_for_service() else { let Ok(mut tx) = super::wait_for_service() else {
@@ -38,7 +38,7 @@ pub fn run() -> Result<()> {
if let Err(e) = tx.write(bytes) { if let Err(e) = tx.write(bytes) {
log::error!("error sending message: {e}"); log::error!("error sending message: {e}");
}; };
if *event == FrontendEvent::Shutdown() { if *event == FrontendRequest::Terminate() {
return; return;
} }
} }
@@ -78,39 +78,39 @@ pub fn run() -> Result<()> {
Err(e) => break log::error!("{e}"), 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, Ok(n) => n,
Err(e) => break log::error!("{e}"), Err(e) => break log::error!("{e}"),
}; };
match notify { match notify {
FrontendNotify::NotifyClientActivate(handle, active) => { FrontendEvent::Activated(handle, active) => {
if active { if active {
log::info!("client {handle} activated"); log::info!("client {handle} activated");
} else { } else {
log::info!("client {handle} deactivated"); log::info!("client {handle} deactivated");
} }
} }
FrontendNotify::NotifyClientCreate(client) => { FrontendEvent::Created(client) => {
let handle = client.handle; let handle = client.handle;
let port = client.port; let port = client.port;
let pos = client.pos; let pos = client.pos;
let hostname = client.hostname.as_deref().unwrap_or(""); let hostname = client.hostname.as_deref().unwrap_or("");
log::info!("new client ({handle}): {hostname}:{port} - {pos}"); log::info!("new client ({handle}): {hostname}:{port} - {pos}");
} }
FrontendNotify::NotifyClientUpdate(client) => { FrontendEvent::Updated(client) => {
let handle = client.handle; let handle = client.handle;
let port = client.port; let port = client.port;
let pos = client.pos; let pos = client.pos;
let hostname = client.hostname.as_deref().unwrap_or(""); let hostname = client.hostname.as_deref().unwrap_or("");
log::info!("client ({handle}) updated: {hostname}:{port} - {pos}"); log::info!("client ({handle}) updated: {hostname}:{port} - {pos}");
} }
FrontendNotify::NotifyClientDelete(client) => { FrontendEvent::Deleted(client) => {
log::info!("client ({client}) deleted."); log::info!("client ({client}) deleted.");
} }
FrontendNotify::NotifyError(e) => { FrontendEvent::Error(e) => {
log::warn!("{e}"); log::warn!("{e}");
} }
FrontendNotify::Enumerate(clients) => { FrontendEvent::Enumerate(clients) => {
for (client, active) in clients.into_iter() { for (client, active) in clients.into_iter() {
log::info!( log::info!(
"client ({}) [{}]: active: {}, associated addresses: [{}]", "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}"), Some(msg) => log::info!("could not change port: {msg}"),
None => log::info!("port changed: {port}"), None => log::info!("port changed: {port}"),
}, },
@@ -153,9 +153,9 @@ fn prompt() {
std::io::stderr().flush().unwrap(); std::io::stderr().flush().unwrap();
} }
fn parse_cmd(s: String, len: usize) -> Option<Vec<FrontendEvent>> { fn parse_cmd(s: String, len: usize) -> Option<Vec<FrontendRequest>> {
if len == 0 { if len == 0 {
return Some(vec![FrontendEvent::Shutdown()]); return Some(vec![FrontendRequest::Terminate()]);
} }
let mut l = s.split_whitespace(); let mut l = s.split_whitespace();
let cmd = l.next()?; let cmd = l.next()?;
@@ -170,8 +170,8 @@ fn parse_cmd(s: String, len: usize) -> Option<Vec<FrontendEvent>> {
log::info!("setport <port> change port"); log::info!("setport <port> change port");
None None
} }
"exit" => return Some(vec![FrontendEvent::Shutdown()]), "exit" => return Some(vec![FrontendRequest::Terminate()]),
"list" => return Some(vec![FrontendEvent::Enumerate()]), "list" => return Some(vec![FrontendRequest::Enumerate()]),
"connect" => Some(parse_connect(l)), "connect" => Some(parse_connect(l)),
"disconnect" => Some(parse_disconnect(l)), "disconnect" => Some(parse_disconnect(l)),
"activate" => Some(parse_activate(l)), "activate" => Some(parse_activate(l)),
@@ -192,7 +192,7 @@ fn parse_cmd(s: String, len: usize) -> Option<Vec<FrontendEvent>> {
} }
} }
fn parse_connect(mut l: SplitWhitespace) -> Result<Vec<FrontendEvent>> { fn parse_connect(mut l: SplitWhitespace) -> Result<Vec<FrontendRequest>> {
let usage = "usage: connect <host> left|right|top|bottom [port]"; let usage = "usage: connect <host> left|right|top|bottom [port]";
let host = l.next().context(usage)?.to_owned(); let host = l.next().context(usage)?.to_owned();
let pos = match l.next().context(usage)? { let pos = match l.next().context(usage)? {
@@ -207,36 +207,36 @@ fn parse_connect(mut l: SplitWhitespace) -> Result<Vec<FrontendEvent>> {
DEFAULT_PORT DEFAULT_PORT
}; };
Ok(vec![ Ok(vec![
FrontendEvent::AddClient(Some(host), port, pos), FrontendRequest::Create(Some(host), port, pos),
FrontendEvent::Enumerate(), FrontendRequest::Enumerate(),
]) ])
} }
fn parse_disconnect(mut l: SplitWhitespace) -> Result<Vec<FrontendEvent>> { fn parse_disconnect(mut l: SplitWhitespace) -> Result<Vec<FrontendRequest>> {
let client = l.next().context("usage: disconnect <client_id>")?.parse()?; let client = l.next().context("usage: disconnect <client_id>")?.parse()?;
Ok(vec![ Ok(vec![
FrontendEvent::DelClient(client), FrontendRequest::Delete(client),
FrontendEvent::Enumerate(), FrontendRequest::Enumerate(),
]) ])
} }
fn parse_activate(mut l: SplitWhitespace) -> Result<Vec<FrontendEvent>> { fn parse_activate(mut l: SplitWhitespace) -> Result<Vec<FrontendRequest>> {
let client = l.next().context("usage: activate <client_id>")?.parse()?; let client = l.next().context("usage: activate <client_id>")?.parse()?;
Ok(vec![ Ok(vec![
FrontendEvent::ActivateClient(client, true), FrontendRequest::Activate(client, true),
FrontendEvent::Enumerate(), FrontendRequest::Enumerate(),
]) ])
} }
fn parse_deactivate(mut l: SplitWhitespace) -> Result<Vec<FrontendEvent>> { fn parse_deactivate(mut l: SplitWhitespace) -> Result<Vec<FrontendRequest>> {
let client = l.next().context("usage: deactivate <client_id>")?.parse()?; let client = l.next().context("usage: deactivate <client_id>")?.parse()?;
Ok(vec![ Ok(vec![
FrontendEvent::ActivateClient(client, false), FrontendRequest::Activate(client, false),
FrontendEvent::Enumerate(), FrontendRequest::Enumerate(),
]) ])
} }
fn parse_port(mut l: SplitWhitespace) -> Result<Vec<FrontendEvent>> { fn parse_port(mut l: SplitWhitespace) -> Result<Vec<FrontendRequest>> {
let port = l.next().context("usage: setport <port>")?.parse()?; let port = l.next().context("usage: setport <port>")?.parse()?;
Ok(vec![FrontendEvent::ChangePort(port)]) Ok(vec![FrontendRequest::ChangePort(port)])
} }

View File

@@ -18,7 +18,7 @@ use gtk::{gio, glib, prelude::ApplicationExt};
use self::client_object::ClientObject; use self::client_object::ClientObject;
use super::FrontendNotify; use super::FrontendEvent;
pub fn run() -> glib::ExitCode { pub fn run() -> glib::ExitCode {
log::debug!("running gtk frontend"); log::debug!("running gtk frontend");
@@ -119,22 +119,22 @@ fn build_ui(app: &Application) {
loop { loop {
let notify = receiver.recv().await.unwrap_or_else(|_| process::exit(1)); let notify = receiver.recv().await.unwrap_or_else(|_| process::exit(1));
match notify { match notify {
FrontendNotify::NotifyClientActivate(handle, active) => { FrontendEvent::Activated(handle, active) => {
window.activate_client(handle, active); window.activate_client(handle, active);
} }
FrontendNotify::NotifyClientCreate(client) => { FrontendEvent::Created(client) => {
window.new_client(client, false); window.new_client(client, false);
}, },
FrontendNotify::NotifyClientUpdate(client) => { FrontendEvent::Updated(client) => {
window.update_client(client); window.update_client(client);
} }
FrontendNotify::NotifyError(e) => { FrontendEvent::Error(e) => {
window.show_toast(e.as_str()); window.show_toast(e.as_str());
}, },
FrontendNotify::NotifyClientDelete(client) => { FrontendEvent::Deleted(client) => {
window.delete_client(client); window.delete_client(client);
} }
FrontendNotify::Enumerate(clients) => { FrontendEvent::Enumerate(clients) => {
for (client, active) in clients { for (client, active) in clients {
if window.client_idx(client.handle).is_some() { if window.client_idx(client.handle).is_some() {
window.activate_client(client.handle, active); 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 { match msg {
None => window.show_toast(format!("port changed: {port}").as_str()), None => window.show_toast(format!("port changed: {port}").as_str()),
Some(msg) => window.show_toast(msg.as_str()), Some(msg) => window.show_toast(msg.as_str()),

View File

@@ -14,7 +14,7 @@ use gtk::{
use crate::{ use crate::{
client::{Client, ClientHandle, Position}, client::{Client, ClientHandle, Position},
config::DEFAULT_PORT, config::DEFAULT_PORT,
frontend::{gtk::client_object::ClientObject, FrontendEvent}, frontend::{gtk::client_object::ClientObject, FrontendRequest},
}; };
use super::client_row::ClientRow; use super::client_row::ClientRow;
@@ -152,7 +152,7 @@ impl Window {
} }
pub fn request_client_create(&self) { 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.imp().set_port(DEFAULT_PORT);
self.request(event); self.request(event);
} }
@@ -160,9 +160,9 @@ impl Window {
pub fn request_port_change(&self) { pub fn request_port_change(&self) {
let port = self.imp().port_entry.get().text().to_string(); let port = self.imp().port_entry.get().text().to_string();
if let Ok(port) = port.as_str().parse::<u16>() { if let Ok(port) = port.as_str().parse::<u16>() {
self.request(FrontendEvent::ChangePort(port)); self.request(FrontendRequest::ChangePort(port));
} else { } else {
self.request(FrontendEvent::ChangePort(DEFAULT_PORT)); self.request(FrontendRequest::ChangePort(DEFAULT_PORT));
} }
} }
@@ -178,11 +178,11 @@ impl Window {
let hostname = data.hostname; let hostname = data.hostname;
let port = data.port as u16; 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:?}"); log::debug!("requesting update: {event:?}");
self.request(event); self.request(event);
let event = FrontendEvent::ActivateClient(client.handle(), active); let event = FrontendRequest::Activate(client.handle(), active);
log::debug!("requesting activate: {event:?}"); log::debug!("requesting activate: {event:?}");
self.request(event); self.request(event);
} }
@@ -193,12 +193,12 @@ impl Window {
.downcast_ref() .downcast_ref()
.expect("Expected object of type `ClientObject`."); .expect("Expected object of type `ClientObject`.");
let handle = client_object.handle(); let handle = client_object.handle();
let event = FrontendEvent::DelClient(handle); let event = FrontendRequest::Delete(handle);
self.request(event); self.request(event);
} }
} }
fn request(&self, event: FrontendEvent) { fn request(&self, event: FrontendRequest) {
let json = serde_json::to_string(&event).unwrap(); let json = serde_json::to_string(&event).unwrap();
log::debug!("requesting {json}"); log::debug!("requesting {json}");
let mut stream = self.imp().stream.borrow_mut(); let mut stream = self.imp().stream.borrow_mut();

View File

@@ -10,7 +10,7 @@ use crate::{
client::{ClientHandle, ClientManager}, client::{ClientHandle, ClientManager},
config::Config, config::Config,
dns, dns,
frontend::{FrontendEvent, FrontendListener}, frontend::{FrontendListener, FrontendRequest},
server::capture_task::CaptureEvent, server::capture_task::CaptureEvent,
}; };
@@ -144,7 +144,7 @@ impl Server {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for (handle, hostname) in active { for (handle, hostname) in active {
frontend_tx frontend_tx
.send(FrontendEvent::ActivateClient(handle, true)) .send(FrontendRequest::Activate(handle, true))
.await?; .await?;
if let Some(hostname) = hostname { if let Some(hostname) = hostname {
let _ = resolve_tx.send(DnsRequest { hostname, handle }).await; let _ = resolve_tx.send(DnsRequest { hostname, handle }).await;
@@ -178,7 +178,7 @@ impl Server {
let _ = emulate_channel.send(EmulationEvent::Terminate).await; let _ = emulate_channel.send(EmulationEvent::Terminate).await;
let _ = capture_channel.send(CaptureEvent::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 !capture_task.is_finished() {
if let Err(e) = capture_task.await { if let Err(e) = capture_task.await {

View File

@@ -18,7 +18,7 @@ use tokio::{
use crate::{ use crate::{
client::{ClientEvent, ClientHandle, Position}, client::{ClientEvent, ClientHandle, Position},
frontend::{self, FrontendEvent, FrontendListener, FrontendNotify}, frontend::{self, FrontendEvent, FrontendListener, FrontendRequest},
}; };
use super::{ use super::{
@@ -27,13 +27,13 @@ use super::{
pub(crate) fn new( pub(crate) fn new(
mut frontend: FrontendListener, mut frontend: FrontendListener,
mut notify_rx: Receiver<FrontendNotify>, mut notify_rx: Receiver<FrontendEvent>,
server: Server, server: Server,
capture: Sender<CaptureEvent>, capture: Sender<CaptureEvent>,
emulate: Sender<EmulationEvent>, emulate: Sender<EmulationEvent>,
resolve_ch: Sender<DnsRequest>, resolve_ch: Sender<DnsRequest>,
port_tx: Sender<u16>, port_tx: Sender<u16>,
) -> (JoinHandle<Result<()>>, Sender<FrontendEvent>) { ) -> (JoinHandle<Result<()>>, Sender<FrontendRequest>) {
let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(32); let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(32);
let event_tx_clone = event_tx.clone(); let event_tx_clone = event_tx.clone();
let frontend_task = tokio::task::spawn_local(async move { let frontend_task = tokio::task::spawn_local(async move {
@@ -57,7 +57,7 @@ pub(crate) fn new(
} }
notify = notify_rx.recv() => { notify = notify_rx.recv() => {
let notify = notify.ok_or(anyhow!("frontend notify closed"))?; 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( async fn handle_frontend_stream(
frontend_tx: &Sender<FrontendEvent>, frontend_tx: &Sender<FrontendRequest>,
#[cfg(unix)] mut stream: ReadHalf<UnixStream>, #[cfg(unix)] mut stream: ReadHalf<UnixStream>,
#[cfg(windows)] mut stream: ReadHalf<TcpStream>, #[cfg(windows)] mut stream: ReadHalf<TcpStream>,
) { ) {
@@ -75,9 +75,9 @@ async fn handle_frontend_stream(
let tx = frontend_tx.clone(); let tx = frontend_tx.clone();
tokio::task::spawn_local(async move { tokio::task::spawn_local(async move {
let _ = tx.send(FrontendEvent::Enumerate()).await; let _ = tx.send(FrontendRequest::Enumerate()).await;
loop { loop {
let event = frontend::read_event(&mut stream).await; let event = frontend::wait_for_request(&mut stream).await;
match event { match event {
Ok(event) => { Ok(event) => {
let _ = tx.send(event).await; let _ = tx.send(event).await;
@@ -103,11 +103,11 @@ async fn handle_frontend_event(
resolve_tx: &Sender<DnsRequest>, resolve_tx: &Sender<DnsRequest>,
frontend: &mut FrontendListener, frontend: &mut FrontendListener,
port_tx: &Sender<u16>, port_tx: &Sender<u16>,
event: FrontendEvent, event: FrontendRequest,
) -> bool { ) -> bool {
log::debug!("frontend: {event:?}"); log::debug!("frontend: {event:?}");
match event { match event {
FrontendEvent::AddClient(hostname, port, pos) => { FrontendRequest::Create(hostname, port, pos) => {
add_client( add_client(
server, server,
frontend, frontend,
@@ -119,33 +119,33 @@ async fn handle_frontend_event(
) )
.await; .await;
} }
FrontendEvent::ActivateClient(handle, active) => { FrontendRequest::Activate(handle, active) => {
if active { if active {
activate_client(server, frontend, capture_tx, emulate_tx, handle).await; activate_client(server, frontend, capture_tx, emulate_tx, handle).await;
} else { } else {
deactivate_client(server, frontend, capture_tx, emulate_tx, handle).await; deactivate_client(server, frontend, capture_tx, emulate_tx, handle).await;
} }
} }
FrontendEvent::ChangePort(port) => { FrontendRequest::ChangePort(port) => {
let _ = port_tx.send(port).await; let _ = port_tx.send(port).await;
} }
FrontendEvent::DelClient(handle) => { FrontendRequest::Delete(handle) => {
remove_client(server, frontend, capture_tx, emulate_tx, handle).await; remove_client(server, frontend, capture_tx, emulate_tx, handle).await;
} }
FrontendEvent::Enumerate() => { FrontendRequest::Enumerate() => {
let clients = server let clients = server
.client_manager .client_manager
.borrow() .borrow()
.get_client_states() .get_client_states()
.map(|s| (s.client.clone(), s.active)) .map(|s| (s.client.clone(), s.active))
.collect(); .collect();
notify_all(frontend, FrontendNotify::Enumerate(clients)).await; notify_all(frontend, FrontendEvent::Enumerate(clients)).await;
} }
FrontendEvent::Shutdown() => { FrontendRequest::Terminate() => {
log::info!("terminating gracefully..."); log::info!("terminating gracefully...");
return true; return true;
} }
FrontendEvent::UpdateClient(handle, hostname, port, pos) => { FrontendRequest::Update(handle, hostname, port, pos) => {
update_client( update_client(
server, server,
frontend, frontend,
@@ -160,8 +160,8 @@ async fn handle_frontend_event(
false false
} }
async fn notify_all(frontend: &mut FrontendListener, event: FrontendNotify) { async fn notify_all(frontend: &mut FrontendListener, event: FrontendEvent) {
if let Err(e) = frontend.notify_all(event).await { if let Err(e) = frontend.broadcast_event(event).await {
log::error!("error notifying frontend: {e}"); log::error!("error notifying frontend: {e}");
} }
} }
@@ -199,7 +199,7 @@ pub async fn add_client(
.unwrap() .unwrap()
.client .client
.clone(); .clone();
notify_all(frontend, FrontendNotify::NotifyClientCreate(client)).await; notify_all(frontend, FrontendEvent::Created(client)).await;
} }
pub async fn deactivate_client( pub async fn deactivate_client(
@@ -220,7 +220,7 @@ pub async fn deactivate_client(
let event = ClientEvent::Destroy(client); let event = ClientEvent::Destroy(client);
let _ = capture.send(CaptureEvent::ClientEvent(event)).await; let _ = capture.send(CaptureEvent::ClientEvent(event)).await;
let _ = emulate.send(EmulationEvent::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; notify_all(frontend, event).await;
} }
@@ -256,7 +256,7 @@ pub async fn activate_client(
let event = ClientEvent::Create(handle, pos); let event = ClientEvent::Create(handle, pos);
let _ = capture.send(CaptureEvent::ClientEvent(event)).await; let _ = capture.send(CaptureEvent::ClientEvent(event)).await;
let _ = emulate.send(EmulationEvent::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; notify_all(frontend, event).await;
} }
@@ -282,7 +282,7 @@ pub async fn remove_client(
let _ = emulate.send(EmulationEvent::ClientEvent(destroy)).await; let _ = emulate.send(EmulationEvent::ClientEvent(destroy)).await;
} }
let event = FrontendNotify::NotifyClientDelete(client); let event = FrontendEvent::Deleted(client);
notify_all(frontend, event).await; notify_all(frontend, event).await;
} }
@@ -358,5 +358,5 @@ async fn update_client(
.unwrap() .unwrap()
.client .client
.clone(); .clone();
notify_all(frontend, FrontendNotify::NotifyClientUpdate(client)).await; notify_all(frontend, FrontendEvent::Updated(client)).await;
} }

View File

@@ -7,13 +7,13 @@ use tokio::{
task::JoinHandle, task::JoinHandle,
}; };
use crate::{event::Event, frontend::FrontendNotify}; use crate::{event::Event, frontend::FrontendEvent};
use super::Server; use super::Server;
pub async fn new( pub async fn new(
server: Server, server: Server,
frontend_notify_tx: Sender<FrontendNotify>, frontend_notify_tx: Sender<FrontendEvent>,
) -> Result<( ) -> Result<(
JoinHandle<()>, JoinHandle<()>,
Sender<(Event, SocketAddr)>, Sender<(Event, SocketAddr)>,
@@ -55,12 +55,12 @@ pub async fn new(
Ok(new_socket) => { Ok(new_socket) => {
socket = new_socket; socket = new_socket;
server.port.replace(port); 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) => { Err(e) => {
log::warn!("could not change port: {e}"); log::warn!("could not change port: {e}");
let port = socket.local_addr().unwrap().port(); let port = socket.local_addr().unwrap().port();
let _ = frontend_notify_tx.send(FrontendNotify::NotifyPortChange( let _ = frontend_notify_tx.send(FrontendEvent::PortChanged(
port, port,
Some(format!("could not change port: {e}")), Some(format!("could not change port: {e}")),
)).await; )).await;