Adapt mesh views to phone rotation and toggle the exit from Quick Settings

Use the available width for the Android device table, keeping individual
peers expandable and their full details reachable in both orientations.
Show network selection and settings side by side in landscape and reuse
the VIP editor with a compact toolbar and width-aware backend columns.
Retain the selected network, expanded peer, traffic unit and VIP draft
across rotation.

Show data-channel readiness consistently in the tray and on Android.
Distinguish an establishing channel, a disabled data plane, an offline
peer and a transport failure. Use an animated arc for visible waiting
peers. Explain Phosphor controls on hover, focus and long press, and
provide a masked-by-default reveal button in the shared secret field.

Store the last confirmed exit network and endpoint in Android's private
preferences. A Quick Settings tap disconnects that selection or restores
the exact peer through the existing agent. First use opens the chooser.
On a cold start, wait for an authenticated exit offer outside the command
loop. Check the current selection again before changing the route. Only
changed exit offers wake roster subscribers. Wire formats, software
version and mesh identity storage remain compatible.

On macOS arm64, cargo fmt and strict workspace Clippy passed. The locked
workspace suite passed 598 tests with four opt-in tests ignored. Built the
tray, the ARM64 debug APK and its test APK. All three instrumentation tests
passed on an Android API 37 emulator. Opened the chooser from the actual
Quick Settings tile, rotated the activity and inspected rendered device
lists with ready, waiting, failed and offline peers. Physical phones and
native Linux and Windows builds were not exercised.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-25 15:38:10 +02:00
1 parent 50c0ecea45
commit e3e6089d0b
29 files changed
+1688 -324

No files matched your search

