Merge main (ad20979) into phase4/session-seam

Main brings the merge of phase5/ui-vm: the toolkit-free crates/voelin-ui-vm
crate and the logic/bind split of crates/voelin-ui. Conflicts, and what each
resolution keeps:

- crates/voelin-ui/src/settings_pages.rs: main deleted it (it is
  settings_pages/{mod,bind}.rs and voelin-ui-vm's settings_pages/logic.rs
  now), this branch had changed its voelin_core::identity paths. Deleted; the
  paths are voelin_core::ts::identity:: in bind.rs and in logic.rs.
- crates/voelin-ui/src/identities.rs: the module comment names
  voelin_core::ts::identity::import_new (this branch) and settings_pages/
  (main).
- docs/architecture.md: the voelin-core row of this branch with the
  voelin-ui-vm and voelin-ui rows of main.

Not conflicts, but needed to compile: voelin-ui-vm named the in-tree
voelin-model by path, which this branch moved to the protocol repository
(workspace dependency), and imported voelin_core::identity::Found, which is
voelin_core::ts::identity::Found. Cargo.lock merged without a conflict and
resolves with --locked; THIRD_PARTY_NOTICES.md is up to date
(scripts/notices.sh --check).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-24 10:32:05 +03:00
commit e13d401b9c
73 files changed
+11836 -5281

No files matched your search

