From e3e6089d0b20c5a182c79338362e9cbf5d70ace0 Mon Sep 17 00:00:00 2001 From: Aleksandr Bogomiakov Date: Wed, 25 Nov 2026 15:38:10 +0200 Subject: [PATCH] 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. --- android/README.md | 4 + .../java/cy/hexor/tsunagi/ExitTileTest.kt | 33 ++ android/app/src/main/AndroidManifest.xml | 8 + .../main/java/cy/hexor/tsunagi/ExitTile.kt | 113 +++++++ .../java/cy/hexor/tsunagi/MainActivity.kt | 18 + .../main/java/cy/hexor/tsunagi/MeshSurface.kt | 6 +- .../src/main/java/cy/hexor/tsunagi/MeshVpn.kt | 13 +- .../src/main/java/cy/hexor/tsunagi/Native.kt | 3 +- .../app/src/main/res/drawable/exit_tile.xml | 6 + crates/tsunagi-android/src/android/display.rs | 14 +- crates/tsunagi-android/src/android/mod.rs | 54 ++- crates/tsunagi-android/src/service.rs | 68 ++++ crates/tsunagi-android/src/tests.rs | 155 ++++++++- crates/tsunagi-android/src/view.rs | 159 ++++++++- crates/tsunagi-core/src/agent/mod.rs | 7 +- crates/tsunagi-core/src/agent/network.rs | 14 +- crates/tsunagi-core/src/agent/status.rs | 5 + crates/tsunagi-tray/src/ui.rs | 2 +- crates/tsunagi-ui/src/about.rs | 19 +- crates/tsunagi-ui/src/devices.rs | 176 +++++----- crates/tsunagi-ui/src/devices/compact.rs | 270 +++++++++++---- crates/tsunagi-ui/src/devices/status.rs | 98 ++++++ crates/tsunagi-ui/src/format.rs | 5 +- crates/tsunagi-ui/src/home.rs | 320 ++++++++++++------ crates/tsunagi-ui/src/lib.rs | 3 + crates/tsunagi-ui/src/presentation_tests.rs | 249 ++++++++++++++ crates/tsunagi-ui/src/vip.rs | 27 +- crates/tsunagi-ui/src/vip_status.rs | 82 +++-- crates/tsunagi-ui/src/widgets.rs | 81 +++++ 29 files changed, 1688 insertions(+), 324 deletions(-) create mode 100644 android/app/src/androidTest/java/cy/hexor/tsunagi/ExitTileTest.kt create mode 100644 android/app/src/main/java/cy/hexor/tsunagi/ExitTile.kt create mode 100644 android/app/src/main/res/drawable/exit_tile.xml create mode 100644 crates/tsunagi-ui/src/devices/status.rs create mode 100644 crates/tsunagi-ui/src/presentation_tests.rs create mode 100644 crates/tsunagi-ui/src/widgets.rs diff --git a/android/README.md b/android/README.md index 160a263..e466166 100644 --- a/android/README.md +++ b/android/README.md @@ -26,8 +26,12 @@ Applications using Android’s system resolver can connect to `. + + + + + + diff --git a/android/app/src/main/java/cy/hexor/tsunagi/ExitTile.kt b/android/app/src/main/java/cy/hexor/tsunagi/ExitTile.kt new file mode 100644 index 0000000..993c19c --- /dev/null +++ b/android/app/src/main/java/cy/hexor/tsunagi/ExitTile.kt @@ -0,0 +1,113 @@ +package cy.hexor.tsunagi + +import android.app.PendingIntent +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.service.quicksettings.Tile +import android.service.quicksettings.TileService +import android.widget.Toast + +/** Quick Settings changes the internet exit of the existing mesh agent. */ +class ExitTile : TileService() { + internal data class Target(val network: String, val peer: String, val name: String) + private data class Snapshot(val session: Long, val active: Target?, val online: Boolean) + + companion object { + internal fun entry(context: Context) = ComponentName(context, "${context.packageName}.OpenExit") + private var live = Snapshot(0, null, false) + private var pending = false + private val main = Handler(Looper.getMainLooper()) + + internal fun last(context: Context): Target? { + val prefs = context.getSharedPreferences("exit_tile", Context.MODE_PRIVATE) + val network = prefs.getString("network", null) ?: return null + val peer = prefs.getString("peer", null) ?: return null + return Target(network, peer, prefs.getString("name", null) ?: peer.take(12)) + } + private fun refresh(context: Context) { + requestListeningState(context, ComponentName(context, ExitTile::class.java)) + } + internal fun publish(context: Context, session: Long, active: Target?, online: Boolean) { + // Only confirmed agent status updates the last selection. Clearing an exit or + // stopping the process leaves the exact network and peer available for reuse. + if (active != null && last(context) != active) { + context.getSharedPreferences("exit_tile", Context.MODE_PRIVATE).edit() + .putString("network", active.network).putString("peer", active.peer) + .putString("name", active.name).apply() + } + live = Snapshot(session, active, online) + refresh(context) + } + internal fun reset(context: Context) { + live = Snapshot(0, null, false) + refresh(context) + } + internal fun restoreIfReady(context: Context, target: Target): Boolean { + if (live.session == 0L) return false + if (live.active == null) change(context, live.session, target, true, waitForDiscovery = true) + return true + } + private fun change(context: Context, session: Long, target: Target, connect: Boolean, waitForDiscovery: Boolean = false) { + if (pending) return + pending = true + refresh(context) + val app = context.applicationContext + Thread({ + val error = Native.tileExit(session, target.network, target.peer, connect, waitForDiscovery) + main.post { + pending = false + if (error != null) Toast.makeText(app, error, Toast.LENGTH_LONG).show() + refresh(app) + } + }, "tsunagi-exit-tile").start() + } + } + + private var displayed = live + private var remembered: Target? = null + + override fun onStartListening() { + super.onStartListening() + displayed = live + remembered = last(this) + val tile = qsTile ?: return + val active = displayed.active + val peer = active ?: remembered + val subtitle = when { + pending -> "Updating…" + active != null && !displayed.online -> "${active.name} · offline" + peer != null -> peer.name + else -> "Choose exit node" + } + tile.state = when { + pending -> Tile.STATE_UNAVAILABLE + active != null -> Tile.STATE_ACTIVE + else -> Tile.STATE_INACTIVE + } + tile.label = if (Build.VERSION.SDK_INT < 29 && peer != null) "Exit · ${peer.name}" else "Tsunagi Exit" + if (Build.VERSION.SDK_INT >= 29) tile.subtitle = subtitle + tile.contentDescription = "Tsunagi exit node, $subtitle" + tile.updateTile() + } + + @Suppress("DEPRECATION") + override fun onClick() { + super.onClick() + if (pending || displayed != live) { onStartListening(); return } + val target = displayed.active ?: remembered + if (displayed.session != 0L && target != null) { + change(this, displayed.session, target, displayed.active == null) + return + } + // Consent, a stopped service, or the first selection needs an activity. + val open = Intent().setComponent(entry(this)) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP) + if (Build.VERSION.SDK_INT >= 34) { + startActivityAndCollapse(PendingIntent.getActivity(this, 2, open, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)) + } else startActivityAndCollapse(open) + } +} diff --git a/android/app/src/main/java/cy/hexor/tsunagi/MainActivity.kt b/android/app/src/main/java/cy/hexor/tsunagi/MainActivity.kt index cc95e67..82bc66f 100644 --- a/android/app/src/main/java/cy/hexor/tsunagi/MainActivity.kt +++ b/android/app/src/main/java/cy/hexor/tsunagi/MainActivity.kt @@ -12,6 +12,7 @@ class MainActivity : Activity() { private val settings by lazy { getSharedPreferences("agent", MODE_PRIVATE) } private var checkedAutoStart = false private var consentPending = false + private var tileRequested = false private var askedForNotifications = false internal fun requestExitNotifications() { if (Build.VERSION.SDK_INT >= 33 && !askedForNotifications && @@ -24,6 +25,7 @@ class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) consentPending = savedInstanceState?.getBoolean("consent_pending") == true + tileRequested = savedInstanceState?.getBoolean("exit_tile") ?: (intent.component == ExitTile.entry(this)) surface = MeshSurface(this) val root = FrameLayout(this) if (Build.VERSION.SDK_INT >= 30) { @@ -39,6 +41,11 @@ class MainActivity : Activity() { } override fun onPostResume() { super.onPostResume() + if (tileRequested && !consentPending) { + checkedAutoStart = true + requestAgent() + return + } if (checkedAutoStart) return checkedAutoStart = true if (!MeshVpn.started && settings.getBoolean("auto_start", true)) requestAgent() @@ -46,6 +53,11 @@ class MainActivity : Activity() { override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean("consent_pending", consentPending) + outState.putBoolean("exit_tile", tileRequested) + } + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + if (intent.component == ExitTile.entry(this)) tileRequested = true } internal fun requestAgent() { if (consentPending) return @@ -58,6 +70,11 @@ class MainActivity : Activity() { private fun startAgent() { settings.edit().putBoolean("auto_start", true).apply() val service = Intent(this, MeshVpn::class.java) + if (tileRequested) { + tileRequested = false + if (ExitTile.last(this) != null) service.action = MeshVpn.RESTORE_EXIT + else surface.openExitPicker() + } // A retry of an existing service may already have left foreground mode. if (MeshVpn.started) startService(service) else startForegroundService(service) } @@ -71,6 +88,7 @@ class MainActivity : Activity() { if (request == 1) { consentPending = false if (result == RESULT_OK) startAgent() else { + tileRequested = false settings.edit().putBoolean("auto_start", false).apply() surface.input(5, "Android VPN permission was declined") } diff --git a/android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt b/android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt index 337b154..ed1a1a1 100644 --- a/android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt +++ b/android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt @@ -23,6 +23,8 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), private var widthPx = 0 private var heightPx = 0 private val repaint = Runnable { requestRender() } + private val pickExit = java.util.concurrent.atomic.AtomicBoolean() + fun openExitPicker() { pickExit.set(true); requestRender() } init { setEGLContextClientVersion(3) preserveEGLContextOnPause = true @@ -34,7 +36,9 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface() override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h } override fun onDrawFrame(gl: GL10?) { - val delay = Native.draw(this, widthPx, heightPx, density, MeshVpn.started) + if (pickExit.getAndSet(false)) Native.input(6, "") + val landscape = resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE + val delay = Native.draw(this, widthPx, heightPx, density, MeshVpn.started, landscape) removeCallbacks(repaint) postDelayed(repaint, delay.coerceAtLeast(16)) } diff --git a/android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt b/android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt index b1cc919..c1c009a 100644 --- a/android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt +++ b/android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt @@ -24,6 +24,7 @@ import java.util.concurrent.TimeUnit class MeshVpn : VpnService() { companion object { const val STOP_VPN = "cy.hexor.tsunagi.STOP_VPN" + const val RESTORE_EXIT = "cy.hexor.tsunagi.RESTORE_EXIT" private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT" private const val NOTIFICATION_ID = 1 private const val EXIT_CHANNEL = "exit-node" @@ -34,6 +35,7 @@ class MeshVpn : VpnService() { private val notifications by lazy { getSystemService(NotificationManager::class.java) } @Volatile private var instance = 0L private var closed = false + private var restore: ExitTile.Target? = null private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) } @Volatile private var upstream: Network? = null private val changes = object : ConnectivityManager.NetworkCallback() { @@ -76,6 +78,10 @@ class MeshVpn : VpnService() { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { when (intent?.action) { STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY } + RESTORE_EXIT -> { + restore = ExitTile.last(this) + restore?.let { if (ExitTile.restoreIfReady(this, it)) restore = null } + } DISCONNECT_EXIT -> { val ids = intent.data?.pathSegments.orEmpty() if (started && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) { @@ -118,9 +124,12 @@ class MeshVpn : VpnService() { // Rust publishes a change even when the activity is closed. Android holds its // own service binding for an established TUN, so mesh-only mode can leave // foreground promotion and remove the app's notification. - fun updateExitNotification(session: Long, network: String, peer: String, title: String, text: String) { + fun updateExitNotification(session: Long, network: String, peer: String, title: String, text: String, name: String, online: Boolean) { main.post { if (closed || session != instance) return@post + val selected = if (peer.isEmpty()) null else ExitTile.Target(network, peer, name) + ExitTile.publish(this, session, selected, online) + restore?.let { if (ExitTile.restoreIfReady(this, it)) restore = null } if (peer.isEmpty()) { stopForeground(STOP_FOREGROUND_REMOVE) return@post @@ -191,6 +200,8 @@ class MeshVpn : VpnService() { @Synchronized private fun shutdown() { if (closed) return closed = true + restore = null + ExitTile.reset(this) if (started) connectivity.unregisterNetworkCallback(changes) started = false if (instance != 0L) Native.stop(instance) diff --git a/android/app/src/main/java/cy/hexor/tsunagi/Native.kt b/android/app/src/main/java/cy/hexor/tsunagi/Native.kt index 3d0a479..42846b7 100644 --- a/android/app/src/main/java/cy/hexor/tsunagi/Native.kt +++ b/android/app/src/main/java/cy/hexor/tsunagi/Native.kt @@ -10,10 +10,11 @@ internal object Native { external fun failed(instance: Long): Boolean external fun stop(instance: Long) external fun disconnectExit(instance: Long, network: String, peer: String): Boolean + external fun tileExit(instance: Long, network: String, peer: String, connect: Boolean, waitForDiscovery: Boolean): String? external fun networkChanged(instance: Long, addresses: String) external fun surface() - external fun draw(host: MeshSurface, width: Int, height: Int, density: Float, serviceStarted: Boolean): Long + external fun draw(host: MeshSurface, width: Int, height: Int, density: Float, serviceStarted: Boolean, landscape: Boolean): Long external fun touch(action: Int, id: Int, x: Float, y: Float) external fun input(kind: Int, value: String) external fun key(key: Int) diff --git a/android/app/src/main/res/drawable/exit_tile.xml b/android/app/src/main/res/drawable/exit_tile.xml new file mode 100644 index 0000000..6d8b672 --- /dev/null +++ b/android/app/src/main/res/drawable/exit_tile.xml @@ -0,0 +1,6 @@ + + + diff --git a/crates/tsunagi-android/src/android/display.rs b/crates/tsunagi-android/src/android/display.rs index b7372a3..6392b34 100644 --- a/crates/tsunagi-android/src/android/display.rs +++ b/crates/tsunagi-android/src/android/display.rs @@ -54,7 +54,16 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObj crate::view::configure(&ctx); DISPLAY.with_borrow_mut(|d| { // If Android discarded the old EGL context, its GPU resources are already gone. - let ui = d.take().map(|old| old.ui).unwrap_or_default(); + let ui = d + .take() + .map(|old| { + // A rotation can recreate EGL. Keep expanded peers and scroll positions + // while the new context uploads its own font atlas. + let data = old.ctx.data_mut(std::mem::take); + ctx.data_mut(|current| *current = data); + old.ui + }) + .unwrap_or_default(); *d = Some(Display { painter, ctx, @@ -76,8 +85,10 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw( h: jint, scale: jfloat, service_started: jboolean, + landscape: jboolean, ) -> jlong { with_display(|d| { + tsunagi_ui::widgets::set_landscape(&d.ctx, landscape != 0); 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)), @@ -231,6 +242,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_input( } 4 => d.ui.paste_secret(text), 5 => d.ui.error(text), + 6 => d.ui.request_exit_picker(), _ => {} }); } diff --git a/crates/tsunagi-android/src/android/mod.rs b/crates/tsunagi-android/src/android/mod.rs index 375643b..6bb572e 100644 --- a/crates/tsunagi-android/src/android/mod.rs +++ b/crates/tsunagi-android/src/android/mod.rs @@ -265,9 +265,10 @@ fn update_exit_notification( let Ok(mut env) = vm.attach_current_thread() else { return; }; - let _ = env.with_local_frame(6, |env| -> jni::errors::Result<()> { + let _ = env.with_local_frame(8, |env| -> jni::errors::Result<()> { let network = env.new_string(notice.map_or("", |n| &n.network))?; let peer = env.new_string(notice.map_or("", |n| &n.peer))?; + let name = env.new_string(notice.map_or("", |n| &n.name))?; let title = env.new_string( notice .map(|n| format!("Exit node · {}", n.name)) @@ -290,13 +291,15 @@ fn update_exit_notification( env.call_method( service, "updateExitNotification", - "(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", + "(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V", &[ JValue::Long(id), JValue::Object(&network), JValue::Object(&peer), JValue::Object(&title), JValue::Object(&text), + JValue::Object(&name), + JValue::Bool(notice.is_some_and(|n| n.online).into()), ], )?; Ok(()) @@ -334,6 +337,53 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_disconnectExit( .into() } #[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_tileExit( + mut env: JNIEnv, + _: JObject, + id: jlong, + network: JString, + peer: JString, + connect: jni::sys::jboolean, + wait_for_discovery: jni::sys::jboolean, +) -> jni::sys::jstring { + // Called on the tile's background worker. Never hold the session lock while awaiting the agent. + let mut run = || -> Result<(), String> { + let network: String = env.get_string(&network).map_err(|e| e.to_string())?.into(); + let peer: String = env.get_string(&peer).map_err(|e| e.to_string())?.into(); + let (commands, mut state) = current() + .as_ref() + .filter(|s| s.id == id) + .map(|s| (s.commands.clone(), s.state.clone())) + .ok_or("Tsunagi Agent stopped")?; + if connect != 0 && wait_for_discovery != 0 { + tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .map_err(|e| e.to_string())? + .block_on(crate::service::wait_for_exit_offer( + &mut state, &network, &peer, + ))?; + } + let request = if connect != 0 { + Request::RestoreExit { network, peer } + } else { + Request::DisconnectExit { network, peer } + }; + let (reply, result) = oneshot::channel(); + commands + .try_send((request, reply)) + .map_err(|_| "Tsunagi Agent is busy or stopped")?; + result + .blocking_recv() + .map_err(|_| "Tsunagi Agent stopped")??; + Ok(()) + }; + run() + .err() + .and_then(|e| env.new_string(e).ok()) + .map_or(std::ptr::null_mut(), JString::into_raw) +} +#[unsafe(no_mangle)] extern "system" fn Java_cy_hexor_tsunagi_Native_failed( _: JNIEnv, _: JObject, diff --git a/crates/tsunagi-android/src/service.rs b/crates/tsunagi-android/src/service.rs index 249c360..fa76560 100644 --- a/crates/tsunagi-android/src/service.rs +++ b/crates/tsunagi-android/src/service.rs @@ -25,6 +25,13 @@ pub enum Request { /// Endpoint id captured at the same time. peer: String, }, + /// Restore a remembered network/peer pair only while no other exit is selected. + RestoreExit { + /// Network saved at the last successful selection. + network: String, + /// Peer used in that network. + peer: String, + }, } /// A configured default route stays visible if its remote peer goes offline. @@ -72,6 +79,66 @@ pub async fn disconnect_exit( Ok(()) } +async fn restore_exit(agent: &Agent, network: &str, peer: &str) -> Result { + let network = network.parse().map_err(|_| "Invalid saved network ID")?; + let peer = peer.parse().map_err(|_| "Invalid saved peer ID")?; + let status = agent.status().await.map_err(|e| e.to_string())?; + for n in &status.networks { + if n.state == tsunagi::agent::NetworkState::Active + && let Some(current) = n.exit_via + { + return if n.network_id == network && current == peer { + Ok(Outcome::Applied) + } else { + Err("Another exit is already selected".into()) + }; + } + } + agent + .set_exit_via(network, Some(peer)) + .await + .map_err(|e| e.to_string())?; + Ok(Outcome::Applied) +} + +// On cold start the first snapshot often precedes peer discovery. Wait on the +// service's roster notifications, outside the command loop, then let the usual +// serialized command validate the selection again before touching the route. +#[cfg(any(target_os = "android", test))] +pub(crate) async fn wait_for_exit_offer( + state: &mut watch::Receiver, + network: &str, + peer: &str, +) -> Result<(), String> { + tokio::time::timeout(std::time::Duration::from_secs(15), async { + loop { + match &*state.borrow_and_update() { + State::Ready(report, _) => { + let n = report + .networks + .iter() + .find(|n| n.network_id == network && n.active) + .ok_or("The saved exit network is no longer active")?; + if report + .networks + .iter() + .any(|n| n.active && n.exit.via.is_some()) + || n.peers.iter().any(|p| p.endpoint_id == peer && p.exit_node) + { + return Ok(()); + } + } + State::Off => return Err("Tsunagi Agent stopped".into()), + State::Error(error) => return Err(error.clone()), + State::Starting => {} + } + state.changed().await.map_err(|_| "Tsunagi Agent stopped")?; + } + }) + .await + .map_err(|_| "The saved peer is offline or no longer offers an exit")? +} + /// Private reply delivered only to the UI that requested the action. pub enum Outcome { /// The agent has applied the action. @@ -256,6 +323,7 @@ pub async fn serve( } Request::DisconnectExit {network, peer} => disconnect_exit(&agent, &network, &peer).await .map(|()| Outcome::Applied).map_err(|e| e.to_string()), + Request::RestoreExit {network, peer} => restore_exit(&agent, &network, &peer).await, }; (Some((reply, result)), refresh_zones) } diff --git a/crates/tsunagi-android/src/tests.rs b/crates/tsunagi-android/src/tests.rs index f1c211c..a20cb27 100644 --- a/crates/tsunagi-android/src/tests.rs +++ b/crates/tsunagi-android/src/tests.rs @@ -65,8 +65,8 @@ async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand #[tokio::test] async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_current_route() { - use crate::service::{ExitNotice, State, disconnect_exit, serve}; - use tokio::sync::{mpsc, watch}; + use crate::service::{ExitNotice, Request, State, disconnect_exit, serve, wait_for_exit_offer}; + use tokio::sync::{mpsc, oneshot, watch}; use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin}; async fn notice_matching( notices: &mut watch::Receiver>, @@ -117,11 +117,11 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_ .await .unwrap(); let agent = phone.agent.clone(); - let (_commands, requests) = mpsc::channel(4); + let (commands, requests) = mpsc::channel(4); let (stop, stopped) = watch::channel(false); let (published, mut notices) = watch::channel(None); + let (state, mut live) = watch::channel(State::Starting); let task = tokio::spawn(async move { - let (state, _) = watch::channel(State::Starting); serve( agent, wg, @@ -142,6 +142,66 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_ assert_eq!(notice.name, "gateway"); assert_eq!(notice.network_name, "travel"); assert!(notice.online); + let restore = |peer: String| { + let commands = commands.clone(); + let network = notice.network.clone(); + async move { + let (reply, result) = oneshot::channel(); + commands + .send((Request::RestoreExit { network, peer }, reply)) + .await + .unwrap(); + result.await.unwrap() + } + }; + disconnect_exit(&phone.agent, ¬ice.network, ¬ice.peer) + .await + .unwrap(); + notice_matching(&mut notices, Option::is_none).await; + assert!( + restore(phone.agent.endpoint_id().to_string()) + .await + .is_err() + ); + assert!( + phone + .agent + .network_status(id) + .await + .unwrap() + .exit_via + .is_none() + ); + // A cold service can publish its first status before the gateway advertises. + // Keep the command loop available while waiting for this exact peer. + exit.agent.set_exit_offer(id, false).await.unwrap(); + drop( + tokio::time::timeout( + std::time::Duration::from_secs(5), + live.wait_for(|s| { + matches!(s, State::Ready(report, _) if + report.networks[0].peers.iter().any(|p| p.endpoint_id == notice.peer && !p.exit_node)) + }), + ) + .await + .unwrap() + .unwrap(), + ); + let waiting = wait_for_exit_offer(&mut live, ¬ice.network, ¬ice.peer); + tokio::pin!(waiting); + tokio::select! { + biased; + _ = &mut waiting => panic!("restored before the peer offered an exit"), + result = exit.agent.set_exit_offer(id, true) => result.unwrap(), + } + waiting.await.unwrap(); + assert!(restore(notice.peer.clone()).await.is_ok()); + notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| n.online)).await; + assert!( + restore(phone.agent.endpoint_id().to_string()) + .await + .is_err() + ); disconnect_exit( &phone.agent, &id.to_string(), @@ -678,12 +738,14 @@ async fn network_cards_start_closed_and_keep_exit_traffic_visible_when_folded() }; let opened = click(titles[0]); assert_eq!(positions(&opened, "Show devices").len(), 1); - let y = |label| positions(&opened, label)[0].y; - assert!((0.0..=26.0).contains(&(y("host") - y("device")))); - assert!((0.0..=26.0).contains(&(y("range") - y("id")))); - assert!((0.0..=26.0).contains(&(y("peers") - y("addr")))); - assert!((y("VIP") - y("Show devices")).abs() < 2.0); - assert!((y("VIP") - y(&format!("{} Copy secret", egui_phosphor::regular::COPY))).abs() < 2.0); + use egui_phosphor::regular as icon; + let vip = format!("{} VIP", icon::NETWORK); + let y = |label: &str| positions(&opened, label)[0].y; + assert!((0.0..=26.0).contains(&(y(icon::DESKTOP_TOWER) - y(icon::FINGERPRINT)))); + assert!((0.0..=26.0).contains(&(y(icon::TREE_STRUCTURE) - y(icon::HASH)))); + assert!((0.0..=26.0).contains(&(y(icon::DEVICES) - y(icon::DEVICE_MOBILE)))); + assert!((y(&vip) - y("Show devices")).abs() < 2.0); + assert!((y(&vip) - y(&format!("{} Copy secret", egui_phosphor::regular::COPY))).abs() < 2.0); let folded = click(positions(&opened, name.as_str())[0]); assert!(positions(&folded, "Show devices").is_empty()); assert_eq!(positions(&folded, "Exit via gateway").len(), 1); @@ -691,7 +753,55 @@ async fn network_cards_start_closed_and_keep_exit_traffic_visible_when_folded() } #[test] -fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() { +fn the_system_tile_waits_for_the_agent_and_distinguishes_networks_with_the_same_name() { + use crate::{ + service::State, + view::{Phone, configure}, + }; + use std::{sync::Arc, time::Instant}; + use tsunagi::ipc::{NetworkReport, StatusReport}; + let ctx = egui::Context::default(); + configure(&ctx); + let mut phone = Phone::default(); + let draw = |phone: &mut Phone, state: &State| { + let out = ctx.run(egui::RawInput::default(), |ctx| { + phone.draw(ctx, state, |_| panic!("opening the tile selected a route")); + }); + out.shapes + .into_iter() + .filter_map(|s| match s.shape { + egui::Shape::Text(t) => Some(t.galley.text().to_owned()), + _ => None, + }) + .collect::>() + }; + phone.request_exit_picker(); + draw(&mut phone, &State::Starting); + let networks = + [("alpha", true), ("bravo", true), ("paused", false)].map(|(id, active)| NetworkReport { + network_id: id.into(), + name: "home".into(), + active, + ..Default::default() + }); + let state = State::Ready( + Arc::new(StatusReport { + networks: networks.into(), + ..Default::default() + }), + Instant::now(), + ); + draw(&mut phone, &state); + let chooser = draw(&mut phone, &state); + assert!(chooser.iter().any(|s| s == "home · alpha")); + assert!(chooser.iter().any(|s| s == "home · bravo")); + assert!(!chooser.iter().any(|s| s.contains("paused"))); + assert!(phone.back().is_none()); + assert!(draw(&mut phone, &state).iter().any(|s| s == "tsunagi")); +} + +#[test] +fn rotating_the_phone_keeps_the_selected_network_and_unsaved_vip_draft() { use crate::service::State; use crate::view::{Phone, configure}; use egui::{Event, PointerButton, Pos2, RawInput, Rect, Shape}; @@ -708,6 +818,7 @@ fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() { port: 8080, }; let mut config = VipConfig::new("web"); + let name_field = egui::Id::new(("vip-name", &config.id)); let mut listener = Listener::new(Protocol::Tcp, 80); listener.backends.push(backend.clone()); config.listeners.push(listener); @@ -747,10 +858,11 @@ fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() { let ctx = egui::Context::default(); configure(&ctx); let mut phone = Phone::default(); + let size = std::cell::Cell::new(egui::vec2(360., 800.)); let mut frame = |events| { ctx.run( RawInput { - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(360., 800.))), + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size.get())), events, ..Default::default() }, @@ -788,21 +900,30 @@ fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() { frame(vec![]) }; click("lab"); - let live = click("VIP"); - for label in ["Overview", "Configuration", "Next new flow", "node:8080"] { + size.set(egui::vec2(800., 360.)); + let live = click(&format!("{} VIP", egui_phosphor::regular::NETWORK)); + for label in ["Overview", "Configuration", "web.lab", "node:8080"] { let p = position(&live, label); assert!( - (0.0..360.0).contains(&p.x), - "{label} is outside the portrait view" + (0.0..800.0).contains(&p.x), + "{label} is outside the landscape view" ); } let editor = click("Configuration"); + position(&editor, "Name"); + ctx.memory_mut(|m| m.request_focus(name_field)); + frame(vec![Event::Text("-draft".into())]); + size.set(egui::vec2(360., 800.)); + let editor_portrait = frame(vec![]); + position(&editor_portrait, "Unsaved changes"); + assert!(editor_portrait.shapes.iter().any(|s| matches!(&s.shape, + Shape::Text(t) if t.galley.text().contains("-draft")))); for label in [ "Active TCP port checks", "Checks and flow expiry", "+ Backend", "+ Listener", ] { - position(&editor, label); + position(&editor_portrait, label); } } diff --git a/crates/tsunagi-android/src/view.rs b/crates/tsunagi-android/src/view.rs index 38615e6..4a2ae81 100644 --- a/crates/tsunagi-android/src/view.rs +++ b/crates/tsunagi-android/src/view.rs @@ -24,6 +24,7 @@ enum Page { Devices(String), Vips(String), Exit(String), + ExitNetworks, Leave(String), } impl Page { @@ -40,7 +41,7 @@ impl Page { Self::Join => "Join a network", Self::Devices(_) => "Devices", Self::Vips(_) => "VIP", - Self::Exit(_) => "Exit node", + Self::Exit(_) | Self::ExitNetworks => "Exit node", Self::Leave(_) => "Leave network", } } @@ -90,10 +91,14 @@ pub struct Phone { pending: Option, error: Option, clipboard: Option>, + landscape: bool, + pick_exit: bool, + before_picker: Option, } /// Keep reads at tray density. Extra hit area is reserved for the navigation bar. pub fn configure(ctx: &Context) { + ctx.set_os(egui::os::OperatingSystem::Android); ctx.set_fonts(tsunagi_ui::app_fonts()); ctx.style_mut(|style| { style.spacing.interact_size.y = 19.0; @@ -104,11 +109,15 @@ pub fn configure(ctx: &Context) { impl Phone { fn home(&mut self) { + if let Some(previous) = self.before_picker.take() { + self.forms.exit_confirm = None; + self.page = previous; + return; + } if let Page::Vips(id) = &self.page { self.forms.vip_windows.remove(id); } - self.forms.join.name.clear(); - self.forms.join.secret.zeroize(); + self.forms.join = Default::default(); self.forms.exit_confirm = None; self.forms.forget_confirm = None; self.page = Page::Home; @@ -127,6 +136,8 @@ impl Phone { && editor.dirty() { editor.request_close(); + } else if self.page == Page::Home && self.landscape && self.forms.close_selection() { + return None; } else if self.page == Page::Home { return Some(SystemAction::Finish); } else { @@ -150,6 +161,99 @@ impl Phone { self.error = Some(message); } + /// The first tile tap opens the chooser once the agent is ready. + pub fn request_exit_picker(&mut self) { + self.pick_exit = true; + } + + fn exit_networks(&mut self, ui: &mut egui::Ui, networks: &[tsunagi::ipc::NetworkReport]) { + if networks.is_empty() { + ui.label("Join a network to choose an exit node."); + if ui.button("Join or create a network").clicked() { + self.page = Page::Join; + } + return; + } + if !networks.iter().any(|n| n.active) { + ui.label("Start a network to choose an exit node."); + if ui.button("Show networks").clicked() { + self.home(); + } + return; + } + ui.label("Choose a network for the exit node"); + for n in networks.iter().filter(|n| n.active) { + let ambiguous = networks.iter().any(|other| { + other.active && other.name == n.name && other.network_id != n.network_id + }); + let label = if ambiguous { + format!("{} · {}", n.name, tsunagi_ui::format::short(&n.network_id)) + } else { + n.name.clone() + }; + if ui.button(label).clicked() { + self.page = Page::Exit(n.network_id.clone()); + } + } + } + + fn landscape_home( + &mut self, + ui: &mut egui::Ui, + actions: &Actions, + report: &tsunagi::ipc::StatusReport, + ) { + let width = (ui.available_width() / 3.) + .clamp(146., 300.) + .min(ui.available_width() * 0.45); + egui::SidePanel::left("network selector") + .resizable(false) + .exact_width(width) + .show_inside(ui, |ui| { + if ui.button("Join or create a network").clicked() { + self.page = Page::Join; + } + ui.separator(); + egui::ScrollArea::vertical() + .id_salt("network list") + .show(ui, |ui| { + for network in &report.networks { + home::draw_network_selector(ui, network, report, &mut self.forms); + } + }); + }); + egui::CentralPanel::default().show_inside(ui, |ui| { + let selected = report + .networks + .iter() + .find(|n| self.forms.selected_network.as_deref() == Some(&n.network_id)); + egui::ScrollArea::vertical() + .id_salt(("network settings", selected.map(|n| &n.network_id))) + .show(ui, |ui| { + if let Some(n) = selected { + ui.heading(&n.name); + ui.push_id(&n.network_id, |ui| { + if home::draw_network_details( + ui, + actions, + &mut self.forms, + &self.traffic, + n, + report, + false, + ) { + self.page = Page::Exit(n.network_id.clone()); + } + }); + } else { + ui.heading("This device"); + ui.label("Tsunagi Agent is running"); + home::draw_header(ui, actions, &mut self.forms, report); + } + }); + }); + } + /// Take a secret once for the platform’s sensitive clipboard. pub fn take_copied_secret(&mut self) -> Option> { self.clipboard.take() @@ -191,6 +295,7 @@ impl Phone { mut submit: impl FnMut(Command) -> Result, ) -> Option { self.acknowledge(); + self.landscape = tsunagi_ui::widgets::landscape(ctx); let report = if let State::Ready(report, at) = state { if self.snapshot.at != Some(*at) { self.snapshot.generation = self.snapshot.generation.wrapping_add(1); @@ -205,6 +310,25 @@ impl Phone { { self.home(); } + if self + .forms + .selected_network + .as_ref() + .is_some_and(|id| !report.networks.iter().any(|n| &n.network_id == id)) + { + self.forms.close_selection(); + } + if self.pick_exit && self.pending.is_none() { + self.pick_exit = false; + let mut active = report.networks.iter().filter(|n| n.active); + let picker = match (active.next(), active.next()) { + (Some(n), None) => Page::Exit(n.network_id.clone()), + _ => Page::ExitNetworks, + }; + if !matches!(self.page, Page::Exit(_) | Page::ExitNetworks) { + self.before_picker = Some(std::mem::replace(&mut self.page, picker)); + } + } Some(report) } else { if self.page.network().is_some() || self.page == Page::Join { @@ -222,14 +346,18 @@ impl Phone { egui::TopBottomPanel::top("navigation").show(ctx, |ui| { ui.horizontal(|ui| { ui.spacing_mut().interact_size.y = 32.0; - if self.page != Page::Home && ui.button(icon::ARROW_LEFT).clicked() { + if self.page != Page::Home + && tsunagi_ui::widgets::icon_button(ui, icon::ARROW_LEFT, "Back").clicked() + { system = self.back(); } ui.heading(self.page.title()); if self.page == Page::Home { ui.weak(env!("CARGO_PKG_VERSION")); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(icon::INFO).clicked() { + if tsunagi_ui::widgets::icon_button(ui, icon::INFO, "About Tsunagi") + .clicked() + { self.page = Page::About; } if report.is_some() { @@ -276,6 +404,10 @@ impl Phone { } _ => { egui::CentralPanel::default().show(ctx, |ui| { + if let Some(report) = report && self.page == Page::Home && self.landscape { + self.landscape_home(ui, &actions, report); + return; + } egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { let Some(report) = report else { match state { @@ -294,8 +426,6 @@ impl Phone { if ui.button("Join or create a network").clicked() {self.page = Page::Join;} for n in &report.networks { if home::draw_network(ui, &actions, &mut self.forms, &self.traffic, n, report, false) {self.page = Page::Exit(n.network_id.clone());} - if self.forms.open_devices.remove(&n.network_id) {self.page = Page::Devices(n.network_id.clone());} - if self.forms.vip_windows.contains_key(&n.network_id) {self.page = Page::Vips(n.network_id.clone());} } } Page::Join => { @@ -307,6 +437,7 @@ impl Phone { self.forms.exit_confirm = Some(choice); } } + Page::ExitNetworks => self.exit_networks(ui, &report.networks), Page::Leave(id) => { if let Some(n) = selected { ui.label(format!("Leave {} on this phone? You will need its secret to join again.", n.name)); @@ -318,6 +449,20 @@ impl Phone { } }); }); + if let Some(report) = report + && self.page == Page::Home + { + for n in &report.networks { + if self.forms.open_devices.remove(&n.network_id) { + self.page = Page::Devices(n.network_id.clone()); + break; + } + if self.forms.vip_windows.contains_key(&n.network_id) { + self.page = Page::Vips(n.network_id.clone()); + break; + } + } + } devices::confirm_exit(ctx, &actions, &mut self.forms.exit_confirm, None); } } diff --git a/crates/tsunagi-core/src/agent/mod.rs b/crates/tsunagi-core/src/agent/mod.rs index de7c9b7..1912734 100644 --- a/crates/tsunagi-core/src/agent/mod.rs +++ b/crates/tsunagi-core/src/agent/mod.rs @@ -26,8 +26,9 @@ mod status; pub use events::Event; pub use status::{ - AgentStatus, CandidateStatus, DataPath, HostnameConflict, MemberStatus, NetworkMetrics, - NetworkState, NetworkStatus, OverlayStatus, PeerStatus, RangeConflict, + AgentStatus, CandidateStatus, DATA_CONNECTING, DATA_DISABLED, DataPath, HostnameConflict, + MemberStatus, NetworkMetrics, NetworkState, NetworkStatus, OverlayStatus, PeerStatus, + RangeConflict, }; use std::collections::HashMap; @@ -709,7 +710,7 @@ impl Agent { self.inner.events.subscribe() } - /// Subscribe to changes affecting the mesh DNS roster or selected exit. + /// Subscribe to changes affecting the mesh DNS roster, exit offers or selected exit. /// Changes coalesce. Read the current status after subscribing and again on /// notification. Packet counters and routine control traffic do not wake subscribers. pub fn watch_roster(&self) -> watch::Receiver<()> { diff --git a/crates/tsunagi-core/src/agent/network.rs b/crates/tsunagi-core/src/agent/network.rs index 7aadfb6..b5c97ed 100644 --- a/crates/tsunagi-core/src/agent/network.rs +++ b/crates/tsunagi-core/src/agent/network.rs @@ -2990,7 +2990,10 @@ impl Runtime { .agent_version .clone_from(&announcement.agent_version); session.broadcast = announcement.broadcast; - session.exit_node = announcement.exit_node; + if session.exit_node != announcement.exit_node { + session.exit_node = announcement.exit_node; + self.params.roster_changed.send_replace(()); + } session.capabilities = capabilities.clone(); } self.remember_hostname(peer, &announcement.hostname); @@ -3178,7 +3181,12 @@ impl Runtime { fn data_error(&self, session: &Session) -> Option { if self.params.carriers.is_empty() { - return Some("data transports disabled locally".into()); + return Some(super::DATA_DISABLED.into()); + } + // Capabilities arrive in the first authenticated announcement, after + // the session is already visible in status. + if session.hostname.is_none() { + return Some(super::DATA_CONNECTING.into()); } if self.params.tunnel.is_some() && self.tunnel_protocol(session).is_none() { return Some( @@ -3226,7 +3234,7 @@ impl Runtime { self.data_errors .get(&session.peer) .cloned() - .or_else(|| Some("establishing external data transport".into())) + .or_else(|| Some(super::DATA_CONNECTING.into())) } fn status(&self) -> NetworkStatus { diff --git a/crates/tsunagi-core/src/agent/status.rs b/crates/tsunagi-core/src/agent/status.rs index 808ac9c..91c23ce 100644 --- a/crates/tsunagi-core/src/agent/status.rs +++ b/crates/tsunagi-core/src/agent/status.rs @@ -16,6 +16,11 @@ use crate::net::{ConnectionCounters, PathAddr, PathInfo, TransportKind}; use crate::proto::handshake::Role; use crate::storage::CacheOutcome; +/// Informational data-channel diagnostics shared by the status UI and runtime. +pub const DATA_CONNECTING: &str = "establishing external data transport"; +/// Data transport was disabled by local policy. +pub const DATA_DISABLED: &str = "data transports disabled locally"; + /// Whether a configured network is running locally. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum NetworkState { diff --git a/crates/tsunagi-tray/src/ui.rs b/crates/tsunagi-tray/src/ui.rs index 6f743cd..a51ca2a 100644 --- a/crates/tsunagi-tray/src/ui.rs +++ b/crates/tsunagi-tray/src/ui.rs @@ -38,7 +38,7 @@ pub(crate) fn draw( .weak(), ); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(icon::INFO).on_hover_text("About").clicked() { + if tsunagi_ui::widgets::icon_button(ui, icon::INFO, "About Tsunagi").clicked() { state.about_open = true; } if snapshot.busy { diff --git a/crates/tsunagi-ui/src/about.rs b/crates/tsunagi-ui/src/about.rs index b8fd218..72e0b0d 100644 --- a/crates/tsunagi-ui/src/about.rs +++ b/crates/tsunagi-ui/src/about.rs @@ -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 "; @@ -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(); } diff --git a/crates/tsunagi-ui/src/devices.rs b/crates/tsunagi-ui/src/devices.rs index cb9898d..0f930aa 100644 --- a/crates/tsunagi-ui/src/devices.rs +++ b/crates/tsunagi-ui/src/devices.rs @@ -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); diff --git a/crates/tsunagi-ui/src/devices/compact.rs b/crates/tsunagi-ui/src/devices/compact.rs index 7217e4b..e59252e 100644 --- a/crates/tsunagi-ui/src/devices/compact.rs +++ b/crates/tsunagi-ui/src/devices/compact.rs @@ -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::() - 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::(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}.")); diff --git a/crates/tsunagi-ui/src/devices/status.rs b/crates/tsunagi-ui/src/devices/status.rs new file mode 100644 index 0000000..371f0a5 --- /dev/null +++ b/crates/tsunagi-ui/src/devices/status.rs @@ -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, + ); + } +} diff --git a/crates/tsunagi-ui/src/format.rs b/crates/tsunagi-ui/src/format.rs index a2731dc..c1438e6 100644 --- a/crates/tsunagi-ui/src/format.rs +++ b/crates/tsunagi-ui/src/format.rs @@ -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())); } diff --git a/crates/tsunagi-ui/src/home.rs b/crates/tsunagi-ui/src/home.rs index 54c28e5..e7c6532 100644 --- a/crates/tsunagi-ui/src/home.rs +++ b/crates/tsunagi-ui/src/home.rs @@ -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, + 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, + /// The network whose settings occupy the detail pane on a landscape phone. + pub selected_network: Option, /// An in-progress hostname edit (`None` when not editing). pub host_edit: Option, /// 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; } } diff --git a/crates/tsunagi-ui/src/lib.rs b/crates/tsunagi-ui/src/lib.rs index 20838e0..9d3b723 100644 --- a/crates/tsunagi-ui/src/lib.rs +++ b/crates/tsunagi-ui/src/lib.rs @@ -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 { diff --git a/crates/tsunagi-ui/src/presentation_tests.rs b/crates/tsunagi-ui/src/presentation_tests.rs new file mode 100644 index 0000000..145aa58 --- /dev/null +++ b/crates/tsunagi-ui/src/presentation_tests.rs @@ -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, + 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 { + 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()); +} diff --git a/crates/tsunagi-ui/src/vip.rs b/crates/tsunagi-ui/src/vip.rs index 854b108..21c3303 100644 --- a/crates/tsunagi-ui/src/vip.rs +++ b/crates/tsunagi-ui/src/vip.rs @@ -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| { diff --git a/crates/tsunagi-ui/src/vip_status.rs b/crates/tsunagi-ui/src/vip_status.rs index ea15762..e4f594f 100644 --- a/crates/tsunagi-ui/src/vip_status.rs +++ b/crates/tsunagi-ui/src/vip_status.rs @@ -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 = 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::() + 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::() + 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), }, diff --git a/crates/tsunagi-ui/src/widgets.rs b/crates/tsunagi-ui/src/widgets.rs new file mode 100644 index 0000000..eddfdaa --- /dev/null +++ b/crates/tsunagi-ui/src/widgets.rs @@ -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"); +}