An open-source cross-platform alternative to AirDrop
refactor: split interactive and headless modes for better separation
Tien Do Nam3da52e5b3da2
diff --git a/cli/src/app/devices.rs b/cli/src/app/devices.rsindex f57149d3..9de7f30c 100644--- a/cli/src/app/devices.rs+++ b/cli/src/app/devices.rs@@ -1,7 +1,7 @@//! The device list overlay: paired and discovered devices, with the send//! and unpair actions.-use super::App;+use super::{App, Overlay};use crate::device_list::{DeviceList, DeviceListOutcome, DeviceRow, Row};use crate::picker::PickerTarget;use crate::storage::PairedChannel;@@ -14,7 +14,7 @@ impl App {match DeviceList::open(self.device_rows()) {Ok(list) => {self.ui.suspend();- self.device_list = Some(list);+ self.overlay = Overlay::DeviceList(list);}Err(err) => {self.ui@@ -72,13 +72,14 @@ impl App {/// Handles a key while the list is open; returns `true` when the/// application should quit (the list was cancelled in `send` mode).pub(super) fn handle_device_list_key(&mut self, key: KeyEvent) -> bool {- let Some(list) = &mut self.device_list else {+ let Overlay::DeviceList(list) = &mut self.overlay else {return false;};match list.handle_key(key) {DeviceListOutcome::Open => {}DeviceListOutcome::Closed => {- self.close_device_list();+ self.close_overlay();+ // In `send` mode the device list is the whole program.return !self.preselected.is_empty();}DeviceListOutcome::Send { fingerprint } => {@@ -92,7 +93,7 @@ impl App {alias: device.device.alias.clone(),});} else {- self.close_device_list();+ self.close_overlay();if !self.preselected.is_empty() {self.start_send(&fingerprint, self.preselected.clone());}@@ -104,13 +105,6 @@ impl App {false}- pub(super) fn close_device_list(&mut self) {- if let Some(list) = self.device_list.take() {- list.close();- self.ui.resume();- }- }-/// Pairs a discovered device; the list stays open and refreshes (the/// device moves up into "Paired"). The log line shows up once the list/// is closed.@@ -134,7 +128,7 @@ impl App {),}let rows = self.device_rows();- if let Some(list) = &mut self.device_list {+ if let Overlay::DeviceList(list) = &mut self.overlay {list.set_rows(rows);list.draw();}@@ -158,7 +152,7 @@ impl App {}}let rows = self.device_rows();- if let Some(list) = &mut self.device_list {+ if let Overlay::DeviceList(list) = &mut self.overlay {list.set_rows(rows);list.draw();}diff --git a/cli/src/app/discovery.rs b/cli/src/app/discovery.rsindex 7d9e80f4..04abf113 100644--- a/cli/src/app/discovery.rs+++ b/cli/src/app/discovery.rs@@ -5,10 +5,13 @@use super::App;use super::web_link::WebMode;use crate::slots::slot_label;-use crate::storage::PairedChannel;-use crate::ui::Category;-use localsend::discovery::{DeviceChannel, DiscoveredDevice, DiscoveryEvent, HttpChannel};+use crate::storage::{PairedChannel, PairedDevices};+use crate::ui::{Category, Ui};+use localsend::discovery::{+ DeviceChannel, DiscoveredDevice, DiscoveryEvent, DiscoveryHandle, HttpChannel,+};use localsend::http::dto_v2::RegisterDtoV2;+use std::sync::Arc;impl App {pub(super) fn handle_discovery(&mut self, event: DiscoveryEvent) {@@ -22,7 +25,12 @@ impl App {return;}};- self.refresh_paired_channels(&device.fingerprint);+ refresh_paired_channels(+ &mut self.ui,+ &mut self.storage.paired,+ &self.discovery,+ &device.fingerprint,+ );let DiscoveryEvent::Discovered { device } = event else {// Re-confirmations update the store silently; multi-homed peers@@ -45,51 +53,70 @@ impl App {);}- /// Keeps a paired device's stored alias and channels in sync with the- /// discovery store, so the next run probes the addresses that worked last.- fn refresh_paired_channels(&mut self, fingerprint: &str) {- if !self.storage.paired.contains(fingerprint) {- return;- }- let Some(stored) = self.discovery.device_by_fingerprint(fingerprint) else {- return;- };- let result = self.storage.paired.update(- fingerprint,- &stored.device.alias,- PairedChannel::channels_of(&stored),+ pub(super) fn device_confirmed(&self, host: String, info: RegisterDtoV2) {+ device_confirmed(+ &self.discovery,+ &self.storage.identity.fingerprint,+ host,+ info,);- if let Err(err) = result {- self.ui.log(- Category::Discovery,- &format!("Could not save the paired devices: {err:#}"),- );- }}+}- /// Feeds a device confirmed outside of discovery — it registered with our- /// HTTP server, or it sent a transfer request — into the discovery store;- /// a device new to the store comes back as a `Discovered` event.- pub(super) fn device_confirmed(&self, host: String, info: RegisterDtoV2) {- if info.fingerprint == self.storage.identity.fingerprint {- return;- }- let device = DiscoveredDevice {- alias: info.alias,- version: info.version,- device_model: info.device_model,- device_type: info.device_type,- fingerprint: info.fingerprint,- channel: DeviceChannel::Http(HttpChannel {- host,- port: info.port,- protocol: info.protocol,- }),- download: info.download,- };- let discovery = self.discovery.clone();- tokio::spawn(async move {- discovery.add_device(device).await;- });+/// Keeps a paired device's stored alias and channels in sync with the+/// discovery store, so the next run probes the addresses that worked last.+pub(super) fn refresh_paired_channels(+ ui: &mut Ui,+ paired: &mut PairedDevices,+ discovery: &DiscoveryHandle,+ fingerprint: &str,+) {+ if !paired.contains(fingerprint) {+ return;+ }+ let Some(stored) = discovery.device_by_fingerprint(fingerprint) else {+ return;+ };+ let result = paired.update(+ fingerprint,+ &stored.device.alias,+ PairedChannel::channels_of(&stored),+ );+ if let Err(err) = result {+ ui.log(+ Category::Discovery,+ &format!("Could not save the paired devices: {err:#}"),+ );+ }+}++/// Feeds a device confirmed outside of discovery — it registered with our+/// HTTP server, or it sent a transfer request — into the discovery store;+/// a device new to the store comes back as a `Discovered` event.+pub(super) fn device_confirmed(+ discovery: &Arc<DiscoveryHandle>,+ own_fingerprint: &str,+ host: String,+ info: RegisterDtoV2,+) {+ if info.fingerprint == own_fingerprint {+ return;}+ let device = DiscoveredDevice {+ alias: info.alias,+ version: info.version,+ device_model: info.device_model,+ device_type: info.device_type,+ fingerprint: info.fingerprint,+ channel: DeviceChannel::Http(HttpChannel {+ host,+ port: info.port,+ protocol: info.protocol,+ }),+ download: info.download,+ };+ let discovery = discovery.clone();+ tokio::spawn(async move {+ discovery.add_device(device).await;+ });}diff --git a/cli/src/app/headless.rs b/cli/src/app/headless.rsnew file mode 100644index 00000000..a7ff41eb--- /dev/null+++ b/cli/src/app/headless.rs@@ -0,0 +1,216 @@+//! The headless `send --to` mode: discover the destination, send the files,+//! exit with the transfer result. There is no keyboard and no overlay — only+//! the network events a send needs are handled, and incoming transfer+//! requests are declined.++use super::sending::{self, SendState};+use super::status;+use super::target::TargetSelector;+use super::{AppEvent, Network, discovery, spawn_staged_discovery, start_network, stop_network};+use crate::storage::Repository;+use crate::ui::{Category, Ui};+use crate::util;+use localsend::discovery::{DiscoveryEvent, DiscoveryHandle};+use localsend::http::server::v2::{PrepareUploadDecisionV2, ServerEventV2};+use std::path::PathBuf;+use std::sync::Arc;+use std::sync::atomic::Ordering;+use std::time::Duration;+use tokio::sync::mpsc;++pub(super) async fn run(+ mut storage: Repository,+ target: TargetSelector,+ paths: Vec<PathBuf>,+) -> anyhow::Result<()> {+ let mut ui = Ui::new();+ let identity = storage.identity.clone();+ let (events_tx, mut events_rx) = mpsc::channel::<AppEvent>(64);+ let Network {+ server,+ server_stop_tx,+ server_tx: _,+ mut server_rx,+ discovery,+ mut discovery_rx,+ discovery_stop_tx,+ } = start_network(&identity).await?;++ // Probe the destination's address directly when `--to` is an IP.+ let mut known_channels = storage.paired.known_http_channels();+ if let Some(channel) = target.direct_channel()+ && !known_channels.contains(&channel)+ {+ known_channels.insert(0, channel);+ }+ spawn_staged_discovery(+ discovery.clone(),+ events_tx.clone(),+ known_channels,+ identity.port,+ );+ ui.log_plain(&format!("Discovering destination {target}..."));++ let mut tick = tokio::time::interval(Duration::from_millis(250));+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);++ 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)),+ }+ }+ 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 {+ 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),+ }+ };+ ui.set_status(None);+ stop_network(&server, Some(server_stop_tx), &discovery, discovery_stop_tx).await;+ result+}++/// Resolves the destination among the discovered devices and spawns the send+/// task towards it.+fn start_send(+ ui: &mut Ui,+ storage: &Repository,+ discovery: &DiscoveryHandle,+ target: &TargetSelector,+ paths: Vec<PathBuf>,+ events_tx: &mpsc::Sender<AppEvent>,+) -> Result<SendState, String> {+ let fingerprint = target.resolve(&discovery.devices())?;+ let device = discovery+ .device_by_fingerprint(&fingerprint)+ .ok_or_else(|| format!("Destination {target} was not discovered"))?;+ sending::spawn_send(+ ui,+ storage.identity.clone(),+ device,+ paths,+ events_tx.clone(),+ )+}++fn handle_server_event(+ ui: &mut Ui,+ storage: &Repository,+ discovery: &Arc<DiscoveryHandle>,+ send: &mut Option<SendState>,+ event: ServerEventV2,+) {+ match event {+ // Peers answer the startup announcement by registering here; this is+ // how the destination usually enters the device store.+ ServerEventV2::Register { ip, info } => {+ discovery::device_confirmed(+ discovery,+ &storage.identity.fingerprint,+ ip.to_string(),+ info,+ );+ }+ ServerEventV2::PrepareUpload {+ info, decision_tx, ..+ } => {+ // Receiving needs the interactive Y/N prompt; decline instead of+ // leaving the sender hanging.+ let _ = decision_tx.send(PrepareUploadDecisionV2::Decline);+ ui.log(+ Category::Receive,+ &format!(+ "{}: Declined the incoming request (busy sending)",+ info.alias+ ),+ );+ }+ ServerEventV2::CancelReceived { ip, session_id } => {+ if let Some(send) = send+ && send.session_id.as_deref() == Some(session_id.as_str())+ && send.host == ip.to_string()+ {+ send.cancel.by_peer.store(true, Ordering::Relaxed);+ send.cancel.token.cancel();+ }+ }+ ServerEventV2::ListenerFailed { error } => {+ ui.log(Category::Receive, &format!("Server stopped: {error}"));+ }+ // No receive session is ever accepted; dropping the responders+ // rejects the requests.+ ServerEventV2::FileUpload { .. }+ | ServerEventV2::SessionEnd { .. }+ | ServerEventV2::PrepareUploadAborted { .. } => {}+ }+}++fn handle_discovery(+ ui: &mut Ui,+ storage: &mut Repository,+ discovery: &DiscoveryHandle,+ event: DiscoveryEvent,+) {+ let device = match &event {+ DiscoveryEvent::Discovered { device } | DiscoveryEvent::Updated { device } => device,+ DiscoveryEvent::MulticastFailed => {+ ui.log(+ Category::Discovery,+ "Multicast stopped, no longer hearing announcements",+ );+ return;+ }+ };+ discovery::refresh_paired_channels(ui, &mut storage.paired, discovery, &device.fingerprint);++ let DiscoveryEvent::Discovered { device } = event else {+ // Re-confirmations update the store silently.+ return;+ };+ let host = device+ .http()+ .map(|http| http.host.as_str())+ .unwrap_or("unknown address");+ ui.log(Category::Discovery, &format!("{} ({host})", device.alias));+}++/// The status line: the progress bar of the running transfer.+fn render_progress(ui: &mut Ui, send: &mut Option<SendState>) {+ let Some(send) = send else {+ ui.set_status(None);+ return;+ };+ let done = send.sent.load(Ordering::Relaxed);+ let speed = send.speed.update(done);+ let width = util::terminal_width().saturating_sub(1);+ ui.set_status(Some(status::transfer_status(+ Category::Send,+ &send.alias,+ done,+ send.total_bytes,+ speed,+ width,+ )));+}diff --git a/cli/src/app/mod.rs b/cli/src/app/mod.rsindex d685a82d..7c1af401 100644--- a/cli/src/app/mod.rs+++ b/cli/src/app/mod.rs@@ -1,5 +1,6 @@mod devices;mod discovery;+mod headless;mod receive;mod sending;mod status;@@ -15,6 +16,7 @@ use crate::{Args, Command};use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};use localsend::discovery::{DEFAULT_DISCOVERY_TIMEOUT, DeviceIdentity, DiscoveryConfig, DiscoveryEvent, DiscoveryHandle,+ HttpChannel,};use localsend::http::server::v2::ServerEventV2;use localsend::http::server::web::{WebConfig, WebDownloadEvent};@@ -58,58 +60,6 @@ pub enum AppEvent {Log { category: Category, text: String },}-struct App {- ui: Ui,- server: Arc<ServerHandle>,-- /// Stops the running server. Consumed on shutdown and whenever the server- /// is restarted for the web share toggle.- server_stop_tx: Option<oneshot::Sender<()>>,-- /// Event senders handed to every (re)started server, so the receivers in- /// [run]'s select loop survive server restarts.- server_tx: mpsc::Sender<ServerEventV2>,- web_tx: mpsc::Sender<WebDownloadEvent>,-- /// The active web link mode ("share via link" / "receive via link");- /// `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,-- /// The core discovery: the store of confirmed devices, and the multicast- /// side when it could be started.- discovery: Arc<DiscoveryHandle>,-- /// The hotkeys (1-9) of the devices in the discovery store.- slots: Slots,-- /// Config, identity and paired devices, see [`storage::Repository`].- storage: storage::Repository,-- pending: Option<PendingReceive>,- receive: Option<ReceiveSession>,- send: Option<SendState>,- picker: Option<Picker>,- device_list: Option<DeviceList>,-- /// Paths given to the `send` command; sending uses these instead of the- /// picker.- preselected: Vec<PathBuf>,-- /// A destination selected by `send --to`; `None` keeps device selection- /// interactive.- target: Option<TargetSelector>,-- /// Returned after network tasks have shut down when headless operation- /// could not complete.- exit_error: Option<anyhow::Error>,-- events_tx: mpsc::Sender<AppEvent>,-}-pub async fn run(args: Args) -> anyhow::Result<()> {let (preselected, target) = match &args.command {Some(Command::Send { to, paths }) => (@@ -118,7 +68,6 @@ pub async fn run(args: Args) -> anyhow::Result<()> {),None => (Vec::new(), None),};- let interactive = target.is_none();for path in &preselected {anyhow::ensure!(path.is_file() || path.is_dir(),@@ -127,12 +76,32 @@ pub async fn run(args: Args) -> anyhow::Result<()> {);}let storage = storage::Repository::load(&args)?;- let identity = storage.identity.clone();- let (events_tx, mut events_rx) = mpsc::channel::<AppEvent>(64);+ match target {+ Some(target) => headless::run(storage, target, preselected).await,+ None => run_interactive(storage, preselected).await,+ }+}- // HTTP server (TLS, like the app, until "share via link" drops it).- let (server_tx, mut server_rx) = mpsc::channel::<ServerEventV2>(16);- let (web_tx, mut web_rx) = mpsc::channel::<WebDownloadEvent>(16);+/// The network tasks shared by the interactive and the headless mode: the+/// HTTP server (TLS, like the app) and the discovery.+struct Network {+ server: Arc<ServerHandle>,+ server_stop_tx: oneshot::Sender<()>,++ /// Event sender handed to every (re)started server, so the receiver+ /// survives server restarts.+ server_tx: mpsc::Sender<ServerEventV2>,+ server_rx: mpsc::Receiver<ServerEventV2>,++ /// The core discovery: the store of confirmed devices, and the multicast+ /// side when it could be started.+ discovery: Arc<DiscoveryHandle>,+ discovery_rx: mpsc::Receiver<DiscoveryEvent>,+ discovery_stop_tx: oneshot::Sender<()>,+}++async fn start_network(identity: &Arc<storage::Identity>) -> anyhow::Result<Network> {+ let (server_tx, server_rx) = mpsc::channel::<ServerEventV2>(16);let (server_stop_tx, server_stop_rx) = oneshot::channel::<()>();let server = start_with_port(identity.port,@@ -148,12 +117,11 @@ pub async fn run(args: Args) -> anyhow::Result<()> {server_stop_rx,).await?;- let server = Arc::new(server);// Discovery: multicast, plus the register requests answering other// devices' announcements. Multicast failure is not fatal: the store keeps// collecting the devices that contact this device over HTTP.- let (discovery_tx, mut discovery_rx) = mpsc::channel::<DiscoveryEvent>(16);+ let (discovery_tx, discovery_rx) = mpsc::channel::<DiscoveryEvent>(16);let (discovery_stop_tx, discovery_stop_rx) = oneshot::channel::<()>();let discovery = Arc::new(localsend::discovery::start(@@ -177,64 +145,166 @@ pub async fn run(args: Args) -> anyhow::Result<()> {if let Some(err) = discovery.multicast_error() {eprintln!("Multicast unavailable: {err:#}");}- {- // Discover in stages: announce this device (peers answer with an HTTP- // register request), probe the paired devices' stored addresses, and- // fall back to scanning the local subnets when nothing was confirmed.- let discovery = discovery.clone();- let events_tx = events_tx.clone();- let port = identity.port;- let mut known_channels = storage.paired.known_http_channels();- if let Some(channel) = target.as_ref().and_then(TargetSelector::direct_channel)- && !known_channels.contains(&channel)- {- known_channels.insert(0, channel);- }- let interface_ips =- local_interface_addresses(&InterfaceFilter::default()).unwrap_or_default();- tokio::spawn(async move {- let result = discovery- .discover_staged(- known_channels,- interface_ips,- port,- ProtocolType::Https,- Duration::from_secs(1),- )++ Ok(Network {+ server: Arc::new(server),+ server_stop_tx,+ server_tx,+ server_rx,+ discovery,+ discovery_rx,+ discovery_stop_tx,+ })+}++/// Discovers in stages: announce this device (peers answer with an HTTP+/// register request), probe the known addresses, and fall back to scanning+/// the local subnets when nothing was confirmed. Ends by emitting+/// [AppEvent::DiscoveryFinished].+fn spawn_staged_discovery(+ discovery: Arc<DiscoveryHandle>,+ events_tx: mpsc::Sender<AppEvent>,+ known_channels: Vec<HttpChannel>,+ port: u16,+) {+ let interface_ips = local_interface_addresses(&InterfaceFilter::default()).unwrap_or_default();+ tokio::spawn(async move {+ let result = discovery+ .discover_staged(+ known_channels,+ interface_ips,+ port,+ ProtocolType::Https,+ Duration::from_secs(1),+ )+ .await;+ if let Err(err) = result {+ let _ = events_tx+ .send(AppEvent::Log {+ category: Category::Discovery,+ text: format!("Discovery failed: {err}"),+ }).await;- if let Err(err) = result {- let _ = events_tx- .send(AppEvent::Log {- category: Category::Discovery,- text: format!("Discovery failed: {err}"),- })- .await;- }- let _ = events_tx.send(AppEvent::DiscoveryFinished).await;- });+ }+ let _ = events_tx.send(AppEvent::DiscoveryFinished).await;+ });+}++/// Stops the server and the discovery, waiting briefly so the ports are+/// released cleanly.+async fn stop_network(+ server: &ServerHandle,+ server_stop_tx: Option<oneshot::Sender<()>>,+ discovery: &DiscoveryHandle,+ discovery_stop_tx: oneshot::Sender<()>,+) {+ if let Some(stop_tx) = server_stop_tx {+ let _ = stop_tx.send(());}+ let _ = discovery_stop_tx.send(());+ let _ = tokio::time::timeout(Duration::from_secs(1), server.wait_stopped()).await;+ let _ = tokio::time::timeout(Duration::from_secs(1), discovery.wait_stopped()).await;+}++/// The modal overlay owning the alternate screen. At most one is open at a+/// time, and while it is, it consumes every key.+enum Overlay {+ None,+ Picker(Box<Picker>),+ DeviceList(DeviceList),+}- if interactive {- crossterm::terminal::enable_raw_mode()?;-- // Keyboard reader. The blocking thread ends with the process.- std::thread::spawn({- let events_tx = events_tx.clone();- move || {- loop {- match crossterm::event::read() {- Ok(Event::Key(key)) if key.kind == KeyEventKind::Press => {- if events_tx.blocking_send(AppEvent::Key(key)).is_err() {- return;- }+struct App {+ ui: Ui,+ server: Arc<ServerHandle>,++ /// Stops the running server. Consumed on shutdown and whenever the server+ /// is restarted for the web share toggle.+ server_stop_tx: Option<oneshot::Sender<()>>,++ /// Event senders handed to every (re)started server, so the receivers in+ /// [run_interactive]'s select loop survive server restarts.+ server_tx: mpsc::Sender<ServerEventV2>,+ web_tx: mpsc::Sender<WebDownloadEvent>,++ /// The active web link mode ("share via link" / "receive via link");+ /// `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,++ /// The core discovery: the store of confirmed devices, and the multicast+ /// side when it could be started.+ discovery: Arc<DiscoveryHandle>,++ /// The hotkeys (1-9) of the devices in the discovery store.+ slots: Slots,++ /// Config, identity and paired devices, see [`storage::Repository`].+ storage: storage::Repository,++ pending: Option<PendingReceive>,+ receive: Option<ReceiveSession>,+ send: Option<SendState>,+ overlay: Overlay,++ /// Paths given to the `send` command without `--to`: sending uses these+ /// instead of the picker, and the one transfer is the whole program.+ preselected: Vec<PathBuf>,++ /// Returned after network tasks have shut down when a `send` command+ /// could not complete.+ exit_error: Option<anyhow::Error>,++ events_tx: mpsc::Sender<AppEvent>,+}++/// The interactive mode: the append-only event log with hotkeys, and the+/// overlays opened from them.+async fn run_interactive(+ storage: storage::Repository,+ preselected: Vec<PathBuf>,+) -> anyhow::Result<()> {+ let identity = storage.identity.clone();+ let (events_tx, mut events_rx) = mpsc::channel::<AppEvent>(64);+ let (web_tx, mut web_rx) = mpsc::channel::<WebDownloadEvent>(16);+ let Network {+ server,+ server_stop_tx,+ server_tx,+ mut server_rx,+ discovery,+ mut discovery_rx,+ discovery_stop_tx,+ } = start_network(&identity).await?;+ spawn_staged_discovery(+ discovery.clone(),+ events_tx.clone(),+ storage.paired.known_http_channels(),+ identity.port,+ );++ crossterm::terminal::enable_raw_mode()?;++ // Keyboard reader. The blocking thread ends with the process.+ std::thread::spawn({+ let events_tx = events_tx.clone();+ move || {+ loop {+ match crossterm::event::read() {+ Ok(Event::Key(key)) if key.kind == KeyEventKind::Press => {+ if events_tx.blocking_send(AppEvent::Key(key)).is_err() {+ return;}- Ok(_) => {}- Err(_) => return,}+ Ok(_) => {}+ Err(_) => return,}}- });- }+ }+ });let mut app = App {ui: Ui::new(),@@ -250,22 +320,17 @@ pub async fn run(args: Args) -> anyhow::Result<()> {pending: None,receive: None,send: None,- picker: None,- device_list: None,+ overlay: Overlay::None,preselected,- target,exit_error: None,events_tx: events_tx.clone(),};- match (&app.target, app.preselected.is_empty()) {- (Some(target), _) => app- .ui- .log_plain(&format!("Discovering destination {target}...")),- (None, true) => app+ match app.preselected.is_empty() {+ true => app.ui.log_plain(&crate::banner::render(&app.storage, &app.server)),- (None, false) => app.open_device_list(),+ false => app.open_device_list(),}let mut tick = tokio::time::interval(Duration::from_millis(250));@@ -292,23 +357,18 @@ pub async fn run(args: Args) -> anyhow::Result<()> {}}- // Shutdown: leave a possibly open modal, restore the terminal, stop the- // network tasks (briefly, so the ports are released cleanly).- if let Some(picker) = app.picker.take() {- picker.close();- app.ui.resume();- }- app.close_device_list();+ // Shutdown: leave a possibly open overlay, restore the terminal, stop the+ // network tasks.+ app.close_overlay();app.ui.set_status(None);- if interactive {- let _ = crossterm::terminal::disable_raw_mode();- }- if let Some(stop_tx) = app.server_stop_tx.take() {- let _ = stop_tx.send(());- }- let _ = discovery_stop_tx.send(());- let _ = tokio::time::timeout(Duration::from_secs(1), app.server.wait_stopped()).await;- let _ = tokio::time::timeout(Duration::from_secs(1), discovery.wait_stopped()).await;+ let _ = crossterm::terminal::disable_raw_mode();+ stop_network(+ &app.server,+ app.server_stop_tx.take(),+ &discovery,+ discovery_stop_tx,+ )+ .await;match app.exit_error.take() {Some(error) => Err(error),None => Ok(()),@@ -343,23 +403,8 @@ impl App {// In `send` mode the transfer is the whole program.return !self.preselected.is_empty();}- AppEvent::DiscoveryFinished => {- let Some(target) = self.target.clone() else {- return false;- };- let fingerprint = match target.resolve(&self.discovery.devices()) {- Ok(fingerprint) => fingerprint,- Err(error) => {- self.exit_error = Some(anyhow::anyhow!(error));- return true;- }- };- self.start_send(&fingerprint, self.preselected.clone());- if self.send.is_none() {- self.exit_error = Some(anyhow::anyhow!("Could not start transfer to {target}"));- return true;- }- }+ // Only the headless mode acts on the end of the startup discovery.+ AppEvent::DiscoveryFinished => {}AppEvent::Log { category, text } => self.ui.log(category, &text),}false@@ -371,13 +416,14 @@ impl App {return self.handle_ctrl_c();}- // While the picker or the device list is open it consumes every key.- if self.picker.is_some() {- self.handle_picker_key(key).await;- return false;- }- if self.device_list.is_some() {- return self.handle_device_list_key(key);+ // 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 => {}}if let KeyCode::Char(c) = key.code {@@ -397,19 +443,21 @@ impl App {false}- /// Cancels the current activity: the open modal, the pending request and+ /// Cancels the current activity: the open overlay, the pending request and/// the active transfers. Returns `true` (quit) only when there was/// nothing to cancel.fn handle_ctrl_c(&mut self) -> bool {- if let Some(picker) = self.picker.take() {- picker.close();- self.ui.resume();- return false;- }- if self.device_list.is_some() {- self.close_device_list();- // In `send` mode the device list is the whole program.- return !self.preselected.is_empty();+ match &self.overlay {+ Overlay::Picker(_) => {+ self.close_overlay();+ return false;+ }+ Overlay::DeviceList(_) => {+ self.close_overlay();+ // In `send` mode the device list is the whole program.+ return !self.preselected.is_empty();+ }+ Overlay::None => {}}let mut cancelled = false;if self.pending.is_some() {@@ -428,4 +476,15 @@ impl App {}!cancelled}++ /// Closes the open overlay (if any) and resumes the terminal output that+ /// was suspended while the overlay owned the alternate screen.+ fn close_overlay(&mut self) {+ match std::mem::replace(&mut self.overlay, Overlay::None) {+ Overlay::None => return,+ Overlay::Picker(picker) => picker.close(),+ Overlay::DeviceList(list) => list.close(),+ }+ self.ui.resume();+ }}diff --git a/cli/src/app/sending.rs b/cli/src/app/sending.rsindex 56bb3d2c..3e0c81bc 100644--- a/cli/src/app/sending.rs+++ b/cli/src/app/sending.rs@@ -1,17 +1,20 @@//! The sending side: picking a target device and files, and tracking the//! transfer driven by the [`crate::send_task`].-use super::App;+use super::{App, AppEvent, Overlay};use crate::picker::{Picker, PickerOutcome, PickerTarget};use crate::send_task;-use crate::ui::Category;+use crate::storage::Identity;+use crate::ui::{Category, Ui};use crate::util::SpeedMeter;use crossterm::event::KeyEvent;+use localsend::discovery::StatefulDevice;use localsend::model::transfer::{FileDto, FileMetadata};use std::collections::HashMap;use std::path::{Component, Path, PathBuf};use std::sync::Arc;use std::sync::atomic::AtomicU64;+use tokio::sync::mpsc;use uuid::Uuid;use walkdir::WalkDir;@@ -103,6 +106,97 @@ fn collect_path(path: &Path) -> Vec<CollectedPath> {.collect()}+/// Collects `picked` and spawns the send task towards `device`. Returns the+/// state tracking the transfer, or the reason the transfer could not start.+pub(super) fn spawn_send(+ ui: &mut Ui,+ identity: Arc<Identity>,+ device: StatefulDevice,+ picked: Vec<PathBuf>,+ events_tx: mpsc::Sender<AppEvent>,+) -> Result<SendState, String> {+ let Some(host) = device+ .get_best_channel()+ .and_then(|channel| channel.http())+ .map(|http| http.host.clone())+ else {+ return Err(format!("{}: No dialable address", device.device.alias));+ };++ let (files, paths, total_bytes) = collect_files(ui, picked);+ if files.is_empty() {+ return Err("No files selected".to_string());+ }++ let progress = Arc::new(AtomicU64::new(0));+ let cancel = send_task::SendCancel::new();+ let state = SendState {+ session_id: None,+ alias: device.device.alias.clone(),+ host,+ total_bytes,+ sent: progress.clone(),+ cancel: cancel.clone(),+ speed: SpeedMeter::new(),+ };+ tokio::spawn(send_task::run_send(+ identity, device, files, paths, progress, cancel, events_tx,+ ));+ Ok(state)+}++/// Expands and stats picked files/directories into transfer metadata keyed+/// by a fresh file ID, plus paths under the same IDs and the total byte+/// count. Entries that are not readable files are skipped with a log line.+pub(super) fn collect_files(+ ui: &mut Ui,+ picked: Vec<PathBuf>,+) -> (HashMap<String, FileDto>, HashMap<String, PathBuf>, u64) {+ let mut files = HashMap::new();+ let mut paths = HashMap::new();+ let mut total_bytes = 0u64;+ for collected in picked.iter().flat_map(|path| collect_path(path)) {+ let (path, file_name) = match collected {+ Ok(collected) => collected,+ Err((path, error)) => {+ ui.log(+ Category::Send,+ &format!("Skipping unreadable path: {} ({error})", path.display()),+ );+ continue;+ }+ };+ let metadata = match std::fs::metadata(&path) {+ Ok(metadata) if metadata.is_file() => metadata,+ _ => {+ ui.log(+ Category::Send,+ &format!("Skipping unreadable file: {}", path.display()),+ );+ continue;+ }+ };+ let id = Uuid::new_v4().to_string();+ total_bytes += metadata.len();+ files.insert(+ id.clone(),+ FileDto {+ id: id.clone(),+ file_name,+ size: metadata.len(),+ file_type: mime_guess::from_path(&path)+ .first_or_octet_stream()+ .to_string(),+ sha256: None,+ preview: None,+ metadata: FileMetadata::from_fs_metadata(&metadata),+ },+ );+ paths.insert(id, path);+ }+ (files, paths, total_bytes)+}+impl App {pub(super) fn start_picking(&mut self, slot: u8) {let device = self@@ -126,18 +220,23 @@ impl App {pub(super) fn open_picker(&mut self, target: PickerTarget) {if matches!(target, PickerTarget::Device { .. }) && self.send.is_some() {- self.close_device_list();+ self.close_overlay();self.ui.log(Category::Send, "A send is already in progress");return;}// When the device list is open, the picker takes over its alternate// screen — leaving and re-entering it would flash the main screen.- let handoff = match self.device_list.take() {- Some(list) => {+ let handoff = match std::mem::replace(&mut self.overlay, Overlay::None) {+ Overlay::DeviceList(list) => {list.close_keeping_screen();true}- None => false,+ // An open picker never reaches here: it consumes every key.+ Overlay::Picker(picker) => {+ picker.close();+ false+ }+ Overlay::None => false,};let opened = match handoff {true => Picker::open_on_alternate_screen(target),@@ -146,7 +245,7 @@ impl App {match opened {Ok(picker) => {self.ui.suspend();- self.picker = Some(picker);+ self.overlay = Overlay::Picker(Box::new(picker));}Err(err) => {if handoff {@@ -162,16 +261,14 @@ impl App {}pub(super) async fn handle_picker_key(&mut self, key: KeyEvent) {- let Some(picker) = &mut self.picker else {+ let Overlay::Picker(picker) = &mut self.overlay else {return;};match picker.handle_key(key) {PickerOutcome::Open => {}PickerOutcome::Picked(files) => {- let picker = self.picker.take().unwrap();let target = picker.target.clone();- picker.close();- self.ui.resume();+ self.close_overlay();match target {PickerTarget::Device { fingerprint, .. } => {self.start_send(&fingerprint, files)@@ -179,11 +276,7 @@ impl App {PickerTarget::WebShare => self.enable_web_share(files).await,}}- PickerOutcome::Cancelled => {- let picker = self.picker.take().unwrap();- picker.close();- self.ui.resume();- }+ PickerOutcome::Cancelled => self.close_overlay(),}}@@ -195,97 +288,16 @@ impl App {let Some(device) = self.discovery.device_by_fingerprint(fingerprint) else {return;};- let Some(host) = device- .get_best_channel()- .and_then(|channel| channel.http())- .map(|http| http.host.clone())- else {- self.ui.log(- Category::Send,- &format!("{}: No dialable address", device.device.alias),- );- return;- };-- let (files, paths, total_bytes) = self.collect_files(picked);- if files.is_empty() {- self.ui.log(Category::Send, "No files selected");- return;- }-- let progress = Arc::new(AtomicU64::new(0));- let cancel = send_task::SendCancel::new();- self.send = Some(SendState {- session_id: None,- alias: device.device.alias.clone(),- host,- total_bytes,- sent: progress.clone(),- cancel: cancel.clone(),- speed: SpeedMeter::new(),- });-- tokio::spawn(send_task::run_send(+ match spawn_send(+ &mut self.ui,self.storage.identity.clone(),device,- files,- paths,- progress,- cancel,+ picked,self.events_tx.clone(),- ));- }-- /// Expands and stats picked files/directories into transfer metadata keyed- /// by a fresh file ID, plus paths under the same IDs and the total byte- /// count. Entries that are not readable files are skipped with a log line.- pub(super) fn collect_files(- &mut self,- picked: Vec<PathBuf>,- ) -> (HashMap<String, FileDto>, HashMap<String, PathBuf>, u64) {- let mut files = HashMap::new();- let mut paths = HashMap::new();- let mut total_bytes = 0u64;- for collected in picked.iter().flat_map(|path| collect_path(path)) {- let (path, file_name) = match collected {- Ok(collected) => collected,- Err((path, error)) => {- self.ui.log(- Category::Send,- &format!("Skipping unreadable path: {} ({error})", path.display()),- );- continue;- }- };- let metadata = match std::fs::metadata(&path) {- Ok(metadata) if metadata.is_file() => metadata,- _ => {- self.ui.log(- Category::Send,- &format!("Skipping unreadable file: {}", path.display()),- );- continue;- }- };- let id = Uuid::new_v4().to_string();- total_bytes += metadata.len();- files.insert(- id.clone(),- FileDto {- id: id.clone(),- file_name,- size: metadata.len(),- file_type: mime_guess::from_path(&path)- .first_or_octet_stream()- .to_string(),- sha256: None,- preview: None,- metadata: FileMetadata::from_fs_metadata(&metadata),- },- );- paths.insert(id, path);+ ) {+ Ok(state) => self.send = Some(state),+ Err(reason) => self.ui.log(Category::Send, &reason),}- (files, paths, total_bytes)}}diff --git a/cli/src/app/status.rs b/cli/src/app/status.rsindex 3043a156..e87fb9f9 100644--- a/cli/src/app/status.rs+++ b/cli/src/app/status.rs@@ -1,7 +1,7 @@//! The status line at the bottom of the screen: one progress bar per active//! transfer, refreshed by the tick of the main loop.-use super::App;+use super::{App, Overlay};use crate::ui::Category;use crate::util;use std::sync::atomic::Ordering;@@ -9,15 +9,15 @@ use std::time::Duration;impl App {pub(super) fn tick(&mut self) {- if let Some(picker) = &mut self.picker {+ if let Overlay::Picker(picker) = &mut self.overlay {// Covers terminal resizes; key presses redraw on their own.picker.draw();return;}- if self.device_list.is_some() {+ if matches!(self.overlay, Overlay::DeviceList(_)) {// Also picks up devices discovered while the list is open.let rows = self.device_rows();- if let Some(list) = &mut self.device_list {+ if let Overlay::DeviceList(list) = &mut self.overlay {list.set_rows(rows);list.draw();}@@ -72,7 +72,7 @@ impl App {/// Formats one transfer for the status line, sizing the progress bar so the/// whole entry occupies `width` visible columns.-fn transfer_status(+pub(super) fn transfer_status(category: Category,alias: &str,done: u64,diff --git a/cli/src/app/web_link.rs b/cli/src/app/web_link.rsindex db569c0c..1a68741e 100644--- a/cli/src/app/web_link.rs+++ b/cli/src/app/web_link.rs@@ -5,15 +5,17 @@//! active the server is restarted without TLS and the links use plain//! `http://`. Toggling off restarts the encrypted server.-use super::App;+use super::{App, sending};use crate::picker::PickerTarget;use crate::ui::Category;use crate::util;-use localsend::http::server::web::{WebConfig, WebMode as CoreWebMode, WebDownloadConfig, WebDownloadEvent};+use localsend::http::server::web::{+ WebConfig, WebDownloadConfig, WebDownloadEvent, WebMode as CoreWebMode,+};use localsend::http::server::{ServerConfigV2, start_with_port};use localsend::model::transfer::FileContent;-use qrcode::{EcLevel, QrCode};use qrcode::render::unicode;+use qrcode::{EcLevel, QrCode};use std::collections::HashMap;use std::path::PathBuf;use std::sync::Arc;@@ -106,7 +108,7 @@ impl App {/// Restarts the server in plain-HTTP mode offering `picked` for download/// and prints the links to open in a browser.pub(super) async fn enable_web_share(&mut self, picked: Vec<PathBuf>) {- let (files, paths, total_bytes) = self.collect_files(picked);+ let (files, paths, total_bytes) = sending::collect_files(&mut self.ui, picked);if files.is_empty() {self.ui.log(Category::Send, "No files selected");return;@@ -155,7 +157,8 @@ impl App {/// code (light on dark), which phone scanners accept.fn web_qr(&self) -> Option<String> {let address = self.server.local_addresses().into_iter().next()?;- let code = QrCode::with_error_correction_level(format!("http://{address}"), EcLevel::L).ok()?;+ let code =+ QrCode::with_error_correction_level(format!("http://{address}"), EcLevel::L).ok()?;Some(code.render::<unicode::Dense1x2>().quiet_zone(false).build())}