diff --git a/crates/voelin-core/src/cache.rs b/crates/voelin-core/src/cache.rs index 7e3db26..adab3fd 100644 --- a/crates/voelin-core/src/cache.rs +++ b/crates/voelin-core/src/cache.rs @@ -131,9 +131,16 @@ impl Cache { self.touch(&mut index, key) } - /// The cached server, channel, group or client icon, if available. + /// The cached server, channel, group or client icon, if available. Not + /// marked as used (no file is opened or touched): the UI asks on every + /// refresh of the server list. pub fn icon(&self, id: u32) -> Option { - (id != 0).then(|| self.get(&icon_key(id))).flatten() + if id == 0 { + return None; + } + let key = icon_key(id); + let path = self.dir.join(&key); + (self.lock().entries.contains_key(&key) && path.is_file()).then_some(path) } fn touch(&self, index: &mut Index, key: &str) -> Option { diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 29131f7..cdc9352 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -9,6 +9,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::PathBuf; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use tokio::time::Instant; @@ -126,6 +127,33 @@ enum ImageRequest { Picture(String), } +/// An image download over the voice connection, finished in the cache +/// once: with its result, or as failed when the request is dropped +/// unanswered (sent while the connection closes, or still queued when it +/// ends). Otherwise the key would stay in flight, and every later fetch of +/// it, in any session, would wait forever. +struct ImageDownload { + cache: cache::Cache, + key: String, + temp: PathBuf, + settings: SharedSettings, + done: AtomicBool, +} + +impl ImageDownload { + fn finish(&self, result: Result<(), String>) { + if !self.done.swap(true, Ordering::AcqRel) { + self.cache.finish(&self.key, &self.temp, result, max_cache_bytes(&self.settings)); + } + } +} + +impl Drop for ImageDownload { + fn drop(&mut self) { + self.finish(Err("the voice connection closed".into())); + } +} + /// At most three retries (after 1, 4 and 16 seconds) per image version. /// Keeping exhausted entries prevents presence traffic from causing a retry storm. struct ImageRetry { @@ -1029,21 +1057,21 @@ impl Session { fn fetch_image(&self, key: String, file: Option<(u64, String)>, fresh: bool, waiter: Waiter) { let cache = self.cache.current(); let Fetch::Download(temp) = cache.fetch(&key, fresh, waiter) else { return }; - let settings = self.settings.clone(); + let download = ImageDownload { + cache, + key, + temp: temp.clone(), + settings: self.settings.clone(), + done: AtomicBool::new(false), + }; let (Some((channel, path)), Some((_, voice))) = (file, &self.voice) else { - cache.finish(&key, &temp, Err(NO_VOICE.into()), max_cache_bytes(&settings)); + download.finish(Err(NO_VOICE.into())); return; }; - let finish = { - let temp = temp.clone(); - move |result: Result<(), String>| { - cache.finish(&key, &temp, result, max_cache_bytes(&settings)); - } - }; let report: Report = Arc::new(move |state| match state { - TransferState::Done { .. } => finish(Ok(())), - TransferState::Failed(e) => finish(Err(e)), - TransferState::Cancelled => finish(Err("cancelled".into())), + TransferState::Done { .. } => download.finish(Ok(())), + TransferState::Failed(e) => download.finish(Err(e)), + TransferState::Cancelled => download.finish(Err("cancelled".into())), _ => {} }); let sink = Sink::File { part: temp.clone(), dest: temp, append: false }; @@ -2041,6 +2069,28 @@ mod banner_tests { std::fs::remove_dir_all(session.cache.current().dir()).unwrap(); } + /// A request the voice connection drops unanswered (sent while it + /// closes) fails, instead of leaving the picture in flight for good. + #[tokio::test] + async fn a_dropped_image_request_fails_instead_of_waiting_forever() { + let (mut session, _events) = session("dropped"); + let (tx, mut commands) = mpsc::unbounded_channel(); + session.voice = Some((1, tx)); + session.icons.insert(1234); + session.fetch_icon(1234); + drop(commands.try_recv().unwrap()); + let Some(SourceEvent::ImageFinished(_, _, ImageRequest::Icon(1234), Err(_))) = + session.sources_rx.as_mut().unwrap().recv().await + else { + panic!("expected the icon to fail"); + }; + // The next fetch downloads again instead of waiting for the lost one. + let cache = session.cache.current(); + let next = cache.fetch(&cache::icon_key(1234), false, Box::new(|_| {})); + assert!(matches!(next, Fetch::Download(_))); + let _ = std::fs::remove_dir_all(cache.dir()); + } + #[tokio::test] async fn retries_are_bounded_and_obey_policy_presence_and_epoch() { let (mut session, mut events) = session("retry-guards"); diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 69ac3c7..49e8e96 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -963,6 +963,8 @@ impl App { // Pictures can arrive after the rows were built: draw them again. Event::AvatarReady { session, client_uid, path, .. } => { let view = self.sessions.entry(session as i64).or_default(); + // A file that arrives again is decoded again. + crate::images::forget(&path); view.avatars.insert(client_uid, path); if self.current == Some(session as i64) { self.refresh_tree(); @@ -974,6 +976,7 @@ impl App { } Event::IconReady { session, icon, path } => { let view = self.sessions.entry(session as i64).or_default(); + crate::images::forget(&path); view.icons.insert(icon, path); self.refresh_servers(); if self.current == Some(session as i64) { diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index 2afb8de..d6ac88a 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -63,7 +63,8 @@ impl App { let name = self .sessions .get(&id) - .and_then(|v| v.presence.channels.get(cid).map(|c| c.name.clone())); + .and_then(|v| v.presence.channels.get(cid)) + .map(|c| vm::tree::channel_title(c).0.to_owned()); format!("#{}", name.unwrap_or_else(|| cid.to_string())) } ChatTarget::Server => "Server".into(), diff --git a/crates/voelin-ui/src/images.rs b/crates/voelin-ui/src/images.rs index 2e7292a..b530760 100644 --- a/crates/voelin-ui/src/images.rs +++ b/crates/voelin-ui/src/images.rs @@ -110,6 +110,9 @@ pub fn usage_text() -> String { }) } +/// What remembering a picture that cannot be decoded costs in the cache. +const UNDECODABLE_COST: usize = 256; + /// A picture the engine put in its cache (avatars, group and client icons), /// decoded once and kept by its path. pub fn file(path: &std::path::Path) -> Image { @@ -121,7 +124,10 @@ pub fn file(path: &std::path::Path) -> Image { // (`avatars/`, `icons/`), and servers keep PNG, JPEG // and SVG icons alike. let bytes = std::fs::read(path).ok()?; - decode(&bytes) + // One that cannot be shown (too large, not a picture) is + // remembered as such, not read again on every refresh; a + // changed file is forgotten first (`forget`). + Some(decode(&bytes).unwrap_or((Image::default(), UNDECODABLE_COST))) }) }) .unwrap_or_default() @@ -328,6 +334,15 @@ mod tests { assert_eq!(file(&path).size().width, 3, "kept until forgotten"); forget(&path); assert_eq!(file(&path).size().width, 5); + // A file that is no picture is remembered as such until forgotten, + // not read again on every refresh. + let junk = dir.join("junk"); + std::fs::write(&junk, b"").unwrap(); + assert_eq!(file(&junk).size().width, 0); + std::fs::write(&junk, &png).unwrap(); + assert_eq!(file(&junk).size().width, 0, "remembered"); + forget(&junk); + assert_eq!(file(&junk).size().width, 3); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index 3d887ba..7faddef 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -409,7 +409,9 @@ impl App { bridge.set_server_banner_mode(details.map_or(0, |d| vm::tree::banner_mode(d.banner_mode))); let own_channel = view.and_then(|v| state.own_channel.and_then(|c| v.presence.channels.get(&c))); - bridge.set_own_channel(own_channel.map(|c| c.name.clone()).unwrap_or_default().into()); + bridge.set_own_channel( + own_channel.map(|c| vm::tree::channel_title(c).0).unwrap_or_default().into(), + ); bridge.set_own_channel_topic( own_channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(), ); diff --git a/crates/voelin-ui/src/vm/tree.rs b/crates/voelin-ui/src/vm/tree.rs index f8753ba..5fecf49 100644 --- a/crates/voelin-ui/src/vm/tree.rs +++ b/crates/voelin-ui/src/vm/tree.rs @@ -4,7 +4,9 @@ use std::collections::{HashMap, HashSet}; use std::path::PathBuf; -use voelin_model::{BannerMode, ChannelId, ClientInfo, GroupInfo, Presence, TreeRow, tree_rows}; +use voelin_model::{ + BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, Presence, TreeRow, tree_rows, +}; use crate::app::{MemberItem, TreeItem}; use crate::settings::ClientPlaybackMap; @@ -113,6 +115,13 @@ fn channel_label(name: &str) -> (&str, bool) { (name, false) } +/// A channel's name as shown, and whether it is a centred spacer. Only +/// top-level channels are spacers, as in TeamSpeak: a sub-channel keeps its +/// name as it is. +pub fn channel_title(channel: &ChannelInfo) -> (&str, bool) { + if channel.parent == 0 { channel_label(&channel.name) } else { (&channel.name, false) } +} + /// The rows of the tree, channels with their clients below. pub fn rows(input: &TreeInput) -> Vec { let p = input.presence; @@ -120,7 +129,7 @@ pub fn rows(input: &TreeInput) -> Vec { .into_iter() .map(|row| match row { TreeRow::Channel { depth, channel } => { - let (name, centered_spacer) = channel_label(&channel.name); + let (name, centered_spacer) = channel_title(channel); TreeItem { centered_spacer, is_channel: true, @@ -235,7 +244,7 @@ impl TreeInput<'_> { && c.streaming != Some(true) && c.away.is_none(); let status = match self.presence.channels.get(&c.channel) { - Some(channel) if elsewhere => format!("In {}", channel.name), + Some(channel) if elsewhere => format!("In {}", channel_title(channel).0), _ => status_of(c, talking), }; MemberItem { @@ -510,6 +519,14 @@ mod tests { for name in ["[cspacerx]Games", "[cspacer2Games", "Games", "[spacer0]Games"] { assert_eq!(channel_label(name), (name, false)); } + // Only top-level channels are spacers: a sub-channel keeps its name. + p.channels.get_mut(&3).unwrap().name = "[cspacer1]Chess".into(); + let (t, c) = (HashSet::new(), HashSet::new()); + let found = super::rows(&input(&p, &t, &c, &pb, "Chess", &e)); + let chess = found.iter().find(|r| r.is_channel && r.id == 3).unwrap(); + assert_eq!((chess.name.as_str(), chess.centered_spacer), ("[cspacer1]Chess", false)); + assert_eq!(channel_title(&p.channels[&2]), ("Гамесы", true)); + assert_eq!(channel_title(&p.channels[&3]), ("[cspacer1]Chess", false)); } #[test] diff --git a/crates/voelin-ui/ui/screens/channels.slint b/crates/voelin-ui/ui/screens/channels.slint index a73e034..65de23c 100644 --- a/crates/voelin-ui/ui/screens/channels.slint +++ b/crates/voelin-ui/ui/screens/channels.slint @@ -158,6 +158,14 @@ component TreeRow inherits Rectangle { y: 0; source: item.banner; } + // The artwork covers the row's own background: tint it as that would + // be for our channel and on hover, translucent so the picture shows. + if item.is-channel && item.banner.width > 0 && (item.own || area.has-hover): Rectangle { + x: root.indent; + width: max(0px, root.width - root.indent); + border-radius: root.border-radius; + background: item.own ? Theme.accent-soft.transparentize(0.35) : Theme.surface-3.transparentize(0.5); + } area := TouchArea { mouse-cursor: MouseCursor.pointer; double-clicked => { @@ -198,7 +206,9 @@ component TreeRow inherits Rectangle { horizontal-stretch: 1; overflow: elide; } - if item.locked && item.icon.width > 0: Icon { + // At the end where the start shows the channel's icon, or nothing + // (a centred spacer). + if item.locked && (item.icon.width > 0 || item.centered-spacer): Icon { source: Icons.lock; size: 14px; tint: item.banner.width > 0 ? Theme.text : Theme.icon;