An open-source cross-platform alternative to AirDrop
refactor(cli): unify events into one dispatch and decode keys into intents
Tien Do Namce1fac207867
diff --git a/cli/src/app/headless.rs b/cli/src/app/headless.rsindex 4eaa8334..c2ef9da2 100644--- a/cli/src/app/headless.rs+++ b/cli/src/app/headless.rs@@ -57,35 +57,52 @@ pub(super) async fn run(let mut send: Option<SendState> = None;let result = loop {- tokio::select! {- Some(event) = events_rx.recv() => match event {- AppEvent::Log { category, text } => ui.log(category, &text),- AppEvent::DiscoveryFinished => {- match start_send(&mut ui, &storage, &discovery, &target, paths.clone(), &events_tx) {- Ok(state) => send = Some(state),- Err(reason) => break Err(anyhow::anyhow!(reason)),- }+ let event = tokio::select! {+ Some(event) = events_rx.recv() => event,+ Some(event) = server_rx.recv() => AppEvent::Server(event),+ Some(event) = discovery_rx.recv() => AppEvent::Discovery(event),+ _ = tick.tick() => AppEvent::Tick,+ };+ match event {+ AppEvent::Server(event) => {+ handle_server_event(&mut ui, &storage, &discovery, &mut send, event)+ }+ AppEvent::Discovery(event) => {+ handle_discovery(&mut ui, &mut storage, &discovery, event)+ }+ AppEvent::Tick => render_progress(&mut ui, &mut send),+ AppEvent::Log { category, text } => ui.log(category, &text),+ AppEvent::DiscoveryFinished => {+ match start_send(+ &mut ui,+ &storage,+ &discovery,+ &target,+ paths.clone(),+ &events_tx,+ ) {+ Ok(state) => send = Some(state),+ Err(reason) => break Err(anyhow::anyhow!(reason)),}- AppEvent::SendSessionStarted { session_id, accepted_bytes } => {- if let Some(send) = &mut send {- send.session_id = Some(session_id);- send.total_bytes = accepted_bytes;- }+ }+ AppEvent::SendSessionStarted {+ session_id,+ accepted_bytes,+ } => {+ if let Some(send) = &mut send {+ send.session_id = Some(session_id);+ send.total_bytes = accepted_bytes;}- AppEvent::SendEnded { success } => break match success {+ }+ AppEvent::SendEnded { success } => {+ break match success {true => Ok(()),false => Err(anyhow::anyhow!("Transfer failed")),- },- // No keyboard and no accepted receive sessions in this mode.- AppEvent::Key(_) | AppEvent::ReceiveFileResult { .. } => {}- },- Some(event) = server_rx.recv() => {- handle_server_event(&mut ui, &storage, &discovery, &mut send, event);- }- Some(event) = discovery_rx.recv() => {- handle_discovery(&mut ui, &mut storage, &discovery, event);+ };}- _ = tick.tick() => render_progress(&mut ui, &mut send),+ // No keyboard, no accepted receive sessions and no web links in+ // this mode.+ AppEvent::Key(_) | AppEvent::ReceiveFileResult { .. } | AppEvent::Web(_) => {}}};ui.set_status(None);diff --git a/cli/src/app/keys.rs b/cli/src/app/keys.rsnew file mode 100644index 00000000..b4bc47a2--- /dev/null+++ b/cli/src/app/keys.rs@@ -0,0 +1,151 @@+//! Decoding raw key presses into semantic [Intent]s, so the handlers act on+//! what the user meant and the chord bookkeeping stays out of them.++use super::receive::Answer;+use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};++/// A semantic action decoded from a key press.+#[derive(Debug, PartialEq)]+pub(super) enum Intent {+ /// Ctrl+C: cancel the open overlay, the pending request, or the active+ /// transfers, or quit when idle.+ Cancel,++ /// While an overlay is open, it consumes every key.+ Overlay(KeyEvent),++ /// W+S: toggle "share via link".+ ToggleWebShare,++ /// W+R: toggle "receive via link".+ ToggleWebReceive,++ /// Y/N/P: answer the pending transfer request.+ Answer(Answer),++ /// D: open the device list overlay.+ OpenDeviceList,++ /// 1-9: send files to the device on that hotkey slot.+ PickDevice(u8),+}++/// Decodes key presses into [Intent]s, tracking the `W` half of the W+S /+/// W+R chords across presses.+pub(super) struct KeyDecoder {+ /// Whether the previously pressed key was `W`.+ chord_w: bool,+}++impl KeyDecoder {+ pub(super) fn new() -> Self {+ Self { chord_w: false }+ }++ /// Decodes a key press; keys without a meaning decode to `None`.+ pub(super) fn decode(&mut self, key: KeyEvent, overlay_open: bool) -> Option<Intent> {+ if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {+ self.chord_w = false;+ return Some(Intent::Cancel);+ }+ if overlay_open {+ return Some(Intent::Overlay(key));+ }+ let KeyCode::Char(c) = key.code else {+ return None;+ };+ let chord_w = std::mem::replace(&mut self.chord_w, false);+ match c.to_ascii_lowercase() {+ 's' if chord_w => Some(Intent::ToggleWebShare),+ 'r' if chord_w => Some(Intent::ToggleWebReceive),+ 'w' => {+ self.chord_w = true;+ None+ }+ 'y' => Some(Intent::Answer(Answer::Accept)),+ 'n' => Some(Intent::Answer(Answer::Decline)),+ 'p' => Some(Intent::Answer(Answer::AcceptAndPair)),+ 'd' => Some(Intent::OpenDeviceList),+ '1'..='9' => Some(Intent::PickDevice(c as u8 - b'0')),+ _ => None,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::{Intent, KeyDecoder};+ use crate::app::receive::Answer;+ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};++ fn char_key(c: char) -> KeyEvent {+ KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)+ }++ #[test]+ fn decodes_the_web_chords() {+ let mut decoder = KeyDecoder::new();++ assert_eq!(decoder.decode(char_key('w'), false), None);+ assert_eq!(+ decoder.decode(char_key('s'), false),+ Some(Intent::ToggleWebShare)+ );++ assert_eq!(decoder.decode(char_key('w'), false), None);+ assert_eq!(+ decoder.decode(char_key('r'), false),+ Some(Intent::ToggleWebReceive)+ );+ }++ #[test]+ fn any_other_key_ends_the_chord() {+ let mut decoder = KeyDecoder::new();++ assert_eq!(decoder.decode(char_key('w'), false), None);+ assert_eq!(+ decoder.decode(char_key('y'), false),+ Some(Intent::Answer(Answer::Accept))+ );+ // The chord was consumed: a plain S means nothing.+ assert_eq!(decoder.decode(char_key('s'), false), None);+ }++ #[test]+ fn ctrl_c_cancels_and_resets_the_chord() {+ let mut decoder = KeyDecoder::new();+ let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);++ assert_eq!(decoder.decode(char_key('w'), false), None);+ assert_eq!(decoder.decode(ctrl_c, false), Some(Intent::Cancel));+ assert_eq!(decoder.decode(char_key('s'), false), None);+ }++ #[test]+ fn an_open_overlay_consumes_every_key_except_ctrl_c() {+ let mut decoder = KeyDecoder::new();+ let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);++ assert_eq!(+ decoder.decode(char_key('d'), true),+ Some(Intent::Overlay(char_key('d')))+ );+ assert_eq!(decoder.decode(ctrl_c, true), Some(Intent::Cancel));+ }++ #[test]+ fn decodes_the_device_slots() {+ let mut decoder = KeyDecoder::new();++ assert_eq!(+ decoder.decode(char_key('1'), false),+ Some(Intent::PickDevice(1))+ );+ assert_eq!(+ decoder.decode(char_key('9'), false),+ Some(Intent::PickDevice(9))+ );+ assert_eq!(decoder.decode(char_key('0'), false), None);+ }+}diff --git a/cli/src/app/mod.rs b/cli/src/app/mod.rsindex 7c1af401..c505a306 100644--- a/cli/src/app/mod.rs+++ b/cli/src/app/mod.rs@@ -1,6 +1,7 @@mod devices;mod discovery;mod headless;+mod keys;mod receive;mod sending;mod status;@@ -13,7 +14,8 @@ use crate::slots::Slots;use crate::storage;use crate::ui::{Category, Ui};use crate::{Args, Command};-use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};+use crossterm::event::{Event, KeyEvent, KeyEventKind};+use keys::{Intent, KeyDecoder};use localsend::discovery::{DEFAULT_DISCOVERY_TIMEOUT, DeviceIdentity, DiscoveryConfig, DiscoveryEvent, DiscoveryHandle,HttpChannel,@@ -32,11 +34,23 @@ use std::time::Duration;use target::TargetSelector;use tokio::sync::{mpsc, oneshot};-/// Events processed by the central application loop.+/// Everything that can happen to the application.pub enum AppEvent {/// A key was pressed.Key(KeyEvent),+ /// An event of the HTTP server (protocol v2).+ Server(ServerEventV2),++ /// An event of the "share via link" download page.+ Web(WebDownloadEvent),++ /// A device entered or updated the discovery store.+ Discovery(DiscoveryEvent),++ /// The periodic redraw of the status line and the open overlay.+ Tick,+/// A file of the active receive session finished (or failed).ReceiveFileResult {session_id: String,@@ -231,9 +245,8 @@ struct App {/// `Some` while the server runs in plain-HTTP mode for browsers.web: Option<web_link::WebMode>,- /// Whether the previously pressed key was `W`, the first half of the- /// W+S / W+R chords toggling the web links.- chord_w: bool,+ /// Decodes key presses into [Intent]s, tracking the W+S / W+R chords.+ keys: KeyDecoder,/// The core discovery: the store of confirmed devices, and the multicast/// side when it could be started.@@ -313,7 +326,7 @@ async fn run_interactive(server_tx,web_tx,web: None,- chord_w: false,+ keys: KeyDecoder::new(),discovery: discovery.clone(),slots: Slots::new(),storage,@@ -338,23 +351,14 @@ async fn run_interactive(let mut quit = false;while !quit {- tokio::select! {- Some(event) = events_rx.recv() => {- quit = app.handle_event(event).await;- }- Some(event) = server_rx.recv() => {- app.handle_server_event(event);- }- Some(event) = web_rx.recv() => {- app.handle_web_event(event);- }- Some(event) = discovery_rx.recv() => {- app.handle_discovery(event);- }- _ = tick.tick() => {- app.tick();- }- }+ let event = tokio::select! {+ Some(event) = events_rx.recv() => event,+ Some(event) = server_rx.recv() => AppEvent::Server(event),+ Some(event) = web_rx.recv() => AppEvent::Web(event),+ Some(event) = discovery_rx.recv() => AppEvent::Discovery(event),+ _ = tick.tick() => AppEvent::Tick,+ };+ quit = app.dispatch(event).await;}// Shutdown: leave a possibly open overlay, restore the terminal, stop the@@ -377,9 +381,13 @@ async fn run_interactive(impl App {/// Handles an event; returns `true` when the application should quit.- async fn handle_event(&mut self, event: AppEvent) -> bool {+ async fn dispatch(&mut self, event: AppEvent) -> bool {match event {AppEvent::Key(key) => return self.handle_key(key).await,+ AppEvent::Server(event) => self.handle_server_event(event),+ AppEvent::Web(event) => self.handle_web_event(event),+ AppEvent::Discovery(event) => self.handle_discovery(event),+ AppEvent::Tick => self.tick(),AppEvent::ReceiveFileResult {session_id,file_id,@@ -411,34 +419,33 @@ impl App {}async fn handle_key(&mut self, key: KeyEvent) -> bool {- if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {- self.chord_w = false;- return self.handle_ctrl_c();- }-- // While an overlay is open it consumes every key.- match &self.overlay {- Overlay::Picker(_) => {- self.handle_picker_key(key).await;- return false;- }- Overlay::DeviceList(_) => return self.handle_device_list_key(key),- Overlay::None => {}+ let overlay_open = !matches!(self.overlay, Overlay::None);+ match self.keys.decode(key, overlay_open) {+ Some(intent) => self.handle_intent(intent).await,+ None => false,}+ }- if let KeyCode::Char(c) = key.code {- let chord_w = std::mem::replace(&mut self.chord_w, false);- match c.to_ascii_lowercase() {- 's' if chord_w => self.toggle_web_share().await,- 'r' if chord_w => self.toggle_web_receive().await,- 'w' => self.chord_w = true,- 'y' => self.answer_pending(Answer::Accept),- 'n' => self.answer_pending(Answer::Decline),- 'p' => self.answer_pending(Answer::AcceptAndPair),- 'd' => self.open_device_list(),- '1'..='9' => self.start_picking(c as u8 - b'0'),- _ => {}+ /// Acts on a decoded intent; returns `true` when the application should+ /// quit.+ async fn handle_intent(&mut self, intent: Intent) -> bool {+ match intent {+ Intent::Cancel => return self.handle_ctrl_c(),+ Intent::Overlay(key) => {+ return match &self.overlay {+ Overlay::Picker(_) => {+ self.handle_picker_key(key).await;+ false+ }+ Overlay::DeviceList(_) => self.handle_device_list_key(key),+ Overlay::None => false,+ };}+ Intent::ToggleWebShare => self.toggle_web_share().await,+ Intent::ToggleWebReceive => self.toggle_web_receive().await,+ Intent::Answer(answer) => self.answer_pending(answer),+ Intent::OpenDeviceList => self.open_device_list(),+ Intent::PickDevice(slot) => self.start_picking(slot),}false}diff --git a/cli/src/app/receive.rs b/cli/src/app/receive.rsindex f645a3bc..65166c22 100644--- a/cli/src/app/receive.rs+++ b/cli/src/app/receive.rs@@ -106,6 +106,7 @@ fn message_of(files: &HashMap<String, FileDto>) -> Option<&str> {const MAX_LISTED_FILES: usize = 20;/// The user's decision on a [`PendingReceive`].+#[derive(Debug, PartialEq)]pub(super) enum Answer {Accept,Decline,