chore: restart the repository with a clean history
CI / Docker image (push) Successful in 12s
CI / Server (push) Successful in 25s
CI / CLI (push) Successful in 13s
Development image / Development image (push) Successful in 21s
CI / CLI (windows) (push) Successful in 57s
CI / CLI (linux-arm64, static) (push) Successful in 1m37s
Release / Prepare release (push) Successful in 2s
Release / Server (linux-x64) (push) Successful in 53s
Release / CLI (linux-arm64, static) (push) Successful in 1m32s
Release / Docker image (push) Successful in 2m48s
Release / Server (windows-x64) (push) Successful in 6m20s
Release / CLI (windows-x64) (push) Successful in 6m48s
Release / CLI (linux-x64) (push) Successful in 7m8s
Release / Publish release (push) Successful in 1s
CI / Docker image (push) Successful in 12s
CI / Server (push) Successful in 25s
CI / CLI (push) Successful in 13s
Development image / Development image (push) Successful in 21s
CI / CLI (windows) (push) Successful in 57s
CI / CLI (linux-arm64, static) (push) Successful in 1m37s
Release / Prepare release (push) Successful in 2s
Release / Server (linux-x64) (push) Successful in 53s
Release / CLI (linux-arm64, static) (push) Successful in 1m32s
Release / Docker image (push) Successful in 2m48s
Release / Server (windows-x64) (push) Successful in 6m20s
Release / CLI (windows-x64) (push) Successful in 6m48s
Release / CLI (linux-x64) (push) Successful in 7m8s
Release / Publish release (push) Successful in 1s
Squash the tree into one commit, drop docs/architecture.html, reset the version line to 0.3.0, consolidate the changelog, enable Renovate automerge for non-major updates and add AGENTS.md.
This commit is contained in:
438 files changed
+45070
No files matched your search
@@ -0,0 +1,770 @@
|
||||
use eframe::egui::{self, Align, Color32, CursorIcon, Frame, Layout, Margin, RichText, Sense, Stroke, TextureHandle, TextureOptions, Ui, UiBuilder};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{self, Receiver, Sender};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc::UnboundedReceiver;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::runtime::Handle;
|
||||
use crate::api::{ApiClient, Me, ServerInfo};
|
||||
use crate::auth::{self, LoginEvent};
|
||||
use crate::config::Config;
|
||||
use crate::connect;
|
||||
use crate::qr;
|
||||
use crate::session::{self, Connection, JoinEvent, Online, Request, Stop, StopHandle, Task, TunnelEvent};
|
||||
use crate::tunnel::{self, connect_target, Options, Target};
|
||||
use crate::update;
|
||||
use super::ports::{self, Listener};
|
||||
use super::{format, hide_by_closing, theme, widgets, Repaint, Wake};
|
||||
|
||||
const MAX_REQUESTS: usize = 500;
|
||||
const TOAST_FOR: Duration = Duration::from_secs(3);
|
||||
const UNDO_FOR: Duration = Duration::from_secs(8);
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(1);
|
||||
const PROBE_INTERVAL: Duration = Duration::from_secs(5);
|
||||
const SCAN_INTERVAL: Duration = Duration::from_secs(4);
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub enum Page { Tunnels, NewTunnel, Tunnel(u64), Connect, Settings }
|
||||
|
||||
pub enum Msg {
|
||||
TunnelReady(u64, String),
|
||||
Tunnel(u64, TunnelEvent),
|
||||
TunnelFailed(u64, String),
|
||||
Join(u64, JoinEvent),
|
||||
JoinFailed(u64, String, Option<u16>),
|
||||
Login(LoginEvent),
|
||||
LoginFailed(String),
|
||||
Info(Result<ServerInfo, String>),
|
||||
Me(Option<Me>),
|
||||
Linked(Result<String, String>),
|
||||
Update(Option<String>),
|
||||
Updated(Result<(), String>),
|
||||
TunnelProbe(u64, Option<String>),
|
||||
Listeners(Vec<Listener>),
|
||||
FolderPicked(Option<PathBuf>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub enum TunnelKind { Http, Files, Tcp }
|
||||
|
||||
impl TunnelKind {
|
||||
pub fn label(self) -> &'static str { match self { Self::Http => "http", Self::Files => "files", Self::Tcp => "tcp" } }
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
pub enum TunnelState { Connecting, Online, Reconnecting { seconds: u64, reason: Option<String> } }
|
||||
|
||||
pub struct LoggedRequest { pub request: Request, pub at: Instant }
|
||||
|
||||
pub struct TunnelCard {
|
||||
pub id: u64,
|
||||
pub kind: TunnelKind,
|
||||
pub opts: Options,
|
||||
pub target_label: String,
|
||||
pub access: Option<String>,
|
||||
pub probe: Option<String>,
|
||||
pub state: TunnelState,
|
||||
pub online: Option<Online>,
|
||||
pub requests: VecDeque<LoggedRequest>,
|
||||
pub connections: VecDeque<Connection>,
|
||||
pub request_count: u64,
|
||||
pub started: Instant,
|
||||
pub stop: StopHandle,
|
||||
pub show_qr: bool,
|
||||
pub copied_at: Option<Instant>,
|
||||
}
|
||||
|
||||
impl TunnelCard {
|
||||
pub fn link(&self, server_url: &str) -> Option<String> { self.online.as_ref().and_then(|online| online.link(server_url)) }
|
||||
pub fn title(&self) -> String { self.online.as_ref().map(|online| online.id.clone()).unwrap_or_else(|| self.target_label.clone()) }
|
||||
}
|
||||
|
||||
pub enum JoinState { Connecting, Forwarding, Reconnecting { seconds: u64, reason: Option<String> } }
|
||||
|
||||
pub struct Forwarding { pub port: u16, pub tunnel_id: String, pub owner_online: bool }
|
||||
|
||||
pub struct JoinCard {
|
||||
pub id: u64,
|
||||
pub target: String,
|
||||
pub code: String,
|
||||
pub server: String,
|
||||
pub state: JoinState,
|
||||
pub forwarding: Option<Forwarding>,
|
||||
pub started: Instant,
|
||||
pub stop: StopHandle,
|
||||
}
|
||||
|
||||
pub enum LoginStage { Idle, Starting, Waiting { code: String, url: String }, Failed(String) }
|
||||
|
||||
pub struct LoginForm { pub server: String, pub accept_invalid: bool, pub key: String, pub use_key: bool, pub stage: LoginStage, pub stop: Option<StopHandle> }
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub enum AuthChoice { Open, Password, Login }
|
||||
|
||||
pub struct NewTunnelForm {
|
||||
pub kind: TunnelKind,
|
||||
pub target: String,
|
||||
pub dir: String,
|
||||
pub picking_dir: bool,
|
||||
pub name: String,
|
||||
pub keep_host: bool,
|
||||
pub auth: AuthChoice,
|
||||
pub password: String,
|
||||
pub allow: Vec<String>,
|
||||
pub allow_input: String,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for NewTunnelForm {
|
||||
fn default() -> Self {
|
||||
Self { kind: TunnelKind::Http, target: String::new(), dir: String::new(), picking_dir: false, name: String::new(), keep_host: false,
|
||||
auth: AuthChoice::Open, password: String::new(), allow: Vec::new(), allow_input: String::new(), error: None }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ConnectForm { pub link: String, pub error: Option<String>, pub retry_port: Option<String> }
|
||||
|
||||
pub enum ToastAction { Reopen(TunnelKind, Options) }
|
||||
|
||||
pub struct Toast { pub text: String, pub at: Instant, pub error: bool, pub action: Option<ToastAction> }
|
||||
|
||||
impl Toast {
|
||||
pub fn expired(&self) -> bool { self.at.elapsed() > if self.action.is_some() { UNDO_FOR } else { TOAST_FOR } }
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Mailbox { tx: Sender<Msg>, repaint: Repaint }
|
||||
|
||||
impl Mailbox {
|
||||
fn send(&self, msg: Msg) {
|
||||
let _ = self.tx.send(msg);
|
||||
self.repaint.ping();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct State {
|
||||
pub runtime: Handle,
|
||||
mailbox: Mailbox,
|
||||
rx: Receiver<Msg>,
|
||||
pub page: Page,
|
||||
pub cfg: Config,
|
||||
pub server_info: Option<Result<ServerInfo, String>>,
|
||||
pub tunnels: Vec<TunnelCard>,
|
||||
pub joins: Vec<JoinCard>,
|
||||
next_id: u64,
|
||||
pub me: Option<Me>,
|
||||
pub listeners: Vec<Listener>,
|
||||
pub scan_ports: Arc<AtomicBool>,
|
||||
pub update: Option<String>,
|
||||
pub updating: bool,
|
||||
pub checked_update: bool,
|
||||
pub managed: bool,
|
||||
pub relaunch: bool,
|
||||
pub start_hidden: bool,
|
||||
pub hotkey: bool,
|
||||
pub autostart: bool,
|
||||
pub login: LoginForm,
|
||||
pub new_tunnel: NewTunnelForm,
|
||||
pub connect: ConnectForm,
|
||||
pub toasts: Vec<Toast>,
|
||||
pub has_tray: bool,
|
||||
pub quitting: bool,
|
||||
monitor: Option<egui::Rect>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn new(runtime: Handle, repaint: Repaint, has_tray: bool) -> Self {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let cfg = Config::load().unwrap_or_default();
|
||||
let login = LoginForm { server: cfg.server_url.clone().unwrap_or_default(), accept_invalid: cfg.accept_invalid_certs, key: String::new(), use_key: false, stage: LoginStage::Idle, stop: None };
|
||||
let mut state = Self {
|
||||
runtime, mailbox: Mailbox { tx, repaint }, rx, page: Page::Tunnels, cfg, server_info: None, tunnels: Vec::new(), joins: Vec::new(), next_id: 1,
|
||||
login, new_tunnel: NewTunnelForm::default(), connect: ConnectForm::default(),
|
||||
me: None, listeners: Vec::new(), scan_ports: Arc::new(AtomicBool::new(false)), update: None, updating: false, checked_update: false, managed: update::detect() == update::Install::Managed, relaunch: false, start_hidden: false, hotkey: false, autostart: super::autostart::enabled(), toasts: Vec::new(), has_tray, quitting: false, monitor: None,
|
||||
};
|
||||
state.fetch_info();
|
||||
state.fetch_me();
|
||||
let mailbox = state.mailbox.clone();
|
||||
state.runtime.spawn(async move { mailbox.send(Msg::Update(update::check().await)); });
|
||||
let (mailbox, scan) = (state.mailbox.clone(), state.scan_ports.clone());
|
||||
state.runtime.spawn(async move {
|
||||
loop {
|
||||
if scan.load(Ordering::Relaxed) {
|
||||
if let Ok(found) = tokio::task::spawn_blocking(ports::scan).await { mailbox.send(Msg::Listeners(found)); }
|
||||
}
|
||||
tokio::time::sleep(SCAN_INTERVAL).await;
|
||||
}
|
||||
});
|
||||
state
|
||||
}
|
||||
|
||||
pub fn expose(&mut self, listener: &Listener) {
|
||||
let target = Target { host: "127.0.0.1".into(), port: listener.port, tls: false };
|
||||
if listener.is_tcp() {
|
||||
self.start_tunnel(TunnelKind::Tcp, Options::tcp(target, None, tunnel::Access::default()));
|
||||
} else {
|
||||
self.start_tunnel(TunnelKind::Http, Options::http(tunnel::TargetSpec::Addr(target), None, false, tunnel::Access::default()));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn suggestions(&self) -> Vec<Listener> {
|
||||
self.listeners.iter().filter(|listener| !self.tunnels.iter().any(|card| card.target_label.ends_with(&format!(":{}", listener.port)))).cloned().collect()
|
||||
}
|
||||
|
||||
pub fn start_update(&mut self) {
|
||||
let Some(version) = self.update.clone() else { return };
|
||||
self.updating = true;
|
||||
let mailbox = self.mailbox.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let result = update::apply(&version, &update::detect(), true).await.map_err(|err| format!("{err:#}"));
|
||||
mailbox.send(Msg::Updated(result));
|
||||
});
|
||||
}
|
||||
|
||||
pub fn linked(&self) -> bool { self.cfg.device_token.is_some() && self.cfg.server_url().is_some() }
|
||||
|
||||
pub fn server_url(&self) -> String { self.cfg.server_url().unwrap_or_default() }
|
||||
|
||||
pub fn corner_position(&self) -> Option<egui::Pos2> { self.monitor.map(super::corner_for) }
|
||||
|
||||
fn next_id(&mut self) -> u64 { let id = self.next_id; self.next_id += 1; id }
|
||||
|
||||
fn forward<E: Send + 'static>(&self, mut rx: UnboundedReceiver<E>, wrap: impl Fn(E) -> Msg + Send + 'static) {
|
||||
let mailbox = self.mailbox.clone();
|
||||
self.runtime.spawn(async move {
|
||||
while let Some(event) = rx.recv().await { mailbox.send(wrap(event)); }
|
||||
});
|
||||
}
|
||||
|
||||
pub fn toast(&mut self, text: impl Into<String>) { self.toasts.push(Toast { text: text.into(), at: Instant::now(), error: false, action: None }); }
|
||||
pub fn toast_error(&mut self, text: impl Into<String>) { self.toasts.push(Toast { text: text.into(), at: Instant::now(), error: true, action: None }); }
|
||||
|
||||
pub fn fetch_me(&mut self) {
|
||||
let (Some(url), Some(token)) = (self.cfg.server_url(), self.cfg.device_token.clone()) else { self.me = None; return };
|
||||
let accept = self.cfg.accept_invalid_certs;
|
||||
let mailbox = self.mailbox.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let me = async { ApiClient::new(&url, Some(&token), accept)?.whoami().await }.await.ok();
|
||||
mailbox.send(Msg::Me(me));
|
||||
});
|
||||
}
|
||||
|
||||
pub fn reload_config(&mut self) {
|
||||
self.cfg = Config::load().unwrap_or_default();
|
||||
self.fetch_me();
|
||||
}
|
||||
|
||||
pub fn stop_all(&self) {
|
||||
for card in &self.tunnels { card.stop.stop(); }
|
||||
for join in &self.joins { join.stop.stop(); }
|
||||
if let Some(stop) = &self.login.stop { stop.stop(); }
|
||||
}
|
||||
|
||||
pub fn open_link(&mut self, link: String) {
|
||||
if let Some(invite) = auth::parse_invite(&link) {
|
||||
self.page = Page::Tunnels;
|
||||
let accept = self.cfg.accept_invalid_certs;
|
||||
let mailbox = self.mailbox.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let result = linked(auth::accept_invite(invite, accept).await);
|
||||
mailbox.send(Msg::Linked(result));
|
||||
});
|
||||
return;
|
||||
}
|
||||
self.page = Page::Connect;
|
||||
self.start_join(link, None, "127.0.0.1".into());
|
||||
}
|
||||
|
||||
pub fn fetch_info(&mut self) {
|
||||
let Some(url) = self.cfg.server_url() else { self.server_info = None; return };
|
||||
let accept = self.cfg.accept_invalid_certs;
|
||||
let mailbox = self.mailbox.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let result = async { ApiClient::new(&url, None, accept)?.info().await }.await.map_err(|err| format!("{err:#}"));
|
||||
mailbox.send(Msg::Info(result));
|
||||
});
|
||||
}
|
||||
|
||||
pub fn link_with_key(&mut self) {
|
||||
let server = self.login.server.trim().to_string();
|
||||
let key = self.login.key.trim().to_string();
|
||||
if server.is_empty() || key.is_empty() { self.login.stage = LoginStage::Failed("Enter the server URL and the API key".into()); return; }
|
||||
self.login.stage = LoginStage::Starting;
|
||||
let accept = self.login.accept_invalid;
|
||||
let mailbox = self.mailbox.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let result = linked(auth::link_token(server, key, accept).await);
|
||||
mailbox.send(Msg::Linked(result));
|
||||
});
|
||||
}
|
||||
|
||||
pub fn start_login(&mut self) {
|
||||
let server = self.login.server.trim().to_string();
|
||||
if server.is_empty() { self.login.stage = LoginStage::Failed("Enter the URL of your frislit server".into()); return; }
|
||||
let (events, rx) = session::channel();
|
||||
let (handle, stop) = Stop::new();
|
||||
self.login.stop = Some(handle);
|
||||
self.login.stage = LoginStage::Starting;
|
||||
let accept = self.login.accept_invalid;
|
||||
self.forward(rx, Msg::Login);
|
||||
let mailbox = self.mailbox.clone();
|
||||
self.runtime.spawn(async move {
|
||||
if let Err(err) = auth::link(&server, accept, events, stop).await {
|
||||
mailbox.send(Msg::LoginFailed(format!("{err:#}")));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn cancel_login(&mut self) {
|
||||
if let Some(stop) = self.login.stop.take() { stop.stop(); }
|
||||
self.login.stage = LoginStage::Idle;
|
||||
}
|
||||
|
||||
pub fn pick_folder(&mut self) {
|
||||
if self.new_tunnel.picking_dir { return; }
|
||||
self.new_tunnel.picking_dir = true;
|
||||
let start = Some(self.new_tunnel.dir.trim().to_string()).filter(|dir| !dir.is_empty()).map(PathBuf::from);
|
||||
let mailbox = self.mailbox.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let mut dialog = rfd::AsyncFileDialog::new().set_title("Folder to share");
|
||||
if let Some(start) = start { dialog = dialog.set_directory(start); }
|
||||
let picked = dialog.pick_folder().await.map(|handle| handle.path().to_path_buf());
|
||||
mailbox.send(Msg::FolderPicked(picked));
|
||||
});
|
||||
}
|
||||
|
||||
pub fn start_tunnel(&mut self, kind: TunnelKind, opts: Options) {
|
||||
let id = self.next_id();
|
||||
let target_label = opts.target.label();
|
||||
let (events, rx) = session::channel();
|
||||
let (handle, stop) = Stop::new();
|
||||
self.tunnels.push(TunnelCard {
|
||||
id, kind, opts: opts.clone(), target_label, access: None, probe: None, state: TunnelState::Connecting, online: None,
|
||||
requests: VecDeque::new(), connections: VecDeque::new(), request_count: 0, started: Instant::now(), stop: handle, show_qr: false, copied_at: None,
|
||||
});
|
||||
self.forward(rx, move |event| Msg::Tunnel(id, event));
|
||||
let mailbox = self.mailbox.clone();
|
||||
self.runtime.spawn(async move {
|
||||
let result = async {
|
||||
let (opts, target, label, _local) = tunnel::prepare(opts).await?;
|
||||
mailbox.send(Msg::TunnelReady(id, label));
|
||||
let _probe = (kind != TunnelKind::Files).then(|| Task(tokio::spawn(probe(mailbox.clone(), id, target.clone()))));
|
||||
tunnel::run(opts, target, events, stop).await
|
||||
}.await;
|
||||
if let Err(err) = result { mailbox.send(Msg::TunnelFailed(id, format!("{err:#}"))); }
|
||||
});
|
||||
self.page = Page::Tunnel(id);
|
||||
}
|
||||
|
||||
pub fn start_join(&mut self, target: String, port: Option<u16>, bind: String) {
|
||||
let (code, server) = match connect::resolve(&target, None) {
|
||||
Ok((code, _, server)) => (code, server),
|
||||
Err(err) => { self.connect.error = Some(format!("{err:#}")); self.connect.link = target; return; }
|
||||
};
|
||||
self.connect = ConnectForm::default();
|
||||
if self.joins.iter().any(|join| join.code == code) {
|
||||
self.toast("That share is already connected");
|
||||
return;
|
||||
}
|
||||
let id = self.next_id();
|
||||
let (events, rx) = session::channel();
|
||||
let (handle, stop) = Stop::new();
|
||||
self.joins.insert(0, JoinCard {
|
||||
id, target: target.clone(), code, server,
|
||||
state: JoinState::Connecting, forwarding: None, started: Instant::now(), stop: handle,
|
||||
});
|
||||
let opts = connect::Options { target, port, bind, server: None, pick_port: None };
|
||||
self.forward(rx, move |event| Msg::Join(id, event));
|
||||
let mailbox = self.mailbox.clone();
|
||||
self.runtime.spawn(async move {
|
||||
if let Err(err) = connect::run(opts, events, stop).await {
|
||||
let port_in_use = err.downcast_ref::<connect::PortInUse>().map(|taken| taken.port);
|
||||
mailbox.send(Msg::JoinFailed(id, format!("{err:#}"), port_in_use));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn fail_join(&mut self, id: u64, message: String, port_in_use: Option<u16>) {
|
||||
let Some(index) = self.joins.iter().position(|join| join.id == id) else { return };
|
||||
let join = self.joins.remove(index);
|
||||
if let Some(port) = port_in_use {
|
||||
self.connect.link = join.target;
|
||||
self.connect.retry_port = Some(port.saturating_add(1).to_string());
|
||||
self.connect.error = Some(message);
|
||||
} else {
|
||||
self.toast_error(message);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stop_tunnel(&mut self, id: u64) {
|
||||
if let Some(index) = self.tunnels.iter().position(|card| card.id == id) {
|
||||
self.tunnels.remove(index).stop.stop();
|
||||
}
|
||||
if self.page == Page::Tunnel(id) { self.page = Page::Tunnels; }
|
||||
}
|
||||
|
||||
pub fn stop_tunnel_by_user(&mut self, id: u64) {
|
||||
let Some(card) = self.tunnels.iter().find(|card| card.id == id) else { return };
|
||||
let (kind, opts, name) = (card.kind, card.opts.clone(), card.title());
|
||||
self.stop_tunnel(id);
|
||||
self.toasts.push(Toast { text: format!("{name} stopped"), at: Instant::now(), error: false, action: Some(ToastAction::Reopen(kind, opts)) });
|
||||
}
|
||||
|
||||
pub fn stop_join(&mut self, id: u64) {
|
||||
if let Some(index) = self.joins.iter().position(|join| join.id == id) {
|
||||
self.joins.remove(index).stop.stop();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn tunnel_mut(&mut self, id: u64) -> Option<&mut TunnelCard> { self.tunnels.iter_mut().find(|card| card.id == id) }
|
||||
|
||||
pub fn drain(&mut self, ctx: &egui::Context) {
|
||||
while let Ok(msg) = self.rx.try_recv() { self.handle(ctx, msg); }
|
||||
}
|
||||
|
||||
fn handle(&mut self, ctx: &egui::Context, msg: Msg) {
|
||||
match msg {
|
||||
Msg::TunnelReady(id, label) => { if let Some(card) = self.tunnel_mut(id) { card.target_label = label; } }
|
||||
Msg::Tunnel(id, event) => self.handle_tunnel(id, event),
|
||||
Msg::TunnelFailed(id, message) => {
|
||||
let fresh = self.tunnel_mut(id).is_some_and(|card| card.online.is_none());
|
||||
self.stop_tunnel(id);
|
||||
if fresh { self.new_tunnel.error = Some(message); self.page = Page::NewTunnel; } else { self.toast_error(message); }
|
||||
}
|
||||
Msg::Me(me) => self.me = me,
|
||||
Msg::Linked(Ok(message)) => { self.login.stage = LoginStage::Idle; self.login.key.clear(); self.reload_config(); self.fetch_info(); self.toast(message); }
|
||||
Msg::Linked(Err(message)) => { self.login.stage = LoginStage::Failed(message); }
|
||||
Msg::Update(version) => { self.update = version; self.checked_update = true; }
|
||||
Msg::Updated(Ok(_)) => { self.relaunch = true; self.quitting = true; ctx.send_viewport_cmd(egui::ViewportCommand::Close); }
|
||||
Msg::Updated(Err(message)) => { self.updating = false; self.toast_error(message); }
|
||||
Msg::TunnelProbe(id, warning) => { if let Some(card) = self.tunnel_mut(id) { card.probe = warning; } }
|
||||
Msg::Listeners(found) => self.listeners = found,
|
||||
Msg::Join(id, event) => self.handle_join(id, event),
|
||||
Msg::JoinFailed(id, message, port_in_use) => self.fail_join(id, message, port_in_use),
|
||||
Msg::Login(LoginEvent::Code { code, handoff_url }) => {
|
||||
ctx.open_url(egui::OpenUrl::new_tab(&handoff_url));
|
||||
self.login.stage = LoginStage::Waiting { code, url: handoff_url };
|
||||
}
|
||||
Msg::Login(LoginEvent::Linked { server_url, info }) => {
|
||||
self.login.stage = LoginStage::Idle;
|
||||
self.login.stop = None;
|
||||
self.reload_config();
|
||||
self.server_info = Some(Ok(info));
|
||||
self.toast(format!("This device is linked to {}", format::host_of(&server_url)));
|
||||
}
|
||||
Msg::LoginFailed(message) => { self.login.stage = LoginStage::Failed(message); self.login.stop = None; }
|
||||
Msg::Info(result) => self.server_info = Some(result),
|
||||
Msg::FolderPicked(path) => {
|
||||
self.new_tunnel.picking_dir = false;
|
||||
if let Some(path) = path { self.new_tunnel.dir = path.display().to_string(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_tunnel(&mut self, id: u64, event: TunnelEvent) {
|
||||
let server_url = self.server_url();
|
||||
let Some(card) = self.tunnel_mut(id) else { return };
|
||||
let mut toast = None;
|
||||
match event {
|
||||
TunnelEvent::Connecting => card.state = TunnelState::Connecting,
|
||||
TunnelEvent::Online(online) | TunnelEvent::Resumed(online) | TunnelEvent::Replaced(online) => {
|
||||
let fresh = card.online.as_ref().is_none_or(|current| current.id != online.id);
|
||||
card.state = TunnelState::Online;
|
||||
card.access = online.access.clone();
|
||||
if fresh {
|
||||
let copied = online.link(&server_url).is_some_and(|link| qr::copy(&link));
|
||||
toast = Some(if copied { format!("{} is online, link copied", online.id) } else { format!("{} is online", online.id) });
|
||||
}
|
||||
card.online = Some(online);
|
||||
}
|
||||
TunnelEvent::Connection(connection) => {
|
||||
if connection.opened {
|
||||
card.connections.push_front(connection);
|
||||
card.connections.truncate(MAX_REQUESTS);
|
||||
} else if let Some(existing) = card.connections.iter_mut().find(|entry| entry.key == connection.key) {
|
||||
*existing = connection;
|
||||
}
|
||||
}
|
||||
TunnelEvent::Access(summary) => card.access = Some(summary),
|
||||
TunnelEvent::Request(request) => {
|
||||
card.request_count += 1;
|
||||
if card.requests.len() == MAX_REQUESTS { card.requests.pop_back(); }
|
||||
card.requests.push_front(LoggedRequest { request, at: Instant::now() });
|
||||
}
|
||||
TunnelEvent::Reconnecting { seconds, reason } => card.state = TunnelState::Reconnecting { seconds, reason },
|
||||
TunnelEvent::Update(version) => self.update = Some(version),
|
||||
TunnelEvent::Stopped => self.stop_tunnel(id),
|
||||
TunnelEvent::Ended(reason) => { self.stop_tunnel(id); toast = Some(format!("Tunnel ended: {reason}")); }
|
||||
}
|
||||
if let Some(text) = toast { self.toast(text); }
|
||||
}
|
||||
|
||||
fn handle_join(&mut self, id: u64, event: JoinEvent) {
|
||||
let Some(join) = self.joins.iter_mut().find(|join| join.id == id) else { return };
|
||||
match event {
|
||||
JoinEvent::Connecting => join.state = JoinState::Connecting,
|
||||
JoinEvent::Forwarding { port, tunnel_id, owner_online, .. } => {
|
||||
join.state = JoinState::Forwarding;
|
||||
join.forwarding = Some(Forwarding { port, tunnel_id, owner_online });
|
||||
}
|
||||
JoinEvent::Reconnecting { seconds, reason } => join.state = JoinState::Reconnecting { seconds, reason },
|
||||
JoinEvent::Reconnected => join.state = JoinState::Forwarding,
|
||||
JoinEvent::Stopped => self.stop_join(id),
|
||||
JoinEvent::Ended(reason) => { self.stop_join(id); self.toast(format!("Disconnected: {reason}")); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Window<'a> {
|
||||
pub state: &'a mut State,
|
||||
wake: &'a Receiver<Wake>,
|
||||
pub logo: TextureHandle,
|
||||
qr: HashMap<u64, (String, TextureHandle)>,
|
||||
visible: bool,
|
||||
focused: bool,
|
||||
was_focused: bool,
|
||||
needs_show: bool,
|
||||
place_frames: u8,
|
||||
}
|
||||
|
||||
impl<'a> Window<'a> {
|
||||
pub fn new(cc: &eframe::CreationContext<'_>, state: &'a mut State, wake: &'a Receiver<Wake>) -> Self {
|
||||
let logo = cc.egui_ctx.load_texture("logo",
|
||||
egui::ColorImage::from_rgba_unmultiplied([super::ICON_SIZE as usize; 2], super::ICON_RGBA), TextureOptions::LINEAR);
|
||||
let start_hidden = std::mem::take(&mut state.start_hidden);
|
||||
let needs_show = !start_hidden && state.corner_position().is_none() && !hide_by_closing();
|
||||
Self { state, wake, logo, qr: HashMap::new(), visible: !start_hidden && !needs_show, focused: false, was_focused: false, needs_show, place_frames: 3 }
|
||||
}
|
||||
|
||||
pub fn qr_for(&mut self, ctx: &egui::Context, card_id: u64, link: &str) -> Option<TextureHandle> {
|
||||
if let Some((known, texture)) = self.qr.get(&card_id) {
|
||||
if known == link { return Some(texture.clone()); }
|
||||
}
|
||||
let texture = qr_texture(ctx, &format!("qr-{card_id}"), link)?;
|
||||
self.qr.insert(card_id, (link.to_string(), texture.clone()));
|
||||
Some(texture)
|
||||
}
|
||||
|
||||
fn place(&mut self, ctx: &egui::Context) {
|
||||
let area = super::work_area(ctx.pixels_per_point())
|
||||
.or_else(|| ctx.input(|input| input.viewport().monitor_size).map(|monitor| {
|
||||
egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(monitor.x, monitor.y - 48.0))
|
||||
}));
|
||||
let Some(area) = area else { return };
|
||||
if area.width() <= super::WINDOW_WIDTH || area.height() <= super::WINDOW_HEIGHT { return; }
|
||||
self.state.monitor = Some(area);
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::OuterPosition(super::corner_for(area)));
|
||||
}
|
||||
|
||||
fn show(&mut self, ctx: &egui::Context) {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(false));
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(true));
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Focus);
|
||||
self.visible = true;
|
||||
self.place_frames = 3;
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
pub fn minimize(&mut self, ctx: &egui::Context) {
|
||||
if !self.state.has_tray {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Minimized(true));
|
||||
} else if hide_by_closing() {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
} else {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Visible(false));
|
||||
self.visible = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn quit(&mut self, ctx: &egui::Context) {
|
||||
self.state.quitting = true;
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
|
||||
fn wake_events(&mut self, ctx: &egui::Context) {
|
||||
while let Ok(wake) = self.wake.try_recv() {
|
||||
match wake {
|
||||
Wake::Toggle => if self.visible && self.focused { self.minimize(ctx) } else { self.show(ctx) },
|
||||
Wake::Show => self.show(ctx),
|
||||
Wake::OpenLink(link) => { if let Some(link) = link { self.state.open_link(link); } self.show(ctx); }
|
||||
Wake::Quit => self.quit(ctx),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn nav(&mut self, root: &mut Ui) {
|
||||
let ctx = root.ctx().clone();
|
||||
let frame = Frame::new().fill(theme::BACKGROUND).inner_margin(Margin::symmetric(theme::GUTTER as i8, 0));
|
||||
egui::Panel::top("nav").frame(frame).exact_size(52.0).resizable(false).show_separator_line(false).show(root, |ui| {
|
||||
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 6.0;
|
||||
ui.image((self.logo.id(), egui::vec2(22.0, 22.0)));
|
||||
widgets::text_family(ui, "frislit", 15.0, theme::TEXT, theme::bold());
|
||||
ui.add_space(6.0);
|
||||
for (page, label) in [(Page::Tunnels, "Tunnels"), (Page::Connect, "Connect"), (Page::Settings, "Settings")] {
|
||||
let active = match (self.state.page, page) {
|
||||
(Page::Tunnels | Page::NewTunnel | Page::Tunnel(_), Page::Tunnels) => true,
|
||||
(current, target) => current == target,
|
||||
};
|
||||
if nav_link(ui, label, active).clicked() { self.state.page = page; }
|
||||
}
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if widgets::minimize_button(ui).clicked() { self.minimize(&ctx); }
|
||||
});
|
||||
});
|
||||
let rect = ui.max_rect();
|
||||
let y = rect.bottom() + 0.5;
|
||||
ui.painter().line_segment([egui::pos2(rect.left() - theme::GUTTER, y), egui::pos2(rect.right() + theme::GUTTER, y)], Stroke::new(1.0, theme::BORDER));
|
||||
});
|
||||
}
|
||||
|
||||
fn toasts(&mut self, ctx: &egui::Context) {
|
||||
self.state.toasts.retain(|toast| !toast.expired());
|
||||
if self.state.toasts.is_empty() { return; }
|
||||
ctx.request_repaint_after(Duration::from_millis(250));
|
||||
let mut acted = None;
|
||||
egui::Area::new(egui::Id::new("toasts")).anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -16.0)).order(egui::Order::Foreground).show(ctx, |ui| {
|
||||
ui.set_max_width(super::WINDOW_WIDTH - 32.0);
|
||||
ui.vertical(|ui| {
|
||||
for (index, toast) in self.state.toasts.iter().enumerate() {
|
||||
let (color, dot) = if toast.error { (theme::ERROR, theme::ERROR) } else { (theme::TEXT, theme::SUCCESS) };
|
||||
Frame::new().fill(theme::SURFACE_RAISED).stroke(Stroke::new(1.0, theme::BORDER_STRONG))
|
||||
.corner_radius(theme::corner(theme::RADIUS_INPUT)).inner_margin(Margin::symmetric(14, 10))
|
||||
.shadow(egui::epaint::Shadow { offset: [0, 6], blur: 24, spread: 0, color: Color32::from_black_alpha(140) })
|
||||
.show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::dot(ui, dot);
|
||||
ui.add(egui::Label::new(RichText::new(&toast.text).size(13.0).color(color)).wrap());
|
||||
if toast.action.is_some() && widgets::button(ui, "Reopen", widgets::ButtonKind::Ghost).clicked() { acted = Some(index); }
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(ToastAction::Reopen(kind, opts)) = acted.and_then(|index| self.state.toasts.remove(index).action) { self.state.start_tunnel(kind, opts); }
|
||||
}
|
||||
|
||||
pub fn content(ui: &mut Ui, add: impl FnOnce(&mut Ui)) {
|
||||
let total = ui.available_width();
|
||||
let width = total - theme::GUTTER * 2.0;
|
||||
let outer = ui.available_rect_before_wrap();
|
||||
let rect = egui::Rect::from_min_size(egui::pos2(outer.left() + theme::GUTTER, outer.top() + 20.0), egui::vec2(width, f32::INFINITY));
|
||||
let mut child = ui.new_child(UiBuilder::new().max_rect(rect).layout(Layout::top_down(Align::Min)));
|
||||
child.set_width(width);
|
||||
add(&mut child);
|
||||
ui.allocate_space(egui::vec2(total, child.min_rect().height() + 20.0 + 40.0));
|
||||
}
|
||||
}
|
||||
|
||||
fn nav_link(ui: &mut Ui, label: &str, active: bool) -> egui::Response {
|
||||
let galley = ui.painter().layout_no_wrap(label.to_string(), theme::font(13.0, theme::medium()), Color32::WHITE);
|
||||
let size = galley.size() + egui::vec2(18.0, 10.0);
|
||||
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
|
||||
let fill = if active { theme::SURFACE_HOVER } else { Color32::TRANSPARENT };
|
||||
let color = if active || response.hovered() { theme::TEXT } else { theme::MUTED };
|
||||
ui.painter().rect_filled(rect, theme::corner(theme::RADIUS_SMALL), fill);
|
||||
ui.painter().galley(rect.center() - galley.size() / 2.0, galley, color);
|
||||
if response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
|
||||
response
|
||||
}
|
||||
|
||||
pub fn qr_texture(ctx: &egui::Context, name: &str, text: &str) -> Option<TextureHandle> {
|
||||
let code = qrcode::QrCode::new(text.as_bytes()).ok()?;
|
||||
let width = code.width();
|
||||
let quiet = 2;
|
||||
let size = width + quiet * 2;
|
||||
let colors = code.to_colors();
|
||||
let mut rgba = vec![0u8; size * size * 4];
|
||||
for y in 0..size {
|
||||
for x in 0..size {
|
||||
let inside = quiet..width + quiet;
|
||||
let dark = inside.contains(&x) && inside.contains(&y) && colors[(y - quiet) * width + (x - quiet)] == qrcode::Color::Dark;
|
||||
let color = if dark { theme::BACKGROUND } else { theme::TEXT };
|
||||
let offset = (y * size + x) * 4;
|
||||
rgba[offset..offset + 4].copy_from_slice(&[color.r(), color.g(), color.b(), 255]);
|
||||
}
|
||||
}
|
||||
let image = egui::ColorImage::from_rgba_unmultiplied([size, size], &rgba);
|
||||
Some(ctx.load_texture(name, image, TextureOptions::NEAREST))
|
||||
}
|
||||
|
||||
impl eframe::App for Window<'_> {
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
self.was_focused = self.focused;
|
||||
self.focused = ctx.input(|input| input.viewport().focused.unwrap_or(false));
|
||||
self.wake_events(ctx);
|
||||
self.state.drain(ctx);
|
||||
if !self.visible || !self.state.has_tray || self.place_frames > 0 { return; }
|
||||
let lost_focus = self.was_focused && !self.focused && !self.state.new_tunnel.picking_dir;
|
||||
let escaped = self.focused && ctx.memory(|memory| memory.focused().is_none()) && ctx.input(|input| input.key_pressed(egui::Key::Escape));
|
||||
if lost_focus || escaped { self.minimize(ctx); }
|
||||
}
|
||||
|
||||
fn ui(&mut self, root: &mut Ui, _frame: &mut eframe::Frame) {
|
||||
let ctx = root.ctx().clone();
|
||||
let closing = ctx.input(|input| input.viewport().close_requested());
|
||||
if closing && !self.state.quitting && self.state.has_tray && !hide_by_closing() {
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
|
||||
self.minimize(&ctx);
|
||||
}
|
||||
if self.needs_show { self.needs_show = false; self.show(&ctx); }
|
||||
if self.place_frames > 0 {
|
||||
self.place_frames -= 1;
|
||||
self.place(&ctx);
|
||||
ctx.request_repaint_after(Duration::from_millis(30));
|
||||
}
|
||||
self.state.scan_ports.store(self.visible && self.state.page == Page::Tunnels && self.state.linked(), Ordering::Relaxed);
|
||||
let rect = ctx.content_rect();
|
||||
ctx.layer_painter(egui::LayerId::background()).rect_stroke(rect, 0.0, Stroke::new(1.0, theme::BORDER_STRONG), egui::StrokeKind::Inside);
|
||||
self.nav(root);
|
||||
egui::CentralPanel::default().frame(Frame::new().fill(theme::BACKGROUND)).show(root, |ui| {
|
||||
let scroll_id = match self.state.page { Page::Tunnels => 0u64, Page::NewTunnel => 1, Page::Tunnel(id) => 100 + id, Page::Connect => 2, Page::Settings => 3 };
|
||||
egui::ScrollArea::vertical().id_salt(("page", scroll_id)).auto_shrink([false, false]).show(ui, |ui| {
|
||||
match self.state.page {
|
||||
Page::Tunnels => self.tunnels_page(ui),
|
||||
Page::NewTunnel => self.new_tunnel_page(ui),
|
||||
Page::Tunnel(id) => self.tunnel_page(ui, id),
|
||||
Page::Connect => self.connect_page(ui),
|
||||
Page::Settings => self.settings_page(ui),
|
||||
}
|
||||
});
|
||||
});
|
||||
self.toasts(&ctx);
|
||||
}
|
||||
}
|
||||
|
||||
fn linked(result: anyhow::Result<(Me, ServerInfo)>) -> Result<String, String> {
|
||||
result.map(|(me, info)| format!("Linked to {} as {}", info.name, me.label())).map_err(|err| format!("{err:#}"))
|
||||
}
|
||||
|
||||
async fn reachable(target: &Target) -> bool {
|
||||
let Ok(addrs) = target.resolve().await else { return false };
|
||||
tokio::time::timeout(PROBE_TIMEOUT, connect_target(&addrs)).await.is_ok_and(|result| result.is_ok())
|
||||
}
|
||||
|
||||
async fn probe(mailbox: Mailbox, id: u64, target: Target) {
|
||||
while !reachable(&target).await {
|
||||
mailbox.send(Msg::TunnelProbe(id, Some(format!("Nothing is listening on {} yet", target.authority()))));
|
||||
tokio::time::sleep(PROBE_INTERVAL).await;
|
||||
}
|
||||
mailbox.send(Msg::TunnelProbe(id, None));
|
||||
}
|
||||
|
||||
pub fn state_label(state: &TunnelState) -> &'static str {
|
||||
match state {
|
||||
TunnelState::Connecting => "Connecting",
|
||||
TunnelState::Online => "Online",
|
||||
TunnelState::Reconnecting { .. } => "Reconnecting",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn state_dot(state: &TunnelState) -> Color32 {
|
||||
match state {
|
||||
TunnelState::Connecting => theme::MUTED,
|
||||
TunnelState::Online => theme::SUCCESS,
|
||||
TunnelState::Reconnecting { .. } => theme::WARNING,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use anyhow::Result;
|
||||
|
||||
#[cfg(unix)]
|
||||
fn entry() -> Result<std::path::PathBuf> {
|
||||
use anyhow::Context;
|
||||
#[cfg(target_os = "linux")]
|
||||
let path = dirs::config_dir().context("No config directory")?.join("autostart/frislit.desktop");
|
||||
#[cfg(target_os = "macos")]
|
||||
let path = dirs::home_dir().context("No home directory")?.join("Library/LaunchAgents/dev.frislit.gui.plist");
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub fn enabled() -> bool {
|
||||
entry().is_ok_and(|path| path.exists())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub fn set(on: bool) -> Result<()> {
|
||||
let path = entry()?;
|
||||
if !on { let _ = std::fs::remove_file(&path); return Ok(()); }
|
||||
std::fs::create_dir_all(path.parent().unwrap())?;
|
||||
let exe = std::env::current_exe()?;
|
||||
#[cfg(target_os = "linux")]
|
||||
let body = format!("[Desktop Entry]\nType=Application\nName=frislit\nExec={} gui --hidden\nX-GNOME-Autostart-enabled=true\n", exe.display());
|
||||
#[cfg(target_os = "macos")]
|
||||
let body = format!(
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>dev.frislit.gui</string>\n<key>ProgramArguments</key><array><string>{}</string><string>gui</string><string>--hidden</string></array>\n<key>RunAtLoad</key><true/>\n</dict></plist>\n",
|
||||
exe.display());
|
||||
std::fs::write(&path, body)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run";
|
||||
|
||||
#[cfg(windows)]
|
||||
fn reg(args: &[&str]) -> Result<bool> {
|
||||
Ok(std::process::Command::new("reg").args(args).output()?.status.success())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn enabled() -> bool {
|
||||
reg(&["query", RUN_KEY, "/v", "frislit"]).unwrap_or(false)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set(on: bool) -> Result<()> {
|
||||
let command = format!("\"{}\" gui --hidden", std::env::current_exe()?.display());
|
||||
let done = if on { reg(&["add", RUN_KEY, "/v", "frislit", "/t", "REG_SZ", "/d", &command, "/f"])? } else { reg(&["delete", RUN_KEY, "/v", "frislit", "/f"])? };
|
||||
anyhow::ensure!(done, "Could not update the autostart entry");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
use std::time::Instant;
|
||||
|
||||
pub fn ago(since: Instant) -> String {
|
||||
let secs = since.elapsed().as_secs();
|
||||
if secs < 5 { "just now".into() }
|
||||
else if secs < 60 { format!("{secs}s ago") }
|
||||
else if secs < 3600 { format!("{}m ago", secs / 60) }
|
||||
else if secs < 86_400 { format!("{}h ago", secs / 3600) }
|
||||
else { format!("{}d ago", secs / 86_400) }
|
||||
}
|
||||
|
||||
pub fn host_of(url: &str) -> String {
|
||||
let rest = url.split("://").nth(1).unwrap_or(url);
|
||||
rest.split('/').next().unwrap_or(rest).to_string()
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
use anyhow::{Context, Result};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader as AsyncBufReader};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::runtime::Handle;
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_millis(800);
|
||||
|
||||
fn lock_file() -> Result<PathBuf> {
|
||||
let dir = dirs::config_dir().context("No config directory")?.join("frislit");
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
Ok(dir.join("gui.instance"))
|
||||
}
|
||||
|
||||
pub fn hand_over(link: Option<&str>) -> bool {
|
||||
let Ok(path) = lock_file() else { return false };
|
||||
let Ok(contents) = std::fs::read_to_string(&path) else { return false };
|
||||
let mut lines = contents.lines();
|
||||
let (Some(port), Some(secret)) = (lines.next().and_then(|p| p.parse::<u16>().ok()), lines.next()) else { return false };
|
||||
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
|
||||
let Ok(mut stream) = TcpStream::connect_timeout(&addr, TIMEOUT) else { return false };
|
||||
let _ = stream.set_read_timeout(Some(TIMEOUT));
|
||||
if writeln!(stream, "{secret} {}", link.unwrap_or("")).is_err() { return false; }
|
||||
let mut reply = String::new();
|
||||
BufReader::new(stream).read_line(&mut reply).is_ok() && reply.trim() == "ok"
|
||||
}
|
||||
|
||||
pub fn serve(runtime: &Handle, on_link: impl Fn(Option<String>) + Send + Sync + 'static) -> Result<()> {
|
||||
let listener = runtime.block_on(TcpListener::bind("127.0.0.1:0"))?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let secret: String = (0..32).map(|_| { let n = rand_byte() % 36; (if n < 10 { b'0' + n } else { b'a' + n - 10 }) as char }).collect();
|
||||
let path = lock_file()?;
|
||||
std::fs::write(&path, format!("{port}\n{secret}\n"))?;
|
||||
#[cfg(unix)]
|
||||
{ use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)); }
|
||||
|
||||
runtime.spawn(async move {
|
||||
loop {
|
||||
let Ok((stream, _)) = listener.accept().await else { continue };
|
||||
let mut reader = AsyncBufReader::new(stream);
|
||||
let mut line = String::new();
|
||||
let Ok(Ok(_)) = tokio::time::timeout(TIMEOUT, reader.read_line(&mut line)).await else { continue };
|
||||
let Some((given, link)) = line.trim_end().split_once(' ') else { continue };
|
||||
if given != secret { continue; }
|
||||
let link = link.trim().to_string();
|
||||
on_link(if link.is_empty() { None } else { Some(link) });
|
||||
let _ = reader.get_mut().write_all(b"ok\n").await;
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn release() {
|
||||
if let Ok(path) = lock_file() { let _ = std::fs::remove_file(path); }
|
||||
}
|
||||
|
||||
fn rand_byte() -> u8 {
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
(RandomState::new().build_hasher().finish() >> 24) as u8
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use eframe::egui;
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::randr;
|
||||
use x11rb::protocol::xproto::{AtomEnum, ConnectionExt};
|
||||
|
||||
#[derive(PartialEq)]
|
||||
pub enum Backend { X11, Wayland }
|
||||
|
||||
pub fn choose_backend() -> Backend {
|
||||
let has_x11 = std::env::var_os("DISPLAY").is_some_and(|value| !value.is_empty());
|
||||
let has_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some_and(|value| !value.is_empty());
|
||||
if has_x11 {
|
||||
if has_wayland { std::env::remove_var("WAYLAND_DISPLAY"); }
|
||||
Backend::X11
|
||||
} else {
|
||||
Backend::Wayland
|
||||
}
|
||||
}
|
||||
|
||||
pub fn primary_work_area(pixels_per_point: f32) -> Option<egui::Rect> {
|
||||
let (connection, screen_number) = x11rb::connect(None).ok()?;
|
||||
let root = connection.setup().roots.get(screen_number)?.root;
|
||||
|
||||
let monitors = randr::get_monitors(&connection, root, true).ok()?.reply().ok()?.monitors;
|
||||
let monitor = monitors.iter().find(|monitor| monitor.primary).or_else(|| monitors.first())?;
|
||||
let mut area = egui::Rect::from_min_size(
|
||||
egui::pos2(monitor.x as f32, monitor.y as f32),
|
||||
egui::vec2(monitor.width as f32, monitor.height as f32),
|
||||
);
|
||||
|
||||
let atom = connection.intern_atom(false, b"_NET_WORKAREA").ok()?.reply().ok()?.atom;
|
||||
let reply = connection.get_property(false, root, atom, AtomEnum::CARDINAL, 0, 4).ok()?.reply().ok()?;
|
||||
if let Some(mut values) = reply.value32() {
|
||||
if let (Some(x), Some(y), Some(width), Some(height)) = (values.next(), values.next(), values.next(), values.next()) {
|
||||
let work = egui::Rect::from_min_size(egui::pos2(x as f32, y as f32), egui::vec2(width as f32, height as f32));
|
||||
area = area.intersect(work);
|
||||
}
|
||||
}
|
||||
if area.width() <= 0.0 || area.height() <= 0.0 { return None; }
|
||||
|
||||
let scale = 1.0 / pixels_per_point;
|
||||
Some(egui::Rect::from_min_max(egui::pos2(area.left() * scale, area.top() * scale), egui::pos2(area.right() * scale, area.bottom() * scale)))
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
mod app;
|
||||
mod autostart;
|
||||
mod format;
|
||||
mod instance;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
mod pages;
|
||||
mod ports;
|
||||
mod theme;
|
||||
mod tray;
|
||||
mod widgets;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use eframe::egui;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{mpsc, Arc, Mutex};
|
||||
use tokio::runtime::Handle;
|
||||
|
||||
const ICON_SIZE: u32 = 128;
|
||||
const ICON_RGBA: &[u8] = include_bytes!("../../assets/icon-128.rgba");
|
||||
|
||||
pub const WINDOW_WIDTH: f32 = 396.0;
|
||||
pub const WINDOW_HEIGHT: f32 = 704.0;
|
||||
const CORNER_MARGIN: f32 = 12.0;
|
||||
|
||||
static WAYLAND: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
pub fn hide_by_closing() -> bool { WAYLAND.load(Ordering::Relaxed) }
|
||||
|
||||
pub const HOTKEY_LABEL: &str = "Super+Shift+T";
|
||||
|
||||
pub enum Wake { Toggle, Show, OpenLink(Option<String>), Quit }
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Repaint(Arc<Mutex<Option<egui::Context>>>);
|
||||
|
||||
impl Repaint {
|
||||
pub fn attach(&self, ctx: &egui::Context) { *self.0.lock().unwrap() = Some(ctx.clone()); }
|
||||
pub fn detach(&self) { *self.0.lock().unwrap() = None; }
|
||||
pub fn ping(&self) { if let Some(ctx) = self.0.lock().unwrap().as_ref() { ctx.request_repaint(); } }
|
||||
}
|
||||
|
||||
pub fn launch(runtime: Handle, link: Option<String>, hidden: bool) -> Result<()> {
|
||||
detach_console();
|
||||
if instance::hand_over(link.as_deref()) { return Ok(()); }
|
||||
#[cfg(target_os = "linux")]
|
||||
WAYLAND.store(linux::choose_backend() == linux::Backend::Wayland, Ordering::Relaxed);
|
||||
|
||||
let (wake_tx, wake_rx) = mpsc::channel::<Wake>();
|
||||
let repaint = Repaint::default();
|
||||
let tray = tray::start(wake_tx.clone(), repaint.clone(), &runtime).ok();
|
||||
{
|
||||
let (wake_tx, repaint) = (wake_tx.clone(), repaint.clone());
|
||||
instance::serve(&runtime, move |link| { let _ = wake_tx.send(Wake::OpenLink(link)); repaint.ping(); })
|
||||
.context("Could not listen for links from the browser")?;
|
||||
}
|
||||
|
||||
let hotkey = hotkey(wake_tx.clone(), repaint.clone());
|
||||
let mut state = app::State::new(runtime, repaint.clone(), tray.is_some());
|
||||
state.start_hidden = hidden && tray.is_some();
|
||||
state.hotkey = hotkey.is_some();
|
||||
if let Some(link) = link { state.open_link(link); }
|
||||
|
||||
let mut open = !(state.start_hidden && hide_by_closing());
|
||||
let result = loop {
|
||||
if open {
|
||||
if let Err(err) = run_window(&mut state, &wake_rx, &repaint) { break Err(err); }
|
||||
if state.quitting { break Ok(()); }
|
||||
}
|
||||
open = true;
|
||||
match wake_rx.recv() {
|
||||
Ok(Wake::Toggle | Wake::Show) => {}
|
||||
Ok(Wake::OpenLink(link)) => { if let Some(link) = link { state.open_link(link); } }
|
||||
Ok(Wake::Quit) | Err(_) => break Ok(()),
|
||||
}
|
||||
};
|
||||
state.stop_all();
|
||||
instance::release();
|
||||
if state.relaunch { let _ = std::process::Command::new(std::env::current_exe()?).arg("gui").spawn(); }
|
||||
result
|
||||
}
|
||||
|
||||
fn run_window(state: &mut app::State, wake_rx: &mpsc::Receiver<Wake>, repaint: &Repaint) -> Result<()> {
|
||||
let icon = egui::IconData { rgba: ICON_RGBA.to_vec(), width: ICON_SIZE, height: ICON_SIZE };
|
||||
let viewport = egui::ViewportBuilder::default()
|
||||
.with_title("frislit")
|
||||
.with_app_id("dev.frislit.cli")
|
||||
.with_inner_size([WINDOW_WIDTH, WINDOW_HEIGHT])
|
||||
.with_min_inner_size([WINDOW_WIDTH, WINDOW_HEIGHT])
|
||||
.with_max_inner_size([WINDOW_WIDTH, WINDOW_HEIGHT])
|
||||
.with_resizable(false)
|
||||
.with_decorations(false)
|
||||
.with_taskbar(false)
|
||||
.with_icon(Arc::new(icon));
|
||||
let viewport = match state.corner_position() {
|
||||
Some(position) => viewport.with_position(position),
|
||||
None => viewport.with_visible(hide_by_closing()),
|
||||
};
|
||||
let viewport = if state.start_hidden { viewport.with_visible(false) } else { viewport };
|
||||
let options = eframe::NativeOptions { viewport, ..Default::default() };
|
||||
|
||||
let outcome = eframe::run_native("frislit", options, Box::new(|cc| {
|
||||
theme::install(&cc.egui_ctx);
|
||||
repaint.attach(&cc.egui_ctx);
|
||||
Ok(Box::new(app::Window::new(cc, state, wake_rx)))
|
||||
}));
|
||||
repaint.detach();
|
||||
outcome.map_err(|err| anyhow::anyhow!("{err}")).context("Could not open the frislit window")
|
||||
}
|
||||
|
||||
fn hotkey(wake: mpsc::Sender<Wake>, repaint: Repaint) -> Option<global_hotkey::GlobalHotKeyManager> {
|
||||
use global_hotkey::{hotkey::{Code, HotKey, Modifiers}, GlobalHotKeyEvent, GlobalHotKeyManager, HotKeyState};
|
||||
let manager = GlobalHotKeyManager::new().ok()?;
|
||||
manager.register(HotKey::new(Some(Modifiers::SUPER | Modifiers::SHIFT), Code::KeyT)).ok()?;
|
||||
GlobalHotKeyEvent::set_event_handler(Some(move |event: GlobalHotKeyEvent| {
|
||||
if event.state == HotKeyState::Pressed { let _ = wake.send(Wake::Toggle); repaint.ping(); }
|
||||
}));
|
||||
Some(manager)
|
||||
}
|
||||
|
||||
pub fn corner_for(area: egui::Rect) -> egui::Pos2 {
|
||||
egui::pos2(area.right() - WINDOW_WIDTH - CORNER_MARGIN, area.bottom() - WINDOW_HEIGHT - CORNER_MARGIN)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn detach_console() {
|
||||
use windows_sys::Win32::System::Console::{FreeConsole, GetConsoleProcessList};
|
||||
let mut processes = [0u32; 2];
|
||||
let count = unsafe { GetConsoleProcessList(processes.as_mut_ptr(), processes.len() as u32) };
|
||||
if count <= 1 { unsafe { FreeConsole(); } }
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
fn detach_console() {}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn work_area(pixels_per_point: f32) -> Option<egui::Rect> {
|
||||
if hide_by_closing() { return None; }
|
||||
linux::primary_work_area(pixels_per_point)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn work_area(pixels_per_point: f32) -> Option<egui::Rect> {
|
||||
use windows_sys::Win32::Foundation::RECT;
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{SystemParametersInfoW, SPI_GETWORKAREA};
|
||||
let mut rect = RECT { left: 0, top: 0, right: 0, bottom: 0 };
|
||||
let ok = unsafe { SystemParametersInfoW(SPI_GETWORKAREA, 0, &mut rect as *mut RECT as *mut _, 0) };
|
||||
if ok == 0 { return None; }
|
||||
let scale = 1.0 / pixels_per_point;
|
||||
Some(egui::Rect::from_min_max(
|
||||
egui::pos2(rect.left as f32 * scale, rect.top as f32 * scale),
|
||||
egui::pos2(rect.right as f32 * scale, rect.bottom as f32 * scale),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(not(any(windows, target_os = "linux")))]
|
||||
pub fn work_area(_pixels_per_point: f32) -> Option<egui::Rect> { None }
|
||||
@@ -0,0 +1,92 @@
|
||||
use eframe::egui::{self, Align, Layout, Ui};
|
||||
use crate::gui::app::{JoinState, Window};
|
||||
use crate::gui::widgets::{self, ButtonKind, FieldOptions};
|
||||
use crate::gui::{format, theme};
|
||||
|
||||
impl Window<'_> {
|
||||
pub fn connect_page(&mut self, ui: &mut Ui) {
|
||||
let logo = self.logo.id();
|
||||
let state = &mut self.state;
|
||||
Window::content(ui, |ui| {
|
||||
let mut start = None;
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(if state.joins.is_empty() { 96.0 } else { 24.0 });
|
||||
ui.image((logo, egui::vec2(56.0, 56.0)));
|
||||
ui.add_space(14.0);
|
||||
widgets::text_family(ui, "Paste a share link.", 24.0, theme::TEXT, theme::semibold());
|
||||
ui.add_space(20.0);
|
||||
ui.with_layout(Layout::top_down(Align::Min), |ui| {
|
||||
let form = &mut state.connect;
|
||||
let mut submit = widgets::field(ui, "connect-link", &mut form.link, FieldOptions { hint: "https://frislit.example.com/@frislit/connect/…", mono: true, ..Default::default() }).lost_focus()
|
||||
&& ui.input(|input| input.key_pressed(egui::Key::Enter));
|
||||
ui.add_space(10.0);
|
||||
if let Some(error) = &form.error { widgets::error_notice(ui, error); ui.add_space(10.0); }
|
||||
if let Some(port) = &mut form.retry_port {
|
||||
widgets::field(ui, "connect-port", port, FieldOptions { label: Some("Local port"), hint: "4000", mono: true, ..Default::default() });
|
||||
ui.add_space(10.0);
|
||||
}
|
||||
if widgets::button_sized(ui, "Connect", ButtonKind::Primary, ui.available_width()).clicked() { submit = true; }
|
||||
if submit {
|
||||
let link = form.link.trim().to_string();
|
||||
let port = form.retry_port.as_ref().map(|port| port.trim().parse::<u16>()).transpose();
|
||||
if link.is_empty() {
|
||||
form.error = Some("Paste a share link first".into());
|
||||
} else if let Ok(port) = port {
|
||||
start = Some((link, port));
|
||||
} else {
|
||||
form.error = Some("The local port must be a number between 1 and 65535".into());
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some((link, port)) = start { state.start_join(link, port, "127.0.0.1".into()); }
|
||||
|
||||
if state.joins.is_empty() { return; }
|
||||
ui.add_space(36.0);
|
||||
|
||||
let mut stop = None;
|
||||
ui.spacing_mut().item_spacing.y = 8.0;
|
||||
for join in &state.joins {
|
||||
widgets::card(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 8.0;
|
||||
match &join.state {
|
||||
JoinState::Connecting => widgets::dot(ui, theme::MUTED),
|
||||
JoinState::Forwarding => widgets::dot(ui, theme::SUCCESS),
|
||||
JoinState::Reconnecting { .. } => widgets::dot(ui, theme::WARNING),
|
||||
}
|
||||
ui.scope(|ui| {
|
||||
ui.set_max_width(ui.available_width() - 84.0);
|
||||
if let Some(forwarding) = &join.forwarding {
|
||||
widgets::mono(ui, format!("Port {}", forwarding.port), 14.0, theme::TEXT);
|
||||
widgets::arrow_right(ui, theme::MUTED);
|
||||
ui.add(egui::Label::new(egui::RichText::new(&forwarding.tunnel_id).size(13.0).color(theme::PRIMARY_BRIGHT).family(theme::mono())).truncate());
|
||||
} else {
|
||||
ui.add(egui::Label::new(egui::RichText::new(&join.target).size(12.5).color(theme::SUBTEXT).family(theme::mono())).truncate());
|
||||
}
|
||||
});
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if widgets::button(ui, "Stop", ButtonKind::Danger).clicked() { stop = Some(join.id); }
|
||||
});
|
||||
});
|
||||
ui.add_space(2.0);
|
||||
widgets::text(ui, format!("{} · {}", format::host_of(&join.server), format::ago(join.started)), 12.0, theme::MUTED);
|
||||
|
||||
match &join.state {
|
||||
JoinState::Reconnecting { seconds, reason } => {
|
||||
ui.add_space(8.0);
|
||||
let text = match reason { Some(reason) => format!("Connection lost, retrying in {seconds}s ({reason})"), None => "Connection lost, reconnecting...".to_string() };
|
||||
widgets::warning_notice(ui, &text);
|
||||
}
|
||||
JoinState::Forwarding if join.forwarding.as_ref().is_some_and(|f| !f.owner_online) => {
|
||||
ui.add_space(8.0);
|
||||
widgets::warning_notice(ui, "The owner is offline right now.");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(id) = stop { state.stop_join(id); }
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
use eframe::egui::{self, Align, Layout, Ui};
|
||||
use crate::gui::app::{state_dot, state_label, Page, TunnelKind, TunnelState, Window};
|
||||
use crate::gui::widgets::{self, ButtonKind};
|
||||
use crate::gui::{format, theme};
|
||||
use crate::session::{bytes, took};
|
||||
|
||||
impl Window<'_> {
|
||||
pub fn tunnel_page(&mut self, ui: &mut Ui, id: u64) {
|
||||
let server_url = self.state.server_url();
|
||||
let Some(index) = self.state.tunnels.iter().position(|card| card.id == id) else { self.state.page = Page::Tunnels; return };
|
||||
let link = self.state.tunnels[index].link(&server_url);
|
||||
let qr = match (&link, self.state.tunnels[index].show_qr) {
|
||||
(Some(link), true) => self.qr_for(&ui.ctx().clone(), id, link),
|
||||
_ => None,
|
||||
};
|
||||
let mut go_back = false;
|
||||
let mut stop = false;
|
||||
|
||||
Window::content(ui, |ui| {
|
||||
let card = &mut self.state.tunnels[index];
|
||||
if widgets::back_link(ui, "Tunnels").clicked() { go_back = true; }
|
||||
ui.add_space(12.0);
|
||||
|
||||
ui.add(egui::Label::new(egui::RichText::new(card.title()).size(20.0).color(theme::TEXT).family(theme::semibold())).truncate());
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = egui::vec2(6.0, 4.0);
|
||||
widgets::dot(ui, state_dot(&card.state));
|
||||
widgets::text(ui, state_label(&card.state), 12.5, theme::SUBTEXT);
|
||||
widgets::text(ui, "·", 12.5, theme::MUTED);
|
||||
widgets::text(ui, card.kind.label(), 12.5, theme::SUBTEXT);
|
||||
widgets::text(ui, "·", 12.5, theme::MUTED);
|
||||
widgets::mono(ui, &card.target_label, 12.5, theme::SUBTEXT);
|
||||
widgets::text(ui, "·", 12.5, theme::MUTED);
|
||||
widgets::text(ui, format!("started {}", format::ago(card.started)), 12.5, theme::MUTED);
|
||||
});
|
||||
if let Some(access) = &card.access {
|
||||
ui.add_space(4.0);
|
||||
widgets::text(ui, format!("Access: {access}"), 12.5, theme::SUBTEXT);
|
||||
}
|
||||
if let Some(warning) = &card.probe {
|
||||
ui.add_space(4.0);
|
||||
widgets::text(ui, warning, 12.5, theme::WARNING);
|
||||
}
|
||||
ui.add_space(12.0);
|
||||
ui.horizontal(|ui| {
|
||||
if let Some(online) = &card.online {
|
||||
if let Some(url) = &online.url {
|
||||
if widgets::button(ui, "Open in browser", ButtonKind::Secondary).clicked() { ui.ctx().open_url(egui::OpenUrl::new_tab(url)); }
|
||||
}
|
||||
if widgets::button(ui, "Dashboard", ButtonKind::Secondary).clicked() {
|
||||
ui.ctx().open_url(egui::OpenUrl::new_tab(format!("{server_url}/@frislit/tunnels/{}", online.id)));
|
||||
}
|
||||
}
|
||||
if widgets::button(ui, "Stop", ButtonKind::Danger).clicked() { stop = true; }
|
||||
});
|
||||
ui.add_space(12.0);
|
||||
|
||||
if let TunnelState::Reconnecting { seconds, reason } = &card.state {
|
||||
let text = match reason { Some(reason) => format!("Connection lost, retrying in {seconds}s ({reason})"), None => "Connection lost, reconnecting...".to_string() };
|
||||
widgets::warning_notice(ui, &text);
|
||||
ui.add_space(12.0);
|
||||
}
|
||||
|
||||
if let Some(link) = &link {
|
||||
let is_share = card.online.as_ref().is_some_and(|online| online.url.is_none());
|
||||
let shown = if is_share { format!("frislit connect {link}") } else { link.clone() };
|
||||
widgets::copy_row(ui, ("copy", card.id), &shown, &mut card.copied_at);
|
||||
ui.add_space(8.0);
|
||||
let label = if card.show_qr { "Hide QR code" } else { "Show QR code" };
|
||||
if widgets::button(ui, label, ButtonKind::Ghost).clicked() { card.show_qr = !card.show_qr; }
|
||||
if let Some(qr) = &qr {
|
||||
ui.vertical_centered(|ui| {
|
||||
egui::Frame::new().fill(theme::TEXT).corner_radius(theme::corner(theme::RADIUS_INPUT)).inner_margin(egui::Margin::same(8)).show(ui, |ui| {
|
||||
ui.image((qr.id(), egui::vec2(176.0, 176.0)));
|
||||
});
|
||||
});
|
||||
}
|
||||
} else if card.state == TunnelState::Connecting {
|
||||
ui.horizontal(|ui| { ui.spinner(); widgets::text(ui, "Connecting to the server...", 14.0, theme::SUBTEXT); });
|
||||
}
|
||||
|
||||
ui.add_space(20.0);
|
||||
if card.kind == TunnelKind::Tcp {
|
||||
let open = card.connections.iter().filter(|connection| connection.opened).count();
|
||||
widgets::section(ui, "Connections", Some(&format!("{open} open")));
|
||||
widgets::card(ui, |ui| {
|
||||
if card.connections.is_empty() {
|
||||
widgets::text(ui, "No connections yet.", 13.0, theme::MUTED);
|
||||
return;
|
||||
}
|
||||
ui.spacing_mut().item_spacing.y = 8.0;
|
||||
for connection in card.connections.iter().take(100) {
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 8.0;
|
||||
widgets::dot(ui, if connection.opened { theme::SUCCESS } else { theme::MUTED });
|
||||
widgets::mono(ui, &connection.protocol, 12.0, theme::TEXT);
|
||||
widgets::mono(ui, &connection.ip, 12.0, theme::SUBTEXT);
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
let right = if connection.opened { connection.detail.clone().unwrap_or_default() } else { format!("{} in · {} out · {}", bytes(connection.bytes_in), bytes(connection.bytes_out), took(connection.duration)) };
|
||||
widgets::mono(ui, right, 11.5, theme::MUTED);
|
||||
});
|
||||
});
|
||||
let note = if connection.opened { connection.intel() } else { connection.reason.clone() };
|
||||
if let Some(note) = note {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(16.0);
|
||||
ui.add(egui::Label::new(egui::RichText::new(note).size(11.5).color(theme::MUTED)).truncate());
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
widgets::section(ui, "Requests", Some(&format!("{} so far", card.request_count)));
|
||||
widgets::card(ui, |ui| {
|
||||
if card.requests.is_empty() {
|
||||
widgets::text(ui, "No requests yet.", 13.0, theme::MUTED);
|
||||
return;
|
||||
}
|
||||
ui.spacing_mut().item_spacing.y = 8.0;
|
||||
for logged in card.requests.iter().take(100) {
|
||||
let request = &logged.request;
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 8.0;
|
||||
let method = if request.kind == "ws" { "WS".to_string() } else { request.method.clone() };
|
||||
ui.allocate_ui_with_layout(egui::vec2(44.0, 18.0), Layout::left_to_right(Align::Center), |ui| { widgets::mono(ui, method, 12.0, theme::TEXT); });
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
ui.allocate_ui_with_layout(egui::vec2(48.0, 18.0), Layout::right_to_left(Align::Center), |ui| { widgets::mono(ui, format!("{}ms", request.duration), 11.5, theme::MUTED); });
|
||||
widgets::mono(ui, request.status.to_string(), 12.0, widgets::status_color(request.status));
|
||||
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(egui::RichText::new(&request.path).size(12.0).color(theme::SUBTEXT).family(theme::mono())).truncate());
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(52.0);
|
||||
let mut note = request.ip.clone();
|
||||
if let Some(intel) = request.intel() { note = format!("{note} · {intel}"); }
|
||||
ui.add(egui::Label::new(egui::RichText::new(format!("{note} · {}", format::ago(logged.at))).size(11.5).color(theme::MUTED)).truncate());
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if stop { self.state.stop_tunnel_by_user(id); }
|
||||
if go_back { self.state.page = Page::Tunnels; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
mod connect;
|
||||
mod detail;
|
||||
mod new_tunnel;
|
||||
mod settings;
|
||||
mod tunnels;
|
||||
@@ -0,0 +1,137 @@
|
||||
use eframe::egui::{self, Align, Layout, Ui};
|
||||
use crate::gui::app::{AuthChoice, NewTunnelForm, Page, TunnelKind, Window};
|
||||
use crate::gui::widgets::{self, ButtonKind, FieldOptions};
|
||||
use crate::gui::theme;
|
||||
use crate::tunnel::{Access, Options, Rules, Target, TargetSpec};
|
||||
|
||||
impl Window<'_> {
|
||||
pub fn new_tunnel_page(&mut self, ui: &mut Ui) {
|
||||
let state = &mut self.state;
|
||||
Window::content(ui, |ui| {
|
||||
if widgets::back_link(ui, "Tunnels").clicked() { state.page = Page::Tunnels; }
|
||||
ui.add_space(12.0);
|
||||
widgets::text_family(ui, "New tunnel", 22.0, theme::TEXT, theme::semibold());
|
||||
ui.add_space(16.0);
|
||||
|
||||
let mut submit = false;
|
||||
ui.horizontal(|ui| {
|
||||
widgets::segmented(ui, &mut state.new_tunnel.kind, &[(TunnelKind::Http, "HTTP"), (TunnelKind::Files, "Folder"), (TunnelKind::Tcp, "TCP + UDP")]);
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if widgets::button(ui, "Open", ButtonKind::Primary).clicked() { submit = true; }
|
||||
});
|
||||
});
|
||||
if let Some(error) = &state.new_tunnel.error {
|
||||
ui.add_space(10.0);
|
||||
widgets::error_notice(ui, error);
|
||||
}
|
||||
ui.add_space(14.0);
|
||||
|
||||
let mut browse = false;
|
||||
let form = &mut state.new_tunnel;
|
||||
widgets::card(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 14.0;
|
||||
match form.kind {
|
||||
TunnelKind::Http => {
|
||||
widgets::field(ui, "nt-target", &mut form.target, FieldOptions { label: Some("Local target"), hint: "3000, 192.168.1.5:8080 or https://localhost:8443", mono: true, ..Default::default() });
|
||||
}
|
||||
TunnelKind::Files => {
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 6.0;
|
||||
widgets::field_label(ui, "Folder");
|
||||
ui.horizontal(|ui| {
|
||||
let width = ui.available_width() - 96.0;
|
||||
widgets::field(ui, "nt-dir", &mut form.dir, FieldOptions { hint: "/path/to/dist", mono: true, width: Some(width), ..Default::default() });
|
||||
ui.add_enabled_ui(!form.picking_dir, |ui| {
|
||||
if widgets::button(ui, "Browse", ButtonKind::Secondary).clicked() { browse = true; }
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
TunnelKind::Tcp => {
|
||||
widgets::field(ui, "nt-tcp", &mut form.target, FieldOptions { label: Some("Local port"), hint: "25565 or 192.168.1.5:5432", mono: true, ..Default::default() });
|
||||
}
|
||||
}
|
||||
widgets::field(ui, "nt-name", &mut form.name, FieldOptions { label: Some("Name (optional)"), hint: "myapp", mono: true, ..Default::default() });
|
||||
if form.kind == TunnelKind::Http {
|
||||
widgets::toggle_row(ui, "Keep the public host", "Send the public hostname as the Host header", &mut form.keep_host);
|
||||
}
|
||||
});
|
||||
|
||||
ui.add_space(16.0);
|
||||
widgets::section(ui, "Access", None);
|
||||
widgets::card(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 14.0;
|
||||
if form.kind != TunnelKind::Tcp {
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 6.0;
|
||||
widgets::field_label(ui, "Sign-in");
|
||||
let label = match form.auth { AuthChoice::Open => "Open to everyone", AuthChoice::Password => "Ask for a password", AuthChoice::Login => "Require a frislit account" };
|
||||
egui::ComboBox::from_id_salt("nt-auth").selected_text(label).width(ui.available_width()).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut form.auth, AuthChoice::Open, "Open to everyone");
|
||||
ui.selectable_value(&mut form.auth, AuthChoice::Password, "Ask for a password");
|
||||
ui.selectable_value(&mut form.auth, AuthChoice::Login, "Require a frislit account");
|
||||
});
|
||||
});
|
||||
if form.auth == AuthChoice::Password {
|
||||
widgets::field(ui, "nt-password", &mut form.password, FieldOptions { label: Some("Password"), hint: "hunter2", secret: true, ..Default::default() });
|
||||
}
|
||||
}
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 6.0;
|
||||
widgets::field_label(ui, "Allowed addresses");
|
||||
ui.horizontal(|ui| {
|
||||
let width = ui.available_width() - 80.0;
|
||||
let entered = widgets::field(ui, "nt-allow", &mut form.allow_input, FieldOptions { hint: "203.0.113.5 or 10.0.0.0/8", mono: true, width: Some(width), ..Default::default() }).lost_focus()
|
||||
&& ui.input(|input| input.key_pressed(egui::Key::Enter));
|
||||
if widgets::button(ui, "Add", ButtonKind::Secondary).clicked() || entered {
|
||||
let value = form.allow_input.trim().to_string();
|
||||
if !value.is_empty() && !form.allow.contains(&value) { form.allow.push(value); }
|
||||
form.allow_input.clear();
|
||||
}
|
||||
});
|
||||
let mut drop = None;
|
||||
for (index, cidr) in form.allow.iter().enumerate() {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::mono(ui, cidr, 13.0, theme::SUBTEXT);
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if widgets::button(ui, "Remove", ButtonKind::Ghost).clicked() { drop = Some(index); }
|
||||
});
|
||||
});
|
||||
}
|
||||
if let Some(index) = drop { form.allow.remove(index); }
|
||||
});
|
||||
});
|
||||
|
||||
if browse { state.pick_folder(); }
|
||||
if submit {
|
||||
match build_options(&state.new_tunnel) {
|
||||
Ok(opts) => {
|
||||
let kind = state.new_tunnel.kind;
|
||||
state.new_tunnel.error = None;
|
||||
state.start_tunnel(kind, opts);
|
||||
}
|
||||
Err(err) => state.new_tunnel.error = Some(format!("{err:#}")),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn build_options(form: &NewTunnelForm) -> anyhow::Result<Options> {
|
||||
let name = Some(form.name.trim().to_string()).filter(|name| !name.is_empty());
|
||||
let auth = if form.kind == TunnelKind::Tcp { AuthChoice::Open } else { form.auth };
|
||||
let password = (auth == AuthChoice::Password).then(|| form.password.clone());
|
||||
if password.as_deref() == Some("") { anyhow::bail!("Enter a password, or pick another sign-in option"); }
|
||||
let access = Access::new(Rules::ips(form.allow.clone()), password, auth == AuthChoice::Login)?;
|
||||
let target = form.target.trim();
|
||||
if form.kind != TunnelKind::Files && target.is_empty() { anyhow::bail!("Enter a port or host:port to share"); }
|
||||
Ok(match form.kind {
|
||||
TunnelKind::Http => Options::http(TargetSpec::parse(target)?, name, form.keep_host, access),
|
||||
TunnelKind::Files => {
|
||||
let dir = form.dir.trim();
|
||||
if dir.is_empty() { anyhow::bail!("Pick the folder to share"); }
|
||||
Options::http(TargetSpec::dir(dir)?, name, false, access)
|
||||
}
|
||||
TunnelKind::Tcp => Options::tcp(Target::parse(target)?, name, access),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
use eframe::egui::{self, Align, Layout, Ui};
|
||||
use crate::auth;
|
||||
use crate::gui::app::Window;
|
||||
use crate::gui::widgets::{self, ButtonKind};
|
||||
use crate::gui::{autostart, theme, HOTKEY_LABEL};
|
||||
|
||||
impl Window<'_> {
|
||||
pub fn settings_page(&mut self, ui: &mut Ui) {
|
||||
let logo = self.logo.id();
|
||||
let mut quit = false;
|
||||
let state = &mut self.state;
|
||||
let server_url = state.cfg.server_url();
|
||||
Window::content(ui, |ui| {
|
||||
widgets::heading(ui, "Settings");
|
||||
ui.add_space(16.0);
|
||||
|
||||
widgets::section(ui, "Server", None);
|
||||
widgets::card(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.scope(|ui| {
|
||||
ui.set_max_width(ui.available_width() - 90.0);
|
||||
match &server_url {
|
||||
Some(url) => { ui.add(egui::Label::new(egui::RichText::new(url).size(14.0).color(theme::TEXT).family(theme::mono())).truncate()); }
|
||||
None => { widgets::text(ui, "No server yet", 14.0, theme::SUBTEXT); }
|
||||
}
|
||||
});
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if state.linked() { widgets::text(ui, "Linked", 12.5, theme::SUCCESS); }
|
||||
else if server_url.is_some() { widgets::text(ui, "Not linked", 12.5, theme::WARNING); }
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
match (&server_url, &state.server_info) {
|
||||
(None, _) => {}
|
||||
(Some(_), Some(Ok(info))) => { ui.add(egui::Label::new(egui::RichText::new(format!("{} {} · tunnels under {}", info.name, info.version, info.base_domain)).size(12.5).color(theme::SUBTEXT)).wrap()); }
|
||||
(Some(_), Some(Err(err))) => { ui.add(egui::Label::new(egui::RichText::new(format!("Not reachable: {err}")).size(12.5).color(theme::ERROR)).wrap()); }
|
||||
(Some(_), None) => { widgets::text(ui, "Checking...", 12.5, theme::MUTED); }
|
||||
}
|
||||
if let Some(me) = &state.me {
|
||||
ui.add_space(2.0);
|
||||
widgets::text(ui, format!("Signed in as {}", me.label()), 12.5, theme::SUBTEXT);
|
||||
}
|
||||
if state.linked() {
|
||||
ui.add_space(10.0);
|
||||
if widgets::button(ui, "Unlink this device", ButtonKind::Danger).clicked() {
|
||||
match auth::logout() {
|
||||
Ok(_) => { state.reload_config(); state.toast("Device unlinked"); }
|
||||
Err(err) => state.toast_error(format!("{err:#}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.add_space(12.0);
|
||||
widgets::divider(ui);
|
||||
ui.add_space(12.0);
|
||||
let mut accept = state.cfg.accept_invalid_certs;
|
||||
if widgets::toggle_row(ui, "Accept self-signed certificates", "", &mut accept).changed() {
|
||||
state.cfg.accept_invalid_certs = accept;
|
||||
state.login.accept_invalid = accept;
|
||||
match state.cfg.save() { Ok(_) => state.fetch_info(), Err(err) => state.toast_error(format!("{err:#}")) }
|
||||
}
|
||||
});
|
||||
|
||||
if state.has_tray {
|
||||
ui.add_space(24.0);
|
||||
widgets::section(ui, "Window", None);
|
||||
widgets::card(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 14.0;
|
||||
let mut autostart_on = state.autostart;
|
||||
if widgets::toggle_row(ui, "Launch at login", "Starts hidden in the tray", &mut autostart_on).changed() {
|
||||
match autostart::set(autostart_on) {
|
||||
Ok(_) => state.autostart = autostart_on,
|
||||
Err(err) => state.toast_error(format!("{err:#}")),
|
||||
}
|
||||
}
|
||||
if state.hotkey { widgets::text(ui, format!("{HOTKEY_LABEL} shows or hides the window"), 12.5, theme::MUTED); }
|
||||
});
|
||||
}
|
||||
|
||||
ui.add_space(24.0);
|
||||
widgets::section(ui, "About", None);
|
||||
widgets::card(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.image((logo, egui::vec2(32.0, 32.0)));
|
||||
widgets::text_family(ui, format!("frislit {}", env!("CARGO_PKG_VERSION")), 14.0, theme::TEXT, theme::semibold());
|
||||
if state.has_tray {
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if widgets::button(ui, "Quit", ButtonKind::Danger).clicked() { quit = true; }
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let mut start_update = false;
|
||||
match (state.update.clone(), state.managed) {
|
||||
(Some(version), true) => { widgets::text(ui, format!("{version} is available through your package manager"), 12.5, theme::WARNING); }
|
||||
(Some(version), false) => {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::text(ui, format!("{version} is available"), 12.5, theme::WARNING);
|
||||
ui.add_enabled_ui(!state.updating, |ui| {
|
||||
if widgets::button(ui, if state.updating { "Updating..." } else { "Update and restart" }, ButtonKind::Primary).clicked() { start_update = true; }
|
||||
});
|
||||
});
|
||||
}
|
||||
(None, _) => { widgets::text(ui, if state.checked_update { "Up to date" } else { "Checking for updates..." }, 12.5, theme::MUTED); }
|
||||
}
|
||||
if start_update { state.start_update(); }
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::button(ui, "Documentation", ButtonKind::Ghost).clicked() { ui.ctx().open_url(egui::OpenUrl::new_tab("https://git.fristy.net/fristy/frislit/blob/main/docs/cli.md")); }
|
||||
if widgets::button(ui, "GitHub", ButtonKind::Ghost).clicked() { ui.ctx().open_url(egui::OpenUrl::new_tab("https://git.fristy.net/fristy/frislit")); }
|
||||
});
|
||||
});
|
||||
});
|
||||
if quit { self.quit(&ui.ctx().clone()); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
use eframe::egui::{self, Align, Layout, Ui};
|
||||
use crate::gui::app::{state_dot, LoginStage, Page, TunnelState, Window};
|
||||
use crate::gui::widgets::{self, ButtonKind, FieldOptions};
|
||||
use crate::gui::{format, theme};
|
||||
|
||||
impl Window<'_> {
|
||||
pub fn tunnels_page(&mut self, ui: &mut Ui) {
|
||||
Window::content(ui, |ui| {
|
||||
if !self.state.linked() {
|
||||
self.login_card(ui);
|
||||
return;
|
||||
}
|
||||
|
||||
let state = &mut self.state;
|
||||
let online = state.tunnels.iter().filter(|card| matches!(card.state, TunnelState::Online)).count();
|
||||
ui.horizontal(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
widgets::heading(ui, "Tunnels");
|
||||
widgets::text(ui, format!("{online} of {} online", state.tunnels.len()), 12.5, theme::MUTED);
|
||||
});
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if widgets::button(ui, "New tunnel", ButtonKind::Primary).clicked() {
|
||||
state.new_tunnel.error = None;
|
||||
state.page = Page::NewTunnel;
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(16.0);
|
||||
|
||||
if state.tunnels.is_empty() {
|
||||
widgets::empty_state(ui, "No tunnels yet", "Share a port, a folder or a TCP service.", |ui| {
|
||||
if widgets::button(ui, "Open your first tunnel", ButtonKind::Secondary).clicked() { state.page = Page::NewTunnel; }
|
||||
});
|
||||
}
|
||||
|
||||
let server_url = state.server_url();
|
||||
let mut open = None;
|
||||
ui.spacing_mut().item_spacing.y = 8.0;
|
||||
for card in &state.tunnels {
|
||||
let response = widgets::clickable_card(ui, ("tunnel-row", card.id), |ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 4.0;
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 8.0;
|
||||
widgets::dot(ui, state_dot(&card.state));
|
||||
widgets::mono(ui, card.title(), 14.0, theme::TEXT);
|
||||
widgets::text(ui, card.kind.label(), 12.0, theme::MUTED);
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
widgets::chevron_right(ui, theme::MUTED);
|
||||
widgets::text(ui, format::ago(card.started), 12.0, theme::MUTED);
|
||||
});
|
||||
});
|
||||
let link = card.link(&server_url).unwrap_or_else(|| "connecting...".into());
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(16.0);
|
||||
ui.add(egui::Label::new(egui::RichText::new(format!("{link} · {}", card.target_label)).size(12.5).color(theme::SUBTEXT)).truncate());
|
||||
});
|
||||
});
|
||||
});
|
||||
if response.clicked() { open = Some(card.id); }
|
||||
}
|
||||
if let Some(id) = open { state.page = Page::Tunnel(id); }
|
||||
|
||||
let suggestions = state.suggestions();
|
||||
if suggestions.is_empty() { return; }
|
||||
ui.add_space(24.0);
|
||||
widgets::section(ui, "Listening on this machine", None);
|
||||
let mut expose = None;
|
||||
widgets::card(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 10.0;
|
||||
for listener in &suggestions {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 10.0;
|
||||
widgets::mono(ui, format!("localhost:{}", listener.port), 14.0, theme::TEXT);
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if widgets::button(ui, "Open", ButtonKind::Secondary).clicked() { expose = Some(listener.clone()); }
|
||||
widgets::text(ui, if listener.is_tcp() { "tcp" } else { "http" }, 12.5, theme::MUTED);
|
||||
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(egui::RichText::new(&listener.process).size(12.5).color(theme::MUTED)).truncate());
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
if let Some(listener) = expose { state.expose(&listener); }
|
||||
});
|
||||
}
|
||||
|
||||
fn login_card(&mut self, ui: &mut Ui) {
|
||||
let logo = self.logo.id();
|
||||
let state = &mut self.state;
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.add_space(28.0);
|
||||
ui.image((logo, egui::vec2(56.0, 56.0)));
|
||||
ui.add_space(12.0);
|
||||
widgets::text_family(ui, "Link this device.", 24.0, theme::TEXT, theme::semibold());
|
||||
ui.add_space(24.0);
|
||||
|
||||
ui.with_layout(Layout::top_down(Align::Min), |ui| {
|
||||
match &state.login.stage {
|
||||
LoginStage::Idle | LoginStage::Failed(_) => {
|
||||
let mut submit = widgets::field(ui, "login-server", &mut state.login.server,
|
||||
FieldOptions { label: Some("Server URL"), hint: "https://frislit.example.com", ..Default::default() }).lost_focus()
|
||||
&& ui.input(|input| input.key_pressed(egui::Key::Enter));
|
||||
ui.add_space(10.0);
|
||||
if state.login.use_key {
|
||||
submit |= widgets::field(ui, "login-key", &mut state.login.key,
|
||||
FieldOptions { label: Some("API key"), hint: "Created under Devices in the web UI", mono: true, secret: true, ..Default::default() }).lost_focus()
|
||||
&& ui.input(|input| input.key_pressed(egui::Key::Enter));
|
||||
ui.add_space(10.0);
|
||||
}
|
||||
widgets::toggle_row(ui, "Accept self-signed certificates", "", &mut state.login.accept_invalid);
|
||||
ui.add_space(8.0);
|
||||
if let LoginStage::Failed(message) = &state.login.stage {
|
||||
widgets::error_notice(ui, message);
|
||||
ui.add_space(8.0);
|
||||
}
|
||||
let label = if state.login.use_key { "Link with key" } else { "Continue" };
|
||||
if widgets::button_sized(ui, label, ButtonKind::Primary, ui.available_width()).clicked() { submit = true; }
|
||||
if submit { if state.login.use_key { state.link_with_key() } else { state.start_login() } }
|
||||
ui.add_space(4.0);
|
||||
let other = if state.login.use_key { "Approve in the browser instead" } else { "Use an API key instead" };
|
||||
if widgets::button(ui, other, ButtonKind::Ghost).clicked() { state.login.use_key = !state.login.use_key; state.login.stage = LoginStage::Idle; }
|
||||
}
|
||||
LoginStage::Starting => {
|
||||
ui.horizontal(|ui| { ui.spinner(); widgets::text(ui, "Contacting the server...", 14.0, theme::SUBTEXT); });
|
||||
}
|
||||
LoginStage::Waiting { code, url } => {
|
||||
let code = code.clone();
|
||||
let url = url.clone();
|
||||
widgets::card(ui, |ui| {
|
||||
ui.vertical_centered(|ui| {
|
||||
widgets::text(ui, "Approve this device in your browser", 14.0, theme::SUBTEXT);
|
||||
ui.add_space(8.0);
|
||||
widgets::text_family(ui, &code, 30.0, theme::PRIMARY_BRIGHT, theme::bold());
|
||||
ui.add_space(8.0);
|
||||
ui.horizontal(|ui| { ui.spinner(); widgets::text(ui, "Waiting for approval...", 13.0, theme::MUTED); });
|
||||
});
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::button(ui, "Open approval page", ButtonKind::Secondary).clicked() { ui.ctx().open_url(egui::OpenUrl::new_tab(&url)); }
|
||||
if widgets::button(ui, "Cancel", ButtonKind::Ghost).clicked() { state.cancel_login(); }
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Listener { pub port: u16, pub process: String }
|
||||
|
||||
const TCP_SERVICES: [&str; 10] = ["postgres", "postmaster", "redis-server", "mysqld", "mariadbd", "mongod", "sshd", "memcached", "valkey-server", "beam.smp"];
|
||||
|
||||
impl Listener {
|
||||
pub fn is_tcp(&self) -> bool { TCP_SERVICES.contains(&self.process.as_str()) }
|
||||
}
|
||||
|
||||
pub fn scan() -> Vec<Listener> {
|
||||
let own = std::process::id();
|
||||
let mut found: BTreeMap<u16, String> = BTreeMap::new();
|
||||
for (port, pid, process) in listeners() {
|
||||
if !(1024..32768).contains(&port) || pid == own || process == "frislit" { continue; }
|
||||
found.entry(port).or_insert(process);
|
||||
}
|
||||
found.into_iter().map(|(port, process)| Listener { port, process }).collect()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn listeners() -> Vec<(u16, u32, String)> {
|
||||
let mut inodes: BTreeMap<u64, u16> = BTreeMap::new();
|
||||
for table in ["/proc/net/tcp", "/proc/net/tcp6"] {
|
||||
let Ok(text) = std::fs::read_to_string(table) else { continue };
|
||||
for line in text.lines().skip(1) {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
if fields.len() < 10 || fields[3] != "0A" { continue; }
|
||||
let (Some(port), Ok(inode)) = (fields[1].rsplit(':').next().and_then(|hex| u16::from_str_radix(hex, 16).ok()), fields[9].parse::<u64>()) else { continue };
|
||||
inodes.insert(inode, port);
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let Ok(procs) = std::fs::read_dir("/proc") else { return out };
|
||||
for entry in procs.flatten() {
|
||||
let Ok(pid) = entry.file_name().to_string_lossy().parse::<u32>() else { continue };
|
||||
let Ok(fds) = std::fs::read_dir(entry.path().join("fd")) else { continue };
|
||||
let cmdline = std::fs::read(entry.path().join("cmdline")).unwrap_or_default();
|
||||
let argv0 = String::from_utf8_lossy(cmdline.split(|byte| *byte == 0).next().unwrap_or_default()).into_owned();
|
||||
let name = argv0.rsplit('/').next().unwrap_or_default().to_string();
|
||||
for fd in fds.flatten() {
|
||||
let Ok(link) = std::fs::read_link(fd.path()) else { continue };
|
||||
let text = link.to_string_lossy();
|
||||
let Some(inode) = text.strip_prefix("socket:[").and_then(|rest| rest.strip_suffix(']')).and_then(|inode| inode.parse::<u64>().ok()) else { continue };
|
||||
if let Some(port) = inodes.get(&inode) { out.push((*port, pid, name.clone())); }
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn listeners() -> Vec<(u16, u32, String)> {
|
||||
let Ok(output) = std::process::Command::new("lsof").args(["-nP", "-iTCP", "-sTCP:LISTEN"]).output() else { return Vec::new() };
|
||||
String::from_utf8_lossy(&output.stdout).lines().skip(1).filter_map(|line| {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
let port = fields.get(8)?.rsplit(':').next()?.parse().ok()?;
|
||||
Some((port, fields.get(1)?.parse().ok()?, fields[0].to_string()))
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn listeners() -> Vec<(u16, u32, String)> {
|
||||
let Ok(netstat) = std::process::Command::new("netstat").args(["-ano", "-p", "TCP"]).output() else { return Vec::new() };
|
||||
let names: BTreeMap<u32, String> = std::process::Command::new("tasklist").args(["/FO", "CSV", "/NH"]).output().map(|output| {
|
||||
String::from_utf8_lossy(&output.stdout).lines().filter_map(|line| {
|
||||
let mut cells = line.split("\",\"");
|
||||
let name = cells.next()?.trim_start_matches('"').trim_end_matches(".exe").to_string();
|
||||
Some((cells.next()?.parse().ok()?, name))
|
||||
}).collect()
|
||||
}).unwrap_or_default();
|
||||
String::from_utf8_lossy(&netstat.stdout).lines().filter_map(|line| {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
if fields.get(3) != Some(&"LISTENING") { return None; }
|
||||
let port = fields.get(1)?.rsplit(':').next()?.parse().ok()?;
|
||||
let pid: u32 = fields.get(4)?.parse().ok()?;
|
||||
Some((port, pid, names.get(&pid).cloned().unwrap_or_default()))
|
||||
}).collect()
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use eframe::egui::{self, Color32, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, Stroke, TextStyle, Visuals};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub const BACKGROUND: Color32 = Color32::from_rgb(0x11, 0x10, 0x0E);
|
||||
pub const SURFACE: Color32 = Color32::from_rgb(0x17, 0x16, 0x13);
|
||||
pub const SURFACE_RAISED: Color32 = Color32::from_rgb(0x1C, 0x1A, 0x17);
|
||||
pub const SURFACE_HOVER: Color32 = Color32::from_rgb(0x22, 0x1F, 0x1B);
|
||||
pub const BORDER: Color32 = Color32::from_rgba_premultiplied(18, 18, 18, 18);
|
||||
pub const BORDER_STRONG: Color32 = Color32::from_rgba_premultiplied(33, 33, 33, 33);
|
||||
|
||||
pub const PRIMARY: Color32 = Color32::from_rgb(0x14, 0xB8, 0xA6);
|
||||
pub const PRIMARY_BRIGHT: Color32 = Color32::from_rgb(0x2D, 0xD4, 0xBF);
|
||||
pub const PRIMARY_HOVER: Color32 = Color32::from_rgb(0x5E, 0xEA, 0xD4);
|
||||
pub const PRIMARY_TINT: Color32 = Color32::from_rgba_premultiplied(3, 26, 23, 36);
|
||||
pub const ON_PRIMARY: Color32 = Color32::from_rgb(0x05, 0x20, 0x1C);
|
||||
|
||||
pub const TEXT: Color32 = Color32::from_rgb(0xFA, 0xFA, 0xF9);
|
||||
pub const SUBTEXT: Color32 = Color32::from_rgb(0xA8, 0xA2, 0x9E);
|
||||
pub const MUTED: Color32 = Color32::from_rgb(0x79, 0x71, 0x6B);
|
||||
|
||||
pub const ERROR: Color32 = Color32::from_rgb(0xF8, 0x71, 0x71);
|
||||
pub const ERROR_TINT: Color32 = Color32::from_rgba_premultiplied(32, 15, 15, 33);
|
||||
pub const SUCCESS: Color32 = Color32::from_rgb(0x34, 0xD3, 0x99);
|
||||
pub const WARNING: Color32 = Color32::from_rgb(0xFB, 0xBF, 0x24);
|
||||
pub const WARNING_TINT: Color32 = Color32::from_rgba_premultiplied(32, 25, 5, 33);
|
||||
|
||||
pub const RADIUS_INPUT: u8 = 12;
|
||||
pub const RADIUS_CARD: u8 = 14;
|
||||
pub const RADIUS_SMALL: u8 = 10;
|
||||
|
||||
pub const GUTTER: f32 = 16.0;
|
||||
|
||||
pub fn medium() -> FontFamily { FontFamily::Proportional }
|
||||
pub fn semibold() -> FontFamily { FontFamily::Name("semibold".into()) }
|
||||
pub fn bold() -> FontFamily { FontFamily::Name("bold".into()) }
|
||||
pub fn mono() -> FontFamily { FontFamily::Monospace }
|
||||
|
||||
pub fn font(size: f32, family: FontFamily) -> FontId { FontId::new(size, family) }
|
||||
|
||||
pub fn corner(radius: u8) -> CornerRadius { CornerRadius::same(radius) }
|
||||
|
||||
pub fn install(ctx: &egui::Context) {
|
||||
let mut fonts = FontDefinitions::default();
|
||||
fonts.font_data.insert("jakarta-medium".into(), Arc::new(FontData::from_static(include_bytes!("../../assets/PlusJakartaSans-Medium.ttf"))));
|
||||
fonts.font_data.insert("jakarta-semibold".into(), Arc::new(FontData::from_static(include_bytes!("../../assets/PlusJakartaSans-SemiBold.ttf"))));
|
||||
fonts.font_data.insert("jakarta-bold".into(), Arc::new(FontData::from_static(include_bytes!("../../assets/PlusJakartaSans-Bold.ttf"))));
|
||||
|
||||
let fallback = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
|
||||
let with_fallback = |first: &str| std::iter::once(first.to_string()).chain(fallback.iter().cloned()).collect::<Vec<_>>();
|
||||
fonts.families.insert(FontFamily::Proportional, with_fallback("jakarta-medium"));
|
||||
fonts.families.insert(semibold(), with_fallback("jakarta-semibold"));
|
||||
fonts.families.insert(bold(), with_fallback("jakarta-bold"));
|
||||
ctx.set_fonts(fonts);
|
||||
|
||||
let mut visuals = Visuals::dark();
|
||||
visuals.panel_fill = BACKGROUND;
|
||||
visuals.window_fill = SURFACE_RAISED;
|
||||
visuals.window_stroke = Stroke::new(1.0, BORDER_STRONG);
|
||||
visuals.window_corner_radius = corner(RADIUS_CARD);
|
||||
visuals.menu_corner_radius = corner(RADIUS_INPUT);
|
||||
visuals.extreme_bg_color = SURFACE;
|
||||
visuals.faint_bg_color = SURFACE_RAISED;
|
||||
visuals.code_bg_color = SURFACE_HOVER;
|
||||
visuals.override_text_color = Some(TEXT);
|
||||
visuals.hyperlink_color = PRIMARY_BRIGHT;
|
||||
visuals.selection.bg_fill = PRIMARY_TINT;
|
||||
visuals.selection.stroke = Stroke::new(1.0, PRIMARY);
|
||||
visuals.text_cursor.stroke.color = PRIMARY_BRIGHT;
|
||||
|
||||
let widgets = &mut visuals.widgets;
|
||||
for (widget, fill, border, text) in [
|
||||
(&mut widgets.noninteractive, SURFACE, BORDER, SUBTEXT),
|
||||
(&mut widgets.inactive, SURFACE_RAISED, BORDER_STRONG, TEXT),
|
||||
(&mut widgets.hovered, SURFACE_HOVER, BORDER_STRONG, TEXT),
|
||||
(&mut widgets.active, SURFACE_HOVER, PRIMARY, TEXT),
|
||||
(&mut widgets.open, SURFACE_RAISED, PRIMARY, TEXT),
|
||||
] {
|
||||
widget.bg_fill = fill;
|
||||
widget.weak_bg_fill = fill;
|
||||
widget.bg_stroke = Stroke::new(1.0, border);
|
||||
widget.fg_stroke = Stroke::new(1.0, text);
|
||||
widget.corner_radius = corner(RADIUS_SMALL);
|
||||
widget.expansion = 0.0;
|
||||
}
|
||||
ctx.set_visuals(visuals);
|
||||
|
||||
ctx.all_styles_mut(|style| {
|
||||
style.text_styles.insert(TextStyle::Body, font(14.0, medium()));
|
||||
style.text_styles.insert(TextStyle::Button, font(14.0, medium()));
|
||||
style.text_styles.insert(TextStyle::Small, font(12.0, medium()));
|
||||
style.text_styles.insert(TextStyle::Heading, font(22.0, semibold()));
|
||||
style.text_styles.insert(TextStyle::Monospace, font(13.0, mono()));
|
||||
style.spacing.item_spacing = egui::vec2(8.0, 8.0);
|
||||
style.spacing.button_padding = egui::vec2(12.0, 6.0);
|
||||
style.spacing.interact_size = egui::vec2(40.0, 30.0);
|
||||
style.spacing.combo_width = 160.0;
|
||||
style.spacing.scroll.bar_width = 8.0;
|
||||
style.spacing.scroll.floating = true;
|
||||
style.visuals.striped = false;
|
||||
style.interaction.selectable_labels = false;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use anyhow::Result;
|
||||
use std::sync::mpsc::Sender;
|
||||
use tokio::runtime::Handle;
|
||||
use super::{Repaint, Wake};
|
||||
|
||||
const ICON_SIZE: u32 = 32;
|
||||
const ICON_RGBA: &[u8] = include_bytes!("../../assets/icon-32.rgba");
|
||||
|
||||
pub struct Tray { _keep: Box<dyn std::any::Any> }
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Notifier { wake: Sender<Wake>, repaint: Repaint }
|
||||
|
||||
impl Notifier {
|
||||
fn send(&self, wake: Wake) {
|
||||
let _ = self.wake.send(wake);
|
||||
self.repaint.ping();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn start(wake: Sender<Wake>, repaint: Repaint, runtime: &Handle) -> Result<Tray> {
|
||||
use ksni::{menu::{MenuItem, StandardItem}, Icon, ToolTip, TrayMethods};
|
||||
|
||||
struct FrislitTray { notify: Notifier }
|
||||
|
||||
impl ksni::Tray for FrislitTray {
|
||||
fn id(&self) -> String { "frislit".into() }
|
||||
fn title(&self) -> String { "frislit".into() }
|
||||
fn tool_tip(&self) -> ToolTip { ToolTip { title: "frislit".into(), ..Default::default() } }
|
||||
fn icon_pixmap(&self) -> Vec<Icon> {
|
||||
let mut data = Vec::with_capacity(ICON_RGBA.len());
|
||||
for pixel in ICON_RGBA.chunks(4) { data.extend_from_slice(&[pixel[3], pixel[0], pixel[1], pixel[2]]); }
|
||||
vec![Icon { width: ICON_SIZE as i32, height: ICON_SIZE as i32, data }]
|
||||
}
|
||||
fn activate(&mut self, _x: i32, _y: i32) { self.notify.send(Wake::Toggle); }
|
||||
fn menu(&self) -> Vec<MenuItem<Self>> {
|
||||
vec![
|
||||
StandardItem { label: "Open frislit".into(), activate: Box::new(|tray: &mut Self| tray.notify.send(Wake::Show)), ..Default::default() }.into(),
|
||||
MenuItem::Separator,
|
||||
StandardItem { label: "Quit".into(), activate: Box::new(|tray: &mut Self| tray.notify.send(Wake::Quit)), ..Default::default() }.into(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
let tray = FrislitTray { notify: Notifier { wake, repaint } };
|
||||
let handle = runtime.block_on(tray.spawn()).map_err(|err| anyhow::anyhow!("No tray available: {err}"))?;
|
||||
Ok(Tray { _keep: Box::new(handle) })
|
||||
}
|
||||
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
pub fn start(wake: Sender<Wake>, repaint: Repaint, _runtime: &Handle) -> Result<Tray> {
|
||||
use tray_icon::{menu::{Menu, MenuEvent, MenuItem, PredefinedMenuItem}, Icon, MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
|
||||
|
||||
let notify = Notifier { wake, repaint };
|
||||
|
||||
let menu = Menu::new();
|
||||
let open = MenuItem::new("Open frislit", true, None);
|
||||
let quit = MenuItem::new("Quit", true, None);
|
||||
menu.append_items(&[&open, &PredefinedMenuItem::separator(), &quit])?;
|
||||
let (open_id, quit_id) = (open.id().clone(), quit.id().clone());
|
||||
|
||||
let icon = Icon::from_rgba(ICON_RGBA.to_vec(), ICON_SIZE, ICON_SIZE)?;
|
||||
let tray = TrayIconBuilder::new()
|
||||
.with_menu(Box::new(menu))
|
||||
.with_tooltip("frislit")
|
||||
.with_icon(icon)
|
||||
.with_icon_as_template(cfg!(target_os = "macos"))
|
||||
.with_menu_on_left_click(false)
|
||||
.build()?;
|
||||
|
||||
let clicks = notify.clone();
|
||||
TrayIconEvent::set_event_handler(Some(move |event: TrayIconEvent| {
|
||||
if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event {
|
||||
clicks.send(Wake::Toggle);
|
||||
}
|
||||
}));
|
||||
MenuEvent::set_event_handler(Some(move |event: MenuEvent| {
|
||||
if *event.id() == open_id { notify.send(Wake::Show); }
|
||||
else if *event.id() == quit_id { notify.send(Wake::Quit); }
|
||||
}));
|
||||
Ok(Tray { _keep: Box::new(tray) })
|
||||
}
|
||||
|
||||
#[cfg(not(any(windows, target_os = "macos", target_os = "linux")))]
|
||||
pub fn start(_wake: Sender<Wake>, _repaint: Repaint, _runtime: &Handle) -> Result<Tray> {
|
||||
anyhow::bail!("No tray on this platform")
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
|
||||
use eframe::egui::{self, Align, Color32, CursorIcon, Frame, Id, Layout, Margin, Response, RichText, Sense, Stroke, StrokeKind, TextEdit, Ui, Vec2};
|
||||
use std::time::Instant;
|
||||
use super::theme::{self, corner};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub enum ButtonKind { Primary, Secondary, Ghost, Danger }
|
||||
|
||||
pub fn button(ui: &mut Ui, text: &str, kind: ButtonKind) -> Response {
|
||||
button_sized(ui, text, kind, 0.0)
|
||||
}
|
||||
|
||||
pub fn button_sized(ui: &mut Ui, text: &str, kind: ButtonKind, min_width: f32) -> Response {
|
||||
let family = if kind == ButtonKind::Primary { theme::semibold() } else { theme::medium() };
|
||||
let galley = ui.painter().layout_no_wrap(text.to_string(), theme::font(14.0, family), Color32::WHITE);
|
||||
let padding = egui::vec2(16.0, 7.0);
|
||||
let size = Vec2::new((galley.size().x + padding.x * 2.0).max(min_width), (galley.size().y + padding.y * 2.0).max(34.0));
|
||||
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
|
||||
if !ui.is_rect_visible(rect) { return response; }
|
||||
|
||||
let enabled = ui.is_enabled();
|
||||
let hovered = response.hovered() && enabled;
|
||||
let (fill, stroke, color) = match kind {
|
||||
ButtonKind::Primary => (if hovered { theme::PRIMARY_HOVER } else { theme::PRIMARY_BRIGHT }, Stroke::NONE, theme::ON_PRIMARY),
|
||||
ButtonKind::Secondary => (if hovered { theme::SURFACE_HOVER } else { Color32::TRANSPARENT }, Stroke::new(1.0, theme::BORDER_STRONG), theme::TEXT),
|
||||
ButtonKind::Ghost => (if hovered { theme::SURFACE_HOVER } else { Color32::TRANSPARENT }, Stroke::NONE, if hovered { theme::TEXT } else { theme::SUBTEXT }),
|
||||
ButtonKind::Danger => if hovered { (theme::ERROR_TINT, Stroke::NONE, theme::ERROR) } else { (Color32::TRANSPARENT, Stroke::new(1.0, theme::BORDER_STRONG), theme::SUBTEXT) },
|
||||
};
|
||||
let (fill, color) = if enabled { (fill, color) } else if kind == ButtonKind::Primary { (theme::SURFACE_HOVER, theme::MUTED) } else { (fill, theme::MUTED) };
|
||||
|
||||
let painter = ui.painter();
|
||||
painter.rect(rect, corner(theme::RADIUS_INPUT), fill, stroke, StrokeKind::Inside);
|
||||
let text_pos = rect.center() - galley.size() / 2.0;
|
||||
painter.galley(text_pos, galley, color);
|
||||
if hovered { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
|
||||
response
|
||||
}
|
||||
|
||||
pub fn text(ui: &mut Ui, value: impl Into<String>, size: f32, color: Color32) -> Response {
|
||||
ui.label(RichText::new(value).size(size).color(color))
|
||||
}
|
||||
|
||||
pub fn text_family(ui: &mut Ui, value: impl Into<String>, size: f32, color: Color32, family: egui::FontFamily) -> Response {
|
||||
ui.label(RichText::new(value).size(size).color(color).family(family))
|
||||
}
|
||||
|
||||
pub fn mono(ui: &mut Ui, value: impl Into<String>, size: f32, color: Color32) -> Response {
|
||||
ui.label(RichText::new(value).size(size).color(color).family(theme::mono()))
|
||||
}
|
||||
|
||||
pub fn heading(ui: &mut Ui, value: &str) {
|
||||
text_family(ui, value, 24.0, theme::TEXT, theme::semibold());
|
||||
}
|
||||
|
||||
pub fn field_label(ui: &mut Ui, label: &str) {
|
||||
text(ui, label, 13.0, theme::SUBTEXT);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct FieldOptions<'a> {
|
||||
pub label: Option<&'a str>,
|
||||
pub hint: &'a str,
|
||||
pub mono: bool,
|
||||
pub secret: bool,
|
||||
pub width: Option<f32>,
|
||||
}
|
||||
|
||||
pub fn field(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &mut String, options: FieldOptions) -> Response {
|
||||
let id = Id::new(id);
|
||||
let edit_id = id.with("edit");
|
||||
let focused = ui.memory(|memory| memory.has_focus(edit_id));
|
||||
let width = options.width.unwrap_or_else(|| ui.available_width());
|
||||
|
||||
ui.vertical(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 6.0;
|
||||
if let Some(label) = options.label { field_label(ui, label); }
|
||||
ui.set_width(width);
|
||||
let frame = Frame::new()
|
||||
.fill(theme::SURFACE)
|
||||
.stroke(Stroke::new(1.0, if focused { theme::PRIMARY } else { theme::BORDER }))
|
||||
.corner_radius(corner(theme::RADIUS_INPUT))
|
||||
.inner_margin(Margin::symmetric(14, 9));
|
||||
let inner = frame.show(ui, |ui| {
|
||||
let family = if options.mono { theme::mono() } else { theme::medium() };
|
||||
let mut edit = TextEdit::singleline(value)
|
||||
.id(edit_id)
|
||||
.frame(Frame::NONE)
|
||||
.background_color(Color32::TRANSPARENT)
|
||||
.font(theme::font(15.0, family))
|
||||
.text_color(theme::TEXT)
|
||||
.hint_text(RichText::new(options.hint).color(theme::MUTED).size(15.0))
|
||||
.desired_width(f32::INFINITY)
|
||||
.margin(Margin::ZERO);
|
||||
if options.secret { edit = edit.password(true); }
|
||||
ui.add(edit)
|
||||
});
|
||||
let response = inner.inner;
|
||||
if inner.response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::Text); }
|
||||
if inner.response.clicked() { ui.memory_mut(|memory| memory.request_focus(edit_id)); }
|
||||
response
|
||||
}).inner
|
||||
}
|
||||
|
||||
pub fn dot(ui: &mut Ui, color: Color32) {
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(8.0, 8.0), Sense::hover());
|
||||
ui.painter().circle_filled(rect.center(), 3.5, color);
|
||||
}
|
||||
|
||||
pub fn card<R>(ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse<R> {
|
||||
Frame::new()
|
||||
.fill(theme::SURFACE)
|
||||
.stroke(Stroke::new(1.0, theme::BORDER))
|
||||
.corner_radius(corner(theme::RADIUS_CARD))
|
||||
.inner_margin(Margin::same(18))
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
add(ui)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn clickable_card(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, add: impl FnOnce(&mut Ui)) -> Response {
|
||||
let id = Id::new(id);
|
||||
let hovered = ui.ctx().read_response(id).is_some_and(|response| response.hovered());
|
||||
let fill = if hovered { theme::SURFACE_HOVER } else { theme::SURFACE };
|
||||
let frame = Frame::new()
|
||||
.fill(fill)
|
||||
.stroke(Stroke::new(1.0, if hovered { theme::BORDER_STRONG } else { theme::BORDER }))
|
||||
.corner_radius(corner(theme::RADIUS_CARD))
|
||||
.inner_margin(Margin::symmetric(18, 14));
|
||||
let inner = frame.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal(|ui| add(ui));
|
||||
});
|
||||
let response = ui.interact(inner.response.rect, id, Sense::click());
|
||||
if response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
|
||||
response
|
||||
}
|
||||
|
||||
pub fn section(ui: &mut Ui, title: &str, hint: Option<&str>) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 10.0;
|
||||
text_family(ui, title, 16.0, theme::TEXT, theme::semibold());
|
||||
if let Some(hint) = hint { text(ui, hint, 13.0, theme::MUTED); }
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
|
||||
pub fn toggle(ui: &mut Ui, on: &mut bool) -> Response {
|
||||
let size = egui::vec2(36.0, 20.0);
|
||||
let (rect, mut response) = ui.allocate_exact_size(size, Sense::click());
|
||||
if response.clicked() { *on = !*on; response.mark_changed(); }
|
||||
let how_on = ui.ctx().animate_bool(response.id, *on);
|
||||
let fill = if *on { theme::PRIMARY } else { theme::SURFACE_HOVER };
|
||||
let stroke = if *on { Stroke::NONE } else { Stroke::new(1.0, theme::BORDER_STRONG) };
|
||||
ui.painter().rect(rect, corner(10), fill, stroke, StrokeKind::Inside);
|
||||
let radius = 7.0;
|
||||
let x = egui::lerp((rect.left() + radius + 3.0)..=(rect.right() - radius - 3.0), how_on);
|
||||
ui.painter().circle_filled(egui::pos2(x, rect.center().y), radius, if *on { theme::ON_PRIMARY } else { theme::SUBTEXT });
|
||||
if response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
|
||||
response
|
||||
}
|
||||
|
||||
pub fn status_color(status: u16) -> Color32 {
|
||||
match status {
|
||||
200..=299 => theme::SUCCESS,
|
||||
300..=399 => theme::PRIMARY,
|
||||
400..=499 => theme::WARNING,
|
||||
_ => theme::ERROR,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn toggle_row(ui: &mut Ui, label: &str, hint: &str, on: &mut bool) -> Response {
|
||||
ui.horizontal(|ui| {
|
||||
let text_width = ui.available_width() - 52.0;
|
||||
ui.vertical(|ui| {
|
||||
ui.set_max_width(text_width);
|
||||
ui.spacing_mut().item_spacing.y = 2.0;
|
||||
text(ui, label, 14.0, theme::TEXT);
|
||||
if !hint.is_empty() { ui.add(egui::Label::new(RichText::new(hint).size(12.5).color(theme::MUTED)).wrap()); }
|
||||
});
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| toggle(ui, on)).inner
|
||||
}).inner
|
||||
}
|
||||
|
||||
pub fn copy_row(ui: &mut Ui, id: impl std::hash::Hash + std::fmt::Debug, value: &str, copied_at: &mut Option<Instant>) -> bool {
|
||||
let mut copied = false;
|
||||
let frame = Frame::new()
|
||||
.fill(theme::SURFACE)
|
||||
.stroke(Stroke::new(1.0, theme::BORDER))
|
||||
.corner_radius(corner(theme::RADIUS_SMALL))
|
||||
.inner_margin(Margin::symmetric(12, 6));
|
||||
frame.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal(|ui| {
|
||||
let recently = copied_at.is_some_and(|at| at.elapsed().as_secs_f32() < 1.6);
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
let label = if recently { "Copied" } else { "Copy" };
|
||||
let response = ui.push_id(Id::new(&id).with("copy"), |ui| button(ui, label, ButtonKind::Ghost)).inner;
|
||||
if response.clicked() {
|
||||
ui.ctx().copy_text(value.to_string());
|
||||
*copied_at = Some(Instant::now());
|
||||
copied = true;
|
||||
}
|
||||
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(RichText::new(value).size(13.0).color(theme::SUBTEXT).family(theme::mono())).truncate());
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
copied
|
||||
}
|
||||
|
||||
pub fn notice(ui: &mut Ui, message: &str, color: Color32, tint: Color32) {
|
||||
Frame::new()
|
||||
.fill(tint)
|
||||
.corner_radius(corner(theme::RADIUS_SMALL))
|
||||
.inner_margin(Margin::symmetric(14, 10))
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.add(egui::Label::new(RichText::new(message).size(13.5).color(color)).wrap());
|
||||
});
|
||||
}
|
||||
|
||||
pub fn error_notice(ui: &mut Ui, message: &str) { notice(ui, message, theme::ERROR, theme::ERROR_TINT); }
|
||||
pub fn warning_notice(ui: &mut Ui, message: &str) { notice(ui, message, theme::WARNING, theme::WARNING_TINT); }
|
||||
|
||||
pub fn empty_state(ui: &mut Ui, title: &str, body: &str, add: impl FnOnce(&mut Ui)) {
|
||||
Frame::new()
|
||||
.stroke(Stroke::new(1.0, theme::BORDER_STRONG))
|
||||
.corner_radius(corner(theme::RADIUS_CARD))
|
||||
.inner_margin(Margin::symmetric(32, 40))
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.vertical_centered(|ui| {
|
||||
ui.spacing_mut().item_spacing.y = 8.0;
|
||||
text_family(ui, title, 17.0, theme::TEXT, theme::semibold());
|
||||
ui.add(egui::Label::new(RichText::new(body).size(14.0).color(theme::SUBTEXT)).wrap());
|
||||
ui.add_space(12.0);
|
||||
add(ui);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn segmented<T: PartialEq + Copy>(ui: &mut Ui, current: &mut T, options: &[(T, &str)]) {
|
||||
Frame::new()
|
||||
.fill(theme::SURFACE)
|
||||
.stroke(Stroke::new(1.0, theme::BORDER))
|
||||
.corner_radius(corner(theme::RADIUS_INPUT))
|
||||
.inner_margin(Margin::same(3))
|
||||
.show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 3.0;
|
||||
ui.horizontal(|ui| {
|
||||
for (value, label) in options {
|
||||
let selected = *current == *value;
|
||||
let galley = ui.painter().layout_no_wrap(label.to_string(), theme::font(13.5, theme::medium()), Color32::WHITE);
|
||||
let size = galley.size() + egui::vec2(24.0, 12.0);
|
||||
let (rect, response) = ui.allocate_exact_size(size, Sense::click());
|
||||
let fill = if selected { theme::SURFACE_HOVER } else if response.hovered() { theme::SURFACE_RAISED } else { Color32::TRANSPARENT };
|
||||
let stroke = if selected { Stroke::new(1.0, theme::BORDER_STRONG) } else { Stroke::NONE };
|
||||
ui.painter().rect(rect, corner(theme::RADIUS_SMALL), fill, stroke, StrokeKind::Inside);
|
||||
let color = if selected { theme::TEXT } else { theme::SUBTEXT };
|
||||
ui.painter().galley(rect.center() - galley.size() / 2.0, galley, color);
|
||||
if response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
|
||||
if response.clicked() { *current = *value; }
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn paint_arrow(painter: &egui::Painter, center: egui::Pos2, size: f32, pointing: f32, stroke: Stroke) {
|
||||
let half = size / 2.0;
|
||||
let wing = size * 0.32;
|
||||
let tip = center + egui::vec2(half * pointing, 0.0);
|
||||
painter.line_segment([center - egui::vec2(half * pointing, 0.0), tip], stroke);
|
||||
painter.line_segment([tip, tip + egui::vec2(-wing * pointing, -wing)], stroke);
|
||||
painter.line_segment([tip, tip + egui::vec2(-wing * pointing, wing)], stroke);
|
||||
}
|
||||
|
||||
pub fn arrow_right(ui: &mut Ui, color: Color32) {
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(14.0, 14.0), Sense::hover());
|
||||
paint_arrow(ui.painter(), rect.center(), 10.0, 1.0, Stroke::new(1.4, color));
|
||||
}
|
||||
|
||||
pub fn chevron_right(ui: &mut Ui, color: Color32) {
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(12.0, 14.0), Sense::hover());
|
||||
let center = rect.center();
|
||||
let stroke = Stroke::new(1.5, color);
|
||||
ui.painter().line_segment([center + egui::vec2(-2.0, -4.0), center + egui::vec2(2.0, 0.0)], stroke);
|
||||
ui.painter().line_segment([center + egui::vec2(2.0, 0.0), center + egui::vec2(-2.0, 4.0)], stroke);
|
||||
}
|
||||
|
||||
pub fn back_link(ui: &mut Ui, label: &str) -> Response {
|
||||
let galley = ui.painter().layout_no_wrap(label.to_string(), theme::font(13.0, theme::medium()), Color32::WHITE);
|
||||
let (rect, response) = ui.allocate_exact_size(egui::vec2(galley.size().x + 20.0, galley.size().y.max(14.0)), Sense::click());
|
||||
let color = if response.hovered() { theme::TEXT } else { theme::MUTED };
|
||||
if response.hovered() { ui.ctx().set_cursor_icon(CursorIcon::PointingHand); }
|
||||
paint_arrow(ui.painter(), egui::pos2(rect.left() + 6.0, rect.center().y), 10.0, -1.0, Stroke::new(1.4, color));
|
||||
ui.painter().galley(egui::pos2(rect.left() + 20.0, rect.center().y - galley.size().y / 2.0), galley, color);
|
||||
response
|
||||
}
|
||||
|
||||
pub fn divider(ui: &mut Ui) {
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), 1.0), Sense::hover());
|
||||
ui.painter().rect_filled(rect, 0.0, theme::BORDER);
|
||||
}
|
||||
|
||||
pub fn minimize_button(ui: &mut Ui) -> Response {
|
||||
let (rect, response) = ui.allocate_exact_size(egui::vec2(30.0, 30.0), Sense::click());
|
||||
let hovered = response.hovered();
|
||||
if hovered {
|
||||
ui.painter().rect_filled(rect, corner(theme::RADIUS_SMALL), theme::SURFACE_HOVER);
|
||||
ui.ctx().set_cursor_icon(CursorIcon::PointingHand);
|
||||
}
|
||||
let color = if hovered { theme::TEXT } else { theme::SUBTEXT };
|
||||
let center = rect.center();
|
||||
let arm = 5.0;
|
||||
ui.painter().line_segment([center + egui::vec2(-arm, 0.0), center + egui::vec2(arm, 0.0)], Stroke::new(1.6, color));
|
||||
response
|
||||
}
|
||||
Reference in new issue
Block a user