diff --git a/Cargo.lock b/Cargo.lock index e346c37..4cbd4c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4063,6 +4063,9 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" dependencies = [ "bytemuck", "byteorder-lite", + "color_quant", + "gif", + "image-webp", "moxcms", "num-traits", "png", @@ -9679,6 +9682,7 @@ dependencies = [ "anyhow", "chrono", "dirs", + "image", "miniz_oxide 0.8.9", "png", "serde", diff --git a/crates/voelin-core/src/cache.rs b/crates/voelin-core/src/cache.rs index 6eaf2ef..f3548a9 100644 --- a/crates/voelin-core/src/cache.rs +++ b/crates/voelin-core/src/cache.rs @@ -374,6 +374,28 @@ mod tests { assert!(matches!(cache.fetch("icons/7", false, Box::new(|_| {})), Fetch::Download(_))); } + #[test] + fn failed_picture_refresh_keeps_previous_file_and_can_retry() { + let dir = temp_dir("refresh-fail"); + let cache = Cache::new(&dir); + let key = picture_key("https://example.com/banner.png").unwrap(); + let path = put(&cache, &key, 32, 0); + let (tx, rx) = mpsc::channel(); + let Fetch::Download(temp) = cache.fetch(&key, true, Box::new(move |r| tx.send(r).unwrap())) + else { + panic!("refresh download"); + }; + std::fs::write(&temp, b"partial download").unwrap(); + cache.finish(&key, &temp, Err("connection lost".into()), 0); + assert_eq!(rx.recv().unwrap(), Err("connection lost".into())); + assert!(!temp.exists()); + assert_eq!(cache.get(&key), Some(path.clone())); + assert_eq!(std::fs::read(&path).unwrap(), vec![0u8; 32]); + assert_eq!(cache.size(), 32); + assert!(matches!(cache.fetch(&key, true, Box::new(|_| {})), Fetch::Download(_))); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn evicts_least_recently_used_and_survives_restart() { let dir = temp_dir("lru"); diff --git a/crates/voelin-core/src/session.rs b/crates/voelin-core/src/session.rs index 34e949c..91f8492 100644 --- a/crates/voelin-core/src/session.rs +++ b/crates/voelin-core/src/session.rs @@ -110,7 +110,9 @@ enum SourceEvent { /// Our avatar file is uploaded (its MD5) or failed: announce it. AvatarUploaded(u64, RequestId, Result), /// Time to fetch the host banner again (`banner_gfx_interval_s`). - ReloadBanner, + ReloadBanner(String), + /// A failed picture can be tried again on the next presence update. + PictureFailed(String), } /// Our live stream, for the gateway's directory. @@ -813,8 +815,9 @@ impl Session { /// Fetch the banners of the presence shown (any source) that are new, /// and have the host banner reloaded as often as the server asks. fn fetch_pictures(&mut self, p: &Presence) { + let enabled = self.settings.current().get(&CACHE_FETCH_IMAGES); let reload = Some((&p.server.banner_gfx_url, p.server.banner_gfx_interval_s)) - .filter(|(url, every)| !url.is_empty() && *every > 0); + .filter(|(url, every)| enabled && cache::picture_key(url).is_some() && *every > 0); if self.banner_reload.as_ref().map(|(url, every, _)| (url, *every)) != reload { if let Some((.., timer)) = self.banner_reload.take() { timer.abort(); @@ -822,13 +825,15 @@ impl Session { if let Some((url, every_s)) = reload { let every = std::time::Duration::from_secs(every_s).max(web::MIN_RELOAD); let tx = self.sources_tx.clone(); - // Ends with the session (nobody receives). + let address = url.clone(); + // Aborted when the banner changes or the session closes. let timer = tokio::spawn(async move { let start = tokio::time::Instant::now() + every; let mut tick = tokio::time::interval_at(start, every); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { tick.tick().await; - if tx.send(SourceEvent::ReloadBanner).is_err() { + if tx.send(SourceEvent::ReloadBanner(address.clone())).is_err() { break; } } @@ -836,12 +841,12 @@ impl Session { self.banner_reload = Some((url.clone(), every_s, timer.abort_handle())); } } - if !self.settings.current().get(&CACHE_FETCH_IMAGES) { + if !enabled { return; } let urls = std::iter::once(&p.server.banner_gfx_url) .chain(p.channels.values().filter_map(|c| c.banner_gfx_url.as_ref())); - for url in urls.filter(|u| !u.is_empty()) { + for url in urls.filter(|u| cache::picture_key(u).is_some()) { if self.pictures.insert(url.clone()) { self.fetch_picture(url, false); } @@ -851,11 +856,15 @@ impl Session { /// Get the picture at `url` into the cache (again with `fresh`). fn fetch_picture(&self, url: &str, fresh: bool) { let (session, events, address) = (self.id, self.events.clone(), url.to_owned()); + let sources = self.sources_tx.clone(); let waiter: Waiter = Box::new(move |result| match result { Ok(path) => { let _ = events.send(Event::PictureReady { session, url: address, path }); } - Err(e) => debug!(url = %address, "no picture: {e}"), + Err(e) => { + debug!(url = %address, "no picture: {e}"); + let _ = sources.send(SourceEvent::PictureFailed(address)); + } }); web::fetch(self.cache.current(), url, fresh, max_cache_bytes(&self.settings), waiter); } @@ -1288,6 +1297,9 @@ impl Session { } fn stop_all(&mut self) { + if let Some((.., timer)) = self.banner_reload.take() { + timer.abort(); + } self.stop_streams("session closed"); if let Some((_, tx)) = self.voice.take() { let _ = tx.send(VoiceCmd::Disconnect); @@ -1363,8 +1375,12 @@ impl Session { self.emit(Event::RequestDone { session: self.id, request, result }); } }, - SourceEvent::ReloadBanner => { + SourceEvent::PictureFailed(url) => { + self.pictures.remove(&url); + } + SourceEvent::ReloadBanner(address) => { if let Some((url, ..)) = &self.banner_reload + && *url == address && self.settings.current().get(&CACHE_FETCH_IMAGES) { self.fetch_picture(url, true); @@ -1687,3 +1703,91 @@ impl Session { self.emit(Event::Presence { session: self.id, presence }); } } + +#[cfg(test)] +mod banner_tests { + use super::*; + use crate::cache::Cache; + use crate::settings::Settings; + + fn session(tag: &str) -> (Session, broadcast::Receiver) { + let (events, receiver) = broadcast::channel(16); + let (frames, _) = broadcast::channel(1); + let history = SharedHistory::default(); + let dir = std::env::temp_dir() + .join(format!("voelin-session-banner-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let shared = Shared { + settings: SharedSettings::new(Settings::default()), + history: history.clone(), + cache: SharedCache::new(Cache::new(dir)), + contacts: Contacts::new(events.clone(), history), + }; + (Session::new(1, events, frames, AudioSettings::default(), shared), receiver) + } + + #[tokio::test] + async fn failed_picture_is_retried_on_next_presence() { + let (mut session, mut events) = session("retry"); + let mut presence = Presence::default(); + presence.server.banner_gfx_url = "https://example.com/banner.png".into(); + let url = &presence.server.banner_gfx_url; + let key = cache::picture_key(url).unwrap(); + let cache = session.cache.current(); + // Own the download so this exercises session completion without network I/O. + let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else { + panic!("first download"); + }; + session.fetch_pictures(&presence); + assert!(session.pictures.contains(url)); + cache.finish(&key, &temp, Err("temporary failure".into()), 0); + let failure = session.sources_rx.as_mut().unwrap().recv().await.unwrap(); + session.source_event(failure); + assert!(!session.pictures.contains(url)); + + let Fetch::Download(temp) = cache.fetch(&key, false, Box::new(|_| {})) else { + panic!("retry download"); + }; + session.fetch_pictures(&presence); + std::fs::create_dir_all(temp.parent().unwrap()).unwrap(); + std::fs::write(&temp, b"picture").unwrap(); + cache.finish(&key, &temp, Ok(()), 0); + assert!( + matches!(events.try_recv(), Ok(Event::PictureReady { url: ready, .. }) if ready == *url) + ); + assert!(session.pictures.contains(url)); + std::fs::remove_dir_all(cache.dir()).unwrap(); + } + + #[tokio::test] + async fn reload_timer_obeys_policy_and_is_stopped_with_session() { + let (mut session, _) = session("timer"); + let mut presence = Presence::default(); + presence.server.banner_gfx_url = "https://example.com/banner.png".into(); + presence.server.banner_gfx_interval_s = 60; + session.settings.current().set(&CACHE_FETCH_IMAGES, false).unwrap(); + session.fetch_pictures(&presence); + assert!(session.banner_reload.is_none()); + assert!(session.pictures.is_empty()); + + let cache = session.cache.current(); + let key = cache::picture_key(&presence.server.banner_gfx_url).unwrap(); + let _pending = cache.fetch(&key, false, Box::new(|_| {})); + session.settings.current().set(&CACHE_FETCH_IMAGES, true).unwrap(); + session.fetch_pictures(&presence); + let timer = session.banner_reload.as_ref().unwrap().2.clone(); + session.settings.current().set(&CACHE_FETCH_IMAGES, false).unwrap(); + session.fetch_pictures(&presence); + assert!(session.banner_reload.is_none()); + tokio::task::yield_now().await; + assert!(timer.is_finished()); + + session.settings.current().set(&CACHE_FETCH_IMAGES, true).unwrap(); + session.fetch_pictures(&presence); + let timer = session.banner_reload.as_ref().unwrap().2.clone(); + session.stop_all(); + assert!(session.banner_reload.is_none()); + tokio::task::yield_now().await; + assert!(timer.is_finished()); + } +} diff --git a/crates/voelin-core/src/settings.rs b/crates/voelin-core/src/settings.rs index 0b51b7f..40b3f70 100644 --- a/crates/voelin-core/src/settings.rs +++ b/crates/voelin-core/src/settings.rs @@ -1125,11 +1125,11 @@ pub static CACHE_MAX_MB: Key = Key::new( || 256, ); -/// Download the avatars and icons of servers we are on by themselves. +/// Download the avatars, icons and web banners of servers we are on. pub static CACHE_FETCH_IMAGES: Key = Key::new( "cache.fetch_images", Kind::Bool, - "Download avatars and icons of the servers we are on.", + "Download avatars, icons and web banners of the servers we are on.", || true, ); diff --git a/crates/voelin-core/tests/live.rs b/crates/voelin-core/tests/live.rs index 2579c72..43681d7 100644 --- a/crates/voelin-core/tests/live.rs +++ b/crates/voelin-core/tests/live.rs @@ -129,13 +129,16 @@ const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+ /// An HTTP server on 127.0.0.1 that answers every request with `body`; /// returns its address. The engine fetches banners itself (the server only /// passes their addresses on), so it reaches this one. -async fn serve(body: Vec) -> String { +async fn serve(body: Vec) -> (String, std::sync::Arc) { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); + let requests = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let count = requests.clone(); tokio::spawn(async move { while let Ok((mut socket, _)) = listener.accept().await { let body = body.clone(); + let count = count.clone(); tokio::spawn(async move { let mut request = Vec::new(); let mut buf = [0u8; 1024]; @@ -145,6 +148,7 @@ async fn serve(body: Vec) -> String { Ok(n) => request.extend_from_slice(&buf[..n]), } } + count.fetch_add(1, std::sync::atomic::Ordering::SeqCst); let head = format!( "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len() @@ -154,95 +158,187 @@ async fn serve(body: Vec) -> String { }); } }); - format!("http://{addr}") + (format!("http://{addr}"), requests) } -/// The host banner and a channel banner set through ServerQuery reach the -/// engine's cache (`Event::PictureReady`); the server is put back after. +/// Banner policy, channel edits/removal and the host refresh against a real TS6. +/// Override only this test's endpoints to use a private fixture. Server settings +/// and the temporary channel are restored even when the assertions panic. #[tokio::test(flavor = "multi_thread")] async fn ts6_banners() { use base64::Engine as _; + use std::sync::atomic::Ordering; + use voelin_core::settings::CACHE_FETCH_IMAGES; use voelin_model::BannerMode; use voelin_query::{Command as Query, QueryClient}; if !live() { return; } + let voice_addr = + std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into()); + let query_addr = + std::env::var("VOELIN_BANNER_QUERY_ADDR").unwrap_or_else(|_| "127.0.0.1:10022".into()); let png = base64::prelude::BASE64_STANDARD.decode(PNG).unwrap(); - let base = serve(png.clone()).await; + let (base, requests) = serve(png.clone()).await; let (host_url, channel_url) = (format!("{base}/host.png"), format!("{base}/channel.png")); - let (admin, _) = QueryClient::connect(&query(voelin_query::Transport::Ssh, "127.0.0.1:10022")) - .await - .unwrap(); + let (admin, _) = + QueryClient::connect(&query(voelin_query::Transport::Ssh, &query_addr)).await.unwrap(); let info = admin.send(&Query::new("serverinfo")).await.unwrap().remove(0); let before = |key: &str| info.get(key).unwrap_or_default().to_owned(); - let (old_url, old_mode) = - (before("virtualserver_hostbanner_gfx_url"), before("virtualserver_hostbanner_mode")); - let edit = Query::new("serveredit") - .arg("virtualserver_hostbanner_gfx_url", &host_url) - .arg("virtualserver_hostbanner_mode", 2); - admin.send(&edit).await.unwrap(); + let restore = Query::new("serveredit") + .arg("virtualserver_hostbanner_gfx_url", before("virtualserver_hostbanner_gfx_url")) + .arg("virtualserver_hostbanner_mode", before("virtualserver_hostbanner_mode")) + .arg( + "virtualserver_hostbanner_gfx_interval", + before("virtualserver_hostbanner_gfx_interval"), + ); let created = admin .send( &Query::new("channelcreate") .arg("channel_name", format!("banner-{}", std::process::id())) + .arg("channel_flag_permanent", 1) .arg("channel_banner_gfx_url", &channel_url) .arg("channel_banner_mode", 1), ) - .await; - + .await + .unwrap(); + let cid = created[0].get("cid").unwrap().to_owned(); + let channel_id: u64 = cid.parse().unwrap(); + let engine = Engine::start(); + engine.settings().set(&CACHE_FETCH_IMAGES, false).unwrap(); + let dir = std::env::temp_dir().join(format!("voelin-live-banners-{}", std::process::id())); + engine.send(Command::AttachCache(dir.clone())); let check = { - let (host_url, channel_url) = (host_url.clone(), channel_url.clone()); + let (admin, engine, cid) = (admin.clone(), engine.clone(), cid.clone()); tokio::spawn(async move { - let engine = Engine::start(); - let dir = - std::env::temp_dir().join(format!("voelin-live-banners-{}", std::process::id())); - engine.send(Command::AttachCache(dir.clone())); + admin + .send( + &Query::new("serveredit") + .arg("virtualserver_hostbanner_gfx_url", &host_url) + .arg("virtualserver_hostbanner_mode", 2) + .arg("virtualserver_hostbanner_gfx_interval", 60), + ) + .await + .unwrap(); let mut events = engine.subscribe(); engine.send(Command::ConnectVoice { session: 1, - options: Box::new(VoiceOptions::new("127.0.0.1:9988", "banner-check")), + options: Box::new(VoiceOptions::new(&voice_addr, "banner-check")), }); - let mut seen = std::collections::HashMap::new(); - let mut channel_mode = None; - wait_for(&mut events, "both banners", |e| { + wait_for(&mut events, "banner metadata with fetching disabled", |e| { + assert!( + !matches!(e, Event::PictureReady { .. }), + "disabled image fetching emitted a picture" + ); + matches!(e, Event::Presence { presence, .. } + if presence.server.banner_gfx_url == host_url + && presence.server.banner_mode == BannerMode::KeepAspect + && presence.channels.get(&channel_id).is_some_and(|c| + c.banner_gfx_url.as_deref() == Some(channel_url.as_str()) + && c.banner_mode == BannerMode::IgnoreAspect)) + }) + .await; + assert_eq!( + requests.load(Ordering::SeqCst), + 0, + "disabled policy must prevent HTTP requests" + ); + + // A new presence after opting in must fetch both existing banners. + engine.settings().set(&CACHE_FETCH_IMAGES, true).unwrap(); + admin + .send(&Query::new("channeledit").arg("cid", &cid).arg("channel_banner_mode", 2)) + .await + .unwrap(); + let mut seen = std::collections::HashSet::new(); + let mut changed_mode = false; + wait_for(&mut events, "both images and changed sizing mode", |e| { match e { Event::PictureReady { url, path, .. } => { - seen.insert(url.clone(), std::fs::read(path).unwrap()); + assert_eq!(std::fs::read(path).unwrap(), png); + seen.insert(url.clone()); } Event::Presence { presence, .. } => { - channel_mode = presence + changed_mode = presence .channels - .values() - .find(|c| c.banner_gfx_url.as_deref() == Some(channel_url.as_str())) - .map(|c| c.banner_mode); - assert_eq!(presence.server.banner_mode, BannerMode::KeepAspect); + .get(&channel_id) + .is_some_and(|c| c.banner_mode == BannerMode::KeepAspect); } _ => {} } - seen.contains_key(&host_url) && seen.contains_key(&channel_url) + changed_mode && seen.contains(&host_url) && seen.contains(&channel_url) }) .await; - assert_eq!(channel_mode, Some(BannerMode::IgnoreAspect)); - assert!(seen.values().all(|bytes| *bytes == png)); - engine.send(Command::CloseSession { session: 1 }); - tokio::time::sleep(Duration::from_millis(500)).await; - let _ = std::fs::remove_dir_all(dir); + + let replacement = format!("{base}/replacement.png"); + admin + .send( + &Query::new("channeledit") + .arg("cid", &cid) + .arg("channel_banner_gfx_url", &replacement) + .arg("channel_banner_mode", 0), + ) + .await + .unwrap(); + let (mut metadata, mut image) = (false, false); + wait_for(&mut events, "replacement channel banner", |e| { + match e { + Event::Presence { presence, .. } => { + metadata = presence.channels.get(&channel_id).is_some_and(|c| { + c.banner_gfx_url.as_deref() == Some(replacement.as_str()) + && c.banner_mode == BannerMode::NoAdjust + }); + } + Event::PictureReady { url, path, .. } if *url == replacement => { + assert_eq!(std::fs::read(path).unwrap(), png); + image = true; + } + _ => {} + } + metadata && image + }) + .await; + admin + .send(&Query::new("channeledit").arg("cid", &cid).arg("channel_banner_gfx_url", "")) + .await + .unwrap(); + wait_for(&mut events, "channel banner removed", |e| { + matches!(e, Event::Presence { presence, .. } if + presence.channels.get(&channel_id).is_some_and(|c| + c.banner_gfx_url.as_deref().is_none_or(str::is_empty))) + }) + .await; + + // The same host URL must be downloaded again, bypassing its cached file. + let before_reload = requests.load(Ordering::SeqCst); + let deadline = Instant::now() + Duration::from_secs(75); + loop { + let event = timeout_at(deadline, events.recv()) + .await + .expect("host banner did not reload after its 60-second interval") + .unwrap(); + if let Event::PictureReady { url, path, .. } = event + && url == host_url + { + assert_eq!(std::fs::read(path).unwrap(), png); + assert!( + requests.load(Ordering::SeqCst) > before_reload, + "reload must make a fresh HTTP request" + ); + break; + } + } }) }; let result = check.await; - - if let Ok(rows) = &created - && let Some(cid) = rows.first().and_then(|r| r.get("cid")) - { - let delete = Query::new("channeldelete").arg("cid", cid).arg("force", 1); - admin.send(&delete).await.unwrap(); - } - let restore = Query::new("serveredit") - .arg("virtualserver_hostbanner_gfx_url", old_url) - .arg("virtualserver_hostbanner_mode", old_mode); - admin.send(&restore).await.unwrap(); - created.unwrap(); - if let Err(e) = result { - std::panic::resume_unwind(e.into_panic()); + engine.send(Command::CloseSession { session: 1 }); + // Attempt both cleanup operations before reporting either failure. + let deleted = admin.send(&Query::new("channeldelete").arg("cid", &cid).arg("force", 1)).await; + let restored = admin.send(&restore).await; + let _ = std::fs::remove_dir_all(dir); + deleted.unwrap(); + restored.unwrap(); + if let Err(error) = result { + std::panic::resume_unwind(error.into_panic()); } } diff --git a/crates/voelin-ui/Cargo.toml b/crates/voelin-ui/Cargo.toml index 9b84489..171667d 100644 --- a/crates/voelin-ui/Cargo.toml +++ b/crates/voelin-ui/Cargo.toml @@ -20,6 +20,10 @@ path = "src/main.rs" anyhow = "1.0.104" chrono = { version = "0.4.45", default-features = false, features = ["clock"] } dirs = "6" +# Slint decodes pictures with `image`, which it builds with PNG and JPEG only; +# avatars, icons and banners on TeamSpeak servers are GIF and WebP too (the +# decoders are in the tree already, for SVG pictures). +image = { version = "0.25", default-features = false, features = ["gif", "webp"] } # Twemoji archive blocks (raw deflate); already used by png. miniz_oxide = "0.8" png = "0.18" diff --git a/crates/voelin-ui/src/app.rs b/crates/voelin-ui/src/app.rs index 27d95b1..673a420 100644 --- a/crates/voelin-ui/src/app.rs +++ b/crates/voelin-ui/src/app.rs @@ -210,8 +210,15 @@ pub(crate) struct SessionView { pub avatars: HashMap, /// Icons in the engine's cache, by icon id ([`Event::IconReady`]). pub icons: HashMap, + /// Banners in the engine's cache, by address ([`Event::PictureReady`]). + pub pictures: HashMap, + /// The server's icon id as its voice connection last told it + /// ([`Event::ServerDetails`]); kept while disconnected, for the rail. + pub server_icon: u32, /// The server groups in display order ([`Event::Groups`]). pub server_groups: Vec, + /// The channel groups ([`Event::Groups`]). + pub channel_groups: Vec, /// What the session's gateway offers (`voelin_gateway_proto::feature`). pub gateway_caps: Vec, /// The client whose member card is open. @@ -241,7 +248,10 @@ impl Default for SessionView { applied_playback: HashSet::new(), avatars: HashMap::new(), icons: HashMap::new(), + pictures: HashMap::new(), + server_icon: 0, server_groups: Vec::new(), + channel_groups: Vec::new(), gateway_caps: Vec::new(), member_card: None, stream_viewers: HashMap::new(), @@ -301,6 +311,13 @@ impl SessionView { let uid = self.presence.clients.get(&client)?.uid.as_deref()?; self.avatars.get(uid) } + + /// The server's icon, if it has one and the engine fetched it. + pub fn server_icon(&self) -> slint::Image { + crate::vm::avatar::image( + self.icons.get(&self.server_icon).filter(|_| self.server_icon != 0), + ) + } } /// The models the Bridge shows, created once and updated row by row @@ -915,30 +932,54 @@ impl App { self.gateway_extra(session as i64, &update); self.gateway_update(session as i64, update); } - Event::Groups { session, server_groups, .. } => { + Event::Groups { session, server_groups, channel_groups } => { let view = self.sessions.entry(session as i64).or_default(); view.server_groups = (*server_groups).clone(); // Display order, as TeamSpeak sorts them. view.server_groups.sort_by_key(|g| (g.sort_id, g.id)); + view.channel_groups = (*channel_groups).clone(); if self.current == Some(session as i64) { self.refresh_tree(); } } + Event::ServerDetails { session, details } => { + let view = self.sessions.entry(session as i64).or_default(); + if view.server_icon != details.icon { + view.server_icon = details.icon; + self.refresh_servers(); + } + } + // 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(); view.avatars.insert(client_uid, path); if self.current == Some(session as i64) { self.refresh_tree(); self.refresh_chat(); + self.refresh_toolbar(); + self.refresh_member_card(); + self.refresh_streams(); } } Event::IconReady { session, icon, path } => { let view = self.sessions.entry(session as i64).or_default(); view.icons.insert(icon, path); + self.refresh_servers(); if self.current == Some(session as i64) { self.refresh_tree(); } } + Event::PictureReady { session, url, path } => { + let view = self.sessions.entry(session as i64).or_default(); + // The host banner reloads into the same file. + crate::images::forget(&path); + view.pictures.insert(url, path); + if self.current == Some(session as i64) { + self.refresh_toolbar(); + self.refresh_tree(); + self.refresh_chat(); + } + } Event::Transfer { session, transfer, state } => { self.transfer_progress(session as i64, transfer, state); } diff --git a/crates/voelin-ui/src/chat.rs b/crates/voelin-ui/src/chat.rs index d31bff3..2afb8de 100644 --- a/crates/voelin-ui/src/chat.rs +++ b/crates/voelin-ui/src/chat.rs @@ -375,31 +375,33 @@ impl App { .unwrap_or_default(); (t, last, time) }) - .map(|(t, last, time)| ChatTab { - last: last.into(), - time: time.into(), - title: t.title.clone().into(), - name: t.title.trim_start_matches(['#', '@']).into(), - kind: match t.target { - ChatTarget::Server => 0, - ChatTarget::Channel(_) => 1, - ChatTarget::Private(_) => 2, - }, - id: match t.target { - ChatTarget::Channel(cid) => cid as i32, - _ => 0, - }, - unread: t.unread, - topic: match t.target { - ChatTarget::Channel(cid) => view - .presence - .channels - .get(&cid) - .and_then(|c| c.topic.clone()) - .unwrap_or_default() - .into(), - _ => Default::default(), - }, + .map(|(t, last, time)| { + let channel = match t.target { + ChatTarget::Channel(cid) => view.presence.channels.get(&cid), + _ => None, + }; + ChatTab { + last: last.into(), + time: time.into(), + title: t.title.clone().into(), + name: t.title.trim_start_matches(['#', '@']).into(), + kind: match t.target { + ChatTarget::Server => 0, + ChatTarget::Channel(_) => 1, + ChatTarget::Private(_) => 2, + }, + id: match t.target { + ChatTarget::Channel(cid) => cid as i32, + _ => 0, + }, + unread: t.unread, + topic: channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(), + banner: vm::tree::banner( + &view.pictures, + channel.and_then(|c| c.banner_gfx_url.as_deref()), + ), + banner_mode: channel.map_or(0, |c| vm::tree::banner_mode(c.banner_mode)), + } }) .collect(); vm::list::sync(&self.models.tabs, &tabs); diff --git a/crates/voelin-ui/src/dev.rs b/crates/voelin-ui/src/dev.rs index c238a23..107112e 100644 --- a/crates/voelin-ui/src/dev.rs +++ b/crates/voelin-ui/src/dev.rs @@ -58,7 +58,7 @@ use voelin_gateway_proto::{ feature, }; use voelin_model::{ - ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence, ServerFlavor, + BannerMode, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence, ServerFlavor, }; use voelin_store::{Bookmark, MessageSource}; @@ -385,17 +385,29 @@ fn demo_ui(app: &mut App) { p.server.welcome_message = "Welcome to [b]Nightfall Guild[/b]! Raids on Tuesdays and Fridays, all levels welcome." .into(); + // The host banner, a server icon, banners behind two channels and an icon + // on another; the pictures arrive below (`demo_pictures`). + p.server.banner_gfx_url = DEMO_HOST_BANNER.into(); + p.server.banner_mode = BannerMode::KeepAspect; + p.server.icon = DEMO_SERVER_ICON; let mut chill = channel(2, 0, 1, "Chill Zone"); chill.max_clients = Some(50); chill.topic = Some("Hang out, chat, and explore the worlds beyond.".into()); + chill.banner_gfx_url = Some(DEMO_CHILL_BANNER.into()); + chill.banner_mode = BannerMode::IgnoreAspect; + let mut raid = channel(4, 3, 0, "Raid Night"); + raid.banner_gfx_url = Some(DEMO_RAID_BANNER.into()); + raid.banner_mode = BannerMode::KeepAspect; + let mut music = channel(5, 0, 3, "Music"); + music.icon = DEMO_MUSIC_ICON; let mut locked = channel(7, 0, 6, "Officers"); locked.has_password = true; for c in [ channel(1, 0, 0, "Lobby"), chill, channel(3, 0, 2, "Gaming"), - channel(4, 3, 0, "Raid Night"), - channel(5, 0, 3, "Music"), + raid, + music, channel(6, 0, 5, "AFK"), locked, ] { @@ -443,7 +455,11 @@ fn demo_ui(app: &mut App) { let group = |id: u64, sort_id: i32, name: &str| GroupInfo { id, name: name.into(), - icon: 0, + icon: match id { + GROUP_ADMIN => DEMO_ADMIN_ICON, + GROUP_MOD => DEMO_MOD_ICON, + _ => 0, + }, sort_id, ..Default::default() }; @@ -517,6 +533,7 @@ fn demo_ui(app: &mut App) { for event in events { app.handle_event(event); } + demo_pictures(app); demo_chat(app, session); demo_social(app); // No toast over the screenshots. @@ -981,6 +998,145 @@ fn demo_social(app: &mut App) { app.refresh_home(); } +/// Addresses and icon ids of the sample server's pictures. +const DEMO_HOST_BANNER: &str = "https://nightfall.example/banner.png"; +const DEMO_CHILL_BANNER: &str = "https://nightfall.example/chill.png"; +const DEMO_RAID_BANNER: &str = "https://nightfall.example/raid.png"; +const DEMO_SERVER_ICON: u32 = 3_120_211_001; +const DEMO_ADMIN_ICON: u32 = 3_120_211_002; +const DEMO_MOD_ICON: u32 = 3_120_211_003; +const DEMO_MUSIC_ICON: u32 = 3_120_211_004; + +/// Avatars, icons and banners as the engine reports them once they are in +/// its cache (here a folder of synthetic pictures in the temporary +/// directory). +fn demo_pictures(app: &mut App) { + let session = DEMO as u64; + let dir = std::env::temp_dir().join("voelin-demo-pictures"); + let _ = std::fs::create_dir_all(&dir); + let save = |name: &str, png: Vec| { + let path = dir.join(name); + let _ = std::fs::write(&path, png); + path + }; + let mut events = vec![Event::ServerDetails { + session, + details: Arc::new(voelin_model::ServerDetails { + icon: DEMO_SERVER_ICON, + ..Default::default() + }), + }]; + for (url, picture) in [ + (DEMO_HOST_BANNER, demo_picture(560, 144, 3)), + (DEMO_CHILL_BANNER, demo_picture(900, 120, 11)), + (DEMO_RAID_BANNER, demo_picture(640, 160, 5)), + ] { + let path = save(url.rsplit('/').next().unwrap_or(url), picture); + events.push(Event::PictureReady { session, url: url.into(), path }); + } + for (icon, color, shape) in [ + (DEMO_SERVER_ICON, [70, 92, 255], Shape::Moon), + (DEMO_ADMIN_ICON, [242, 178, 44], Shape::Diamond), + (DEMO_MOD_ICON, [45, 196, 132], Shape::Disc), + (DEMO_MUSIC_ICON, [214, 76, 182], Shape::Ring), + ] { + let path = save(&icon.to_string(), demo_icon(color, shape)); + events.push(Event::IconReady { session, icon, path }); + } + // Some people have pictures, the rest initials. + for (sample_session, uid, seed) in [ + (session, "demo-2", 1), + (session, "demo-3", 2), + (session, "demo-4", 3), + (session, "demo-7", 4), + (session, "demo-9", 5), + (session + 1, "demo-ivy", 6), + ] { + let path = save(&format!("avatar-{uid}"), demo_avatar(seed)); + events.push(Event::AvatarReady { + session: sample_session, + client_uid: uid.into(), + path, + hash: String::new(), + }); + } + for event in events { + app.handle_event(event); + } +} + +/// Shapes of the sample icons. +#[derive(Clone, Copy)] +enum Shape { + Moon, + Diamond, + Disc, + Ring, +} + +/// A 32×32 icon: a shape in `color` on transparency; PNG bytes. +fn demo_icon(color: [u8; 3], shape: Shape) -> Vec { + let size = 32u32; + let mut rgba = Vec::with_capacity((size * size * 4) as usize); + for y in 0..size { + for x in 0..size { + let (dx, dy) = (x as f32 - 15.5, y as f32 - 15.5); + let d = (dx * dx + dy * dy).sqrt(); + let inside = match shape { + Shape::Moon => d < 14.0 && ((dx - 6.0).powi(2) + (dy + 5.0).powi(2)).sqrt() > 10.0, + Shape::Diamond => dx.abs() + dy.abs() < 15.0, + Shape::Disc => d < 13.0, + Shape::Ring => (8.0..14.0).contains(&d) || d < 4.0, + }; + let [r, g, b] = color; + rgba.extend(if inside { [r, g, b, 255] } else { [0, 0, 0, 0] }); + } + } + png_of(size, size, &rgba) +} + +/// A 96×96 portrait: a head and shoulders on a gradient; PNG bytes. +fn demo_avatar(seed: u32) -> Vec { + const SKY: [[f32; 3]; 6] = [ + [255.0, 140.0, 90.0], + [90.0, 170.0, 255.0], + [170.0, 110.0, 255.0], + [60.0, 200.0, 170.0], + [250.0, 200.0, 80.0], + [240.0, 110.0, 160.0], + ]; + let size = 96u32; + let sky = SKY[seed as usize % SKY.len()]; + let mut rgba = Vec::with_capacity((size * size * 4) as usize); + for y in 0..size { + for x in 0..size { + let (fx, fy) = (x as f32, y as f32); + let t = (fx + fy) / (2.0 * size as f32); + let mut c = + [sky[0] * (1.0 - 0.45 * t), sky[1] * (1.0 - 0.45 * t), sky[2] * (1.0 - 0.3 * t)]; + let head = ((fx - 48.0).powi(2) + (fy - 40.0).powi(2)).sqrt() < 19.0; + let shoulders = ((fx - 48.0) / 36.0).powi(2) + ((fy - 98.0) / 30.0).powi(2) < 1.0; + if head || shoulders { + c = [250.0 - c[0] * 0.25, 244.0 - c[1] * 0.25, 238.0 - c[2] * 0.2]; + } + rgba.extend([c[0] as u8, c[1] as u8, c[2] as u8, 255]); + } + } + png_of(size, size, &rgba) +} + +/// RGBA pixels as PNG bytes. +fn png_of(width: u32, height: u32, rgba: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut encoder = png::Encoder::new(&mut out, width, height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + if let Ok(mut writer) = encoder.write_header() { + let _ = writer.write_image_data(rgba); + } + out +} + /// A painted night: sky, moon, stars, hills and a castle; PNG bytes. fn demo_picture(width: u32, height: u32, seed: u32) -> Vec { let mut rgba = Vec::with_capacity((width * height * 4) as usize); @@ -1031,14 +1187,7 @@ fn demo_picture(width: u32, height: u32, seed: u32) -> Vec { rgba.extend([c[0].min(255.0) as u8, c[1].min(255.0) as u8, c[2].min(255.0) as u8, 255]); } } - let mut out = Vec::new(); - let mut encoder = png::Encoder::new(&mut out, width, height); - encoder.set_color(png::ColorType::Rgba); - encoder.set_depth(png::BitDepth::Eight); - if let Ok(mut writer) = encoder.write_header() { - let _ = writer.write_image_data(&rgba); - } - out + png_of(width, height, &rgba) } /// Server group ids of the sample server. diff --git a/crates/voelin-ui/src/images.rs b/crates/voelin-ui/src/images.rs index c986b61..34c35d4 100644 --- a/crates/voelin-ui/src/images.rs +++ b/crates/voelin-ui/src/images.rs @@ -1,4 +1,4 @@ -//! Decoded images by key (emoji now; avatars and server icons later): each +//! Decoded images by key (emoji, avatars, icons and banners): each //! is decoded once and kept while it fits the budget (setting //! `ui.image_cache_mb`); the least recently used go first. //! @@ -8,6 +8,7 @@ use std::cell::RefCell; use std::collections::{BTreeMap, HashMap}; +use std::io::Cursor; use slint::Image; @@ -67,6 +68,14 @@ impl Lru { Some(value) } + /// Drop `key`, so the next use loads it again. + pub fn remove(&mut self, key: &str) { + if let Some((_, cost, tick)) = self.entries.remove(key) { + self.order.remove(&tick); + self.used -= cost; + } + } + fn evict(&mut self) { while self.used > self.budget { let Some((_, key)) = self.order.pop_first() else { break }; @@ -112,27 +121,52 @@ 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()?; - let image = Image::load_from_data(&bytes, None).ok()?; - let size = image.size(); - Some((image, size.width as usize * size.height as usize * 4)) + decode(&bytes) }) }) .unwrap_or_default() } +/// Forget the decoded picture of a file that changed (a reloaded banner). +pub fn forget(path: &std::path::Path) { + CACHE.with(|c| c.borrow_mut().remove(&path.to_string_lossy())); +} + +/// Compressed pictures can be small on disk but huge when decoded. Check +/// raster dimensions before Slint allocates pixels on the UI thread. SVGs +/// keep Slint's native vector loader and are rasterized at the displayed size. +fn decode(bytes: &[u8]) -> Option<(Image, usize)> { + let reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?; + let cost = if reader.format().is_some() { + let (width, height) = reader.into_dimensions().ok()?; + // At most the default decoded-image cache (64 MiB of RGBA). + if width == 0 + || height == 0 + || width > 16_384 + || height > 16_384 + || u64::from(width) * u64::from(height) * 4 > 64 << 20 + { + tracing::debug!(width, height, "image exceeds the decoded raster size limit"); + return None; + } + width as usize * height as usize * 4 + } else { + let start = bytes.trim_ascii_start(); + if !start.starts_with(b" Image { let cache_key = format!("picture:{key}"); - CACHE - .with(|c| { - c.borrow_mut().get_or_load(&cache_key, || { - let image = Image::load_from_data(bytes, None).ok()?; - let size = image.size(); - Some((image, size.width as usize * size.height as usize * 4)) - }) - }) - .unwrap_or_default() + CACHE.with(|c| c.borrow_mut().get_or_load(&cache_key, || decode(bytes))).unwrap_or_default() } /// A Twemoji by key; an empty image if there is none. @@ -182,6 +216,13 @@ mod tests { assert_eq!(lru.usage(), (0, 0)); // Unknown keys are not cached. assert_eq!(lru.get_or_load("none", || None), None); + lru.set_budget(10); + get(&mut lru, "a", 4); + lru.remove("a"); + lru.remove("never"); + assert_eq!((lru.usage(), lru.len()), ((0, 10), 0)); + get(&mut lru, "a", 4); + assert_eq!(loads.get(), 7, "loaded again after remove"); } #[test] @@ -195,6 +236,47 @@ mod tests { assert_eq!(picture("test:junk", b"not a picture").size().width, 0); } + #[test] + fn large_svg_coordinates_do_not_overflow_the_cache_cost() { + let svg = br#""#; + let (image, cost) = decode(svg).unwrap(); + assert!(image.size().width > 0); + assert_eq!(cost, svg_cost(svg.len())); + assert!(picture("test:large-svg", svg).size().width > 0); + } + + #[test] + fn oversized_rasters_are_refused_before_pixels_are_read() { + use std::io::Write; + for (width, height) in [(6000, 6000), (16_385, 1), (1, 16_385)] { + let mut bytes = Vec::new(); + let mut encoder = png::Encoder::new(&mut bytes, width, height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().unwrap(); + let mut stream = writer.stream_writer().unwrap(); + let row = vec![255; width as usize * 4]; + for _ in 0..height { + stream.write_all(&row).unwrap(); + } + stream.finish().unwrap(); + writer.finish().unwrap(); + // A valid solid picture fits the download cap but not the + // decoded budget. Generate it a row at a time, without ever + // allocating the large pixel buffer this test guards against. + assert!(bytes.len() < 4 << 20); + assert_eq!( + image::ImageReader::new(Cursor::new(&bytes)) + .with_guessed_format() + .unwrap() + .into_dimensions() + .unwrap(), + (width, height) + ); + assert!(decode(&bytes).is_none()); + } + } + /// Cached avatars and icons are named without an extension. #[test] fn cached_files_decode_by_content() { @@ -207,11 +289,38 @@ mod tests { encoder.write_header().unwrap().write_image_data(&[90; 24]).unwrap(); let svg = br#" "#; - for (name, bytes, width) in [("287478770", &png[..], 3), ("413901487", &svg[..], 16)] { + // GIF avatars and banners are common on TeamSpeak 3 servers. + let gif = b"GIF89a\x01\0\x01\0\x80\0\0\xff\xff\xff\0\0\0!\xf9\x04\x01\0\0\0\0,\0\0\0\0\x01\0\x01\0\0\x02\x02D\x01\0;"; + let mut webp = Vec::new(); + image::ImageEncoder::write_image( + image::codecs::webp::WebPEncoder::new_lossless(&mut webp), + &[90; 24], + 3, + 2, + image::ExtendedColorType::Rgba8, + ) + .unwrap(); + for (name, bytes, width) in [ + ("287478770", &png[..], 3), + ("413901487", &svg[..], 16), + ("gif", &gif[..], 1), + ("webp", &webp[..], 3), + ] { let path = dir.join(name); std::fs::write(&path, bytes).unwrap(); assert_eq!(file(&path).size().width, width, "{name}"); } + // A file that changed is decoded again once forgotten. + let path = dir.join("287478770"); + let mut wider = Vec::new(); + let mut encoder = png::Encoder::new(&mut wider, 5, 2); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder.write_header().unwrap().write_image_data(&[90; 40]).unwrap(); + std::fs::write(&path, wider).unwrap(); + assert_eq!(file(&path).size().width, 3, "kept until forgotten"); + forget(&path); + assert_eq!(file(&path).size().width, 5); std::fs::remove_dir_all(dir).unwrap(); } diff --git a/crates/voelin-ui/src/servers.rs b/crates/voelin-ui/src/servers.rs index f362e5f..09fb121 100644 --- a/crates/voelin-ui/src/servers.rs +++ b/crates/voelin-ui/src/servers.rs @@ -322,7 +322,8 @@ impl App { .map(|v| vm::tree::stats(&v.presence)) .unwrap_or_default(); let flavor = view.map(|v| v.extra.flavor.clone()).unwrap_or_default(); - vm::servers::item(b, &state, unread, live, detail, flavor) + let icon = view.map(|v| v.server_icon()).unwrap_or_default(); + vm::servers::item(b, &state, unread, live, detail, flavor, icon) }) .collect(); vm::list::sync(&self.models.servers, &items); @@ -349,12 +350,25 @@ impl App { .into(), ); bridge.set_nickname(bookmark.map(|b| b.nickname.clone()).unwrap_or_default().into()); + let own = view.zip(state.own_client).and_then(|(v, c)| v.avatar(c)); + bridge.set_own_avatar(vm::avatar::image(own)); + let banner = |url: Option<&str>| { + view.map(|v| vm::tree::banner(&v.pictures, url)).unwrap_or_default() + }; + let details = view.map(|v| &v.presence.server); + bridge.set_server_banner(banner(details.map(|d| d.banner_gfx_url.as_str()))); + 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_topic( own_channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(), ); + bridge + .set_own_channel_banner(banner(own_channel.and_then(|c| c.banner_gfx_url.as_deref()))); + bridge.set_own_channel_banner_mode( + own_channel.map_or(0, |c| vm::tree::banner_mode(c.banner_mode)), + ); bridge.set_own_channel_limit( own_channel.and_then(|c| c.max_clients).filter(|m| *m >= 0).unwrap_or(-1), ); @@ -401,7 +415,9 @@ impl App { filter: "", avatars: &view.avatars, icons: &view.icons, + pictures: &view.pictures, groups: &view.server_groups, + channel_groups: &view.channel_groups, }; vm::list::sync(&self.models.tree, &vm::tree::rows(&input)); let connected = view.state.voice == VoiceState::Connected; diff --git a/crates/voelin-ui/src/social.rs b/crates/voelin-ui/src/social.rs index 670dbaf..69b99b0 100644 --- a/crates/voelin-ui/src/social.rs +++ b/crates/voelin-ui/src/social.rs @@ -958,6 +958,11 @@ impl App { subtitle: b.address.clone().into(), initials: vm::avatar::initials(&b.name).into(), tint: vm::avatar::tint(&b.name), + avatar: self + .sessions + .get(&b.id) + .map(|v| v.server_icon()) + .unwrap_or_default(), ..Default::default() }, Found::Server(b.id), diff --git a/crates/voelin-ui/src/streams.rs b/crates/voelin-ui/src/streams.rs index cfc15b2..cd1a4de 100644 --- a/crates/voelin-ui/src/streams.rs +++ b/crates/voelin-ui/src/streams.rs @@ -379,6 +379,9 @@ impl App { } .into(), message: v.message.clone().into(), + avatar: crate::vm::avatar::image( + view.and_then(|view| view.avatar(v.client.0)), + ), }) .collect() }) diff --git a/crates/voelin-ui/src/vm/servers.rs b/crates/voelin-ui/src/vm/servers.rs index b31c2ae..7564f1b 100644 --- a/crates/voelin-ui/src/vm/servers.rs +++ b/crates/voelin-ui/src/vm/servers.rs @@ -19,7 +19,7 @@ pub fn status(state: &SessionState) -> &'static str { /// A server of the rail and the home page. `unread`: messages in its /// chats; `live`: streams on it; `detail`: who is there ("9 online · 7 /// channels"), empty for its address; `flavor`: "TeamSpeak 6" once -/// reached. +/// reached; `icon`: the server's icon (empty: its initials). pub fn item( bookmark: &Bookmark, state: &SessionState, @@ -27,6 +27,7 @@ pub fn item( live: bool, detail: String, flavor: String, + icon: slint::Image, ) -> ServerItem { ServerItem { id: bookmark.id as i32, @@ -35,6 +36,7 @@ pub fn item( status: status(state).into(), initials: avatar::initials(&bookmark.name).into(), tint: avatar::tint(&bookmark.name), + icon, unread, live, detail: if detail.is_empty() { bookmark.address.clone() } else { detail }.into(), diff --git a/crates/voelin-ui/src/vm/tree.rs b/crates/voelin-ui/src/vm/tree.rs index bac0197..01e7c69 100644 --- a/crates/voelin-ui/src/vm/tree.rs +++ b/crates/voelin-ui/src/vm/tree.rs @@ -4,12 +4,26 @@ use std::collections::{HashMap, HashSet}; use std::path::PathBuf; -use voelin_model::{ChannelId, ClientInfo, GroupInfo, Presence, TreeRow, tree_rows}; +use voelin_model::{BannerMode, ChannelId, ClientInfo, GroupInfo, Presence, TreeRow, tree_rows}; use crate::app::{MemberItem, TreeItem}; use crate::settings::ClientPlaybackMap; use crate::vm::avatar; +/// A banner mode as the UI takes it (`TreeItem.banner-mode`). +pub fn banner_mode(mode: BannerMode) -> i32 { + match mode { + BannerMode::NoAdjust => 0, + BannerMode::IgnoreAspect => 1, + BannerMode::KeepAspect => 2, + } +} + +/// The picture of a banner address, if the engine fetched it. +pub fn banner(pictures: &HashMap, url: Option<&str>) -> slint::Image { + avatar::image(url.and_then(|u| pictures.get(u))) +} + /// What the tree shows besides the presence. pub struct TreeInput<'a> { pub presence: &'a Presence, @@ -23,11 +37,16 @@ pub struct TreeInput<'a> { pub filter: &'a str, /// Avatar pictures in the engine's cache, by unique id. pub avatars: &'a HashMap, - /// Icons in the engine's cache, by icon id (group icons). + /// Icons in the engine's cache, by icon id (channel, group and client + /// icons). pub icons: &'a HashMap, + /// Banner pictures in the engine's cache, by address. + pub pictures: &'a HashMap, /// The server groups in display order; members are grouped by the /// first one each client is in. pub groups: &'a [GroupInfo], + /// The channel groups (their icons). + pub channel_groups: &'a [GroupInfo], } impl TreeInput<'_> { @@ -35,6 +54,26 @@ impl TreeInput<'_> { avatar::image(client.uid.as_ref().and_then(|uid| self.avatars.get(uid))) } + /// An icon by id, if the engine fetched it (0: none). + fn icon(&self, id: u32) -> Option { + let path = self.icons.get(&id).filter(|_| id != 0)?; + Some(avatar::image(Some(path))).filter(|i| i.size().width > 0) + } + + /// The icons beside a client, as TeamSpeak shows them: its server + /// groups' in display order, its channel group's, its own. + fn client_icons(&self, client: &ClientInfo) -> Vec { + let groups = self.groups.iter().filter(|g| client.server_groups.contains(&g.id)); + let channel_group = + self.channel_groups.iter().filter(|g| client.channel_group == Some(g.id)); + groups + .chain(channel_group) + .map(|g| g.icon) + .chain([client.icon]) + .filter_map(|id| self.icon(id)) + .collect() + } + /// The group a client is sorted under: the first of its server groups /// in display order. fn group_of(&self, client: &ClientInfo) -> Option<&GroupInfo> { @@ -80,6 +119,9 @@ pub fn rows(input: &TreeInput) -> Vec { local_volume: 100, members: p.members(channel.id).count() as i32, max_members: channel.max_clients.filter(|m| *m >= 0).unwrap_or(-1), + icon: input.icon(channel.icon).unwrap_or_default(), + banner: banner(input.pictures, channel.banner_gfx_url.as_deref()), + banner_mode: banner_mode(channel.banner_mode), ..Default::default() }, TreeRow::Client { depth, client } => { @@ -89,6 +131,7 @@ pub fn rows(input: &TreeInput) -> Vec { .and_then(|uid| input.playback.get(uid)) .copied() .unwrap_or_default(); + let mut icons = input.client_icons(client).into_iter(); TreeItem { is_channel: false, depth: depth as i32, @@ -105,6 +148,9 @@ pub fn rows(input: &TreeInput) -> Vec { initials: avatar::initials(&client.nickname).into(), tint: avatar::tint(&client.nickname), avatar: input.avatar(client), + icon: icons.next().unwrap_or_default(), + icon_2: icons.next().unwrap_or_default(), + icon_3: icons.next().unwrap_or_default(), ..Default::default() } } @@ -235,12 +281,7 @@ fn sectioned( fn group_section(input: &TreeInput, client: &ClientInfo) -> (Section, usize) { match input.group_of(client) { Some(g) => ( - Section { - title: g.name.clone(), - icon: avatar::image( - Some(g.icon).filter(|i| *i != 0).and_then(|i| input.icons.get(&i)), - ), - }, + Section { title: g.name.clone(), icon: input.icon(g.icon).unwrap_or_default() }, 1 + input.group_rank(client), ), None => (Section { title: "Online".into(), ..Default::default() }, usize::MAX), @@ -349,7 +390,9 @@ mod tests { struct Extras { avatars: HashMap, icons: HashMap, + pictures: HashMap, groups: Vec, + channel_groups: Vec, } fn input<'a>( @@ -370,10 +413,73 @@ mod tests { filter, avatars: &extras.avatars, icons: &extras.icons, + pictures: &extras.pictures, groups: &extras.groups, + channel_groups: &extras.channel_groups, } } + /// A PNG of this width in a file (the engine's cache names them without + /// an extension). + fn picture_file(dir: &std::path::Path, name: &str, width: u32) -> PathBuf { + let mut png = Vec::new(); + let mut encoder = png::Encoder::new(&mut png, width, 2); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder.write_header().unwrap().write_image_data(&vec![120; width as usize * 8]).unwrap(); + let path = dir.join(name); + std::fs::write(&path, png).unwrap(); + path + } + + /// Avatars, channel icons and banners, group and client icons (in + /// TeamSpeak's order, those that arrived) reach the rows. + #[test] + fn pictures_in_rows() { + let dir = std::env::temp_dir().join(format!("voelin-tree-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut p = presence(); + let lobby = p.channels.get_mut(&1).unwrap(); + lobby.icon = 2001; + lobby.banner_gfx_url = Some("https://e.com/lobby.png".into()); + lobby.banner_mode = BannerMode::KeepAspect; + let alice = p.clients.get_mut(&10).unwrap(); + alice.uid = Some("alice=".into()); + alice.server_groups = vec![7, 6]; + alice.channel_group = Some(5); + alice.icon = 4004; + let group = |id, sort_id, icon| GroupInfo { id, icon, sort_id, ..Default::default() }; + let e = Extras { + avatars: HashMap::from([("alice=".into(), picture_file(&dir, "avatar", 5))]), + icons: HashMap::from([ + (2001, picture_file(&dir, "2001", 7)), + (3003, picture_file(&dir, "3003", 3)), + (4004, picture_file(&dir, "4004", 4)), + (5005, picture_file(&dir, "5005", 6)), + ]), + pictures: HashMap::from([( + "https://e.com/lobby.png".into(), + picture_file(&dir, "banner", 9), + )]), + // Group 7 sorts first; group 6's icon has not arrived. + groups: vec![group(7, 10, 3003), group(6, 20, 9999)], + channel_groups: vec![group(5, 0, 5005)], + }; + let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new()); + let rows = rows(&input(&p, &t, &c, &pb, "", &e)); + let width = |i: &slint::Image| i.size().width; + let lobby = &rows[0]; + assert_eq!((width(&lobby.icon), width(&lobby.banner), lobby.banner_mode), (7, 9, 2)); + let alice = &rows[1]; + assert_eq!(width(&alice.avatar), 5); + assert_eq!([&alice.icon, &alice.icon_2, &alice.icon_3].map(width), [3, 6, 4]); + // Nothing for the others. + let games = &rows[2]; + assert_eq!((width(&games.icon), width(&games.banner), games.banner_mode), (0, 0, 0)); + assert_eq!(width(&rows[3].avatar), 0); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn tree_rows_and_counts() { let p = presence(); diff --git a/crates/voelin-ui/ui/app.slint b/crates/voelin-ui/ui/app.slint index 26a3b0e..f7ecd20 100644 --- a/crates/voelin-ui/ui/app.slint +++ b/crates/voelin-ui/ui/app.slint @@ -214,6 +214,12 @@ export component MainWindow inherits Window { } if Nav.narrow && root.chrome: MobileShell { + property channel-chat: Nav.page == Page.server && !Nav.phone-voice + && Nav.mobile-tab == MobileTab.chat && !Bridge.viewer-open + && Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length + && Bridge.tabs[Bridge.current-tab].kind == 1; + banner: self.channel-chat ? Bridge.tabs[Bridge.current-tab].banner : @image-url(""); + banner-mode: self.channel-chat ? Bridge.tabs[Bridge.current-tab].banner-mode : 0; title: Nav.page == Page.settings ? @tr("Settings") : Nav.page == Page.friends ? @tr("Friends") : Nav.page == Page.messages ? @tr("Messages") diff --git a/crates/voelin-ui/ui/bridge.slint b/crates/voelin-ui/ui/bridge.slint index 50fc209..8d3bc35 100644 --- a/crates/voelin-ui/ui/bridge.slint +++ b/crates/voelin-ui/ui/bridge.slint @@ -11,6 +11,8 @@ export struct ServerItem { // Avatar of a server without an icon. initials: string, tint: color, + // The server's icon, empty without one. + icon: image, // Unread messages in its chats. unread: int, // Someone streams in our channel there. @@ -50,6 +52,16 @@ export struct TreeItem { // Channels: clients inside, and the limit (-1: none). members: int, max-members: int, + // Icons at the end of the row, empty where there is none: a channel's + // icon; a client's server group icons, its channel group's and its own, + // in that order (the first three). + icon: image, + icon-2: image, + icon-3: image, + // A channel's banner picture (TeamSpeak 6), drawn behind the row; + // banner-mode: 0 as it is, 1 stretched, 2 scaled keeping its aspect. + banner: image, + banner-mode: int, } // A client for the members panel (everyone on the server) and the voice @@ -129,6 +141,9 @@ export struct ChatTab { // The last message ("Mira: the banner I promised") and its time. last: string, time: string, + // The channel's banner picture behind the chat's header (as TreeItem). + banner: image, + banner-mode: int, } // A piece of a chat line: text, or an emoji shown as an image (`emoji` is @@ -259,6 +274,8 @@ export struct ViewerItem { name: string, state: string, message: string, + // Their avatar picture, empty without one. + avatar: image, } // A capture source for the share dialog. @@ -800,12 +817,21 @@ export global Bridge { in property server-title: @tr("No server selected"); // "12 online · 8 channels" in property server-stats; - // Our nickname on the current server, and the channel we are in. + // The server's host banner, empty without one (the server card shows its + // painted art then); mode as TreeItem.banner-mode. + in property server-banner; + in property server-banner-mode; + // Our nickname on the current server, our avatar there (empty without + // one), and the channel we are in. in property nickname; + in property own-avatar; in property own-channel; // Its topic, and how many people it takes (-1: no limit). in property own-channel-topic; in property own-channel-limit: -1; + // Its banner picture (TeamSpeak 6), as TreeItem.banner. + in property own-channel-banner; + in property own-channel-banner-mode; in property voice-connected; in property voice-connecting; in property observing; diff --git a/crates/voelin-ui/ui/components/banner-picture.slint b/crates/voelin-ui/ui/components/banner-picture.slint new file mode 100644 index 0000000..8c5faf9 --- /dev/null +++ b/crates/voelin-ui/ui/components/banner-picture.slint @@ -0,0 +1,29 @@ +import { Theme } from "../theme.slint"; + +// A server's banner picture (the host banner, a TeamSpeak 6 channel banner) +// filling its area, behind other content. `mode` as the server sets it: +// 0 as it is (centred), 1 stretched, 2 scaled to fit keeping its aspect +// ratio. A wash of `scrim-color` at `scrim` opacity over it keeps text on +// top readable. +export component BannerPicture inherits Rectangle { + in property source; + in property mode; + in property scrim-color: Theme.surface; + // Keep small text readable over even a solid white/black banner in + // both themes. Text-free artwork can explicitly turn this off. + in property scrim: 0.9; + clip: true; + accessible-role: AccessibleRole.none; + Image { + width: 100%; + height: 100%; + source: root.source; + image-fit: root.mode == 1 ? ImageFit.fill : root.mode == 2 ? ImageFit.contain : ImageFit.preserve; + horizontal-alignment: center; + vertical-alignment: center; + accessible-role: AccessibleRole.none; + } + if root.scrim > 0: Rectangle { + background: root.scrim-color.transparentize(1 - root.scrim); + } +} diff --git a/crates/voelin-ui/ui/components/index.slint b/crates/voelin-ui/ui/components/index.slint index df39879..b67248d 100644 --- a/crates/voelin-ui/ui/components/index.slint +++ b/crates/voelin-ui/ui/components/index.slint @@ -9,6 +9,7 @@ export { Toggle, ToggleRow, RadioRow } from "toggle.slint"; export { Slider } from "slider.slint"; export { SegmentedTabs, TabItem } from "tabs.slint"; export { Status, Avatar } from "avatar.slint"; +export { BannerPicture } from "banner-picture.slint"; export { CountBadge, LiveBadge, Chip, Dot } from "badge.slint"; export { SectionHeader, Card, Divider, Banner } from "card.slint"; export { Meter, SpeakingBars } from "meter.slint"; diff --git a/crates/voelin-ui/ui/screens/channels.slint b/crates/voelin-ui/ui/screens/channels.slint index 4e85959..882dd4e 100644 --- a/crates/voelin-ui/ui/screens/channels.slint +++ b/crates/voelin-ui/ui/screens/channels.slint @@ -5,7 +5,7 @@ import { Theme } from "../theme.slint"; import { Icons } from "../icons.slint"; import { Bridge, TreeItem } from "../bridge.slint"; import { Nav } from "../nav.slint"; -import { Icon, Button, ButtonKind, IconButton, Avatar, LiveBadge, Chip, SectionHeader, SpeakingBars, PopupMenu, MenuEntry, ListView } from "../components/index.slint"; +import { Icon, Button, ButtonKind, IconButton, Avatar, LiveBadge, Chip, SectionHeader, SpeakingBars, PopupMenu, MenuEntry, ListView, BannerPicture } from "../components/index.slint"; // The banner at the top of the sidebar: server name, counts, a menu. export component ServerHeader inherits Rectangle { @@ -15,8 +15,24 @@ export component ServerHeader inherits Rectangle { background: Theme.surface-2; accessible-role: AccessibleRole.groupbox; accessible-label: Bridge.server-title; - // Painted banner: a night sky gradient with a horizon glow. - Rectangle { + // The server's host banner, fading into the card. + if Bridge.server-banner.width > 0: Rectangle { + height: 72px; + y: 0; + BannerPicture { + source: Bridge.server-banner; + mode: Bridge.server-banner-mode; + scrim: 0; + } + Rectangle { + y: parent.height - 30px; + height: 30px; + background: @linear-gradient(180deg, transparent 0%, Theme.surface-2 100%); + } + } + // Without one, a painted banner: a night sky gradient with a horizon + // glow. + if Bridge.server-banner.width == 0: Rectangle { height: 72px; y: 0; background: @linear-gradient(180deg, #1a2d7a 0%, #3a2a8f 45%, #0b1330 100%); @@ -117,6 +133,20 @@ export component ConnectActions inherits HorizontalLayout { } } +// A server's icon (channel, group, client) at the end of a tree row, in its +// own colours. +component RowIcon inherits VerticalLayout { + in property source; + alignment: center; + Image { + width: 16px; + height: 16px; + source: root.source; + image-fit: contain; + accessible-role: AccessibleRole.none; + } +} + // One row of the tree: a channel or a client. component TreeRow inherits Rectangle { in property item; @@ -137,6 +167,14 @@ component TreeRow inherits Rectangle { client-clicked(item.id); } } + // The channel's banner behind its row, washed so the name stays + // readable (the own channel's tint over it). + if item.is-channel && item.banner.width > 0: BannerPicture { + border-radius: root.border-radius; + source: item.banner; + mode: item.banner-mode; + scrim-color: item.own ? Theme.accent-soft : area.has-hover ? Theme.surface-3 : Theme.surface; + } area := TouchArea { mouse-cursor: MouseCursor.pointer; double-clicked => { @@ -178,12 +216,16 @@ component TreeRow inherits Rectangle { } Text { text: item.name; - color: item.own ? Theme.text : Theme.text-secondary; - font-weight: item.own ? Theme.weight-semibold : Theme.weight-medium; + // Full contrast over a banner. + color: item.own || item.banner.width > 0 ? Theme.text : Theme.text-secondary; + font-weight: item.own || item.banner.width > 0 ? Theme.weight-semibold : Theme.weight-medium; vertical-alignment: center; horizontal-stretch: 1; overflow: elide; } + if item.icon.width > 0: RowIcon { + source: item.icon; + } if item.members > 0 || item.max-members >= 0: HorizontalLayout { spacing: 3px; if item.own: Icon { @@ -194,7 +236,7 @@ component TreeRow inherits Rectangle { } Text { text: item.max-members >= 0 ? item.members + "/" + item.max-members : item.members; - color: item.own ? Theme.text : Theme.text-muted; + color: item.own ? Theme.text : item.banner.width > 0 ? Theme.text-secondary : Theme.text-muted; font-size: Theme.font-sm; vertical-alignment: center; } @@ -210,6 +252,7 @@ component TreeRow inherits Rectangle { size: 22px; initials: item.initials; tint: item.tint; + image: item.avatar; speaking: item.talking; label: item.name; } @@ -283,6 +326,16 @@ component TreeRow inherits Rectangle { font-size: Theme.font-xs; vertical-alignment: center; } + // Group and client icons. + if item.icon.width > 0: RowIcon { + source: item.icon; + } + if item.icon-2.width > 0: RowIcon { + source: item.icon-2; + } + if item.icon-3.width > 0: RowIcon { + source: item.icon-3; + } } } diff --git a/crates/voelin-ui/ui/screens/chat.slint b/crates/voelin-ui/ui/screens/chat.slint index f5cb672..db07755 100644 --- a/crates/voelin-ui/ui/screens/chat.slint +++ b/crates/voelin-ui/ui/screens/chat.slint @@ -6,16 +6,23 @@ import { Theme } from "../theme.slint"; import { Icons } from "../icons.slint"; import { Bridge, ChatLine, ReactionItem, FileItem, Images } from "../bridge.slint"; import { Nav } from "../nav.slint"; -import { Icon, IconButton, Avatar, Chip, TabItem, TextField, RichText, Banner, Button, ButtonKind, Spinner, Tooltip, ListView } from "../components/index.slint"; +import { Icon, IconButton, Avatar, Chip, TabItem, TextField, RichText, Banner, Button, ButtonKind, Spinner, Tooltip, ListView, BannerPicture } from "../components/index.slint"; // The header of the main area: an icon, a title and a description, and -// actions (@children) at the right. +// actions (@children) at the right; a channel's banner picture behind them +// (`banner`, `banner-mode` as TreeItem's). export component PageHeader inherits Rectangle { in property icon: Icons.hash; in property title; in property description; + in property banner; + in property banner-mode; min-height: 60px; border-width: 0px; + if root.banner.width > 0: BannerPicture { + source: root.banner; + mode: root.banner-mode; + } HorizontalLayout { padding-left: Theme.space-6; padding-right: Theme.space-4; @@ -44,7 +51,7 @@ export component PageHeader inherits Rectangle { Text { text: root.description; font-size: Theme.font-sm; - color: Theme.text-muted; + color: root.banner.width > 0 ? Theme.text-secondary : Theme.text-muted; vertical-alignment: center; horizontal-stretch: 1; overflow: elide; @@ -583,11 +590,15 @@ export component ChatView inherits VerticalLayout { property tab-name: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].name : ""; property tab-kind: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].kind : 0; property tab-topic: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].topic : ""; + property tab-banner: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].banner : @image-url(""); + property tab-banner-mode: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].banner-mode : 0; if root.header: PageHeader { icon: root.tab-kind == 1 ? Icons.hash : root.tab-kind == 2 ? Icons.at-sign : Icons.message-square; title: root.tab-name; description: root.tab-topic != "" ? root.tab-topic : Bridge.server-title; + banner: root.tab-banner; + banner-mode: root.tab-banner-mode; // Only when the chat does not come through our voice connection // (an invisible observer or a relay). if Bridge.presence-source != "" && !Bridge.voice-connected: Chip { diff --git a/crates/voelin-ui/ui/screens/dialogs.slint b/crates/voelin-ui/ui/screens/dialogs.slint index 462cbfb..6eb64bb 100644 --- a/crates/voelin-ui/ui/screens/dialogs.slint +++ b/crates/voelin-ui/ui/screens/dialogs.slint @@ -290,11 +290,13 @@ component ShareCard inherits Modal { Avatar { size: 32px; initials: ""; + image: viewer.avatar; status: viewer.state == "connected" ? Status.online : viewer.state == "requested" ? Status.idle : Status.offline; Icon { source: Icons.user; size: 16px; tint: #ffffff; + visible: viewer.avatar.width == 0; } } } diff --git a/crates/voelin-ui/ui/screens/home.slint b/crates/voelin-ui/ui/screens/home.slint index d37ef44..fcd9365 100644 --- a/crates/voelin-ui/ui/screens/home.slint +++ b/crates/voelin-ui/ui/screens/home.slint @@ -291,6 +291,7 @@ component HomeBanner inherits Rectangle { size: root.compact ? 44px : 56px; square: true; initials: root.server.initials; + image: root.server.icon; tint: root.server.tint; label: root.server.name; status: root.server.status == "connected" ? Status.online : root.server.status == "observing" ? Status.info : root.server.status == "connecting" ? Status.idle : Status.none; diff --git a/crates/voelin-ui/ui/screens/mobile-voice.slint b/crates/voelin-ui/ui/screens/mobile-voice.slint index a2cb4ef..707880a 100644 --- a/crates/voelin-ui/ui/screens/mobile-voice.slint +++ b/crates/voelin-ui/ui/screens/mobile-voice.slint @@ -7,7 +7,7 @@ import { Theme } from "../theme.slint"; import { Icons } from "../icons.slint"; import { Bridge, MemberItem, StreamItem } from "../bridge.slint"; import { Nav, MobileTab } from "../nav.slint"; -import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Select, Slider, SpeakingBars, ScrollView } from "../components/index.slint"; +import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Select, Slider, SpeakingBars, ScrollView, BannerPicture } from "../components/index.slint"; import { MessageList, Composer } from "chat.slint"; import { StudioBridge } from "../studio-bridge.slint"; @@ -21,52 +21,58 @@ export global PhoneVoice { } } -// The channel's name and topic, back, and Leave. -component ChannelBar inherits HorizontalLayout { - padding-left: Theme.space-3; - padding-right: Theme.space-3; - spacing: Theme.space-3; +// The channel's name and topic, back, and Leave; its banner behind them. +component ChannelBar inherits Rectangle { height: 56px; - IconButton { - icon: Icons.arrow-left; - label: @tr("Back"); - round: true; - filled: true; - size: 40px; - y: (parent.height - self.height) / 2; - clicked => { PhoneVoice.close(); } + if Bridge.own-channel-banner.width > 0: BannerPicture { + source: Bridge.own-channel-banner; + mode: Bridge.own-channel-banner-mode; } - Icon { - source: Icons.volume-2; - size: 28px; - tint: Theme.text-secondary; - y: (parent.height - self.height) / 2; - } - VerticalLayout { - alignment: center; - horizontal-stretch: 1; - Text { - text: Bridge.own-channel; - color: Theme.text; - font-size: Theme.font-lg; - font-weight: Theme.weight-semibold; - overflow: elide; + HorizontalLayout { + padding-left: Theme.space-3; + padding-right: Theme.space-3; + spacing: Theme.space-3; + IconButton { + icon: Icons.arrow-left; + label: @tr("Back"); + round: true; + filled: true; + size: 40px; + y: (parent.height - self.height) / 2; + clicked => { PhoneVoice.close(); } } - if Bridge.own-channel-topic != "": Text { - text: Bridge.own-channel-topic; - color: Theme.text-secondary; - font-size: Theme.font-sm; - overflow: elide; + Icon { + source: Icons.volume-2; + size: 28px; + tint: Theme.text-secondary; + y: (parent.height - self.height) / 2; } - } - Button { - kind: ButtonKind.danger; - icon: Icons.log-out; - text: @tr("Leave"); - y: (parent.height - self.height) / 2; - clicked => { - PhoneVoice.close(); - Bridge.disconnect-voice(); + VerticalLayout { + alignment: center; + horizontal-stretch: 1; + Text { + text: Bridge.own-channel; + color: Theme.text; + font-size: Theme.font-lg; + font-weight: Theme.weight-semibold; + overflow: elide; + } + if Bridge.own-channel-topic != "": Text { + text: Bridge.own-channel-topic; + color: Theme.text-secondary; + font-size: Theme.font-sm; + overflow: elide; + } + } + Button { + kind: ButtonKind.danger; + icon: Icons.log-out; + text: @tr("Leave"); + y: (parent.height - self.height) / 2; + clicked => { + PhoneVoice.close(); + Bridge.disconnect-voice(); + } } } } diff --git a/crates/voelin-ui/ui/screens/mobile.slint b/crates/voelin-ui/ui/screens/mobile.slint index 50f9c23..fc12200 100644 --- a/crates/voelin-ui/ui/screens/mobile.slint +++ b/crates/voelin-ui/ui/screens/mobile.slint @@ -44,6 +44,7 @@ export component MobileServers inherits VerticalLayout { size: 46px; square: true; initials: server.initials; + image: server.icon; tint: server.tint; status: server.status == "connected" ? Status.online : server.status == "observing" ? Status.info : Status.none; } @@ -129,12 +130,14 @@ export component YouPage inherits ScrollView { Avatar { size: 56px; initials: ""; + image: Bridge.own-avatar; tint: Theme.accent; status: Bridge.voice-connected ? Status.online : Bridge.observing ? Status.info : Status.offline; Icon { source: Icons.user; size: 28px; tint: #ffffff; + visible: Bridge.own-avatar.width == 0; } } VerticalLayout { diff --git a/crates/voelin-ui/ui/screens/streams.slint b/crates/voelin-ui/ui/screens/streams.slint index 7ec83af..c2164fa 100644 --- a/crates/voelin-ui/ui/screens/streams.slint +++ b/crates/voelin-ui/ui/screens/streams.slint @@ -457,6 +457,8 @@ export component StreamViewer inherits Rectangle { icon: Icons.volume-2; title: Bridge.own-channel != "" ? Bridge.own-channel : Bridge.viewer-title; description: Bridge.own-channel-topic; + banner: Bridge.own-channel-banner; + banner-mode: Bridge.own-channel-banner-mode; if Bridge.members.length > 0: Button { icon: Icons.users; text: @tr("{} in voice", Bridge.members.length); diff --git a/crates/voelin-ui/ui/screens/studio-parts.slint b/crates/voelin-ui/ui/screens/studio-parts.slint index e47b5df..f95f355 100644 --- a/crates/voelin-ui/ui/screens/studio-parts.slint +++ b/crates/voelin-ui/ui/screens/studio-parts.slint @@ -930,6 +930,7 @@ component ChatRow inherits Rectangle { if !line.continued: Avatar { size: 34px; initials: line.initials; + image: line.avatar; tint: line.tint; label: line.author; } diff --git a/crates/voelin-ui/ui/screens/studio.slint b/crates/voelin-ui/ui/screens/studio.slint index e039020..400bfae 100644 --- a/crates/voelin-ui/ui/screens/studio.slint +++ b/crates/voelin-ui/ui/screens/studio.slint @@ -17,6 +17,7 @@ component StudioUser inherits HorizontalLayout { Avatar { size: 38px; initials: Bridge.nickname != "" ? "" : "?"; + image: Bridge.own-avatar; tint: Theme.accent; label: Bridge.nickname; crown: StudioBridge.status.live; @@ -25,7 +26,7 @@ component StudioUser inherits HorizontalLayout { source: Icons.user; size: 20px; tint: #ffffff; - visible: Bridge.nickname != ""; + visible: Bridge.nickname != "" && Bridge.own-avatar.width == 0; } } } diff --git a/crates/voelin-ui/ui/screens/voice.slint b/crates/voelin-ui/ui/screens/voice.slint index 84a2f4f..301a432 100644 --- a/crates/voelin-ui/ui/screens/voice.slint +++ b/crates/voelin-ui/ui/screens/voice.slint @@ -5,7 +5,7 @@ import { Theme } from "../theme.slint"; import { Icons } from "../icons.slint"; import { Bridge, MemberItem, StreamItem } from "../bridge.slint"; import { Nav, SettingsSection } from "../nav.slint"; -import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Chip, SpeakingBars } from "../components/index.slint"; +import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Chip, SpeakingBars, BannerPicture } from "../components/index.slint"; import { MessageList, Composer } from "chat.slint"; // One person: a large avatar with a ring (green while talking, blue while @@ -213,77 +213,83 @@ component StreamCard inherits Rectangle { // The voice channel view (desktop): header, people, streams, chat. export component VoiceView inherits VerticalLayout { // The title with the buttons beside it; the topic and the count below - // take the whole width. - HorizontalLayout { - padding-left: Theme.space-7; - padding-right: Theme.space-5; - padding-top: Theme.space-5; - padding-bottom: Theme.space-3; - spacing: Theme.space-5; - Icon { - source: Icons.volume-2; - size: 40px; - tint: Theme.text-secondary; - y: Theme.space-1; + // take the whole width. The channel's banner behind them. + Rectangle { + if Bridge.own-channel-banner.width > 0: BannerPicture { + source: Bridge.own-channel-banner; + mode: Bridge.own-channel-banner-mode; } - VerticalLayout { - horizontal-stretch: 1; - spacing: Theme.space-1; - HorizontalLayout { - spacing: Theme.space-3; - Text { - text: Bridge.own-channel; - color: Theme.text; - font-size: Theme.font-3xl; - font-weight: Theme.weight-semibold; - vertical-alignment: center; - horizontal-stretch: 1; - overflow: elide; - } - IconButton { - icon: Icons.message-square; - label: @tr("Chat only"); - y: (parent.height - self.height) / 2; - clicked => { Nav.show-voice(false); } - } - Button { - icon: Icons.settings; - text: @tr("Voice Settings"); - y: (parent.height - self.height) / 2; - clicked => { Nav.open-settings(SettingsSection.voice); } - } - Button { - kind: ButtonKind.danger; - icon: Icons.phone-off; - text: @tr("Leave"); - y: (parent.height - self.height) / 2; - clicked => { - Nav.show-voice(false); - Bridge.disconnect-voice(); + HorizontalLayout { + padding-left: Theme.space-7; + padding-right: Theme.space-5; + padding-top: Theme.space-5; + padding-bottom: Theme.space-3; + spacing: Theme.space-5; + Icon { + source: Icons.volume-2; + size: 40px; + tint: Theme.text-secondary; + y: Theme.space-1; + } + VerticalLayout { + horizontal-stretch: 1; + spacing: Theme.space-1; + HorizontalLayout { + spacing: Theme.space-3; + Text { + text: Bridge.own-channel; + color: Theme.text; + font-size: Theme.font-3xl; + font-weight: Theme.weight-semibold; + vertical-alignment: center; + horizontal-stretch: 1; + overflow: elide; + } + IconButton { + icon: Icons.message-square; + label: @tr("Chat only"); + y: (parent.height - self.height) / 2; + clicked => { Nav.show-voice(false); } + } + Button { + icon: Icons.settings; + text: @tr("Voice Settings"); + y: (parent.height - self.height) / 2; + clicked => { Nav.open-settings(SettingsSection.voice); } + } + Button { + kind: ButtonKind.danger; + icon: Icons.phone-off; + text: @tr("Leave"); + y: (parent.height - self.height) / 2; + clicked => { + Nav.show-voice(false); + Bridge.disconnect-voice(); + } } } - } - if Bridge.own-channel-topic != "": Text { - text: Bridge.own-channel-topic; - color: Theme.text-secondary; - font-size: Theme.font-md; - overflow: elide; - } - HorizontalLayout { - spacing: Theme.space-2; - alignment: start; - Icon { - source: Icons.users; - size: 16px; - tint: Theme.text-secondary; - y: (parent.height - self.height) / 2; - } - Text { - text: Bridge.own-channel-limit >= 0 - ? @tr("{} in voice / {} total", Bridge.members.length, Bridge.own-channel-limit) - : @tr("{} in voice", Bridge.members.length); + if Bridge.own-channel-topic != "": Text { + text: Bridge.own-channel-topic; color: Theme.text-secondary; - font-size: Theme.font-body; + font-size: Theme.font-md; + overflow: elide; + } + HorizontalLayout { + spacing: Theme.space-2; + alignment: start; + Icon { + source: Icons.users; + size: 16px; + tint: Theme.text-secondary; + y: (parent.height - self.height) / 2; + } + Text { + text: Bridge.own-channel-limit >= 0 + ? @tr("{} in voice / {} total", Bridge.members.length, Bridge.own-channel-limit) + : @tr("{} in voice", Bridge.members.length); + color: Theme.text-secondary; + font-size: Theme.font-body; + } } } } diff --git a/crates/voelin-ui/ui/shells/common.slint b/crates/voelin-ui/ui/shells/common.slint index 4020dfc..03543b6 100644 --- a/crates/voelin-ui/ui/shells/common.slint +++ b/crates/voelin-ui/ui/shells/common.slint @@ -180,6 +180,7 @@ export component UserCard inherits Rectangle { Avatar { size: 38px; initials: Bridge.nickname != "" ? "" : "?"; + image: Bridge.own-avatar; tint: Theme.accent; label: Bridge.nickname; // Green ring while our voice goes out. @@ -189,7 +190,7 @@ export component UserCard inherits Rectangle { source: Icons.user; size: 20px; tint: #ffffff; - visible: Bridge.nickname != ""; + visible: Bridge.nickname != "" && Bridge.own-avatar.width == 0; } } } diff --git a/crates/voelin-ui/ui/shells/desktop.slint b/crates/voelin-ui/ui/shells/desktop.slint index cbcf031..1c9cba1 100644 --- a/crates/voelin-ui/ui/shells/desktop.slint +++ b/crates/voelin-ui/ui/shells/desktop.slint @@ -46,6 +46,7 @@ component RailServer inherits Rectangle { size: 46px; square: true; initials: server.initials; + image: server.icon; tint: server.tint; label: server.name; status: server.status == "connected" ? Status.online : server.status == "observing" ? Status.info : server.status == "connecting" ? Status.idle : Status.none; diff --git a/crates/voelin-ui/ui/shells/mobile.slint b/crates/voelin-ui/ui/shells/mobile.slint index c567ec2..f7f16a7 100644 --- a/crates/voelin-ui/ui/shells/mobile.slint +++ b/crates/voelin-ui/ui/shells/mobile.slint @@ -6,7 +6,7 @@ import { Theme } from "../theme.slint"; import { Icons } from "../icons.slint"; import { Bridge } from "../bridge.slint"; import { Nav, Page, MobileTab, SettingsSection } from "../nav.slint"; -import { Icon, IconButton, CountBadge, PopupMenu, MenuEntry } from "../components/index.slint"; +import { Icon, IconButton, CountBadge, PopupMenu, MenuEntry, BannerPicture } from "../components/index.slint"; import { PhoneVoice } from "../screens/mobile-voice.slint"; // One entry of the bottom navigation. @@ -106,6 +106,8 @@ component PeoplePill inherits Rectangle { export component MobileShell inherits Rectangle { in property title; in property subtitle; + in property banner; + in property banner-mode; // Total unread messages (the Chat tab's badge). in property unread; // Show a back arrow (sub-pages such as the settings). @@ -123,6 +125,10 @@ export component MobileShell inherits Rectangle { Rectangle { height: 60px; accessible-role: AccessibleRole.banner; + if root.banner.width > 0: BannerPicture { + source: root.banner; + mode: root.banner-mode; + } HorizontalLayout { padding-left: Theme.space-4; padding-right: Theme.space-3; diff --git a/docs/screenshots/banners-desktop-dark.png b/docs/screenshots/banners-desktop-dark.png new file mode 100644 index 0000000..fc3f159 Binary files /dev/null and b/docs/screenshots/banners-desktop-dark.png differ diff --git a/docs/screenshots/banners-desktop-light.png b/docs/screenshots/banners-desktop-light.png new file mode 100644 index 0000000..58af452 Binary files /dev/null and b/docs/screenshots/banners-desktop-light.png differ diff --git a/docs/screenshots/banners-desktop-voice.png b/docs/screenshots/banners-desktop-voice.png new file mode 100644 index 0000000..22a7853 Binary files /dev/null and b/docs/screenshots/banners-desktop-voice.png differ diff --git a/docs/screenshots/banners-mobile-chat.png b/docs/screenshots/banners-mobile-chat.png new file mode 100644 index 0000000..29dc097 Binary files /dev/null and b/docs/screenshots/banners-mobile-chat.png differ diff --git a/docs/screenshots/banners-mobile-servers.png b/docs/screenshots/banners-mobile-servers.png new file mode 100644 index 0000000..e65bae9 Binary files /dev/null and b/docs/screenshots/banners-mobile-servers.png differ diff --git a/docs/screenshots/banners-mobile-voice.png b/docs/screenshots/banners-mobile-voice.png new file mode 100644 index 0000000..f1521e6 Binary files /dev/null and b/docs/screenshots/banners-mobile-voice.png differ diff --git a/docs/ui.md b/docs/ui.md index 6d739a6..e66a2f5 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -422,6 +422,55 @@ the window's size so the pointer is not over the window, and passes | ![friends](screenshots/mobile-friends.png) | ![messages](screenshots/mobile-messages.png) | ![events](screenshots/mobile-events.png) | ![the bell](screenshots/mobile-notifications.png) | ![streaming settings](screenshots/mobile-settings-streaming.png) | | ![add server](screenshots/mobile-add-server.png) | | | | | +## Server and channel pictures + +The server card shows the host banner. TeamSpeak 6 channel banners appear +behind their tree rows, the desktop chat and voice headers, and the phone's +chat and voice headers. The server's sizing mode is preserved: 0 centres +the original picture, 1 stretches it, and 2 fits it while keeping its aspect +ratio. A theme-coloured wash keeps the text readable over bright pictures. +Missing or refused pictures leave the normal background in place. + +The engine downloads HTTP(S) banners only while `cache.fetch_images` is +enabled. Downloads have a 4 MiB limit, a 10-second connection timeout and +a 30-second overall timeout. Failed downloads can retry on a later +presence update. A host banner's reload interval is at least 60 seconds; +failed refreshes preserve the previous cached picture. Closing the session +stops its reload timer. `PictureReady` invalidates the decoded image before +refreshing the visible models, including when the URL and cache path stay +the same. + +PNG, JPEG, GIF, WebP and SVG are decoded by content, since cached files have +no extension. Raster pictures larger than 16,384 pixels on either axis or +64 MiB of decoded RGBA are refused before pixel allocation on the UI +thread. SVG uses Slint's vector loader and the existing vector-cache cost. +Avatars and server, channel, client and group icons use the same image cache. + +The focused checks are the `voelin-core`, `voelin-model`, `voelin-observer` +and `voelin-ui` library tests. The live `ts6_banners` test checks disabled +fetching, initial downloads, all three modes, channel URL replacement and +removal, and a fresh host download after the 60-second interval. It uses +the development TS6 server by default; a private fixture can override its +endpoints without changing the other live tests: + +```sh +VOELIN_LIVE=1 \ +VOELIN_BANNER_VOICE_ADDR=127.0.0.1:19988 \ +VOELIN_BANNER_QUERY_ADDR=127.0.0.1:20022 \ +cargo test --locked -p voelin-core --test live ts6_banners -- --exact +``` + +The 2026-10-04 check passed 168 focused library tests and the live scenario +against a private TS6 6.0.0-beta13.1 instance, including its real reload +interval. These screenshots use sample data on Xvfb with Slint's software +renderer; the phone layouts are desktop renders, not Android device tests. + +| Desktop | Phone layout | +|---|---| +| ![Dark chat and channel banners](screenshots/banners-desktop-dark.png) | ![Channel banner in the mobile chat header](screenshots/banners-mobile-chat.png) | +| ![Light chat and channel banners](screenshots/banners-desktop-light.png) | ![Light server list](screenshots/banners-mobile-servers.png) | +| ![Banner in the desktop voice header](screenshots/banners-desktop-voice.png) | ![Banner in the mobile voice header](screenshots/banners-mobile-voice.png) | + ## Limits - No drop shadows or blur (the software renderer draws none): glows are