Keep Android exit lists scrolling and test exits by network

Deliver the primary touch release to egui one frame before clearing the pointer. This preserves the velocity that ScrollArea uses for a fling. Cancellations clear it immediately and a new primary touch takes precedence.

Add a speedometer to each network heading in the exit chooser. It reuses the Devices batch command and capability checks. Show queued or measured results in the existing rows and let the same control stop the batch without selecting a different exit.

Verified scroll deceleration, cancellation, consecutive gestures and per-network start/stop with egui input tests. The Android ARM64 check, formatting and workspace Clippy passed. The macOS workspace suite passed 673 tests with 7 ignored.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-26 02:58:21 +02:00
1 parent 7b83aec3be
commit 8e0cfc97ac
9 files changed
+359 -88

No files matched your search

+11 -37
View File
@@ -1,8 +1,9 @@
//! Android owns the GLES surface, keyboard and clipboard. egui owns the widgets.
use crate::view::{Phone, SystemAction};
use egui::{
Event, ImeEvent, Key, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase,
use crate::{
touch::TouchInput,
view::{Phone, SystemAction},
};
use egui::{Event, ImeEvent, Key, Modifiers, Pos2, TouchPhase};
use egui_glow::{Painter, glow};
use jni::{
JNIEnv,
@@ -26,7 +27,7 @@ struct Display {
ctx: egui::Context,
ui: Phone,
events: Vec<Event>,
primary: Option<i32>,
touch: TouchInput,
start: Instant,
ime: i32,
exit_active: bool,
@@ -81,7 +82,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(
ctx,
ui,
events: Vec::new(),
primary: None,
touch: TouchInput::default(),
start: Instant::now(),
ime: -1,
exit_active: false,
@@ -104,7 +105,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
let size = egui::vec2(w as f32, h as f32) / scale;
let mut input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
events: std::mem::take(&mut d.events),
events: d.touch.take_frame(&mut d.events),
time: Some(d.start.elapsed().as_secs_f64()),
..Default::default()
};
@@ -122,6 +123,9 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
}
d.exit_active = exit_active;
let output = d.ctx.run(input, |ctx| {
if !d.events.is_empty() {
ctx.request_repaint();
}
action = d.ui.draw(ctx, &state, super::send).or(action);
});
d.ui.poll_monitor(|| super::submit(crate::service::Request::WatchTraffic));
@@ -201,37 +205,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_touch(
2 => TouchPhase::End,
_ => TouchPhase::Cancel,
};
d.events.push(Event::Touch {
device_id: TouchDeviceId(0),
id: TouchId(id as u64),
phase,
pos,
force: None,
});
if phase == TouchPhase::Start && d.primary.is_none() {
d.primary = Some(id);
}
if d.primary != Some(id) {
return;
}
if phase != TouchPhase::Cancel {
d.events.push(Event::PointerMoved(pos));
}
if phase != TouchPhase::Move {
if phase == TouchPhase::Cancel {
d.events.push(Event::PointerGone);
}
d.events.push(Event::PointerButton {
pos,
button: PointerButton::Primary,
pressed: phase == TouchPhase::Start,
modifiers: Modifiers::NONE,
});
}
if matches!(phase, TouchPhase::Cancel | TouchPhase::End) {
d.events.push(Event::PointerGone);
d.primary = None;
}
d.touch.push(&mut d.events, phase, id, pos);
});
}
#[unsafe(no_mangle)]
+2
View File
@@ -9,6 +9,8 @@ mod android;
pub mod service;
#[cfg(test)]
mod tests;
#[cfg(any(target_os = "android", test))]
mod touch;
#[cfg(unix)]
pub mod tun;
pub mod view;
+161
View File
@@ -0,0 +1,161 @@
//! Translate Android fingers into egui touch events and one primary pointer.
use egui::{Event, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase};
#[derive(Default)]
pub(crate) struct TouchInput {
primary: Option<i32>,
clear_after_release: bool,
}
impl TouchInput {
pub(crate) fn push(&mut self, events: &mut Vec<Event>, phase: TouchPhase, id: i32, pos: Pos2) {
events.push(Event::Touch {
device_id: TouchDeviceId(0),
id: TouchId(id as u64),
phase,
pos,
force: None,
});
if phase == TouchPhase::Start && self.primary.is_none() {
self.primary = Some(id);
self.clear_after_release = false;
}
if self.primary != Some(id) {
return;
}
if phase != TouchPhase::Cancel {
events.push(Event::PointerMoved(pos));
}
if phase != TouchPhase::Move {
events.push(Event::PointerButton {
pos,
button: PointerButton::Primary,
pressed: phase == TouchPhase::Start,
modifiers: Modifiers::NONE,
});
}
match phase {
TouchPhase::End => {
self.primary = None;
self.clear_after_release = true;
}
TouchPhase::Cancel => {
self.primary = None;
events.push(Event::PointerGone);
}
_ => {}
}
}
pub(crate) fn take_frame(&mut self, events: &mut Vec<Event>) -> Vec<Event> {
let frame = std::mem::take(events);
// ScrollArea reads the release velocity in this frame. PointerGone clears
// egui's position history, so clear the touch hover in the following frame.
if std::mem::take(&mut self.clear_after_release) {
events.push(Event::PointerGone);
}
frame
}
}
#[cfg(test)]
mod tests {
use super::*;
use egui::{CentralPanel, Context, RawInput, Rect, ScrollArea, pos2, vec2};
#[test]
fn a_flick_coasts_and_slows_while_a_cancelled_drag_stops() {
for end in [TouchPhase::End, TouchPhase::Cancel] {
let ctx = Context::default();
ctx.set_os(egui::os::OperatingSystem::Android);
let mut input = TouchInput::default();
let mut events = Vec::new();
let mut frame_no = 0;
let mut frame = |touch| {
if let Some((phase, y)) = touch {
input.push(&mut events, phase, 0, pos2(80., y));
}
frame_no += 1;
let mut offset = 0.;
let _ = ctx.run(
RawInput {
time: Some(f64::from(frame_no) / 60.),
events: input.take_frame(&mut events),
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(320., 320.))),
..Default::default()
},
|ctx| {
CentralPanel::default().show(ctx, |ui| {
offset = ScrollArea::vertical()
.auto_shrink([false, false])
.show(ui, |ui| {
for i in 0..60 {
ui.add_sized(
[270., 40.],
egui::Button::new(format!("Peer {i}")),
);
}
})
.state
.offset
.y;
});
},
);
offset
};
// The first layout measures the content. The next registers its drag area.
frame(None);
frame(None);
frame(Some((TouchPhase::Start, 220.)));
for y in [208., 190., 168., 146.] {
frame(Some((TouchPhase::Move, y)));
}
let released = frame(Some((end, 126.)));
let first = frame(None);
let second = frame(None);
assert!(released > 0., "{end:?} should follow a drag");
if end == TouchPhase::End {
assert!(
second > first && first > released,
"the scroll should coast after release"
);
assert!(
second - first < first - released,
"the fling should decelerate"
);
} else {
assert_eq!((released, first), (first, second));
}
}
}
#[test]
fn a_new_primary_touch_supersedes_a_release_in_the_same_frame() {
let mut input = TouchInput::default();
let mut events = Vec::new();
for (phase, id) in [
(TouchPhase::Start, 1),
(TouchPhase::End, 1),
(TouchPhase::Start, 2),
] {
input.push(&mut events, phase, id, Pos2::ZERO);
}
let frame = input.take_frame(&mut events);
assert!(matches!(
frame.last(),
Some(Event::PointerButton { pressed: true, .. })
));
assert!(events.is_empty());
input.push(&mut events, TouchPhase::End, 2, Pos2::ZERO);
let release = input.take_frame(&mut events);
assert!(matches!(
release.last(),
Some(Event::PointerButton { pressed: false, .. })
));
assert!(matches!(
input.take_frame(&mut events).as_slice(),
[Event::PointerGone]
));
}
}
+1 -1
View File
@@ -493,7 +493,7 @@ impl Phone {
if ui.button(format!("{} Paste secret", icon::CLIPBOARD)).clicked() {system = Some(SystemAction::PasteSecret);}
}
Page::Exits => {
if let Some(choice) = devices::choose_exit_from_networks(ui, &report.networks, &report.endpoint_id) {
if let Some(choice) = devices::choose_exit_with_tests(ui, &report.networks, &report.endpoint_id, &actions) {
self.forms.exit_confirm = Some(choice);
}
if report.networks.is_empty() && ui.button("Join or create a network").clicked() {
+4 -2
View File
@@ -13,7 +13,9 @@ mod speed;
mod speed_tests;
mod status;
pub use crate::exit::name_of;
pub use exit_picker::{choose_exit, choose_exit_from_networks, exit_action_colors};
pub use exit_picker::{
choose_exit, choose_exit_from_networks, choose_exit_with_tests, exit_action_colors,
};
use egui_phosphor::regular as icon;
@@ -244,7 +246,7 @@ pub fn show(
"devices ({online} online / {} known)",
devices.len()
));
speed.toolbar(ui);
speed.batch_button(ui, false);
});
};
+57 -20
View File
@@ -1,5 +1,5 @@
//! One touch target per exit, grouped by the network that will carry the traffic.
use super::{ExitConfirm, devices};
use super::{Client, ExitConfirm, devices, speed};
use crate::{exit, format, widgets};
use egui::{Align, Align2, Color32, FontFamily, FontId, Rect, Sense, Ui, pos2, vec2};
use egui_phosphor::regular as icon;
@@ -15,6 +15,25 @@ pub fn choose_exit_from_networks(
ui: &mut Ui,
networks: &[NetworkReport],
own: &str,
) -> Option<ExitConfirm> {
chooser(ui, networks, own, None)
}
/// The interactive Android picker can also measure every eligible exit in one network.
pub fn choose_exit_with_tests(
ui: &mut Ui,
networks: &[NetworkReport],
own: &str,
client: &dyn Client,
) -> Option<ExitConfirm> {
chooser(ui, networks, own, Some(client))
}
fn chooser(
ui: &mut Ui,
networks: &[NetworkReport],
own: &str,
client: Option<&dyn Client>,
) -> Option<ExitConfirm> {
let current = networks
.iter()
@@ -28,7 +47,7 @@ pub fn choose_exit_from_networks(
glyph: icon::GLOBE,
};
let mut choice = None;
if local.draw(ui, "local internet")
if local.draw(ui, "local internet", None)
&& let Some((network, id)) = current
{
choice = Some(ExitConfirm::stop_from_tile(network, id));
@@ -64,17 +83,30 @@ pub fn choose_exit_from_networks(
network.name.clone()
};
ui.add_space(10.);
let (header, hint) =
ui.allocate_exact_size(vec2(ui.available_width(), 30.), Sense::hover());
widgets::single_line(
ui.painter(),
header,
Align::Min,
&title,
bold(19.),
ui.visuals().strong_text_color(),
);
widgets::hint(hint, &network.network_id);
ui.push_id(&network.network_id, |ui| {
ui.horizontal(|ui| {
let (height, button_space) = if client.is_some() {
(44., 44. + ui.spacing().item_spacing.x)
} else {
(30., 0.)
};
let title_width = (ui.available_width() - button_space).max(0.);
let (header, hint) =
ui.allocate_exact_size(vec2(title_width, height), Sense::hover());
widgets::single_line(
ui.painter(),
header,
Align::Min,
&title,
bold(19.),
ui.visuals().strong_text_color(),
);
widgets::hint(hint, &network.network_id);
if let Some(client) = client {
speed::Controls::new(network, client).batch_button(ui, true);
}
});
});
if let Some(rules) = &network.exit.client_rules
&& !rules.ok
{
@@ -94,7 +126,7 @@ pub fn choose_exit_from_networks(
selected: true,
glyph: icon::SIGN_OUT,
}
.draw(ui, (&network.network_id, id));
.draw(ui, (&network.network_id, id), None);
}
for d in candidates {
let name = d.name();
@@ -112,15 +144,17 @@ pub fn choose_exit_from_networks(
}
};
let latency = d.data_rtt_ms.map(|ms| format!("{ms} ms"));
let speed = network.speed.peers.get(d.id).map(speed::exit_caption);
let address = d.address.as_deref();
let row = Row {
name: &name,
caption: d.address.as_deref().unwrap_or(""),
caption: speed.as_deref().or(address).unwrap_or(""),
latency: latency.as_deref(),
path: Some(&path),
selected: d.in_use,
glyph: icon::SIGN_OUT,
};
if row.draw(ui, (&network.network_id, d.id)) && !d.in_use {
if row.draw(ui, (&network.network_id, d.id), address) && !d.in_use {
choice = Some(ExitConfirm {
network_id: network.network_id.clone(),
peer_id: d.id.into(),
@@ -159,7 +193,7 @@ struct Row<'a> {
glyph: &'static str,
}
impl Row<'_> {
fn draw(&self, ui: &mut Ui, id: impl std::hash::Hash) -> bool {
fn draw(&self, ui: &mut Ui, id: impl std::hash::Hash, hint: Option<&str>) -> bool {
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 58.), Sense::hover());
let response = ui.interact(
rect,
@@ -273,9 +307,12 @@ impl Row<'_> {
detail,
);
}
response
.on_hover_cursor(egui::CursorIcon::PointingHand)
.clicked()
let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
match hint {
Some(hint) => widgets::hint(response, hint),
None => response,
}
.clicked()
}
}
+51 -28
View File
@@ -29,21 +29,15 @@ impl<'a> Controls<'a> {
self.network.speed.capable.iter().any(|peer| peer == id)
}
pub(super) fn toolbar(&self, ui: &mut Ui) {
let (label, help, available) = if self.running {
pub(super) fn batch_button(&self, ui: &mut Ui, icon_only: bool) {
let (glyph, 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_CIRCLE),
|batch| {
format!(
"{} Stop {}/{}",
icon::STOP_CIRCLE,
batch.done,
batch.total
)
},
|| "Stop test".to_owned(),
|batch| format!("Stop {}/{}", batch.done, batch.total),
);
(
icon::STOP_CIRCLE,
label,
"Stop this speed test and skip any queued exits.",
true,
@@ -56,7 +50,8 @@ impl<'a> Controls<'a> {
.iter()
.any(|p| p.exit_node && self.capable(&p.endpoint_id));
(
format!("{} Test exits", icon::GAUGE),
icon::GAUGE,
"Test exits".to_owned(),
if available {
"Test each compatible online exit node in this network, one at a time."
} else {
@@ -65,22 +60,26 @@ impl<'a> Controls<'a> {
available,
)
};
// Leave room for the batch count before starting. A wrapping toolbar
// must keep the same height when the button becomes Stop.
let width = ui
.painter()
.layout_no_wrap(
format!("{} Stop 9999/9999", icon::STOP_CIRCLE),
egui::TextStyle::Button.resolve(ui.style()),
ui.visuals().text_color(),
)
.size()
.x
+ 2. * ui.spacing().button_padding.x;
let button = ui.add_enabled(
available && !self.client.busy(),
egui::Button::new(label).min_size(vec2(width, 0.)),
);
let button = if icon_only {
egui::Button::new(egui::RichText::new(glyph).size(22.)).min_size(vec2(44., 44.))
} else {
// Switching to Stop must not wrap a toolbar onto a second line.
let width = ui
.painter()
.layout_no_wrap(
format!("{} Stop 9999/9999", icon::STOP_CIRCLE),
egui::TextStyle::Button.resolve(ui.style()),
ui.visuals().text_color(),
)
.size()
.x
+ 2. * ui.spacing().button_padding.x;
egui::Button::new(format!("{glyph} {label}")).min_size(vec2(width, 0.))
};
let button = ui.add_enabled(available && !self.client.busy(), button);
button.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, button.enabled(), &label)
});
if widgets::hint(button, help).clicked() {
let network_id = self.network.network_id.clone();
let command = if self.running {
@@ -132,6 +131,30 @@ impl<'a> Controls<'a> {
}
}
pub(super) fn exit_caption(test: &SpeedPeerReport) -> String {
match test.phase {
SpeedPhase::Queued => "Queued".into(),
SpeedPhase::Preparing => "Starting…".into(),
SpeedPhase::Cancelled => "Stopped".into(),
SpeedPhase::Failed(_) => "Test failed".into(),
SpeedPhase::Download | SpeedPhase::Upload | SpeedPhase::Done => {
let rate = |value: Option<SpeedRate>, phase| {
value.map_or_else(
|| if test.phase == phase { "…" } else { "—" }.into(),
compact_rate,
)
};
format!(
"{} {} {} {} Mbit/s",
icon::ARROW_DOWN,
rate(test.down, SpeedPhase::Download),
icon::ARROW_UP,
rate(test.up, SpeedPhase::Upload)
)
}
}
}
fn paint_reading(
ui: &Ui,
rect: Rect,
@@ -52,6 +52,76 @@ fn reading(phase: SpeedPhase) -> SpeedPeerReport {
}
}
#[test]
fn exit_picker_tests_only_the_tapped_network_and_keeps_the_route_selection() {
let screen = Screen::new(320., true);
let a = network();
let mut b = network();
b.name = "office".into();
b.network_id = "office-id".into();
b.exit.via = Some("alice".into());
let mut nets = [a, b];
let draw = |nets: &[NetworkReport], events| {
screen.ctx.run(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(320., 650.),
)),
events,
..Default::default()
},
|ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
assert!(choose_exit_with_tests(ui, nets, "self", &screen.log).is_none());
assert!(ui.min_rect().right() <= 320.);
});
},
)
};
let tap = |nets: &[NetworkReport], pos| {
for pressed in [true, false] {
draw(
nets,
vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
},
],
);
}
};
let first = draw(&nets, vec![]);
let gauges = positions(&first, |s| s == icon::GAUGE);
assert_eq!(gauges.len(), 2);
let office = positions(&first, |s| s == "office")[0];
let button = *gauges.iter().find(|p| (p.y - office.y).abs() < 4.).unwrap();
tap(&nets, button);
assert!(
matches!(screen.log.0.borrow().as_slice(), [Command::StartSpeedTest { network_id, peer: None }] if network_id == "office-id")
);
nets[1].speed.batch = Some(SpeedBatchReport { done: 0, total: 1 });
nets[1]
.speed
.peers
.insert("alice".into(), reading(SpeedPhase::Upload));
let live = draw(&nets, vec![]);
assert!(!positions(&live, |s| s.contains("125") && s.contains("Mbit/s")).is_empty());
let stop = positions(&live, |s| s == icon::STOP_CIRCLE)[0];
tap(&nets, stop);
assert!(
matches!(screen.log.0.borrow().last(), Some(Command::StopSpeedTest { network_id }) if network_id == "office-id")
);
nets[1].speed = Default::default();
draw(&nets, vec![]);
tap(&nets, button);
assert_eq!(screen.log.0.borrow().len(), 2);
}
struct Screen {
ctx: egui::Context,
width: f32,