Keep the devices window responsive and make traffic flows sortable
A waiting peer or speed-test animation in an immediate egui viewport repainted the parent and its other windows. Each pass also supersampled the same 64-pixel logo and handed the new allocation to the OS. Give each Devices window its own repaint schedule. Wake it when status or shared controls change, reuse the native icon, and skip measuring the wide roster when its remembered minimum width exceeds the viewport. Use the bundled Phosphor StopCircle for single and batch tests. Bind incoming throughput probes to the signed address pair for the running diagnostic. Cache its validity across packets under a routing revision. A change of ownership, including removal or reassignment, revalidates the pair under the routing read lock. This removes a lock and a linear peer search from the steady-state receive path and keeps the timing, byte limits and wire protocol compatible. Give the traffic inspector a pinned header and compact, aligned rows with readable text in both themes. The column chooser keeps the peer visible on a narrow screen. Clicking a header sorts the complete filtered capture with a stable cursor across pages. Maintain one sort index on the window's scratch database and expire idle rates there. Address sorting uses numeric IP and port values. Peer and network sorting follows displayed names, including live name changes. Bump the applications, Android package and Nix package to 1.0.8. On macOS, verified formatting, workspace Clippy and all-target tests, including real encrypted tests between local agents. Rendered the monitor in light and dark desktop themes and at phone width. Built the arm64 Android debug APK and cross-checked the Windows GNU target. Across 500 optimized viewport updates, egui produced 500 native icon replacements on 1.0.7 and zero with this change.
This commit is contained in:
1 parent
b47acb8321
commit
d8b7787430
27 files changed
+1500
-399
No files matched your search
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.7"
|
||||
version = "1.0.8"
|
||||
description = "Shared egui widgets for the tray and Android clients."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -10,7 +10,7 @@ publish = false
|
||||
|
||||
[dependencies]
|
||||
postcard.workspace = true
|
||||
rusqlite = { version = "0.40", features = ["bundled"] }
|
||||
rusqlite = { version = "0.40", features = ["bundled", "functions"] }
|
||||
tempfile.workspace = true
|
||||
egui = "0.31"
|
||||
egui-phosphor = "0.9"
|
||||
|
||||
@@ -232,9 +232,20 @@ pub fn show(
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
let table = desktop_columns(ui, unit, network, &devices, traffic);
|
||||
let required = table.widths.iter().sum::<f32>() + crate::table::GAP * 8.;
|
||||
if required <= ui.available_width() {
|
||||
// Remembered desktop widths only grow. While this window is compact,
|
||||
// an animation frame need not format and measure all peers a second time.
|
||||
let available = ui.available_width();
|
||||
let id = egui::Id::new(("devices column widths", &network.network_id));
|
||||
let fits = |w: &[f32; 9]| {
|
||||
w[..8].iter().sum::<f32>() + MIN_PLOT_WIDTH + crate::table::GAP * 8.
|
||||
<= available
|
||||
};
|
||||
let could_fit = ui
|
||||
.data(|d| d.get_temp::<[f32; 9]>(id))
|
||||
.is_none_or(|w| fits(&w));
|
||||
let table =
|
||||
could_fit.then(|| desktop_columns(ui, unit, network, &devices, traffic));
|
||||
if let Some(table) = table.filter(|t| fits(&t.widths)) {
|
||||
device_table(
|
||||
ui,
|
||||
network,
|
||||
@@ -626,9 +637,11 @@ fn column_widths(ui: &egui::Ui, id: egui::Id) -> [f32; 9] {
|
||||
})
|
||||
}
|
||||
|
||||
const MIN_PLOT_WIDTH: f32 = 100.;
|
||||
|
||||
fn stretch_columns(mut widths: [f32; 9], available: f32) -> [f32; 9] {
|
||||
let gaps = crate::table::GAP * (widths.len() - 1) as f32;
|
||||
widths[8] = (available - gaps - widths[..8].iter().sum::<f32>()).clamp(100.0, 180.0);
|
||||
widths[8] = (available - gaps - widths[..8].iter().sum::<f32>()).clamp(MIN_PLOT_WIDTH, 180.0);
|
||||
widths
|
||||
}
|
||||
|
||||
@@ -1555,6 +1568,45 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compact_frames_skip_the_hidden_desktop_layout_until_the_window_grows() {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
let id = egui::Id::new(("devices column widths", "lab"));
|
||||
let mut net = NetworkReport {
|
||||
network_id: "lab".into(),
|
||||
members: vec![member("peer", true, DataPathReport::None)],
|
||||
..Default::default()
|
||||
};
|
||||
let draw = |width, net: &NetworkReport| {
|
||||
let _ = ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, 600.),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
show(
|
||||
ctx,
|
||||
&ReadOnly,
|
||||
&mut Unit::Bytes,
|
||||
(&mut None, &mut None),
|
||||
net,
|
||||
"self",
|
||||
&Traffic::default(),
|
||||
)
|
||||
},
|
||||
);
|
||||
ctx.data(|d| d.get_temp::<[f32; 9]>(id)).unwrap()
|
||||
};
|
||||
let first = draw(660., &net);
|
||||
net.members[0].hostname = Some("a-much-longer-peer-name-for-the-wide-table".into());
|
||||
assert_eq!(draw(660., &net), first);
|
||||
assert!(draw(2300., &net)[0] > first[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_relay_name_gets_its_full_column_width() {
|
||||
let mut relay = member("near", true, DataPathReport::None);
|
||||
|
||||
@@ -33,8 +33,15 @@ impl<'a> Controls<'a> {
|
||||
let (label, help, available) = if self.running {
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(250));
|
||||
let label = self.network.speed.batch.map_or_else(
|
||||
|| format!("{} Stop test", icon::STOP),
|
||||
|batch| format!("{} Stop {}/{}", icon::STOP, batch.done, batch.total),
|
||||
|| format!("{} Stop test", icon::STOP_CIRCLE),
|
||||
|batch| {
|
||||
format!(
|
||||
"{} Stop {}/{}",
|
||||
icon::STOP_CIRCLE,
|
||||
batch.done,
|
||||
batch.total
|
||||
)
|
||||
},
|
||||
);
|
||||
(
|
||||
label,
|
||||
@@ -63,7 +70,7 @@ impl<'a> Controls<'a> {
|
||||
let width = ui
|
||||
.painter()
|
||||
.layout_no_wrap(
|
||||
format!("{} Stop 9999/9999", icon::STOP),
|
||||
format!("{} Stop 9999/9999", icon::STOP_CIRCLE),
|
||||
egui::TextStyle::Button.resolve(ui.style()),
|
||||
ui.visuals().text_color(),
|
||||
)
|
||||
|
||||
@@ -273,7 +273,9 @@ fn exit_batch_requires_an_online_capable_exit_and_stops_in_its_own_network() {
|
||||
s.click(&n, start);
|
||||
n.speed.batch = Some(SpeedBatchReport { done: 0, total: 1 });
|
||||
let batch = s.frame(&n, vec![]);
|
||||
assert!(!positions(&batch, |s| s.contains("0/1")).is_empty());
|
||||
assert!(!positions(&batch, |s| s == format!("{} Stop 0/1", icon::STOP_CIRCLE)).is_empty());
|
||||
let font = egui::TextStyle::Button.resolve(&s.ctx.style());
|
||||
assert!(s.ctx.fonts(|f| f.has_glyphs(&font, icon::STOP_CIRCLE)));
|
||||
s.click(&n, positions(&batch, |s| s.contains("Stop"))[0]);
|
||||
assert!(matches!(s.log.0.borrow().as_slice(), [
|
||||
Command::StartSpeedTest { network_id, peer: None },
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Fields shared by the table, its column chooser and the history ordering.
|
||||
use super::{Names, endpoints, role_name};
|
||||
use rusqlite::types::Value;
|
||||
use tsunagi::traffic::{Flow, FlowKey, IpDetail};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) enum Column {
|
||||
Peer,
|
||||
Network,
|
||||
Near,
|
||||
Far,
|
||||
Protocol,
|
||||
Role,
|
||||
Sent,
|
||||
Received,
|
||||
SendRate,
|
||||
ReceiveRate,
|
||||
SentPackets,
|
||||
ReceivedPackets,
|
||||
Seen,
|
||||
PeerId,
|
||||
}
|
||||
|
||||
impl Column {
|
||||
pub fn title(self) -> &'static str {
|
||||
match self {
|
||||
Self::Peer => "Peer",
|
||||
Self::Network => "Network",
|
||||
Self::Near => "Endpoint A",
|
||||
Self::Far => "Endpoint B",
|
||||
Self::Protocol => "Protocol",
|
||||
Self::Role => "Role",
|
||||
Self::Sent => "Sent",
|
||||
Self::Received => "Received",
|
||||
Self::SendRate => "TX rate",
|
||||
Self::ReceiveRate => "RX rate",
|
||||
Self::SentPackets => "TX packets",
|
||||
Self::ReceivedPackets => "RX packets",
|
||||
Self::Seen => "Last seen",
|
||||
Self::PeerId => "Peer ID",
|
||||
}
|
||||
}
|
||||
pub fn hint(self) -> &'static str {
|
||||
match self {
|
||||
Self::Peer => "Authenticated peer",
|
||||
Self::Network => "Tsunagi network",
|
||||
Self::Near => "Agent-side endpoint, or the first endpoint of an encrypted relay",
|
||||
Self::Far => "Peer-side endpoint, or the second endpoint of an encrypted relay",
|
||||
Self::Protocol => "IP protocol or transport session",
|
||||
Self::Role => "How this agent handles the traffic",
|
||||
Self::Sent => "Total bytes sent from A to B",
|
||||
Self::Received => "Total bytes received from B to A",
|
||||
Self::SendRate => "Bytes per second from A to B",
|
||||
Self::ReceiveRate => "Bytes per second from B to A",
|
||||
Self::SentPackets => "Packets sent from A to B",
|
||||
Self::ReceivedPackets => "Packets received from B to A",
|
||||
Self::Seen => "Time since the last observation",
|
||||
Self::PeerId => "Public peer ID. Select a value to copy it.",
|
||||
}
|
||||
}
|
||||
pub fn descending_first(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Sent
|
||||
| Self::Received
|
||||
| Self::SendRate
|
||||
| Self::ReceiveRate
|
||||
| Self::SentPackets
|
||||
| Self::ReceivedPackets
|
||||
| Self::Seen
|
||||
)
|
||||
}
|
||||
pub fn sql(self) -> &'static str {
|
||||
match self {
|
||||
Self::Sent => "tx",
|
||||
Self::Received => "rx",
|
||||
Self::SendRate => "tx_rate",
|
||||
Self::ReceiveRate => "rx_rate",
|
||||
Self::SentPackets => "ntx",
|
||||
Self::ReceivedPackets => "nrx",
|
||||
Self::Seen => "last",
|
||||
Self::PeerId => "peer",
|
||||
_ => "flow_label(key)",
|
||||
}
|
||||
}
|
||||
pub fn uses_names(self) -> bool {
|
||||
matches!(self, Self::Peer | Self::Network | Self::Near | Self::Far)
|
||||
}
|
||||
// SQLite indexes this value only while sorting by a descriptive column.
|
||||
// Numeric IPv4 address and port order is independent of their spelling.
|
||||
pub fn label_key(self, key: &FlowKey, names: &Names) -> Value {
|
||||
if let Flow::Ip {
|
||||
near, far, detail, ..
|
||||
} = key.flow
|
||||
&& matches!(self, Self::Near | Self::Far)
|
||||
{
|
||||
let near_side = self == Self::Near;
|
||||
let ip = u32::from_be_bytes(if near_side { near } else { far });
|
||||
let port = match detail {
|
||||
IpDetail::Ports(a, b) => 1 + i64::from(if near_side { a } else { b }),
|
||||
_ => 0,
|
||||
};
|
||||
return Value::Integer((i64::from(ip) << 17) + port);
|
||||
}
|
||||
let label = match self {
|
||||
Self::Peer => names.peer(&key.network, &key.peer),
|
||||
Self::Network => names.network(&key.network),
|
||||
Self::Near => endpoints(key, names).0,
|
||||
Self::Far => endpoints(key, names).1,
|
||||
Self::Protocol => endpoints(key, names).2,
|
||||
Self::Role => role_name(key.role).into(),
|
||||
_ => return Value::Null,
|
||||
};
|
||||
Value::Text(label.to_lowercase())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct Sort {
|
||||
pub column: Column,
|
||||
pub descending: bool,
|
||||
}
|
||||
impl Default for Sort {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
column: Column::Seen,
|
||||
descending: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Sort {
|
||||
pub fn select(&mut self, column: Column) {
|
||||
self.descending = if self.column == column {
|
||||
!self.descending
|
||||
} else {
|
||||
column.descending_first()
|
||||
};
|
||||
self.column = column;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,34 @@
|
||||
//! A private scratch database belongs to one window and one worker thread.
|
||||
//! A capture with millions of flows uses disk, and the UI reads one page at a time.
|
||||
use super::{Column, Names, Sort};
|
||||
use rusqlite::functions::FunctionFlags;
|
||||
use rusqlite::{Connection, params, params_from_iter, types::Value};
|
||||
use std::path::Path;
|
||||
use std::{path::Path, sync::Arc};
|
||||
use tsunagi::traffic::{Flow, FlowDelta, Role};
|
||||
|
||||
pub(super) const PAGE_SIZE: usize = 64;
|
||||
pub(super) const RATE_LIFETIME_MS: u64 = 1900;
|
||||
const RETAIN_MS: u64 = 60_000;
|
||||
|
||||
#[derive(Default, Clone, PartialEq, Eq)]
|
||||
#[derive(Default, Clone, PartialEq)]
|
||||
pub(super) struct Filter {
|
||||
pub network: Option<[u8; 32]>,
|
||||
pub peer: Option<[u8; 32]>,
|
||||
pub protocol: Option<u8>,
|
||||
pub role: Option<Role>,
|
||||
pub transport: bool,
|
||||
pub before: Option<i64>,
|
||||
pub sort: Sort,
|
||||
pub before: Option<Cursor>,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub(super) struct Cursor {
|
||||
value: Value,
|
||||
id: i64,
|
||||
}
|
||||
|
||||
pub(super) struct Row {
|
||||
order_value: Value,
|
||||
pub id: i64,
|
||||
pub data: FlowDelta,
|
||||
pub last: u64,
|
||||
@@ -25,6 +36,14 @@ pub(super) struct Row {
|
||||
pub tx_rate: f32,
|
||||
pub rx_rate: f32,
|
||||
}
|
||||
impl Row {
|
||||
pub fn cursor(&self) -> Cursor {
|
||||
Cursor {
|
||||
value: self.order_value.clone(),
|
||||
id: self.id,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct Page {
|
||||
pub rows: Vec<Row>,
|
||||
@@ -33,6 +52,8 @@ pub(super) struct Page {
|
||||
|
||||
pub(super) struct History {
|
||||
connection: Connection,
|
||||
indexed: Option<Column>,
|
||||
names: Arc<Names>,
|
||||
}
|
||||
|
||||
// SQLite counters are signed 64-bit integers; clamp only at its representable maximum.
|
||||
@@ -63,6 +84,7 @@ impl History {
|
||||
tx INTEGER NOT NULL, rx INTEGER NOT NULL, ntx INTEGER NOT NULL, nrx INTEGER NOT NULL,
|
||||
last INTEGER NOT NULL, sampled INTEGER NOT NULL, tx_rate REAL NOT NULL, rx_rate REAL NOT NULL
|
||||
);
|
||||
CREATE INDEX live_rates ON flow(sampled) WHERE tx_rate>0 OR rx_rate>0;
|
||||
CREATE INDEX by_last ON flow(last);
|
||||
CREATE INDEX by_layer ON flow(transport,id);
|
||||
CREATE INDEX by_network ON flow(transport,network,id);
|
||||
@@ -73,7 +95,52 @@ impl History {
|
||||
// All platforms that pass a directory are Unix; unlink the open file so even
|
||||
// force-stopping the activity releases it when the OS closes the descriptor.
|
||||
drop(file);
|
||||
Ok(Self { connection: db })
|
||||
Ok(Self {
|
||||
connection: db,
|
||||
indexed: None,
|
||||
names: Arc::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn use_names(&mut self, names: Arc<Names>) {
|
||||
if !Arc::ptr_eq(&self.names, &names) {
|
||||
self.names = names;
|
||||
if self.indexed.is_some_and(Column::uses_names) {
|
||||
self.indexed = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One index serves the active ordering, including its stable tie-breaker.
|
||||
// Long captures pay its setup cost once per change on the window worker.
|
||||
fn prepare_order(&mut self, column: Column) -> rusqlite::Result<()> {
|
||||
if self.indexed == Some(column) {
|
||||
return Ok(());
|
||||
}
|
||||
self.connection
|
||||
.execute_batch("DROP INDEX IF EXISTS by_view")?;
|
||||
let expr = column.sql();
|
||||
if expr == "flow_label(key)" {
|
||||
let names = self.names.clone();
|
||||
self.connection.create_scalar_function(
|
||||
"flow_label",
|
||||
1,
|
||||
FunctionFlags::SQLITE_UTF8
|
||||
| FunctionFlags::SQLITE_DETERMINISTIC
|
||||
| FunctionFlags::SQLITE_INNOCUOUS,
|
||||
move |ctx| {
|
||||
let bytes = ctx.get_raw(0).as_blob()?;
|
||||
let key = postcard::from_bytes(bytes)
|
||||
.map_err(|e| rusqlite::Error::UserFunctionError(Box::new(e)))?;
|
||||
Ok(column.label_key(&key, &names))
|
||||
},
|
||||
)?;
|
||||
}
|
||||
self.connection.execute_batch(&format!(
|
||||
"CREATE INDEX by_view ON flow(transport,{expr},id)"
|
||||
))?;
|
||||
self.indexed = Some(column);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn interrupt(&self) -> rusqlite::InterruptHandle {
|
||||
@@ -122,6 +189,13 @@ impl History {
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
if now >= RATE_LIFETIME_MS {
|
||||
txn.execute(
|
||||
"UPDATE flow SET tx_rate=0,rx_rate=0 WHERE sampled<=? AND (tx_rate>0 OR rx_rate>0)",
|
||||
[integer(now - RATE_LIFETIME_MS)],
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
if !keep && now >= RETAIN_MS {
|
||||
txn.execute(
|
||||
"DELETE FROM flow WHERE last <= ?1",
|
||||
@@ -132,9 +206,12 @@ impl History {
|
||||
txn.commit().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn page(&self, f: &Filter) -> Result<Page, String> {
|
||||
let mut sql = String::from(
|
||||
"SELECT id,key,tx,rx,ntx,nrx,last,sampled,tx_rate,rx_rate FROM flow WHERE transport=?",
|
||||
pub fn page(&mut self, f: &Filter) -> Result<Page, String> {
|
||||
self.prepare_order(f.sort.column)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let expr = f.sort.column.sql();
|
||||
let mut sql = format!(
|
||||
"SELECT id,key,tx,rx,ntx,nrx,last,sampled,tx_rate,rx_rate,{expr} FROM flow WHERE transport=?"
|
||||
);
|
||||
let mut args = vec![Value::Integer(i64::from(f.transport))];
|
||||
if let Some(n) = f.network {
|
||||
@@ -153,11 +230,18 @@ impl History {
|
||||
sql.push_str(" AND protocol=?");
|
||||
args.push(Value::Integer(p.into()));
|
||||
}
|
||||
if let Some(cursor) = f.before {
|
||||
sql.push_str(" AND id<?");
|
||||
args.push(Value::Integer(cursor));
|
||||
let (op, direction) = if f.sort.descending {
|
||||
("<", "DESC")
|
||||
} else {
|
||||
(">", "ASC")
|
||||
};
|
||||
if let Some(cursor) = &f.before {
|
||||
sql.push_str(&format!(" AND ({expr},id){op}(?,?)"));
|
||||
args.extend([cursor.value.clone(), Value::Integer(cursor.id)]);
|
||||
}
|
||||
sql.push_str(" ORDER BY id DESC LIMIT ?");
|
||||
sql.push_str(&format!(
|
||||
" ORDER BY {expr} {direction},id {direction} LIMIT ?"
|
||||
));
|
||||
args.push(Value::Integer(PAGE_SIZE as i64 + 1));
|
||||
let mut q = self
|
||||
.connection
|
||||
@@ -175,6 +259,7 @@ impl History {
|
||||
})?;
|
||||
Ok(Row {
|
||||
id: r.get(0)?,
|
||||
order_value: r.get(10)?,
|
||||
data: FlowDelta {
|
||||
key,
|
||||
tx_bytes: r.get::<_, i64>(2)? as u64,
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
//! Live traffic inspector shared by the tray and Android clients.
|
||||
mod columns;
|
||||
mod history;
|
||||
mod table;
|
||||
use columns::{Column, Sort};
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod worker;
|
||||
|
||||
use crate::{
|
||||
format::{bytes, short},
|
||||
widgets,
|
||||
};
|
||||
use egui::{RichText, Ui};
|
||||
use crate::{format::short, widgets};
|
||||
use egui::Ui;
|
||||
use egui_phosphor::regular as icon;
|
||||
use history::{Filter, Row};
|
||||
use std::{collections::BTreeMap, net::Ipv4Addr, path::PathBuf, time::Duration};
|
||||
use history::{Cursor, Filter};
|
||||
use std::{collections::BTreeMap, net::Ipv4Addr, path::PathBuf, sync::Arc, time::Duration};
|
||||
use tsunagi::{
|
||||
NetworkId,
|
||||
ipc::StatusReport,
|
||||
@@ -22,12 +22,12 @@ pub use worker::Feed;
|
||||
use worker::Worker;
|
||||
|
||||
type Id = [u8; 32];
|
||||
#[derive(Default)]
|
||||
#[derive(Clone, Default)]
|
||||
struct Network {
|
||||
name: String,
|
||||
peers: BTreeMap<Id, String>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
#[derive(Clone, Default)]
|
||||
struct Names {
|
||||
networks: BTreeMap<Id, Network>,
|
||||
generation: Option<u64>,
|
||||
@@ -37,18 +37,25 @@ fn public_id(id: &Id) -> String {
|
||||
id.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
impl Names {
|
||||
fn refresh(&mut self, report: Option<&StatusReport>, generation: u64) {
|
||||
let Some(report) = report else { return };
|
||||
fn refresh(&mut self, report: Option<&StatusReport>, generation: u64) -> bool {
|
||||
let Some(report) = report else { return false };
|
||||
if self.generation == Some(generation) {
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
self.generation = Some(generation);
|
||||
let mut changed = false;
|
||||
for n in &report.networks {
|
||||
let Ok(id) = n.network_id.parse::<NetworkId>() else {
|
||||
continue;
|
||||
};
|
||||
let entry = self.networks.entry(*id.as_bytes()).or_default();
|
||||
entry.name = n.name.clone();
|
||||
if entry.name != n.name {
|
||||
entry.name.clone_from(&n.name);
|
||||
changed = true;
|
||||
}
|
||||
// Resolve duplicate membership and live entries first. A stale member name
|
||||
// must not trigger a rebuild of a multi-day capture's index every poll.
|
||||
let mut reported = BTreeMap::new();
|
||||
for (key, name) in n
|
||||
.members
|
||||
.iter()
|
||||
@@ -63,18 +70,32 @@ impl Names {
|
||||
Some(report.hostname.as_str()),
|
||||
)))
|
||||
{
|
||||
let label = reported.entry(key).or_default();
|
||||
if let Some(name) = name.filter(|s| !s.is_empty()) {
|
||||
*label = Some(name);
|
||||
}
|
||||
}
|
||||
for (key, name) in reported {
|
||||
if let Ok(peer) = key.parse::<EndpointId>() {
|
||||
let label = name.filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
let current = entry
|
||||
.peers
|
||||
.entry(*peer.as_bytes())
|
||||
.or_insert_with(|| short(key));
|
||||
if let Some(label) = label {
|
||||
*current = label;
|
||||
use std::collections::btree_map::Entry;
|
||||
match entry.peers.entry(*peer.as_bytes()) {
|
||||
Entry::Vacant(e) => {
|
||||
e.insert(name.map_or_else(|| short(key), str::to_owned));
|
||||
changed = true;
|
||||
}
|
||||
Entry::Occupied(mut e) => {
|
||||
if let Some(name) = name
|
||||
&& name != e.get()
|
||||
{
|
||||
*e.get_mut() = name.into();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
fn network(&self, id: &Id) -> String {
|
||||
let Some(n) = self.networks.get(id) else {
|
||||
@@ -115,17 +136,6 @@ fn role_name(r: Role) -> &'static str {
|
||||
Role::Relay => "Encrypted relay",
|
||||
}
|
||||
}
|
||||
fn role_text(role: Role) -> String {
|
||||
let glyph = match role {
|
||||
Role::ViaExit => icon::SIGN_OUT,
|
||||
Role::ServeExit => icon::SIGN_IN,
|
||||
Role::Relay => icon::GIT_FORK,
|
||||
Role::Broadcast => icon::BROADCAST,
|
||||
Role::SpeedTest => icon::GAUGE,
|
||||
_ => return role_name(role).to_owned(),
|
||||
};
|
||||
format!("{glyph} {}", role_name(role))
|
||||
}
|
||||
fn protocol(n: u8) -> String {
|
||||
match n {
|
||||
1 => "ICMP".into(),
|
||||
@@ -189,8 +199,8 @@ pub struct Window {
|
||||
names: Names,
|
||||
filter: Filter,
|
||||
keep: bool,
|
||||
previous: Vec<Option<i64>>,
|
||||
selected: Option<i64>,
|
||||
previous: Vec<Option<Cursor>>,
|
||||
column_page: usize,
|
||||
}
|
||||
impl Window {
|
||||
/// Creates an empty view. Android supplies its application-private cache directory.
|
||||
@@ -201,7 +211,7 @@ impl Window {
|
||||
filter: Filter::default(),
|
||||
keep: false,
|
||||
previous: Vec::new(),
|
||||
selected: None,
|
||||
column_page: 0,
|
||||
}
|
||||
}
|
||||
/// The endpoint into which this window's subscription feeds interval snapshots.
|
||||
@@ -209,31 +219,57 @@ impl Window {
|
||||
self.worker.feed.clone()
|
||||
}
|
||||
|
||||
fn controls(&mut self, ui: &mut Ui) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let layer = self.filter.transport;
|
||||
ui.selectable_value(&mut self.filter.transport, false, format!("{} IP flows", icon::ARROWS_LEFT_RIGHT));
|
||||
ui.selectable_value(&mut self.filter.transport, true, format!("{} Transport", icon::GIT_FORK))
|
||||
.on_hover_text("Authenticated control sessions and encrypted traffic relayed between peers");
|
||||
if layer != self.filter.transport {
|
||||
self.filter.role = None;
|
||||
self.filter.protocol = None;
|
||||
}
|
||||
widgets::hint(ui.checkbox(&mut self.keep,"Keep until close"),
|
||||
"Keep inactive flows for this window session. Otherwise they expire after 60 seconds.");
|
||||
});
|
||||
let width = ((ui.available_width() - ui.spacing().item_spacing.x) / 2.).clamp(60., 135.);
|
||||
fn controls(&mut self, ui: &mut Ui, grid: &table::Grid) {
|
||||
if ui.available_width() < 540. {
|
||||
ui.horizontal(|ui| self.layers(ui));
|
||||
ui.horizontal(|ui| self.history_controls(ui, grid));
|
||||
} else {
|
||||
ui.horizontal(|ui| {
|
||||
self.layers(ui);
|
||||
self.history_controls(ui, grid);
|
||||
});
|
||||
}
|
||||
if ui.available_width() < 580. {
|
||||
let width = ((ui.available_width() - ui.spacing().item_spacing.x) / 2.).max(60.);
|
||||
ui.horizontal(|ui| self.identity_filters(ui, width));
|
||||
ui.horizontal(|ui| self.flow_filters(ui, width));
|
||||
} else {
|
||||
ui.horizontal(|ui| {
|
||||
self.identity_filters(ui, width);
|
||||
self.flow_filters(ui, width);
|
||||
self.identity_filters(ui, 135.);
|
||||
self.flow_filters(ui, 135.);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn layers(&mut self, ui: &mut Ui) {
|
||||
let layer = self.filter.transport;
|
||||
ui.selectable_value(
|
||||
&mut self.filter.transport,
|
||||
false,
|
||||
format!("{} IP flows", icon::ARROWS_LEFT_RIGHT),
|
||||
);
|
||||
ui.selectable_value(
|
||||
&mut self.filter.transport,
|
||||
true,
|
||||
format!("{} Transport", icon::GIT_FORK),
|
||||
)
|
||||
.on_hover_text(
|
||||
"Authenticated control sessions and encrypted traffic relayed between peers",
|
||||
);
|
||||
if layer != self.filter.transport {
|
||||
self.filter.role = None;
|
||||
self.filter.protocol = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn history_controls(&mut self, ui: &mut Ui, grid: &table::Grid) {
|
||||
widgets::hint(
|
||||
ui.checkbox(&mut self.keep, "Keep until close"),
|
||||
"Keep inactive flows for this window session. Otherwise they expire after 60 seconds.",
|
||||
);
|
||||
grid.chooser(ui, &mut self.column_page);
|
||||
}
|
||||
|
||||
fn identity_filters(&mut self, ui: &mut Ui, width: f32) {
|
||||
let network = self.filter.network;
|
||||
egui::ComboBox::from_id_salt("flow-network")
|
||||
@@ -322,14 +358,18 @@ impl Window {
|
||||
|
||||
/// Draw the responsive inspector inside the current viewport.
|
||||
pub fn show(&mut self, ui: &mut Ui, report: Option<&StatusReport>, generation: u64) {
|
||||
self.names.refresh(report, generation);
|
||||
if self.names.refresh(report, generation) {
|
||||
self.worker.names(Arc::new(self.names.clone()));
|
||||
}
|
||||
table::style(ui);
|
||||
let before = self.filter.clone();
|
||||
let keep = self.keep;
|
||||
self.controls(ui);
|
||||
let grid = table::Grid::new(ui);
|
||||
self.column_page = self.column_page.min(grid.pages.len() - 1);
|
||||
self.controls(ui, &grid);
|
||||
if self.filter != before {
|
||||
self.filter.before = None;
|
||||
self.previous.clear();
|
||||
self.selected = None;
|
||||
}
|
||||
if self.filter != before || self.keep != keep {
|
||||
self.worker.options(self.filter.clone(), self.keep);
|
||||
@@ -346,40 +386,44 @@ impl Window {
|
||||
}
|
||||
ui.separator();
|
||||
let now = self.worker.feed.elapsed();
|
||||
let wide = ui.available_width() >= 690.;
|
||||
if !self.previous.is_empty() || page.more {
|
||||
ui.horizontal(|ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui
|
||||
.add_enabled(
|
||||
!self.previous.is_empty(),
|
||||
egui::Button::new(format!("{} Newer", icon::CARET_LEFT)),
|
||||
egui::Button::new(format!("{} Previous", icon::CARET_LEFT)),
|
||||
)
|
||||
.clicked()
|
||||
&& let Some(cursor) = self.previous.pop()
|
||||
{
|
||||
self.filter.before = cursor;
|
||||
self.selected = None;
|
||||
self.worker.options(self.filter.clone(), self.keep);
|
||||
}
|
||||
ui.weak(format!("Page {}", self.previous.len() + 1));
|
||||
ui.label(format!("Page {}", self.previous.len() + 1));
|
||||
if ui
|
||||
.add_enabled(
|
||||
page.more,
|
||||
egui::Button::new(format!("Older {}", icon::CARET_RIGHT)),
|
||||
egui::Button::new(format!("Next {}", icon::CARET_RIGHT)),
|
||||
)
|
||||
.clicked()
|
||||
&& let Some(r) = page.rows.last()
|
||||
&& let Some(row) = page.rows.last()
|
||||
{
|
||||
self.previous.push(self.filter.before);
|
||||
self.filter.before = Some(r.id);
|
||||
self.selected = None;
|
||||
self.previous.push(self.filter.before.clone());
|
||||
self.filter.before = Some(row.cursor());
|
||||
self.worker.options(self.filter.clone(), self.keep);
|
||||
}
|
||||
});
|
||||
}
|
||||
let columns = &grid.pages[self.column_page];
|
||||
if let Some(column) = grid.header(ui, columns, self.filter.sort) {
|
||||
self.filter.sort.select(column);
|
||||
self.filter.before = None;
|
||||
self.previous.clear();
|
||||
self.worker.options(self.filter.clone(), self.keep);
|
||||
}
|
||||
if page.rows.is_empty() {
|
||||
ui.add_space(14.);
|
||||
ui.weak(if error.is_some() {
|
||||
ui.add_space(10.);
|
||||
ui.label(if error.is_some() {
|
||||
"No captured flows in this view."
|
||||
} else if self.filter.network.is_some()
|
||||
|| self.filter.role.is_some()
|
||||
@@ -391,160 +435,15 @@ impl Window {
|
||||
"Listening for traffic…"
|
||||
});
|
||||
} else {
|
||||
if wide {
|
||||
desktop_header(ui);
|
||||
}
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("flow-rows")
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
for row in &page.rows {
|
||||
let chosen = self.selected == Some(row.id);
|
||||
egui::Frame::new()
|
||||
.inner_margin(egui::Margin::symmetric(5, 3))
|
||||
.fill(if chosen {
|
||||
ui.visuals().selection.bg_fill
|
||||
} else if row.id % 2 == 0 {
|
||||
ui.visuals().faint_bg_color
|
||||
} else {
|
||||
egui::Color32::TRANSPARENT
|
||||
})
|
||||
.show(ui, |ui| {
|
||||
let summary = ui.scope(|ui| self.row(ui, row, now, wide)).response;
|
||||
let selected = ui.interact(
|
||||
summary.rect,
|
||||
ui.id().with(("flow", row.id)),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
if selected.clicked() {
|
||||
self.selected = if chosen { None } else { Some(row.id) };
|
||||
}
|
||||
|
||||
if chosen {
|
||||
ui.separator();
|
||||
let key = &row.data.key;
|
||||
let (a, b, p) = endpoints(key, &self.names);
|
||||
ui.label(format!("{a} ↔ {b} · {p}"));
|
||||
ui.label(format!(
|
||||
"{} {} packets sent {} {} received",
|
||||
icon::ARROW_UP,
|
||||
row.data.tx_packets,
|
||||
icon::ARROW_DOWN,
|
||||
row.data.rx_packets
|
||||
));
|
||||
let id = public_id(&key.peer);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.weak("Peer ID");
|
||||
crate::format::copy_field(ui, &short(&id), &id);
|
||||
});
|
||||
}
|
||||
});
|
||||
.show_rows(ui, grid.row_height, page.rows.len(), |ui, visible| {
|
||||
for index in visible {
|
||||
grid.row(ui, columns, &page.rows[index], &self.names, now, index);
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.ctx().request_repaint_after(Duration::from_secs(1));
|
||||
}
|
||||
|
||||
fn row(&self, ui: &mut Ui, r: &Row, now: u64, wide: bool) {
|
||||
let k = &r.data.key;
|
||||
let (a, b, p) = endpoints(k, &self.names);
|
||||
let network = self.names.network(&k.network);
|
||||
let peer = self.names.peer(&k.network, &k.peer);
|
||||
let role = role_text(k.role);
|
||||
let current = now.saturating_sub(r.sampled) < 1900;
|
||||
let rates = |n: f32| format!("{}/s", bytes(if current { n as f64 } else { 0. }));
|
||||
let (tx, rx) = (bytes(r.data.tx_bytes as f64), bytes(r.data.rx_bytes as f64));
|
||||
let age = ago(now.saturating_sub(r.last));
|
||||
if wide {
|
||||
let widths = widths(ui);
|
||||
ui.horizontal(|ui| {
|
||||
cell(ui, widths[0], &peer, &network);
|
||||
cell(ui, widths[1], &a, &b);
|
||||
cell(ui, widths[2], &p, &role);
|
||||
cell(ui, widths[3], &tx, &rates(r.tx_rate));
|
||||
cell(ui, widths[4], &rx, &rates(r.rx_rate));
|
||||
cell(ui, widths[5], &age, "");
|
||||
});
|
||||
} else {
|
||||
ui.set_min_width(ui.available_width());
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong(peer);
|
||||
ui.weak(&network);
|
||||
ui.label(role);
|
||||
ui.weak(age);
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(&p);
|
||||
ui.monospace(&a);
|
||||
ui.weak("↔");
|
||||
ui.monospace(&b);
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(format!("{} {tx}", icon::ARROW_UP))
|
||||
.on_hover_text("Sent");
|
||||
ui.weak(rates(r.tx_rate));
|
||||
ui.separator();
|
||||
ui.label(format!("{} {rx}", icon::ARROW_DOWN))
|
||||
.on_hover_text("Received");
|
||||
ui.weak(rates(r.rx_rate));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
fn widths(ui: &Ui) -> [f32; 6] {
|
||||
let usable = (ui.available_width() - ui.spacing().item_spacing.x * 5. - 4.).max(0.);
|
||||
[0.18, 0.30, 0.18, 0.13, 0.13, 0.08].map(|s| s * usable)
|
||||
}
|
||||
fn cell(ui: &mut Ui, width: f32, one: &str, two: &str) {
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(width, 0.),
|
||||
egui::Layout::top_down(egui::Align::Min),
|
||||
|ui| {
|
||||
ui.add(egui::Label::new(one).truncate()).on_hover_text(one);
|
||||
if !two.is_empty() {
|
||||
ui.add(egui::Label::new(RichText::new(two).weak().small()).truncate())
|
||||
.on_hover_text(two);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
fn desktop_header(ui: &mut Ui) {
|
||||
egui::Frame::new()
|
||||
.inner_margin(egui::Margin::symmetric(5, 2))
|
||||
.show(ui, |ui| {
|
||||
let widths = widths(ui);
|
||||
ui.horizontal(|ui| {
|
||||
for ((title, hint), width) in [
|
||||
("Peer / network", "Authenticated peer and local network"),
|
||||
(
|
||||
"Endpoints",
|
||||
"This side ↔ peer side. Encrypted relay shows the two named endpoints.",
|
||||
),
|
||||
(
|
||||
"Protocol / role",
|
||||
"IP protocol or transport observation and forwarding role",
|
||||
),
|
||||
(
|
||||
"↑ Sent",
|
||||
"Total and rate toward the peer (first to second endpoint for relay)",
|
||||
),
|
||||
(
|
||||
"↓ Received",
|
||||
"Total and rate from the peer (second to first endpoint for relay)",
|
||||
),
|
||||
("Seen", "Time since last activity"),
|
||||
]
|
||||
.into_iter()
|
||||
.zip(widths)
|
||||
{
|
||||
ui.add_sized(
|
||||
[width, 17.],
|
||||
egui::Label::new(RichText::new(title).small().weak())
|
||||
.halign(egui::Align::Min)
|
||||
.truncate(),
|
||||
)
|
||||
.on_hover_text(hint);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
//! One shared column layout for the pinned header and the virtualized rows.
|
||||
use super::{
|
||||
Column, Names, Sort, ago, endpoints,
|
||||
history::{RATE_LIFETIME_MS, Row},
|
||||
public_id, role_name,
|
||||
};
|
||||
use crate::{
|
||||
format::{bytes, short},
|
||||
widgets,
|
||||
};
|
||||
use egui::{
|
||||
Align, Align2, Color32, FontFamily, FontId, Layout, Rect, RichText, Sense, Ui, UiBuilder, pos2,
|
||||
vec2,
|
||||
};
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
const PAD: f32 = 8.;
|
||||
const GAP: f32 = 12.;
|
||||
|
||||
struct Colors {
|
||||
text: Color32,
|
||||
secondary: Color32,
|
||||
sent: Color32,
|
||||
received: Color32,
|
||||
header: Color32,
|
||||
stripe: Color32,
|
||||
}
|
||||
impl Colors {
|
||||
fn new(dark: bool) -> Self {
|
||||
let tone = |dark_rgb: [u8; 3], light_rgb: [u8; 3]| {
|
||||
let [r, g, b] = if dark { dark_rgb } else { light_rgb };
|
||||
Color32::from_rgb(r, g, b)
|
||||
};
|
||||
Self {
|
||||
text: tone([239, 244, 249], [27, 40, 53]),
|
||||
secondary: tone([195, 207, 219], [62, 79, 96]),
|
||||
sent: tone([140, 211, 255], [16, 89, 145]),
|
||||
received: tone([145, 226, 185], [16, 102, 72]),
|
||||
header: tone([42, 55, 68], [224, 234, 243]),
|
||||
stripe: tone([35, 42, 49], [240, 245, 249]),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn style(ui: &mut Ui) {
|
||||
let colors = Colors::new(ui.visuals().dark_mode);
|
||||
let style = ui.style_mut();
|
||||
for id in [egui::TextStyle::Body, egui::TextStyle::Button] {
|
||||
if let Some(font) = style.text_styles.get_mut(&id) {
|
||||
font.size = font.size.max(15.);
|
||||
}
|
||||
}
|
||||
style.visuals.widgets.noninteractive.fg_stroke.color = colors.text;
|
||||
style.visuals.widgets.inactive.fg_stroke.color = colors.text;
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Slot {
|
||||
column: Column,
|
||||
left: f32,
|
||||
width: f32,
|
||||
}
|
||||
pub(super) struct Grid {
|
||||
pub pages: Vec<Vec<Slot>>,
|
||||
pub row_height: f32,
|
||||
width: f32,
|
||||
body: FontId,
|
||||
bold: FontId,
|
||||
mono: FontId,
|
||||
colors: Colors,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
pub fn new(ui: &Ui) -> Self {
|
||||
use Column::*;
|
||||
// Leave the same scroll gutter above and below, even while the bar animates.
|
||||
let width = (ui.available_width() - ui.spacing().scroll.allocated_width()).max(1.);
|
||||
let body = egui::FontSelection::Default.resolve(ui.style());
|
||||
let bold = FontId::new(body.size, FontFamily::Name("Bold".into()));
|
||||
let mono = FontId::monospace(body.size);
|
||||
let measure = |s: &str, f: &FontId| {
|
||||
ui.painter()
|
||||
.layout_no_wrap(s.into(), f.clone(), Color32::WHITE)
|
||||
.size()
|
||||
.x
|
||||
};
|
||||
let height = ui.fonts(|f| {
|
||||
f.row_height(&body)
|
||||
.max(f.row_height(&bold))
|
||||
.max(f.row_height(&mono))
|
||||
});
|
||||
let minimum = |col: Column| {
|
||||
let sample = match col {
|
||||
Near | Far => "255.255.255.255:65535",
|
||||
Network => "network",
|
||||
Protocol => "ICMP echo",
|
||||
Role => "Serving exit",
|
||||
Sent | Received => "1024.0 MB",
|
||||
SendRate | ReceiveRate => "1024.0 MB/s",
|
||||
SentPackets | ReceivedPackets => "99999999",
|
||||
Seen => "Last seen",
|
||||
PeerId => "0123456789ab…",
|
||||
Peer => "device-name",
|
||||
};
|
||||
let font = if matches!(col, Near | Far | PeerId) {
|
||||
&mono
|
||||
} else {
|
||||
&body
|
||||
};
|
||||
measure(sample, font)
|
||||
.max(measure(col.title(), &bold) + 15.)
|
||||
.ceil()
|
||||
+ 2.
|
||||
};
|
||||
// Keep the peer visible on each column page. Put the most useful live
|
||||
// numbers on the first page, then arrange each page in reading order.
|
||||
let mut remaining = vec![
|
||||
Sent,
|
||||
Received,
|
||||
Seen,
|
||||
Far,
|
||||
Near,
|
||||
Protocol,
|
||||
Role,
|
||||
Network,
|
||||
SendRate,
|
||||
ReceiveRate,
|
||||
SentPackets,
|
||||
ReceivedPackets,
|
||||
PeerId,
|
||||
];
|
||||
let inner = (width - 2. * PAD).max(1.);
|
||||
let pinned = minimum(Peer).min(inner * 0.32);
|
||||
let room = (inner - pinned - GAP).max(0.);
|
||||
let mut pages = Vec::new();
|
||||
while !remaining.is_empty() {
|
||||
let mut fields = vec![(Peer, pinned)];
|
||||
let mut free = room;
|
||||
remaining.retain(|c| {
|
||||
let w = minimum(*c).min(room);
|
||||
if fields.len() == 1 || w <= free {
|
||||
fields.push((*c, w));
|
||||
free -= w + GAP;
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
fields.sort_by_key(|(c, _)| *c);
|
||||
let weight = |c: Column| {
|
||||
if matches!(c, Peer | Near | Far | Network | Role) {
|
||||
2.
|
||||
} else {
|
||||
1.
|
||||
}
|
||||
};
|
||||
let parts: f32 = fields.iter().map(|(c, _)| weight(*c)).sum();
|
||||
let extra = (free + GAP).max(0.) / parts;
|
||||
let mut x = PAD;
|
||||
pages.push(
|
||||
fields
|
||||
.into_iter()
|
||||
.map(|(column, w)| {
|
||||
let slot = Slot {
|
||||
column,
|
||||
left: x,
|
||||
width: w + extra * weight(column),
|
||||
};
|
||||
x += slot.width + GAP;
|
||||
slot
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
Self {
|
||||
pages,
|
||||
row_height: height.ceil() + 8.,
|
||||
width,
|
||||
body,
|
||||
bold,
|
||||
mono,
|
||||
colors: Colors::new(ui.visuals().dark_mode),
|
||||
}
|
||||
}
|
||||
pub fn chooser(&self, ui: &mut Ui, page: &mut usize) {
|
||||
if self.pages.len() == 1 {
|
||||
return;
|
||||
}
|
||||
let response = egui::ComboBox::from_id_salt("traffic-columns")
|
||||
.selected_text(format!(
|
||||
"{} Columns {}/{}",
|
||||
icon::COLUMNS,
|
||||
*page + 1,
|
||||
self.pages.len()
|
||||
))
|
||||
.show_ui(ui, |ui| {
|
||||
ui.set_max_width((ui.ctx().screen_rect().width() - 45.).clamp(100., 400.));
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
|
||||
for (i, slots) in self.pages.iter().enumerate() {
|
||||
let fields = slots
|
||||
.iter()
|
||||
.skip(1)
|
||||
.map(|s| s.column.title())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" · ");
|
||||
ui.selectable_value(page, i, fields);
|
||||
}
|
||||
})
|
||||
.response;
|
||||
widgets::hint(
|
||||
response,
|
||||
"Choose which columns to show. The peer stays visible.",
|
||||
);
|
||||
}
|
||||
fn ink(&self, column: Column) -> Color32 {
|
||||
match column {
|
||||
Column::Sent | Column::SentPackets | Column::SendRate => self.colors.sent,
|
||||
Column::Received | Column::ReceivedPackets | Column::ReceiveRate => {
|
||||
self.colors.received
|
||||
}
|
||||
Column::Network | Column::Seen => self.colors.secondary,
|
||||
_ => self.colors.text,
|
||||
}
|
||||
}
|
||||
pub fn header(&self, ui: &mut Ui, slots: &[Slot], sort: Sort) -> Option<Column> {
|
||||
let (row, _) =
|
||||
ui.allocate_exact_size(vec2(self.width, self.row_height + 3.), Sense::hover());
|
||||
ui.painter().rect_filled(row, 3., self.colors.header);
|
||||
let mut clicked = None;
|
||||
for slot in slots {
|
||||
let col = slot.column;
|
||||
let bounds = slot.rect(row);
|
||||
let active = sort.column == col;
|
||||
let mut text = bounds;
|
||||
if active {
|
||||
let right = numeric(col);
|
||||
let x = if right {
|
||||
text.min.x += 14.;
|
||||
bounds.left()
|
||||
} else {
|
||||
text.max.x -= 14.;
|
||||
bounds.right()
|
||||
};
|
||||
ui.painter().text(
|
||||
pos2(x, row.center().y),
|
||||
if right {
|
||||
Align2::LEFT_CENTER
|
||||
} else {
|
||||
Align2::RIGHT_CENTER
|
||||
},
|
||||
if sort.descending {
|
||||
icon::CARET_DOWN
|
||||
} else {
|
||||
icon::CARET_UP
|
||||
},
|
||||
self.body.clone(),
|
||||
self.colors.text,
|
||||
);
|
||||
}
|
||||
cell(
|
||||
ui,
|
||||
text,
|
||||
col.title(),
|
||||
&self.bold,
|
||||
self.ink(col),
|
||||
numeric(col),
|
||||
);
|
||||
let r = ui
|
||||
.interact(
|
||||
bounds,
|
||||
ui.id().with(("sort traffic", col.title())),
|
||||
Sense::click(),
|
||||
)
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||
let direction = if active && sort.descending {
|
||||
"descending"
|
||||
} else {
|
||||
"ascending"
|
||||
};
|
||||
let hint = if active {
|
||||
format!("{} · Sorted {direction}. Select to reverse.", col.hint())
|
||||
} else {
|
||||
format!("{} · Select to sort.", col.hint())
|
||||
};
|
||||
r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &hint));
|
||||
if widgets::hint(r, &hint).clicked() {
|
||||
clicked = Some(col);
|
||||
}
|
||||
}
|
||||
clicked
|
||||
}
|
||||
pub fn row(&self, ui: &mut Ui, slots: &[Slot], r: &Row, names: &Names, now: u64, index: usize) {
|
||||
let (row, _) = ui.allocate_exact_size(vec2(self.width, self.row_height), Sense::hover());
|
||||
if index % 2 == 1 {
|
||||
ui.painter().rect_filled(row, 0., self.colors.stripe);
|
||||
}
|
||||
let key = &r.data.key;
|
||||
let (near, far, protocol) = endpoints(key, names);
|
||||
let live = now.saturating_sub(r.sampled) < RATE_LIFETIME_MS;
|
||||
for slot in slots {
|
||||
use Column::*;
|
||||
let col = slot.column;
|
||||
let label = match col {
|
||||
Peer => names.peer(&key.network, &key.peer),
|
||||
Network => names.network(&key.network),
|
||||
Near => near.clone(),
|
||||
Far => far.clone(),
|
||||
Protocol => protocol.clone(),
|
||||
Role => role_name(key.role).into(),
|
||||
Sent => bytes(r.data.tx_bytes as f64),
|
||||
Received => bytes(r.data.rx_bytes as f64),
|
||||
SendRate | ReceiveRate => {
|
||||
let rate = if !live {
|
||||
0.
|
||||
} else if col == SendRate {
|
||||
r.tx_rate
|
||||
} else {
|
||||
r.rx_rate
|
||||
};
|
||||
format!("{}/s", bytes(f64::from(rate)))
|
||||
}
|
||||
SentPackets => r.data.tx_packets.to_string(),
|
||||
ReceivedPackets => r.data.rx_packets.to_string(),
|
||||
Seen => ago(now.saturating_sub(r.last)),
|
||||
PeerId => short(&public_id(&key.peer)),
|
||||
};
|
||||
let font = match col {
|
||||
Peer => &self.bold,
|
||||
Near | Far | PeerId => &self.mono,
|
||||
_ => &self.body,
|
||||
};
|
||||
let bounds = slot.rect(row);
|
||||
let response = cell(ui, bounds, &label, font, self.ink(col), numeric(col));
|
||||
if col == PeerId {
|
||||
let full = public_id(&key.peer);
|
||||
let button = ui
|
||||
.interact(
|
||||
bounds,
|
||||
ui.id().with(("copy flow peer", r.id)),
|
||||
Sense::click(),
|
||||
)
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||
button.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Copy peer ID")
|
||||
});
|
||||
if widgets::hint(button, &format!("Copy peer ID\n{full}")).clicked() {
|
||||
ui.ctx().copy_text(full);
|
||||
}
|
||||
} else {
|
||||
widgets::hint(response, &label);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Slot {
|
||||
fn rect(&self, row: Rect) -> Rect {
|
||||
Rect::from_min_size(
|
||||
pos2(row.left() + self.left, row.top()),
|
||||
vec2(self.width, row.height()),
|
||||
)
|
||||
}
|
||||
}
|
||||
fn numeric(c: Column) -> bool {
|
||||
c.descending_first()
|
||||
}
|
||||
fn cell(
|
||||
ui: &mut Ui,
|
||||
bounds: Rect,
|
||||
text: &str,
|
||||
font: &FontId,
|
||||
color: Color32,
|
||||
right: bool,
|
||||
) -> egui::Response {
|
||||
let layout = if right {
|
||||
Layout::right_to_left(Align::Center)
|
||||
} else {
|
||||
Layout::left_to_right(Align::Center)
|
||||
};
|
||||
// Glyph origins are snapped to physical pixels. Leave a point inside each
|
||||
// edge so the overhang of a right-aligned digit or bold header stays visible.
|
||||
let content = bounds.shrink2(vec2(1., 0.));
|
||||
let mut child = ui.new_child(UiBuilder::new().max_rect(content).layout(layout));
|
||||
child.set_clip_rect(ui.clip_rect().intersect(bounds));
|
||||
child.add(
|
||||
egui::Label::new(RichText::new(text).font(font.clone()).color(color))
|
||||
.selectable(false)
|
||||
.truncate(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[test]
|
||||
fn all_columns_are_reachable_without_horizontal_scrolling() {
|
||||
use Column::*;
|
||||
let expected = BTreeSet::from([
|
||||
Network,
|
||||
Near,
|
||||
Far,
|
||||
Protocol,
|
||||
Role,
|
||||
Sent,
|
||||
Received,
|
||||
SendRate,
|
||||
ReceiveRate,
|
||||
SentPackets,
|
||||
ReceivedPackets,
|
||||
Seen,
|
||||
PeerId,
|
||||
]);
|
||||
for size in [15., 20.] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
ctx.style_mut(|s| {
|
||||
s.text_styles
|
||||
.insert(egui::TextStyle::Body, FontId::proportional(size));
|
||||
});
|
||||
for width in [320., 480., 760., 920., 1600.] {
|
||||
let input = egui::RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 400.))),
|
||||
..Default::default()
|
||||
};
|
||||
let _ = ctx.run(input, |ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
style(ui);
|
||||
let grid = Grid::new(ui);
|
||||
let mut seen = BTreeSet::new();
|
||||
for page in &grid.pages {
|
||||
assert_eq!(page[0].column, Peer);
|
||||
for slot in &page[1..] {
|
||||
assert!(seen.insert(slot.column));
|
||||
assert!(
|
||||
slot.width > 0. && slot.left + slot.width <= grid.width + 0.1
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(seen, expected);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
#![allow(clippy::unwrap_used, clippy::panic)]
|
||||
use super::history::*;
|
||||
use tsunagi::traffic::*;
|
||||
|
||||
@@ -42,7 +42,7 @@ fn window_history_expires_and_long_capture_is_paged_and_bidirectional() {
|
||||
assert_eq!(p.rows.len(), PAGE_SIZE);
|
||||
assert!(p.more);
|
||||
let next = Filter {
|
||||
before: Some(p.rows.last().unwrap().id),
|
||||
before: Some(p.rows.last().unwrap().cursor()),
|
||||
..filter.clone()
|
||||
};
|
||||
assert!(
|
||||
@@ -133,48 +133,295 @@ fn private_cache_file_is_unlinked_and_remains_writable_across_transactions() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn live_monitor_has_readable_rows_inside_phone_and_desktop_widths() {
|
||||
use super::Window;
|
||||
use std::time::{Duration, Instant};
|
||||
let mut win = Window::new(None);
|
||||
let feed = win.feed();
|
||||
assert!(win.worker.view().0.rows.is_empty());
|
||||
feed.sample(TrafficSnapshot {
|
||||
flows: vec![sample(55201, true)],
|
||||
interval_ms: 1_000,
|
||||
omitted: 0,
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
while win.worker.view().0.rows.is_empty() {
|
||||
assert!(Instant::now() < deadline, "worker did not publish the flow");
|
||||
std::thread::yield_now();
|
||||
}
|
||||
for width in [320., 390., 720., 900.] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
let frame = ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, 600.),
|
||||
)),
|
||||
..Default::default()
|
||||
fn sorting_uses_the_entire_filtered_capture_and_pages_through_ties() {
|
||||
use super::{Column, Sort};
|
||||
let mut db = History::open(None).unwrap();
|
||||
let mut data: Vec<_> = (0..150)
|
||||
.map(|port| {
|
||||
let mut flow = sample(port, true);
|
||||
flow.tx_bytes = u64::from((port * 7) % 13) * 1024;
|
||||
flow
|
||||
})
|
||||
.collect();
|
||||
let mut foreign = sample(443, true);
|
||||
foreign.key.network = [7; 32];
|
||||
foreign.tx_bytes = 99_000_000;
|
||||
data.push(foreign);
|
||||
db.apply(&data, 1000, 1000, true).unwrap();
|
||||
for descending in [false, true] {
|
||||
let mut filter = Filter {
|
||||
network: Some([1; 32]),
|
||||
sort: Sort {
|
||||
column: Column::Sent,
|
||||
descending,
|
||||
},
|
||||
|ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
win.show(ui, None, 0);
|
||||
assert!(
|
||||
ui.min_rect().right() <= width,
|
||||
"monitor grew beyond {width}: {:?}",
|
||||
ui.min_rect()
|
||||
);
|
||||
});
|
||||
..Default::default()
|
||||
};
|
||||
let mut seen = Vec::new();
|
||||
loop {
|
||||
let page = db.page(&filter).unwrap();
|
||||
seen.extend(page.rows.iter().map(|r| (r.data.tx_bytes, r.id)));
|
||||
if !page.more {
|
||||
break;
|
||||
}
|
||||
filter.before = Some(page.rows.last().unwrap().cursor());
|
||||
}
|
||||
assert_eq!(seen.len(), 150);
|
||||
assert!(seen.windows(2).all(|pair| if descending {
|
||||
pair[0] > pair[1]
|
||||
} else {
|
||||
pair[0] < pair[1]
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stale_member_name_does_not_reindex_the_capture_every_refresh() {
|
||||
use tsunagi::ipc::{MemberReport, NetworkReport, PeerReport, StatusReport};
|
||||
let peer = tsunagi::identity::DeviceIdentity::from_secret_bytes(&[9; 32]).endpoint_id();
|
||||
let network = tsunagi::NetworkId::from_bytes([3; 32]);
|
||||
let mut report = StatusReport {
|
||||
networks: vec![NetworkReport {
|
||||
network_id: network.to_string(),
|
||||
name: "lab".into(),
|
||||
members: vec![MemberReport {
|
||||
endpoint_id: peer.to_string(),
|
||||
hostname: Some("old".into()),
|
||||
..Default::default()
|
||||
}],
|
||||
peers: vec![PeerReport {
|
||||
endpoint_id: peer.to_string(),
|
||||
hostname: Some("current".into()),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
let mut names = super::Names::default();
|
||||
assert!(names.refresh(Some(&report), 1));
|
||||
assert_eq!(names.peer(network.as_bytes(), peer.as_bytes()), "current");
|
||||
assert!(!names.refresh(Some(&report), 2));
|
||||
report.networks[0].peers[0].hostname = None;
|
||||
assert!(names.refresh(Some(&report), 3));
|
||||
assert_eq!(names.peer(network.as_bytes(), peer.as_bytes()), "old");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sorting_uses_display_names_numeric_endpoints_and_live_rates() {
|
||||
use super::{Column, Names, Network, Sort};
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
let mut db = History::open(None).unwrap();
|
||||
let first = sample(200, true);
|
||||
let mut second = sample(9, true);
|
||||
second.key.peer = [3; 32];
|
||||
if let Flow::Ip { ref mut far, .. } = second.key.flow {
|
||||
*far = [10, 0, 0, 10];
|
||||
}
|
||||
second.tx_bytes = 250;
|
||||
let mut names = Names::default();
|
||||
names.networks.insert(
|
||||
[1; 32],
|
||||
Network {
|
||||
name: "lab".into(),
|
||||
peers: BTreeMap::from([([2; 32], "zeta".into()), ([3; 32], "Alpha".into())]),
|
||||
},
|
||||
);
|
||||
db.use_names(Arc::new(names.clone()));
|
||||
db.apply(&[first.clone(), second.clone()], 1000, 1000, true)
|
||||
.unwrap();
|
||||
let filter = |column| Filter {
|
||||
sort: Sort {
|
||||
column,
|
||||
descending: false,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
db.page(&filter(Column::Peer)).unwrap().rows[0]
|
||||
.data
|
||||
.key
|
||||
.peer,
|
||||
[3; 32]
|
||||
);
|
||||
names
|
||||
.networks
|
||||
.get_mut(&[1; 32])
|
||||
.unwrap()
|
||||
.peers
|
||||
.insert([2; 32], "aardvark".into());
|
||||
db.use_names(Arc::new(names));
|
||||
for (column, id) in [(Column::Peer, 2), (Column::Near, 3), (Column::Far, 2)] {
|
||||
assert_eq!(
|
||||
db.page(&filter(column)).unwrap().rows[0].data.key.peer,
|
||||
[id; 32]
|
||||
);
|
||||
}
|
||||
db.apply(&[first], 3000, 1000, true).unwrap();
|
||||
let speeds = db.page(&filter(Column::SendRate)).unwrap();
|
||||
assert_eq!(
|
||||
(speeds.rows[0].data.key.peer, speeds.rows[0].tx_rate),
|
||||
([3; 32], 0.)
|
||||
);
|
||||
assert!(speeds.rows[1].tx_rate > 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_rows_stay_on_one_line_and_headers_sort_in_both_themes() {
|
||||
use super::{Column, Network, Window};
|
||||
use egui::{Color32, Context, Event, Pos2, Rect, Shape, Theme};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
for (theme, width) in [
|
||||
(Theme::Dark, 920.),
|
||||
(Theme::Light, 920.),
|
||||
(Theme::Dark, 320.),
|
||||
] {
|
||||
let ctx = Context::default();
|
||||
ctx.set_theme(theme);
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
let mut win = Window::new(None);
|
||||
win.names.networks.insert(
|
||||
[1; 32],
|
||||
Network {
|
||||
name: "lab".into(),
|
||||
peers: [([2; 32], "alder".into()), ([3; 32], "birch".into())].into(),
|
||||
},
|
||||
);
|
||||
for value in ["10.0.0.1:55201", "10.0.0.2:443", "TCP", "Mesh"] {
|
||||
assert!(frame.shapes.iter().any(|s|matches!(&s.shape,egui::Shape::Text(t) if t.galley.text().contains(value) && t.visual_bounding_rect().right()<=width)), "{value} outside {width}");
|
||||
let left = sample(55201, true);
|
||||
let mut right = sample(7, false);
|
||||
right.key.peer = [3; 32];
|
||||
let feed = win.feed();
|
||||
assert!(win.worker.view().0.rows.is_empty());
|
||||
feed.sample(TrafficSnapshot {
|
||||
flows: vec![left, right],
|
||||
interval_ms: 1000,
|
||||
omitted: 0,
|
||||
});
|
||||
let wait = |win: &Window| {
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
while win.worker.view().0.rows.len() != 2 {
|
||||
assert!(Instant::now() < deadline);
|
||||
std::thread::yield_now();
|
||||
}
|
||||
};
|
||||
wait(&win);
|
||||
let draw = |win: &mut Window, events: Vec<Event>| {
|
||||
ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(width, 480.))),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
win.show(ui, None, 0);
|
||||
assert!(ui.min_rect().right() <= width);
|
||||
});
|
||||
},
|
||||
)
|
||||
};
|
||||
let label = |frame: &egui::FullOutput, value: &str| {
|
||||
frame
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
Shape::Text(t) if t.galley.text() == value => {
|
||||
let section = &t.galley.job.sections[0].format;
|
||||
assert!(
|
||||
section.font_id.size >= 14.,
|
||||
"{value} at {}",
|
||||
section.font_id.size
|
||||
);
|
||||
assert!(
|
||||
s.clip_rect.contains_rect(t.visual_bounding_rect()),
|
||||
"{value} clipped at {width}: {:?} outside {:?}",
|
||||
t.visual_bounding_rect(),
|
||||
s.clip_rect
|
||||
);
|
||||
Some((
|
||||
t.visual_bounding_rect(),
|
||||
t.override_text_color.unwrap_or(section.color),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing {value} at {width}"))
|
||||
};
|
||||
let click = |win: &mut Window, pos| {
|
||||
for pressed in [true, false] {
|
||||
draw(
|
||||
win,
|
||||
vec![
|
||||
Event::PointerMoved(pos),
|
||||
Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
wait(win);
|
||||
};
|
||||
let mut frame = draw(&mut win, vec![]);
|
||||
let chooser = frame
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
Shape::Text(t) if t.galley.text().contains("Columns 1/") => {
|
||||
Some(t.visual_bounding_rect())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(
|
||||
chooser.right() < width,
|
||||
"column chooser is outside the viewport at {width}"
|
||||
);
|
||||
let (peer, _) = label(&frame, "alder");
|
||||
let (sent, ink) = label(&frame, "90 B");
|
||||
let (header, _) = label(&frame, "Sent");
|
||||
assert!((peer.center().y - sent.center().y).abs() < 2.);
|
||||
assert!((label(&frame, "birch").0.center().y - peer.center().y).abs() < 34.);
|
||||
assert!((sent.right() - header.right()).abs() < 2.);
|
||||
assert!(sent.left() > width * 0.33 || width < 400.);
|
||||
let bg = if theme == Theme::Dark {
|
||||
Color32::from_gray(35)
|
||||
} else {
|
||||
Color32::from_gray(239)
|
||||
};
|
||||
let luminance = |c: Color32| {
|
||||
let v = egui::Rgba::from(c);
|
||||
0.2126 * v.r() + 0.7152 * v.g() + 0.0722 * v.b()
|
||||
};
|
||||
let (a, b) = (luminance(ink), luminance(bg));
|
||||
assert!(
|
||||
(a.max(b) + 0.05) / (a.min(b) + 0.05) >= 4.5,
|
||||
"contrast of {ink:?} at {width}"
|
||||
);
|
||||
click(&mut win, peer.center());
|
||||
frame = draw(&mut win, vec![]);
|
||||
assert!(!frame.shapes.iter().any(
|
||||
|s| matches!(&s.shape,Shape::Text(t) if t.galley.text().contains("packets sent"))
|
||||
));
|
||||
assert!(
|
||||
(label(&frame, "birch").0.center().y - label(&frame, "alder").0.center().y).abs() < 34.
|
||||
);
|
||||
for descending in [true, false] {
|
||||
click(&mut win, header.center());
|
||||
assert_eq!(
|
||||
(win.filter.sort.column, win.filter.sort.descending),
|
||||
(Column::Sent, descending)
|
||||
);
|
||||
frame = draw(&mut win, vec![]);
|
||||
assert_eq!(
|
||||
label(&frame, "alder").0.top() < label(&frame, "birch").0.top(),
|
||||
descending
|
||||
);
|
||||
}
|
||||
drop(win);
|
||||
assert!(!feed.sample(TrafficSnapshot::default()));
|
||||
}
|
||||
drop(win);
|
||||
assert!(!feed.sample(TrafficSnapshot::default()));
|
||||
}
|
||||
@@ -1,15 +1,19 @@
|
||||
use super::history::{Filter, History, Page};
|
||||
use super::{
|
||||
Names,
|
||||
history::{Filter, History, Page},
|
||||
};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
path::PathBuf,
|
||||
sync::{Arc, Condvar, Mutex, MutexGuard},
|
||||
time::Instant,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tsunagi::traffic::TrafficSnapshot;
|
||||
|
||||
struct Work {
|
||||
samples: VecDeque<(u64, TrafficSnapshot)>,
|
||||
filter: Filter,
|
||||
names: Arc<Names>,
|
||||
keep: bool,
|
||||
dirty: bool,
|
||||
closed: bool,
|
||||
@@ -79,6 +83,7 @@ impl Worker {
|
||||
state: Mutex::new(Work {
|
||||
samples: VecDeque::new(),
|
||||
filter: Filter::default(),
|
||||
names: Arc::default(),
|
||||
keep: false,
|
||||
dirty: true,
|
||||
closed: false,
|
||||
@@ -110,6 +115,12 @@ impl Worker {
|
||||
pub fn protocols(&self) -> Vec<u8> {
|
||||
self.feed.0.lock().protocols.iter().copied().collect()
|
||||
}
|
||||
pub fn names(&self, names: Arc<Names>) {
|
||||
let mut w = self.feed.0.lock();
|
||||
w.names = names;
|
||||
w.dirty = true;
|
||||
self.feed.0.wake.notify_one();
|
||||
}
|
||||
pub fn options(&self, filter: Filter, keep: bool) {
|
||||
let mut w = self.feed.0.lock();
|
||||
if w.filter != filter {
|
||||
@@ -142,18 +153,26 @@ fn run(shared: &Shared, directory: Option<PathBuf>) -> Result<(), String> {
|
||||
let mut db = History::open(directory.as_deref())?;
|
||||
shared.lock().interrupt = Some(db.interrupt());
|
||||
loop {
|
||||
let (mut samples, filter, keep) = {
|
||||
let (mut samples, filter, keep, names) = {
|
||||
let w = shared.lock();
|
||||
let mut w = shared
|
||||
let (mut w, _) = shared
|
||||
.wake
|
||||
.wait_while(w, |w| !w.closed && !w.dirty && w.samples.is_empty())
|
||||
.wait_timeout_while(w, Duration::from_secs(1), |w| {
|
||||
!w.closed && !w.dirty && w.samples.is_empty()
|
||||
})
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
if w.closed {
|
||||
return Ok(());
|
||||
}
|
||||
w.dirty = false;
|
||||
(std::mem::take(&mut w.samples), w.filter.clone(), w.keep)
|
||||
(
|
||||
std::mem::take(&mut w.samples),
|
||||
w.filter.clone(),
|
||||
w.keep,
|
||||
w.names.clone(),
|
||||
)
|
||||
};
|
||||
db.use_names(names.clone());
|
||||
if samples.is_empty() {
|
||||
db.apply(&[], shared.start.elapsed().as_millis() as u64, 0, keep)?;
|
||||
}
|
||||
@@ -162,7 +181,7 @@ fn run(shared: &Shared, directory: Option<PathBuf>) -> Result<(), String> {
|
||||
}
|
||||
let page = Arc::new(db.page(&filter)?);
|
||||
let mut w = shared.lock();
|
||||
if !w.closed && filter == w.filter {
|
||||
if !w.closed && filter == w.filter && Arc::ptr_eq(&names, &w.names) {
|
||||
w.page = page;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user