diff --git a/CLAUDE.md b/CLAUDE.md
index d850d73..90efcf7 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -89,11 +89,12 @@ Never modify: `PROMPT.md` (the user's brief), the user's other projects under `~
| `XDG_DATA_HOME=
/data cargo run -p tunal-core --example ops -- ` (refuses unless XDG_DATA_HOME is inside ``) | job engine + trash smoke run: conflicts, cancel, trash/restore/empty | S007 |
| `cargo run -p tunal -- --gallery --screenshot [--dark] --size 1200x1000` (`--gallery` alone opens it in a window) | every control in rest/hover/pressed/focused/disabled; press squeeze not drawn by the software renderer | S004 |
| `cargo run -p tunal -- --gallery --page menu\|dialog --screenshot [--dark] --size 960x640` | open menu + submenu + two toasts, or dialog + indeterminate toast, over a stand-in folder | S005 |
-| `TUNAL_SETTINGS=<0-4> cargo run -p tunal -- --screenshot --size 1000x700` (`XDG_CONFIG_HOME=`) | settings dialog page over a folder | S013 |
+| `TUNAL_SETTINGS=<0-5> cargo run -p tunal -- --screenshot --size 1000x700` (`XDG_CONFIG_HOME=`) | settings dialog page over a folder | S013 |
| `TUNAL_DRAG=x1,y1,x2,y2[,hold] TUNAL_REDUCED_MOTION=1 cargo run -p tunal -- --screenshot --size 1200x760` (`XDG_CONFIG_HOME=`) | drags between window points and drops (drop menu) or holds (glow + drag image) before the frame | S014 |
| `TUNAL_APPEARANCE=1 XDG_CONFIG_HOME= cargo run -p tunal -- --screenshot --size 1000x760` | folder appearance dialog for `` (theme icons looked up at once); `cargo run -p tunal-dirmeta --example roundtrip -- ` sets `Icon` in `/.directory` and prints the old values | S015 |
| `TUNAL_PLAY= XDG_CONFIG_HOME= cargo run -p tunal -- --screenshot [--dark] --size 1200x760` | player bar open on that file, a third in (tags, cover, waveform read at once; no audio output) | S023 |
| `TUNAL_TAGS=editor\|lookup\|mapping\|apply:: TUNAL_TAGS_SYNC=1 TUNAL_MUSICBRAINZ= XDG_CONFIG_HOME= cargo run -p tunal -- --screenshot --size 1000x760` | tag editor / lookup / mapping over a folder; `apply` also writes the tags (scratch copies only); mock = a local server for both services | S021 |
+| `cargo run -p tunal -- --gallery --page connection\|host-key\|secret --screenshot [--dark] --size 960x640` | the connection editor, the unknown-host-key prompt, the password prompt over a stand-in folder; with a scratch `HOME` (own `.ssh/config`, key) and `XDG_CONFIG_HOME` holding `tunal/connections.toml`, `session.toml` (pane `sftp://…`) and a trusted `known_hosts`, a normal `--screenshot` shows the Network section and an SFTP folder (local sshd on a spare port only) | S029 |
Don't assume a tool exists: check first. When your plan creates a tool, add its row here.
diff --git a/Cargo.lock b/Cargo.lock
index 8fd087b..988e0a8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6994,6 +6994,7 @@ dependencies = [
"image",
"jiff",
"png",
+ "secrecy",
"serde",
"slint",
"slint-build",
@@ -7002,6 +7003,7 @@ dependencies = [
"tunal-devices",
"tunal-dirmeta",
"tunal-elevate",
+ "tunal-net",
"tunal-player",
"tunal-tags",
"tunal-theme",
diff --git a/Plans/10 Network/S029-sftp-ui.md b/Plans/10 Network/S029-sftp-ui.md
index e7d8dd9..7fc170b 100644
--- a/Plans/10 Network/S029-sftp-ui.md
+++ b/Plans/10 Network/S029-sftp-ui.md
@@ -10,11 +10,11 @@ Saved connections and ssh-config hosts in places; prompts for unknown hosts, pas
crates/tunal-net API; places API; crates/tunal/ui/components/{dialog,text-field}.slint; CLAUDE.md §3 (secrets).
## Steps
-- [ ] `connections.toml`: name, host, port, user, start folder, auth (agent / key path / password — the password itself is never saved); add/edit/remove dialog.
-- [ ] Network section in places: saved connections and ssh-config hosts ('save as connection'); opening one opens a tab at its `sftp://` URI; breadcrumb accepts `sftp://`.
-- [ ] Prompts: unknown host (fingerprint; accept once / always), mismatch warning, password and passphrase (secret field moved into a secret type at once, field cleared).
-- [ ] Connection state and errors with retry; disconnect action.
-- [ ] PROGRESS entry, INDEX line, commit `S029: …`
+- [x] `connections.toml`: name, host, port, user, start folder, auth (agent / key path / password — the password itself is never saved); add/edit/remove dialog.
+- [x] Network section in places: saved connections and ssh-config hosts ('save as connection'); opening one opens a tab at its `sftp://` URI; breadcrumb accepts `sftp://`.
+- [x] Prompts: unknown host (fingerprint; accept once / always), mismatch warning, password and passphrase (secret field moved into a secret type at once, field cleared).
+- [x] Connection state and errors with retry; disconnect action.
+- [x] PROGRESS entry, INDEX line, commit `S029: …`
## End criteria
- `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass.
diff --git a/Plans/INDEX.md b/Plans/INDEX.md
index 5edf266..bb5d3ed 100644
--- a/Plans/INDEX.md
+++ b/Plans/INDEX.md
@@ -63,7 +63,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v
- [x] [S027 — ssh config and known_hosts](10%20Network/S027-ssh-config-known-hosts.md) · Sonnet high
- [x] [S028 — SFTP location](10%20Network/S028-sftp-location.md) · Opus high
-- [ ] [S029 — SFTP connections in the UI](10%20Network/S029-sftp-ui.md) · Opus high
+- [x] [S029 — SFTP connections in the UI](10%20Network/S029-sftp-ui.md) · Opus high
## 11 Native drag and drop
diff --git a/crates/tunal-net/examples/sftp-ls.rs b/crates/tunal-net/examples/sftp-ls.rs
index 951507f..dde50a4 100644
--- a/crates/tunal-net/examples/sftp-ls.rs
+++ b/crates/tunal-net/examples/sftp-ls.rs
@@ -7,7 +7,7 @@ use std::sync::Arc;
use secrecy::SecretString;
use tunal_core::{Location, Uri};
-use tunal_net::auth::{HostKeyInfo, InteractiveRequest, Prompts};
+use tunal_net::auth::{HostKeyChoice, HostKeyInfo, InteractiveRequest, Prompts};
use tunal_net::sftp::SftpLocation;
struct Terminal;
@@ -28,13 +28,16 @@ fn line(prompt: &str, hidden: bool) -> Option {
}
impl Prompts for Terminal {
- fn confirm_host_key(&self, i: &HostKeyInfo) -> bool {
+ fn confirm_host_key(&self, i: &HostKeyInfo) -> HostKeyChoice {
use secrecy::ExposeSecret;
let q = format!(
"Unknown host {}:{} {} {}. Accept? [y/N]",
i.host, i.port, i.key_type, i.fingerprint
);
- line(&q, false).is_some_and(|a| a.expose_secret().eq_ignore_ascii_case("y"))
+ match line(&q, false) {
+ Some(a) if a.expose_secret().eq_ignore_ascii_case("y") => HostKeyChoice::Always,
+ _ => HostKeyChoice::Refuse,
+ }
}
fn password(&self, user: &str, host: &str) -> Option {
diff --git a/crates/tunal-net/src/auth.rs b/crates/tunal-net/src/auth.rs
index 869ee8e..28b05e3 100644
--- a/crates/tunal-net/src/auth.rs
+++ b/crates/tunal-net/src/auth.rs
@@ -16,6 +16,29 @@ use crate::ssh_config::{Resolved, ssh_dir};
const MAX_TRIES: usize = 3;
+/// The user's answer to an unknown host key.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum HostKeyChoice {
+ Refuse,
+ /// Connect now, ask again next time.
+ Once,
+ /// Connect and remember the key in Tunal's known_hosts.
+ Always,
+}
+
+/// Which credentials a host uses.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub enum AuthPref {
+ /// Agent, then identity files, then password (hosts from ssh config).
+ #[default]
+ Any,
+ Agent,
+ /// Only this private key file.
+ Key(PathBuf),
+ /// Only password or keyboard-interactive.
+ Password,
+}
+
/// A host key not seen before, shown to the user to accept or refuse.
#[derive(Debug, Clone)]
pub struct HostKeyInfo {
@@ -46,11 +69,14 @@ pub struct InteractiveRequest {
/// Questions the connection layer asks the user. Called on a worker thread and may block
/// until the user answers; `None` / `false` means the user cancelled. Defaults refuse.
pub trait Prompts: Send + Sync {
- /// Unknown host key: accept (and remember in Tunal's known_hosts) or refuse.
- fn confirm_host_key(&self, _info: &HostKeyInfo) -> bool {
- false
+ /// Unknown host key: refuse, accept once or accept and remember.
+ fn confirm_host_key(&self, _info: &HostKeyInfo) -> HostKeyChoice {
+ HostKeyChoice::Refuse
}
+ /// The host's key differs from the one on record; the connection is refused after this.
+ fn host_key_changed(&self, _info: &HostKeyInfo) {}
+
/// Account password for `user@host`.
fn password(&self, _user: &str, _host: &str) -> Option {
None
@@ -86,9 +112,14 @@ pub(crate) async fn authenticate(
user: &str,
host: &str,
resolved: &Resolved,
+ pref: &AuthPref,
prompts: &Arc,
) -> Result<(), Error> {
- let files = identity_files(resolved);
+ let files = match pref {
+ AuthPref::Any | AuthPref::Agent => identity_files(resolved),
+ AuthPref::Key(file) => vec![file.clone()],
+ AuthPref::Password => Vec::new(),
+ };
let rsa_hash = handle
.best_supported_rsa_hash()
.await
@@ -96,14 +127,21 @@ pub(crate) async fn authenticate(
.flatten()
.flatten();
- if try_agent(handle, user, resolved, &files, rsa_hash).await {
+ if matches!(pref, AuthPref::Any | AuthPref::Agent)
+ && try_agent(handle, user, resolved, &files, rsa_hash).await
+ {
return Ok(());
}
- for file in &files {
- if try_key_file(handle, user, file, rsa_hash, prompts).await {
- return Ok(());
+ if *pref != AuthPref::Agent {
+ for file in &files {
+ if try_key_file(handle, user, file, rsa_hash, prompts).await {
+ return Ok(());
+ }
}
}
+ if matches!(pref, AuthPref::Agent | AuthPref::Key(_)) {
+ return Err(denied());
+ }
let methods = match handle.authenticate_none(user).await {
Ok(result) if result.success() => return Ok(()),
diff --git a/crates/tunal-net/src/lib.rs b/crates/tunal-net/src/lib.rs
index 17065c0..24eb12e 100644
--- a/crates/tunal-net/src/lib.rs
+++ b/crates/tunal-net/src/lib.rs
@@ -3,6 +3,8 @@
pub mod auth;
pub mod known_hosts;
mod session;
+
+pub use session::{Options, set_options};
pub mod sftp;
pub mod ssh_config;
diff --git a/crates/tunal-net/src/session.rs b/crates/tunal-net/src/session.rs
index 789569a..2ca3a6e 100644
--- a/crates/tunal-net/src/session.rs
+++ b/crates/tunal-net/src/session.rs
@@ -12,15 +12,45 @@ use russh_sftp::client::SftpSession;
use tokio::runtime::Runtime;
use tunal_core::{Error, Result};
-use crate::auth::{HostKeyInfo, Prompts, authenticate};
+use crate::auth::{AuthPref, HostKeyChoice, HostKeyInfo, Prompts, authenticate};
use crate::known_hosts::{self, HostCheck, KnownHosts};
use crate::ssh_config::Resolved;
-const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
-const KEEPALIVE: Duration = Duration::from_secs(30);
-const IDLE_CLOSE: Duration = Duration::from_secs(300);
const SWEEP: Duration = Duration::from_secs(30);
+/// Connection settings; new values apply to connections made afterwards (idle close at once).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Options {
+ pub connect_timeout: Duration,
+ /// `None`: no keepalive messages.
+ pub keepalive: Option,
+ pub idle_close: Duration,
+}
+
+impl Default for Options {
+ fn default() -> Self {
+ Self {
+ connect_timeout: Duration::from_secs(15),
+ keepalive: Some(Duration::from_secs(30)),
+ idle_close: Duration::from_secs(300),
+ }
+ }
+}
+
+static OPTIONS: Mutex = Mutex::new(Options {
+ connect_timeout: Duration::from_secs(15),
+ keepalive: Some(Duration::from_secs(30)),
+ idle_close: Duration::from_secs(300),
+});
+
+pub fn set_options(options: Options) {
+ *OPTIONS.lock().unwrap() = options;
+}
+
+fn options() -> Options {
+ *OPTIONS.lock().unwrap()
+}
+
fn runtime() -> &'static Runtime {
static RT: OnceLock = OnceLock::new();
RT.get_or_init(|| {
@@ -95,12 +125,12 @@ impl Pool {
}
/// A live connection for `key`, connecting (and authenticating) when needed.
- pub fn get(&self, key: &ConnKey, resolved: &Resolved) -> Result> {
+ pub fn get(&self, key: &ConnKey, resolved: &Resolved, pref: &AuthPref) -> Result> {
if let Some(c) = self.conns.lock().unwrap().get(key).filter(|c| c.alive()) {
c.touch();
return Ok(c.clone());
}
- let conn = block_on(connect(key, resolved, &self.prompts))?;
+ let conn = block_on(connect(key, resolved, pref, &self.prompts))?;
self.conns.lock().unwrap().insert(key.clone(), conn.clone());
Ok(conn)
}
@@ -113,13 +143,29 @@ impl Pool {
}
}
+ pub fn is_connected(&self, key: &ConnKey) -> bool {
+ self.conns
+ .lock()
+ .unwrap()
+ .get(key)
+ .is_some_and(|c| c.alive())
+ }
+
+ /// Closes the connection to `key` (streams still open on it fail).
+ pub fn disconnect(&self, key: &ConnKey) {
+ let conn = self.conns.lock().unwrap().remove(key);
+ if let Some(conn) = conn {
+ block_on(conn.close());
+ }
+ }
+
/// Closes connections unused for `IDLE_CLOSE` that nothing else holds (open streams do).
async fn close_idle(&self) {
let stale: Vec> = {
let mut conns = self.conns.lock().unwrap();
let mut out = Vec::new();
conns.retain(|_, c| {
- let idle = c.last_used.lock().unwrap().elapsed() > IDLE_CLOSE;
+ let idle = c.last_used.lock().unwrap().elapsed() > options().idle_close;
let drop_it = !c.alive() || (idle && Arc::strong_count(c) == 1);
if drop_it {
out.push(c.clone());
@@ -137,15 +183,17 @@ impl Pool {
async fn connect(
key: &ConnKey,
resolved: &Resolved,
+ pref: &AuthPref,
prompts: &Arc,
) -> Result> {
+ let opts = options();
if resolved.unsupported_proxy {
return Err(Error::Remote(
"hosts behind ProxyJump / ProxyCommand are not supported".into(),
));
}
let config = Arc::new(client::Config {
- keepalive_interval: Some(KEEPALIVE),
+ keepalive_interval: opts.keepalive,
keepalive_max: 3,
..Default::default()
});
@@ -158,7 +206,7 @@ async fn connect(
failure: failure.clone(),
};
let connecting = client::connect(config, (key.host.as_str(), key.port), client);
- let mut handle = match tokio::time::timeout(CONNECT_TIMEOUT, connecting).await {
+ let mut handle = match tokio::time::timeout(opts.connect_timeout, connecting).await {
Err(_) => {
return Err(Error::Remote(format!(
"connecting to {} timed out",
@@ -167,11 +215,11 @@ async fn connect(
}
Ok(Err(e)) => {
let reason = failure.lock().unwrap().take();
- return Err(Error::Remote(reason.unwrap_or_else(|| e.to_string())));
+ return Err(Error::Remote(reason.unwrap_or_else(|| why(&e, &key.host))));
}
Ok(Ok(h)) => h,
};
- authenticate(&mut handle, &key.user, &key.host, resolved, prompts).await?;
+ authenticate(&mut handle, &key.user, &key.host, resolved, pref, prompts).await?;
let remote = |e: &dyn std::fmt::Display| Error::Remote(e.to_string());
let channel = handle
.channel_open_session()
@@ -191,6 +239,24 @@ async fn connect(
}))
}
+/// A russh failure in plain words.
+fn why(e: &russh::Error, host: &str) -> String {
+ use std::io::ErrorKind::*;
+ match e {
+ russh::Error::IO(io) => match io.kind() {
+ ConnectionRefused => format!("{host} refused the connection"),
+ TimedOut => format!("{host} didn't answer in time"),
+ ConnectionReset | UnexpectedEof | BrokenPipe => format!("{host} closed the connection"),
+ _ if io.to_string().contains("lookup") || io.to_string().contains("resolve") => {
+ format!("couldn't find {host}")
+ }
+ _ => format!("couldn't reach {host}"),
+ },
+ russh::Error::Disconnect | russh::Error::HUP => format!("{host} closed the connection"),
+ _ => format!("couldn't connect to {host}"),
+ }
+}
+
/// russh handler: checks the server key against known_hosts.
struct Client {
host: String,
@@ -201,6 +267,17 @@ struct Client {
failure: Arc>>,
}
+impl Client {
+ fn info(&self, key_type: &str, fingerprint: String) -> HostKeyInfo {
+ HostKeyInfo {
+ host: self.host.clone(),
+ port: self.port,
+ key_type: key_type.to_owned(),
+ fingerprint,
+ }
+ }
+}
+
impl client::Handler for Client {
type Error = russh::Error;
@@ -221,39 +298,35 @@ impl client::Handler for Client {
.and_then(|l| l.split_whitespace().nth(1).map(str::to_owned));
let Some(blob) = blob else { return Ok(false) };
let fail = |msg: String| *self.failure.lock().unwrap() = Some(msg);
- match self.known.check(&self.host, self.port, &key_type, &blob) {
+ let check = self.known.check(&self.host, self.port, &key_type, &blob);
+ match check {
HostCheck::Match => Ok(true),
- HostCheck::Mismatch => {
- fail(format!(
- "host key of {} changed ({fingerprint}); someone may be intercepting the connection",
- self.host
- ));
- Ok(false)
- }
- HostCheck::Revoked => {
- fail(format!(
- "host key of {} is revoked ({fingerprint})",
- self.host
- ));
+ HostCheck::Mismatch | HostCheck::Revoked => {
+ let revoked = check == HostCheck::Revoked;
+ let info = self.info(&key_type, fingerprint);
+ let prompts = self.prompts.clone();
+ let _ = tokio::task::spawn_blocking(move || prompts.host_key_changed(&info)).await;
+ fail(if revoked {
+ format!("the host key of {} is revoked", self.host)
+ } else {
+ format!(
+ "the host key of {} changed; someone may be intercepting the connection",
+ self.host
+ )
+ });
Ok(false)
}
HostCheck::Unknown => {
- let info = HostKeyInfo {
- host: self.host.clone(),
- port: self.port,
- key_type: key_type.clone(),
- fingerprint,
- };
+ let info = self.info(&key_type, fingerprint);
let prompts = self.prompts.clone();
- let ask = info.clone();
- let accepted = tokio::task::spawn_blocking(move || prompts.confirm_host_key(&ask))
+ let choice = tokio::task::spawn_blocking(move || prompts.confirm_host_key(&info))
.await
- .unwrap_or(false);
- if !accepted {
- fail(format!("host key of {} was not accepted", self.host));
+ .unwrap_or(HostKeyChoice::Refuse);
+ if choice == HostKeyChoice::Refuse {
+ fail(format!("the host key of {} was not accepted", self.host));
return Ok(false);
}
- if let Some(own) = known_hosts::own_file() {
+ if let (HostKeyChoice::Always, Some(own)) = (choice, known_hosts::own_file()) {
let _ = known_hosts::accept_key(&own, &self.host, self.port, &key_type, &blob);
}
Ok(true)
diff --git a/crates/tunal-net/src/sftp.rs b/crates/tunal-net/src/sftp.rs
index aa2c96e..a91b730 100644
--- a/crates/tunal-net/src/sftp.rs
+++ b/crates/tunal-net/src/sftp.rs
@@ -14,9 +14,11 @@ use tunal_core::{
display_name,
};
-use crate::auth::Prompts;
+use crate::auth::{AuthPref, Prompts};
use crate::session::{Conn, ConnKey, Pool, block_on};
use crate::ssh_config::SshConfig;
+use std::collections::HashMap;
+use std::sync::Mutex;
/// Scheme of SFTP locations.
pub const SCHEME: &str = "sftp";
@@ -26,6 +28,8 @@ const CHUNK: usize = 256;
pub struct SftpLocation {
pool: Arc,
config: SshConfig,
+ /// Credentials per host (lower case, as written in the URI).
+ prefs: Mutex>,
}
impl SftpLocation {
@@ -38,6 +42,7 @@ impl SftpLocation {
Self {
pool: Pool::new(prompts),
config,
+ prefs: Mutex::default(),
}
}
@@ -47,7 +52,29 @@ impl SftpLocation {
Ok(Uri::new(SCHEME, uri.authority(), home.into_bytes()))
}
- fn conn(&self, uri: &Uri) -> Result<(ConnKey, Arc)> {
+ /// Sets which credentials `host` (as it appears in `sftp://` URIs) uses.
+ pub fn set_auth(&self, host: &str, pref: AuthPref) {
+ self.prefs
+ .lock()
+ .unwrap()
+ .insert(host.to_ascii_lowercase(), pref);
+ }
+
+ /// True while a live connection to `uri`'s host is open.
+ pub fn is_connected(&self, uri: &Uri) -> bool {
+ self.target(uri)
+ .is_ok_and(|(key, ..)| self.pool.is_connected(&key))
+ }
+
+ /// Closes the connection to `uri`'s host; the next access connects again.
+ pub fn disconnect(&self, uri: &Uri) {
+ if let Ok((key, ..)) = self.target(uri) {
+ self.pool.disconnect(&key);
+ }
+ }
+
+ /// Where `uri` goes: connection key, resolved host options and credentials.
+ fn target(&self, uri: &Uri) -> Result<(ConnKey, crate::ssh_config::Resolved, AuthPref)> {
if uri.scheme() != SCHEME {
return Err(Error::Unsupported);
}
@@ -63,7 +90,19 @@ impl SftpLocation {
host: resolved.host_name.clone(),
port: port.unwrap_or(resolved.port),
};
- let conn = self.pool.get(&key, &resolved)?;
+ let pref = self
+ .prefs
+ .lock()
+ .unwrap()
+ .get(&host.to_ascii_lowercase())
+ .cloned()
+ .unwrap_or_default();
+ Ok((key, resolved, pref))
+ }
+
+ fn conn(&self, uri: &Uri) -> Result<(ConnKey, Arc)> {
+ let (key, resolved, pref) = self.target(uri)?;
+ let conn = self.pool.get(&key, &resolved, &pref)?;
Ok((key, conn))
}
diff --git a/crates/tunal/Cargo.toml b/crates/tunal/Cargo.toml
index c454468..f49df0a 100644
--- a/crates/tunal/Cargo.toml
+++ b/crates/tunal/Cargo.toml
@@ -16,6 +16,8 @@ tunal-dirmeta = { path = "../tunal-dirmeta" }
tunal-thumbs = { path = "../tunal-thumbs" }
tunal-tags = { path = "../tunal-tags" }
tunal-player = { path = "../tunal-player" }
+tunal-net = { path = "../tunal-net" }
+secrecy.workspace = true
image.workspace = true
jiff.workspace = true
serde.workspace = true
diff --git a/crates/tunal/src/actions.rs b/crates/tunal/src/actions.rs
index c967d52..10ffe01 100644
--- a/crates/tunal/src/actions.rs
+++ b/crates/tunal/src/actions.rs
@@ -257,6 +257,11 @@ pub struct Actions {
}
impl Actions {
+ /// A short message toast.
+ pub fn notify(&self, message: String) {
+ self.bridge.notify(message);
+ }
+
pub fn attach(ui: &MainWindow, shell: &Rc, locations: Locations) -> Rc {
let bridge = Bridge::attach(ui, locations.clone());
let opener = Opener::attach(ui, locations.clone(), bridge.clone());
diff --git a/crates/tunal/src/config.rs b/crates/tunal/src/config.rs
index fd74e35..293ddc4 100644
--- a/crates/tunal/src/config.rs
+++ b/crates/tunal/src/config.rs
@@ -155,6 +155,14 @@ pub struct Settings {
pub preview_remote: bool,
/// The player goes on to the next audio file of the folder when a track ends.
pub player_next: bool,
+ /// Hosts of `~/.ssh/config` in the sidebar's Network section.
+ pub ssh_hosts: bool,
+ /// Seconds to wait for a server (5 to 120).
+ pub connect_timeout_secs: u32,
+ /// Seconds between keepalive messages, 0 for none.
+ pub keepalive_secs: u32,
+ /// Minutes of no use before a connection closes.
+ pub idle_close_mins: u32,
}
impl Default for Settings {
@@ -177,6 +185,10 @@ impl Default for Settings {
preview_max_mib: 64,
preview_remote: false,
player_next: true,
+ ssh_hosts: true,
+ connect_timeout_secs: 15,
+ keepalive_secs: 30,
+ idle_close_mins: 5,
}
}
}
diff --git a/crates/tunal/src/main.rs b/crates/tunal/src/main.rs
index 91c75bc..4f5228a 100644
--- a/crates/tunal/src/main.rs
+++ b/crates/tunal/src/main.rs
@@ -7,6 +7,7 @@ mod folder;
mod icons;
mod jobs_bridge;
mod menus;
+mod net_bridge;
mod open;
mod player_bridge;
mod properties;
@@ -26,7 +27,7 @@ use tunal_core::{Locations, Uri};
slint::include_modules!();
const USAGE: &str = "usage: tunal […] [--split ] \
- [--gallery [--page menu|dialog]] [--screenshot [--dark] [--size WxH]]";
+ [--gallery [--page menu|dialog|connection|host-key|secret]] [--screenshot [--dark] [--size WxH]]";
fn main() -> ExitCode {
// Root helper (`pkexec tunal --elevated-helper`): before any UI, theme or env lookups.
@@ -88,8 +89,10 @@ fn window(
.collect();
let mut locations = Locations::with_local();
let mtp = devices_bridge::register(&mut locations);
+ let net = net_bridge::register(&mut locations, &ui);
let shell = shell::Shell::attach(&ui, locations, tabs, blocking);
devices_bridge::attach(&shell, mtp);
+ net_bridge::attach(&ui, &shell, net);
// `TUNAL_SETTINGS=` opens the settings dialog (screenshots).
if let Some(page) = std::env::var("TUNAL_SETTINGS")
.ok()
@@ -156,6 +159,9 @@ fn parse(mut args: impl Iterator- ) -> Result
{
page = match args.next().as_deref() {
Some("menu") => GalleryPage::Menu,
Some("dialog") => GalleryPage::Dialog,
+ Some("connection") => GalleryPage::Connection,
+ Some("host-key") => GalleryPage::HostKey,
+ Some("secret") => GalleryPage::Secret,
_ => return Err(USAGE.into()),
}
}
diff --git a/crates/tunal/src/net_bridge.rs b/crates/tunal/src/net_bridge.rs
new file mode 100644
index 0000000..9eed7fa
--- /dev/null
+++ b/crates/tunal/src/net_bridge.rs
@@ -0,0 +1,645 @@
+//! SFTP in the shell: saved connections (`connections.toml`), the hosts of `~/.ssh/config`,
+//! the questions a connection asks (host key, password, passphrase) and the connection dialog.
+//!
+//! Passwords and passphrases are never stored: they go from the dialog into a secret type,
+//! to the connection, and are dropped.
+
+use std::cell::RefCell;
+use std::rc::{Rc, Weak};
+use std::sync::mpsc;
+use std::sync::{Arc, Mutex, PoisonError};
+use std::time::Duration;
+
+use secrecy::SecretString;
+use serde::{Deserialize, Serialize};
+use slint::ComponentHandle;
+use tunal_core::{Locations, Uri};
+use tunal_net::auth::{AuthPref, HostKeyChoice, HostKeyInfo, InteractiveRequest, Prompts};
+use tunal_net::sftp::{self, SftpLocation};
+use tunal_net::ssh_config::SshConfig;
+
+use crate::shell::Shell;
+use crate::shell::places::{Place, REMOTE};
+use crate::{ConnectionData, FolderActions, HostKeyData, MainWindow, SecretPromptData, config};
+
+/// Material Symbols `cloud_done`: a place with a live connection.
+const CONNECTED: &str = "\u{e2bf}";
+
+/// How a saved connection signs in.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+enum Auth {
+ /// Agent, default keys, then a password.
+ #[default]
+ Automatic,
+ Key,
+ Password,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(default)]
+struct Connection {
+ name: String,
+ /// A host name, address or an alias of `~/.ssh/config`.
+ host: String,
+ port: Option,
+ user: String,
+ /// Where the connection opens; empty for the home folder.
+ folder: String,
+ auth: Auth,
+ key_file: String,
+}
+
+impl Connection {
+ fn authority(&self) -> String {
+ let user = if self.user.is_empty() {
+ String::new()
+ } else {
+ format!("{}@", self.user)
+ };
+ match self.port {
+ Some(port) => format!("{user}{}:{port}", self.host),
+ None => format!("{user}{}", self.host),
+ }
+ }
+
+ /// The root of the connection, or its start folder.
+ fn uri(&self) -> Uri {
+ let folder = if self.folder.is_empty() {
+ "/"
+ } else {
+ &self.folder
+ };
+ Uri::new(sftp::SCHEME, &self.authority(), folder.as_bytes())
+ }
+
+ fn pref(&self) -> AuthPref {
+ match self.auth {
+ Auth::Automatic => AuthPref::Any,
+ Auth::Key => AuthPref::Key(expand(&self.key_file)),
+ Auth::Password => AuthPref::Password,
+ }
+ }
+}
+
+fn expand(path: &str) -> std::path::PathBuf {
+ match path.strip_prefix("~/") {
+ Some(rest) => crate::shell::places::home().join(rest),
+ None => path.into(),
+ }
+}
+
+/// `connections.toml`.
+#[derive(Debug, Default, Serialize, Deserialize)]
+#[serde(default)]
+struct Store {
+ connections: Vec,
+}
+
+/// One row of the Network section.
+#[derive(Clone)]
+enum Entry {
+ Saved(usize),
+ /// A host alias of `~/.ssh/config` that is not saved.
+ Config(String),
+}
+
+/// What the place menu offers on a Network entry.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Item {
+ Edit,
+ SaveAs,
+ Disconnect,
+ Remove,
+}
+
+impl Item {
+ fn label(self) -> &'static str {
+ match self {
+ Self::Edit => "Edit",
+ Self::SaveAs => "Save as connection",
+ Self::Disconnect => "Disconnect",
+ Self::Remove => "Remove",
+ }
+ }
+
+ fn glyph(self) -> &'static str {
+ match self {
+ Self::Edit => "\u{e3c9}",
+ Self::SaveAs => "\u{e145}",
+ Self::Disconnect => "\u{e16f}",
+ Self::Remove => "\u{e872}",
+ }
+ }
+}
+
+/// The UI thread's side.
+struct Net {
+ ui: slint::Weak,
+ shell: Weak,
+ sftp: Arc,
+ store: RefCell,
+ entries: RefCell>,
+ config: RefCell,
+ show_ssh_hosts: std::cell::Cell,
+ /// The saved connection the dialog edits, `None` for a new one.
+ editing: std::cell::Cell>,
+ /// What the sidebar shows now, to skip identical updates.
+ shown: RefCell>,
+}
+
+thread_local! {
+ static NET: RefCell>> = const { RefCell::new(None) };
+}
+
+fn net() -> Option> {
+ NET.with(|n| n.borrow().clone())
+}
+
+/// What the user answered to the question on screen.
+enum Answer {
+ Choice(i32),
+ Secret(Option),
+}
+
+/// The question on screen waits for its answer here.
+static PENDING: Mutex>> = Mutex::new(None);
+
+fn answer(a: Answer) {
+ let tx = PENDING
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .take();
+ if let Some(tx) = tx {
+ let _ = tx.send(a);
+ }
+}
+
+/// Shows the connection's questions in dialogs, one at a time. Called from connection threads.
+struct UiPrompts {
+ ui: slint::Weak,
+ one_at_a_time: Mutex<()>,
+}
+
+impl UiPrompts {
+ /// Runs `show` on the UI thread and waits for the dialog's answer.
+ fn ask(&self, show: impl FnOnce(&MainWindow) + Send + 'static) -> Option {
+ let _turn = self
+ .one_at_a_time
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner);
+ let (tx, rx) = mpsc::channel();
+ *PENDING.lock().unwrap_or_else(PoisonError::into_inner) = Some(tx);
+ self.ui.upgrade_in_event_loop(move |ui| show(&ui)).ok()?;
+ rx.recv().ok()
+ }
+
+ fn host_key(&self, info: &HostKeyInfo, changed: bool) -> Option {
+ let data = (
+ host_label(&info.host, info.port),
+ info.key_type.clone(),
+ info.fingerprint.clone(),
+ );
+ self.ask(move |ui| {
+ ui.set_host_key(HostKeyData {
+ host: data.0.into(),
+ key_type: data.1.into(),
+ fingerprint: data.2.into(),
+ changed,
+ });
+ ui.invoke_show_host_key();
+ })
+ }
+
+ fn secret(&self, data: (String, String, String, bool)) -> Option {
+ let answer = self.ask(move |ui| {
+ ui.set_secret_prompt(SecretPromptData {
+ title: data.0.into(),
+ body: data.1.into(),
+ label: data.2.into(),
+ echo: data.3,
+ });
+ ui.invoke_show_secret();
+ })?;
+ match answer {
+ Answer::Secret(secret) => secret,
+ Answer::Choice(_) => None,
+ }
+ }
+}
+
+fn host_label(host: &str, port: u16) -> String {
+ if port == 22 {
+ host.to_owned()
+ } else {
+ format!("{host}:{port}")
+ }
+}
+
+const SECRET_NOTE: &str = "Tunal uses it for this connection only and never saves it.";
+
+impl Prompts for UiPrompts {
+ fn confirm_host_key(&self, info: &HostKeyInfo) -> HostKeyChoice {
+ match self.host_key(info, false) {
+ Some(Answer::Choice(1)) => HostKeyChoice::Once,
+ Some(Answer::Choice(2)) => HostKeyChoice::Always,
+ _ => HostKeyChoice::Refuse,
+ }
+ }
+
+ fn host_key_changed(&self, info: &HostKeyInfo) {
+ self.host_key(info, true);
+ }
+
+ fn password(&self, user: &str, host: &str) -> Option {
+ self.secret((
+ format!("Password for {user}@{host}"),
+ SECRET_NOTE.into(),
+ "Password".into(),
+ false,
+ ))
+ }
+
+ fn passphrase(&self, key: &std::path::Path) -> Option {
+ let name = key.file_name().map_or_else(
+ || key.display().to_string(),
+ |n| n.to_string_lossy().into_owned(),
+ );
+ self.secret((
+ format!("Passphrase for {name}"),
+ SECRET_NOTE.into(),
+ "Passphrase".into(),
+ false,
+ ))
+ }
+
+ fn interactive(&self, req: &InteractiveRequest) -> Option> {
+ let title = if req.name.is_empty() {
+ "Sign in".to_owned()
+ } else {
+ req.name.clone()
+ };
+ req.prompts
+ .iter()
+ .map(|p| {
+ self.secret((
+ title.clone(),
+ req.instructions.clone(),
+ p.text.clone(),
+ p.echo,
+ ))
+ })
+ .collect()
+ }
+}
+
+/// Adds the SFTP backend to `locations`.
+pub fn register(locations: &mut Locations, ui: &MainWindow) -> Arc {
+ let prompts = Arc::new(UiPrompts {
+ ui: ui.as_weak(),
+ one_at_a_time: Mutex::new(()),
+ });
+ let sftp = Arc::new(SftpLocation::new(prompts));
+ locations.register(sftp.clone());
+ sftp
+}
+
+/// Binds the dialogs and fills the Network section.
+pub fn attach(ui: &MainWindow, shell: &Rc, sftp: Arc) {
+ let net = Rc::new(Net {
+ ui: ui.as_weak(),
+ shell: Rc::downgrade(shell),
+ sftp,
+ store: RefCell::new(config::load("connections")),
+ entries: RefCell::new(Vec::new()),
+ config: RefCell::new(SshConfig::load_default()),
+ show_ssh_hosts: std::cell::Cell::new(true),
+ editing: std::cell::Cell::new(None),
+ shown: RefCell::new(Vec::new()),
+ });
+ NET.with(|n| *n.borrow_mut() = Some(net.clone()));
+
+ ui.on_host_key_answered(|choice| answer(Answer::Choice(choice)));
+ ui.on_secret_answered(|ok, text| {
+ // Into a secret type at once; the dialog has already cleared its field.
+ let secret = ok.then(|| SecretString::from(text.to_string()));
+ answer(Answer::Secret(secret));
+ });
+ let weak = Rc::downgrade(&net);
+ ui.on_add_connection(move || {
+ if let Some(net) = weak.upgrade() {
+ net.edit(None, Connection::default());
+ }
+ });
+ let weak = Rc::downgrade(&net);
+ ui.on_connection_saved(move |data| {
+ weak.upgrade()
+ .map_or_else(Default::default, |net| net.save(&data).into())
+ });
+ let weak = Rc::downgrade(&net);
+ ui.on_connection_removed(move || {
+ if let Some(net) = weak.upgrade()
+ && let Some(i) = net.editing.get()
+ {
+ net.remove(i);
+ }
+ });
+ let weak = Rc::downgrade(&net);
+ ui.global::().on_retry(move || {
+ if let Some(shell) = weak.upgrade().and_then(|n| n.shell.upgrade()) {
+ shell.retry_failed();
+ }
+ });
+
+ let cfg: config::Settings = config::load("settings");
+ net.apply_options(&cfg);
+ net.set_auth_prefs();
+ net.refresh();
+}
+
+/// Settings changed: connection options and whether ssh config hosts show.
+pub fn configure(_shell: &Shell, cfg: &config::Settings) {
+ if let Some(net) = net() {
+ net.apply_options(cfg);
+ net.refresh();
+ }
+}
+
+/// A pane showing an SFTP folder changed: the connection may have opened or dropped.
+pub fn states_changed() {
+ if let Some(net) = net() {
+ net.refresh();
+ }
+}
+
+/// A Network entry was clicked.
+pub fn open(shell: &Shell, index: usize, new_tab: bool) {
+ if let Some(net) = net() {
+ net.open(shell, index, new_tab);
+ }
+}
+
+/// Labels and glyphs the place menu adds for Network entry `index`.
+pub fn menu_items(index: usize) -> Vec<(&'static str, &'static str)> {
+ net().map_or_else(Vec::new, |n| {
+ n.items(index)
+ .into_iter()
+ .map(|i| (i.label(), i.glyph()))
+ .collect()
+ })
+}
+
+/// Runs menu item `choice` (an index into [`menu_items`]) on Network entry `index`.
+pub fn menu_activated(index: usize, choice: usize) {
+ if let Some(net) = net()
+ && let Some(item) = net.items(index).get(choice).copied()
+ {
+ net.run(index, item);
+ }
+}
+
+impl Net {
+ fn apply_options(&self, cfg: &config::Settings) {
+ tunal_net::set_options(tunal_net::Options {
+ connect_timeout: Duration::from_secs(cfg.connect_timeout_secs.clamp(5, 120).into()),
+ keepalive: (cfg.keepalive_secs > 0)
+ .then(|| Duration::from_secs(cfg.keepalive_secs.into())),
+ idle_close: Duration::from_secs(u64::from(cfg.idle_close_mins.clamp(1, 120)) * 60),
+ });
+ self.show_ssh_hosts.set(cfg.ssh_hosts);
+ }
+
+ fn set_auth_prefs(&self) {
+ for c in &self.store.borrow().connections {
+ self.sftp.set_auth(&c.host, c.pref());
+ }
+ }
+
+ fn save_store(&self) {
+ config::store("connections", &*self.store.borrow());
+ }
+
+ /// Fills the sidebar: saved connections, then config hosts that are not saved.
+ fn refresh(&self) {
+ let Some(shell) = self.shell.upgrade() else {
+ return;
+ };
+ let store = self.store.borrow();
+ let mut entries: Vec = (0..store.connections.len()).map(Entry::Saved).collect();
+ if self.show_ssh_hosts.get() {
+ for alias in self.config.borrow().hosts() {
+ if !store.connections.iter().any(|c| c.host == alias) {
+ entries.push(Entry::Config(alias));
+ }
+ }
+ }
+ let places: Vec<(String, &'static str, Uri)> = entries
+ .iter()
+ .map(|e| {
+ let (name, uri) = self.target(&store, e);
+ let glyph = if self.sftp.is_connected(&uri) {
+ CONNECTED
+ } else {
+ REMOTE
+ };
+ (name, glyph, uri)
+ })
+ .collect();
+ drop(store);
+ *self.entries.borrow_mut() = entries;
+ if *self.shown.borrow() == places {
+ return;
+ }
+ *self.shown.borrow_mut() = places.clone();
+ shell.set_network(
+ places
+ .into_iter()
+ .map(|(name, glyph, uri)| Place { name, glyph, uri })
+ .collect(),
+ );
+ }
+
+ fn target(&self, store: &Store, entry: &Entry) -> (String, Uri) {
+ match entry {
+ Entry::Saved(i) => {
+ let c = &store.connections[*i];
+ (c.name.clone(), c.uri())
+ }
+ Entry::Config(alias) => (alias.clone(), Uri::new(sftp::SCHEME, alias, b"/".to_vec())),
+ }
+ }
+
+ fn entry(&self, index: usize) -> Option {
+ self.entries.borrow().get(index).cloned()
+ }
+
+ fn items(&self, index: usize) -> Vec- {
+ let Some(entry) = self.entry(index) else {
+ return Vec::new();
+ };
+ let store = self.store.borrow();
+ let (_, uri) = self.target(&store, &entry);
+ let mut items = vec![match entry {
+ Entry::Saved(_) => Item::Edit,
+ Entry::Config(_) => Item::SaveAs,
+ }];
+ if self.sftp.is_connected(&uri) {
+ items.push(Item::Disconnect);
+ }
+ if matches!(entry, Entry::Saved(_)) {
+ items.push(Item::Remove);
+ }
+ items
+ }
+
+ fn run(&self, index: usize, item: Item) {
+ let Some(entry) = self.entry(index) else {
+ return;
+ };
+ match (item, entry) {
+ (Item::Edit, Entry::Saved(i)) => {
+ let c = self.store.borrow().connections[i].clone();
+ self.edit(Some(i), c);
+ }
+ (Item::SaveAs, Entry::Config(alias)) => self.edit(
+ None,
+ Connection {
+ name: alias.clone(),
+ host: alias,
+ ..Default::default()
+ },
+ ),
+ (Item::Disconnect, entry) => {
+ let uri = self.target(&self.store.borrow(), &entry).1;
+ let sftp = self.sftp.clone();
+ let ui = self.ui.clone();
+ // Closing waits for the server's goodbye.
+ std::thread::spawn(move || {
+ sftp.disconnect(&uri);
+ let _ = ui.upgrade_in_event_loop(|_| {
+ if let Some(net) = net() {
+ net.refresh();
+ }
+ });
+ });
+ }
+ (Item::Remove, Entry::Saved(i)) => self.remove(i),
+ _ => {}
+ }
+ }
+
+ fn remove(&self, index: usize) {
+ {
+ let mut store = self.store.borrow_mut();
+ if index < store.connections.len() {
+ store.connections.remove(index);
+ }
+ }
+ self.save_store();
+ self.refresh();
+ }
+
+ /// Opens the connection dialog for connection `index` (`None`: a new one).
+ fn edit(&self, index: Option
, c: Connection) {
+ let Some(ui) = self.ui.upgrade() else {
+ return;
+ };
+ self.editing.set(index);
+ ui.set_connection(ConnectionData {
+ name: c.name.into(),
+ host: c.host.into(),
+ port: c.port.map(|p| p.to_string()).unwrap_or_default().into(),
+ user: c.user.into(),
+ folder: c.folder.into(),
+ auth: c.auth as i32,
+ key_file: c.key_file.into(),
+ editing: index.is_some(),
+ error: Default::default(),
+ });
+ ui.invoke_show_connection();
+ }
+
+ /// Validates and stores the dialog's connection; returns why it can't, or "".
+ fn save(&self, data: &ConnectionData) -> String {
+ let host = data.host.trim();
+ if host.is_empty() || host.contains(char::is_whitespace) || host.contains('/') {
+ return "Enter the name or address of the server".into();
+ }
+ let port = match data.port.trim() {
+ "" => None,
+ p => match p.parse::() {
+ Ok(p) if p > 0 => Some(p),
+ _ => return "The port is a number from 1 to 65535".into(),
+ },
+ };
+ let auth = [Auth::Automatic, Auth::Key, Auth::Password][data.auth.clamp(0, 2) as usize];
+ if auth == Auth::Key && data.key_file.trim().is_empty() {
+ return "Enter the key file".into();
+ }
+ let user = data.user.trim().to_owned();
+ let name = match data.name.trim() {
+ "" => host.to_owned(),
+ name => name.to_owned(),
+ };
+ let folder = data.folder.trim();
+ let folder = if folder.is_empty() || folder.starts_with('/') {
+ folder.to_owned()
+ } else {
+ format!("/{folder}")
+ };
+ let connection = Connection {
+ name,
+ host: host.to_owned(),
+ port,
+ user,
+ folder,
+ auth,
+ key_file: data.key_file.trim().to_owned(),
+ };
+ self.sftp.set_auth(&connection.host, connection.pref());
+ {
+ let mut store = self.store.borrow_mut();
+ match self.editing.get().filter(|&i| i < store.connections.len()) {
+ Some(i) => store.connections[i] = connection,
+ None => store.connections.push(connection),
+ }
+ }
+ self.save_store();
+ self.refresh();
+ String::new()
+ }
+
+ /// Opens the entry in the active pane or a new tab. A connection with no start folder
+ /// opens at the server's home folder, found on a thread (it may ask for a password).
+ fn open(&self, shell: &Shell, index: usize, new_tab: bool) {
+ let Some(entry) = self.entry(index) else {
+ return;
+ };
+ let (name, uri) = self.target(&self.store.borrow(), &entry);
+ let at_home = match &entry {
+ Entry::Saved(i) => self.store.borrow().connections[*i].folder.is_empty(),
+ Entry::Config(_) => true,
+ };
+ if !at_home {
+ shell.open_at(uri, new_tab);
+ return;
+ }
+ let sftp = self.sftp.clone();
+ let ui = self.ui.clone();
+ std::thread::spawn(move || {
+ let home = sftp.home(&uri);
+ let _ = ui.upgrade_in_event_loop(move |_| {
+ let Some(net) = net() else {
+ return;
+ };
+ if let Some(shell) = net.shell.upgrade() {
+ match home {
+ Ok(home) => shell.open_at(home, new_tab),
+ Err(e) => shell.notify(format!("Couldn't connect to {name}: {e}")),
+ }
+ }
+ net.refresh();
+ });
+ });
+ }
+}
diff --git a/crates/tunal/src/settings.rs b/crates/tunal/src/settings.rs
index 74d47dd..a9de3eb 100644
--- a/crates/tunal/src/settings.rs
+++ b/crates/tunal/src/settings.rs
@@ -77,6 +77,10 @@ impl SettingsUi {
preview_max_mib: cfg.preview_max_mib as i32,
preview_remote: cfg.preview_remote,
player_next: cfg.player_next,
+ ssh_hosts: cfg.ssh_hosts,
+ connect_timeout: cfg.connect_timeout_secs as i32,
+ keepalive: cfg.keepalive_secs as i32,
+ idle_close: cfg.idle_close_mins as i32,
}
}
@@ -117,6 +121,10 @@ impl SettingsUi {
cfg.preview_max_mib = data.preview_max_mib.clamp(1, 4096) as u32;
cfg.preview_remote = data.preview_remote;
cfg.player_next = data.player_next;
+ cfg.ssh_hosts = data.ssh_hosts;
+ cfg.connect_timeout_secs = data.connect_timeout.clamp(5, 120) as u32;
+ cfg.keepalive_secs = data.keepalive.clamp(0, 300) as u32;
+ cfg.idle_close_mins = data.idle_close.clamp(1, 120) as u32;
// The window's own sidebar state is saved with the session, not by this dialog.
if let Some(ui) = self.ui.upgrade() {
cfg.show_sidebar = ui.get_show_sidebar();
@@ -126,6 +134,7 @@ impl SettingsUi {
format::set_dates(cfg.date_style, cfg.clock);
if let Some(shell) = self.shell.upgrade() {
shell.thumbs().configure(&cfg);
+ crate::net_bridge::configure(&shell, &cfg);
for pane in shell.panes() {
pane.model.apply_config(&cfg);
pane.model.redraw_dates();
diff --git a/crates/tunal/src/shell/mod.rs b/crates/tunal/src/shell/mod.rs
index 5ddde73..5d4ac2b 100644
--- a/crates/tunal/src/shell/mod.rs
+++ b/crates/tunal/src/shell/mod.rs
@@ -421,6 +421,13 @@ impl Shell {
}
if is_active {
self.show_chrome();
+ if self
+ .pane_at(index)
+ .and_then(|p| p.dir())
+ .is_some_and(|d| d.scheme() == tunal_net::sftp::SCHEME)
+ {
+ crate::net_bridge::states_changed();
+ }
}
}
if is_active {
@@ -477,6 +484,40 @@ impl Shell {
self.show_chrome();
}
+ /// Replaces the sidebar's Network entries.
+ pub(crate) fn set_network(&self, items: Vec) {
+ self.places
+ .borrow_mut()
+ .set_section(Section::Network, items);
+ self.show_chrome();
+ }
+
+ /// A short message toast.
+ pub(crate) fn notify(&self, message: String) {
+ if let Some(actions) = self.actions.get() {
+ actions.notify(message);
+ }
+ }
+
+ /// Opens `uri` in the active pane, or in a new tab.
+ pub(crate) fn open_at(&self, uri: Uri, new_tab: bool) {
+ if new_tab {
+ self.open_tab(vec![uri]);
+ self.show_current();
+ } else {
+ self.go(uri);
+ }
+ }
+
+ /// Lists again every pane that failed to open its folder (the Try again button).
+ pub(crate) fn retry_failed(&self) {
+ for pane in self.panes() {
+ if pane.model.state().status == crate::FolderStatus::Error {
+ pane.model.refresh();
+ }
+ }
+ }
+
pub(crate) fn show_chrome(&self) {
let Some(ui) = self.ui.upgrade() else {
return;
@@ -538,6 +579,7 @@ impl Shell {
collapsed: places.collapsed(section),
empty: section.empty().into(),
can_add: section == Section::Bookmarks,
+ can_connect: section == Section::Network,
}
})
.collect();
@@ -575,6 +617,10 @@ impl Shell {
// ---- places -------------------------------------------------------------------------
fn open_place(&self, section: Section, index: usize, new_tab: bool) {
+ if section == Section::Network {
+ crate::net_bridge::open(self, index, new_tab);
+ return;
+ }
let Some(uri) = self
.places
.borrow()
@@ -628,6 +674,11 @@ impl Shell {
if self.ejectable(section, index).is_some() {
items.push(item("Eject", "\u{e8fb}", false));
}
+ if section == Section::Network {
+ for (label, glyph) in crate::net_bridge::menu_items(index) {
+ items.push(item(label, glyph, false));
+ }
+ }
items
}
@@ -645,6 +696,7 @@ impl Shell {
};
match choice {
0 => self.open_place(section, index, true),
+ c if section == Section::Network => crate::net_bridge::menu_activated(index, c - 1),
1 if section == Section::Devices => {
if let Some(uri) = self.ejectable(section, index) {
crate::devices_bridge::eject(&uri);
diff --git a/crates/tunal/ui/app.slint b/crates/tunal/ui/app.slint
index 28fc2aa..4c7c993 100644
--- a/crates/tunal/ui/app.slint
+++ b/crates/tunal/ui/app.slint
@@ -7,7 +7,7 @@ import { Menu, MenuItem, MenuEntry } from "components/menu.slint";
import { Dialog } from "components/dialog.slint";
import { ButtonKind } from "components/button.slint";
import { TextField } from "components/text-field.slint";
-import { DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode } from "views/details-view.slint";
+import { DetailRow, FolderActions, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode } from "views/details-view.slint";
import { GridRow } from "views/grid-view.slint";
import { TabBar, TabData } from "shell/tab-bar.slint";
import { Toolbar } from "shell/toolbar.slint";
@@ -27,11 +27,14 @@ import { FolderAppearanceDialog, IconChoice } from "dialogs/folder-appearance.sl
import { TagEditorDialog, TagEditorData, TagField } from "dialogs/tag-editor.slint";
import { TagLookupDialog, TagLookupData, ReleaseRow, MapRow } from "dialogs/tag-lookup.slint";
import { SettingsDialog, SettingsData, EditRow } from "dialogs/settings.slint";
+import { ConnectionDialog, ConnectionData } from "dialogs/connection.slint";
+import { HostKeyDialog, HostKeyData } from "dialogs/host-key.slint";
+import { SecretPromptDialog, SecretPromptData } from "dialogs/secret-prompt.slint";
import { Dnd, DropAction, DropMenu, DropTarget } from "components/drop-menu.slint";
export { Theme, Shapes, ShapeKind, MotionPrefs, MenuItem, MenuEntry, DetailRow, FolderState, FolderStatus, Grouping, NavKey, SortColumn, Travel, ViewMode, GridRow }
export { ButtonKind, TabData, PaneData, Crumb, Completion, SidebarSection, PlaceItem, ToastData, ToastProgress, DialogAction, ConflictInfo, SettingsData, EditRow }
-export { PlayerData }
+export { PlayerData, FolderActions, ConnectionData, HostKeyData, SecretPromptData }
export { PropertiesInfo, PropRow, AppRow, IconChoice, Dnd, DropAction, DropTarget, TagEditorData, TagField, TagLookupData, ReleaseRow, MapRow }
export { Gallery, GalleryPage } from "gallery.slint";
@@ -220,6 +223,39 @@ export component MainWindow inherits Window {
in property status;
+ // Network connections (net_bridge.rs): the connection editor, an unknown or changed host
+ // key, and a password or passphrase to ask for.
+ in-out property connection;
+ // Returns the reason it can't be saved, or an empty string.
+ callback connection-saved(ConnectionData) -> string;
+ callback connection-removed();
+ callback add-connection();
+ in property host-key;
+ // 0 refuse, 1 connect once, 2 connect and remember.
+ callback host-key-answered(int);
+ in property secret-prompt;
+ callback secret-answered(bool, string);
+
+ public function show-connection() {
+ connection-dialog.show();
+ }
+
+ public function show-host-key() {
+ host-key-dialog.show();
+ }
+
+ public function close-host-key() {
+ host-key-dialog.close();
+ }
+
+ public function show-secret() {
+ secret-dialog.show();
+ }
+
+ public function close-secret() {
+ secret-dialog.close();
+ }
+
public function open-place-menu(x: length, y: length) {
place-popup.open-at(x, y);
}
@@ -408,6 +444,9 @@ export component MainWindow inherits Window {
add-bookmark => {
root.add-bookmark();
}
+ add-connection => {
+ root.add-connection();
+ }
item-menu(section, index, x, y) => {
root.place-menu-requested(section, index);
place-popup.open-at(x, y);
@@ -882,6 +921,37 @@ export component MainWindow inherits Window {
}
}
+ connection-dialog := ConnectionDialog {
+ width: 100%;
+ height: 100%;
+ data <=> root.connection;
+ saved(data) => {
+ return root.connection-saved(data);
+ }
+ removed => {
+ root.connection-removed();
+ }
+ }
+
+ host-key-dialog := HostKeyDialog {
+ width: 100%;
+ height: 100%;
+ data: root.host-key;
+ answered(i) => {
+ self.close();
+ root.host-key-answered(i);
+ }
+ }
+
+ secret-dialog := SecretPromptDialog {
+ width: 100%;
+ height: 100%;
+ data: root.secret-prompt;
+ answered(ok, text) => {
+ root.secret-answered(ok, text);
+ }
+ }
+
ToastStack {
width: 100%;
height: 100%;
diff --git a/crates/tunal/ui/components/icon.slint b/crates/tunal/ui/components/icon.slint
index d08508c..f5cecd4 100644
--- a/crates/tunal/ui/components/icon.slint
+++ b/crates/tunal/ui/components/icon.slint
@@ -63,6 +63,12 @@ export global Icons {
out property restore: "\u{e8b3}";
out property create-new-folder: "\u{e2cc}";
out property settings: "\u{e8b8}";
+ // Network (net_bridge.rs).
+ out property cloud: "\u{e2bd}";
+ out property key: "\u{e73c}";
+ out property lock: "\u{e897}";
+ out property warning: "\u{e002}";
+ out property refresh: "\u{e5d5}";
// File categories (icons.rs).
out property image: "\u{e3f4}";
out property audio: "\u{eb82}";
diff --git a/crates/tunal/ui/components/text-field.slint b/crates/tunal/ui/components/text-field.slint
index 2525c8c..72b5486 100644
--- a/crates/tunal/ui/components/text-field.slint
+++ b/crates/tunal/ui/components/text-field.slint
@@ -13,6 +13,8 @@ export component TextField {
in property supporting;
in property error;
in property enabled: true;
+ // Dots instead of the characters (passwords, passphrases).
+ in property secret;
in property force-state: ForceState.none;
in-out property text;
public function focus-input() {
@@ -86,6 +88,7 @@ export component TextField {
accessible-placeholder-text: root.placeholder;
enabled: root.enabled;
single-line: true;
+ input-type: root.secret ? InputType.password : InputType.text;
color: root.enabled ? Theme.on-surface : root.disabled;
selection-background-color: Theme.primary-container;
selection-foreground-color: Theme.on-primary-container;
diff --git a/crates/tunal/ui/dialogs/connection.slint b/crates/tunal/ui/dialogs/connection.slint
new file mode 100644
index 0000000..f898612
--- /dev/null
+++ b/crates/tunal/ui/dialogs/connection.slint
@@ -0,0 +1,145 @@
+import { Theme } from "../theme.slint";
+import { Icons } from "../components/icon.slint";
+import { Dialog } from "../components/dialog.slint";
+import { ButtonKind } from "../components/button.slint";
+import { TextField } from "../components/text-field.slint";
+import { Chip } from "../components/chip.slint";
+
+// A saved SFTP connection as the dialog edits it. The password is never part of it.
+export struct ConnectionData {
+ name: string,
+ host: string,
+ port: string,
+ user: string,
+ folder: string,
+ // 0 automatic (agent, default keys, password), 1 key file, 2 password.
+ auth: int,
+ key-file: string,
+ // An existing connection: the dialog offers Remove.
+ editing: bool,
+ error: string,
+}
+
+// Adds or edits a connection. `saved` returns the reason it can't be saved, or an empty
+// string; the dialog stays open on a reason and shows it under the host.
+export component ConnectionDialog inherits Dialog {
+ in-out property data;
+ callback saved(ConnectionData) -> string;
+ callback removed();
+
+ glyph: Icons.cloud;
+ title: root.data.editing ? "Edit connection" : "New connection";
+ dialog-width: 520px;
+ content-focus: true;
+ actions: root.data.editing
+ ? [{ text: "Cancel", kind: ButtonKind.text }, { text: "Remove", kind: ButtonKind.text }, { text: "Save", kind: ButtonKind.filled }]
+ : [{ text: "Cancel", kind: ButtonKind.text }, { text: "Save", kind: ButtonKind.filled }];
+ default-action: root.actions.length - 1;
+ cancel-action: 0;
+ focus-content => {
+ name-field.focus-input();
+ }
+ action(i) => {
+ if i == 0 {
+ self.close();
+ } else if root.data.editing && i == 1 {
+ self.close();
+ root.removed();
+ } else {
+ let reason = root.saved(root.data);
+ if reason == "" {
+ self.close();
+ } else {
+ root.data.error = reason;
+ }
+ }
+ }
+
+ name-field := TextField {
+ label: "Name";
+ placeholder: "Home server";
+ text <=> root.data.name;
+ }
+
+ HorizontalLayout {
+ spacing: Theme.space-3;
+
+ TextField {
+ horizontal-stretch: 1;
+ label: "Host";
+ placeholder: "name or address";
+ error: root.data.error;
+ text <=> root.data.host;
+ edited => {
+ root.data.error = "";
+ }
+ }
+
+ TextField {
+ width: 96px;
+ label: "Port";
+ placeholder: "22";
+ text <=> root.data.port;
+ }
+ }
+
+ HorizontalLayout {
+ spacing: Theme.space-3;
+
+ TextField {
+ horizontal-stretch: 1;
+ label: "User";
+ placeholder: "your name on the server";
+ text <=> root.data.user;
+ }
+
+ TextField {
+ horizontal-stretch: 1;
+ label: "Start folder";
+ placeholder: "home folder";
+ text <=> root.data.folder;
+ }
+ }
+
+ HorizontalLayout {
+ spacing: Theme.space-2;
+ alignment: start;
+
+ Text {
+ text: "Sign in with";
+ color: Theme.on-surface-variant;
+ font-size: Theme.body-small.size;
+ font-weight: Theme.body-small.weight;
+ vertical-alignment: center;
+ }
+
+ for name[i] in ["Automatic", "Key file", "Password"]: Chip {
+ property sel: i == root.data.auth;
+
+ text: name;
+ checked: self.sel;
+ changed sel => {
+ self.checked = self.sel;
+ }
+ clicked => {
+ root.data.auth = i;
+ self.checked = true;
+ }
+ }
+ }
+
+ if root.data.auth == 1: TextField {
+ label: "Key file";
+ placeholder: "~/.ssh/id_ed25519";
+ supporting: "The passphrase is asked when needed and never saved.";
+ text <=> root.data.key-file;
+ }
+
+ if root.data.auth != 1: Text {
+ text: root.data.auth == 0 ? "Uses your key agent and default keys, then asks for a password." : "Asks for the password each time it connects. It is never saved.";
+ color: Theme.on-surface-variant;
+ font-size: Theme.body-small.size;
+ font-weight: Theme.body-small.weight;
+ wrap: word-wrap;
+ }
+}
diff --git a/crates/tunal/ui/dialogs/host-key.slint b/crates/tunal/ui/dialogs/host-key.slint
new file mode 100644
index 0000000..3e8d65e
--- /dev/null
+++ b/crates/tunal/ui/dialogs/host-key.slint
@@ -0,0 +1,54 @@
+import { Theme } from "../theme.slint";
+import { Icons } from "../components/icon.slint";
+import { Dialog } from "../components/dialog.slint";
+import { ButtonKind } from "../components/button.slint";
+
+// A server key to decide on (net_bridge.rs). `changed`: the key differs from the saved one,
+// so the connection is refused and the dialog only warns.
+export struct HostKeyData {
+ host: string,
+ key-type: string,
+ fingerprint: string,
+ changed: bool,
+}
+
+// `answered(0)` refuses, 1 connects this once, 2 connects and remembers the key.
+export component HostKeyDialog inherits Dialog {
+ in property data;
+ callback answered(int);
+
+ glyph: root.data.changed ? Icons.warning : Icons.lock;
+ title: root.data.changed ? "The host key changed" : "Connect to a new host?";
+ body: root.data.changed
+ ? "The key of " + root.data.host + " is not the one saved before. Someone may be intercepting the connection, or the server was set up again. Tunal did not connect."
+ : "Tunal hasn't connected to " + root.data.host + " before. Check that this fingerprint matches the one on the server.";
+ dialog-width: 480px;
+ actions: root.data.changed
+ ? [{ text: "Close", kind: ButtonKind.filled }]
+ : [{ text: "Cancel", kind: ButtonKind.text }, { text: "Connect once", kind: ButtonKind.tonal }, { text: "Trust and connect", kind: ButtonKind.filled }];
+ // Enter and Escape never trust a key.
+ default-action: 0;
+ cancel-action: 0;
+ action(i) => {
+ root.answered(i);
+ }
+
+ VerticalLayout {
+ spacing: Theme.space-1;
+
+ Text {
+ text: root.data.key-type + " key";
+ color: Theme.on-surface-variant;
+ font-size: Theme.label-medium.size;
+ font-weight: Theme.label-medium.weight;
+ }
+
+ Text {
+ text: root.data.fingerprint;
+ color: Theme.on-surface;
+ font-size: Theme.body-medium.size;
+ font-weight: Theme.body-medium.weight;
+ wrap: word-wrap;
+ }
+ }
+}
diff --git a/crates/tunal/ui/dialogs/secret-prompt.slint b/crates/tunal/ui/dialogs/secret-prompt.slint
new file mode 100644
index 0000000..423a5de
--- /dev/null
+++ b/crates/tunal/ui/dialogs/secret-prompt.slint
@@ -0,0 +1,41 @@
+import { Icons } from "../components/icon.slint";
+import { Dialog } from "../components/dialog.slint";
+import { ButtonKind } from "../components/button.slint";
+import { TextField } from "../components/text-field.slint";
+
+// A password, passphrase or keyboard-interactive answer to ask for (net_bridge.rs).
+export struct SecretPromptData {
+ title: string,
+ body: string,
+ label: string,
+ // False: the answer shows as dots.
+ echo: bool,
+}
+
+// `answered(true, text)` carries the answer; the field is cleared as soon as it is sent, and
+// Rust moves the text into a secret type at once.
+export component SecretPromptDialog inherits Dialog {
+ in property data;
+ callback answered(bool, string);
+
+ glyph: root.data.echo ? Icons.cloud : Icons.key;
+ title: root.data.title;
+ body: root.data.body;
+ content-focus: true;
+ actions: [{ text: "Cancel", kind: ButtonKind.text }, { text: "Continue", kind: ButtonKind.filled }];
+ default-action: 1;
+ cancel-action: 0;
+ focus-content => {
+ field.focus-input();
+ }
+ action(i) => {
+ self.close();
+ root.answered(i == 1, field.text);
+ field.text = "";
+ }
+
+ field := TextField {
+ label: root.data.label;
+ secret: !root.data.echo;
+ }
+}
diff --git a/crates/tunal/ui/dialogs/settings.slint b/crates/tunal/ui/dialogs/settings.slint
index 35a289a..b7b7a71 100644
--- a/crates/tunal/ui/dialogs/settings.slint
+++ b/crates/tunal/ui/dialogs/settings.slint
@@ -33,6 +33,11 @@ export struct SettingsData {
preview-max-mib: int,
preview-remote: bool,
player-next: bool,
+ // Network page.
+ ssh-hosts: bool,
+ connect-timeout: int,
+ keepalive: int,
+ idle-close: int,
}
// One choice out of a few, as a row of chips.
@@ -179,7 +184,7 @@ export component SettingsDialog inherits Dialog {
glyph: Icons.settings;
in-out property data;
in-out property page;
- // The context menu editor (page 4).
+ // The context menu editor (page 5).
in property <[string]> menu-contexts;
in property menu-context;
in property <[EditRow]> menu-rows;
@@ -194,8 +199,8 @@ export component SettingsDialog inherits Dialog {
callback menu-reset();
callback closed();
- property <[string]> pages: ["General", "View", "Previews", "Motion", "Context menus"];
- property <[string]> glyphs: ["\u{e8b8}", "\u{e8f4}", "\u{e3f4}", "\u{e037}", "\u{e5d4}"];
+ property <[string]> pages: ["General", "View", "Previews", "Motion", "Network", "Context menus"];
+ property <[string]> glyphs: ["\u{e8b8}", "\u{e8f4}", "\u{e3f4}", "\u{e037}", "\u{e2bd}", "\u{e5d4}"];
title: "Settings";
dialog-width: 780px;
@@ -448,7 +453,71 @@ export component SettingsDialog inherits Dialog {
}
}
- if root.page == 4: MenuEditor {
+ if root.page == 4: VerticalLayout {
+ alignment: start;
+
+ Setting {
+ title: "Hosts from ~/.ssh/config";
+ hint: "Lists them in the sidebar under Network. Tunal only reads that file.";
+ Switch {
+ checked: root.data.ssh-hosts;
+ changed checked => {
+ root.data.ssh-hosts = self.checked;
+ root.changed(root.data);
+ }
+ }
+ }
+
+ Setting {
+ title: "Connection timeout";
+ hint: "How long to wait for a server to answer.";
+ Stepper {
+ value: root.data.connect-timeout;
+ lo: 5;
+ hi: 120;
+ step: 5;
+ unit: "s";
+ picked(v) => {
+ root.data.connect-timeout = v;
+ root.changed(root.data);
+ }
+ }
+ }
+
+ Setting {
+ title: "Keep alive";
+ hint: "Sends a small message this often so quiet connections stay open. 0 turns it off.";
+ Stepper {
+ value: root.data.keepalive;
+ lo: 0;
+ hi: 300;
+ step: 10;
+ unit: "s";
+ picked(v) => {
+ root.data.keepalive = v;
+ root.changed(root.data);
+ }
+ }
+ }
+
+ Setting {
+ title: "Close idle connections";
+ hint: "After this long without use. They open again when you need them.";
+ Stepper {
+ value: root.data.idle-close;
+ lo: 1;
+ hi: 120;
+ step: 1;
+ unit: "min";
+ picked(v) => {
+ root.data.idle-close = v;
+ root.changed(root.data);
+ }
+ }
+ }
+ }
+
+ if root.page == 5: MenuEditor {
contexts: root.menu-contexts;
context: root.menu-context;
rows: root.menu-rows;
diff --git a/crates/tunal/ui/gallery.slint b/crates/tunal/ui/gallery.slint
index fc72227..d89d8f2 100644
--- a/crates/tunal/ui/gallery.slint
+++ b/crates/tunal/ui/gallery.slint
@@ -12,10 +12,13 @@ import { Tab, TabBar } from "components/tab.slint";
import { TextField } from "components/text-field.slint";
import { Menu } from "components/menu.slint";
import { Dialog } from "components/dialog.slint";
+import { ConnectionDialog } from "dialogs/connection.slint";
+import { HostKeyDialog } from "dialogs/host-key.slint";
+import { SecretPromptDialog } from "dialogs/secret-prompt.slint";
import { ToastStack, ToastProgress } from "components/toast.slint";
// What the gallery shows: every control, or a stand-in folder under open overlays.
-export enum GalleryPage { controls, menu, dialog }
+export enum GalleryPage { controls, menu, dialog, connection, host-key, secret }
// Every control in every state, for screenshots: `tunal --gallery --screenshot `.
// Columns force the state; the last one is the disabled control.
@@ -74,6 +77,12 @@ export component Gallery inherits Window {
menu.expand(7);
} else if root.page == GalleryPage.dialog {
dialog.show();
+ } else if root.page == GalleryPage.connection {
+ connection-dialog.show();
+ } else if root.page == GalleryPage.host-key {
+ host-key-dialog.show();
+ } else if root.page == GalleryPage.secret {
+ secret-dialog.show();
}
}
@@ -421,6 +430,41 @@ export component Gallery inherits Window {
];
}
+ connection-dialog := ConnectionDialog {
+ width: 100%;
+ height: 100%;
+ data: {
+ name: "Home server",
+ host: "nas.local",
+ port: "22",
+ user: "astar",
+ folder: "/srv/music",
+ auth: 1,
+ key-file: "~/.ssh/id_ed25519",
+ editing: true,
+ };
+ }
+
+ host-key-dialog := HostKeyDialog {
+ width: 100%;
+ height: 100%;
+ data: {
+ host: "nas.local",
+ key-type: "ssh-ed25519",
+ fingerprint: "SHA256:1dvW/EyXWEyfwR0dH12B1qDtX5UD71A+IEcAJqtWVU8",
+ };
+ }
+
+ secret-dialog := SecretPromptDialog {
+ width: 100%;
+ height: 100%;
+ data: {
+ title: "Password for astar@nas.local",
+ body: "The password is used for this connection only and is never saved.",
+ label: "Password",
+ };
+ }
+
dialog := Dialog {
glyph: Icons.create-new-folder;
width: 100%;
diff --git a/crates/tunal/ui/shell/sidebar.slint b/crates/tunal/ui/shell/sidebar.slint
index bf9c89b..0c9cc24 100644
--- a/crates/tunal/ui/shell/sidebar.slint
+++ b/crates/tunal/ui/shell/sidebar.slint
@@ -25,13 +25,17 @@ export struct SidebarSection {
empty: string,
// Offers "Add the current folder" in its header (bookmarks).
can-add: bool,
+ // Offers "Add a connection" in its header (network).
+ can-connect: bool,
}
component SectionHeader inherits StateLayer {
in property title;
in property collapsed;
in property can-add;
+ in property can-connect;
callback add();
+ callback connect();
height: 36px;
border-radius: Theme.corner-full(self.height);
@@ -73,6 +77,19 @@ component SectionHeader inherits StateLayer {
}
}
+ if root.can-connect: VerticalLayout {
+ alignment: center;
+ IconButton {
+ icon: Icons.add;
+ size: 28px;
+ icon-size: 18px;
+ tooltip: "Add a connection";
+ clicked => {
+ root.connect();
+ }
+ }
+ }
+
VerticalLayout {
alignment: center;
Rectangle {
@@ -97,6 +114,7 @@ export component Sidebar inherits Rectangle {
callback open(section: int, index: int, new-tab: bool);
callback toggle(section: int);
callback add-bookmark();
+ callback add-connection();
// Right click on an item, at window coordinates.
callback item-menu(section: int, index: int, x: length, y: length);
@@ -121,12 +139,16 @@ export component Sidebar inherits Rectangle {
title: section.title;
collapsed: section.collapsed;
can-add: section.can-add;
+ can-connect: section.can-connect;
clicked => {
root.toggle(s);
}
add => {
root.add-bookmark();
}
+ connect => {
+ root.add-connection();
+ }
// Folders dropped on the header become bookmarks (Rust accepts only there).
DropZone {
diff --git a/crates/tunal/ui/views/details-view.slint b/crates/tunal/ui/views/details-view.slint
index b162dd4..2f5098a 100644
--- a/crates/tunal/ui/views/details-view.slint
+++ b/crates/tunal/ui/views/details-view.slint
@@ -7,6 +7,7 @@ import { ListRow } from "../components/list-row.slint";
import { FileShapes } from "../components/shape.slint";
import { IconButton } from "../components/icon-button.slint";
import { Chip, ChipKind } from "../components/chip.slint";
+import { Button, ButtonKind } from "../components/button.slint";
import { Dnd, DropTarget, DropZone } from "../components/drop-menu.slint";
export enum SortColumn { name, size, type, modified, playlist }
@@ -212,11 +213,19 @@ component Cell inherits HorizontalLayout {
}
}
+// Buttons of the folder messages that act on a pane's folder (the shell finds the pane).
+export global FolderActions {
+ callback retry();
+}
+
// Centred message for the loading, empty and error states.
export component Message inherits VerticalLayout {
in property glyph;
in property title;
in property body;
+ // A button below the text; empty for none.
+ in property action-text;
+ callback action();
alignment: center;
spacing: Theme.space-2;
@@ -247,6 +256,19 @@ export component Message inherits VerticalLayout {
horizontal-alignment: center;
wrap: word-wrap;
}
+
+ if root.action-text != "": HorizontalLayout {
+ alignment: center;
+ padding-top: Theme.space-2;
+
+ Button {
+ text: root.action-text;
+ kind: ButtonKind.tonal;
+ clicked => {
+ root.action();
+ }
+ }
+ }
}
// The keyboard of a folder view: arrows move the cursor (`move`), typing filters, Ctrl+A
@@ -356,6 +378,10 @@ export component FolderMessages inherits Rectangle {
glyph: Icons.error;
title: "Can't open this folder";
body: root.state.error;
+ action-text: "Try again";
+ action => {
+ FolderActions.retry();
+ }
}
if root.state.status == FolderStatus.loading && root.row-count == 0: Message {
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index e102c74..eb23e23 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -227,6 +227,14 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
- Not done: no live window (sound, slide, morph, scrub, Space, next track unchecked live); cover is drawn square inside the cookie (Shape's picture behaviour), not clipped to it.
- Later: clip pictures to the shape; remember volume; previous/next buttons.
+## S029 — SFTP connections in the UI
+- Done: `net_bridge.rs`: `connections.toml` (name, host or ssh alias, port, user, start folder, auth automatic/key file/password + key path; never a password), Network section = saved connections then `~/.ssh/config` hosts not saved (switch in Settings, new Network page: ssh hosts, connect timeout, keep alive, idle close; `Settings` fields `ssh_hosts`, `connect_timeout_secs`, `keepalive_secs`, `idle_close_mins`). Header "+" opens `dialogs/connection.slint` (validates host/port/key, Remove when editing); place menu on Network entries: Open in new tab, Edit / Save as connection, Disconnect (while connected), Remove. Opening a saved entry without a start folder resolves the server's home on a thread (toast on failure); connected entries show a cloud-done glyph. Typed `sftp://…` in the breadcrumb already worked.
+- Prompts (`UiPrompts`, serialised, answer through an mpsc channel): `dialogs/host-key.slint` (fingerprint; Cancel / Connect once / Trust and connect; changed key = warning only, nothing is trusted by Enter), `dialogs/secret-prompt.slint` (password, passphrase, keyboard-interactive; field cleared after sending, text moved into `SecretString` at once). tunal-net: `HostKeyChoice` (Once/Always), `Prompts::host_key_changed`, `AuthPref` (Any/Agent/Key/Password per host, `SftpLocation::set_auth`), `disconnect`, `is_connected`, `set_options`, plain-word connect errors.
+- Folder error state has a "Try again" button (`FolderActions.retry` global; refreshes panes that failed). `TextField.secret` shows dots. Gallery pages `connection`, `host-key`, `secret`.
+- Verified: build, fmt; clippy clean for my files (workspace clippy stops on S030's `native/mod.rs` type-complexity lint); looked at gallery PNGs (connection light+dark, host-key light+dark, secret), shell PNG with a local sshd (Network section, connected glyph, SFTP folder listed over key auth) and the refused-connection error with Try again; literal grep empty.
+- Not done: no live clicks (add/edit flow, password dialog with a real server, press motion not watched); the dialogs reuse `Dialog` motion only. Keyboard-interactive and password logins untested. Connection dialog is tall at 480 px window height. No key-file picker (path typed).
+- Later: file picker for the key; show connection errors in the sidebar; per-connection options (compression, keepalive).
+
## Later
- (orchestrator) Breadcrumb: a long path is hard-clipped at the bar's left edge with no elision mark, and the root crumb elides at 960 px — for S034.
-