+17 -2
View File
@@ -7,7 +7,8 @@
use tsunagi::ipc::{PrivilegeReport, StatusReport};
use crate::client::Snapshot;
use crate::format;
use crate::{format, widgets};
use egui_phosphor::regular as icon;
const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");
const AUTHOR: &str = "AB <tsunagi@hexor.cy>";
@@ -177,7 +178,21 @@ fn grid(ui: &mut egui::Ui, id: &str, add: impl FnOnce(&mut egui::Ui)) {
/// One label/value line of a table.
fn row(ui: &mut egui::Ui, label: &str, value: impl FnOnce(&mut egui::Ui)) {
ui.weak(label);
match label {
"repository" => widgets::field(ui, icon::GITHUB_LOGO, "", "Source code repository"),
"license" => widgets::field(ui, icon::SCALES, "", "Software license"),
"build" => widgets::field(
ui,
icon::CPU,
"Build",
"Platform, architecture and build profile",
),
"version" => widgets::field(ui, icon::TAG, "Version", "Tsunagi Agent software version"),
"endpoint id" => widgets::field(ui, icon::FINGERPRINT, "", "Device endpoint ID"),
_ => {
ui.weak(label);
}
}
value(ui);
ui.end_row();
}
+97 -79
View File
@@ -8,6 +8,7 @@
use std::collections::HashMap;
mod compact;
mod exit_picker;
mod status;
pub use crate::exit::name_of;
pub use exit_picker::choose_exit;
@@ -19,9 +20,9 @@ use crate::client::{Client, Command};
use crate::exit;
use crate::format;
use crate::stats::{Traffic, Unit};
use crate::widgets;
/// A device that works but not as well as it could: reached through others,
/// or with a name somebody else holds.
/// A hostname that another peer already holds.
const AMBER: egui::Color32 = egui::Color32::from_rgb(0xd9, 0xa4, 0x2c);
/// A readable title for a network's window.
@@ -121,6 +122,9 @@ fn short_id(id: &str) -> String {
/// Clicking either copies its own full value.
fn name_cell(ui: &mut egui::Ui, device: &Device<'_>) {
ui.spacing_mut().item_spacing.x = 4.0;
let (rect, r) = ui.allocate_exact_size(egui::Vec2::splat(16.), egui::Sense::click());
device.channel().paint(ui, rect);
widgets::hint(r, device.channel_hint());
match (device.hostname, &device.copy) {
(Some(hostname), Some(copy)) => {
format::copy_field(ui, hostname, copy);
@@ -134,10 +138,14 @@ fn name_cell(ui: &mut egui::Ui, device: &Device<'_>) {
device.agent_version.unwrap_or("version unknown")
));
if let Some((name, holder)) = &device.name_taken {
ui.label(egui::RichText::new(egui_phosphor::regular::WARNING).color(AMBER))
.on_hover_text(format!(
"Name `{name}` belongs to {holder}. Use this device's address."
));
let warning = ui.add(
egui::Label::new(egui::RichText::new(icon::WARNING).color(AMBER))
.sense(egui::Sense::click()),
);
widgets::hint(
warning,
&format!("Name `{name}` belongs to {holder}. Use this device's address."),
);
}
}
@@ -154,11 +162,16 @@ pub fn show(
let (confirm, forget_confirm) = confirmations;
egui::CentralPanel::default().show(ctx, |ui| {
ui.horizontal(|ui| {
ui.heading(&network.name);
// Reserve the unit switch even when a network name fills the viewport.
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.selectable_value(unit, Unit::Bytes, "bytes");
ui.selectable_value(unit, Unit::Packets, "pkts");
ui.label("show:");
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
ui.add(
egui::Label::new(egui::RichText::new(&network.name).heading()).truncate(),
);
});
});
});
// A copy of the chosen unit for the read-only rendering below.
@@ -169,7 +182,13 @@ pub fn show(
.auto_shrink([false, false])
.show(ui, |ui| {
ui.collapsing("Network details", |ui| summary(ui, network));
format::sparkline(ui, traffic.network(&network.network_id), unit, 34.0);
if widgets::landscape(ctx) {
ui.collapsing("Network traffic", |ui| {
format::sparkline(ui, traffic.network(&network.network_id), unit, 34.0)
});
} else {
format::sparkline(ui, traffic.network(&network.network_id), unit, 34.0);
}
compact::roster(
ui,
network,
@@ -345,7 +364,7 @@ fn summary(ui: &mut egui::Ui, network: &NetworkReport) {
.num_columns(2)
.spacing([12.0, 3.0])
.show(ui, |ui| {
ui.weak("id");
widgets::network_id(ui);
let id = if ui.ctx().os() == egui::os::OperatingSystem::Android
|| ui.available_width() < 440.0
{
@@ -356,33 +375,53 @@ fn summary(ui: &mut egui::Ui, network: &NetworkReport) {
format::copy_field(ui, &id, &network.network_id);
ui.end_row();
ui.weak("active");
widgets::field(ui, icon::POWER, "Active", "Network active on this device");
ui.label(yes_no(network.active));
ui.end_row();
ui.weak("broadcast");
widgets::field(
ui,
icon::BROADCAST,
"Broadcast",
"Local broadcast participation",
);
ui.label(yes_no(network.broadcast));
ui.end_row();
if let Some(range) = &network.range {
ui.weak("range");
widgets::range(ui);
format::copy_field(ui, range, range);
ui.end_row();
}
if let Some(address) = network.overlay.as_ref().and_then(|o| o.address.as_ref()) {
ui.weak("this device");
widgets::device_address(ui);
format::copy_field(ui, address, address);
ui.end_row();
}
ui.weak("candidates");
widgets::field(
ui,
icon::MAGNIFYING_GLASS,
"Candidates",
"Unverified discovery candidates",
);
ui.label(network.candidates.to_string());
ui.end_row();
ui.weak("relay fwd/via/recv");
widgets::field(
ui,
icon::FLOW_ARROW,
"Relay fwd / via / recv",
"Datagrams forwarded / sent via relay / received via relay",
);
ui.label(format!(
"{} / {} / {}",
network.relay_forwarded, network.relay_sent_via, network.relay_received_via
));
ui.end_row();
ui.weak("dial/handshake fails");
widgets::field(
ui,
icon::WARNING,
"Dial / handshake failures",
"Failed connection attempts / failed membership handshakes",
);
ui.label(format!(
"{} / {}",
network.dial_failures, network.handshake_failures
@@ -601,9 +640,8 @@ fn exit_cell(
)
.sense(egui::Sense::click()),
)
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text(hint);
if response.clicked() {
.on_hover_cursor(egui::CursorIcon::PointingHand);
if widgets::hint(response, hint).clicked() {
*confirm = Some(ExitConfirm {
network_id: network_id.to_string(),
peer_id: device.id.to_string(),
@@ -655,10 +693,10 @@ fn device_table(
device.version_label(),
if !device.online { " Forget" } else { "" }
);
widths[0] = widths[0].max(measure(name) + 24.0);
let (path, _) = data_path_text(device.path, device.via_name.as_deref(), device.online);
widths[0] = widths[0].max(measure(name) + 44.0);
let path = data_path_text(device.path, device.via_name.as_deref(), device.online);
for (column, text) in [
(2, "waiting".to_owned()),
(2, device.channel().label().to_owned()),
(3, rtt_pair(device)),
(4, device.address.clone().unwrap_or_default()),
(5, path),
@@ -781,71 +819,51 @@ fn rtt_pair(device: &Device<'_>) -> String {
}
fn tunnel_cell(ui: &mut egui::Ui, device: &Device<'_>) {
let ready = device.overlay.is_some_and(|peer| peer.is_up())
&& !matches!(device.path, None | Some(DataPathReport::None));
let text = if !device.online {
"—"
} else if ready {
"ready"
} else {
"waiting"
};
let error = device.data_error.unwrap_or({
if ready {
"Encrypted data channel ready"
} else {
"Encrypted data channel is not ready"
}
});
ui.label(text).on_hover_text(error);
let state = device.channel();
let r = ui.add(
egui::Label::new(egui::RichText::new(state.label()).color(state.color(ui)))
.sense(egui::Sense::click()),
);
widgets::hint(r, device.channel_hint());
}
/// Compact route label and whether that route is the preferred direct form.
/// Compact route label for either client.
/// The icon font is embedded by egui-phosphor and installed in `App::new`.
fn data_path_text(
path: Option<&DataPathReport>,
via_name: Option<&str>,
online: bool,
) -> (String, bool) {
fn data_path_text(path: Option<&DataPathReport>, via_name: Option<&str>, online: bool) -> String {
if !online {
return ("offline".into(), false);
return "offline".into();
}
match path {
Some(DataPathReport::Direct { transport }) => (format!("{} {transport}", icon::LINK), true),
Some(DataPathReport::Relayed { hops, .. }) => (
format!(
"{} {} · {hops} hops",
icon::SHARE_NETWORK,
via_name.unwrap_or("another device")
),
false,
Some(DataPathReport::Direct { transport }) => format!("{} {transport}", icon::LINK),
Some(DataPathReport::Relayed { hops, .. }) => format!(
"{} {} · {hops} hops",
icon::SHARE_NETWORK,
via_name.unwrap_or("another device")
),
Some(DataPathReport::None) | None => ("no data path yet".into(), false),
Some(DataPathReport::None) | None => "no data path yet".into(),
}
}
/// How a device is reached right now.
///
/// A device reached through others is online, over a longer path, and says
/// so: the colour is the only difference in how it is treated.
fn data_path_cell(ui: &mut egui::Ui, device: &Device<'_>) {
let (text, good) = data_path_text(device.path, device.via_name.as_deref(), device.online);
let response = if good {
ui.add(egui::Label::new(text).wrap_mode(egui::TextWrapMode::Extend))
} else {
ui.add(
egui::Label::new(egui::RichText::new(text).color(AMBER))
.wrap_mode(egui::TextWrapMode::Extend),
)
};
response.on_hover_text(match device.path {
Some(DataPathReport::Direct { .. }) => device
.data_transport_detail
.unwrap_or("Direct link to this member."),
Some(DataPathReport::Relayed { .. }) => "Traffic forwarded through another device.",
_ if device.online => "Control connected; data transport unavailable.",
_ => "Unreachable.",
});
let text = data_path_text(device.path, device.via_name.as_deref(), device.online);
let mut text = egui::RichText::new(text);
if !device.online {
text = text.weak();
}
let response = ui.add(egui::Label::new(text).extend().sense(egui::Sense::click()));
widgets::hint(
response,
match device.path {
Some(DataPathReport::Direct { .. }) => device
.data_transport_detail
.unwrap_or("Direct link to this member."),
Some(DataPathReport::Relayed { .. }) => "Traffic forwarded through another device.",
_ if device.online => "Control connected; data transport unavailable.",
_ => "Unreachable.",
},
);
}
fn forget_button(
@@ -1093,7 +1111,7 @@ mod tests {
None,
true,
),
(format!("{} tcp-tls", icon::LINK), true)
format!("{} tcp-tls", icon::LINK)
);
}
@@ -1109,13 +1127,13 @@ mod tests {
Some("iris"),
true,
),
(format!("{} iris · 2 hops", icon::SHARE_NETWORK), false)
format!("{} iris · 2 hops", icon::SHARE_NETWORK)
);
assert_eq!(
data_path_text(Some(&DataPathReport::None), None, true),
("no data path yet".into(), false)
"no data path yet"
);
assert_eq!(data_path_text(None, None, false), ("offline".into(), false));
assert_eq!(data_path_text(None, None, false), "offline");
}
#[test]
@@ -1465,7 +1483,7 @@ mod tests {
};
let rows = devices(&network, "own");
let far = rows.iter().find(|device| device.id == "far").unwrap();
let (label, _) = data_path_text(far.path, far.via_name.as_deref(), far.online);
let label = data_path_text(far.path, far.via_name.as_deref(), far.online);
let context = egui::Context::default();
let mut fonts = egui::FontDefinitions::default();
egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular);
+204 -66
View File
@@ -1,11 +1,99 @@
//! One line per member and one expanded detail block, with no horizontal scroller.
//! A width-constrained device table for touch. Optional columns move into the
//! expanded row before any essential columns run out of space.
use super::{
AMBER, Device, ExitConfirm, ForgetConfirm, NetworkReport, Traffic, Unit, data_path_text,
devices, exit, forget_button, format, icon, rtt_text, tunnel_cell,
devices, exit, forget_button, format, icon, rtt_text, traffic_pair, tunnel_cell,
};
use crate::widgets;
use egui::{Align2, Color32, FontId, Rect, Sense, Ui, Vec2, pos2, vec2};
#[derive(Clone, Copy)]
enum Column {
Device,
State,
Address,
Rtt,
Traffic,
Version,
Path,
Plot,
}
impl Column {
fn title(self, unit: Unit) -> &'static str {
match self {
Self::Device => "device",
Self::State => "State",
Self::Address => "IPv4",
Self::Rtt => "Data RTT",
Self::Traffic if unit == Unit::Bytes => "bytes (TX / RX)",
Self::Traffic => "pkts (TX / RX)",
Self::Version => "Version",
Self::Path => "Data path",
Self::Plot => "Traffic / s",
}
}
}
fn columns(ui: &Ui, width: f32, landscape: bool, unit: Unit) -> Vec<(Column, f32)> {
let font = egui::TextStyle::Body.resolve(ui.style());
let measure = |s: &str| {
ui.painter()
.layout_no_wrap(s.into(), font.clone(), Color32::WHITE)
.size()
.x
+ 10.
};
let mut cols = vec![(Column::Device, 0.)];
if landscape && width >= 510. {
cols.push((Column::State, measure("Control only").min(width * 0.16)));
}
cols.push((
Column::Address,
measure("255.255.255.255").min(width * if landscape { 0.27 } else { 0.35 }),
));
cols.push((
Column::Rtt,
measure("9999 ms").min(width * if landscape { 0.15 } else { 0.22 }),
));
if landscape {
cols.push((
Column::Traffic,
measure(Column::Traffic.title(unit))
.max(measure("999 MB / 999 MB"))
.min(width * 0.29),
));
let mut spare = width - cols.iter().map(|c| c.1).sum::<f32>() - 122.;
for (column, desire) in [
(Column::Version, measure("v1.0.4-rc.1")),
(Column::Path, measure("tcp-tls direct")),
(Column::Plot, 110.),
] {
if spare < desire {
break;
}
cols.push((column, desire));
spare -= desire;
}
}
let other: f32 = cols.iter().map(|c| c.1).sum();
// Reserve the disclosure arrow at the end, including on small split screens.
cols[0].1 = (width - other - 16.).max(0.);
cols
}
fn text_cell(ui: &Ui, rect: Rect, text: &str, font: &FontId, color: Color32) {
let mut job = egui::text::LayoutJob::simple_singleline(text.into(), font.clone(), color);
job.wrap.max_rows = 1;
job.wrap.max_width = (rect.width() - 3.).max(0.);
job.wrap.break_anywhere = true;
let galley = ui.painter().layout_job(job);
let pos = pos2(rect.left(), rect.center().y - galley.size().y / 2.);
ui.painter_at(rect).galley(pos, galley, color);
}
pub(super) fn roster(
ui: &mut egui::Ui,
ui: &mut Ui,
network: &NetworkReport,
own_id: &str,
traffic: &Traffic,
@@ -15,46 +103,61 @@ pub(super) fn roster(
let members = devices(network, own_id);
let online = members.iter().filter(|m| m.online).count();
ui.strong(format!(
"devices ({} online / {} known)",
online,
"devices ({online} online / {} known)",
members.len()
));
let id = ui.make_persistent_id(("expanded device", &network.network_id));
// An Android rotation changes the surrounding scroll area but not the selected peer.
let id = egui::Id::new(("expanded device", &network.network_id));
let mut selected = ui.data(|d| d.get_temp::<String>(id));
let width = ui.available_width();
let columns = columns(ui, width, widgets::landscape(ui.ctx()), unit);
let font = egui::TextStyle::Body.resolve(ui.style());
let measure = |s: &str| {
ui.painter()
.layout_no_wrap(s.to_owned(), font.clone(), ui.visuals().text_color())
.size()
.x
};
let rtt_x = width - (measure("9999 ms") + 18.0).min(width * 0.25);
let ip_x = rtt_x - (measure("255.255.255.255") + 14.0).min(width * 0.40);
let offsets = [16.0, ip_x, rtt_x];
let size = egui::vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 8.0);
ui.spacing_mut().item_spacing.y = 1.0;
let (header, _) = ui.allocate_exact_size(size, egui::Sense::hover());
for (x, title) in offsets.into_iter().zip(["device", "IPv4", "Data RTT"]) {
ui.painter().text(
header.left_center() + egui::vec2(x, 0.),
egui::Align2::LEFT_CENTER,
title,
font.clone(),
ui.visuals().weak_text_color(),
let size = vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 9.);
ui.spacing_mut().item_spacing.y = 1.;
let (header, _) = ui.allocate_exact_size(size, Sense::hover());
let mut x = header.left();
for &(column, w) in &columns {
let mut rect = Rect::from_min_size(pos2(x, header.top()), vec2(w, size.y));
if matches!(column, Column::Device) {
rect.min.x += 20.;
}
text_cell(
ui,
rect,
column.title(unit),
&font,
ui.visuals().text_color(),
);
x += w;
}
for (index, member) in members.iter().enumerate() {
let (row, _) = ui.allocate_exact_size(size, egui::Sense::hover());
let response = ui.interact(row, id.with(member.id), egui::Sense::click());
if response.clicked() {
let (row, _) = ui.allocate_exact_size(size, Sense::hover());
let response = ui.interact(row, id.with(member.id), Sense::click());
let clicked = response.clicked();
let exit_hint = if member.in_use {
" · Selected internet exit"
} else if member.exit_node {
" · Offers an exit node"
} else {
""
};
let description = format!("{} · {}{exit_hint}", member.name(), member.channel_hint());
response.widget_info(|| {
egui::WidgetInfo::labeled(
egui::WidgetType::SelectableLabel,
response.enabled(),
&description,
)
});
widgets::hint(response, &description);
if clicked {
selected = (selected.as_deref() != Some(member.id)).then(|| member.id.to_owned());
}
let open = selected.as_deref() == Some(member.id);
if open || index % 2 == 0 {
ui.painter().rect_filled(
row,
2.0,
2.,
if open {
ui.visuals().widgets.hovered.weak_bg_fill
} else {
@@ -62,52 +165,88 @@ pub(super) fn roster(
},
);
}
let dot = row.left_center() + egui::vec2(6., 0.);
if member.online {
ui.painter().circle_filled(dot, 3., exit::GOOD);
} else {
ui.painter().circle_stroke(
dot,
3.,
egui::Stroke::new(1.0_f32, ui.visuals().weak_text_color()),
);
}
let name = member.name();
let rtt = rtt_text(member.data_rtt_ms);
let labels = [
name.as_str(),
member.address.as_deref().unwrap_or("—"),
rtt.as_str(),
];
let color = if member.online {
let channel = member.channel();
let normal = if member.online {
ui.visuals().text_color()
} else {
ui.visuals().weak_text_color()
channel.color(ui)
};
for ((x, end), label) in offsets
.into_iter()
.zip([ip_x, rtt_x, width - 13.0])
.zip(labels)
{
let mut job =
egui::text::LayoutJob::simple_singleline(label.into(), font.clone(), color);
job.wrap.max_rows = 1;
job.wrap.max_width = (end - x - 4.0).max(0.0);
job.wrap.break_anywhere = true;
let galley = ui.painter().layout_job(job);
let origin = row.left_center() + egui::vec2(x, -galley.size().y * 0.5);
ui.painter().galley(origin, galley, color);
let mut x = row.left();
for &(column, w) in &columns {
let mut rect = Rect::from_min_size(pos2(x, row.top()), vec2(w, row.height()));
x += w;
let text = match column {
Column::Device => {
channel.paint(
ui,
Rect::from_center_size(rect.left_center() + vec2(9., 0.), Vec2::splat(16.)),
);
rect.min.x += 20.;
if member.in_use || member.exit_node {
ui.painter_at(rect).text(
rect.left_center(),
Align2::LEFT_CENTER,
icon::SIGN_OUT,
font.clone(),
if member.in_use { exit::GOOD } else { normal },
);
rect.min.x += font.size + 3.;
}
member.name()
}
Column::State => channel.label().into(),
Column::Address => member.address.as_deref().unwrap_or("—").into(),
Column::Rtt => rtt_text(member.data_rtt_ms),
Column::Version => member.version_label(),
Column::Path => {
data_path_text(member.path, member.via_name.as_deref(), member.online)
}
Column::Traffic => member.overlay.filter(|_| member.online).map_or_else(
|| "—".into(),
|peer| {
let (tx, rx) = unit.counters(peer);
traffic_pair(tx, rx, unit)
},
),
Column::Plot => {
if let Some(peer) = member.overlay.filter(|_| member.online) {
let mut plot = ui.new_child(
egui::UiBuilder::new()
.max_rect(rect.shrink2(vec2(2., 2.)))
.layout(egui::Layout::top_down(egui::Align::Min)),
);
format::sparkline(
&mut plot,
traffic.peer(&network.network_id, &peer.public_key),
unit,
rect.height() - 4.,
);
}
continue;
}
};
text_cell(
ui,
rect,
&text,
&font,
if matches!(column, Column::State) {
channel.color(ui)
} else {
normal
},
);
}
ui.painter().text(
row.right_center(),
egui::Align2::RIGHT_CENTER,
Align2::RIGHT_CENTER,
if open {
icon::CARET_DOWN
} else {
icon::CARET_RIGHT
},
font.clone(),
ui.visuals().weak_text_color(),
ui.visuals().text_color(),
);
if open {
ui.push_id(member.id, |ui| {
@@ -138,8 +277,7 @@ fn details(
ui.spacing_mut().item_spacing.y = 4.0;
ui.columns(2, |cols| {
cols[0].small("Data path");
let (path, _) =
data_path_text(member.path, member.via_name.as_deref(), member.online);
let path = data_path_text(member.path, member.via_name.as_deref(), member.online);
cols[0].horizontal_wrapped(|ui| {
ui.label(path);
if member.online {
@@ -204,7 +342,7 @@ fn details(
format::copy_field(ui, name, name);
}
if let Some(error) = member.data_error {
ui.colored_label(AMBER, error);
ui.colored_label(member.channel().color(ui), error);
}
if let Some((taken, holder)) = &member.name_taken {
ui.colored_label(AMBER, format!("Name {taken} belongs to {holder}."));
+98
View File
@@ -0,0 +1,98 @@
use super::{DataPathReport, Device, icon};
use tsunagi::agent::{DATA_CONNECTING, DATA_DISABLED};
#[derive(Copy, Clone, PartialEq, Eq)]
pub(super) enum Channel {
Ready,
Waiting,
Error,
Offline,
Disabled,
}
impl Device<'_> {
pub(super) fn channel(&self) -> Channel {
if !self.online {
return Channel::Offline;
}
match self.data_error {
Some(DATA_DISABLED) => Channel::Disabled,
Some(DATA_CONNECTING) => Channel::Waiting,
Some(_) => Channel::Error,
None if self.overlay.is_some_and(|p| p.is_up())
&& !matches!(self.path, None | Some(DataPathReport::None)) =>
{
Channel::Ready
}
None => Channel::Waiting,
}
}
pub(super) fn channel_hint(&self) -> &str {
match self.channel() {
Channel::Offline => "Offline · peer unreachable",
Channel::Ready => "Ready · encrypted data channel available",
Channel::Waiting => "Waiting for the encrypted data channel",
Channel::Disabled => "Control only · data transports disabled locally",
Channel::Error => self.data_error.unwrap_or("Data channel error"),
}
}
}
impl Channel {
pub(super) fn label(self) -> &'static str {
match self {
Self::Ready => "Ready",
Self::Waiting => "Waiting",
Self::Error => "Error",
Self::Offline => "Offline",
Self::Disabled => "Control only",
}
}
pub(super) fn color(self, ui: &egui::Ui) -> egui::Color32 {
use egui::Color32;
match (self, ui.visuals().dark_mode) {
(Self::Ready, true) => Color32::from_rgb(100, 210, 136),
(Self::Ready, false) => Color32::from_rgb(25, 120, 61),
(Self::Waiting, true) => Color32::from_rgb(244, 190, 85),
(Self::Waiting, false) => Color32::from_rgb(150, 94, 8),
(Self::Error, true) => Color32::from_rgb(255, 129, 116),
(Self::Error, false) => Color32::from_rgb(179, 52, 44),
(Self::Offline | Self::Disabled, true) => Color32::from_rgb(136, 139, 145),
(Self::Offline | Self::Disabled, false) => Color32::from_rgb(98, 102, 108),
}
}
pub(super) fn paint(self, ui: &egui::Ui, rect: egui::Rect) {
if !ui.is_rect_visible(rect) {
return;
}
let color = self.color(ui);
let glyph = match self {
Self::Ready => icon::CHECK_CIRCLE,
Self::Error => icon::WARNING,
Self::Offline => icon::MINUS_CIRCLE,
Self::Disabled => icon::PAUSE_CIRCLE,
Self::Waiting => {
let start = ui.input(|i| (i.time % 1.2) as f32) * std::f32::consts::TAU / 1.2;
let radius = rect.height() * 0.34;
let points = (0..=12)
.map(|i| {
rect.center()
+ egui::Vec2::angled(start + std::f32::consts::PI * i as f32 / 12.)
* radius
})
.collect();
ui.painter()
.add(egui::Shape::line(points, egui::Stroke::new(1.8_f32, color)));
ui.ctx()
.request_repaint_after(std::time::Duration::from_millis(65));
return;
}
};
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
glyph,
egui::FontId::proportional(rect.height()),
color,
);
}
}
+2 -3
View File
@@ -87,9 +87,8 @@ pub fn copy_field(ui: &mut egui::Ui, display: &str, value: &str) {
};
let response = ui
.add(egui::Label::new(text).sense(egui::Sense::click()))
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text("click to copy");
if response.clicked() {
.on_hover_cursor(egui::CursorIcon::PointingHand);
if crate::widgets::hint(response, "Copy to clipboard").clicked() {
ui.ctx().copy_text(value.to_owned());
ui.memory_mut(|memory| memory.data.insert_temp(id, Instant::now()));
}
+208 -112
View File
@@ -3,6 +3,7 @@ use crate::{
client::{Client, Command},
devices, exit, format,
stats::{Traffic, Unit},
widgets,
};
use egui_phosphor::regular as icon;
use std::collections::BTreeSet;
@@ -20,6 +21,7 @@ pub struct JoinForm {
pub name: String,
/// User-entered network secret.
pub secret: Zeroizing<String>,
revealed: bool,
}
/// Local UI state kept across frames.
@@ -30,6 +32,8 @@ pub struct UiState {
pub unit: Unit,
/// Network details opened during this run, keyed by identity even for namesakes.
expanded_networks: BTreeSet<String>,
/// The network whose settings occupy the detail pane on a landscape phone.
pub selected_network: Option<String>,
/// An in-progress hostname edit (`None` when not editing).
pub host_edit: Option<String>,
/// Network ids whose devices window is open.
@@ -50,6 +54,7 @@ impl Default for UiState {
join: JoinForm::default(),
unit: Unit::Bytes,
expanded_networks: BTreeSet::new(),
selected_network: None,
host_edit: None,
open_devices: BTreeSet::new(),
vip_windows: Default::default(),
@@ -69,21 +74,17 @@ pub fn draw_header(
) {
ui.add_space(4.0);
ui.horizontal(|ui| {
ui.weak("device");
widgets::field(ui, icon::FINGERPRINT, "", "Device endpoint ID");
// Clicking the shortened id copies the full one.
format::copy_field(ui, &format::short(&report.endpoint_id), &report.endpoint_id);
});
ui.horizontal(|ui| {
ui.weak("host");
widgets::field(ui, icon::DESKTOP_TOWER, "", "Device hostname");
match &mut state.host_edit {
None => {
ui.label(&report.hostname);
if ui
.small_button(icon::PENCIL_SIMPLE)
.on_hover_text("rename")
.clicked()
{
if widgets::icon_button(ui, icon::PENCIL_SIMPLE, "Rename this device").clicked() {
state.host_edit = Some(report.hostname.clone());
}
}
@@ -91,11 +92,11 @@ pub fn draw_header(
let response = ui.add(egui::TextEdit::singleline(buffer).desired_width(150.0));
let submit = (response.lost_focus()
&& ui.input(|i| i.key_pressed(egui::Key::Enter)))
|| ui.small_button(icon::CHECK).on_hover_text("save").clicked();
|| widgets::icon_button(ui, icon::CHECK, "Save hostname").clicked();
if submit {
agent.send(Command::SetHostname(buffer.trim().to_string()));
state.host_edit = None;
} else if ui.small_button(icon::X).on_hover_text("cancel").clicked() {
} else if widgets::icon_button(ui, icon::X, "Cancel hostname edit").clicked() {
state.host_edit = None;
}
}
@@ -128,91 +129,162 @@ pub fn draw_network(
ui.push_id(&network.network_id, |ui| {
egui::Frame::group(ui.style()).show(ui, |ui| {
ui.set_min_width(ui.available_width());
let mut open = state.expanded_networks.contains(&network.network_id);
let status = if network.active {
format!(
"{} online",
devices::online_count(network, &report.endpoint_id)
)
} else {
"Stopped".to_owned()
};
if network_header(ui, &network.name, &status, open).clicked() {
open = !open;
if open {
state.expanded_networks.insert(network.network_id.clone());
} else {
state.expanded_networks.remove(&network.network_id);
}
let open = state.expanded_networks.contains(&network.network_id);
if overview(ui, network, report, state, open) {
state.toggle_network(&network.network_id, !open);
}
if let Some(via) = &network.exit.via {
draw_selected_exit(ui, network, via, state);
if state.expanded_networks.contains(&network.network_id) {
ui.separator();
pick_exit =
draw_network_details(ui, agent, state, traffic, network, report, offer_exit);
}
for warning in exit::warnings(network) {
draw_exit_warning(ui, &warning);
}
if !network.range_conflicts.is_empty() {
ui.colored_label(BAD, "Stopped: overlapping network ranges");
}
if !open {
return;
}
ui.separator();
draw_metadata(ui, network, &report.endpoint_id);
draw_protocols(ui, agent, network, &report.available_protocols);
format::sparkline(ui, traffic.network(&network.network_id), state.unit, 34.0);
pick_exit = network_settings(ui, agent, network, offer_exit);
ui.separator();
ui.horizontal_wrapped(|ui| {
if ui
.button(format!("{} Copy secret", icon::COPY))
.on_hover_text("Copy this network's secret to the clipboard")
.clicked()
{
agent.send(Command::CopySecret {
network_id: network.network_id.clone(),
});
}
if ui.button("Show devices").clicked() {
state.open_devices.insert(network.network_id.clone());
}
if ui.button("VIP").clicked() {
state
.vip_windows
.entry(network.network_id.clone())
.or_default();
}
});
});
});
pick_exit
}
impl UiState {
fn toggle_network(&mut self, id: &str, open: bool) {
if open {
self.expanded_networks.insert(id.to_owned());
self.selected_network = Some(id.to_owned());
} else {
self.expanded_networks.remove(id);
if self.selected_network.as_deref() == Some(id) {
self.selected_network = None;
}
}
}
/// Close the landscape detail pane and fold that card when rotated back.
pub fn close_selection(&mut self) -> bool {
if let Some(id) = self.selected_network.take() {
self.expanded_networks.remove(&id);
return true;
}
false
}
}
fn overview(
ui: &mut egui::Ui,
network: &NetworkReport,
report: &StatusReport,
state: &mut UiState,
open: bool,
) -> bool {
let status = if network.active {
format!(
"{} online",
devices::online_count(network, &report.endpoint_id)
)
} else {
"Stopped".into()
};
let clicked = network_header(ui, &network.name, &status, open).clicked();
if let Some(via) = &network.exit.via {
draw_selected_exit(ui, network, via, state);
}
for warning in exit::warnings(network) {
draw_exit_warning(ui, &warning);
}
if !network.range_conflicts.is_empty() {
ui.colored_label(BAD, "Stopped: overlapping network ranges");
}
clicked
}
/// One network in the landscape selector. Exit status stays visible beside its network.
pub fn draw_network_selector(
ui: &mut egui::Ui,
network: &NetworkReport,
report: &StatusReport,
state: &mut UiState,
) {
let open = state.selected_network.as_deref() == Some(&network.network_id);
ui.push_id(&network.network_id, |ui| {
let mut frame = egui::Frame::group(ui.style());
if open {
frame = frame.stroke(ui.visuals().selection.stroke);
}
frame.show(ui, |ui| {
ui.set_min_width(ui.available_width());
if overview(ui, network, report, state, open) {
state.toggle_network(&network.network_id, !open);
}
});
});
}
/// Actions and settings shared by a folded card and the landscape detail pane.
pub fn draw_network_details(
ui: &mut egui::Ui,
agent: &dyn Client,
state: &mut UiState,
traffic: &Traffic,
network: &NetworkReport,
report: &StatusReport,
offer_exit: bool,
) -> bool {
ui.horizontal_wrapped(|ui| {
if ui
.button(format!("{} Copy secret", icon::COPY))
.on_hover_text("Copy this network's secret to the clipboard")
.clicked()
{
agent.send(Command::CopySecret {
network_id: network.network_id.clone(),
});
}
if ui.button("Show devices").clicked() {
state.open_devices.insert(network.network_id.clone());
}
if widgets::hint(
ui.button(format!("{} VIP", icon::NETWORK)),
"Manage virtual IP services",
)
.clicked()
{
state
.vip_windows
.entry(network.network_id.clone())
.or_default();
}
});
ui.separator();
draw_metadata(ui, network, &report.endpoint_id);
draw_protocols(ui, agent, network, &report.available_protocols);
format::sparkline(ui, traffic.network(&network.network_id), state.unit, 34.0);
network_settings(ui, agent, network, offer_exit)
}
fn draw_metadata(ui: &mut egui::Ui, network: &NetworkReport, own_id: &str) {
egui::Grid::new(ui.id().with("metadata"))
.num_columns(2)
.spacing([10.0, 3.0])
.show(ui, |ui| {
ui.weak("name");
widgets::field(ui, icon::TAG, "", "Network name");
format::copy_field(ui, &network.name, &network.name);
ui.end_row();
ui.weak("id");
widgets::network_id(ui);
format::copy_field(ui, &format::short(&network.network_id), &network.network_id);
ui.end_row();
if let Some(range) = &network.range {
ui.weak("range");
widgets::range(ui);
format::copy_field(ui, range, range);
ui.end_row();
}
if let Some(address) = network.overlay.as_ref().and_then(|o| o.address.as_ref()) {
ui.weak("addr");
widgets::device_address(ui);
format::copy_field(ui, address, address);
ui.end_row();
}
ui.weak("peers");
ui.label(format!("{} known", devices::known_count(network, own_id)));
widgets::field(ui, icon::DEVICES, "", "Online and known peers");
ui.label(format!(
"{} online · {} known",
devices::online_count(network, own_id),
devices::known_count(network, own_id)
));
ui.end_row();
});
}
@@ -339,9 +411,10 @@ fn network_header(ui: &mut egui::Ui, name: &str, status: &str, open: bool) -> eg
title,
visuals.text_color(),
);
response
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text(name)
widgets::hint(
response.on_hover_cursor(egui::CursorIcon::PointingHand),
name,
)
}
fn draw_selected_exit(ui: &mut egui::Ui, network: &NetworkReport, via: &str, state: &mut UiState) {
@@ -352,31 +425,29 @@ fn draw_selected_exit(ui: &mut egui::Ui, network: &NetworkReport, via: &str, sta
exit::LOUD
};
let name = exit::name_of(network, via);
let clicked = ui
.add(egui::Button::new(egui::RichText::new(icon::SIGN_OUT).color(color)).frame(false))
.on_hover_text("Stop using this exit node")
.clicked();
if ui
.link(format!("Exit via {name}"))
.on_hover_text("Stop using this exit node")
.clicked()
let button = ui
.add(egui::Button::new(egui::RichText::new(icon::SIGN_OUT).color(color)).frame(false));
let clicked = widgets::hint(button, "Stop using this exit node").clicked();
if widgets::hint(
ui.link(format!("Exit via {name}")),
"Stop using this exit node",
)
.clicked()
|| clicked
{
state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via));
}
if let Some(t) = network.exit.traffic {
ui.label(format!(
"{} {}",
icon::ARROW_UP,
format::bytes(t.tx_bytes as f64)
))
.on_hover_text("Sent through this exit");
ui.label(format!(
"{} {}",
icon::ARROW_DOWN,
format::bytes(t.rx_bytes as f64)
))
.on_hover_text("Received through this exit");
for (glyph, bytes, hint) in [
(icon::ARROW_UP, t.tx_bytes, "Sent through this exit"),
(icon::ARROW_DOWN, t.rx_bytes, "Received through this exit"),
] {
let text = format!("{glyph} {}", format::bytes(bytes as f64));
widgets::hint(
ui.add(egui::Label::new(text).sense(egui::Sense::click())),
hint,
);
}
}
});
}
@@ -423,21 +494,16 @@ fn draw_protocols(
changed = true;
}
if let Some(index) = selected.iter().position(|p| p == &protocol.name) {
if ui
.add_enabled(index > 0, egui::Button::new(icon::ARROW_UP))
.on_hover_text("prefer earlier")
.clicked()
if widgets::hint(ui.add_enabled(index > 0, egui::Button::new(icon::ARROW_UP)),
"Move transport up in preference order").clicked()
{
selected.swap(index, index - 1);
changed = true;
}
if ui
.add_enabled(
if widgets::hint(ui.add_enabled(
index + 1 < selected.len(),
egui::Button::new(icon::ARROW_DOWN),
)
.on_hover_text("prefer later")
.clicked()
), "Move transport down in preference order").clicked()
{
selected.swap(index, index + 1);
changed = true;
@@ -498,18 +564,47 @@ pub fn draw_join(ui: &mut egui::Ui, agent: &dyn Client, join: &mut JoinForm) {
ui.label("secret");
ui.horizontal(|ui| {
ui.add(
egui::TextEdit::singleline(&mut *join.secret)
.id("join-secret".into())
.desired_width(INPUT_WIDTH - 26.0)
.password(true),
);
if ui
.button(icon::SHUFFLE)
.on_hover_text("Generate a new random secret")
.clicked()
let visuals = ui.visuals().widgets.inactive;
egui::Frame::new()
.fill(ui.visuals().extreme_bg_color)
.stroke(visuals.bg_stroke)
.corner_radius(visuals.corner_radius)
.inner_margin(egui::Margin::symmetric(3, 1))
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
let input = ui.add(
egui::TextEdit::singleline(&mut *join.secret)
.id("join-secret".into())
.frame(false)
.desired_width(INPUT_WIDTH - 65.0)
.password(!join.revealed),
);
let (glyph, label) = if join.revealed {
(icon::EYE_SLASH, "Hide secret")
} else {
(icon::EYE, "Show secret")
};
let eye = ui.add(egui::Button::new(glyph).frame(false));
eye.widget_info(|| {
egui::WidgetInfo::labeled(
egui::WidgetType::Button,
eye.enabled(),
label,
)
});
if widgets::hint(eye, label).clicked() {
join.revealed = !join.revealed;
if input.lost_focus() {
input.request_focus();
}
}
});
});
if widgets::icon_button(ui, icon::SHUFFLE, "Generate a new random secret").clicked()
{
join.secret = tsunagi::identity::NetworkSecret::generate().encode();
join.revealed = false;
}
});
ui.end_row();
@@ -525,5 +620,6 @@ pub fn draw_join(ui: &mut egui::Ui, agent: &dyn Client, join: &mut JoinForm) {
secret: Zeroizing::new(join.secret.trim().to_owned()),
});
join.secret.zeroize();
join.revealed = false;
}
}
+3
View File
@@ -6,10 +6,13 @@ mod exit;
pub mod format;
pub mod home;
pub mod listeners;
#[cfg(test)]
mod presentation_tests;
pub mod stats;
mod table;
pub mod vip;
mod vip_status;
pub mod widgets;
/// Install the Phosphor icons and bold network title face for both egui clients.
pub fn app_fonts() -> egui::FontDefinitions {
+249
View File
@@ -0,0 +1,249 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use crate::{
client::{Client, Command},
devices, home,
stats::{Traffic, Unit},
};
use egui::{Context, Event, FullOutput, Pos2, Rect, Vec2};
use egui_phosphor::regular as icon;
use tsunagi::ipc::{
DataPathReport, MemberReport, NetworkReport, OverlayPeerReport, OverlayReport, PeerReport,
};
#[test]
fn keyboard_focus_explains_an_icon_and_the_shared_font_contains_the_status_glyphs() {
let ctx = Context::default();
ctx.set_fonts(crate::app_fonts());
let draw = |time| {
frame(&ctx, egui::vec2(360., 500.), time, vec![], |ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
let r = crate::widgets::icon_button(ui, icon::EYE, "Show secret");
r.request_focus();
let font = egui::TextStyle::Body.resolve(ui.style());
for glyph in [
icon::EYE,
icon::EYE_SLASH,
icon::NETWORK,
icon::CHECK_CIRCLE,
icon::WARNING,
icon::MINUS_CIRCLE,
icon::PAUSE_CIRCLE,
icon::SIGN_OUT,
icon::FINGERPRINT,
icon::HASH,
icon::TREE_STRUCTURE,
icon::DEVICE_MOBILE,
icon::DEVICES,
icon::BROADCAST,
icon::FLOW_ARROW,
icon::GITHUB_LOGO,
icon::SCALES,
] {
assert!(
ui.fonts(|f| f.has_glyphs(&font, glyph)),
"missing glyph {glyph}"
);
}
});
})
};
draw(0.);
draw(0.1);
assert!(label(&draw(0.2), "Show secret").is_some());
}
struct ReadOnly;
impl Client for ReadOnly {
fn busy(&self) -> bool {
false
}
fn send(&self, _: Command) {
panic!("reading the UI issued a command");
}
}
fn frame(
ctx: &Context,
size: Vec2,
time: f64,
events: Vec<Event>,
draw: impl FnMut(&Context),
) -> FullOutput {
ctx.run(
egui::RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size)),
time: Some(time),
events,
..Default::default()
},
draw,
)
}
fn label(frame: &FullOutput, value: &str) -> Option<Rect> {
frame.shapes.iter().find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == value => Some(t.visual_bounding_rect()),
_ => None,
})
}
fn press(pos: Pos2, pressed: bool) -> Event {
Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
}
}
#[test]
fn secret_eye_masks_by_default_and_long_touch_explains_without_revealing() {
let ctx = Context::default();
ctx.set_fonts(crate::app_fonts());
ctx.set_os(egui::os::OperatingSystem::Android);
let mut form = home::JoinForm::default();
form.secret.push_str("test-only-value");
let mut draw = |time, events| {
frame(&ctx, egui::vec2(360., 720.), time, events, |ctx| {
egui::CentralPanel::default().show(ctx, |ui| home::draw_join(ui, &ReadOnly, &mut form));
})
};
draw(0., vec![]);
let masked = draw(0.1, vec![]);
assert!(label(&masked, "test-only-value").is_none());
let eye = label(&masked, icon::EYE)
.expect("show secret button")
.center();
let touch = |phase| Event::Touch {
device_id: egui::TouchDeviceId(0),
id: egui::TouchId(1),
phase,
pos: eye,
force: None,
};
draw(
0.2,
vec![
touch(egui::TouchPhase::Start),
Event::PointerMoved(eye),
press(eye, true),
],
);
draw(1.2, vec![]);
let held = draw(1.3, vec![]);
assert!(label(&held, "Show secret").is_some());
draw(
1.4,
vec![
touch(egui::TouchPhase::End),
press(eye, false),
Event::PointerGone,
],
);
assert!(label(&draw(1.5, vec![]), "test-only-value").is_none());
for (time, visible) in [(2., true), (3., false)] {
draw(time, vec![Event::PointerMoved(eye), press(eye, true)]);
draw(time + 0.1, vec![press(eye, false)]);
let out = draw(time + 0.2, vec![]);
assert_eq!(label(&out, "test-only-value").is_some(), visible);
assert!(label(&out, if visible { icon::EYE_SLASH } else { icon::EYE }).is_some());
}
}
#[test]
fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_screen() {
let ctx = Context::default();
ctx.set_os(egui::os::OperatingSystem::Android);
ctx.set_fonts(crate::app_fonts());
let mut net = NetworkReport {
name: "lab".into(),
network_id: "network".into(),
..Default::default()
};
for (id, state) in [
("alpha", "ready"),
("bravo", "waiting"),
("charlie", "error"),
("delta", "offline"),
("echo", "control only"),
] {
net.members.push(MemberReport {
endpoint_id: id.into(),
hostname: Some(id.into()),
online: state != "offline",
overlay_address_v4: Some("192.168.254.251".into()),
..Default::default()
});
if state != "offline" {
net.peers.push(PeerReport {
endpoint_id: id.into(),
path: DataPathReport::Relayed {
hops: 2,
via: "another".into(),
},
data_error: match state {
"waiting" => Some(tsunagi::agent::DATA_CONNECTING.into()),
"error" => Some("Carrier unavailable".into()),
"control only" => Some(tsunagi::agent::DATA_DISABLED.into()),
_ => None,
},
agent_version: Some("1.0.4".into()),
..Default::default()
});
}
}
net.overlay = Some(OverlayReport {
peers: vec![OverlayPeerReport {
endpoint_id: "alpha".into(),
handshake_secs_ago: Some(2),
tx_bytes: 2048,
rx_bytes: 512,
..Default::default()
}],
..Default::default()
});
let draw = |size, time, events| {
frame(&ctx, size, time, events, |ctx| {
devices::show(
ctx,
&ReadOnly,
&mut Unit::Bytes,
(&mut None, &mut None),
&net,
"self",
&Traffic::default(),
)
})
};
let portrait = egui::vec2(360., 740.);
draw(portrait, 0., vec![]);
let pos = label(&draw(portrait, 0.1, vec![]), "alpha")
.unwrap()
.center();
draw(
portrait,
0.2,
vec![Event::PointerMoved(pos), press(pos, true)],
);
draw(portrait, 0.3, vec![press(pos, false)]);
for (index, width) in [580., 740., 960.].into_iter().enumerate() {
let size = egui::vec2(width, 360.);
let time = 1. + index as f64;
draw(size, time, vec![]);
let out = draw(size, time + 0.1, vec![]);
for text in [
"bytes (TX / RX)",
"2.0 kB / 512 B",
"Ready",
"Waiting",
"Error",
"Offline",
"Control only",
"Endpoint ID",
] {
let rect = label(&out, text).unwrap_or_else(|| panic!("missing {text} at {width}"));
assert!(
rect.left() >= 0. && rect.right() <= width,
"{text} exceeds {width}: {rect:?}"
);
}
}
assert!(label(&draw(portrait, 4., vec![]), "Endpoint ID").is_some());
}
+21 -6
View File
@@ -93,8 +93,16 @@ pub fn show(
let mut close = state.close_after_save && !state.dirty();
let mut discard_new = false;
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading(format!("VIP · {}", n.name));
ui.weak("Configuration is shared with every member. Changes take effect only after Save.");
let wide = ui.available_width() >= 580.;
ui.horizontal_wrapped(|ui| {
ui.heading(format!("VIP · {}", n.name));
crate::widgets::field(
ui,
egui_phosphor::regular::INFO,
"",
"Configuration is shared with every member. Changes take effect only after Save.",
);
});
if state.close_question {
ui.horizontal_wrapped(|ui| {
ui.label("Unsaved changes.");
@@ -176,7 +184,15 @@ pub fn show(
);
}
let busy = state.pending.is_some();
let tabs = |ui: &mut egui::Ui, configure: &mut bool| {
ui.selectable_value(configure, false, "Overview");
ui.selectable_value(configure, true, "Configuration");
};
ui.horizontal_wrapped(|ui| {
if wide {
tabs(ui, &mut state.configure);
ui.separator();
}
let valid = draft.config.validate(&tsunagi::Limits::default());
if !n.active {
ui.weak("Start the network to save changes.");
@@ -224,10 +240,9 @@ pub fn show(
}
});
ui.separator();
ui.horizontal(|ui| {
ui.selectable_value(&mut state.configure, false, "Overview");
ui.selectable_value(&mut state.configure, true, "Configuration");
});
if !wide {
ui.horizontal(|ui| tabs(ui, &mut state.configure));
}
egui::ScrollArea::vertical()
.auto_shrink([false, false])
.show(ui, |ui| {
+63 -19
View File
@@ -229,12 +229,15 @@ pub(crate) fn show(ui: &mut egui::Ui, v: &VipStatus, n: &NetworkReport, view: &m
ui.separator();
diagram(ui, v, l, n, view);
ui.add_space(6.0);
egui::ScrollArea::horizontal()
.id_salt("backend table scroll")
.auto_shrink([false, true])
.show(ui, |ui| {
backend_table(ui, v, l, n, view);
});
let phone = ui.ctx().os() == egui::os::OperatingSystem::Android;
if phone {
backend_table(ui, v, l, n, view, true);
} else {
egui::ScrollArea::horizontal()
.id_salt("backend table scroll")
.auto_shrink([false, true])
.show(ui, |ui| backend_table(ui, v, l, n, view, false));
}
if let Some(b) = l
.backends
.iter()
@@ -271,6 +274,23 @@ pub(crate) fn show(ui: &mut egui::Ui, v: &VipStatus, n: &NetworkReport, view: &m
format::copy_field(ui, address, address);
}
});
if phone {
let rates = view.backends.get(&key(v, l, &b.backend));
ui.horizontal_wrapped(|ui| {
metric(ui, "TX", &format::bytes(b.counters.tx_bytes as f64));
metric(ui, "RX", &format::bytes(b.counters.rx_bytes as f64));
metric(
ui,
"TX rate",
&format::series_rate(rates.map(|r| &r.tx), view.unit),
);
metric(
ui,
"RX rate",
&format::series_rate(rates.map(|r| &r.rx), view.unit),
);
});
}
});
}
});
@@ -307,6 +327,7 @@ fn backend_table(
l: &ListenerStatus,
n: &NetworkReport,
view: &mut View,
fit: bool,
) {
let headers = [
"Backend",
@@ -365,17 +386,40 @@ fn backend_table(
);
}
}
let widths_id = ui.id().with("backend column widths");
if let Some(previous) = ui.memory(|memory| memory.data.get_temp::<[f32; 8]>(widths_id)) {
for (width, previous) in widths.iter_mut().zip(previous) {
*width = width.max(previous);
let columns: Vec<usize> = if fit {
let mut columns = vec![0, 1, 3];
let free = ui.available_width();
// Keep health and RTT visible even on a portrait phone. Secondary values
// also live in the selected backend's details.
widths[1] = 90.0_f32.min(free * 0.30);
widths[3] = 65.0_f32.min(free * 0.21);
let mut reserved = widths[1] + widths[3] + 2. * table::GAP;
for column in [2, 4, 5, 6, 7] {
let next = reserved + widths[column] + table::GAP;
if free - next < 115. {
break;
}
columns.push(column);
reserved = next;
}
}
ui.memory_mut(|memory| memory.data.insert_temp(widths_id, widths));
let fixed = widths.iter().sum::<f32>() + table::GAP * 7.0;
widths[7] += (ui.available_width() - fixed).max(0.0);
table::row(ui, "backend headers", &widths, false, |column, ui| {
ui.weak(headers[column]);
widths[0] = (free - reserved).max(0.);
columns.sort_unstable();
columns
} else {
let widths_id = ui.id().with("backend column widths");
if let Some(previous) = ui.memory(|memory| memory.data.get_temp::<[f32; 8]>(widths_id)) {
for (width, previous) in widths.iter_mut().zip(previous) {
*width = width.max(previous);
}
}
ui.memory_mut(|memory| memory.data.insert_temp(widths_id, widths));
let fixed = widths.iter().sum::<f32>() + table::GAP * 7.0;
widths[7] += (ui.available_width() - fixed).max(0.0);
(0..widths.len()).collect()
};
let visible: Vec<_> = columns.iter().map(|&i| widths[i]).collect();
table::row(ui, "backend headers", &visible, false, |column, ui| {
ui.weak(headers[columns[column]]);
});
for (index, b) in l.backends.iter().enumerate() {
let key = key(v, l, &b.backend);
@@ -383,9 +427,9 @@ fn backend_table(
table::row(
ui,
&key,
&widths,
&visible,
index % 2 == 0,
|column, ui| match column {
|column, ui| match columns[column] {
0 => {
if ui
.selectable_label(view.selected.as_ref() == Some(&key), &values[index][0])
@@ -416,7 +460,7 @@ fn backend_table(
);
}
3..=6 => {
ui.label(&values[index][column]);
ui.label(&values[index][columns[column]]);
}
_ => format::sparkline(ui, rates.map(|r| &r.total), view.unit, 24.0),
},
+81
View File
@@ -0,0 +1,81 @@
//! Icons with the same meaning and input behavior across both clients.
use egui::{Response, Sense, Ui, WidgetInfo, WidgetType};
use egui_phosphor::regular as icon;
/// Supplied by Android so the soft keyboard never looks like an orientation change.
pub fn set_landscape(ctx: &egui::Context, landscape: bool) {
ctx.data_mut(|d| d.insert_temp(egui::Id::new("window landscape"), landscape));
}
/// Whether this viewport has a landscape layout.
pub fn landscape(ctx: &egui::Context) -> bool {
ctx.data(|d| d.get_temp(egui::Id::new("window landscape")))
.unwrap_or_else(|| ctx.screen_rect().width() > ctx.screen_rect().height())
}
/// A tooltip for mouse hover, keyboard focus or a deliberate long press.
pub fn hint(response: Response, description: &str) -> Response {
let ctx = &response.ctx;
let touch = ctx.os() == egui::os::OperatingSystem::Android;
let now = ctx.input(|i| i.time);
let key = egui::Id::new(("touch explanation", ctx.viewport_id()));
if response.long_touched() {
ctx.data_mut(|d| d.insert_temp(key, (response.id, now + 2.5)));
ctx.request_repaint();
}
let held = ctx
.data(|d| d.get_temp::<(egui::Id, f64)>(key))
.filter(|(id, until)| touch && *id == response.id && now < *until);
if held.is_some() || (!touch && response.has_focus()) {
egui::show_tooltip_for(ctx, response.layer_id, response.id, &response.rect, |ui| {
ui.set_max_width(
ui.spacing()
.tooltip_width
.min(ctx.screen_rect().width() - 16.),
);
ui.label(description);
});
if let Some((_, until)) = held {
ctx.request_repaint_after_secs((until - now) as f32);
}
response
} else {
response
.on_hover_text(description)
.on_disabled_hover_text(description)
}
}
/// A glyph-only button with its action exposed to assistive technology.
pub fn icon_button(ui: &mut Ui, glyph: &str, description: &str) -> Response {
let r = ui.button(glyph);
r.widget_info(|| WidgetInfo::labeled(WidgetType::Button, r.enabled(), description));
hint(r, description)
}
/// A field caption, or just its icon when the adjacent value is self-explanatory.
pub(crate) fn field(ui: &mut Ui, glyph: &str, caption: &str, description: &str) {
let label = if caption.is_empty() {
glyph.to_string()
} else {
format!("{glyph} {caption}")
};
let r = ui.add(egui::Label::new(egui::RichText::new(label).weak()).sense(Sense::click()));
r.widget_info(|| WidgetInfo::labeled(WidgetType::Label, r.enabled(), description));
hint(r, description);
}
pub(crate) fn network_id(ui: &mut Ui) {
field(ui, icon::HASH, "", "Network ID");
}
pub(crate) fn range(ui: &mut Ui) {
field(ui, icon::TREE_STRUCTURE, "", "Network range (CIDR)");
}
pub(crate) fn device_address(ui: &mut Ui) {
let glyph = if ui.ctx().os() == egui::os::OperatingSystem::Android {
icon::DEVICE_MOBILE
} else {
icon::LAPTOP
};
field(ui, glyph, "", "This device’s IPv4 address");
}