Skip to content

Commit

Permalink
Rename FrontendEvent to FrontendRequest (#111)
Browse files Browse the repository at this point in the history
* rename frontend event and notify
* simplify event names
  • Loading branch information
feschber authored Apr 25, 2024
1 parent 9edd2f7 commit 279e582
Show file tree
Hide file tree
Showing 7 changed files with 97 additions and 92 deletions.
41 changes: 23 additions & 18 deletions src/frontend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,34 +84,39 @@ pub fn wait_for_service() -> Result<std::net::TcpStream> {
}

#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
pub enum FrontendEvent {
pub enum FrontendRequest {
/// add a new client
AddClient(Option<String>, u16, Position),
Create(Option<String>, 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<String>, u16, Position),
Update(ClientHandle, Option<String>, 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<String>),
/// Client State, active
PortChanged(u16, Option<String>),
/// list of all clients, used for initial state synchronization
Enumerate(Vec<(Client, bool)>),
NotifyError(String),
/// an error occured
Error(String),
}

pub struct FrontendListener {
Expand Down Expand Up @@ -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(&notify).unwrap();
let payload = json.as_bytes();
Expand Down Expand Up @@ -255,7 +260,7 @@ impl Drop for FrontendListener {
}

#[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?;
assert!(len <= 256);
let mut buf = [0u8; 256];
Expand All @@ -264,7 +269,7 @@ pub async fn read_event(stream: &mut ReadHalf<UnixStream>) -> Result<FrontendEve
}

#[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 mut buf = [0u8; 256];
stream.read_exact(&mut buf[..len as usize]).await?;
Expand Down
56 changes: 28 additions & 28 deletions src/frontend/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -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: [{}]",
Expand All @@ -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}"),
},
Expand All @@ -153,9 +153,9 @@ fn prompt() {
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 {
return Some(vec![FrontendEvent::Shutdown()]);
return Some(vec![FrontendRequest::Terminate()]);
}
let mut l = s.split_whitespace();
let cmd = l.next()?;
Expand All @@ -170,8 +170,8 @@ fn parse_cmd(s: String, len: usize) -> Option<Vec<FrontendEvent>> {
log::info!("setport <port> 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)),
Expand All @@ -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 host = l.next().context(usage)?.to_owned();
let pos = match l.next().context(usage)? {
Expand All @@ -207,36 +207,36 @@ fn parse_connect(mut l: SplitWhitespace) -> Result<Vec<FrontendEvent>> {
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<Vec<FrontendEvent>> {
fn parse_disconnect(mut l: SplitWhitespace) -> Result<Vec<FrontendRequest>> {
let client = l.next().context("usage: disconnect <client_id>")?.parse()?;
Ok(vec![
FrontendEvent::DelClient(client),
FrontendEvent::Enumerate(),
FrontendRequest::Delete(client),
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()?;
Ok(vec![
FrontendEvent::ActivateClient(client, true),
FrontendEvent::Enumerate(),
FrontendRequest::Activate(client, true),
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()?;
Ok(vec![
FrontendEvent::ActivateClient(client, false),
FrontendEvent::Enumerate(),
FrontendRequest::Activate(client, false),
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()?;
Ok(vec![FrontendEvent::ChangePort(port)])
Ok(vec![FrontendRequest::ChangePort(port)])
}
16 changes: 8 additions & 8 deletions src/frontend/gtk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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);
Expand All @@ -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()),
Expand Down
16 changes: 8 additions & 8 deletions src/frontend/gtk/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -152,17 +152,17 @@ 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);
}

pub fn request_port_change(&self) {
let port = self.imp().port_entry.get().text().to_string();
if let Ok(port) = port.as_str().parse::<u16>() {
self.request(FrontendEvent::ChangePort(port));
self.request(FrontendRequest::ChangePort(port));
} else {
self.request(FrontendEvent::ChangePort(DEFAULT_PORT));
self.request(FrontendRequest::ChangePort(DEFAULT_PORT));
}
}

Expand All @@ -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);
}
Expand All @@ -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();
Expand Down
6 changes: 3 additions & 3 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::{
client::{ClientHandle, ClientManager},
config::Config,
dns,
frontend::{FrontendEvent, FrontendListener},
frontend::{FrontendListener, FrontendRequest},
server::capture_task::CaptureEvent,
};

Expand Down Expand Up @@ -144,7 +144,7 @@ impl Server {
.collect::<Vec<_>>();
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;
Expand Down Expand Up @@ -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 {
Expand Down
Loading

0 comments on commit 279e582

Please sign in to comment.