From 15f382b654b1f4f4c567dec648d0cff5d6ca0479 Mon Sep 17 00:00:00 2001 From: Dreaded_X Date: Sat, 12 Apr 2025 23:30:53 +0200 Subject: [PATCH] Added the ability to close a tunnel from the tui --- src/handler.rs | 25 +++++++++++++++++++++++-- src/input.rs | 2 ++ src/tui.rs | 1 + src/tunnel.rs | 10 ++++------ 4 files changed, 30 insertions(+), 8 deletions(-) diff --git a/src/handler.rs b/src/handler.rs index 97f534a..70dd225 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -1,4 +1,4 @@ -use std::{io::Write, iter::once}; +use std::{cmp::min, io::Write, iter::once}; use clap::Parser as _; use ratatui::{Terminal, TerminalOptions, Viewport, layout::Rect, prelude::CrosstermBackend}; @@ -116,6 +116,25 @@ impl Handler { warn!("User not set"); } } + Input::Delete => { + let Some(selected) = self.selected else { + return Ok(false); + }; + + if selected >= self.tunnels.len() { + warn!("Trying to delete tunnel out of bounds"); + return Ok(false); + } + + let tunnel = self.tunnels.remove(selected); + self.all_tunnels.remove_tunnel(tunnel).await; + + if self.tunnels.is_empty() { + self.selected = None; + } else { + self.selected = Some(min(self.tunnels.len() - 1, selected)); + } + } Input::CtrlP => { self.set_access_selection(TunnelAccess::Protected).await; } @@ -321,7 +340,9 @@ impl Drop for Handler { let mut all_tunnels = self.all_tunnels.clone(); tokio::spawn(async move { - all_tunnels.remove_tunnels(&tunnels).await; + for tunnel in tunnels { + all_tunnels.remove_tunnel(tunnel).await; + } }); } } diff --git a/src/input.rs b/src/input.rs index ccd6cc6..8949136 100644 --- a/src/input.rs +++ b/src/input.rs @@ -5,6 +5,7 @@ pub enum Input { Char(char), Up, Down, + Delete, Esc, Enter, CtrlP, @@ -18,6 +19,7 @@ impl From<&[u8]> for Input { [27] => Input::Esc, [27, 91, 65] => Input::Up, [27, 91, 66] => Input::Down, + [27, 91, 51, 126] => Input::Delete, [13] => Input::Enter, // NOTE: Actual char is DLE, this happens to map to ctrl-p [16] => Input::CtrlP, diff --git a/src/tui.rs b/src/tui.rs index 41ed26d..5f8464d 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -42,6 +42,7 @@ impl Renderer { command("esc", "deselect"), command("↓/j", "move down"), command("↑/k", "move up"), + command("del", "close tunnel"), vec![], command("p", "make private"), command("ctrl-p", "make protected"), diff --git a/src/tunnel.rs b/src/tunnel.rs index d37caa0..ac12805 100644 --- a/src/tunnel.rs +++ b/src/tunnel.rs @@ -130,13 +130,11 @@ impl Tunnels { tunnel } - pub async fn remove_tunnels(&mut self, tunnels: &[Tunnel]) { + pub async fn remove_tunnel(&mut self, tunnel: Tunnel) { let mut all_tunnels = self.tunnels.write().await; - for tunnel in tunnels { - if let Some(address) = tunnel.get_address() { - trace!(tunnel.name, "Removing tunnel"); - all_tunnels.remove(&address); - } + if let Some(address) = tunnel.get_address() { + trace!(tunnel.name, "Removing tunnel"); + all_tunnels.remove(&address); } } }