S029: SFTP connections in the UI

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-19 00:35:39 -06:00
commit 29f4456154
27 changed files with 1442 additions and 65 deletions

View file

@ -89,11 +89,12 @@ Never modify: `PROMPT.md` (the user's brief), the user's other projects under `~
| `XDG_DATA_HOME=<dir>/data cargo run -p tunal-core --example ops -- <dir>` (refuses unless XDG_DATA_HOME is inside `<dir>`) | job engine + trash smoke run: conflicts, cancel, trash/restore/empty | S007 |
| `cargo run -p tunal -- --gallery --screenshot <png> [--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 <png> [--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 -- <dir> --screenshot <png> --size 1000x700` (`XDG_CONFIG_HOME=<scratch>`) | settings dialog page over a folder | S013 |
| `TUNAL_SETTINGS=<0-5> cargo run -p tunal -- <dir> --screenshot <png> --size 1000x700` (`XDG_CONFIG_HOME=<scratch>`) | settings dialog page over a folder | S013 |
| `TUNAL_DRAG=x1,y1,x2,y2[,hold] TUNAL_REDUCED_MOTION=1 cargo run -p tunal -- <dir> --screenshot <png> --size 1200x760` (`XDG_CONFIG_HOME=<scratch>`) | drags between window points and drops (drop menu) or holds (glow + drag image) before the frame | S014 |
| `TUNAL_APPEARANCE=1 XDG_CONFIG_HOME=<scratch> cargo run -p tunal -- <dir> --screenshot <png> --size 1000x760` | folder appearance dialog for `<dir>` (theme icons looked up at once); `cargo run -p tunal-dirmeta --example roundtrip -- <dir>` sets `Icon` in `<dir>/.directory` and prints the old values | S015 |
| `TUNAL_PLAY=<audio file> XDG_CONFIG_HOME=<scratch> cargo run -p tunal -- <dir> --screenshot <png> [--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:<file>:<file> TUNAL_TAGS_SYNC=1 TUNAL_MUSICBRAINZ=<mock url> XDG_CONFIG_HOME=<scratch> cargo run -p tunal -- <dir> --screenshot <png> --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 <png> [--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.

2
Cargo.lock generated
View file

@ -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",

View file

@ -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.

View file

@ -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

View file

@ -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<SecretString> {
}
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<SecretString> {

View file

@ -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<SecretString> {
None
@ -86,9 +112,14 @@ pub(crate) async fn authenticate<H: Handler>(
user: &str,
host: &str,
resolved: &Resolved,
pref: &AuthPref,
prompts: &Arc<dyn Prompts>,
) -> 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<H: Handler>(
.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(()),

View file

@ -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;

View file

@ -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<Duration>,
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<Options> = 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<Runtime> = 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<Arc<Conn>> {
pub fn get(&self, key: &ConnKey, resolved: &Resolved, pref: &AuthPref) -> Result<Arc<Conn>> {
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<Arc<Conn>> = {
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<dyn Prompts>,
) -> Result<Arc<Conn>> {
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<Mutex<Option<String>>>,
}
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)

View file

@ -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<Pool>,
config: SshConfig,
/// Credentials per host (lower case, as written in the URI).
prefs: Mutex<HashMap<String, AuthPref>>,
}
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<Conn>)> {
/// 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<Conn>)> {
let (key, resolved, pref) = self.target(uri)?;
let conn = self.pool.get(&key, &resolved, &pref)?;
Ok((key, conn))
}

View file

@ -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

View file

@ -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<Shell>, locations: Locations) -> Rc<Self> {
let bridge = Bridge::attach(ui, locations.clone());
let opener = Opener::attach(ui, locations.clone(), bridge.clone());

View file

@ -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,
}
}
}

View file

@ -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 [<folder>…] [--split <folder> <folder>] \
[--gallery [--page menu|dialog]] [--screenshot <png> [--dark] [--size WxH]]";
[--gallery [--page menu|dialog|connection|host-key|secret]] [--screenshot <png> [--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=<page 0-4>` 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<Item = String>) -> Result<Args, String> {
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()),
}
}

View file

@ -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<u16>,
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<Connection>,
}
/// 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<MainWindow>,
shell: Weak<Shell>,
sftp: Arc<SftpLocation>,
store: RefCell<Store>,
entries: RefCell<Vec<Entry>>,
config: RefCell<SshConfig>,
show_ssh_hosts: std::cell::Cell<bool>,
/// The saved connection the dialog edits, `None` for a new one.
editing: std::cell::Cell<Option<usize>>,
/// What the sidebar shows now, to skip identical updates.
shown: RefCell<Vec<(String, &'static str, Uri)>>,
}
thread_local! {
static NET: RefCell<Option<Rc<Net>>> = const { RefCell::new(None) };
}
fn net() -> Option<Rc<Net>> {
NET.with(|n| n.borrow().clone())
}
/// What the user answered to the question on screen.
enum Answer {
Choice(i32),
Secret(Option<SecretString>),
}
/// The question on screen waits for its answer here.
static PENDING: Mutex<Option<mpsc::Sender<Answer>>> = 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<MainWindow>,
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<Answer> {
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<Answer> {
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<SecretString> {
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<SecretString> {
self.secret((
format!("Password for {user}@{host}"),
SECRET_NOTE.into(),
"Password".into(),
false,
))
}
fn passphrase(&self, key: &std::path::Path) -> Option<SecretString> {
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<Vec<SecretString>> {
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<SftpLocation> {
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<Shell>, sftp: Arc<SftpLocation>) {
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::<FolderActions>().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<Entry> = (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<Entry> {
self.entries.borrow().get(index).cloned()
}
fn items(&self, index: usize) -> Vec<Item> {
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<usize>, 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::<u16>() {
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();
});
});
}
}

View file

@ -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();

View file

@ -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<places::Place>) {
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);

View file

@ -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 <string> 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 <ConnectionData> 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 <HostKeyData> host-key;
// 0 refuse, 1 connect once, 2 connect and remember.
callback host-key-answered(int);
in property <SecretPromptData> 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%;

View file

@ -63,6 +63,12 @@ export global Icons {
out property <string> restore: "\u{e8b3}";
out property <string> create-new-folder: "\u{e2cc}";
out property <string> settings: "\u{e8b8}";
// Network (net_bridge.rs).
out property <string> cloud: "\u{e2bd}";
out property <string> key: "\u{e73c}";
out property <string> lock: "\u{e897}";
out property <string> warning: "\u{e002}";
out property <string> refresh: "\u{e5d5}";
// File categories (icons.rs).
out property <string> image: "\u{e3f4}";
out property <string> audio: "\u{eb82}";

View file

@ -13,6 +13,8 @@ export component TextField {
in property <string> supporting;
in property <string> error;
in property <bool> enabled: true;
// Dots instead of the characters (passwords, passphrases).
in property <bool> secret;
in property <ForceState> force-state: ForceState.none;
in-out property <string> 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;

View file

@ -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 <ConnectionData> 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 <bool> 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;
}
}

Some files were not shown because too many files have changed in this diff Show more