+94
View File
@@ -0,0 +1,94 @@
//! Avatars without pictures: initials on a colour from the name.
use unicode_segmentation::UnicodeSegmentation;
use crate::color::Rgb;
use crate::image::{ImageRef, ImageSource};
/// Background colours for initials; white text reads on all of them.
const TINTS: [u32; 10] = [
0x2d6bff, 0x7c4dff, 0xc2379a, 0xe0572e, 0xd08a00, 0x1f9d6b, 0x0c93b8, 0x5865f2, 0xa0439e,
0x3a7d44,
];
/// Up to two letters: the first letters of the first two words, or the
/// first two of a single word ("Nova Star" → "NS", "dex" → "DE").
pub fn initials(name: &str) -> String {
let words: Vec<&str> = name
.split(|c: char| c.is_whitespace() || c == '_' || c == '-' || c == '.')
.filter(|w| w.chars().any(char::is_alphanumeric))
.collect();
let first = |w: &str| w.chars().find(|c| c.is_alphanumeric());
let letters: String = match words.as_slice() {
[] => String::new(),
[one] => one.chars().filter(|c| c.is_alphanumeric()).take(2).collect(),
[a, b, ..] => first(a).into_iter().chain(first(b)).collect(),
};
letters.to_uppercase()
}
/// The first letter of `initials`, for avatars too small for two ("NS" →
/// "N").
pub fn first_letter(initials: &str) -> String {
initials.graphemes(true).next().unwrap_or_default().to_owned()
}
/// A picture from the engine's cache (an avatar, a group icon); none when
/// there is no path.
pub fn image(path: Option<&std::path::PathBuf>) -> ImageRef {
path.map(ImageSource::file).unwrap_or_default()
}
/// A stable number for a name, in any case (FNV-1a).
pub fn name_hash(name: &str) -> u32 {
let mut hash: u32 = 0x811c_9dc5;
for b in name.to_lowercase().bytes() {
hash ^= u32::from(b);
hash = hash.wrapping_mul(0x0100_0193);
}
hash
}
/// `0xrrggbb` as a colour.
pub fn rgb(rgb: u32) -> Rgb {
Rgb::from(rgb)
}
/// A stable colour for a name.
pub fn tint(name: &str) -> Rgb {
rgb(TINTS[(name_hash(name) % TINTS.len() as u32) as usize])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn initials_of_names() {
assert_eq!(initials("Nova Star"), "NS");
assert_eq!(initials("dex"), "DE");
assert_eq!(initials("x"), "X");
assert_eq!(initials("dark_knight"), "DK");
assert_eq!(initials(" "), "");
assert_eq!(initials("[Bot] Relay"), "BR");
assert_eq!(initials("Ärger über"), "ÄÜ");
}
#[test]
fn first_letter_of_initials() {
assert_eq!(first_letter("NS"), "N");
assert_eq!(first_letter("ÄÜ"), "Ä");
assert_eq!(first_letter(""), "");
assert_eq!(first_letter("X"), "X");
// A letter with a combining mark stays whole.
assert_eq!(first_letter("A\u{308}B"), "A\u{308}");
}
#[test]
fn tints_are_stable() {
assert_eq!(tint("Alice"), tint("alice"));
let distinct: std::collections::HashSet<_> =
["Alice", "Bob", "Carol", "Dave", "Eve", "Mallory"].iter().map(|n| tint(n).0).collect();
assert!(distinct.len() > 2);
}
}
File diff suppressed because it is too large. Load diff
+934
View File
@@ -0,0 +1,934 @@
//! The bridge structs: the rows and forms the screens show, as plain
//! values. They mirror the Slint structs of `crates/voelin-ui/ui/bridge.slint`
//! field by field (strings are shared `Arc<str>`, pictures [`ImageRef`],
//! colours [`Rgb`], lists `Vec`); the Slint crate converts them
//! (`bind/convert.rs`), the GPUI client will render them as they are.
//! `MytsBadge` and `MytsForm` (account screens without a data source in this
//! build) stay in Slint.
use std::sync::Arc;
use crate::color::Rgb;
use crate::image::ImageRef;
/// A row or form of the bridge (the plain counterpart of the Slint struct `ServerItem`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ServerItem {
pub id: i32,
pub name: Arc<str>,
pub address: Arc<str>,
/// "offline", "connecting", "observing" or "connected"
pub status: Arc<str>,
/// Avatar of a server without an icon.
pub initials: Arc<str>,
pub tint: Rgb,
/// The server's icon, empty without one.
pub icon: ImageRef,
/// Unread messages in its chats.
pub unread: i32,
/// Someone streams in our channel there.
pub live: bool,
/// "9 online · 7 channels" while its presence is known, else the address.
pub detail: Arc<str>,
/// "TeamSpeak 6", "TeamSpeak 3", "" before it was reached.
pub product: Arc<str>,
/// Gateway or query credentials: presence without joining.
pub gateway: bool,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `TreeItem`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TreeItem {
pub is_channel: bool,
/// A TeamSpeak spacer channel, its name without the `[cspacer1]` part:
/// 0 none, 1 left, 2 centred, 3 right, 4 a line (the name repeats its
/// pattern across the row).
pub spacer: i32,
pub depth: i32,
pub id: i32,
pub name: Arc<str>,
pub own: bool,
pub talking: bool,
pub muted: bool,
pub sound_off: bool,
pub away: bool,
pub streaming: bool,
pub locked: bool,
pub collapsed: bool,
/// Local playback of this client: muted, or its volume in percent
/// (100 = unchanged).
pub local_muted: bool,
pub local_volume: i32,
/// Our own client.
pub myself: bool,
/// Avatar of a client.
pub initials: Arc<str>,
pub tint: Rgb,
/// The client's avatar picture, empty without one.
pub avatar: ImageRef,
/// Channels: clients inside, and the limit (-1: none).
pub members: i32,
pub max_members: i32,
/// Leading channel icon or trailing client icons, empty where absent: a channel's
/// icon; a client's server group icons, its channel group's and its own,
/// in that order (the first three).
pub icon: ImageRef,
pub icon_2: ImageRef,
pub icon_3: ImageRef,
/// A client's badges (myTeamSpeak), the first three in its order, empty
/// where absent; shown after the name.
pub badge: ImageRef,
pub badge_2: ImageRef,
pub badge_3: ImageRef,
/// A channel's banner picture (TeamSpeak 6), drawn behind the row;
/// Wire sizing metadata; compact decorative backgrounds always cover.
pub banner: ImageRef,
pub banner_mode: i32,
}
/// A client for the members panel (everyone on the server) and the voice
/// channel view (our channel).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MemberItem {
pub id: i32,
pub name: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
pub talking: bool,
pub muted: bool,
pub sound_off: bool,
pub away: bool,
pub streaming: bool,
pub myself: bool,
/// "Speaking", "Streaming", "Away", ...
pub status: Arc<str>,
/// The away message, empty without one.
pub away_message: Arc<str>,
/// The section the row is in (a server group, "In Voice",
/// "Streaming"), and the group's icon.
pub group: Arc<str>,
pub group_icon: ImageRef,
/// The first row of its section draws the heading, with the number of
/// rows in the section.
pub first_in_group: bool,
pub group_count: i32,
/// Badges: a crown for the server's admin groups.
pub admin: bool,
/// A moderator group's name, shown as a role next to the name.
pub role: Arc<str>,
pub priority: bool,
pub commander: bool,
pub recording: bool,
/// Its channel needs more talk power than it has (and it is no
/// talker): it cannot speak.
pub cannot_talk: bool,
/// myTeamSpeak badges, as in `TreeItem`.
pub badge: ImageRef,
pub badge_2: ImageRef,
pub badge_3: ImageRef,
}
/// A myTeamSpeak badge on the member card: "Badge" and its GUID for one
/// the app does not know; its picture is empty until it is downloaded.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BadgeItem {
pub name: Arc<str>,
pub description: Arc<str>,
pub icon: ImageRef,
}
/// The member card over a member row: everything about one client and what
/// can be done with them.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MemberCard {
pub open: bool,
pub id: i32,
pub name: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
pub status: Arc<str>,
pub description: Arc<str>,
/// Server groups, one per line.
pub groups: Vec<Arc<str>>,
/// The badges the client shows (at most three, in its order).
pub badges: Vec<BadgeItem>,
pub country: Arc<str>,
pub talk_power: i32,
pub friend: bool,
pub blocked: bool,
/// Local playback, in percent.
pub volume: f32,
pub muted: bool,
/// The client has a unique id, so contacts and private chats work.
pub known: bool,
/// The client streams: the card offers to watch it.
pub streaming: bool,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `ChatTab`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ChatTab {
/// "Lobby", "@alice", "Server"
pub title: Arc<str>,
/// The name alone ("Lobby").
pub name: Arc<str>,
/// 0 = server chat, 1 = channel chat, 2 = private chat
pub kind: i32,
pub id: i32,
pub unread: i32,
/// The channel's topic (channel chats).
pub topic: Arc<str>,
/// The last message ("Mira: the banner I promised") and its time.
pub last: Arc<str>,
pub time: Arc<str>,
/// The channel's banner picture behind the chat's header (as TreeItem).
pub banner: ImageRef,
pub banner_mode: i32,
}
/// A piece of a chat line: a word in its style, or an emoji shown as an
/// image (`emoji` is its Twemoji key, e.g. "1f600"; `text` then holds the
/// characters).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TextRun {
pub text: Arc<str>,
pub emoji: Arc<str>,
pub bold: bool,
pub italic: bool,
pub underline: bool,
pub strike: bool,
/// Code: on a background.
pub code: bool,
/// The author's colour, made readable on each theme; transparent: the
/// text's own.
pub ink_dark: Option<Rgb>,
pub ink_light: Option<Rgb>,
/// Where it links to ("": nowhere), and whether its text shows something
/// else (a page's name, another address): asked about before it opens.
pub link: Arc<str>,
pub masked: bool,
}
/// A block of a chat line (`vm::bbcode`): its runs, and what it is.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TextBlock {
pub runs: Vec<TextRun>,
/// 0 = a line, 1 = a quote's line, 2 = a line of code, 3 = a list item,
/// 4 = a rule (no runs)
pub kind: i32,
/// Who a quote quotes, on its first line.
pub caption: Arc<str>,
}
/// One emoji under a message, with how many put it there.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ReactionItem {
/// The Twemoji key of the first emoji in `text` ("1f389"), for the image.
pub key: Arc<str>,
pub text: Arc<str>,
pub count: i32,
/// We reacted with it.
pub me: bool,
}
/// A file linked in a message (`ChatMessage::file_refs`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FileItem {
pub name: Arc<str>,
/// "2.4 MB", or what the transfer is doing.
pub detail: Arc<str>,
/// Index of the link in the message (what `download-file` takes).
pub index: i32,
/// "", "running", "done", "failed"
pub state: Arc<str>,
/// 0 … 1 while it downloads.
pub progress: f32,
/// A picture, so the icon differs.
pub picture: bool,
/// The picture itself, once downloaded: shown inline instead of the card.
pub preview: ImageRef,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `ChatLine`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ChatLine {
/// A handle for this message in its chat, stable while the chat is open
/// (the engine's ids do not fit a Slint int).
pub key: i32,
pub author: Arc<str>,
/// The text without formatting, a line per block (shown as it is when
/// the message has neither formatting nor emoji, and read out).
pub text: Arc<str>,
pub time: Arc<str>,
/// The text in blocks of styled runs; only filled when it has
/// formatting or emoji (`rich`).
pub blocks: Vec<TextBlock>,
pub rich: bool,
/// Only one to three emoji: shown large.
pub jumbo: bool,
/// Same author as the line before, shortly after: no header.
pub continued: bool,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
/// From a blocked contact.
pub blocked: bool,
pub pinned: bool,
pub reactions: Vec<ReactionItem>,
pub files: Vec<FileItem>,
/// The gateway knows this message: it can be pinned, reacted to and
/// made into a topic.
pub remote: bool,
/// The topic it belongs to, "" outside a topic.
pub topic: Arc<str>,
/// Highlighted after jumping to it from the pins.
pub marked: bool,
/// The first web address it links to, "" if none.
pub link: Arc<str>,
/// The first new message: the "New" divider is above it (never
/// `continued`).
pub unread_start: bool,
}
/// A pinned message in the pins drawer.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PinItem {
pub line: ChatLine,
/// "pinned by Nova · 12:04"
pub by: Arc<str>,
}
/// A gateway topic (thread).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TopicItem {
pub id: i32,
pub title: Arc<str>,
pub creator: Arc<str>,
/// "12 messages · by Nova"
pub detail: Arc<str>,
/// "Last active 3 min ago", and whether that was within the hour.
pub activity: Arc<str>,
pub recent: bool,
pub archived: bool,
}
/// The server dialog: a bookmark (id -1: a new one) and, from a link, where
/// Connect goes.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BookmarkForm {
pub id: i32,
pub name: Arc<str>,
pub address: Arc<str>,
pub nickname: Arc<str>,
pub server_password: Arc<str>,
/// The server has voice: no Connect.
pub connected: bool,
/// From a link, not stored with the server: the channel to join (a
/// path, or /<id>), its password and a privilege key.
pub channel: Arc<str>,
pub channel_password: Arc<str>,
pub token: Arc<str>,
}
/// A stream on the server, ours first: a stream can be watched from any
/// channel. An empty id: a client that streams, but whose stream is still
/// being looked up (it started before we joined, or in another channel).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StreamItem {
pub id: Arc<str>,
pub name: Arc<str>,
pub streamer: Arc<str>,
/// The streamer's channel when it is not ours; empty in ours.
pub channel: Arc<str>,
/// The streamer's client id (their avatar in the members).
pub streamer_id: i32,
/// The streamer's avatar, as the members show it: their picture, or
/// their initials on their colour (also the card's picture's colour).
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
/// How many watch it (the gateway's directory; 0 unknown).
pub viewers: i32,
pub audio: bool,
/// "Screen", "Window", "Camera"; and the announced bitrate ("8 Mbit/s").
pub kind: Arc<str>,
pub bitrate: Arc<str>,
/// Shown in the viewer.
pub watching: bool,
/// Our own stream.
pub own: bool,
/// Ours from the Stream Studio: its preview is the card's picture.
pub studio: bool,
}
/// A viewer of our stream. state: "requested", "connecting" or "connected".
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ViewerItem {
pub client: i32,
pub name: Arc<str>,
pub state: Arc<str>,
pub message: Arc<str>,
/// Their avatar picture, empty without one.
pub avatar: ImageRef,
}
/// A capture source for the share dialog.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SourceItem {
pub name: Arc<str>,
pub detail: Arc<str>,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `ShareForm`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ShareForm {
pub source: i32,
pub name: Arc<str>,
/// Index into the frame rate choices (15, 30, 60, 120, 144, 240, 320).
pub fps_index: i32,
/// Frames per second as typed; a choice fills it in. Any number above 0.
pub fps: Arc<str>,
/// Index into the bitrate choices (Auto, 2.5, 4.6, 8, 10, 20, 40, 60
/// Mbit/s).
pub bitrate_index: i32,
/// Video bitrate in kbit/s as typed; a choice fills it in. Empty with
/// Auto: from the size and frame rate shared, up to 60 Mbit/s.
pub bitrate: Arc<str>,
pub audio: bool,
pub auto_accept: bool,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `AudioForm`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AudioForm {
/// 0 = system default, then the devices.
pub input_index: i32,
pub output_index: i32,
/// 0 = push-to-talk, 1 = voice activation, 2 = continuous.
pub transmit: i32,
/// dBFS.
pub vad_threshold: f32,
pub echo_cancellation: bool,
pub noise_suppression: bool,
/// 0 = low ... 3 = very high.
pub noise_level: i32,
pub auto_gain: bool,
/// dB.
pub input_gain: f32,
/// Percent.
pub output_volume: f32,
/// Milliseconds.
pub playback_buffer: f32,
}
/// Local playback settings of one client. volume in percent.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ClientAudio {
pub id: i32,
pub name: Arc<str>,
pub volume: f32,
pub muted: bool,
/// The client streams: the dialog offers to watch it.
pub streaming: bool,
}
/// The appearance settings (`ui.*` keys).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AppearanceForm {
/// "dark", "light" or "system"
pub theme: Arc<str>,
pub font_scale: f32,
/// Pixels.
pub narrow_breakpoint: f32,
pub image_cache_mb: f32,
}
/// A contact (friend, blocked or neutral) and where they are now.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ContactItem {
pub uid: Arc<str>,
pub name: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
/// "friend", "blocked" or "neutral"
pub relation: Arc<str>,
pub online: bool,
pub away: bool,
pub streaming: bool,
/// What they do: "In Chill Zone", "Streaming", "Away: brb", "Offline".
pub status: Arc<str>,
/// Where: the server of the first session that sees them, or "Last seen
/// 2 h ago on Nightfall Guild".
pub place: Arc<str>,
/// "12m ago": online since (this run), else when last seen.
pub when: Arc<str>,
pub note: Arc<str>,
/// Local playback in percent.
pub volume: f32,
pub muted: bool,
/// "Contact since 14 Jan 2022".
pub since: Arc<str>,
/// Every session that sees them: "Nightfall Guild · Chill Zone".
pub spots: Vec<Arc<str>>,
/// A voice connection sees them: they can be messaged, poked, joined.
pub reachable: bool,
pub selected: bool,
}
/// A live stream on one of our servers (home page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LiveItem {
/// The session (bookmark id) and the stream (directory or stream id).
pub session: i32,
pub id: Arc<str>,
pub title: Arc<str>,
pub streamer: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
pub server: Arc<str>,
pub channel: Arc<str>,
/// 0: unknown.
pub viewers: i32,
/// "Screen", "Camera", ...
pub kind: Arc<str>,
/// The server's colour, for the card's picture.
pub backdrop: Rgb,
/// In our voice channel: it can be watched at once.
pub watchable: bool,
}
/// A chat in the recent chats and in the direct messages list.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ConversationItem {
/// Index in Rust's list (what `open-conversation` takes).
pub key: i32,
/// 0 server chat, 1 channel chat, 2 private chat, 3 offline message.
pub kind: i32,
pub title: Arc<str>,
/// The server's name.
pub server: Arc<str>,
/// "You: That works!", "Sent a file".
pub preview: Arc<str>,
/// "11:42", "Yesterday", "Mon", "12 Mar".
pub time: Arc<str>,
/// "10m ago".
pub ago: Arc<str>,
pub unread: i32,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
pub online: bool,
pub selected: bool,
}
/// A notification of the bell.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NoticeItem {
pub key: i32,
/// "mention", "poke", "message", "event", "friend"
pub kind: Arc<str>,
pub title: Arc<str>,
pub body: Arc<str>,
/// "3 min ago"
pub time: Arc<str>,
pub unread: bool,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
}
/// A result of the search (Ctrl+K).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SearchItem {
/// "server", "channel", "person", "contact", "setting"
pub kind: Arc<str>,
pub title: Arc<str>,
pub subtitle: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
/// The first result of a group names it ("Servers", "People", ...).
pub header: Arc<str>,
}
/// Something on our servers: an event, a scheduled stream or server news.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct HappeningItem {
/// "event", "stream", "news"
pub kind: Arc<str>,
pub title: Arc<str>,
pub subtitle: Arc<str>,
/// "Sat 26 Apr · 19:00"
pub when: Arc<str>,
pub session: i32,
pub id: i32,
pub live: bool,
}
/// Home's "Continue where you left off": the voice channel we were in last.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ResumeItem {
/// There is one: its server is still a bookmark at the same address.
pub shown: bool,
pub server_id: i32,
pub server: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub icon: ImageRef,
/// The channel's name as the tree shows it.
pub channel: Arc<str>,
/// Voice is connected there: the button shows the server; else it
/// connects into the channel.
pub open: bool,
pub connecting: bool,
}
/// A scheduled event of a server's gateway.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EventItem {
pub id: i32,
pub title: Arc<str>,
pub description: Arc<str>,
/// The date block: "SAT", "26", "APR".
pub weekday: Arc<str>,
pub day: Arc<str>,
pub month: Arc<str>,
/// "Sat 26 Apr, 19:00 – 21:00"
pub when: Arc<str>,
/// "Raid Night" or "Server-wide".
pub place: Arc<str>,
/// A scheduled stream: "Exploring the Lands Between · Elden Ring".
pub stream: Arc<str>,
pub live: bool,
pub going: i32,
pub maybe: i32,
pub not_going: i32,
/// "going", "maybe", "not_going" or "".
pub rsvp: Arc<str>,
pub creator: Arc<str>,
/// We may edit and delete it (ours, or we moderate).
pub editable: bool,
/// "Starts in 15 min", "Started 5 min ago", "".
pub soon: Arc<str>,
/// "Nova (going)", ...; filled once the event was opened.
pub attendees: Vec<Arc<str>>,
pub expanded: bool,
}
/// The event form (create or edit).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EventForm {
/// -1: a new event.
pub id: i32,
pub title: Arc<str>,
pub description: Arc<str>,
/// "2026-10-04 19:00", local time.
pub start: Arc<str>,
/// Empty: no end.
pub end: Arc<str>,
/// Index into `event-channels` (0: server-wide).
pub channel: i32,
pub stream: bool,
pub stream_title: Arc<str>,
pub game: Arc<str>,
}
/// An offline message to write (mail the server keeps).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct OfflineForm {
/// The peer's unique id and name.
pub uid: Arc<str>,
pub to: Arc<str>,
pub subject: Arc<str>,
pub text: Arc<str>,
}
/// The open direct message: who, and what can be done.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DmPeer {
pub open: bool,
pub uid: Arc<str>,
pub name: Arc<str>,
pub initials: Arc<str>,
pub tint: Rgb,
pub avatar: ImageRef,
pub online: bool,
/// "Online · Nightfall Guild · Chill Zone", "Offline · last seen 2 h ago".
pub status: Arc<str>,
pub description: Arc<str>,
pub groups: Vec<Arc<str>>,
pub note: Arc<str>,
pub since: Arc<str>,
/// Where they are now, or where they were last seen.
pub servers: Vec<Arc<str>>,
/// Pictures linked in the conversation that are downloaded, newest
/// first (at most six; `media-more` counts the others), and the other
/// files: name, "2.4 MB · Today at 11:36", picture.
pub media: Vec<ImageRef>,
pub media_more: i32,
pub files: Vec<FileItem>,
pub friend: bool,
pub blocked: bool,
pub volume: f32,
pub muted: bool,
/// Messages can be sent now (a voice connection that sees them).
pub can_send: bool,
/// Why not: "Kairo is offline.", "Connect to Nightfall Guild to send."
pub notice: Arc<str>,
/// The server keeps offline messages: offer one.
pub offline: bool,
/// Connect with voice to the server of this conversation.
pub can_connect: bool,
/// The messages come from the store, without a session: read-only.
pub stored: bool,
/// An offline message is shown instead of the conversation.
pub mail: bool,
pub mail_subject: Arc<str>,
pub mail_text: Arc<str>,
pub mail_time: Arc<str>,
}
/// An identity (Profiles page); never its key.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct IdentityItem {
pub id: i32,
pub name: Arc<str>,
/// Unique ids on TeamSpeak 3 and TeamSpeak 6 servers.
pub uid: Arc<str>,
pub uid6: Arc<str>,
pub level: i32,
/// The store's default: servers see us as this one unless a bookmark
/// names another.
pub default: bool,
/// Where it came from: "Made in Voelin", "Imported", "Chosen by you".
pub origin: Arc<str>,
/// Raising its level: the level aimed at and the best one reached (0: no).
pub improving: i32,
pub reached: i32,
/// The bookmarks that use it.
pub used_by: Arc<str>,
}
/// An identity found in another client's files (import).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct FoundIdentity {
pub name: Arc<str>,
pub uid: Arc<str>,
pub level: i32,
pub source: Arc<str>,
/// Already in our identities.
pub known: bool,
pub picked: bool,
}
/// A bookmark and the identity it connects with (Profiles page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BookmarkIdentity {
pub id: i32,
pub name: Arc<str>,
/// Index into `identity-names` (0: the default identity).
pub identity: i32,
}
/// Camera, video and stream quality (Voice & Video page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct VideoForm {
/// Index into `cameras`.
pub camera: i32,
/// 0 none, 1 blur.
pub background: i32,
/// "auto", "1280x720", ...
pub resolution: Arc<str>,
/// `stream.fps` as typed.
pub fps: Arc<str>,
/// auto, vp8, vp9, h264, av1.
pub codec: i32,
pub hardware: bool,
pub mirror: bool,
/// everyone, friends, channel, nobody.
pub permissions: i32,
/// 0 auto, 1 720p, 2 1080p, 3 1440p, -1 other layers.
pub quality: i32,
/// kbit/s.
pub bitrate: f32,
/// The camera preview runs.
pub preview: bool,
}
/// A simulcast layer of our stream (Streaming page); numbers as typed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct LayerItem {
/// "1920x1080", or a scale like "0.5".
pub size: Arc<str>,
/// Frames per second; "" no cap.
pub fps: Arc<str>,
/// kbit/s.
pub bitrate: Arc<str>,
pub min_bitrate: Arc<str>,
pub max_bitrate: Arc<str>,
}
/// An audio source mixed into our stream.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AudioSourceItem {
/// "desktop", "app", "window", "microphone", "synthetic"
pub kind: Arc<str>,
pub name: Arc<str>,
pub detail: Arc<str>,
/// Percent.
pub gain: f32,
pub muted: bool,
}
/// Stream defaults (Streaming page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StreamingForm {
pub fps: Arc<str>,
pub bitrate: Arc<str>,
/// auto, vp8, vp9, h264, av1.
pub codec: i32,
/// auto, portal, wlroots, x11.
pub capture: i32,
pub replay_seconds: Arc<str>,
pub replay_memory: Arc<str>,
pub recording_dir: Arc<str>,
}
/// Notification kinds: 0 off, 1 in the app, 2 also on the desktop.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NotifyForm {
pub mentions: i32,
pub pokes: i32,
pub messages: i32,
pub events: i32,
pub friends: i32,
}
/// Privacy & Safety.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PrivacyForm {
/// 0 hide, 1 show flagged.
pub block_mode: i32,
/// everyone, friends, nobody.
pub messages: i32,
pub pokes: i32,
}
/// A server's gateway (Integrations page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct GatewayItem {
pub session: i32,
pub server: Arc<str>,
pub url: Arc<str>,
/// "connected", "connecting", "off"
pub status: Arc<str>,
pub features: Vec<Arc<str>>,
pub admin: bool,
}
/// A gateway configuration key (gateway administration).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ConfigItem {
pub key: Arc<str>,
/// JSON.
pub value: Arc<str>,
pub source: Arc<str>,
pub description: Arc<str>,
pub kind: Arc<str>,
pub bootstrap: bool,
}
/// A gateway permission rule.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PermItem {
pub action: Arc<str>,
/// "Everyone", "Server groups 6, 7", "Default: server admins".
pub rule: Arc<str>,
pub source: Arc<str>,
pub everyone: bool,
pub server_groups: Arc<str>,
pub channel_groups: Arc<str>,
}
/// A video encoder backend (Integrations page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EncoderItem {
pub name: Arc<str>,
pub api: Arc<str>,
pub codec: Arc<str>,
pub hardware: bool,
pub ok: bool,
/// Why it does not work, or "used first".
pub status: Arc<str>,
}
/// Any registered setting (Advanced page).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SettingItem {
pub key: Arc<str>,
pub doc: Arc<str>,
/// JSON.
pub value: Arc<str>,
/// "set here", "command line", "config file", "default".
pub source: Arc<str>,
}
/// A recording or clip of the Stream Studio (Library).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RecordingItem {
pub name: Arc<str>,
/// "12.3 MB · 3 Oct 18:04".
pub detail: Arc<str>,
pub clip: bool,
pub path: Arc<str>,
}
/// Encoders, chat history, cache and logs (Advanced page); numbers as typed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AdvancedForm {
pub encoder: Arc<str>,
pub hardware: bool,
/// `stream.decoder_backend`, `stream.hardware_decoding`.
pub decoder: Arc<str>,
pub hardware_decoding: bool,
pub store_history: bool,
pub history_page: Arc<str>,
pub dedupe_ms: Arc<str>,
pub retention_days: Arc<str>,
pub cache_mb: Arc<str>,
pub fetch_images: bool,
pub progress_ms: Arc<str>,
/// `ui.image_preview_kb`.
pub preview_kb: Arc<str>,
pub logs: Arc<str>,
pub crash_dir: Arc<str>,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `AccountForm`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AccountForm {
pub nickname: Arc<str>,
pub identity: Arc<str>,
pub uid: Arc<str>,
pub uid6: Arc<str>,
pub level: i32,
pub server: Arc<str>,
}
/// One emoji of the picker. `text` is what picking it inserts.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EmojiCell {
pub key: Arc<str>,
pub name: Arc<str>,
pub text: Arc<str>,
}
/// A row or form of the bridge (the plain counterpart of the Slint struct `EmojiRow`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct EmojiRow {
pub cells: Vec<EmojiCell>,
}
File diff suppressed because it is too large. Load diff
+55
View File
@@ -0,0 +1,55 @@
//! Colours without a toolkit.
/// An opaque colour as `0xrrggbb`. Where "no colour" means something (a
/// text's own colour), the field is an `Option<Rgb>`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Rgb(pub u32);
impl Rgb {
/// The colour with these channels.
pub const fn new(r: u8, g: u8, b: u8) -> Self {
Self((r as u32) << 16 | (g as u32) << 8 | b as u32)
}
/// The red channel.
pub const fn r(self) -> u8 {
(self.0 >> 16) as u8
}
/// The green channel.
pub const fn g(self) -> u8 {
(self.0 >> 8) as u8
}
/// The blue channel.
pub const fn b(self) -> u8 {
self.0 as u8
}
}
impl From<u32> for Rgb {
/// `0xrrggbb`; the top byte is ignored.
fn from(rgb: u32) -> Self {
Self(rgb & 0x00ff_ffff)
}
}
impl From<[u8; 3]> for Rgb {
fn from([r, g, b]: [u8; 3]) -> Self {
Self::new(r, g, b)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn channels() {
let c = Rgb::from(0x2d6bff);
assert_eq!((c.r(), c.g(), c.b()), (0x2d, 0x6b, 0xff));
assert_eq!(Rgb::new(0x2d, 0x6b, 0xff), c);
assert_eq!(Rgb::from([1, 2, 3]), Rgb(0x010203));
assert_eq!(Rgb::from(0xff12_3456), Rgb(0x123456));
}
}
+413
View File
@@ -0,0 +1,413 @@
//! Twemoji as images. The software renderer draws no colour glyphs, so the
//! UI shows emoji as pictures: this module reads the packed archive
//! (`assets/twemoji.bin`, made by `scripts/pack-twemoji.py`), finds the
//! picture of a grapheme cluster, splits text into runs of words and emoji,
//! and lists emoji for the picker. Decoding the SVGs into images is
//! `images.rs`' job.
use std::sync::{Arc, Mutex, OnceLock};
use unicode_segmentation::UnicodeSegmentation;
static DATA: &[u8] = include_bytes!("../assets/twemoji.bin");
const MAGIC: &[u8; 8] = b"VTWEMOJ1";
const ENTRY_SIZE: usize = 28;
#[derive(Clone, Copy, Debug)]
struct Block {
offset: u32,
len: u32,
raw_len: u32,
}
#[derive(Clone, Copy, Debug)]
struct Entry {
key: (u32, u16),
category: u16,
block: u32,
offset: u32,
len: u32,
name: (u32, u16),
picker: bool,
}
/// An emoji of the picker.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PickerEmoji {
/// The archive key (`1f600`).
pub key: &'static str,
/// Lower-case name for search and screen readers.
pub name: &'static str,
/// The characters picking it inserts.
pub text: String,
}
/// The packed Twemoji: an index sorted by key and deflate blocks.
pub struct Archive {
entries: Vec<Entry>,
blocks: Vec<Block>,
strings: &'static [u8],
data: &'static [u8],
/// Picker entries (indices into `entries`) in picker order.
picker: Vec<u32>,
/// The last decompressed block: neighbours are often wanted together.
last: Mutex<Option<(u32, Arc<[u8]>)>>,
}
fn u32_at(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_le_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
fn u16_at(b: &[u8], at: usize) -> Option<u16> {
Some(u16::from_le_bytes(b.get(at..at + 2)?.try_into().ok()?))
}
impl Archive {
/// Parse the index of an archive; `None` if it is malformed.
pub fn parse(bytes: &'static [u8]) -> Option<Self> {
if bytes.get(..8)? != MAGIC {
return None;
}
let count = u32_at(bytes, 8)? as usize;
let block_count = u32_at(bytes, 12)? as usize;
let strings_len = u32_at(bytes, 16)? as usize;
let mut at = 20;
let mut blocks = Vec::with_capacity(block_count);
for _ in 0..block_count {
blocks.push(Block {
offset: u32_at(bytes, at)?,
len: u32_at(bytes, at + 4)?,
raw_len: u32_at(bytes, at + 8)?,
});
at += 12;
}
let mut entries = Vec::with_capacity(count);
for _ in 0..count {
entries.push(Entry {
key: (u32_at(bytes, at)?, u16_at(bytes, at + 4)?),
category: u16_at(bytes, at + 6)?,
block: u32_at(bytes, at + 8)?,
offset: u32_at(bytes, at + 12)?,
len: u32_at(bytes, at + 16)?,
name: (u32_at(bytes, at + 20)?, u16_at(bytes, at + 24)?),
picker: u16_at(bytes, at + 26)? & 1 == 1,
});
at += ENTRY_SIZE;
}
let strings = bytes.get(at..at + strings_len)?;
let data = bytes.get(at + strings_len..)?;
let mut picker: Vec<u32> =
(0..entries.len() as u32).filter(|&i| entries[i as usize].picker).collect();
picker.sort_by_key(|&i| {
let e = &entries[i as usize];
(e.category, e.block, e.offset)
});
Some(Self { entries, blocks, strings, data, picker, last: Mutex::new(None) })
}
fn string(&self, (offset, len): (u32, u16)) -> &'static str {
let (offset, len) = (offset as usize, len as usize);
let strings: &'static [u8] = self.strings;
strings.get(offset..offset + len).and_then(|b| std::str::from_utf8(b).ok()).unwrap_or("")
}
fn find(&self, key: &str) -> Option<&Entry> {
self.entries
.binary_search_by(|e| self.string(e.key).cmp(key))
.ok()
.map(|i| &self.entries[i])
}
/// The archive has an emoji for this key (code points joined by `-`).
pub fn contains(&self, key: &str) -> bool {
self.find(key).is_some()
}
/// The name of an emoji (lower case), if the archive has it.
#[allow(dead_code, reason = "for screens that label emoji (reactions)")]
pub fn name(&self, key: &str) -> Option<&'static str> {
self.find(key).map(|e| self.string(e.name))
}
/// The SVG of an emoji.
pub fn svg(&self, key: &str) -> Option<Vec<u8>> {
let entry = *self.find(key)?;
let block = self.block(entry.block)?;
let (start, len) = (entry.offset as usize, entry.len as usize);
block.get(start..start + len).map(<[u8]>::to_vec)
}
fn block(&self, index: u32) -> Option<Arc<[u8]>> {
let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
if let Some((i, block)) = last.as_ref()
&& *i == index
{
return Some(block.clone());
}
let b = self.blocks.get(index as usize)?;
let compressed = self.data.get(b.offset as usize..(b.offset + b.len) as usize)?;
let raw =
miniz_oxide::inflate::decompress_to_vec_with_limit(compressed, b.raw_len as usize)
.ok()?;
let raw: Arc<[u8]> = raw.into();
*last = Some((index, raw.clone()));
Some(raw)
}
fn picker_emoji(&self, entry: &Entry) -> PickerEmoji {
let key = self.string(entry.key);
PickerEmoji { key, name: self.string(entry.name), text: text_of(key) }
}
/// The picker's emoji of a category: smileys, people, nature, food,
/// activities, travel, objects, symbols, flags (0-8).
pub fn category(&self, category: usize) -> Vec<PickerEmoji> {
self.picker
.iter()
.map(|&i| &self.entries[i as usize])
.filter(|e| e.category as usize == category)
.map(|e| self.picker_emoji(e))
.collect()
}
/// Picker emoji whose name has every word of `query` (case-insensitive).
pub fn search(&self, query: &str) -> Vec<PickerEmoji> {
let words: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
if words.is_empty() {
return Vec::new();
}
self.picker
.iter()
.map(|&i| &self.entries[i as usize])
.filter(|e| {
let name = self.string(e.name);
words.iter().all(|w| name.contains(w.as_str()))
})
.map(|e| self.picker_emoji(e))
.collect()
}
}
/// The archive in the binary.
pub fn archive() -> &'static Archive {
static ARCHIVE: OnceLock<Archive> = OnceLock::new();
ARCHIVE.get_or_init(|| Archive::parse(DATA).expect("the bundled emoji archive is valid"))
}
/// Characters shown as emoji even without U+FE0F: Emoji_Presentation=Yes
/// below U+1F000 (above it nearly everything is).
const PRESENTATION_BMP: &[(u32, u32)] = &[
(0x231A, 0x231B),
(0x23E9, 0x23EC),
(0x23F0, 0x23F0),
(0x23F3, 0x23F3),
(0x25FD, 0x25FE),
(0x2614, 0x2615),
(0x2648, 0x2653),
(0x267F, 0x267F),
(0x2693, 0x2693),
(0x26A1, 0x26A1),
(0x26AA, 0x26AB),
(0x26BD, 0x26BE),
(0x26C4, 0x26C5),
(0x26CE, 0x26CE),
(0x26D4, 0x26D4),
(0x26EA, 0x26EA),
(0x26F2, 0x26F3),
(0x26F5, 0x26F5),
(0x26FA, 0x26FA),
(0x26FD, 0x26FD),
(0x2705, 0x2705),
(0x270A, 0x270B),
(0x2728, 0x2728),
(0x274C, 0x274C),
(0x274E, 0x274E),
(0x2753, 0x2755),
(0x2757, 0x2757),
(0x2795, 0x2797),
(0x27B0, 0x27B0),
(0x27BF, 0x27BF),
(0x2B1B, 0x2B1C),
(0x2B50, 0x2B50),
(0x2B55, 0x2B55),
];
fn emoji_presentation(cp: u32) -> bool {
cp >= 0x1F000 || PRESENTATION_BMP.iter().any(|&(lo, hi)| (lo..=hi).contains(&cp))
}
/// Whether a character can start an emoji; text without any is plain.
fn may_be_emoji(c: char) -> bool {
c as u32 >= 0x2000 || c == '\u{FE0F}' || c == '\u{20E3}' || c == '\u{a9}' || c == '\u{ae}'
}
fn key_of(cps: &[u32]) -> String {
cps.iter().map(|cp| format!("{cp:x}")).collect::<Vec<_>>().join("-")
}
/// The characters of an archive key, with U+FE0F after a lone character
/// that is text by default, so other clients show an emoji too.
pub fn text_of(key: &str) -> String {
let cps: Vec<u32> = key.split('-').filter_map(|p| u32::from_str_radix(p, 16).ok()).collect();
let mut text: String = cps.iter().filter_map(|&cp| char::from_u32(cp)).collect();
if cps.len() == 1 && !emoji_presentation(cps[0]) {
text.push('\u{FE0F}');
}
text
}
/// The archive key of a grapheme cluster that is an emoji: code points in
/// hex joined by `-`, without U+FE0F unless the sequence has a ZWJ (as
/// Twemoji names its files).
pub fn key_for(grapheme: &str) -> Option<String> {
let cps: Vec<u32> = grapheme.chars().map(|c| c as u32).collect();
let first = *cps.first()?;
let has_vs = cps.contains(&0xFE0F);
let has_keycap = cps.contains(&0x20E3);
// Text characters (digits, ©, ↔) are emoji only with U+FE0F or a keycap.
if cps.len() == 1 && !emoji_presentation(first) {
return None;
}
if first < 0x2000 && !has_vs && !has_keycap && first != 0xA9 && first != 0xAE {
return None;
}
if (first == 0xA9 || first == 0xAE) && !has_vs {
return None;
}
let archive = archive();
let key = if cps.contains(&0x200D) {
key_of(&cps)
} else {
key_of(&cps.iter().copied().filter(|&cp| cp != 0xFE0F).collect::<Vec<_>>())
};
if archive.contains(&key) {
return Some(key);
}
// Some ZWJ sequences are named without their U+FE0F.
let bare = key_of(&cps.iter().copied().filter(|&cp| cp != 0xFE0F).collect::<Vec<_>>());
archive.contains(&bare).then_some(bare)
}
/// The archive key of the first emoji in `text` (a reaction's emoji, which
/// may be any string).
pub fn first_key(text: &str) -> Option<String> {
text.graphemes(true).find_map(key_for)
}
/// A piece of text: plain, or one emoji (`emoji` is its key).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Run {
pub text: String,
pub emoji: Option<String>,
}
/// A line of text split into runs for a wrapping layout: a run per word
/// (with the space after it) and per emoji. A line break is a space: lines
/// are blocks of their own (`vm::bbcode`).
pub fn split(text: &str) -> Vec<Run> {
let emoji = text.chars().any(may_be_emoji);
let mut out: Vec<Run> = Vec::new();
let mut word = String::new();
for g in text.graphemes(true) {
if let Some(key) = emoji.then(|| key_for(g)).flatten() {
if !word.is_empty() {
out.push(Run { text: std::mem::take(&mut word), emoji: None });
}
out.push(Run { text: g.to_owned(), emoji: Some(key) });
continue;
}
if g.chars().all(char::is_whitespace) {
// Spaces stay with the word before them (or stand alone after
// an emoji).
word.push(' ');
out.push(Run { text: std::mem::take(&mut word), emoji: None });
} else {
word.push_str(g);
}
}
if !word.is_empty() {
out.push(Run { text: word, emoji: None });
}
out
}
/// One to three emoji and nothing else but spaces: shown large.
pub fn is_jumbo(runs: &[Run]) -> bool {
let emoji = runs.iter().filter(|r| r.emoji.is_some()).count();
(1..=3).contains(&emoji) && runs.iter().all(|r| r.emoji.is_some() || r.text.trim().is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn archive_opens() {
let a = archive();
assert!(a.entries.len() > 3000);
assert!(a.contains("1f600"));
assert!(!a.contains("zzz"));
assert_eq!(a.name("1f600"), Some("grinning face"));
let svg = a.svg("1f600").unwrap();
assert!(svg.starts_with(b"<svg"), "{:?}", String::from_utf8_lossy(&svg[..20]));
assert!(svg.ends_with(b"</svg>"));
// Twice (the cached block).
assert_eq!(a.svg("1f600").unwrap(), svg);
let zwj = a.svg("1f468-200d-1f4bb").unwrap();
assert!(zwj.starts_with(b"<svg"));
}
#[test]
fn keys_of_graphemes() {
assert_eq!(key_for("😀").as_deref(), Some("1f600"));
// U+FE0F dropped outside ZWJ sequences.
assert_eq!(key_for("❤\u{FE0F}").as_deref(), Some("2764"));
// Keycap.
assert_eq!(key_for("1\u{FE0F}\u{20E3}").as_deref(), Some("31-20e3"));
// Skin tone.
assert_eq!(key_for("👍🏽").as_deref(), Some("1f44d-1f3fd"));
// ZWJ sequence.
assert_eq!(key_for("👨\u{200D}💻").as_deref(), Some("1f468-200d-1f4bb"));
// Flag.
assert_eq!(key_for("🇩🇪").as_deref(), Some("1f1e9-1f1ea"));
// Text stays text.
assert_eq!(key_for("a"), None);
assert_eq!(key_for("1"), None);
assert_eq!(key_for("©"), None);
assert_eq!(key_for("❤"), None);
assert_eq!(key_for("—"), None);
}
#[test]
fn text_runs() {
let texts = |text: &str| -> Vec<(String, Option<String>)> {
split(text).into_iter().map(|r| (r.text, r.emoji)).collect()
};
let word = |w: &str| (w.to_owned(), None);
assert_eq!(texts("plain text, no"), [word("plain "), word("text, "), word("no")]);
assert_eq!(texts("em — dash"), [word("em "), word("— "), word("dash")]);
let r = split("hi 👋 there");
assert_eq!(
texts("hi 👋 there"),
[word("hi "), ("👋".into(), Some("1f44b".into())), word(" "), word("there")]
);
assert!(!is_jumbo(&r));
assert!(is_jumbo(&split("🔥🔥 ")));
assert!(!is_jumbo(&split("🔥🔥🔥🔥")));
assert!(!is_jumbo(&split("no emoji")));
}
#[test]
fn picker() {
let a = archive();
let smileys = a.category(0);
assert!(smileys.len() > 50);
assert_eq!(smileys[0].key, "1f600");
assert_eq!(smileys[0].text, "😀");
assert!(a.category(1).iter().all(|e| !e.key.contains("1f3fb")), "no skin tone variants");
let hearts = a.search("red heart");
assert!(hearts.iter().any(|e| e.key == "2764" && e.text == "❤\u{FE0F}"));
assert!(a.search(" ").is_empty());
}
}
+114
View File
@@ -0,0 +1,114 @@
//! Home's "Continue where you left off": the voice channel we were in last,
//! if it can still be reached.
use voelin_core::VoiceState;
use voelin_store::Bookmark;
use crate::settings::LastVoice;
/// What the card's button does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResumeAction {
/// Voice is connected there: show the server.
Open,
/// Connect into the channel.
Join,
}
/// The card: the server, the channel and the button.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Resume {
pub bookmark: i64,
/// The channel's path, its names from the top as the server has them.
pub path: Vec<String>,
pub action: ResumeAction,
}
impl Resume {
/// The channel's name as the tree shows it (a spacer's text).
pub fn title(&self) -> &str {
match self.path.as_slice() {
[top] => voelin_model::parse_spacer(top).map_or(top.as_str(), |(_, text)| text),
[.., last] => last,
[] => "",
}
}
}
/// Where to continue: the last voice channel, unless its bookmark is gone
/// or points at another address now. Open while `voice` says a bookmark is
/// connected, else Join.
pub fn resume(
last: Option<&LastVoice>,
bookmarks: &[Bookmark],
voice: impl Fn(i64) -> VoiceState,
) -> Option<Resume> {
let last = last.filter(|l| !l.channel.is_empty())?;
bookmarks.iter().find(|b| b.id == last.bookmark && b.address == last.address)?;
let action = match voice(last.bookmark) {
VoiceState::Connected => ResumeAction::Open,
_ => ResumeAction::Join,
};
Some(Resume { bookmark: last.bookmark, path: last.channel.clone(), action })
}
#[cfg(test)]
mod tests {
use super::*;
fn bookmark(id: i64, address: &str) -> Bookmark {
Bookmark { id, address: address.into(), ..Default::default() }
}
fn last(bookmark: i64, address: &str, channel: &[&str]) -> LastVoice {
LastVoice {
bookmark,
address: address.into(),
channel: channel.iter().map(|n| n.to_string()).collect(),
}
}
#[test]
fn resume_cases() {
let bookmarks = [bookmark(1, "ts.example"), bookmark(2, "pixel.example:9988")];
let offline = |_| VoiceState::Disconnected;
assert_eq!(resume(None, &bookmarks, offline), None, "nothing stored");
assert_eq!(
resume(Some(&last(3, "gone.example", &["Lobby"])), &bookmarks, offline),
None,
"the bookmark was deleted"
);
assert_eq!(
resume(Some(&last(1, "old.example", &["Lobby"])), &bookmarks, offline),
None,
"the bookmark has another address now"
);
assert_eq!(resume(Some(&last(1, "ts.example", &[])), &bookmarks, offline), None);
let place = last(2, "pixel.example:9988", &["Games", "Chess"]);
let joined = resume(Some(&place), &bookmarks, offline).unwrap();
assert_eq!(joined.bookmark, 2);
assert_eq!(joined.path, ["Games", "Chess"]);
assert_eq!(joined.action, ResumeAction::Join);
assert_eq!(joined.title(), "Chess");
let connecting = resume(Some(&place), &bookmarks, |_| VoiceState::Connecting);
assert_eq!(connecting.unwrap().action, ResumeAction::Join);
// Connected elsewhere is not connected there.
let connected = |id| if id == 2 { VoiceState::Connected } else { VoiceState::Disconnected };
assert_eq!(resume(Some(&place), &bookmarks, connected).unwrap().action, ResumeAction::Open);
let elsewhere = |id| if id == 1 { VoiceState::Connected } else { VoiceState::Disconnected };
assert_eq!(resume(Some(&place), &bookmarks, elsewhere).unwrap().action, ResumeAction::Join);
}
#[test]
fn resume_titles() {
let title = |path: &[&str]| {
let path = path.iter().map(|n| n.to_string()).collect();
Resume { bookmark: 1, path, action: ResumeAction::Join }.title().to_owned()
};
assert_eq!(title(&["Lobby"]), "Lobby");
assert_eq!(title(&["[cspacer0]Gaming"]), "Gaming", "a spacer by its text");
// Only channels at the top are spacers.
assert_eq!(title(&["Games", "[cspacer]Chess"]), "[cspacer]Chess");
}
}
+308
View File
@@ -0,0 +1,308 @@
//! Pictures without a toolkit: where a picture comes from, and how large it
//! is. A front end turns an [`ImageRef`] into its own image type (Slint's
//! `Image` through its decoded-picture cache, GPUI's `img()`).
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
/// A picture: shared, cheap to clone, compared by what it is made of.
pub type ImageRef = Arc<ImageSource>;
/// Where a picture comes from.
#[derive(Clone, Default, PartialEq, Eq)]
pub enum ImageSource {
/// No picture.
#[default]
None,
/// A file of the engine's picture cache (`avatars/<md5>`, `icons/<id>`,
/// banners): PNG, JPEG, GIF, WebP, BMP, ICO or SVG, told by content, not
/// by name. The engine writes a picture that arrives again into the same
/// file, so the reference carries the file's [`Stamp`]: a changed file is
/// another picture, and a list that shows it redraws the row.
File {
/// Where the file is.
path: PathBuf,
/// What the file was when the reference was made.
stamp: Stamp,
},
/// Decoded pixels, 4 bytes per pixel in the order red, green, blue, alpha.
Rgba {
/// Width in pixels.
w: u32,
/// Height in pixels.
h: u32,
/// `w * h * 4` bytes.
bytes: Arc<[u8]>,
},
/// An SVG document.
Svg(Arc<[u8]>),
/// A picture file held in memory (a chat picture downloaded for its
/// preview): the file's bytes, and a key the front end may keep its
/// decoded picture under.
Memory {
/// Names the picture, for caches.
key: Arc<str>,
/// The file's bytes.
bytes: Arc<[u8]>,
},
}
impl fmt::Debug for ImageSource {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::None => f.write_str("None"),
Self::File { path, .. } => f.debug_tuple("File").field(path).finish(),
Self::Rgba { w, h, .. } => write!(f, "Rgba({w}x{h})"),
Self::Svg(bytes) => write!(f, "Svg({} bytes)", bytes.len()),
Self::Memory { key, bytes } => write!(f, "Memory({key}, {} bytes)", bytes.len()),
}
}
}
/// What identifies a file's content without reading it: its length and the
/// time it was last written. Both zero for a file that is missing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Stamp {
len: u64,
modified: Option<SystemTime>,
}
impl Stamp {
/// The stamp of the file at `path`.
pub fn of(path: &Path) -> Self {
std::fs::metadata(path)
.map(|meta| Self { len: meta.len(), modified: meta.modified().ok() })
.unwrap_or_default()
}
}
/// A picture's size in pixels.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Size {
/// Width, 0 for no picture.
pub width: u32,
/// Height, 0 for no picture.
pub height: u32,
}
impl ImageSource {
/// A reference to no picture.
pub fn none() -> ImageRef {
ImageRef::default()
}
/// A reference to a file of the picture cache, as the file is now.
pub fn file(path: impl Into<PathBuf>) -> ImageRef {
let path = path.into();
let stamp = Stamp::of(&path);
Arc::new(Self::File { path, stamp })
}
/// A reference to decoded pixels (`bytes`: `w * h * 4`, red, green, blue,
/// alpha); no picture if the length does not fit.
pub fn rgba(w: u32, h: u32, bytes: impl Into<Arc<[u8]>>) -> ImageRef {
let bytes = bytes.into();
if bytes.len() as u64 == u64::from(w) * u64::from(h) * 4 {
Arc::new(Self::Rgba { w, h, bytes })
} else {
Self::none()
}
}
/// The size the picture shows with; 0 by 0 when there is none or it can
/// not be shown: a file that is missing, is not a picture, or is too
/// large to decode (a front end drops those, as it would show nothing).
/// A file's size is read from its header, once while it stays as it is;
/// a vector picture has none of its own: its stated width and height,
/// else 1 by 1.
pub fn size(&self) -> Size {
match self {
Self::None => Size::default(),
Self::File { path, stamp } => file_size(path, *stamp),
Self::Rgba { w, h, .. } => Size { width: *w, height: *h },
Self::Svg(bytes) => svg_size(bytes),
Self::Memory { bytes, .. } => bytes_size(bytes),
}
}
/// There is no picture, or it can not be shown ([`Self::size`]).
pub fn is_empty(&self) -> bool {
self.size().width == 0
}
}
/// A picture with more pixels than this (as RGBA bytes) is not decoded.
const MAX_DECODED_BYTES: u64 = 128 << 20;
fn checked(width: u32, height: u32) -> Size {
if width == 0 || height == 0 || u64::from(width) * u64::from(height) * 4 > MAX_DECODED_BYTES {
Size::default()
} else {
Size { width, height }
}
}
/// The size of a picture file's bytes, told by content.
fn bytes_size(bytes: &[u8]) -> Size {
let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
let Ok(reader) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()
else {
return Size::default();
};
if reader.format().is_none() {
return if voelin_core::is_svg(bytes) { svg_size(bytes) } else { Size::default() };
}
reader.into_dimensions().map_or_else(|_| Size::default(), |(w, h)| checked(w, h))
}
/// The number at the start of an attribute's value ("48", "48px", "4.5em").
fn number(value: &str) -> Option<u32> {
let end = value.find(|c: char| !c.is_ascii_digit() && c != '.').unwrap_or(value.len());
value[..end].parse::<f32>().ok().filter(|v| *v >= 1.0).map(|v| v as u32)
}
/// The value of `name="…"` in the root tag of an SVG.
fn attribute<'a>(tag: &'a str, name: &str) -> Option<&'a str> {
let mut rest = tag;
while let Some(at) = rest.find(name) {
let before = rest[..at].chars().next_back();
let after = &rest[at + name.len()..];
let after = after.trim_start();
if before.is_none_or(char::is_whitespace)
&& let Some(value) = after.strip_prefix('=')
{
let value = value.trim_start();
let quote = value.chars().next().filter(|q| matches!(q, '"' | '\''))?;
return value[1..].split(quote).next();
}
rest = &rest[at + name.len()..];
}
None
}
fn svg_size(bytes: &[u8]) -> Size {
let text = String::from_utf8_lossy(bytes);
let Some(start) = text.find("<svg") else { return Size { width: 1, height: 1 } };
let tag = &text[start..];
let tag = &tag[..tag.find('>').unwrap_or(tag.len())];
let stated =
attribute(tag, "width").and_then(number).zip(attribute(tag, "height").and_then(number));
let boxed = || {
let mut parts = attribute(tag, "viewBox")?.split([' ', ',']).filter(|p| !p.is_empty());
let (_, _, w, h) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?);
number(w).zip(number(h))
};
let (width, height) = stated.or_else(boxed).unwrap_or((1, 1));
checked(width, height)
}
/// What a probe of a file found, and what the file was then.
type Probe = (Stamp, Size);
/// Probed files, so a picture shown in many rows is read once; entries are
/// checked against the file's length and time before use.
static PROBES: Mutex<Option<HashMap<PathBuf, Probe>>> = Mutex::new(None);
/// Probes kept at most; the picture cache is far smaller than this.
const MAX_PROBES: usize = 4096;
fn file_size(path: &Path, stamp: Stamp) -> Size {
if stamp == Stamp::default() {
return Size::default();
}
let mut guard = PROBES.lock().unwrap_or_else(|e| e.into_inner());
let probes = guard.get_or_insert_with(HashMap::new);
if let Some((was, size)) = probes.get(path)
&& *was == stamp
{
return *size;
}
// The file is read with the lock held; probes are short and rare.
let size = std::fs::read(path).map_or_else(|_| Size::default(), |bytes| bytes_size(&bytes));
if probes.len() >= MAX_PROBES {
probes.clear();
}
probes.insert(path.to_owned(), (stamp, size));
size
}
#[cfg(test)]
mod tests {
use super::*;
/// A PNG of `width` by `height` pixels.
pub(crate) fn png(width: u32, height: u32) -> Vec<u8> {
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 pixels = vec![200; width as usize * height as usize * 4];
encoder.write_header().unwrap().write_image_data(&pixels).unwrap();
bytes
}
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-ui-vm-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn pixels_and_nothing() {
assert_eq!(ImageSource::none().size(), Size::default());
assert!(ImageSource::none().is_empty());
let pixels = ImageSource::rgba(2, 3, vec![0u8; 24]);
assert_eq!(pixels.size(), Size { width: 2, height: 3 });
assert!(!pixels.is_empty());
// The wrong length is no picture.
assert!(ImageSource::rgba(2, 3, vec![0u8; 23]).is_empty());
assert_eq!(format!("{pixels:?}"), "Rgba(2x3)");
}
#[test]
fn files_by_content() {
let dir = temp("files");
// No extension: the cache's files have none.
let path = dir.join("1234");
std::fs::write(&path, png(4, 2)).unwrap();
assert_eq!(ImageSource::file(&path).size(), Size { width: 4, height: 2 });
let before = ImageSource::file(&path);
// A changed file is read again.
std::fs::write(&path, png(5, 3)).unwrap();
let after = ImageSource::file(&path);
assert_eq!(after.size(), Size { width: 5, height: 3 });
// The same file, another picture: a list redraws the row.
assert_ne!(before, after);
assert_eq!(after, ImageSource::file(&path));
let junk = dir.join("junk");
std::fs::write(&junk, b"not a picture").unwrap();
assert!(ImageSource::file(&junk).is_empty());
assert!(ImageSource::file(dir.join("missing")).is_empty());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn vector_pictures() {
let size = |svg: &str| ImageSource::Svg(svg.as_bytes().into()).size();
assert_eq!(size("<svg width=\"32\" height=\"16\"/>"), Size { width: 32, height: 16 });
assert_eq!(size("<svg viewBox='0 0 24 12'/>"), Size { width: 24, height: 12 });
assert_eq!(size("<svg xmlns='http://www.w3.org/2000/svg'/>"), Size { width: 1, height: 1 });
assert_eq!(size("<svg width=\"4096px\" height=\"4096px\"/>").width, 4096);
// Too large to decode.
assert!(
ImageSource::Svg(b"<svg width=\"99999\" height=\"99999\"/>".as_slice().into())
.is_empty()
);
// An SVG file with a byte order mark and a prolog, and in memory.
let svg: &[u8] = b"\xef\xbb\xbf<?xml version=\"1.0\"?><svg width=\"8\" height=\"8\"/>";
let dir = temp("svg");
std::fs::write(dir.join("icon"), svg).unwrap();
assert_eq!(ImageSource::file(dir.join("icon")).size().width, 8);
let memory = ImageSource::Memory { key: "k".into(), bytes: png(3, 3).into() };
assert_eq!(memory.size(), Size { width: 3, height: 3 });
std::fs::remove_dir_all(dir).unwrap();
}
}
+26
View File
@@ -0,0 +1,26 @@
//! Toolkit-free view models of the desktop client: engine state turned into
//! plain rows and forms, with the logic that decides what the screens show.
//! Neither Slint nor GPUI is a dependency; each front end converts these
//! types (docs/ui.md, "Two crates").
pub mod avatar;
pub mod bbcode;
pub mod bridge;
pub mod chat;
pub mod color;
pub mod emoji;
pub mod home;
pub mod image;
pub mod list;
pub mod servers;
pub mod settings;
pub mod settings_pages;
pub mod social;
pub mod state;
pub mod streams;
pub mod studio;
pub mod studio_bridge;
pub mod tree;
pub use color::Rgb;
pub use image::{ImageRef, ImageSource, Size};
+138
View File
@@ -0,0 +1,138 @@
//! Incremental list updates: what changed between two versions of a list,
//! as row operations. A front end that keeps a list model (Slint's
//! `VecModel`) applies them row by row, so a client that starts talking
//! redraws one row of the tree; one that rebuilds from the list (GPUI) just
//! re-renders and has no use for them.
/// One row operation of a [`Changes`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Change {
/// Row `i` holds another value: `new[i]`.
Update(usize),
/// Row `i` is gone.
Remove(usize),
/// `new[i]` is a new row, at `i`.
Insert(usize),
}
/// Row operations that turn the old list into the new one, in the order to
/// apply them: updates, then removals (each at the index it has when its
/// turn comes), then insertions (in ascending order).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Changes(pub Vec<Change>);
impl Changes {
/// Nothing changed.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// How many rows are updated in place.
pub fn updated(&self) -> usize {
self.0.iter().filter(|c| matches!(c, Change::Update(_))).count()
}
/// How many rows are removed.
pub fn removed(&self) -> usize {
self.0.iter().filter(|c| matches!(c, Change::Remove(_))).count()
}
/// How many rows are inserted.
pub fn inserted(&self) -> usize {
self.0.iter().filter(|c| matches!(c, Change::Insert(_))).count()
}
/// Apply the changes to `rows` (the old list), which then equals `new`.
/// Also the reference for front ends: their models do the same
/// operations in the same order.
pub fn apply<T: Clone>(&self, rows: &mut Vec<T>, new: &[T]) {
for change in &self.0 {
match *change {
Change::Update(i) => rows[i] = new[i].clone(),
Change::Remove(i) => {
rows.remove(i);
}
Change::Insert(i) => rows.insert(i, new[i].clone()),
}
}
}
}
/// What changes `old` into `new` with few row operations: the rows both
/// share at the start and the end stay, rows in between are changed in
/// place where they differ, and the rest inserted or removed.
pub fn diff<T: PartialEq>(old: &[T], new: &[T]) -> Changes {
let min = old.len().min(new.len());
let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
let suffix = old[prefix..]
.iter()
.rev()
.zip(new[prefix..].iter().rev())
.take(min - prefix)
.take_while(|(a, b)| a == b)
.count();
let old_mid = old.len() - prefix - suffix;
let new_mid = new.len() - prefix - suffix;
let common = old_mid.min(new_mid);
let mut changes = Vec::new();
for i in prefix..prefix + common {
if old[i] != new[i] {
changes.push(Change::Update(i));
}
}
let at = prefix + common;
changes.extend((new_mid..old_mid).map(|_| Change::Remove(at)));
changes.extend((at..at + new_mid.saturating_sub(old_mid)).map(Change::Insert));
Changes(changes)
}
#[cfg(test)]
mod tests {
use super::*;
/// The changes from `old` to `new`; applying them gives `new`.
fn run(old: &[i32], new: &[i32]) -> Changes {
let changes = diff(old, new);
let mut rows = old.to_vec();
changes.apply(&mut rows, new);
assert_eq!(rows, new, "{old:?} -> {new:?}");
changes
}
fn counts(changes: &Changes) -> (usize, usize, usize) {
(changes.updated(), changes.inserted(), changes.removed())
}
#[test]
fn minimal_changes() {
assert!(run(&[1, 2, 3], &[1, 2, 3]).is_empty());
assert_eq!(run(&[1, 2, 3], &[1, 9, 3]), Changes(vec![Change::Update(1)]));
assert_eq!(run(&[1, 2, 3], &[1, 2, 7, 3]), Changes(vec![Change::Insert(2)]));
assert_eq!(run(&[1, 2, 3], &[1, 3]), Changes(vec![Change::Remove(1)]));
assert_eq!(counts(&run(&[], &[1, 2])), (0, 2, 0));
assert_eq!(counts(&run(&[1, 2], &[])), (0, 0, 2));
assert_eq!(run(&[1, 2, 3, 4], &[5, 6]).updated(), 2);
run(&[1, 1, 1], &[1, 1]);
run(&[1, 2, 1], &[1, 1, 2, 1]);
run(&[4, 5, 6], &[1, 2, 3, 4, 5, 6, 7]);
}
/// Whatever the lists, applying the changes gives the new list, and
/// rows that stay at the ends are not touched.
#[test]
fn every_small_pair() {
let lists: Vec<Vec<i32>> = (0..4usize)
.flat_map(|n| (0..3i32.pow(n as u32)).map(move |k| (n, k)))
.map(|(n, k)| (0..n as u32).map(|i| (k / 3i32.pow(i)) % 3).collect())
.collect();
for old in &lists {
for new in &lists {
let changes = run(old, new);
let kept = old.iter().zip(new).take_while(|(a, b)| a == b).count();
assert!(changes.0.iter().all(|c| match *c {
Change::Update(i) | Change::Remove(i) | Change::Insert(i) => i >= kept,
}));
}
}
}
}
+640
View File
@@ -0,0 +1,640 @@
//! The server rail, the server dialog, and joining a channel.
use std::sync::Arc;
use voelin_core::{ObserveState, SessionState, VoiceState};
use voelin_model::{ChannelId, ChannelInfo, Presence, ServerLink};
use voelin_store::Bookmark;
use crate::avatar;
use crate::bridge::{BookmarkForm, ServerItem};
use crate::color::Rgb;
use crate::image::ImageRef;
/// Restore a known server icon before any session exists. A missing/evicted
/// cache file falls back to initials; the bookmark stores no filesystem path.
pub fn cached_icon(bookmark: &Bookmark, cache: &voelin_core::Cache) -> ImageRef {
avatar::image(bookmark.server_icon_id().and_then(|id| cache.icon(id)).as_ref())
}
/// Server colours: hues around the wheel, each far from the one before it
/// (where a server goes when its own is taken). White initials read on all.
const SERVER_TINTS: [u32; 10] = [
0x2d6bff, // blue
0xc2379a, // magenta
0xc08400, // gold
0x0c8fb0, // teal
0x9c3fd1, // purple
0xe0652a, // orange
0x1f9d55, // green
0x7c4dff, // violet
0xd63a3a, // red
0x6e8f1c, // olive
];
/// A colour for each server, in `bookmarks` order: its name picks one, and
/// when an earlier server has it, it takes the next free one. So no two
/// share a colour until there are more servers than colours (then they
/// start over), and adding a server leaves the others' colours.
pub fn tints(bookmarks: &[Bookmark]) -> Vec<Rgb> {
let n = SERVER_TINTS.len();
let mut taken = [false; SERVER_TINTS.len()];
bookmarks
.iter()
.enumerate()
.map(|(i, bookmark)| {
if i % n == 0 {
taken = [false; SERVER_TINTS.len()];
}
let start = avatar::name_hash(&bookmark.name) as usize % n;
let slot = (0..n).map(|k| (start + k) % n).find(|&s| !taken[s]).unwrap_or(start);
taken[slot] = true;
avatar::rgb(SERVER_TINTS[slot])
})
.collect()
}
/// "offline", "connecting", "observing" or "connected". "connecting" is
/// voice only: observing that is not there yet (a gateway that is away and
/// tried again) is "offline", as users never hear of the gateway.
pub fn status(state: &SessionState) -> &'static str {
match (state.voice, state.observe) {
(VoiceState::Connected, _) => "connected",
(VoiceState::Connecting, _) => "connecting",
(_, ObserveState::Observing) => "observing",
_ => "offline",
}
}
/// 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; `product`: "TeamSpeak 6" once
/// reached; `icon`: the server's icon (empty: its initials) on `tint`
/// ([`tints`]).
#[allow(clippy::too_many_arguments)]
pub fn item(
bookmark: &Bookmark,
state: &SessionState,
unread: i32,
live: bool,
detail: String,
product: String,
icon: ImageRef,
tint: Rgb,
) -> ServerItem {
ServerItem {
id: bookmark.id as i32,
name: bookmark.name.clone().into(),
address: bookmark.address.clone().into(),
status: status(state).into(),
initials: avatar::initials(&bookmark.name).into(),
tint,
icon,
unread,
live,
detail: if detail.is_empty() { bookmark.address.clone() } else { detail }.into(),
product: product.into(),
gateway: bookmark.gateway_url.is_some() || bookmark.query.is_some(),
}
}
/// The server dialog's form for `bookmark`, with its stored password:
/// `connected` while `state` has voice, which hides Connect. A server still
/// named by its address shows no name, so a new address names it again.
pub fn form(
bookmark: &Bookmark,
state: Option<&SessionState>,
server_password: &str,
) -> BookmarkForm {
BookmarkForm {
id: bookmark.id as i32,
name: if bookmark.name == bookmark.address {
"".into()
} else {
bookmark.name.clone().into()
},
address: bookmark.address.clone().into(),
nickname: bookmark.nickname.clone().into(),
server_password: server_password.into(),
connected: state.is_some_and(|s| s.voice == VoiceState::Connected),
..Default::default()
}
}
/// Where the server dialog's Connect goes ([`connect_to`]).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ConnectTo {
/// A channel path, or `/<id>`.
pub channel: Option<String>,
pub channel_password: Option<String>,
/// A privilege key.
pub token: Option<String>,
}
/// What the server dialog's Connect connects with, once the form was saved
/// as `saved` (none: saving failed, and nothing connects): the form's
/// channel (a link's) with its password, else the server's default
/// channel; and the link's privilege key.
pub fn connect_to(form: &BookmarkForm, saved: Option<&Bookmark>) -> Option<ConnectTo> {
let saved = saved?;
let given = |text: &Arc<str>| Some(text.to_string()).filter(|t| !t.is_empty());
let channel = given(&form.channel);
Some(ConnectTo {
channel_password: channel.as_ref().and_then(|_| given(&form.channel_password)),
channel: channel.or_else(|| saved.default_channel.clone()),
token: given(&form.token),
})
}
/// A `ts3server://` link that joins the channel at `path` (its names from
/// the top) on the server at `address` (`host`, `host:port` or
/// `[v6]:port`), as TeamSpeak clients open them.
pub fn invite_link(address: &str, path: &[&str]) -> String {
let mut link = ServerLink::new(address);
link.channel = (!path.is_empty()).then(|| voelin_model::join_channel_path(path));
link.to_url()
}
/// TeamSpeak's voice port, of an address without one.
const DEFAULT_PORT: u16 = 9987;
/// Whether two addresses name the same server: the host in any case, an
/// IPv6 address with or without its brackets, no port as 9987 (a port a
/// DNS record gives is not looked up).
pub fn same_address(a: &str, b: &str) -> bool {
let key = |address: &str| {
let link = ServerLink::new(address);
(link.host.trim_end_matches('.').to_lowercase(), link.port.unwrap_or(DEFAULT_PORT))
};
let a = key(a);
!a.0.is_empty() && a == key(b)
}
/// The saved server a link to `address` opens, and whether it has voice
/// (`in_voice`): of those at that address ([`same_address`]; two can be,
/// with other identities), the one in voice, else the one shown
/// (`current`), else the first.
pub fn link_server(
bookmarks: &[Bookmark],
address: &str,
current: Option<i64>,
in_voice: impl Fn(i64) -> bool,
) -> Option<(i64, bool)> {
let saved: Vec<i64> =
bookmarks.iter().filter(|b| same_address(&b.address, address)).map(|b| b.id).collect();
if let Some(id) = saved.iter().copied().find(|id| in_voice(*id)) {
return Some((id, true));
}
let shown = saved.iter().copied().find(|id| Some(*id) == current);
shown.or_else(|| saved.first().copied()).map(|id| (id, false))
}
/// The channel a link's path names (`/<id>`, or names from the top as the
/// server has them, [`voelin_model::split_channel_path`]). Of siblings with
/// the same name, the first in the tree's order that has the rest of the
/// path.
pub fn channel_by_path(presence: &Presence, path: &str) -> Option<ChannelId> {
fn below(presence: &Presence, parent: ChannelId, names: &[String]) -> Option<ChannelId> {
let (name, rest) = names.split_first()?;
let siblings = presence.channels.values().filter(|c| c.parent == parent).collect();
voelin_model::order_siblings(siblings)
.into_iter()
.filter(|c| c.name == *name)
.find_map(|c| if rest.is_empty() { Some(c.id) } else { below(presence, c.id, rest) })
}
match voelin_model::channel_path_id(path) {
Some(id) => presence.channels.contains_key(&id).then_some(id),
None => below(presence, 0, &voelin_model::split_channel_path(path)),
}
}
/// The server dialog's form for a link, over `form`: a saved server's
/// keeps its address, name and nickname (a link never changes it), and its
/// stored password unless the link has one; a new server's takes the
/// link's address, nickname (else `default_nickname`) and password. The
/// link's channel, its password and privilege key come along, for Connect.
pub fn link_form(
link: &ServerLink,
mut form: BookmarkForm,
default_nickname: &str,
) -> BookmarkForm {
let text = |value: &Option<String>| Arc::<str>::from(value.as_deref().unwrap_or_default());
if form.id < 0 {
form.address = link.address().into();
}
if form.id < 0 || form.nickname.is_empty() {
form.nickname = link.nickname.as_deref().unwrap_or(default_nickname).into();
}
if let Some(password) = &link.password {
form.server_password = password.as_str().into();
}
form.channel = text(&link.channel);
form.channel_password = text(&link.channel_password);
form.token = text(&link.token);
form
}
/// What joining a channel takes ([`join_password`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum JoinStep {
/// Move there, with this password.
Send(Option<String>),
/// Ask for the channel's password first.
Ask,
}
/// How to join `channel`, given the password remembered for it this
/// connection: a locked channel asks for one unless it was given before,
/// as TeamSpeak does. A password given before goes along even when the
/// channel shows no lock: one locked since then still lets us in.
pub fn join_password(channel: &ChannelInfo, remembered: Option<&str>) -> JoinStep {
match remembered.filter(|p| !p.is_empty()) {
Some(password) => JoinStep::Send(Some(password.to_owned())),
None if channel.has_password => JoinStep::Ask,
None => JoinStep::Send(None),
}
}
/// Where a voice connection asked into a channel stands ([`after_connect`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AfterConnect {
/// Not known yet.
Wait,
/// In it.
Joined,
/// Put elsewhere without a word (a wrong password, for one): joining
/// it again says why.
JoinAgain,
}
/// A connection asked into `asked`, connected with voice: `own` is our
/// channel once known, `known` whether `asked` shows in the presence yet
/// (it can come after our own channel).
pub fn after_connect(own: Option<ChannelId>, asked: ChannelId, known: bool) -> AfterConnect {
match own {
Some(own) if own == asked => AfterConnect::Joined,
Some(_) if known => AfterConnect::JoinAgain,
_ => AfterConnect::Wait,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn server_icon_is_visible_before_connection_and_missing_files_fall_back() {
let dir =
std::env::temp_dir().join(format!("voelin-server-icon-model-{}", std::process::id()));
std::fs::create_dir_all(dir.join("icons")).unwrap();
let path = dir.join("icons/1234");
let mut bytes = Vec::new();
let mut encoder = png::Encoder::new(&mut bytes, 4, 4);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
encoder.write_header().unwrap().write_image_data(&[200; 64]).unwrap();
std::fs::write(&path, bytes).unwrap();
let cache = voelin_core::Cache::new(&dir);
let mut bookmark = Bookmark { address: "example.test".into(), ..Default::default() };
bookmark.remember_server_icon(1234);
let server = item(
&bookmark,
&SessionState::default(),
0,
false,
String::new(),
String::new(),
cached_icon(&bookmark, &cache),
Rgb::default(),
);
assert_eq!(server.status.as_ref(), "offline");
assert_eq!(server.icon.size().width, 4);
bookmark.address = "different.test".into();
assert_eq!(cached_icon(&bookmark, &cache).size().width, 0);
bookmark.address = "example.test".into();
std::fs::remove_file(path).unwrap();
assert_eq!(cached_icon(&bookmark, &cache).size().width, 0);
std::fs::remove_dir_all(dir).unwrap();
}
/// The chip of a server reads the product its session reported.
#[test]
fn a_server_shows_the_product_it_runs() {
let bookmark = Bookmark { address: "example.test".into(), ..Default::default() };
let state = SessionState::default();
let on = |product: &str| {
item(
&bookmark,
&state,
0,
false,
String::new(),
product.into(),
Default::default(),
Rgb::default(),
)
};
assert_eq!(on("TeamSpeak 6").product.as_ref(), "TeamSpeak 6");
// Before the server answered, and for software nobody recognised: none.
assert_eq!(on("").product.as_ref(), "");
}
fn named(names: &[&str]) -> Vec<Bookmark> {
names.iter().map(|n| Bookmark { name: (*n).into(), ..Default::default() }).collect()
}
/// The colour a name picks.
fn own_tint(name: &str, step: usize) -> Rgb {
let n = SERVER_TINTS.len();
avatar::rgb(SERVER_TINTS[(avatar::name_hash(name) as usize + step) % n])
}
#[test]
fn tints_are_distinct_up_to_the_palette_size() {
let names: Vec<String> = (0..SERVER_TINTS.len()).map(|i| format!("Server {i}")).collect();
let mut bookmarks = named(&names.iter().map(String::as_str).collect::<Vec<_>>());
let distinct: std::collections::HashSet<_> =
tints(&bookmarks).iter().map(|t| t.0).collect();
assert_eq!(distinct.len(), SERVER_TINTS.len());
// One more starts over with its name's colour.
bookmarks.extend(named(&["One more"]));
assert_eq!(tints(&bookmarks)[SERVER_TINTS.len()], own_tint("One more", 0));
// The sample servers, two of which shared a blue.
let sample = tints(&named(&["Nightfall Guild", "Pixel Lounge", "Dev TS3"]));
assert!(sample[0] != sample[1] && sample[1] != sample[2] && sample[0] != sample[2]);
}
#[test]
fn tints_follow_the_name_and_stay_when_a_server_is_added() {
let names = ["Nightfall Guild", "Pixel Lounge", "Dev TS3", "Home", "Raid"];
let before = tints(&named(&names));
let mut more = named(&names);
more.extend(named(&["New one"]));
assert_eq!(tints(&more)[..names.len()], before[..]);
// Alone, a server has its name's colour, in any case.
assert_eq!(tints(&named(&["pixel lounge"])), [own_tint("Pixel Lounge", 0)]);
// A second server with the name takes the next colour.
assert_eq!(tints(&named(&["Raid", "Raid"])), [own_tint("Raid", 0), own_tint("Raid", 1)]);
}
#[test]
fn connect_shows_only_without_voice() {
let b = Bookmark {
id: 3,
name: "ts.example.test".into(),
address: "ts.example.test".into(),
nickname: "Nova".into(),
..Default::default()
};
let mut state = SessionState::default();
let f = form(&b, None, "pw");
assert_eq!((f.id, f.name.as_ref(), f.address.as_ref()), (3, "", "ts.example.test"));
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "pw"));
assert!(!f.connected);
for (voice, connected) in [
(VoiceState::Disconnected, false),
// Connect again with another address.
(VoiceState::Connecting, false),
(VoiceState::Connected, true),
] {
state.voice = voice;
assert_eq!(form(&b, Some(&state), "").connected, connected, "{voice:?}");
}
// Observing is not voice.
state.voice = VoiceState::Disconnected;
state.observe = ObserveState::Observing;
assert!(!form(&b, Some(&state), "").connected);
let named = Bookmark { name: "Nightfall".into(), ..b };
assert_eq!(form(&named, None, "").name.as_ref(), "Nightfall");
}
#[test]
fn connect_only_what_was_saved() {
let saved = Bookmark { id: 3, default_channel: Some("Lobby".into()), ..Default::default() };
let plain = BookmarkForm { address: "ts.example.test".into(), ..Default::default() };
// Saving failed: nothing connects (not the server shown before).
assert_eq!(connect_to(&plain, None), None);
assert_eq!(
connect_to(&plain, Some(&saved)),
Some(ConnectTo { channel: Some("Lobby".into()), ..Default::default() })
);
// A link's channel, its password and privilege key.
let link = BookmarkForm {
channel: "Gaming/Raid Night".into(),
channel_password: "raid".into(),
token: "key".into(),
..plain.clone()
};
assert_eq!(connect_to(&link, None), None);
assert_eq!(
connect_to(&link, Some(&saved)),
Some(ConnectTo {
channel: Some("Gaming/Raid Night".into()),
channel_password: Some("raid".into()),
token: Some("key".into()),
})
);
// A password goes only with the link's channel.
let token = BookmarkForm { channel_password: "raid".into(), token: "key".into(), ..plain };
assert_eq!(
connect_to(&token, Some(&saved)),
Some(ConnectTo {
channel: Some("Lobby".into()),
channel_password: None,
token: Some("key".into()),
})
);
}
#[test]
fn invite_links() {
assert_eq!(
invite_link("ts.example.com:9988", &["Gaming", "Raid Night"]),
"ts3server://ts.example.com?port=9988&channel=Gaming/Raid%20Night"
);
assert_eq!(invite_link(" ts.example.com ", &[]), "ts3server://ts.example.com");
assert_eq!(
invite_link("[2001:db8::1]:9987", &["Chill & Co"]),
"ts3server://[2001:db8::1]?port=9987&channel=Chill%20%26%20Co"
);
// A bare IPv6 address has no port.
assert_eq!(invite_link("2001:db8::1", &[]), "ts3server://2001:db8::1");
assert_eq!(invite_link("h:x", &["Ä/b"]), "ts3server://h:x?channel=%C3%84%2Fb");
// Read back, they name the same server and channel.
let Some(voelin_model::Link::Server(link)) =
voelin_model::Link::parse(&invite_link("[2001:db8::1]:9987", &["Games", "Ä/b"]))
else {
panic!("not a server link");
};
assert!(same_address(&link.address(), "[2001:db8::1]:9987"));
assert_eq!(voelin_model::split_channel_path(&link.channel.unwrap()), ["Games", "Ä/b"]);
}
#[test]
fn same_addresses() {
for (a, b) in [
("ts.example.org", "TS.Example.org"),
(" ts.example.org ", "ts.example.org:9987"),
("ts.example.org.", "ts.example.org"),
("[2001:db8::1]:9987", "2001:db8::1"),
("[2001:db8::1]", "[2001:DB8::1]:9987"),
("127.0.0.1:9988", "127.0.0.1:9988"),
] {
assert!(same_address(a, b), "{a} = {b}");
}
for (a, b) in [
("ts.example.org", "ts.example.org:9988"),
("ts.example.org", "example.org"),
("[2001:db8::1]:9988", "2001:db8::1"),
("", ""),
] {
assert!(!same_address(a, b), "{a} != {b}");
}
}
#[test]
fn servers_of_links() {
let saved =
|id, address: &str| Bookmark { id, address: address.into(), ..Default::default() };
let bookmarks = [
saved(1, "other.example"),
saved(2, "ts.example.org"),
saved(3, "TS.example.org:9987"),
saved(4, "ts.example.org:9988"),
];
let voice = |ids: &'static [i64]| move |id| ids.contains(&id);
// Not in voice: the one shown, else the first.
assert_eq!(link_server(&bookmarks, "ts.example.org", None, voice(&[])), Some((2, false)));
assert_eq!(
link_server(&bookmarks, "ts.example.org", Some(3), voice(&[])),
Some((3, false))
);
// In voice on one of them, also when another is shown.
assert_eq!(
link_server(&bookmarks, "ts.example.org:9987", Some(2), voice(&[1, 3])),
Some((3, true))
);
// Voice on the server at another port does not count.
assert_eq!(
link_server(&bookmarks, "ts.example.org:9988", None, voice(&[2])),
Some((4, false))
);
assert_eq!(link_server(&bookmarks, "new.example", Some(1), voice(&[1])), None);
}
#[test]
fn channels_by_path() {
let channel = |id, parent, order, name: &str| ChannelInfo {
id,
parent,
order,
name: name.into(),
..Default::default()
};
let mut p = Presence::default();
for c in [
channel(1, 0, 0, "Lobby"),
// Two of the same name, the first in the tree with the higher id.
channel(4, 0, 1, "Games"),
channel(3, 4, 0, "Chess"),
channel(7, 0, 4, "AC/DC"),
channel(2, 0, 7, "Games"),
channel(5, 2, 0, "Go"),
channel(6, 2, 5, "Chess"),
] {
p.channels.insert(c.id, c);
}
assert_eq!(channel_by_path(&p, "Lobby"), Some(1), "at the top");
assert_eq!(channel_by_path(&p, "Games/Chess"), Some(3), "nested");
// The same name: the first, unless only another has the rest.
assert_eq!(channel_by_path(&p, "Games"), Some(4));
assert_eq!(channel_by_path(&p, "Games/Go"), Some(5));
assert_eq!(channel_by_path(&p, "AC\\/DC"), Some(7), "a / in a name");
assert_eq!(channel_by_path(&p, "/6"), Some(6), "by id");
for missing in ["Chess", "Games/Poker", "Lobby/Games", "/99", "", "lobby"] {
assert_eq!(channel_by_path(&p, missing), None, "{missing}");
}
}
#[test]
fn forms_from_links() {
let link = ServerLink {
host: "ts.example.org".into(),
port: Some(9988),
nickname: Some("Link".into()),
password: Some("pw".into()),
channel: Some("Gaming/Raid Night".into()),
channel_password: Some("raid".into()),
token: Some("key".into()),
};
let bare = ServerLink::new("ts.example.org");
// A new server: the link's address, nickname and password.
let new = BookmarkForm { id: -1, nickname: "Me".into(), ..Default::default() };
let f = link_form(&link, new.clone(), "Me");
assert_eq!((f.id, f.name.as_ref(), f.address.as_ref()), (-1, "", "ts.example.org:9988"));
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Link", "pw"));
assert_eq!(
(f.channel.as_ref(), f.channel_password.as_ref(), f.token.as_ref()),
("Gaming/Raid Night", "raid", "key")
);
let f = link_form(&bare, new, "Me");
assert_eq!((f.address.as_ref(), f.nickname.as_ref()), ("ts.example.org", "Me"));
assert_eq!(
(f.server_password.as_ref(), f.channel.as_ref(), f.token.as_ref()),
("", "", "")
);
// A saved server keeps its address, name, nickname and password...
let saved = BookmarkForm {
id: 3,
name: "Nightfall".into(),
address: "TS.example.org:9988".into(),
nickname: "Nova".into(),
server_password: "stored".into(),
..Default::default()
};
let f = link_form(&bare, saved.clone(), "Me");
assert_eq!(
(f.id, f.name.as_ref(), f.address.as_ref()),
(3, "Nightfall", "TS.example.org:9988")
);
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "stored"));
// ...the link's password in place of the stored one.
let f = link_form(&link, saved, "Me");
assert_eq!((f.nickname.as_ref(), f.server_password.as_ref()), ("Nova", "pw"));
assert_eq!((f.channel.as_ref(), f.token.as_ref()), ("Gaming/Raid Night", "key"));
}
#[test]
fn locked_channels_ask_for_their_password_once() {
let open = ChannelInfo { id: 1, name: "Lobby".into(), ..Default::default() };
let locked = ChannelInfo { has_password: true, ..open.clone() };
assert_eq!(join_password(&open, None), JoinStep::Send(None));
assert_eq!(join_password(&locked, None), JoinStep::Ask);
assert_eq!(join_password(&locked, Some("")), JoinStep::Ask);
assert_eq!(join_password(&locked, Some("pw")), JoinStep::Send(Some("pw".into())));
assert_eq!(join_password(&open, Some("pw")), JoinStep::Send(Some("pw".into())));
}
#[test]
fn connecting_into_a_channel() {
assert_eq!(after_connect(None, 4, true), AfterConnect::Wait);
assert_eq!(after_connect(Some(4), 4, false), AfterConnect::Joined);
// Put into the default channel: once the channel is known, again.
assert_eq!(after_connect(Some(1), 4, false), AfterConnect::Wait);
assert_eq!(after_connect(Some(1), 4, true), AfterConnect::JoinAgain);
}
#[test]
fn states() {
let mut s = SessionState::default();
assert_eq!(status(&s), "offline");
s.observe = ObserveState::Connecting;
assert_eq!(status(&s), "offline");
s.observe = ObserveState::Observing;
assert_eq!(status(&s), "observing");
s.voice = VoiceState::Connecting;
assert_eq!(status(&s), "connecting");
s.voice = VoiceState::Connected;
assert_eq!(status(&s), "connected");
}
}
+629
View File
@@ -0,0 +1,629 @@
//! The UI's settings keys (besides the engine's, in
//! `voelin_core::settings`), and their conversion to and from the forms of
//! the settings page.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use voelin_audio::process::NoiseLevel;
use voelin_core::settings::{Key, Kind};
use voelin_core::{AudioSettings, TransmitMode};
use crate::bridge::AudioForm;
/// The window's settings, one value (the `ui` blob of earlier versions).
pub static UI: Key<UiSettings> = Key::new(
"ui",
Kind::Json,
"The window's settings: push-to-talk key, H.264, the share dialog's choices.",
UiSettings::default,
);
/// Volume and mute of clients, by unique id.
pub static CLIENT_PLAYBACK: Key<ClientPlaybackMap> = Key::new(
"client_playback",
Kind::Json,
"Volume and mute of clients, by unique id.",
ClientPlaybackMap::new,
);
/// Colours of the window.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ThemeChoice {
#[default]
Dark,
Light,
/// The system's light or dark scheme.
System,
}
impl ThemeChoice {
/// The value stored for this choice.
pub fn as_str(self) -> &'static str {
match self {
Self::Dark => "dark",
Self::Light => "light",
Self::System => "system",
}
}
/// The choice a stored value names (dark for any other).
pub fn parse(text: &str) -> Self {
match text {
"light" => Self::Light,
"system" => Self::System,
_ => Self::Dark,
}
}
}
/// `ui.theme`. (In a config file write `"ui.theme" = "light"` at the top:
/// a `[ui]` table would be read as the `ui` blob.)
pub static UI_THEME: Key<ThemeChoice> = Key::new(
"ui.theme",
Kind::Choice(&["dark", "light", "system"]),
"Colours of the window: dark, light, or the system's scheme.",
ThemeChoice::default,
);
fn positive_scale(v: &f32) -> Result<(), String> {
if v.is_finite() && *v > 0.0 { Ok(()) } else { Err("must be a number above 0".into()) }
}
/// `ui.font_scale`: text size, 1 = normal (no upper limit).
pub static UI_FONT_SCALE: Key<f32> =
Key::new("ui.font_scale", Kind::Json, "Text size as a factor (a number; 1 = normal).", || 1.0)
.validated(positive_scale);
/// `ui.narrow_breakpoint`: below this window width (logical pixels) the
/// phone layout is used.
pub static UI_NARROW_BREAKPOINT: Key<u32> = Key::new(
"ui.narrow_breakpoint",
Kind::UInt { min: 0 },
"Window width in pixels below which the phone layout is used.",
|| 800,
);
/// `ui.image_cache_mb`: memory for decoded images (avatars, icons, emoji).
pub static UI_IMAGE_CACHE_MB: Key<u32> = Key::new(
"ui.image_cache_mb",
Kind::UInt { min: 0 },
"Memory in MB for decoded images (avatars, icons, banners, emoji); 0 keeps none.",
|| 256,
);
/// `ui.members_width`: how wide the members and streams panel is, in
/// pixels. Dragging its handle stores it; there is no built-in maximum.
pub static UI_MEMBERS_WIDTH: Key<u32> = Key::new(
"ui.members_width",
Kind::UInt { min: 0 },
"Width of the members and streams panel in pixels.",
|| 280,
);
/// `ui.voice_compact`: the voice channel view's smaller stage (a strip of
/// people and stream rows, more room for the chat). Its toggle stores it.
pub static UI_VOICE_COMPACT: Key<bool> = Key::new(
"ui.voice_compact",
Kind::Bool,
"The voice channel view's smaller stage, leaving more room for the chat.",
|| false,
);
/// The UI's keys besides [`UI`] and [`CLIENT_PLAYBACK`], for registering.
pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 6] {
[
&UI_THEME,
&UI_FONT_SCALE,
&UI_NARROW_BREAKPOINT,
&UI_IMAGE_CACHE_MB,
&UI_MEMBERS_WIDTH,
&UI_VOICE_COMPACT,
]
}
/// What a kind of notification does: nothing, the bell, or the bell and a
/// desktop notification.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NotifyLevel {
Off,
App,
#[default]
Desktop,
}
impl NotifyLevel {
/// The position in the settings' list (off, app, desktop).
pub fn index(self) -> i32 {
self as i32
}
/// The choice at a list position (desktop for any other).
pub fn from_index(index: i32) -> Self {
match index {
0 => Self::Off,
1 => Self::App,
_ => Self::Desktop,
}
}
}
const NOTIFY_LEVELS: Kind = Kind::Choice(&["off", "app", "desktop"]);
/// `notify.*`: what the bell and the desktop say about each kind.
pub static NOTIFY_MENTIONS: Key<NotifyLevel> = Key::new(
"notify.mentions",
NOTIFY_LEVELS,
"Our name in a channel or server chat: off, app (the bell) or desktop.",
NotifyLevel::default,
);
/// Private messages: off, app (the bell) or desktop.
pub static NOTIFY_MESSAGES: Key<NotifyLevel> = Key::new(
"notify.private_messages",
NOTIFY_LEVELS,
"Private messages: off, app (the bell) or desktop.",
NotifyLevel::default,
);
/// Pokes: off, app (the bell) or desktop.
pub static NOTIFY_POKES: Key<NotifyLevel> =
Key::new("notify.pokes", NOTIFY_LEVELS, "Pokes: off, app (the bell) or desktop.", || {
NotifyLevel::Desktop
});
/// Reminders of scheduled events: off, app (the bell) or desktop.
pub static NOTIFY_EVENTS: Key<NotifyLevel> = Key::new(
"notify.event_reminders",
NOTIFY_LEVELS,
"Reminders of scheduled events: off, app (the bell) or desktop.",
NotifyLevel::default,
);
/// Friends coming online: off, app (the bell) or desktop.
pub static NOTIFY_FRIENDS: Key<NotifyLevel> = Key::new(
"notify.friends_online",
NOTIFY_LEVELS,
"Friends coming online: off, app (the bell) or desktop.",
|| NotifyLevel::App,
);
/// `video.camera`: the camera of the preview and the default of camera
/// sources (a device id; empty: the first camera).
pub static VIDEO_CAMERA: Key<String> = Key::new(
"video.camera",
Kind::Text { suggestions: &[] },
"Camera device (empty: the first one).",
String::new,
);
/// `video.background`: the camera's background effect.
pub static VIDEO_BACKGROUND: Key<String> = Key::new(
"video.background",
Kind::Choice(&["none", "blur"]),
"Background effect of the camera: none or blur.",
|| "none".into(),
);
/// `video.resolution`: the camera's capture size, `auto` or `WIDTHxHEIGHT`.
pub static VIDEO_RESOLUTION: Key<String> = Key::new(
"video.resolution",
Kind::Text { suggestions: &["auto", "1280x720", "1920x1080", "2560x1440"] },
"Camera resolution: auto or WIDTHxHEIGHT.",
|| "auto".into(),
)
.validated(valid_resolution);
/// `video.mirror`: show our camera mirrored, as in a mirror.
pub static VIDEO_MIRROR: Key<bool> =
Key::new("video.mirror", Kind::Bool, "Show our camera mirrored.", || true);
/// `ui.image_preview_kb`: linked pictures up to this size are downloaded
/// and shown in the chat (0: never). No maximum.
pub static UI_IMAGE_PREVIEW_KB: Key<u32> = Key::new(
"ui.image_preview_kb",
Kind::UInt { min: 0 },
"Show pictures linked in chat up to this size in KB (0: never).",
|| 8192,
);
#[allow(clippy::ptr_arg)] // a validation of `Key<String>` is `fn(&String)`
fn valid_resolution(text: &String) -> Result<(), String> {
if text == "auto" || parse_size(text).is_some() {
Ok(())
} else {
Err("auto or WIDTHxHEIGHT, e.g. 1280x720".into())
}
}
/// `1280x720` → (1280, 720), both above 0.
pub fn parse_size(text: &str) -> Option<(u32, u32)> {
let (w, h) = text.trim().split_once(['x', 'X', '×'])?;
let (w, h) = (w.trim().parse().ok()?, h.trim().parse().ok()?);
(w > 0 && h > 0).then_some((w, h))
}
/// The keys of the home, messages and settings pages, for registering.
pub fn page_keys() -> [&'static dyn voelin_core::settings::Setting; 10] {
[
&NOTIFY_MENTIONS,
&NOTIFY_MESSAGES,
&NOTIFY_POKES,
&NOTIFY_EVENTS,
&NOTIFY_FRIENDS,
&VIDEO_CAMERA,
&VIDEO_BACKGROUND,
&VIDEO_RESOLUTION,
&VIDEO_MIRROR,
&UI_IMAGE_PREVIEW_KB,
]
}
/// Frame rates and bitrates (kbit/s; 0: automatic) the share dialog
/// offers, in the order of its lists (`dialogs.slint`); any other value can
/// be typed in.
pub const FPS_CHOICES: [u32; 7] = [15, 30, 60, 120, 144, 240, 320];
/// The bitrates (kbit/s, 0 for automatic) the share dialog offers, in the
/// order of its list.
pub const BITRATE_CHOICES: [u32; 8] = [0, 2500, 4608, 8000, 10_000, 20_000, 40_000, 60_000];
/// The share dialog's lists before they grew, which [`ShareDefaults`]
/// indexes for older versions.
pub const LEGACY_FPS_CHOICES: [u32; 3] = [15, 30, 60];
/// The bitrates of the share dialog's list before it grew.
pub const LEGACY_BITRATE_CHOICES: [u32; 4] = [2500, 4608, 8000, 10_000];
/// The index of the choice closest to `value`.
pub fn nearest_choice(choices: &[u32], value: u32) -> usize {
(0..choices.len()).min_by_key(|&i| choices[i].abs_diff(value)).unwrap_or(0)
}
/// A whole number above 0 typed into a form field.
pub fn parse_positive(text: &str) -> Option<u32> {
text.trim().parse().ok().filter(|v| *v > 0)
}
/// The `ui` settings: what the front end keeps about itself (the push-to-talk
/// hotkey, codecs, the share dialog's defaults, the last voice channel).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct UiSettings {
/// Global push-to-talk hotkey (besides the button in the window).
pub global_ptt: bool,
/// E.g. `Ctrl+Shift+T` (`voelin_platform::Hotkey` syntax).
pub ptt_key: String,
/// H.264 through Cisco's OpenH264, downloaded on request.
pub openh264: bool,
/// The ScreenCast portal's token for the last shared screen.
pub portal_restore_token: Option<String>,
pub share: ShareDefaults,
/// Write crash reports to disk (opt-in; never uploaded).
pub crash_reports: bool,
/// The voice channel we were in last (Home's "Continue where you left
/// off").
pub last_voice: Option<LastVoice>,
}
impl Default for UiSettings {
fn default() -> Self {
Self {
global_ptt: true,
ptt_key: "Ctrl+Shift+T".into(),
openh264: false,
portal_restore_token: None,
share: ShareDefaults::default(),
crash_reports: false,
last_voice: None,
}
}
}
/// Where we were with voice last: the bookmark with the address it had
/// then (one that now points elsewhere does not resume), and the channel's
/// path, its names from the top as the server has them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LastVoice {
pub bookmark: i64,
pub address: String,
pub channel: Vec<String>,
}
/// The last choices in the share dialog. Frame rate and bitrate are the
/// settings `stream.fps` and `stream.bitrate_kbps`; the indices of the
/// closest choices of the old lists ([`LEGACY_FPS_CHOICES`],
/// [`LEGACY_BITRATE_CHOICES`]) are kept for older versions.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ShareDefaults {
pub fps_index: usize,
pub bitrate_index: usize,
pub audio: bool,
pub auto_accept: bool,
}
impl Default for ShareDefaults {
fn default() -> Self {
Self { fps_index: 1, bitrate_index: 1, audio: true, auto_accept: false }
}
}
/// Local playback of one client, kept by its unique id.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ClientPlayback {
/// Linear, 1 = unchanged.
pub volume: f32,
pub muted: bool,
}
impl Default for ClientPlayback {
fn default() -> Self {
Self { volume: 1.0, muted: false }
}
}
impl ClientPlayback {
/// Nothing differs from the defaults, so there is nothing to store.
pub fn is_default(&self) -> bool {
*self == Self::default()
}
}
/// Each client's playback settings, by the client's unique id.
pub type ClientPlaybackMap = BTreeMap<String, ClientPlayback>;
/// Audio devices as listed in the settings: the system default first.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DeviceChoices {
pub names: Vec<String>,
/// Device ids by index; `None` for the system default.
pub ids: Vec<Option<String>>,
}
impl DeviceChoices {
/// `devices` as `(id, name, is_default)`. A selected device that is not
/// connected stays in the list, so the choice survives.
pub fn new(devices: &[(String, String, bool)], selected: Option<&str>) -> Self {
let default_name = devices.iter().find(|d| d.2).map(|d| d.1.as_str());
let mut choices = Self {
names: vec![match default_name {
Some(name) => format!("System default ({name})"),
None => "System default".into(),
}],
ids: vec![None],
};
for (id, name, _) in devices {
choices.names.push(name.clone());
choices.ids.push(Some(id.clone()));
}
if let Some(id) = selected
&& !choices.ids.iter().any(|i| i.as_deref() == Some(id))
{
choices.names.push(format!("{id} (not connected)"));
choices.ids.push(Some(id.to_owned()));
}
choices
}
/// The index of the choice for device `id` (the system default for `None` or
/// an unknown id).
pub fn index_of(&self, id: Option<&str>) -> usize {
self.ids.iter().position(|i| i.as_deref() == id).unwrap_or(0)
}
/// The device id of choice `index`; `None` for the system default or an index
/// outside the list.
pub fn id_at(&self, index: i32) -> Option<String> {
usize::try_from(index).ok().and_then(|i| self.ids.get(i).cloned()).flatten()
}
}
fn noise_index(level: NoiseLevel) -> i32 {
match level {
NoiseLevel::Low => 0,
NoiseLevel::Moderate => 1,
NoiseLevel::High => 2,
NoiseLevel::VeryHigh => 3,
}
}
fn noise_level(index: i32) -> NoiseLevel {
match index {
0 => NoiseLevel::Low,
2 => NoiseLevel::High,
3 => NoiseLevel::VeryHigh,
_ => NoiseLevel::Moderate,
}
}
/// The form's number for a transmit mode (`AudioForm.transmit`).
pub fn transmit_index(mode: TransmitMode) -> i32 {
match mode {
TransmitMode::PushToTalk => 0,
TransmitMode::VoiceActivation => 1,
TransmitMode::Continuous => 2,
}
}
fn transmit_mode(index: i32) -> TransmitMode {
match index {
1 => TransmitMode::VoiceActivation,
2 => TransmitMode::Continuous,
_ => TransmitMode::PushToTalk,
}
}
/// The settings page's form for `settings`.
pub fn audio_form(
settings: &AudioSettings,
inputs: &DeviceChoices,
outputs: &DeviceChoices,
) -> AudioForm {
let p = &settings.processing;
AudioForm {
input_index: inputs.index_of(settings.input_device.as_deref()) as i32,
output_index: outputs.index_of(settings.output_device.as_deref()) as i32,
transmit: transmit_index(settings.transmit),
vad_threshold: settings.vad.threshold_db,
echo_cancellation: p.echo_cancellation,
noise_suppression: p.noise_suppression,
noise_level: noise_index(p.noise_level),
auto_gain: p.auto_gain,
input_gain: p.input_gain_db,
output_volume: settings.output_volume * 100.0,
playback_buffer: settings.playback_buffer_ms as f32,
}
}
/// `settings` changed as the form says; what the form does not show stays.
pub fn apply_audio_form(
form: &AudioForm,
settings: &AudioSettings,
inputs: &DeviceChoices,
outputs: &DeviceChoices,
) -> AudioSettings {
let mut s = settings.clone();
s.input_device = inputs.id_at(form.input_index);
s.output_device = outputs.id_at(form.output_index);
s.transmit = transmit_mode(form.transmit);
s.vad.threshold_db = form.vad_threshold;
s.processing.echo_cancellation = form.echo_cancellation;
s.processing.noise_suppression = form.noise_suppression;
s.processing.noise_level = noise_level(form.noise_level);
s.processing.auto_gain = form.auto_gain;
s.processing.input_gain_db = form.input_gain;
s.output_volume = (form.output_volume / 100.0).clamp(0.0, 4.0);
s.playback_buffer_ms = form.playback_buffer.round().clamp(20.0, 180.0) as u32;
s
}
#[cfg(test)]
mod tests {
use super::*;
fn devices() -> Vec<(String, String, bool)> {
vec![
("alsa:hw:0,0".into(), "Built-in".into(), true),
("alsa:hw:1,0".into(), "Headset".into(), false),
]
}
#[test]
fn device_choices() {
let choices = DeviceChoices::new(&devices(), None);
assert_eq!(choices.names, ["System default (Built-in)", "Built-in", "Headset"]);
assert_eq!(choices.index_of(Some("alsa:hw:1,0")), 2);
assert_eq!(choices.id_at(0), None);
assert_eq!(choices.id_at(2).as_deref(), Some("alsa:hw:1,0"));
assert_eq!(choices.id_at(9), None);
// An unplugged device stays selectable.
let choices = DeviceChoices::new(&devices(), Some("usb:mic"));
assert_eq!(choices.names.last().unwrap(), "usb:mic (not connected)");
assert_eq!(choices.index_of(Some("usb:mic")), 3);
}
#[test]
fn audio_form_roundtrip() {
let inputs = DeviceChoices::new(&devices(), None);
let outputs = DeviceChoices::new(&devices(), None);
let mut settings = AudioSettings {
transmit: TransmitMode::VoiceActivation,
input_device: Some("alsa:hw:1,0".into()),
output_volume: 0.5,
playback_buffer_ms: 80,
..Default::default()
};
settings.vad.threshold_db = -35.0;
settings.processing.noise_level = NoiseLevel::High;
settings.processing.input_gain_db = 6.0;
let form = audio_form(&settings, &inputs, &outputs);
assert_eq!((form.input_index, form.output_index, form.transmit), (2, 0, 1));
assert_eq!(form.output_volume, 50.0);
assert_eq!(apply_audio_form(&form, &settings, &inputs, &outputs), settings);
let form =
AudioForm { transmit: 2, echo_cancellation: false, playback_buffer: 500.0, ..form };
let changed = apply_audio_form(&form, &settings, &inputs, &outputs);
assert_eq!(changed.transmit, TransmitMode::Continuous);
assert!(!changed.processing.echo_cancellation);
assert_eq!(changed.playback_buffer_ms, 180);
}
#[test]
fn transmit_modes() {
for (mode, index) in [
(TransmitMode::PushToTalk, 0),
(TransmitMode::VoiceActivation, 1),
(TransmitMode::Continuous, 2),
] {
assert_eq!(transmit_index(mode), index);
assert_eq!(transmit_mode(index), mode);
}
// Any other number is the default, push-to-talk (Hold to talk shows).
assert_eq!(transmit_mode(7), TransmitMode::PushToTalk);
assert_eq!(transmit_mode(-1), TransmitMode::PushToTalk);
assert_eq!(transmit_index(AudioSettings::default().transmit), 0);
}
#[test]
fn free_values() {
assert_eq!(nearest_choice(&FPS_CHOICES, 60), 2);
assert_eq!(nearest_choice(&FPS_CHOICES, 144), 4);
assert_eq!(nearest_choice(&FPS_CHOICES, 1000), 6);
assert_eq!(nearest_choice(&BITRATE_CHOICES, 0), 0, "automatic");
assert_eq!(nearest_choice(&BITRATE_CHOICES, 3000), 1);
assert_eq!(nearest_choice(&BITRATE_CHOICES, 55_000), 7);
assert_eq!(nearest_choice(&BITRATE_CHOICES, 120_000), 7);
assert_eq!(parse_positive(" 144 "), Some(144));
assert_eq!(parse_positive("0"), None);
assert_eq!(parse_positive("fast"), None);
}
#[test]
fn page_keys() {
assert_eq!(parse_size("1280x720"), Some((1280, 720)));
assert_eq!(parse_size(" 1920 × 1080 "), Some((1920, 1080)));
assert_eq!(parse_size("0x720"), None);
assert_eq!(parse_size("big"), None);
assert!(VIDEO_RESOLUTION.validate(&"auto".into()).is_ok());
assert!(VIDEO_RESOLUTION.validate(&"wide".into()).is_err());
assert_eq!(serde_json::to_value(NotifyLevel::App).unwrap(), "app");
assert_eq!(NotifyLevel::from_index(NotifyLevel::Off.index()), NotifyLevel::Off);
assert_eq!(NotifyLevel::from_index(7), NotifyLevel::Desktop);
}
#[test]
fn voice_compact_key() {
let settings = voelin_core::settings::Settings::in_memory();
for key in appearance_keys() {
settings.register(key);
}
assert_eq!(settings.get_json("ui.voice_compact"), Some(false.into()), "the full stage");
assert!(settings.apply_overrides(["ui.voice_compact=true"]).is_empty());
assert!(settings.get(&UI_VOICE_COMPACT));
assert!(settings.set_json("ui.voice_compact", "small".into()).is_err());
}
#[test]
fn ui_settings_defaults() {
let parsed: UiSettings = serde_json::from_str(r#"{"openh264":true}"#).unwrap();
assert!(parsed.openh264);
assert!(!parsed.crash_reports, "crash reports are opt-in");
assert_eq!(parsed.ptt_key, "Ctrl+Shift+T");
assert_eq!(parsed.share, ShareDefaults::default());
assert_eq!(parsed.last_voice, None, "older settings have no last channel");
let last = LastVoice {
bookmark: 3,
address: "ts.example".into(),
channel: vec!["Games".into(), "Chess".into()],
};
let settings = UiSettings { last_voice: Some(last.clone()), ..UiSettings::default() };
let json = serde_json::to_string(&settings).unwrap();
assert_eq!(serde_json::from_str::<UiSettings>(&json).unwrap().last_voice, Some(last));
assert_eq!(serde_json::to_value(ThemeChoice::System).unwrap(), "system");
assert_eq!(ThemeChoice::parse("light"), ThemeChoice::Light);
assert_eq!(ThemeChoice::parse("??"), ThemeChoice::Dark);
assert!(UI_FONT_SCALE.validate(&0.0).is_err());
assert!(UI_FONT_SCALE.validate(&3.5).is_ok());
let map: ClientPlaybackMap =
serde_json::from_str(r#"{"uid=":{"volume":0.5,"muted":false}}"#).unwrap();
assert_eq!(map["uid="].volume, 0.5);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
//! The settings pages added with the new design: My Account, Profiles
//! (identities), Voice & Video, Streaming, Devices, Notifications, Privacy &
//! Safety, Integrations (gateways, gateway administration, encoders) and
//! Advanced. [`logic`] has what the pages show and what their controls
//! change; the front ends put the rows on screen.
pub mod logic;
+348
View File
@@ -0,0 +1,348 @@
//! Texts of the home, friends, messages, bell and events screens: times
//! ("12m ago", "Yesterday"), message previews without BBCode (read by
//! `vm::bbcode`), mentions, event dates, a poke's message, the private
//! chats of the home sidebar; pure, so they are tested here.
use chrono::{DateTime, Local, NaiveDateTime, TimeZone};
use voelin_core::HistoryMessage;
use voelin_model::ChatTarget;
/// A chat of any server.
#[derive(Clone, Debug, PartialEq)]
pub struct ChatRef {
/// The bookmark (session) it belongs to, when known.
pub session: Option<i64>,
/// The server's unique id.
pub server_uid: Option<String>,
/// Which chat of the server.
pub target: ChatTarget,
/// Its newest message.
pub last: Option<HistoryMessage>,
/// Messages not read.
pub unread: i32,
}
fn local(ts_ms: i64) -> Option<NaiveDateTime> {
DateTime::from_timestamp_millis(ts_ms).map(|t| t.with_timezone(&Local).naive_local())
}
fn now_local() -> NaiveDateTime {
Local::now().naive_local()
}
/// "now", "5m ago", "2h ago", "3d ago", else the date ("12 Mar").
pub fn ago(ts_ms: i64) -> String {
ago_at(ts_ms, chrono::Utc::now().timestamp_millis())
}
/// [`ago`] for a given time `now_ms`.
pub fn ago_at(ts_ms: i64, now_ms: i64) -> String {
if ts_ms <= 0 {
return String::new();
}
let minutes = (now_ms - ts_ms) / 60_000;
match minutes {
i64::MIN..=0 => "now".into(),
1..=59 => format!("{minutes}m ago"),
60..=1439 => format!("{}h ago", minutes / 60),
1440..=10079 => format!("{}d ago", minutes / 1440),
_ => local(ts_ms).map(|t| t.format("%-d %b").to_string()).unwrap_or_default(),
}
}
/// The time of a conversation in a list: "11:42" today, "Yesterday", the
/// weekday within a week ("Mon"), else the date ("12 Mar", with the year
/// when it is another).
pub fn list_time(ts_ms: i64) -> String {
local(ts_ms).map(|t| list_time_at(t, now_local())).unwrap_or_default()
}
/// [`list_time`] for a given local time `now`.
pub fn list_time_at(then: NaiveDateTime, now: NaiveDateTime) -> String {
use chrono::Datelike;
let days = (now.date() - then.date()).num_days();
match days {
i64::MIN..=0 => then.format("%H:%M").to_string(),
1 => "Yesterday".into(),
2..=6 => then.format("%a").to_string(),
_ if then.year() == now.year() => then.format("%-d %b").to_string(),
_ => then.format("%-d %b %Y").to_string(),
}
}
/// Chat text without BBCode (`[b]`, `[URL=…]`, `[/URL]`), on one line.
pub fn plain(text: &str) -> String {
without_emoji(&crate::bbcode::parse(text).one_line())
}
/// Text without emoji, runs of spaces as one: one line of text draws no
/// emoji (they are pictures in the chat).
pub fn without_emoji(text: &str) -> String {
let mut words = String::with_capacity(text.len());
for run in crate::emoji::split(text).into_iter().filter(|r| r.emoji.is_none()) {
words.extend(run.text.chars().filter(|c| !is_emoji(*c)));
}
words.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// Pictographs, symbols and their joiners and variation selectors.
fn is_emoji(c: char) -> bool {
matches!(u32::from(c), 0x1F000..=0x1FAFF | 0x2600..=0x27BF | 0xFE0F | 0x200D)
}
/// A one-line preview of a message: "You: …" for our own, "Sent a
/// picture" / "Sent a file" for links without text.
pub fn preview(text: &str, mine: bool, files: &[voelin_model::FileRef]) -> String {
let body = if files.is_empty() { plain(text) } else { String::new() };
let body = if body.is_empty() && !files.is_empty() {
if files.iter().any(|f| crate::chat::is_picture(&f.name)) {
"Sent a picture".to_owned()
} else {
"Sent a file".to_owned()
}
} else {
body
};
if mine { format!("You: {body}") } else { body }
}
/// Whether `text` names `nick` as a word (case does not matter): a mention.
pub fn mentions(text: &str, nick: &str) -> bool {
let nick = nick.trim().to_lowercase();
if nick.is_empty() {
return false;
}
let text = text.to_lowercase();
text.match_indices(&nick).any(|(at, _)| {
let before = text[..at].chars().next_back();
let after = text[at + nick.len()..].chars().next();
!before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric)
})
}
/// Case-insensitive search in any of `fields`.
pub fn matches(query: &str, fields: &[&str]) -> bool {
let q = query.trim().to_lowercase();
q.is_empty() || fields.iter().any(|f| f.to_lowercase().contains(&q))
}
/// A poke's message as it is sent: trimmed, and cut to the
/// [`voelin_core::POKE_MESSAGE_MAX`] characters servers take.
pub fn poke_message(text: &str) -> String {
let cut: String = text.trim().chars().take(voelin_core::POKE_MESSAGE_MAX).collect();
cut.trim_end().to_owned()
}
/// The private chats of the home sidebar, by their index in `chats`
/// (newest first): at most `n`, those with unread messages first.
pub fn sidebar_dms(chats: &[ChatRef], n: usize) -> Vec<usize> {
let mut private: Vec<usize> = (0..chats.len())
.filter(|&i| matches!(chats[i].target, voelin_model::ChatTarget::Private(_)))
.collect();
private.sort_by_key(|&i| chats[i].unread == 0);
private.truncate(n);
private
}
/// The channels the search (Ctrl+K) finds for `query`, with their titles:
/// a spacer by its text, never a line or an empty spacer.
pub fn found_channels<'a>(
channels: impl IntoIterator<Item = &'a voelin_model::ChannelInfo>,
query: &str,
) -> Vec<(u64, &'a str)> {
channels
.into_iter()
.filter_map(|c| Some((c.id, crate::tree::listed_title(c)?)))
.filter(|(_, title)| matches(query, &[*title]))
.collect()
}
/// The date block of an event: "SAT", "26", "APR".
pub fn date_block(ts_ms: i64) -> (String, String, String) {
local(ts_ms)
.map(|t| {
(
t.format("%a").to_string().to_uppercase(),
t.format("%-d").to_string(),
t.format("%b").to_string().to_uppercase(),
)
})
.unwrap_or_default()
}
/// "Sat 26 Apr, 19:00 – 21:00" (the end's date too when it is another day).
pub fn event_when(start_ms: i64, end_ms: Option<i64>) -> String {
let Some(start) = local(start_ms) else { return String::new() };
let mut out = start.format("%a %-d %b, %H:%M").to_string();
if let Some(end) = end_ms.and_then(local) {
let end = if end.date() == start.date() {
end.format("%H:%M")
} else {
end.format("%a %-d %b, %H:%M")
};
out.push_str(&format!(" – {end}"));
}
out
}
/// "Starts in 15 min", "Starts in 3 h", "Happening now", or nothing (more
/// than a day away, or over).
pub fn soon(start_ms: i64, end_ms: Option<i64>, now_ms: i64) -> String {
let minutes = (start_ms - now_ms) / 60_000;
let over = end_ms.map_or(now_ms - start_ms > 3 * 3_600_000, |end| now_ms > end);
match minutes {
_ if over => String::new(),
i64::MIN..=0 => "Happening now".into(),
1..=59 => format!("Starts in {minutes} min"),
60..=1439 => format!("Starts in {} h", minutes / 60),
_ => String::new(),
}
}
/// `2026-10-04 19:00` in local time → Unix milliseconds.
pub fn parse_local(text: &str) -> Option<i64> {
let t = NaiveDateTime::parse_from_str(text.trim(), "%Y-%m-%d %H:%M").ok()?;
Local.from_local_datetime(&t).earliest().map(|t| t.timestamp_millis())
}
/// Unix milliseconds → `2026-10-04 19:00` in local time.
pub fn format_local(ts_ms: i64) -> String {
local(ts_ms).map(|t| t.format("%Y-%m-%d %H:%M").to_string()).unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
fn at(text: &str) -> NaiveDateTime {
NaiveDateTime::parse_from_str(text, "%Y-%m-%d %H:%M").unwrap()
}
#[test]
fn times() {
let now = 1_800_000_000_000;
assert_eq!(ago_at(now - 30_000, now), "now");
assert_eq!(ago_at(now - 12 * 60_000, now), "12m ago");
assert_eq!(ago_at(now - 2 * 3_600_000, now), "2h ago");
assert_eq!(ago_at(now - 3 * 86_400_000, now), "3d ago");
assert_eq!(ago_at(0, now), "");
let now = at("2026-10-03 14:00");
assert_eq!(list_time_at(at("2026-10-03 11:42"), now), "11:42");
assert_eq!(list_time_at(at("2026-10-02 23:00"), now), "Yesterday");
assert_eq!(list_time_at(at("2026-09-28 10:00"), now), "Mon");
assert_eq!(list_time_at(at("2026-03-12 10:00"), now), "12 Mar");
assert_eq!(list_time_at(at("2025-03-12 10:00"), now), "12 Mar 2025");
}
#[test]
fn previews() {
assert_eq!(plain("[b]Hi[/b] there"), "Hi there");
assert_eq!(plain("see [URL=https://x.org]this[/URL]"), "see this");
assert_eq!(plain("a [not a tag here] b"), "a [not a tag here] b");
assert_eq!(plain("[1] item"), "[1] item");
assert_eq!(plain("later? 👀 Posting ❤️"), "later? Posting");
// Only known tags go.
assert_eq!(plain("[nick] hi"), "[nick] hi");
assert_eq!(plain("[quote=Mira]raid?[/quote]\nyes [i]now[/i]"), "raid? yes now");
assert_eq!(preview("Hello", true, &[]), "You: Hello");
let file = |name: &str| voelin_model::FileRef { name: name.into(), ..Default::default() };
assert_eq!(
preview("[URL=ts3file://x]a.png[/URL]", false, &[file("a.png")]),
"Sent a picture"
);
assert_eq!(preview("x", true, &[file("notes.txt")]), "You: Sent a file");
}
#[test]
fn mention_words() {
assert!(mentions("hey Nova, raid?", "nova"));
assert!(mentions("@Nova", "Nova"));
assert!(!mentions("supernova", "Nova"));
assert!(!mentions("anything", ""));
assert!(matches("kai", &["Kairo", "x"]));
assert!(matches("", &[]));
assert!(!matches("zz", &["Kairo"]));
}
#[test]
fn poke_messages() {
assert_eq!(poke_message(" Raid in 5? "), "Raid in 5?");
assert_eq!(poke_message(""), "");
assert_eq!(poke_message(" \n "), "");
let exact = "x".repeat(100);
assert_eq!(poke_message(&exact), exact);
// Characters, not bytes: two bytes each.
assert_eq!(poke_message(&"ä".repeat(150)), "ä".repeat(100));
assert_eq!(poke_message(&format!("{}€!", "ü".repeat(99))), format!("{}€", "ü".repeat(99)));
// A cut that ends in a space leaves it out.
assert_eq!(poke_message(&format!("{} more", "a".repeat(99))), "a".repeat(99));
}
/// The search shows spacers by their text and leaves out lines.
#[test]
fn search_channels() {
let channel = |id, parent, name: &str| voelin_model::ChannelInfo {
id,
parent,
name: name.into(),
..Default::default()
};
let channels = [
channel(1, 0, "[cspacer0]Gaming"),
channel(2, 0, "[*spacer]---"),
channel(3, 0, "[spacer1]"),
// Only top-level channels are spacers.
channel(4, 1, "[cspacer]Game Night"),
channel(5, 0, "Lobby"),
];
assert_eq!(found_channels(&channels, "gam"), [(1, "Gaming"), (4, "[cspacer]Game Night")]);
assert!(found_channels(&channels, "-").is_empty());
// A spacer is not found by its prefix; a sub-channel's name is all
// its own.
assert_eq!(found_channels(&channels, "spacer"), [(4, "[cspacer]Game Night")]);
assert_eq!(found_channels(&channels, "").len(), 3);
}
#[test]
fn sidebar_chats() {
use voelin_model::ChatTarget;
let chat = |target: ChatTarget, unread| ChatRef {
session: Some(1),
server_uid: None,
target,
last: None,
unread,
};
let dm = |uid: &str, unread| chat(ChatTarget::Private(uid.into()), unread);
let chats = [
dm("a", 0),
chat(ChatTarget::Server, 4),
dm("b", 2),
chat(ChatTarget::Channel(3), 1),
dm("c", 0),
dm("d", 1),
dm("e", 0),
dm("f", 0),
];
// Private chats only, unread first, otherwise newest first; capped.
assert_eq!(sidebar_dms(&chats, 5), [2, 5, 0, 4, 6]);
assert_eq!(sidebar_dms(&chats, 1), [2]);
assert!(sidebar_dms(&chats[1..2], 5).is_empty());
}
#[test]
fn event_dates() {
let start = parse_local("2026-04-25 19:00").unwrap();
assert_eq!(format_local(start), "2026-04-25 19:00");
assert_eq!(date_block(start), ("SAT".into(), "25".into(), "APR".into()));
let end = parse_local("2026-04-25 21:30").unwrap();
assert_eq!(event_when(start, Some(end)), "Sat 25 Apr, 19:00 – 21:30");
assert_eq!(event_when(start, None), "Sat 25 Apr, 19:00");
assert!(parse_local("tomorrow").is_none());
assert_eq!(soon(start, Some(end), start - 15 * 60_000), "Starts in 15 min");
assert_eq!(soon(start, Some(end), start - 3 * 3_600_000), "Starts in 3 h");
assert_eq!(soon(start, Some(end), start + 60_000), "Happening now");
assert_eq!(soon(start, Some(end), end + 60_000), "");
assert_eq!(soon(start, None, start - 2 * 86_400_000), "");
}
}
+723
View File
@@ -0,0 +1,723 @@
//! What the client knows, apart from how it is shown: the servers' sessions
//! with their chat tabs, and the data the screens share. A front end owns
//! one [`AppState`] and fills it from the engine's events; the view models
//! (`chat`, `tree`, `servers`, ...) turn it into rows.
//!
//! The lines of a chat tab are the front end's own list type `L`: a Slint
//! model (`bind::rows::Rows`), or a plain `Vec` of rows.
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use voelin_core::stream::StreamInfo;
use voelin_core::{
AudioSettings, Bytes, Contact, HistoryMessage, OfflineMessageInfo, SessionState, TransferState,
VoiceState,
};
use voelin_gateway_proto::{
Action, ActivityEntry, ConfigEntry, EventInfo, PermRuleInfo, StreamEntry, TopicInfo,
};
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, GroupInfo, Presence};
use voelin_store::Bookmark;
use crate::chat::{LineCache, Previous};
use crate::image::ImageRef;
use crate::settings::{ClientPlaybackMap, DeviceChoices, UiSettings};
/// The store's name of a chat.
pub fn store_target(target: &ChatTarget) -> voelin_store::ChatTarget {
match target {
ChatTarget::Server => voelin_store::ChatTarget::Server,
ChatTarget::Channel(cid) => voelin_store::ChatTarget::Channel(*cid),
ChatTarget::Private(uid) => voelin_store::ChatTarget::Private(uid.clone()),
}
}
/// A file being downloaded from a chat message.
pub struct Download {
/// The message's handle.
pub key: i32,
/// Which of the message's links this is.
pub index: usize,
/// The file's name.
pub name: String,
/// How the transfer stands.
pub state: TransferState,
}
/// A pinned message of a chat, with who pinned it.
pub struct PinRow {
/// The message's handle.
pub key: i32,
/// The message.
pub message: HistoryMessage,
/// Who pinned it.
pub by: String,
/// When it was pinned.
pub ts_ms: i64,
}
/// A linked picture.
#[derive(Clone, Debug)]
pub enum Preview {
/// Downloading (transfer id).
Loading(u64),
/// Downloaded: the file's bytes.
Ready(Bytes),
/// Too large, not a picture, or the download failed.
Failed,
}
/// What a session's gateway and voice connection add for these screens.
#[derive(Default)]
pub struct SessionExtra {
/// The gateway's stream directory.
pub directory: Vec<StreamEntry>,
/// The gateway's events by start time.
pub events: Vec<EventInfo>,
/// The events were asked for and arrived.
pub events_loaded: bool,
/// The events whose answers are shown (by event id).
pub expanded: HashSet<i64>,
/// The activity feed, newest first.
pub activity: Vec<ActivityEntry>,
/// Our unique id at the gateway.
pub gateway_uid: Option<String>,
/// What we may do at the gateway.
pub actions: Vec<Action>,
/// Gateway administration: its keys.
pub config: Vec<ConfigEntry>,
/// Gateway administration: its permission rules.
pub perms: Vec<PermRuleInfo>,
/// Offline messages (voice).
pub inbox: Vec<OfflineMessageInfo>,
/// The offline messages were asked for.
pub inbox_asked: bool,
/// Pictures linked in chat, by link.
pub previews: HashMap<String, Preview>,
/// When this session's presence first came (ms): friends found in it
/// then are not "coming online".
pub presence_since: i64,
/// "TeamSpeak 6", "TeamSpeak 3" once the server told what it runs;
/// empty before that, and for software nobody recognised.
pub product: String,
}
/// A message of a chat with the handle the UI knows it by: the engine's
/// local ids are 64 bit, a bridge `int` is not.
pub struct Msg {
/// The handle (see [`Tab::take_key`]).
pub key: i32,
/// The message as the engine stored it.
pub message: HistoryMessage,
}
/// A chat of a session: its lines (`L`) are what the chat view shows while
/// the tab is selected, so a new message is one row appended.
pub struct Tab<L> {
/// The chat.
pub target: ChatTarget,
/// The tab's name.
pub title: String,
/// The lines the chat view shows.
pub lines: L,
/// The messages, oldest first, by `(ts_ms, id)`.
pub messages: Vec<Msg>,
/// Live messages of a session that keeps no history (no server unique
/// id yet): grouped from the message before, without ids.
pub last: Option<Previous>,
/// Messages not read, not ours: those after `read` (without stored
/// history, those that came while the tab was not on screen).
pub unread: i32,
/// The newest message read, by `(ts_ms, id)`: kept in the store
/// (`chat_reads`) when the tab is left, the session closes and on exit
/// (`App::save_read`). `stored_read` is what the store has.
pub read: Option<(i64, i64)>,
/// What the store has of `read`.
pub stored_read: Option<(i64, i64)>,
/// The message the "New" divider is above: the first that was new when
/// the tab came on screen. It stays until the tab is left.
pub divider: Option<i64>,
/// Nothing older exists as far as the engine can tell.
pub complete: bool,
/// A gateway page arrived: the chat is not only what we saw.
pub synced: bool,
/// An older page was asked for.
pub loading: bool,
/// The next message handle.
next_key: i32,
/// The pins of this chat, once asked for.
pub pins: Vec<PinRow>,
/// The pins were asked for and arrived.
pub pins_loaded: bool,
/// The gateway topics of this chat.
pub topics: Vec<TopicInfo>,
/// The topics were asked for and arrived.
pub topics_loaded: bool,
/// The open topic.
pub topic: Option<i64>,
/// The messages of the open topic.
pub topic_messages: Vec<Msg>,
/// The message jumped to from the pins.
pub marked: Option<i64>,
/// What the lines of `messages` were built from.
pub cache: LineCache,
}
impl<L: Default> Tab<L> {
/// An empty tab for a chat, nothing read or asked for.
pub fn new(target: ChatTarget, title: String) -> Self {
Self {
target,
title,
lines: L::default(),
messages: Vec::new(),
last: None,
unread: 0,
read: None,
stored_read: None,
divider: None,
complete: false,
synced: false,
loading: false,
next_key: 1,
pins: Vec::new(),
pins_loaded: false,
topics: Vec::new(),
topics_loaded: false,
topic: None,
topic_messages: Vec::new(),
marked: None,
cache: Default::default(),
}
}
}
impl<L> Tab<L> {
/// A private chat (on the Direct Messages page, not in the chat strip).
pub fn is_private(&self) -> bool {
matches!(self.target, ChatTarget::Private(_))
}
/// A handle for a message that has none yet.
pub fn take_key(&mut self) -> i32 {
self.next_key += 1;
self.next_key
}
/// The message with this handle, in the chat or in the open topic.
pub fn message(&self, key: i32) -> Option<&HistoryMessage> {
self.messages.iter().chain(&self.topic_messages).find(|m| m.key == key).map(|m| &m.message)
}
/// Where each message is and whether it is ours (`own`), for the read
/// markers ([`crate::chat::first_unread`]).
pub fn positions(&self, own: impl Fn(&ChatMessage) -> bool) -> Vec<(i64, i64, bool)> {
self.messages
.iter()
.map(|m| (m.message.message.ts_ms, m.message.id, own(&m.message.message)))
.collect()
}
/// Where the newest message is.
pub fn newest(&self) -> Option<(i64, i64)> {
self.messages.last().map(|m| (m.message.message.ts_ms, m.message.id))
}
/// The tab came on screen: the first new message gets the divider
/// (unless one shows), and everything is read.
pub fn enter(&mut self, own: impl Fn(&ChatMessage) -> bool) {
if self.unread > 0 && self.divider.is_none() {
let first = crate::chat::first_unread(&self.positions(own), self.read);
self.divider = first.map(|i| self.messages[i].message.id);
}
self.catch_up();
}
/// Everything in the tab is read (it is on screen).
pub fn catch_up(&mut self) {
self.read = self.read.max(self.newest());
self.unread = 0;
}
/// Count what is not read: what came after `read`, not ours.
pub fn count_unread(&mut self, own: impl Fn(&ChatMessage) -> bool) {
self.unread = crate::chat::unread_count(&self.positions(own), self.read);
}
/// Start from where the store says the chat was read (`reads`: by the
/// store's name of the chat).
pub fn read_from(&mut self, reads: &HashMap<String, (i64, i64)>) {
if let Some(&read) = reads.get(&store_target(&self.target).key()) {
self.read = self.read.max(Some(read));
self.stored_read = Some(read);
}
}
}
/// What we know about one server session.
pub struct SessionView<L> {
/// Where the connections stand.
pub state: SessionState,
/// What the server offers.
pub capabilities: Capabilities,
/// The server's channels and clients.
pub presence: Arc<Presence>,
/// The channels folded in the tree.
pub collapsed: HashSet<ChannelId>,
/// The clients talking now.
pub talking: HashSet<u16>,
/// The chats, the server's first.
pub tabs: Vec<Tab<L>>,
/// The chat on screen (an index of `tabs`).
pub current_tab: usize,
/// The chat strip's chat last current (the server's or a channel's): a
/// private chat is current only on the Direct Messages page, and this
/// one is current again when that page is left.
pub channel_tab: ChatTarget,
/// The own channel's tab was focused for this voice connection.
pub focused_own_channel: bool,
/// The streams in our channel (TeamSpeak 6).
pub streams: Vec<StreamInfo>,
/// Clients whose stored volume was sent for this voice connection.
pub applied_playback: HashSet<u16>,
/// Avatar pictures in the engine's cache, by unique id
/// ([`Event::AvatarReady`]).
pub avatars: HashMap<String, PathBuf>,
/// Icons in the engine's cache, by icon id ([`Event::IconReady`]).
pub icons: HashMap<u32, PathBuf>,
/// Banners and badges in the engine's cache, by address
/// ([`Event::PictureReady`]).
pub pictures: HashMap<String, PathBuf>,
/// The server's icon id as its voice connection last told it
/// ([`Event::ServerDetails`]); kept while disconnected, for the rail.
pub server_icon: u32,
/// Bookmark address that supplied this session's icon.
pub icon_address: Option<String>,
/// The server groups in display order ([`Event::Groups`]).
pub server_groups: Vec<GroupInfo>,
/// The channel groups ([`Event::Groups`]).
pub channel_groups: Vec<GroupInfo>,
/// What the session's gateway offers (`voelin_gateway_proto::feature`).
pub gateway_caps: Vec<String>,
/// The client whose member card is open.
pub member_card: Option<u16>,
/// Passwords given for locked channels, until voice disconnects.
pub channel_passwords: HashMap<ChannelId, String>,
/// The channel a voice connection was asked into, until it is joined
/// or joined again (`App::join_after_connect`).
pub join_after_connect: Option<ChannelId>,
/// Viewers of the streams in the gateway's directory, by stream id.
pub stream_viewers: HashMap<String, u32>,
/// Downloads started from chat, by transfer id.
pub downloads: HashMap<u64, Download>,
/// The next transfer id.
pub next_transfer: u64,
/// What the home, messages and events screens keep of the session.
pub extra: SessionExtra,
/// Where its chats were read, from the store (by the store's name of
/// the chat), for the server unique id `reads_of`.
pub reads: HashMap<String, (i64, i64)>,
/// The server unique id `reads` are for.
pub reads_of: Option<String>,
}
impl<L: Default> Default for SessionView<L> {
fn default() -> Self {
Self {
state: SessionState::default(),
capabilities: Capabilities::default(),
presence: Arc::default(),
collapsed: HashSet::new(),
talking: HashSet::new(),
tabs: vec![Tab::new(ChatTarget::Server, "Server".into())],
current_tab: 0,
channel_tab: ChatTarget::Server,
focused_own_channel: false,
streams: Vec::new(),
applied_playback: HashSet::new(),
avatars: HashMap::new(),
icons: HashMap::new(),
pictures: HashMap::new(),
server_icon: 0,
icon_address: None,
server_groups: Vec::new(),
channel_groups: Vec::new(),
gateway_caps: Vec::new(),
member_card: None,
channel_passwords: HashMap::new(),
join_after_connect: None,
stream_viewers: HashMap::new(),
downloads: HashMap::new(),
next_transfer: 1,
extra: Default::default(),
reads: HashMap::new(),
reads_of: None,
}
}
}
impl<L> SessionView<L> {
/// Streams can be watched and shared: TeamSpeak 6, connected with voice.
pub fn streams_available(&self) -> bool {
self.capabilities.streams && self.state.voice == VoiceState::Connected
}
/// The channel a client is in.
pub fn channel_of(&self, client: u16) -> Option<u64> {
self.presence.clients.get(&client).map(|c| c.channel)
}
/// The name of a client's channel when it is not ours; empty in ours.
pub fn other_channel_name(&self, client: u16) -> String {
self.channel_of(client)
.filter(|c| Some(*c) != self.state.own_channel)
.and_then(|c| self.presence.channels.get(&c))
.map_or_else(String::new, |c| crate::tree::channel_title(c).0.to_owned())
}
/// A client's nickname, or its id.
pub fn nickname(&self, client: u16) -> String {
self.presence
.clients
.get(&client)
.map_or_else(|| format!("client {client}"), |c| c.nickname.clone())
}
/// Unread messages in the server's and the channels' chats (the rail and
/// the chat strip count them; private chats count on the Direct
/// Messages page).
pub fn channel_unread(&self) -> i32 {
self.tabs.iter().filter(|t| !t.is_private()).map(|t| t.unread).sum()
}
/// Unread messages in private chats.
pub fn private_unread(&self) -> i32 {
self.tabs.iter().filter(|t| t.is_private()).map(|t| t.unread).sum()
}
/// Make tab `index` the current one; the chat strip remembers it unless
/// it is a private chat.
pub fn set_current_tab(&mut self, index: usize) {
self.current_tab = index;
if let Some(tab) = self.tabs.get(index).filter(|t| !t.is_private()) {
self.channel_tab = tab.target.clone();
}
}
/// Focus tab `index`. While a private chat is current (the Direct
/// Messages page shows it, and its composer sends there), a chat of the
/// strip does not take its place: it is the strip's chat, current once
/// that page is left (voice connecting focuses its channel's chat).
pub fn focus_tab(&mut self, index: usize) {
let Some(tab) = self.tabs.get(index) else { return };
if !tab.is_private() && self.tabs.get(self.current_tab).is_some_and(Tab::is_private) {
self.channel_tab = tab.target.clone();
} else {
self.set_current_tab(index);
}
}
/// Remove tab `index`. The current tab stays; when it is this one, the
/// chat strip's next tab takes its place, else its last.
pub fn remove_tab(&mut self, index: usize) -> Tab<L> {
let tab = self.tabs.remove(index);
if self.current_tab > index {
self.current_tab -= 1;
} else if self.current_tab == index {
let (strip, _) = crate::chat::strip(self.tabs.iter().map(|t| &t.target), 0);
let next = strip.iter().find(|&&i| i >= index).or(strip.last()).copied();
self.set_current_tab(next.unwrap_or(0));
}
tab
}
/// Leave a current private chat for the chat strip's last one (the
/// Direct Messages page was left); `true` if the current tab changed.
pub fn leave_private(&mut self) -> bool {
if !self.tabs.get(self.current_tab).is_some_and(Tab::is_private) {
return false;
}
self.current_tab = self.tabs.iter().position(|t| t.target == self.channel_tab).unwrap_or(0);
true
}
/// The session's gateway offers this feature
/// (`voelin_gateway_proto::feature`).
pub fn gateway_has(&self, feature: &str) -> bool {
self.gateway_caps.iter().any(|c| c == feature)
}
/// The chat history is kept by the engine (it knows the server): its
/// messages come with ids, reactions and pins.
pub fn has_history(&self) -> bool {
self.state.server_uid.is_some()
}
/// The avatar picture of a client, if the engine fetched one.
pub fn avatar(&self, client: u16) -> Option<&PathBuf> {
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) -> ImageRef {
crate::avatar::image(self.icons.get(&self.server_icon).filter(|_| self.server_icon != 0))
}
/// Icons stay associated with the address that supplied them, including
/// while a reconnect to an edited bookmark is pending or has failed.
pub fn server_icon_for(&self, address: &str) -> ImageRef {
if self.icon_address.as_deref() == Some(address) {
self.server_icon()
} else {
ImageRef::default()
}
}
}
impl<L: Default> SessionView<L> {
/// A new tab for `target`, read as far as the store says.
pub fn new_tab(&self, target: ChatTarget, title: String) -> Tab<L> {
let mut tab = Tab::new(target, title);
tab.read_from(&self.reads);
tab
}
}
/// The data the screens share, apart from the engine and the toolkit: the
/// servers and what is known of their sessions, the settings the screens
/// show and the dialogs' targets.
pub struct AppState<L> {
/// The saved servers, in the rail's order.
pub bookmarks: Vec<Bookmark>,
/// The server shown (a bookmark id).
pub current: Option<i64>,
/// What is known of each server's session, by bookmark id.
pub sessions: HashMap<i64, SessionView<L>>,
/// The line at the bottom: what happened last.
pub status: String,
/// What the toast of the next copy says instead of "Copied" (an invite
/// names its channel and link).
pub copy_note: Option<String>,
/// The members panel's search.
pub member_filter: String,
/// The topics drawer's search.
pub topic_filter: String,
/// The voice channel view is shown (its people come first in the
/// members panel).
pub voice_view: bool,
/// The UI's own settings (a working copy of the `ui` key).
pub settings: UiSettings,
/// The audio settings (a working copy).
pub audio: AudioSettings,
/// Audio settings changed since they were last stored.
pub audio_dirty: bool,
/// The input devices, as the settings list them.
pub inputs: DeviceChoices,
/// The output devices, as the settings list them.
pub outputs: DeviceChoices,
/// Local playback of each client, by unique id.
pub playback: ClientPlaybackMap,
/// The engine's contacts, by unique id.
pub contacts: HashMap<String, Contact>,
/// The client in the volume dialog: session, client id, unique id.
pub playback_dialog: Option<(i64, u16, Option<String>)>,
/// The locked channel the password dialog is for: session, channel.
pub join_target: Option<(i64, ChannelId)>,
/// Who the poke dialog pokes: session, client, nickname.
pub poke_target: Option<(i64, u16, String)>,
/// The window has the focus (desktop: the toolkit tells; elsewhere
/// assumed): messages are read only then.
pub focused: bool,
/// The chat whose messages are on screen (session, target): when it is
/// left, it is stored and loses its divider.
pub reading: Option<(i64, ChatTarget)>,
/// The microphone test runs.
pub mic_test: bool,
/// The capture for a share is being started.
pub share_busy: bool,
/// Why the last share did not start.
pub share_error: String,
/// A client whose stream was asked for before it was known (session,
/// client): watched when the lookup brings it.
pub pending_watch: Option<(i64, u16)>,
/// Stream volume in percent, kept between streams.
pub stream_volume: f32,
/// Servers whose gateway was looked up in this run.
pub gateways_looked_up: HashSet<i64>,
/// Files being uploaded to a channel from the composer: session,
/// channel and name, so the link can be posted when they are up.
pub uploads: HashMap<u64, (i64, u64, String)>,
}
impl<L> AppState<L> {
/// The state at start: the saved servers (the first one shown), the
/// stored settings, nothing known of any session yet.
pub fn new(
bookmarks: Vec<Bookmark>,
settings: UiSettings,
audio: AudioSettings,
playback: ClientPlaybackMap,
) -> Self {
Self {
current: bookmarks.first().map(|b| b.id),
bookmarks,
sessions: HashMap::new(),
status: String::new(),
copy_note: None,
member_filter: String::new(),
topic_filter: String::new(),
voice_view: false,
settings,
audio,
audio_dirty: false,
inputs: DeviceChoices::default(),
outputs: DeviceChoices::default(),
playback,
contacts: HashMap::new(),
playback_dialog: None,
join_target: None,
poke_target: None,
focused: true,
reading: None,
mic_test: false,
share_busy: false,
share_error: String::new(),
pending_watch: None,
stream_volume: 100.0,
gateways_looked_up: HashSet::new(),
uploads: HashMap::new(),
}
}
}
#[cfg(test)]
mod tests {
use voelin_store::MessageSource;
use super::*;
fn msg(key: i32, id: i64, ts_ms: i64, own: bool) -> Msg {
Msg {
key,
message: HistoryMessage {
id,
message: ChatMessage {
target: ChatTarget::Server,
author_name: if own { "me" } else { "you" }.into(),
author_uid: None,
author_id: None,
text: format!("message {id}"),
ts_ms,
via_relay: false,
blocked: false,
},
source: MessageSource::Voice,
remote_id: None,
topic_id: None,
reactions: Vec::new(),
pinned: false,
rev: 0,
},
}
}
fn is_own(message: &ChatMessage) -> bool {
message.author_name == "me"
}
/// A session with the server's chat and then these.
fn session(targets: &[ChatTarget]) -> SessionView<()> {
let mut view = SessionView::<()>::default();
for target in targets {
view.tabs.push(Tab::new(target.clone(), "chat".into()));
}
view
}
#[test]
fn a_private_chat_stays_current_until_its_page_is_left() {
let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Private("uid".into())]);
view.set_current_tab(2);
assert_eq!((view.current_tab, &view.channel_tab), (2, &ChatTarget::Server));
// A chat of the strip does not take the private chat's place ...
view.focus_tab(1);
assert_eq!((view.current_tab, &view.channel_tab), (2, &ChatTarget::Channel(1)));
// ... it is current once the page is left, and only once.
assert!(view.leave_private());
assert_eq!(view.current_tab, 1);
assert!(!view.leave_private());
}
#[test]
fn removing_a_tab_keeps_the_current_one_or_picks_the_next_of_the_strip() {
let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Channel(2)]);
view.set_current_tab(2);
view.remove_tab(1);
assert_eq!(view.current_tab, 1);
assert_eq!(view.tabs[1].target, ChatTarget::Channel(2));
// The current tab itself: the strip's next one takes its place.
let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Channel(2)]);
view.set_current_tab(1);
view.remove_tab(1);
assert_eq!(view.tabs[view.current_tab].target, ChatTarget::Channel(2));
}
#[test]
fn unread_messages_are_counted_after_the_read_marker_and_not_ours() {
let mut tab = Tab::<()>::new(ChatTarget::Server, "Server".into());
tab.messages = vec![msg(1, 1, 100, false), msg(2, 2, 200, true), msg(3, 3, 300, false)];
tab.count_unread(is_own);
assert_eq!(tab.unread, 2);
tab.read = Some((100, 1));
tab.count_unread(is_own);
assert_eq!(tab.unread, 1);
assert_eq!(tab.newest(), Some((300, 3)));
}
#[test]
fn entering_a_tab_puts_the_divider_above_the_first_new_message() {
let mut tab = Tab::<()>::new(ChatTarget::Server, "Server".into());
tab.messages = vec![msg(1, 1, 100, false), msg(2, 2, 200, false), msg(3, 3, 300, false)];
tab.read = Some((100, 1));
tab.count_unread(is_own);
tab.enter(is_own);
assert_eq!(tab.divider, Some(2));
assert_eq!((tab.unread, tab.read), (0, Some((300, 3))));
// A divider that shows stays when the tab is entered again.
tab.unread = 1;
tab.enter(is_own);
assert_eq!(tab.divider, Some(2));
}
#[test]
fn a_new_tab_starts_from_where_the_store_says_the_chat_was_read() {
let mut view = SessionView::<()>::default();
view.reads.insert(store_target(&ChatTarget::Channel(5)).key(), (700, 9));
let tab = view.new_tab(ChatTarget::Channel(5), "five".into());
assert_eq!((tab.read, tab.stored_read), (Some((700, 9)), Some((700, 9))));
let other = view.new_tab(ChatTarget::Channel(6), "six".into());
assert_eq!((other.read, other.stored_read), (None, None));
}
#[test]
fn handles_are_taken_one_by_one_and_found_in_topics_too() {
let mut tab = Tab::<()>::new(ChatTarget::Server, "Server".into());
let (a, b) = (tab.take_key(), tab.take_key());
assert_ne!(a, b);
tab.topic_messages.push(msg(a, 4, 400, false));
assert_eq!(tab.message(a).map(|m| m.id), Some(4));
assert!(tab.message(b).is_none());
}
#[test]
fn unread_counts_split_between_the_strip_and_private_chats() {
let mut view = session(&[ChatTarget::Channel(1), ChatTarget::Private("uid".into())]);
view.tabs[0].unread = 2;
view.tabs[1].unread = 3;
view.tabs[2].unread = 4;
assert_eq!((view.channel_unread(), view.private_unread()), (5, 4));
}
}
+70
View File
@@ -0,0 +1,70 @@
//! Streams on the voice view, the phone's Activity tab and Home: what is
//! shared, and who shares it.
use std::path::PathBuf;
use voelin_core::stream::StreamKind;
use crate::avatar;
use crate::bridge::StreamItem;
/// "Screen", "Window", "Camera"; "" for a kind we do not know.
pub fn kind_label(kind: &StreamKind) -> &'static str {
match kind {
StreamKind::Screen => "Screen",
StreamKind::Window => "Window",
StreamKind::Camera => "Camera",
StreamKind::Other(_) => "",
}
}
/// A gateway directory's kind as a label: "screen" → "Screen".
pub fn directory_kind_label(kind: &str) -> String {
let mut chars = kind.chars();
chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default()
}
/// A stream with its streamer: the name, and the avatar as the members
/// show it (the picture from the engine's cache, else the initials on the
/// name's colour). The caller fills in the rest.
pub fn streamer(name: &str, picture: Option<&PathBuf>) -> StreamItem {
StreamItem {
streamer: name.into(),
initials: avatar::initials(name).into(),
tint: avatar::tint(name),
avatar: avatar::image(picture),
..StreamItem::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Size;
#[test]
fn kinds_have_labels() {
assert_eq!(kind_label(&StreamKind::Screen), "Screen");
assert_eq!(kind_label(&StreamKind::Window), "Window");
assert_eq!(kind_label(&StreamKind::Camera), "Camera");
assert_eq!(kind_label(&StreamKind::Other(9)), "");
assert_eq!(kind_label(&StreamKind::from_u8(2)), "Camera");
}
#[test]
fn directory_kinds_are_capitalised() {
assert_eq!(directory_kind_label("screen"), "Screen");
assert_eq!(directory_kind_label("Camera"), "Camera");
assert_eq!(directory_kind_label(""), "");
}
#[test]
fn streamers_look_as_in_the_members() {
let item = streamer("Nova Star", None);
assert_eq!(&*item.streamer, "Nova Star");
assert_eq!(&*item.initials, "NS");
assert_eq!(item.tint, avatar::tint("Nova Star"));
assert_eq!(item.avatar.size(), Size::default());
assert!(item.id.is_empty() && !item.own && !item.studio);
}
}
File diff suppressed because it is too large. Load diff
+742
View File
@@ -0,0 +1,742 @@
//! The Stream Studio's view models: scene, source, mixer and layer rows,
//! the header's numbers, the source dialog's form, where new sources go and
//! the overlay sources the stream settings' switches keep in the scenes.
//! Decisions of the studio (what it does when) are in [`logic`].
pub mod logic;
use std::time::Duration;
use voelin_core::settings::{AudioSourceKindSetting, AudioSourceSetting, LayerSetting};
use voelin_core::studio::SourceChange;
use voelin_core::studio::SourceStats;
use voelin_core::studio::scene::{
Align, Background, Colour, Crop, Fit, Scene, Scenes, Source, SourceKind, Transform,
};
use crate::studio_bridge::{StudioAudio, StudioLayer, StudioScene, StudioSource, StudioSourceForm};
/// The scenes; the live one marked, each with what it shows.
pub fn scenes(scenes: &Scenes) -> Vec<StudioScene> {
let live = scenes.active().map(|s| s.id);
scenes
.scenes
.iter()
.map(|scene| StudioScene {
id: scene.id as i32,
name: scene.name.clone().into(),
detail: summary(scene).into(),
live: Some(scene.id) == live,
kind: scene.sources.first().map_or("", |s| s.kind.label()).into(),
})
.collect()
}
/// "Screen + Camera": the names of the visible sources, back first (the
/// main picture, then what is over it).
fn summary(scene: &Scene) -> String {
let names: Vec<&str> = scene.sources.iter().filter(|s| s.visible).map(Source::label).collect();
if names.is_empty() { "Empty".into() } else { names.join(" + ") }
}
/// The kind of a background by name: keep, blur, image or colour.
pub fn background_name(background: &Background) -> &'static str {
match background {
Background::Keep => "keep",
Background::Blur { .. } => "blur",
Background::Image { .. } => "image",
Background::Colour { .. } => "colour",
}
}
/// The sources of `scene`, front first, with what the studio reports.
pub fn sources(scene: Option<&Scene>, stats: &[SourceStats]) -> Vec<StudioSource> {
let Some(scene) = scene else { return Vec::new() };
let last = scene.sources.len().saturating_sub(1);
scene
.sources
.iter()
.enumerate()
.rev()
.map(|(i, s)| {
let stat = stats.iter().find(|st| st.id == s.id);
let info = stat
.filter(|st| st.width > 0)
.map(|st| format!("{}×{} · {:.0} fps", st.width, st.height, st.fps))
.unwrap_or_default();
StudioSource {
id: s.id as i32,
name: s.label().into(),
kind: s.kind.label().into(),
visible: s.visible,
locked: s.locked,
background: background_name(&s.background).into(),
error: stat.and_then(|st| st.error.clone()).unwrap_or_default().into(),
info: info.into(),
front: i == last,
back: i == 0,
}
})
.collect()
}
/// Linear gain as dB (silence: -60).
pub fn gain_db(gain: f32) -> f32 {
if gain > 0.001 { 20.0 * gain.log10() } else { -60.0 }
}
/// dB as linear gain.
pub fn gain_linear(db: f32) -> f32 {
10f32.powf(db / 20.0)
}
/// Name, detail and icon kind of an audio source.
pub fn audio_label(kind: &AudioSourceKindSetting) -> (String, String, &'static str) {
match kind {
AudioSourceKindSetting::Microphone => ("Microphone".into(), String::new(), "microphone"),
AudioSourceKindSetting::Desktop => {
("Desktop Audio".into(), "without Voelin".into(), "desktop")
}
AudioSourceKindSetting::App { name: Some(name), .. } => {
("App Audio".into(), name.clone(), "app")
}
AudioSourceKindSetting::App { pid, .. } => {
("App Audio".into(), pid.map(|p| format!("process {p}")).unwrap_or_default(), "app")
}
AudioSourceKindSetting::Window => {
("Window Audio".into(), "the shared window".into(), "window-audio")
}
AudioSourceKindSetting::Synthetic { frequency } => {
("Test Tone".into(), format!("{frequency} Hz"), "tone")
}
}
}
/// What the mixer says about one source now.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AudioLive {
/// Peak in dBFS.
pub level: f32,
pub error: Option<String>,
}
/// The mixer rows: the stream's audio sources with their meters.
pub fn audio(sources: &[AudioSourceSetting], live: &[Option<AudioLive>]) -> Vec<StudioAudio> {
sources
.iter()
.enumerate()
.map(|(i, s)| {
let (name, detail, kind) = audio_label(&s.kind);
let live = live.get(i).cloned().flatten();
StudioAudio {
name: name.into(),
detail: detail.into(),
kind: kind.into(),
gain_db: gain_db(s.gain),
muted: s.muted,
level: live.as_ref().map_or(-100.0, |l| l.level),
error: live.and_then(|l| l.error).unwrap_or_default().into(),
}
})
.collect()
}
/// A number without trailing zeros ("0.5", "1").
fn short(value: f32) -> String {
let text = format!("{value:.3}");
text.trim_end_matches('0').trim_end_matches('.').to_owned()
}
/// The simulcast layers as rows (bitrates in kbit/s).
pub fn layers(layers: &[LayerSetting]) -> Vec<StudioLayer> {
layers
.iter()
.map(|l| StudioLayer {
size: l.size.map(|(w, h)| format!("{w}x{h}")).unwrap_or_default().into(),
scale: short(l.scale).into(),
fps: l.max_fps.map(|f| f.to_string()).unwrap_or_default().into(),
bitrate: (l.bitrate / 1000).to_string().into(),
min_bitrate: (l.min_bitrate / 1000).to_string().into(),
})
.collect()
}
/// A layer as typed into `old`: a size ("1280x720") or a scale ("0.5",
/// "0.5×", "50%"), a frame-rate cap (empty: none), kbit/s. Any numbers.
pub fn parse_layer(row: &StudioLayer, old: &LayerSetting) -> Result<LayerSetting, String> {
let mut layer = old.clone();
let size = row.size.trim();
let parts: Vec<&str> = size.split(['x', 'X', '×']).map(str::trim).collect();
match parts.as_slice() {
[w, h] if !w.is_empty() && !h.is_empty() => {
let (w, h) = (w.parse::<u32>(), h.parse::<u32>());
let (Ok(w), Ok(h)) = (w, h) else { return Err(format!("{size:?} is not a size")) };
layer.size = Some((w, h));
}
_ => {
let text = size.trim_end_matches(['x', 'X', '×', '%']).trim();
let mut scale: f32 = text.parse().map_err(|_| format!("{size:?} is not a size"))?;
if size.ends_with('%') {
scale /= 100.0;
}
layer.size = None;
layer.scale = scale;
}
}
let fps = row.fps.trim();
layer.max_fps =
if fps.is_empty() { None } else { Some(fps.parse().map_err(|_| "a frame rate")?) };
let kbps: u64 = row.bitrate.trim().parse().map_err(|_| "kbit/s as a number")?;
layer.bitrate = kbps * 1000;
Ok(layer)
}
/// A layer below the last one: half its size, a quarter of its bitrate.
pub fn next_layer(layers: &[LayerSetting], bitrate_kbps: u32) -> LayerSetting {
match layers.last() {
None => LayerSetting { bitrate: u64::from(bitrate_kbps) * 1000, ..LayerSetting::default() },
Some(last) => LayerSetting {
id: None,
scale: last.size.map_or(last.scale / 2.0, |_| 0.5),
size: last.size.map(|(w, h)| (w / 2, h / 2)),
bitrate: (last.bitrate / 4).max(100_000),
rid: None,
..last.clone()
},
}
}
/// 0: not live, 1 poor … 4 excellent; how the stream gets out. The worse
/// of the frame rate made (against the output's) and the bandwidth the
/// viewers have (their estimates against the bitrate sent).
pub fn quality(
live: bool,
wanted_fps: u32,
fps: f64,
bandwidth: Option<f64>,
) -> (i32, &'static str) {
if !live {
return (0, "Not live");
}
let rate = if wanted_fps == 0 { 1.0 } else { fps / f64::from(wanted_fps) };
let worst = rate.min(bandwidth.unwrap_or(1.0));
match worst {
w if w >= 0.9 => (4, "Excellent Connection"),
w if w >= 0.75 => (3, "Good Connection"),
w if w >= 0.5 => (2, "Fair Connection"),
_ => (1, "Poor Connection"),
}
}
/// 8250 → "8,250".
pub fn thousands(n: u64) -> String {
let digits = n.to_string();
let mut out = String::new();
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(c);
}
out
}
/// "1080p • 60 FPS • 8,250 kbps".
pub fn format_line(height: u32, fps: u32, kbps: u64) -> String {
format!("{height}p • {fps} FPS • {} kbps", thousands(kbps))
}
/// "00:12:34".
pub fn clock(d: Duration) -> String {
let s = d.as_secs();
format!("{:02}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)
}
/// "#rrggbb" or "#rrggbbaa" (the # optional).
pub fn parse_colour(text: &str) -> Option<Colour> {
let hex = text.trim().trim_start_matches('#');
if !matches!(hex.len(), 6 | 8) || !hex.is_ascii() {
return None;
}
let byte = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
let a = if hex.len() == 8 { byte(6)? } else { 255 };
Some(Colour::rgba(byte(0)?, byte(2)?, byte(4)?, a))
}
/// A colour as `#rrggbb`, or `#rrggbbaa` when it is not opaque.
pub fn colour_text(c: Colour) -> String {
if c.a == 255 {
format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b)
} else {
format!("#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a)
}
}
fn number(value: f32) -> String {
short(value)
}
/// The source dialog's form for `source`.
pub fn form(source: &Source) -> StudioSourceForm {
let t = &source.transform;
let mut form = StudioSourceForm {
id: source.id as i32,
name: source.name.clone().into(),
kind: source.kind.label().into(),
x: number(t.x).into(),
y: number(t.y).into(),
width: t.width.map(number).unwrap_or_default().into(),
height: t.height.map(number).unwrap_or_default().into(),
scale: number(t.scale).into(),
fit: match t.fit {
Fit::Contain => "contain",
Fit::Cover => "cover",
Fit::Stretch => "stretch",
}
.into(),
crop_left: source.crop.left.to_string().into(),
crop_top: source.crop.top.to_string().into(),
crop_right: source.crop.right.to_string().into(),
crop_bottom: source.crop.bottom.to_string().into(),
opacity: source.opacity * 100.0,
locked: source.locked,
visible: source.visible,
background: background_name(&source.background).into(),
blur: "4".into(),
background_colour: "#00b140".into(),
..StudioSourceForm::default()
};
match &source.background {
Background::Blur { strength } => form.blur = number(strength * 100.0).into(),
Background::Image { path } => form.background_path = path.display().to_string().into(),
Background::Colour { colour } => form.background_colour = colour_text(*colour).into(),
Background::Keep => {}
}
match &source.kind {
SourceKind::Text { text, size_px, colour, .. } => {
form.text = text.replace('\n', "\\n").into();
form.text_size = number(*size_px).into();
form.colour = colour_text(*colour).into();
}
SourceKind::Colour { colour, .. } => form.colour = colour_text(*colour).into(),
SourceKind::Image { path } => form.path = path.display().to_string().into(),
SourceKind::Camera { mirror, .. } => form.mirror = *mirror,
_ => {}
}
form
}
fn parse_f32(text: &str, what: &str) -> Result<f32, String> {
text.trim()
.parse::<f32>()
.ok()
.filter(|v| v.is_finite())
.ok_or_else(|| format!("{what}: a number"))
}
/// An optional size: empty is `None`.
fn parse_size(text: &str, what: &str) -> Result<Option<f32>, String> {
if text.trim().is_empty() {
return Ok(None);
}
let v = parse_f32(text, what)?;
if v > 0.0 { Ok(Some(v)) } else { Err(format!("{what}: above 0")) }
}
fn parse_crop(text: &str) -> Result<u32, String> {
if text.trim().is_empty() {
return Ok(0);
}
text.trim().parse().map_err(|_| "crop: whole pixels".to_owned())
}
fn transform(form: &StudioSourceForm) -> Result<Transform, String> {
let scale = if form.scale.trim().is_empty() { 1.0 } else { parse_f32(&form.scale, "scale")? };
if scale <= 0.0 {
return Err("scale: above 0".into());
}
Ok(Transform {
x: parse_f32(&form.x, "X").unwrap_or(0.0),
y: parse_f32(&form.y, "Y").unwrap_or(0.0),
width: parse_size(&form.width, "width")?,
height: parse_size(&form.height, "height")?,
scale,
fit: match form.fit.as_ref() {
"cover" => Fit::Cover,
"stretch" => Fit::Stretch,
_ => Fit::Contain,
},
})
}
fn background(form: &StudioSourceForm) -> Result<Background, String> {
Ok(match form.background.as_ref() {
"blur" => Background::Blur { strength: parse_f32(&form.blur, "blur")?.max(0.0) / 100.0 },
"image" if !form.background_path.trim().is_empty() => {
Background::Image { path: form.background_path.trim().into() }
}
"image" => return Err("background image: a file".into()),
"colour" => Background::Colour {
colour: parse_colour(&form.background_colour).ok_or("background colour: #rrggbb")?,
},
_ => Background::Keep,
})
}
/// What `form` changes in `old` (only what differs).
pub fn change(form: &StudioSourceForm, old: &Source) -> Result<SourceChange, String> {
let transform = transform(form)?;
let crop = Crop {
left: parse_crop(&form.crop_left)?,
top: parse_crop(&form.crop_top)?,
right: parse_crop(&form.crop_right)?,
bottom: parse_crop(&form.crop_bottom)?,
};
let kind = kind(form, Some(&old.kind))?;
let background = background(form)?;
let opacity = (form.opacity / 100.0).clamp(0.0, 1.0);
let differs = |a: bool| a.then_some(());
Ok(SourceChange {
name: differs(form.name.as_ref() != old.name).map(|_| form.name.to_string()),
kind: differs(kind != old.kind).map(|_| kind),
transform: differs(transform != old.transform).map(|_| transform),
crop: differs(crop != old.crop).map(|_| crop),
opacity: differs((opacity - old.opacity).abs() > f32::EPSILON).map(|_| opacity),
visible: differs(form.visible != old.visible).map(|_| form.visible),
locked: differs(form.locked != old.locked).map(|_| form.locked),
background: differs(background != old.background).map(|_| background),
})
}
/// The kind as the form says: text, colour and image from their fields, a
/// camera's mirroring, anything else as it was.
fn kind(form: &StudioSourceForm, old: Option<&SourceKind>) -> Result<SourceKind, String> {
Ok(match (form.kind.as_ref(), old) {
("text", old) => {
let (font, backdrop, align, padding) = match old {
Some(SourceKind::Text { font, backdrop, align, padding, .. }) => {
(font.clone(), *backdrop, *align, *padding)
}
_ => (None, Colour::CLEAR, Align::Left, 0),
};
let size_px = parse_f32(&form.text_size, "text size")?;
if size_px <= 0.0 {
return Err("text size: above 0".into());
}
SourceKind::Text {
text: form.text.replace("\\n", "\n"),
font,
size_px,
colour: parse_colour(&form.colour).ok_or("colour: #rrggbb")?,
backdrop,
align,
padding,
}
}
("colour", old) => SourceKind::Colour {
colour: parse_colour(&form.colour).ok_or("colour: #rrggbb")?,
size: match old {
Some(SourceKind::Colour { size, .. }) => *size,
_ => (1920, 1080),
},
},
("image", _) if form.path.trim().is_empty() => return Err("image: a file".into()),
("image", _) => SourceKind::Image { path: form.path.trim().into() },
(_, Some(SourceKind::Camera { device, size, fps, .. })) => SourceKind::Camera {
device: device.clone(),
size: *size,
fps: *fps,
mirror: form.mirror,
},
(_, Some(old)) => old.clone(),
(other, None) => return Err(format!("cannot add a {other} source here")),
})
}
/// A new text, colour or image source from the dialog (id 0: the
/// controller gives it one).
pub fn new_source(form: &StudioSourceForm, output: (u32, u32)) -> Result<Source, String> {
let kind = kind(form, None)?;
let mut source = Source::new(0, kind);
source.name = form.name.trim().to_owned();
source.transform = if &*form.kind == "colour" {
Transform::full(output.0, output.1)
} else {
let mut t = placement(&source.kind, output);
if let Ok(x) = parse_f32(&form.x, "X") {
t.x = x;
}
if let Ok(y) = parse_f32(&form.y, "Y") {
t.y = y;
}
t
};
source.opacity = (form.opacity / 100.0).clamp(0.0, 1.0);
Ok(source)
}
/// Where a new source goes in a `w` x `h` picture: captures fill it
/// (cropping what does not fit), a camera sits in the bottom right corner,
/// text at the bottom left, images at their own size in the top left.
pub fn placement(kind: &SourceKind, (w, h): (u32, u32)) -> Transform {
let (w, h) = (w as f32, h as f32);
match kind {
SourceKind::Camera { .. } => {
let width = (w * 0.25).round();
let height = (width * 9.0 / 16.0).round();
let margin = (h * 0.03).round();
Transform {
fit: Fit::Cover,
..Transform::box_at(w - width - margin, h - height - margin, width, height)
}
}
SourceKind::Text { .. } => {
Transform { x: (w * 0.03).round(), y: (h * 0.8).round(), ..Transform::default() }
}
SourceKind::Image { .. } => Transform::default(),
_ => Transform { fit: Fit::Cover, ..Transform::box_at(0.0, 0.0, w, h) },
}
}
/// A source the stream settings' switches keep: its name, and its text
/// (`None`: switched off, so it is removed).
#[derive(Clone, Debug, PartialEq)]
pub struct Overlay {
pub name: &'static str,
pub text: Option<String>,
}
/// The overlay source that shows how many are watching.
pub const OVERLAY_VIEWERS: &str = "Viewer count";
/// The overlay source that shows the stream chat's last lines.
pub const OVERLAY_CHAT: &str = "Chat overlay";
/// The overlay source that names what plays.
pub const OVERLAY_NOW_PLAYING: &str = "Now playing";
fn overlay_kind(name: &str, text: &str) -> SourceKind {
SourceKind::Text {
text: text.to_owned(),
font: None,
size_px: if name == OVERLAY_CHAT { 26.0 } else { 34.0 },
colour: Colour::WHITE,
backdrop: Colour::rgba(6, 10, 24, 170),
align: Align::Left,
padding: 14,
}
}
/// Where an overlay starts (people can move it): the viewer count at the
/// top right (by an estimate of its width), the chat at the left, what is
/// on above the bottom left. Clear of the corners the studio's own badges
/// cover in the preview.
fn overlay_place(name: &str, text: &str, (w, h): (u32, u32)) -> Transform {
let (w, h) = (w as f32, h as f32);
let margin = (w * 0.025).round();
let (x, y) = match name {
OVERLAY_VIEWERS => {
let wide = text.chars().count() as f32 * 34.0 * 0.58 + 28.0;
(w - margin - wide, h * 0.14)
}
OVERLAY_CHAT => (margin, h * 0.3),
_ => (margin, h * 0.7),
};
Transform { x: x.max(0.0).round(), y: y.round(), ..Transform::default() }
}
/// Make the scenes hold `wanted`: an overlay that is on is added to the live
/// scene if it has none, and its text follows in every scene; one that is
/// off is removed everywhere. Overlays are found by their names, so a
/// person can move them like any source. Returns whether anything changed.
pub fn apply_overlays(scenes: &mut Scenes, wanted: &[Overlay]) -> bool {
let size = scenes.size();
let live = scenes.active().map(|s| s.id);
let mut changed = false;
for overlay in wanted {
match &overlay.text {
None => {
for scene in &mut scenes.scenes {
let before = scene.sources.len();
scene.sources.retain(|s| s.name != overlay.name);
changed |= scene.sources.len() != before;
}
}
Some(text) => {
for scene in &mut scenes.scenes {
for source in scene.sources.iter_mut().filter(|s| s.name == overlay.name) {
if let SourceKind::Text { text: shown, .. } = &mut source.kind
&& shown != text
{
shown.clone_from(text);
changed = true;
}
}
}
let Some(scene) = live.and_then(|id| scenes.scene_mut(id)) else { continue };
if !scene.sources.iter().any(|s| s.name == overlay.name) {
let id = scene.next_source_id();
scene.sources.push(Source {
name: overlay.name.into(),
transform: overlay_place(overlay.name, text, size),
..Source::new(id, overlay_kind(overlay.name, text))
});
changed = true;
}
}
}
}
changed
}
#[cfg(test)]
mod tests {
use super::*;
fn scene_with(names: &[&str]) -> Scenes {
let mut scene = Scene::new(1, "Main");
for (i, name) in names.iter().enumerate() {
let kind = SourceKind::Colour { colour: Colour::BLACK, size: (16, 16) };
scene.sources.push(Source { name: (*name).into(), ..Source::new(i as u64 + 1, kind) });
}
Scenes { scenes: vec![scene, Scene::new(2, "Break")], active: 1, ..Scenes::default() }
}
#[test]
fn rows_show_scenes_and_sources_front_first() {
let scenes = scene_with(&["Screen", "Camera"]);
let rows = super::scenes(&scenes);
assert_eq!(rows.len(), 2);
assert!(rows[0].live && !rows[1].live);
assert_eq!(&*rows[0].detail, "Screen + Camera");
assert_eq!(&*rows[1].detail, "Empty");
let sources = super::sources(scenes.active(), &[]);
assert_eq!(
sources.iter().map(|s| s.name.as_ref()).collect::<Vec<_>>(),
["Camera", "Screen"]
);
assert!(sources[0].front && !sources[0].back && sources[1].back);
}
#[test]
fn numbers_for_the_header() {
assert_eq!(thousands(8250), "8,250");
assert_eq!(thousands(1_234_567), "1,234,567");
assert_eq!(thousands(999), "999");
assert_eq!(format_line(1080, 60, 8250), "1080p • 60 FPS • 8,250 kbps");
assert_eq!(clock(Duration::from_secs(12 * 60 + 34)), "00:12:34");
assert_eq!(clock(Duration::from_secs(3 * 3600 + 5)), "03:00:05");
assert_eq!(quality(false, 60, 60.0, None).0, 0);
assert_eq!(quality(true, 60, 59.0, None).0, 4);
assert_eq!(quality(true, 60, 59.0, Some(0.6)).0, 2);
assert_eq!(quality(true, 60, 20.0, Some(1.0)).0, 1);
}
#[test]
fn gains_and_colours_round_trip() {
assert!((gain_db(1.0)).abs() < 1e-6);
assert!((gain_db(gain_linear(-6.0)) + 6.0).abs() < 1e-4);
assert_eq!(gain_db(0.0), -60.0);
let c = parse_colour("#ff8000").unwrap();
assert_eq!(c, Colour::rgb(255, 128, 0));
assert_eq!(colour_text(c), "#ff8000");
assert_eq!(parse_colour("10203040"), Some(Colour::rgba(16, 32, 48, 64)));
assert_eq!(parse_colour("#ff80"), None);
assert_eq!(parse_colour("#gg0000"), None);
}
#[test]
fn layers_as_typed() {
let old = LayerSetting::default();
let row = |size: &str, fps: &str, kbps: &str| StudioLayer {
size: size.into(),
fps: fps.into(),
bitrate: kbps.into(),
..StudioLayer::default()
};
let l = parse_layer(&row("1280x720", "30", "2500"), &old).unwrap();
assert_eq!((l.size, l.max_fps, l.bitrate), (Some((1280, 720)), Some(30), 2_500_000));
let l = parse_layer(&row("0.5×", "", "800"), &old).unwrap();
assert_eq!((l.size, l.scale, l.max_fps), (None, 0.5, None));
assert_eq!(parse_layer(&row("50%", "", "800"), &old).unwrap().scale, 0.5);
assert!(parse_layer(&row("big", "", "800"), &old).is_err());
assert!(parse_layer(&row("1", "", "fast"), &old).is_err());
let rows = layers(&[l]);
assert_eq!((rows[0].scale.as_ref(), rows[0].bitrate.as_ref()), ("0.5", "800"));
let below = next_layer(&[LayerSetting { bitrate: 8_000_000, ..old.clone() }], 8000);
assert_eq!((below.scale, below.bitrate), (0.5, 2_000_000));
}
#[test]
fn the_source_form_changes_only_what_differs() {
let mut source = Source::new(
3,
SourceKind::Text {
text: "Hello\nthere".into(),
font: None,
size_px: 48.0,
colour: Colour::WHITE,
backdrop: Colour::CLEAR,
align: Align::Center,
padding: 4,
},
);
source.transform = Transform::box_at(10.0, 20.0, 300.0, 100.0);
let mut f = form(&source);
assert_eq!(&*f.text, "Hello\\nthere");
assert_eq!((f.x.as_ref(), f.width.as_ref()), ("10", "300"));
assert_eq!(change(&f, &source).unwrap(), SourceChange::default());
f.x = "40".into();
f.opacity = 50.0;
f.text = "Bye".into();
let c = change(&f, &source).unwrap();
assert_eq!(c.transform.unwrap().x, 40.0);
assert_eq!(c.opacity, Some(0.5));
let Some(SourceKind::Text { text, align, padding, .. }) = c.kind else { panic!() };
assert_eq!((text.as_str(), align, padding), ("Bye", Align::Center, 4));
f.width = "-1".into();
assert!(change(&f, &source).is_err());
}
#[test]
fn new_sources_are_placed_by_kind() {
let camera =
SourceKind::Camera { device: String::new(), size: None, fps: None, mirror: false };
let t = placement(&camera, (1920, 1080));
assert_eq!((t.width, t.height, t.fit), (Some(480.0), Some(270.0), Fit::Cover));
assert!(t.x + 480.0 < 1920.0 && t.y + 270.0 < 1080.0);
let screen = SourceKind::Screen { monitor: 0, backend: None, cursor: true };
assert_eq!(placement(&screen, (1920, 1080)).width, Some(1920.0));
let form = StudioSourceForm {
kind: "colour".into(),
name: "Slate".into(),
colour: "#101a3c".into(),
opacity: 100.0,
..Default::default()
};
let s = new_source(&form, (1280, 720)).unwrap();
assert_eq!((s.name.as_str(), s.transform.width), ("Slate", Some(1280.0)));
assert!(new_source(&StudioSourceForm { kind: "image".into(), ..form }, (1, 1)).is_err());
}
#[test]
fn overlays_follow_the_switches() {
let mut scenes = scene_with(&["Screen"]);
let on = |text: &str| Overlay { name: OVERLAY_VIEWERS, text: Some(text.into()) };
assert!(apply_overlays(&mut scenes, &[on("3 watching")]));
let live = &scenes.scenes[0];
assert_eq!(live.sources.len(), 2);
assert_eq!(live.sources[1].name, OVERLAY_VIEWERS);
// Nothing to do the second time; the text follows.
assert!(!apply_overlays(&mut scenes, &[on("3 watching")]));
assert!(apply_overlays(&mut scenes, &[on("4 watching")]));
let SourceKind::Text { text, .. } = &scenes.scenes[0].sources[1].kind else { panic!() };
assert_eq!(text, "4 watching");
// A scene switch adds it to the new live scene too; off removes all.
scenes.active = 2;
assert!(apply_overlays(&mut scenes, &[on("4 watching")]));
assert_eq!(scenes.scenes[1].sources.len(), 1);
assert!(apply_overlays(&mut scenes, &[Overlay { name: OVERLAY_VIEWERS, text: None }]));
assert_eq!(scenes.scenes[0].sources.len(), 1);
assert!(scenes.scenes[1].sources.is_empty());
assert!(scenes.check().is_ok());
}
}
+195
View File
@@ -0,0 +1,195 @@
//! The Stream Studio's structs: the plain counterparts of
//! `crates/voelin-ui/ui/studio-bridge.slint`, as [`crate::bridge`] has those of
//! `bridge.slint`.
use std::sync::Arc;
use crate::image::ImageRef;
/// A scene of the studio.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioScene {
pub id: i32,
pub name: Arc<str>,
/// Its sources, front first: "Screen + Camera + Text".
pub detail: Arc<str>,
/// Composited now (the live scene).
pub live: bool,
/// The kind of its front-most source (for the icon).
pub kind: Arc<str>,
}
/// A source of the live scene, front first.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioSource {
pub id: i32,
pub name: Arc<str>,
/// screen, window, portal, camera, image, text, colour, pattern
pub kind: Arc<str>,
pub visible: bool,
pub locked: bool,
/// keep, blur, image, colour
pub background: Arc<str>,
/// Why it shows nothing ("" while it works).
pub error: Arc<str>,
/// "1920×1080 · 60 fps"
pub info: Arc<str>,
/// At the front or the back (cannot move further).
pub front: bool,
pub back: bool,
}
/// An audio source of the stream (`stream.audio_sources`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioAudio {
pub name: Arc<str>,
/// "Elgato Wave:3", the application...
pub detail: Arc<str>,
/// microphone, desktop, app, window, tone
pub kind: Arc<str>,
pub gain_db: f32,
pub muted: bool,
/// The meter in dBFS, after the gain.
pub level: f32,
/// Why it captures nothing.
pub error: Arc<str>,
}
/// A simulcast layer (`stream.layers`) as typed: any numbers.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioLayer {
/// "1280x720"; empty: `scale` of the output.
pub size: Arc<str>,
pub scale: Arc<str>,
/// Frame-rate cap; empty: the output's.
pub fps: Arc<str>,
/// kbit/s.
pub bitrate: Arc<str>,
/// kbit/s a viewer needs for this layer.
pub min_bitrate: Arc<str>,
}
/// A viewer of the studio's stream.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioViewer {
pub client: i32,
pub name: Arc<str>,
/// requested, connecting, connected
pub state: Arc<str>,
}
/// An entry of a picker (screens, windows, cameras, audio sources).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioPick {
pub name: Arc<str>,
pub detail: Arc<str>,
/// For the icon: monitor, window, portal, camera, microphone, desktop, app, tone
pub kind: Arc<str>,
/// The application's own icon (audio), if it has one.
pub icon: ImageRef,
/// Already mixed in (audio): picking it again takes it out.
pub selected: bool,
}
/// The header, the preview's badges and the bottom bar.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioStatus {
/// The engine runs (preview, mixer, replay buffer).
pub running: bool,
/// "Chill Zone • Starfall Community"; empty without a destination.
pub destination: Arc<str>,
/// 0: not live, 1: poor, 2: fair, 3: good, 4: excellent.
pub quality: i32,
pub quality_text: Arc<str>,
/// "1080p • 60 FPS • 8,250 kbps"
pub format: Arc<str>,
/// The numbers behind it, for the info button.
pub details: Arc<str>,
pub live: bool,
/// Going live: waiting for the server.
pub starting: bool,
/// "00:12:34"
pub elapsed: Arc<str>,
pub viewers: i32,
pub participants: i32,
pub can_go_live: bool,
/// Why Go Live is off, or what goes wrong.
pub hint: Arc<str>,
pub recording: bool,
pub recorded: Arc<str>,
/// The replay buffer's window (0: off) and what it holds now.
pub replay_seconds: i32,
pub replay_held: Arc<str>,
pub output_width: i32,
pub output_height: i32,
pub fps: i32,
pub detached: bool,
/// A window of its own is possible (not on Android).
pub can_detach: bool,
/// The live scene shows a screen, a camera, a window (the phone's cards).
pub screen_shown: bool,
pub camera_shown: bool,
pub window_shown: bool,
}
/// The stream settings panel (`studio.stream`, `stream.bitrate_kbps`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioForm {
pub destination: i32,
pub title: Arc<str>,
pub game: Arc<str>,
pub message: Arc<str>,
pub show_viewers: bool,
pub show_chat: bool,
pub show_now_playing: bool,
pub audio: bool,
/// kbit/s of the stream without layers, as typed.
pub bitrate: Arc<str>,
}
/// The source properties dialog (also for adding text, colour and image
/// sources: `id` -1). Numbers as typed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioSourceForm {
pub id: i32,
pub name: Arc<str>,
pub kind: Arc<str>,
pub x: Arc<str>,
pub y: Arc<str>,
/// Empty: the source's own size times `scale`.
pub width: Arc<str>,
pub height: Arc<str>,
pub scale: Arc<str>,
/// contain, cover, stretch
pub fit: Arc<str>,
pub crop_left: Arc<str>,
pub crop_top: Arc<str>,
pub crop_right: Arc<str>,
pub crop_bottom: Arc<str>,
/// Percent.
pub opacity: f32,
pub locked: bool,
pub visible: bool,
/// keep, blur, image, colour
pub background: Arc<str>,
/// Blur radius in percent of the picture's height.
pub blur: Arc<str>,
pub background_path: Arc<str>,
pub background_colour: Arc<str>,
/// Text, colour ("#rrggbb" or "#rrggbbaa") and image sources.
pub text: Arc<str>,
pub text_size: Arc<str>,
pub colour: Arc<str>,
pub path: Arc<str>,
pub mirror: bool,
}
/// The studio settings dialog (`studio.*` keys and the preview).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StudioSettingsForm {
pub replay_seconds: Arc<str>,
pub replay_memory: Arc<str>,
pub recording_dir: Arc<str>,
pub preview_width: Arc<str>,
pub preview_fps: Arc<str>,
}
+908
View File
@@ -0,0 +1,908 @@
//! The channel tree, the members of our channel and everyone on the
//! server for the members panel.
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
pub use voelin_model::channel_title;
use voelin_model::{
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, Presence, Spacer, TreeRow, badges,
tree_rows,
};
use crate::avatar;
use crate::bridge::{BadgeItem, MemberItem, TreeItem};
use crate::image::ImageRef;
use crate::settings::ClientPlaybackMap;
/// 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<String, PathBuf>, url: Option<&str>) -> ImageRef {
avatar::image(url.and_then(|u| pictures.get(u)))
}
/// A badge's picture, if the engine fetched it.
fn badge_icon(pictures: &HashMap<String, PathBuf>, guid: &str) -> ImageRef {
avatar::image(badges::icon_url(guid).and_then(|url| pictures.get(&url)))
}
/// A client's badges for the member card: the first three in its order.
/// One the app does not know is "Badge", with its GUID as description.
pub fn badge_items(guids: &[String], pictures: &HashMap<String, PathBuf>) -> Vec<BadgeItem> {
guids
.iter()
.take(badges::SHOWN)
.map(|guid| {
let (name, description) = match badges::info(guid) {
Some(info) => (info.name.as_str(), info.description.as_str()),
None => ("Badge", guid.as_str()),
};
BadgeItem {
name: name.into(),
description: description.into(),
icon: badge_icon(pictures, guid),
}
})
.collect()
}
/// What the tree shows besides the presence.
pub struct TreeInput<'a> {
pub presence: &'a Presence,
pub collapsed: &'a HashSet<ChannelId>,
pub talking: &'a HashSet<u16>,
pub playback: &'a ClientPlaybackMap,
pub own_channel: Option<ChannelId>,
pub own_client: Option<u16>,
/// Search text: only matching channels and clients (and the channels
/// above them) are shown. Empty: everything.
pub filter: &'a str,
/// Avatar pictures in the engine's cache, by unique id.
pub avatars: &'a HashMap<String, PathBuf>,
/// Icons in the engine's cache, by icon id (channel, group and client
/// icons).
pub icons: &'a HashMap<u32, PathBuf>,
/// Banners and badges in the engine's cache, by address.
pub pictures: &'a HashMap<String, PathBuf>,
/// 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<'_> {
fn avatar(&self, client: &ClientInfo) -> ImageRef {
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<ImageRef> {
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<ImageRef> {
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 pictures of the badges a client shows that arrived, in its
/// order; empty slots last.
fn badges(&self, client: &ClientInfo) -> [ImageRef; badges::SHOWN] {
let mut icons = client
.badges
.iter()
.take(badges::SHOWN)
.map(|guid| badge_icon(self.pictures, guid))
.filter(|i| i.size().width > 0);
std::array::from_fn(|_| icons.next().unwrap_or_default())
}
/// The group a client is sorted under: the first of its server groups
/// in display order.
fn group_of(&self, client: &ClientInfo) -> Option<&GroupInfo> {
self.groups.iter().find(|g| client.server_groups.contains(&g.id))
}
}
/// "Speaking", "Away: brb", "Muted", …
pub fn status_of(client: &ClientInfo, talking: bool) -> String {
if talking {
"Speaking".to_owned()
} else if client.streaming == Some(true) {
"Streaming".to_owned()
} else if let Some(message) = &client.away {
if message.is_empty() { "Away".to_owned() } else { format!("Away: {message}") }
} else if client.output_muted {
"Sound off".to_owned()
} else if client.input_muted {
"Muted".to_owned()
} else {
"Listening".to_owned()
}
}
fn talking(input: &TreeInput, client: &ClientInfo) -> bool {
input.talking.contains(&client.id) || client.talking == Some(true)
}
/// A spacer kind as the UI takes it (`TreeItem.spacer`, 0: no spacer).
fn spacer_index(kind: Spacer) -> i32 {
match kind {
Spacer::Left => 1,
Spacer::Center => 2,
Spacer::Right => 3,
Spacer::Fill => 4,
}
}
/// A channel's title for lists and pickers (the search, the event form);
/// none for a spacer that only separates.
pub fn listed_title(channel: &ChannelInfo) -> Option<&str> {
match channel_title(channel) {
(text, Some(kind)) if kind.separates(text) => None,
(text, _) => Some(text),
}
}
/// Channels deeper than this are not followed up (a broken presence could
/// loop).
const PATH_DEPTH: usize = 64;
/// The path of a channel, its names from the top as the server has them
/// (what an invite link names, what connecting into it takes); empty for a
/// channel the presence does not know.
pub fn channel_path(presence: &Presence, channel: ChannelId) -> Vec<String> {
let mut names = Vec::new();
let mut next = presence.channels.get(&channel);
while let Some(c) = next.filter(|_| names.len() < PATH_DEPTH) {
names.push(c.name.clone());
next = presence.channels.get(&c.parent).filter(|_| c.parent != 0);
}
names.reverse();
names
}
/// About as many characters as a fill spacer's row holds: more than the
/// widest tree shows.
const FILL_CHARS: usize = 200;
/// A spacer's text as its row shows it: a fill pattern repeated across the
/// row, a blank text empty.
fn spacer_text(kind: Spacer, text: &str) -> String {
match kind {
Spacer::Fill => match text.chars().count() {
0 => String::new(),
n => text.repeat((FILL_CHARS / n).max(1)),
},
_ if text.trim().is_empty() => String::new(),
_ => text.to_owned(),
}
}
/// The rows of the tree, channels with their clients below.
pub fn rows(input: &TreeInput) -> Vec<TreeItem> {
let p = input.presence;
let rows: Vec<TreeItem> = tree_rows(p, &|cid| input.collapsed.contains(&cid))
.into_iter()
.map(|row| match row {
TreeRow::Channel { depth, channel } => {
let (name, spacer) = match channel_title(channel) {
(text, Some(kind)) => (spacer_text(kind, text), spacer_index(kind)),
(name, None) => (name.to_owned(), 0),
};
TreeItem {
spacer,
is_channel: true,
depth: depth as i32,
id: channel.id as i32,
name: name.into(),
own: input.own_channel == Some(channel.id),
locked: channel.has_password,
collapsed: input.collapsed.contains(&channel.id),
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 } => {
let playback = client
.uid
.as_ref()
.and_then(|uid| input.playback.get(uid))
.copied()
.unwrap_or_default();
let mut icons = input.client_icons(client).into_iter();
let [badge, badge_2, badge_3] = input.badges(client);
TreeItem {
is_channel: false,
depth: depth as i32,
id: client.id as i32,
name: client.nickname.clone().into(),
talking: talking(input, client),
muted: client.input_muted,
sound_off: client.output_muted,
away: client.away.is_some(),
streaming: client.streaming == Some(true),
local_muted: playback.muted,
local_volume: (playback.volume * 100.0).round() as i32,
myself: input.own_client == Some(client.id),
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(),
badge,
badge_2,
badge_3,
..Default::default()
}
}
})
.collect();
filter(rows, input.filter)
}
/// A spacer row that only separates: a line, or no text.
fn separator(row: &TreeItem) -> bool {
row.is_channel
&& (row.spacer == spacer_index(Spacer::Fill) || (row.spacer != 0 && row.name.is_empty()))
}
/// Rows that match `query`, and the channels above them. A separator
/// never matches (`---` is no channel to look for), but stays above what
/// does.
fn filter(rows: Vec<TreeItem>, query: &str) -> Vec<TreeItem> {
let query = query.trim().to_lowercase();
if query.is_empty() {
return rows;
}
let matches: Vec<bool> = rows
.iter()
.map(|r| !separator(r) && r.name.to_lowercase().contains(query.as_str()))
.collect();
let mut keep = matches.clone();
// A channel stays if anything below it matches.
for i in 0..rows.len() {
if !rows[i].is_channel || keep[i] {
continue;
}
let depth = rows[i].depth;
keep[i] = rows[i + 1..]
.iter()
.zip(&matches[i + 1..])
.take_while(|(r, _)| r.depth > depth)
.any(|(_, m)| *m);
}
rows.into_iter().zip(keep).filter_map(|(r, k)| k.then_some(r)).collect()
}
/// "12 online · 8 channels"
pub fn stats(p: &Presence) -> String {
let online = p.clients.values().filter(|c| !c.is_query).count();
let channels = p.channels.len();
format!("{online} online · {channels} {}", if channels == 1 { "channel" } else { "channels" })
}
/// Names of server groups whose members wear the crown (the server's
/// admins). TeamSpeak has no flag for it, so the usual names are matched.
fn is_admin_group(name: &str) -> bool {
let lower = name.to_lowercase();
["admin", "owner", "operator", "leiter"].iter().any(|w| lower.contains(w))
}
/// Moderator groups, shown as a role next to the name.
fn is_moderator_group(name: &str) -> bool {
name.to_lowercase().contains("mod")
}
/// Whether a client cannot speak in its channel: the channel needs more
/// talk power than it has, and it was not made a talker.
pub fn cannot_talk(channel: Option<&ChannelInfo>, client: &ClientInfo) -> bool {
channel.is_some_and(|c| {
c.needed_talk_power > 0 && client.talk_power < c.needed_talk_power && !client.talker
})
}
impl TreeInput<'_> {
/// The position of a client's group in display order (no group last).
fn group_rank(&self, client: &ClientInfo) -> usize {
self.groups.iter().position(|g| client.server_groups.contains(&g.id)).unwrap_or(usize::MAX)
}
/// One row of the members panel or the voice channel, under `section`.
fn member(&self, c: &ClientInfo, section: &Section) -> MemberItem {
let talking = talking(self, c);
let group = self.group_of(c).map_or("", |g| g.name.as_str());
let admin = is_admin_group(group);
// Someone elsewhere on the server: where they are says more than
// "Listening".
let elsewhere = self.own_channel != Some(c.channel)
&& !talking
&& c.streaming != Some(true)
&& c.away.is_none();
let channel = self.presence.channels.get(&c.channel);
let status = match channel {
Some(channel) if elsewhere => format!("In {}", channel_title(channel).0),
_ => status_of(c, talking),
};
let [badge, badge_2, badge_3] = self.badges(c);
MemberItem {
id: c.id as i32,
name: c.nickname.clone().into(),
initials: avatar::initials(&c.nickname).into(),
tint: avatar::tint(&c.nickname),
avatar: self.avatar(c),
talking,
muted: c.input_muted,
sound_off: c.output_muted,
away: c.away.is_some(),
streaming: c.streaming == Some(true),
myself: self.own_client == Some(c.id),
status: status.into(),
away_message: c.away.clone().unwrap_or_default().into(),
group: section.title.clone().into(),
group_icon: section.icon.clone(),
first_in_group: false,
group_count: 0,
admin,
role: if !admin && is_moderator_group(group) { group.into() } else { "".into() },
priority: c.priority_speaker,
commander: c.channel_commander,
recording: c.recording,
cannot_talk: cannot_talk(channel, c),
badge,
badge_2,
badge_3,
}
}
}
/// A heading of the members panel.
#[derive(Clone, Default)]
struct Section {
title: String,
icon: ImageRef,
}
/// Rows in sections: each section's first row carries the heading and how
/// many rows follow.
fn sectioned(
input: &TreeInput,
mut clients: Vec<(Section, usize, &ClientInfo)>,
) -> Vec<MemberItem> {
clients.sort_by_key(|(_, rank, c)| (*rank, c.nickname.to_lowercase(), c.id));
let mut rows: Vec<MemberItem> = clients.iter().map(|(s, _, c)| input.member(c, s)).collect();
let mut start = 0;
while start < rows.len() {
let rank = clients[start].1;
let count = clients[start..].iter().take_while(|(_, r, _)| *r == rank).count();
rows[start].first_in_group = true;
rows[start].group_count = count as i32;
start += count;
}
rows
}
/// The section of a client's server group.
fn group_section(input: &TreeInput, client: &ClientInfo) -> (Section, usize) {
match input.group_of(client) {
Some(g) => (
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),
}
}
/// The clients in our channel, grouped by server group (in the server's
/// display order) and by name inside a group.
pub fn members(input: &TreeInput) -> Vec<MemberItem> {
let Some(channel) = input.own_channel else { return Vec::new() };
let clients = input
.presence
.members(channel)
.map(|c| {
let (section, rank) = group_section(input, c);
(section, rank, c)
})
.collect();
sectioned(input, clients)
}
/// The rows whose name contains `filter` (lower case), in sections
/// counted again.
pub fn matching(rows: Vec<MemberItem>, filter: &str) -> Vec<MemberItem> {
let mut rows: Vec<MemberItem> =
rows.into_iter().filter(|m| m.name.to_lowercase().contains(filter)).collect();
let mut start = 0;
while start < rows.len() {
let group = rows[start].group.clone();
let count = rows[start..].iter().take_while(|m| m.group == group).count();
for (i, row) in rows[start..start + count].iter_mut().enumerate() {
row.first_in_group = i == 0;
row.group_count = if i == 0 { count as i32 } else { 0 };
}
start += count;
}
rows
}
/// Everyone on the server for the members panel: first the people in our
/// voice channel (`voice_first`, in the voice channel and stream views) or
/// those streaming, then each server group in the server's order.
pub fn server_members(input: &TreeInput, voice_first: bool) -> Vec<MemberItem> {
let first = Section {
title: if voice_first { "In Voice" } else { "Streaming" }.into(),
icon: ImageRef::default(),
};
let clients = input
.presence
.clients
.values()
.filter(|c| !c.is_query)
.map(|c| {
let lead = if voice_first {
input.own_channel == Some(c.channel)
} else {
c.streaming == Some(true)
};
if lead {
(first.clone(), 0, c)
} else {
let (section, rank) = group_section(input, c);
(section, rank, c)
}
})
.collect();
sectioned(input, clients)
}
#[cfg(test)]
mod tests {
use voelin_model::ChannelInfo;
use super::*;
fn presence() -> Presence {
let channel = |id, parent, order, name: &str| ChannelInfo {
id,
parent,
order,
name: name.into(),
max_clients: if id == 2 { Some(5) } else { None },
..Default::default()
};
let client = |id, channel, name: &str| ClientInfo {
id,
channel,
nickname: name.into(),
..Default::default()
};
let mut p = Presence::default();
for c in [channel(1, 0, 0, "Lobby"), channel(2, 0, 1, "Games"), channel(3, 2, 0, "Chess")] {
p.channels.insert(c.id, c);
}
for c in [client(10, 1, "Alice"), client(11, 2, "bob"), client(12, 3, "Carol")] {
p.clients.insert(c.id, c);
}
let mut query = client(13, 1, "serveradmin");
query.is_query = true;
p.clients.insert(13, query);
p
}
/// Empty caches and no groups, for the tests below.
#[derive(Default)]
struct Extras {
avatars: HashMap<String, PathBuf>,
icons: HashMap<u32, PathBuf>,
pictures: HashMap<String, PathBuf>,
groups: Vec<GroupInfo>,
channel_groups: Vec<GroupInfo>,
}
fn input<'a>(
p: &'a Presence,
talking: &'a HashSet<u16>,
collapsed: &'a HashSet<ChannelId>,
playback: &'a ClientPlaybackMap,
filter: &'a str,
extras: &'a Extras,
) -> TreeInput<'a> {
TreeInput {
presence: p,
collapsed,
talking,
playback,
own_channel: Some(2),
own_client: Some(11),
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: &ImageRef| 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();
}
/// A client's badges: the first three in its order, on the card by name
/// ("Badge" for one the app does not know), in the rows the pictures
/// that arrived.
#[test]
fn badges_on_the_card_and_in_rows() {
let dir = std::env::temp_dir().join(format!("voelin-tree-badges-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let guids: Vec<String> = [
"4b27be5a-b92a-4b30-8b2d-14b59653f427",
"00000000-0000-0000-0000-000000000000",
"05114019-6b46-4b13-b5a1-e5179ef69fb5",
"2bf80270-8efe-46dc-a472-3280a0479145",
]
.map(String::from)
.into();
let picture = |i: usize, width| {
(badges::icon_url(&guids[i]).unwrap(), picture_file(&dir, &format!("badge-{i}"), width))
};
let e = Extras {
pictures: HashMap::from([picture(0, 3), picture(2, 5), picture(3, 7)]),
..Default::default()
};
let width = |i: &ImageRef| i.size().width;
let card = badge_items(&guids, &e.pictures);
let names: Vec<_> = card.iter().map(|b| b.name.as_ref()).collect();
assert_eq!(names, ["20th Anniversary", "Badge", "April Fools!"]);
assert_eq!(card[1].description.as_ref(), guids[1]);
assert_eq!(card.iter().map(|b| width(&b.icon)).collect::<Vec<_>>(), [3, 0, 5]);
let mut p = presence();
p.clients.get_mut(&11).unwrap().badges = guids;
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let tree = input(&p, &t, &c, &pb, "", &e);
let bob = rows(&tree).into_iter().find(|r| !r.is_channel && r.id == 11).unwrap();
assert_eq!([&bob.badge, &bob.badge_2, &bob.badge_3].map(width), [3, 5, 0]);
let bob = members(&tree).into_iter().find(|m| m.id == 11).unwrap();
assert_eq!([&bob.badge, &bob.badge_2, &bob.badge_3].map(width), [3, 5, 0]);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn spacer_rows_keep_tree_identity() {
let mut p = presence();
p.channels.get_mut(&2).unwrap().name = "[cspacer12]Гамесы".into();
let more = |id, order, name: &str| ChannelInfo {
id,
order,
name: name.into(),
has_password: id == 5,
..Default::default()
};
for c in
[more(4, 2, "[*spacer1]-="), more(5, 4, "[rspacer2]Staff"), more(6, 5, "[spacer3]")]
{
p.channels.insert(c.id, c);
}
let (t, c, pb) = (HashSet::new(), HashSet::from([2]), ClientPlaybackMap::new());
let e = Extras::default();
let rows = rows(&input(&p, &t, &c, &pb, "", &e));
let channels: Vec<_> = rows
.iter()
.filter(|r| r.is_channel)
.map(|r| (r.id, r.spacer, r.name.chars().take(6).collect::<String>()))
.collect();
let row = |id, spacer, name: &str| (id, spacer, name.to_owned());
assert_eq!(
channels,
[
row(1, 0, "Lobby"),
row(2, 2, "Гамесы"),
row(4, 4, "-=-=-="),
row(5, 3, "Staff"),
row(6, 1, ""),
]
);
// A fill line repeats its pattern across the row.
let fill = &rows.iter().find(|r| r.id == 4 && r.is_channel).unwrap().name;
assert_eq!(fill.chars().count(), FILL_CHARS);
assert_eq!(spacer_text(Spacer::Fill, ""), "");
assert_eq!(spacer_text(Spacer::Fill, "x".repeat(300).as_str()).len(), 300);
let games = rows.iter().find(|r| r.id == 2 && r.is_channel).unwrap();
assert!(games.collapsed && games.members == 1);
assert!(rows.iter().any(|r| r.id == 5 && r.is_channel && r.locked));
// Only top-level channels are spacers: a sub-channel keeps its name.
p.channels.get_mut(&3).unwrap().name = "[cspacer1]Chess".into();
let c = HashSet::new();
let rows = super::rows(&input(&p, &t, &c, &pb, "", &e));
let chess = rows.iter().find(|r| r.is_channel && r.id == 3).unwrap();
assert_eq!((chess.name.as_ref(), chess.spacer), ("[cspacer1]Chess", 0));
assert_eq!(channel_title(&p.channels[&2]), ("Гамесы", Some(Spacer::Center)));
assert_eq!(channel_title(&p.channels[&3]), ("[cspacer1]Chess", None));
// Lists and pickers leave out what only separates.
let listed: Vec<_> = p.channels.values().filter_map(listed_title).collect();
assert_eq!(listed, ["Lobby", "Гамесы", "[cspacer1]Chess", "Staff"]);
}
/// The search finds a spacer by its text, never a separator, but keeps
/// separators above what it finds.
#[test]
fn search_skips_separators() {
let mut p = presence();
p.channels.get_mut(&2).unwrap().name = "[*spacer1]---".into();
p.channels.get_mut(&1).unwrap().name = "[cspacer]Lobby".into();
p.channels.insert(
4,
ChannelInfo { id: 4, order: 2, name: "[spacer4]".into(), ..Default::default() },
);
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let e = Extras::default();
let names = |filter| {
super::rows(&input(&p, &t, &c, &pb, filter, &e))
.iter()
.map(|r| r.name.chars().take(3).collect::<String>())
.collect::<Vec<_>>()
};
assert!(names("-").is_empty());
assert!(names("spacer").is_empty());
assert_eq!(names("lob"), ["Lob"]);
// The line stays as the parent of Chess.
assert_eq!(names("chess"), ["---", "Che"]);
}
#[test]
fn tree_rows_and_counts() {
let p = presence();
let (t, c, pb) = (HashSet::from([11]), HashSet::new(), ClientPlaybackMap::new());
let e = Extras::default();
let rows = rows(&input(&p, &t, &c, &pb, "", &e));
let names: Vec<_> = rows.iter().map(|r| r.name.as_ref()).collect();
assert_eq!(names, ["Lobby", "Alice", "Games", "bob", "Chess", "Carol"]);
assert_eq!((rows[0].members, rows[0].max_members), (1, -1));
assert_eq!((rows[2].members, rows[2].max_members, rows[2].own), (1, 5, true));
assert!(rows[3].talking && rows[3].myself);
assert_eq!(&*rows[3].initials, "BO");
assert_eq!(stats(&p), "3 online · 3 channels");
}
#[test]
fn search_keeps_parents() {
let p = presence();
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let e = Extras::default();
let rows = rows(&input(&p, &t, &c, &pb, "car", &e));
let names: Vec<_> = rows.iter().map(|r| r.name.as_ref()).collect();
assert_eq!(names, ["Games", "Chess", "Carol"]);
let rows = super::rows(&input(&p, &t, &c, &pb, "LOBBY", &e));
assert_eq!(rows.len(), 1);
}
#[test]
fn members_of_our_channel() {
let mut p = presence();
p.clients.get_mut(&12).unwrap().channel = 2;
p.clients.get_mut(&12).unwrap().away = Some(String::new());
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let e = Extras::default();
let members = members(&input(&p, &t, &c, &pb, "", &e));
let names: Vec<_> = members.iter().map(|m| (m.name.as_ref(), m.status.as_ref())).collect();
assert_eq!(names, [("bob", "Listening"), ("Carol", "Away")]);
}
#[test]
fn members_are_grouped_by_server_group() {
let mut p = presence();
p.clients.get_mut(&12).unwrap().channel = 2;
p.clients.get_mut(&12).unwrap().server_groups = vec![6];
p.clients.get_mut(&11).unwrap().server_groups = vec![7];
let group = |id, sort_id, name: &str| GroupInfo {
id,
name: name.into(),
icon: 0,
sort_id,
..Default::default()
};
let e = Extras {
groups: vec![group(6, 10, "Server Admin"), group(7, 20, "Guest")],
..Default::default()
};
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let members = members(&input(&p, &t, &c, &pb, "", &e));
let rows: Vec<_> =
members.iter().map(|m| (m.name.as_ref(), m.group.as_ref(), m.first_in_group)).collect();
assert_eq!(rows, [("Carol", "Server Admin", true), ("bob", "Guest", true)]);
assert!(members[0].admin && !members[1].admin);
}
#[test]
fn members_who_cannot_talk() {
let channel = |needed| ChannelInfo { needed_talk_power: needed, ..Default::default() };
let client = |talk_power, talker| ClientInfo { talk_power, talker, ..Default::default() };
for (needed, power, talker, cannot) in [
(50, 75, false, false),
(50, 50, false, false),
(50, 0, false, true),
(50, 49, false, true),
// A talker speaks without talk power.
(50, 0, true, false),
// The channel needs none.
(0, 0, false, false),
] {
let case = format!("needed {needed}, power {power}, talker {talker}");
assert_eq!(
cannot_talk(Some(&channel(needed)), &client(power, talker)),
cannot,
"{case}"
);
}
assert!(!cannot_talk(None, &client(0, false)));
// In the members panel: bob (talk power 75) speaks in Games, which
// needs 50; Carol (none) cannot.
let mut p = presence();
p.channels.get_mut(&2).unwrap().needed_talk_power = 50;
p.clients.get_mut(&11).unwrap().talk_power = 75;
p.clients.get_mut(&12).unwrap().channel = 2;
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let e = Extras::default();
let rows: Vec<_> = members(&input(&p, &t, &c, &pb, "", &e))
.iter()
.map(|m| (m.name.to_string(), m.cannot_talk))
.collect();
assert_eq!(rows, [("bob".to_owned(), false), ("Carol".to_owned(), true)]);
}
#[test]
fn everyone_in_sections() {
let mut p = presence();
p.clients.get_mut(&10).unwrap().server_groups = vec![7];
p.clients.get_mut(&12).unwrap().server_groups = vec![7];
p.clients.get_mut(&12).unwrap().streaming = Some(true);
p.clients.get_mut(&11).unwrap().server_groups = vec![6];
let group = |id, sort_id, name: &str| GroupInfo {
id,
name: name.into(),
icon: 0,
sort_id,
..Default::default()
};
let e = Extras {
groups: vec![group(6, 10, "Moderator"), group(7, 20, "Guest")],
..Default::default()
};
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
let rows = |voice_first| {
server_members(&input(&p, &t, &c, &pb, "", &e), voice_first)
.iter()
.map(|m| {
(
m.name.to_string(),
m.first_in_group.then(|| format!("{} — {}", m.group, m.group_count)),
m.status.to_string(),
)
})
.collect::<Vec<_>>()
};
let row = |name: &str, head: Option<&str>, status: &str| {
(name.to_owned(), head.map(str::to_owned), status.to_owned())
};
// The query client is left out; people elsewhere show their channel.
assert_eq!(
rows(false),
[
row("Carol", Some("Streaming — 1"), "Streaming"),
row("bob", Some("Moderator — 1"), "Listening"),
row("Alice", Some("Guest — 1"), "In Lobby"),
]
);
assert_eq!(
rows(true),
[
row("bob", Some("In Voice — 1"), "Listening"),
row("Alice", Some("Guest — 2"), "In Lobby"),
row("Carol", None, "Streaming"),
]
);
let all = server_members(&input(&p, &t, &c, &pb, "", &e), false);
assert_eq!(&*all[1].role, "Moderator");
assert!(!all[1].admin);
// The search keeps the sections of what it finds.
let found = matching(all, "al");
assert_eq!(found.len(), 1);
assert!(
found[0].first_in_group && &*found[0].group == "Guest" && found[0].group_count == 1
);
}
#[test]
fn channel_paths() {
let mut p = presence();
assert_eq!(channel_path(&p, 1), ["Lobby"], "a channel at the top");
assert_eq!(channel_path(&p, 3), ["Games", "Chess"], "the names from the top");
assert!(channel_path(&p, 99).is_empty(), "an unknown channel");
// Two channels each other's parent: the path stops.
p.channels.get_mut(&2).unwrap().parent = 3;
assert_eq!(channel_path(&p, 3).len(), PATH_DEPTH);
}
}